Files
PaperClipAI/packages/paperclip-runner/src/contracts/completion-result.test.ts
T
eece07a747 fix: repair the complete projectless repository setup chain (#17088)
## Thinking Path

> - Paperclip lets people manage agents that do useful work.
> - A projectless task can prepare an authorized repository in its
retained workspace.
> - Setup must hand work to a later run without user supervision.
> - Real task attempts exposed gaps across admission, completion, and
queue dispatch.
> - A successful provider exit did not prove that the requested result
was delivered.
> - This PR repairs the existing lifecycle and checks the complete
repository journey.

## Linked Issues or Issue Description

Refs #17047. This PR includes the preserved repairs from #17049, #17052,
and #17082.

**What happened?**

A projectless native task could stop after requesting a repository. It
could also continue through a timer or generic recovery path and lose
its saved conversation lineage. The latest real Codex and Claude
attempts delivered correct files, but the native continuation had been
folded into the finishing predecessor. Both attempts remain failed
measurements.

**Expected behavior**

Prepare the authorized repository, retain the original context, and
dispatch one saved continuation after its predecessor finishes. Deliver
the verified result in the originating conversation. Stop, current
access, approval, and real blocker rules remain authoritative.

**Steps to reproduce**

Run the explicit automatic-repository suite for native Codex or Claude.
Inspect the downloaded result, original context artifact, both committed
run records, and continuation receipts. The suite uses one attempt and
does not widen the default paid selection.

## What Changed

- Resolve the retained local-board identity through current company
membership and workspace authority.
- Prepare required source dependencies before the isolated server
imports native tool authority.
- Explain the saved repository continuation in production completion
tools. Correct only the exact pending-checkout blocker backed by a live
receipt. Reject an unfinished response wait without a real response
source.
- Preserve the persisted task-session workspace source and its explicit
absence of root repository context. Permit Git's exact no-repository
result only for a validated plain task directory. Keep other Git errors
and linked metadata strict.
- Revalidate server-resolved same-agent continuation values against
current ownership and the saved kind, summary, and key. Carry this shape
through the internal bridge schema. Keep provider-facing schemas
restrictive.
- Preserve terminal result authority after a correlated successful
controller response. Controller rejection creates no result authority.
Bind the shared guidance and transport source in Copilot v55 and
preserve historical identities.
- Admit native status wakes with the existing no-coalescing contract.
The existing deferred queue retains a distinct future dispatch instead
of retagging the finishing run.
- Recover deferred conversation lineage through the actual admitted
dispatch. Accept a null outbox run binding only with matching decision,
effect, dispatch actor, idempotency, task, company, agent, and requester
evidence. Reject a conflicting nonnull binding.
- Independently grade retained random context, actual checkout bytes and
HEAD, accessible output, distinct continuation receipts, and admission
order.

## Verification

- Real database and Git regressions fail before their repairs. Prior
focused cohorts cover local-board authority, optional repository waits,
plain task directories, and first/reused workspace provenance.
- The new valid decision/effect-backed assembled-heartbeat regression
reproduces coalescing into its active predecessor before the queue
repair. With the repair, it dispatches one successor after the
predecessor finishes. Duplicate sweeps create no extra run.
- The deferred-outbox conversation regression fails before its repair.
The repaired test also rejects a conflicting predecessor binding.
- The current queue, continuation, publication, cancellation,
stale-admission, and domain cohort passes 344 checks across 11 suites.
Server and Product E2E typechecks pass. The strengthened
automatic-repository oracle passes 34 calibration checks.
- Three omitted/null/resolved forms pass through the compiled Rust
runner and controlled provider. The prior shared bridge cohort passes
492 TypeScript checks and 399 Rust core checks. Runner source identity,
TypeScript, Rust formatting, and locked Rust typechecks pass.
- Six real local development cells passed ordinary repository,
conversion, and necessary-question journeys. Independent artifacts and
rendered question/result evidence agree. They do not qualify staging or
Slack.
- Both latest automatic-repository attempts delivered correct files but
failed the strict continuation check. They remain failures. A fresh
replay of this queue repair is pending.
- On the combined candidate `380047f4b923807a8c4f7ef6016e4fe130ab4a3a`,
`pnpm -r typecheck` and `pnpm build` pass. Product E2E support passes
3,525 checks with two existing skips, plus 128 source checks. The
complete local `pnpm test:run` is running and is not yet a pass.
- The first replay selection failed catalog validation due to an
operator profile-ID error. A second selection used the wrong
default-model suite and was cancelled before any provider job existed.
Both setup attempts remain recorded. The corrected campaign selects the
recorded GPT-6.1 and Opus 5.5 models plus the local Stop/resume journey.
- Exact-head CI, review, and deployment acceptance remain pending.
GitHub reports delayed PR updates and webhook delivery; the current head
and checks have now propagated. No earlier-head green badge establishes
acceptance of this commit.

## Risks

This changes several boundaries of repository setup. Full product and
deployment acceptance remain required. The queue uses the existing
deferred admission and delivery contracts. Batch deduplication remains
in place. The provenance repair requires the actual bound dispatch and
does not grant publication authority. Current authorization is still
checked at publication. No accepted provider result is rewritten, and
completed provider work is not rerun to repair persistence or delivery.

## Model Used

OpenAI Codex, GPT-6 family, with repository tools and code execution.
The runtime does not expose its exact deployment ID or context-window
size. Those values are not inferred.

## 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: Paperclip <paperclip@paperclip.ing>
2026-10-21 11:21:55 -05:00

290 lines
14 KiB
TypeScript

import { normalizeLegacyPrpStructuredRunResult } from "../protocol/result-normalization.js";
import Ajv2020 from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import {
PRP_BLOCK_RESULT_OUTPUT_SCHEMA,
PRP_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA,
PRP_BLOCK_TOOL_DESCRIPTION,
PRP_COMPLETION_RESULT_BRIDGE_INPUT_SCHEMA,
PRP_COMPLETION_RESULT_OUTPUT_SCHEMA,
PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA,
PRP_COMPLETION_TOOL_DESCRIPTION,
} from "./completion-result.js";
import { codexSemanticToolSpecs } from "../drivers/codex/codex-driver-values.js";
const baseResult = {
schema: "paperclip.run_result.v1",
reportedWorkDisposition: "done",
summary: "Completed the requested work.",
completionClaim: {
contractRevision: "1",
objectiveSatisfied: true,
criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }],
remainingWork: [],
},
evidence: [],
verification: [],
attentionRequests: [],
artifacts: [],
};
describe("provider-neutral completion result schema", () => {
const validate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_OUTPUT_SCHEMA);
it("accepts an explicit monitor wait across provider and normalized schemas", () => {
const report = { ...baseResult, reportedWorkDisposition: "yielded",
completionClaim: { ...baseResult.completionClaim, objectiveSatisfied: false,
remainingWork: [{ description: "Check the next run", blocksCompletion: true }] },
continuation: { kind: "monitor", summary: "Wait for persisted timer", idempotencyKey: "monitor-wait" } };
expect(validate(report)).toBe(true);
const providerValidate = new Ajv2020({ allErrors: true, strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
expect(providerValidate(report)).toBe(true);
expect(validate({ ...report, continuation: { ...report.continuation, kind: "invented" } })).toBe(false);
});
it("requires a persisted handoff identifier for a case handoff continuation", () => {
const report = { ...baseResult, reportedWorkDisposition: "yielded", continuation: {
kind: "case_handoff", handoffId: "accepted-handoff-id", summary: "Next phase", idempotencyKey: "handoff-1" } };
expect(validate(report)).toBe(true);
const providerValidate = new Ajv2020({ allErrors: true, strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
expect(providerValidate(report)).toBe(true);
const { handoffId: _omitted, ...withoutId } = report.continuation;
expect(validate({ ...report, continuation: withoutId })).toBe(false);
expect(providerValidate({ ...report, continuation: withoutId })).toBe(false);
});
it("lets the controller resolve an omitted provider continuation without weakening canonical results", () => {
const report = { ...baseResult, reportedWorkDisposition: "yielded" };
const providerValidate = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
expect(providerValidate(report)).toBe(true);
expect(validate(report)).toBe(false);
});
it("carries a normalized workspace continuation only on the internal bridge", () => {
const bridge = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_BRIDGE_INPUT_SCHEMA);
const provider = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const report = { ...baseResult, reportedWorkDisposition: "yielded", continuation: {
kind: "same_agent", summary: "Use the staged task checkout.", idempotencyKey: "repository:task:receipt:run" } };
expect(bridge(report)).toBe(true);
expect(provider(report)).toBe(false);
for (const invalid of [
{ ...report, reportedWorkDisposition: "done" },
{ ...report, continuation: { ...report.continuation, kind: "retry" } },
{ ...report, continuation: { ...report.continuation, idempotencyKey: "" } },
]) expect(bridge(invalid)).toBe(false);
expect(bridge(baseResult)).toBe(true);
});
it("allows done with no verification and no actionable attention", () => {
expect(validate(structuredClone(baseResult))).toBe(true);
});
it("distinguishes user-facing answer content from the internal response-wake reason", () => {
for (const schema of [
PRP_COMPLETION_RESULT_OUTPUT_SCHEMA,
PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA,
PRP_BLOCK_RESULT_OUTPUT_SCHEMA,
PRP_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA,
]) {
const summary = schema.properties.summary;
expect(summary.description).toContain("complete user-facing answer");
expect(summary.description).toContain(
"genuine actionable failure, limitation, or required user action",
);
expect(summary.description).toContain(
"Unless explicitly requested, omit routine preparation, unconfirmed-delivery, and wait/review status",
);
expect(summary.description).toContain(
"Never claim delivery without a confirmed receipt",
);
}
for (const schema of [
PRP_COMPLETION_RESULT_OUTPUT_SCHEMA,
PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA,
]) {
const summary = schema.properties.continuation.properties.summary;
expect(summary.description).toContain("Internal control-plane reason");
expect(summary.description).toContain(
"not in the top-level user-facing summary",
);
expect(summary.description).toContain("not the answer to the user's request");
}
});
it("propagates answer and wait descriptions into the actual Codex semantic tool schemas", () => {
const tools = JSON.parse(JSON.stringify(codexSemanticToolSpecs()));
const finish = tools.find(
(tool: { name: string }) => tool.name === "paperclip_finish",
);
const block = tools.find(
(tool: { name: string }) => tool.name === "paperclip_block",
);
expect(finish.inputSchema.properties.summary.description).toContain(
"complete user-facing answer",
);
expect(
finish.inputSchema.properties.continuation.properties.summary.description,
).toContain("not in the top-level user-facing summary");
expect(block.inputSchema.properties.summary.description).toContain(
"genuine actionable failure, limitation, or required user action",
);
expect(finish.inputSchema).toEqual(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
expect(block.inputSchema).toEqual(PRP_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA);
expect(finish.description).toBe(PRP_COMPLETION_TOOL_DESCRIPTION);
expect(finish.description).toContain("saved repository-preparation continuation");
expect(finish.inputSchema.properties.continuation.description).toContain("repository-preparation continuation");
expect(block.description).toContain("Routine repository preparation is not a blocker");
expect(block.description).toBe(PRP_BLOCK_TOOL_DESCRIPTION);
});
it("allows only a response-wake continuation when completion explicitly yields", () => {
const yielded = {
...structuredClone(baseResult),
reportedWorkDisposition: "yielded",
completionClaim: {
...structuredClone(baseResult.completionClaim),
objectiveSatisfied: false,
remainingWork: [{ description: "Wait for the next response.", blocksCompletion: true }],
},
continuation: {
kind: "response_wake",
summary: "Resume after the next response.",
idempotencyKey: "response-wake-1",
},
};
expect(validate(yielded)).toBe(true);
expect(validate({ ...yielded, continuation: undefined })).toBe(false);
expect(validate({
...yielded,
continuation: { ...yielded.continuation, kind: "same_agent" },
})).toBe(false);
});
it("allows provider tool callers to omit the constant schema discriminator", () => {
const providerValidate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const providerResult = structuredClone(baseResult) as Record<string, unknown>;
delete providerResult.schema;
expect(providerValidate(providerResult)).toBe(true);
});
it.each(["done", "needs_review", "completed"])("rejects a response-wake continuation on %s", (disposition) => {
const response = {
...structuredClone(baseResult),
reportedWorkDisposition: disposition,
attentionRequests: disposition === "needs_review"
? [{ kind: "review", summary: "Review this result.", ownerClass: "human" }]
: [],
continuation: { kind: "response_wake", summary: "Contradictory wait.", idempotencyKey: "wait-1" },
};
const providerValidate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
expect(providerValidate(response)).toBe(false);
expect(validate(response)).toBe(false);
});
it.each(["done", "needs_review", "completed"])("accepts explicit no-continuation at the provider boundary for %s", (disposition) => {
const providerValidate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const response = {
...structuredClone(baseResult),
reportedWorkDisposition: disposition,
continuation: null,
};
expect(providerValidate(response)).toBe(true);
// The canonical output remains strict; normalization removes only null.
expect(validate(response)).toBe(false);
});
it("exposes concrete completion fields while retaining response-wake validation", () => {
// The live Codex code-mode renderer reduced a conditional-only root allOf
// to `args: unknown`. Keep this tool object-shaped for provider discovery.
expect(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA.type).toBe("object");
expect(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA).not.toHaveProperty("allOf");
expect(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA.required).toEqual([
"reportedWorkDisposition", "summary", "completionClaim", "evidence", "verification",
]);
expect(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA.properties.continuation.required)
.toEqual(["kind", "summary", "idempotencyKey"]);
const providerValidate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const yielded = {
...structuredClone(baseResult),
reportedWorkDisposition: "yielded",
continuation: {
kind: "response_wake",
summary: "Wait for the next response.",
idempotencyKey: "response-wake-provider-1",
},
};
expect(providerValidate(yielded)).toBe(true);
expect(providerValidate({ ...yielded, continuation: undefined })).toBe(true);
expect(providerValidate({ ...yielded, continuation: null })).toBe(true);
expect(providerValidate({ ...yielded, continuation: { kind: "response_wake" } })).toBe(false);
expect(providerValidate({
...yielded, continuation: { ...yielded.continuation, kind: "same_agent" },
})).toBe(false);
expect(providerValidate({ ...yielded, evidence: undefined })).toBe(false);
});
it("admits known smaller-model aliases at the provider boundary for canonical normalization", () => {
const providerValidate = new Ajv2020({ allErrors: true, strict: false })
.compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const providerResult = structuredClone(baseResult);
providerResult.schema = "paperclip_paperclip_finish";
providerResult.reportedWorkDisposition = "completed";
providerResult.completionClaim.criteria[0]!.status = "passed";
providerResult.verification = [{ commandOrCheck: "model check", status: "pass" } as never];
expect(providerValidate(providerResult)).toBe(true);
});
it.each([undefined, null, "", " ", "artifact:verified-result"])("normalizes optional verification artifact metadata (%s)", (artifactRef) => {
const providerValidate = new Ajv2020({ strict: false }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA);
const input = { ...structuredClone(baseResult), verification: [{ commandOrCheck: "Check answer", status: "passed", artifactRef }] };
expect(providerValidate(input)).toBe(true);
const normalized = normalizeLegacyPrpStructuredRunResult(input);
expect(validate(normalized)).toBe(true);
expect(normalized).toMatchObject({ verification: [{ commandOrCheck: "Check answer", status: "passed" }] });
if (artifactRef?.trim()) expect(normalized).toHaveProperty("verification.0.artifactRef", artifactRef);
else expect(normalized).not.toHaveProperty("verification.0.artifactRef");
expect(providerValidate({ ...input, verification: [{ ...input.verification[0], artifactRef: 42 }] })).toBe(false);
});
it("requires a reason code for verification that was not run", () => {
const result = structuredClone(baseResult);
result.verification = [{ commandOrCheck: "Run tests", status: "not_run" } as never];
expect(validate(result)).toBe(false);
result.verification = [{
commandOrCheck: "Run tests",
status: "not_run",
reasonCode: "tool_unavailable",
} as never];
expect(validate(result)).toBe(true);
});
it("requires needs_review for actionable attention", () => {
const result = structuredClone(baseResult);
result.attentionRequests = [{
kind: "review",
summary: "Confirm the external result.",
ownerClass: "human",
} as never];
expect(validate(result)).toBe(false);
result.reportedWorkDisposition = "needs_review";
expect(validate(result)).toBe(true);
});
it("requires agent-owned attention to identify its target agent", () => {
const result = structuredClone(baseResult);
result.reportedWorkDisposition = "needs_review";
result.attentionRequests = [{
kind: "agent_handoff",
summary: "Ask the deployment agent to continue.",
ownerClass: "agent",
} as never];
expect(validate(result)).toBe(false);
});
});