Files
PaperClipAI/tests/runner-e2e/hiring-template-flow.ts
T
DottaandPaperclip 78e0034498 fix(evals): account for hiring completion notifications (#15007)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E evals check real hiring and delegated task completion.
> - The hiring fixture requires three requested CEO turns and two coder
executions.
> - The server can also wake the CEO when each delegated task completes.
> - Two exact-five-run guards rejected these valid completion turns in
all four retained cells.
> - This pull request validates bounded completion turns in both guards.
> - The benefit is accurate workflow grading while all actual runs and
coverage failures remain visible.

## Linked Issues or Issue Description

Refs: #14985, #14948, #14961.

**What happened?**

The original hiring comparison reports Codex Fail → Fail and Claude Fail
→ Fail. Each cell has seven successful runs. The five requested work
turns are accompanied by two server task-completion notifications. All
six other delivery checks pass.

**Expected behavior**

Require exactly three distinct user-requested CEO turns and one coder
execution for each of two known tasks. Admit at most two strictly
attributed server completion turns, including one turn that batches both
tasks. Reject unknown, duplicate, failed, retried or extra-work runs.

**Steps to reproduce**

Inspect the retained four-cell report linked below. Each original result
fails `five-successful-turns`. The same exact count was also enforced by
the final chat-flow guard.

## What Changed

- Add one typed lifecycle helper shared by the hiring scorer and the
hiring-only final chat guard.
- Validate public run ledgers, company/user/account identity, request
attribution, task origins, completion deliveries, timing and replies.
- Keep exactly five required work turns; declare seven maximum total
turns for cost and timeout planning.
- Count all actual runs, including notification runs and unexpected
resets. Keep other chat count guards unchanged.
- Version the hiring grader as v3 (turn accounting v2) and include the
helper and chat guard in its definition digest.
- Keep source-read, exact coder-body and all six other delivery checks
unchanged.
- Add 144 focused helper/scorer/settlement calibrations and separately
versioned exact retained-input replay reports.
- Retry complete bracketed observations, await both owed callbacks and
attributed replies, and refresh the final guard consistently.
- Reject unrelated completion writes and failed mutation attempts using
exact canonical/native action IDs. Missing identity mapping is
uncomparable action coverage.

## Verification

- All 977 credential-free E2E support tests pass across 64 files,
including 144 focused lifecycle/action/scorer/settlement calibrations.
- E2E typecheck, ordinary plugin SDK and Runner TypeScript dependency
builds, capability contract/inventory checks and the existing two-cell
hiring discovery pass.
- [Executable replay
report](https://github.com/paperclipai/paperclip/blob/fed1729018cc100f5f4bbfb692777e49009c423b/doc/plans/2026-10-02-hiring-executable-accounting-replay.md)
pins current code revision `e4077ade1818d98b9862ae79ee1d49a007dcf9c1`,
v3 definition digest, exact source/input hashes and each original/new
check.
- The stricter replay verifies both Codex variants through both
executable guards. ACPX Claude action attribution remains
unresolved/uncomparable because provider execution IDs cannot be exactly
joined to native request IDs; guards fail closed. No notification writes
are observed. All six other outcomes and every original source/template
coverage check stay unchanged. Original files and Fail → Fail machine
verdicts remain preserved; zero providers are called.
- Full attempts remain uncomparable in both profiles. Historical Claude
also keeps its six-backtick exact-template mismatch. This grading repair
does not prove model-performance equivalence.
- The limited sidecar-v1 and initial executable-v2 passes checked
notification-created tasks but could miss unrelated document writes.
Those assessments remain preserved and do not prove harmless
notifications. The stricter v3 replay is separate.
- [Original measurement and separate
sidecar](https://github.com/paperclipai/paperclip/blob/8eb517ca1497687237163bdef4dfc4d3332ea916/doc/plans/2026-10-02-hiring-template-live-comparison.md)
retain 28 actual runs, eight automatic notifications, four successful
cleanups and unknown actual model charges. No models are rerun.
- The branch is replayed on master `59c07ede7`. Intervening master
changes are UI-only; eval source bytes and replay verdicts match. The
four-cell provider-free replay was repeated against the reachable code
revision.
- Initial-head normal CI retained browser failures in agent-run denial
feedback and touch-picker scroll position. Those browser paths and
imports were unchanged, but their cause was not established. The
necessary review-fix head passes both browser checks; no blind rerun was
requested.
- Local full repository typecheck/test/build were not repeated.
Exact-head normal CI passes the required repository gates, including
typecheck, tests, build and browser shards. Fresh Greptile review
completed on `fed1729018cc100f5f4bbfb692777e49009c423b` with 5/5 and
zero unresolved threads. An independent rerun of the 144 focused
helper/scorer/settlement tests passes on the unchanged head.


**Merge readiness:** This PR repairs the evaluator. Its positive and
negative calibrations pass, both guards reject missing action
attribution, current-head CI and review pass, and there are no merge
conflicts. The retained ACPX cells remain uncomparable because their
action IDs cannot be joined. That coverage limit remains a separate
follow-up; it does not require relaxing this grader or changing the old
results. No model calls, production instructions, carrier changes, or
historical regrades are part of this readiness update.

## Risks

- Missing or inconsistent public lifecycle evidence fails the bounded
helper. The focused calibrations reject plausible false positives and
malformed observations. Unmatched action IDs fail closed and are
reported as uncomparable rather than a model task regression.
- Source-read evidence remains incomplete. This PR does not change
provider event carriers or relax the coverage oracle.
- The versioned count check differs from original v1 results. Reports
retain both versions and exact input hashes.

## Model Used

OpenAI Codex, GPT-6 family as identified by this session. The exact
deployment ID and context-window size are not exposed. The assistant
used reasoning, repository tools, code execution and delegated
calibration work.

## 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 normal CI gates are green (exact head
`fed1729018cc100f5f4bbfb692777e49009c423b`; fresh review tracked
separately below)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(completed exact-head review; zero unresolved threads)
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-03 06:42:51 -05:00

211 lines
15 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { loadDefaultAgentInstructionsBundle } from "../../server/src/services/default-agent-instructions.js";
import { readChatOutputDocument, type ChatFlowInput, type ChatIssue, type ChatRun } from "./chat-flow.js";
import { collectRunEvents } from "./run-observations.js";
import { HIRING_TEMPLATE_GRADER_VERSION, HIRING_TEMPLATE_READ_FILES, HIRING_TEMPLATE_SKILL_KEY,
HIRING_TEMPLATE_SOURCE_FILES, hiringTemplateDefinitionDigest, hiringTemplateScenario } from "./hiring-template-cases.js";
import { gradeHiringTemplate, hiringTemplateHash, hiringTemplateSize, type HiringAgent, type HiringDocument,
type HiringInstructionSnapshot, type HiringTemplateEvidence } from "./hiring-template-scoring.js";
import { pollUntil, type RunnerApi } from "./api.js";
export async function readHiringInstructions(api: Pick<RunnerApi, "get">, agentId: string): Promise<HiringInstructionSnapshot> {
const bundle = await api.get<{ mode: string | null; entryFile: string; files: Array<{ path: string; binary?: boolean }> }>(`/api/agents/${agentId}/instructions-bundle`);
const files: Record<string, string> = {};
// Agent-home notes may be added by a run. Retain the entry and legacy CEO
// policy files so the baseline and candidate default bundles can be compared.
for (const file of bundle.files.filter(file => !file.binary && (file.path === bundle.entryFile || ["HEARTBEAT.md", "SOUL.md", "TOOLS.md"].includes(file.path)))) {
const detail = await api.get<{ content: string }>(`/api/agents/${agentId}/instructions-bundle/file?path=${encodeURIComponent(file.path)}`);
files[file.path] = detail.content;
}
return { entryFile: bundle.entryFile, mode: bundle.mode, files };
}
async function readHiringSkillSelections(api: Pick<RunnerApi, "get">, companyId: string, agentId: string) {
const snapshot = await api.get<{ desiredSkills: string[]; desiredSkillEntries: unknown[] }>(`/api/agents/${agentId}/skills?companyId=${companyId}`);
return { desiredSkills: snapshot.desiredSkills, desiredSkillEntries: snapshot.desiredSkillEntries };
}
export async function readHiringTemplateSources(api: Pick<RunnerApi, "get">, companyId: string, leadId: string) {
const expectedCeoFiles = await loadDefaultAgentInstructionsBundle("ceo");
const expectedSourceHashes: Record<string, string> = {}, servedSourceHashes: Record<string, string> = {};
const sourceSizes: Record<string, ReturnType<typeof hiringTemplateSize>> = {};
for (const relative of [...HIRING_TEMPLATE_SOURCE_FILES, ...Object.keys(expectedCeoFiles).map(file => `server/src/onboarding-assets/ceo/${file}`)]) {
const content = await readFile(new URL(`../../${relative}`, import.meta.url), "utf8");
expectedSourceHashes[relative] = hiringTemplateHash(content);
sourceSizes[relative] = hiringTemplateSize(content);
}
const leadInstructions = await readHiringInstructions(api, leadId);
for (const [file, content] of Object.entries(leadInstructions.files)) servedSourceHashes[`server/src/onboarding-assets/ceo/${file}`] = hiringTemplateHash(content);
const skills = await api.get<Array<{ id: string; key: string }>>(`/api/companies/${companyId}/skills`);
const creator = skills.find(skill => skill.key === HIRING_TEMPLATE_SKILL_KEY);
if (!creator) throw new Error("Production hiring skill is absent from the company library");
const assigned = await api.get<{ desiredSkills: string[] }>(`/api/agents/${leadId}/skills?companyId=${companyId}`);
let coderReference = "";
for (const file of [...HIRING_TEMPLATE_READ_FILES, "references/baseline-role-guide.md"]) {
const detail = await api.get<{ content: string }>(`/api/companies/${companyId}/skills/${creator.id}/files?path=${encodeURIComponent(file)}`);
servedSourceHashes[`skills/paperclip-create-agent/${file}`] = hiringTemplateHash(detail.content);
if (file === "references/agents/coder.md") coderReference = detail.content;
}
// The loader and execution contract are source provenance, not served skill
// reads. Their bytes are retained separately from the equality checks.
delete expectedSourceHashes["server/src/services/default-agent-instructions.ts"];
delete expectedSourceHashes["server/src/onboarding-assets/default/AGENTS.md"];
return { expectedCeoFiles, leadInstructions, expectedSourceHashes, servedSourceHashes,
sourceSizes, assignedSkills: assigned.desiredSkills, coderReference, creatorSkillId: creator.id,
loaderHash: hiringTemplateHash(await readFile(new URL("../../server/src/services/default-agent-instructions.ts", import.meta.url), "utf8")),
executionContractHash: hiringTemplateHash(await readFile(new URL("../../server/src/onboarding-assets/default/AGENTS.md", import.meta.url), "utf8")) };
}
export function renderHiringCoderExample(reference: string, agentName: string, companyName: string, managerTitle: string, issuePrefix: string) {
const example = reference.match(/```md\s*\n([\s\S]*?)\n```/)?.[1];
if (!example?.trim()) throw new Error("Production coder reference has no AGENTS.md example");
return example.replaceAll("{{agentName}}", agentName).replaceAll("{{companyName}}", companyName).replaceAll("{{managerTitle}}", managerTitle).replaceAll("{{issuePrefix}}", issuePrefix);
}
/** Reads only existing public surfaces; this does not fabricate lifecycle evidence. */
export async function readHiringTurnApiState(api: Pick<RunnerApi, "get">, chatIssueId: string, allRuns: () => Promise<ChatRun[]>) {
const [issue, comments, runs, wakes] = await Promise.all([
api.get<ChatIssue>(`/api/issues/${chatIssueId}`),
api.get<unknown[]>(`/api/issues/${chatIssueId}/comments`),
allRuns(),
api.get<{ events: Array<{ kind: string; status?: string; finishedAt?: string | null; runId?: string | null }>; truncated: boolean }>(`/api/issues/${chatIssueId}/diagnostics/wakes`),
]);
return { issue, comments, runs, wakes };
}
type HiringTurnApiState = Awaited<ReturnType<typeof readHiringTurnApiState>>;
interface HiringObservation {
agents: HiringAgent[]; tasks: ChatIssue[]; runs: ChatRun[]; readRuns: HiringTemplateEvidence["readRuns"];
apiState?: HiringTurnApiState; finalApiState?: HiringTurnApiState;
}
/** Retry whole observations, never splice different ledger generations together. */
export async function waitForSettledHiringObservation(
load: () => Promise<HiringObservation>, options: { deadlineAt?: number; intervalMs?: number } = {},
) {
let previous: string | undefined;
return pollUntil({ label: "hiring work and completion deliveries settle consistently",
deadlineAt: options.deadlineAt ?? Date.now() + 90_000, intervalMs: options.intervalMs ?? 1_000,
load, accept: observation => {
const before = observation.apiState, after = observation.finalApiState;
const stable = before && after && JSON.stringify(before) === JSON.stringify(after)
&& JSON.stringify(observation.runs) === JSON.stringify(after.runs);
const completionRuns = observation.runs.filter(run => run.contextSnapshot?.wakeReason === "chat_task_completed");
const completionsObserved = observation.tasks.filter(task => task.status === "done").every(task => {
const callbacks = completionRuns.filter(run => Array.isArray(run.contextSnapshot?.chatCompletionUpdates)
&& run.contextSnapshot.chatCompletionUpdates.filter((update: { id?: string }) => update.id === task.id).length === 1);
return callbacks.length === 1 && after?.comments.some(value => {
const comment = value as Record<string, unknown>;
return comment.createdByRunId === callbacks[0]!.id && comment.issueId === after.issue.id
&& comment.authorAgentId === callbacks[0]!.agentId && !comment.authorUserId
&& typeof comment.body === "string" && comment.body.trim().length > 0;
});
});
const pending = !after || after.wakes.truncated || after.wakes.events.some(wake => {
if (wake.kind !== "wake_request") return false;
if (wake.status === "coalesced") return !completionsObserved || !observation.runs.some(run => run.id === wake.runId
&& ["succeeded", "failed", "cancelled"].includes(run.status));
return !["completed", "skipped", "failed", "cancelled"].includes(wake.status ?? "");
}) || observation.runs.some(run => ["queued", "running", "scheduled_retry"].includes(run.status));
// Await both known callbacks, even before the pending outbox enqueues a
// wake. Reply attribution proves the server acknowledged each delivery.
const signature = stable && !pending && completionsObserved && after.issue.conversationState === "waiting"
? JSON.stringify(observation) : undefined;
const settled = Boolean(signature && signature === previous);
previous = signature;
return settled;
},
});
}
export async function runHiringTemplateFlow(context: {
input: ChatFlowInput; issue(): ChatIssue; turn(message: string, count: number): Promise<void>;
tasks(): Promise<ChatIssue[]>; allRuns(): Promise<ChatRun[]>;
}) {
const { input, turn, tasks, allRuns } = context;
const { api, fixtures: f } = input;
const company = `/api/companies/${f.company.id}`;
const account = f.aiConnection;
if (!account) throw new Error("Hiring-template fixture requires a managed execution account");
const issuePrefix = f.company.issuePrefix;
if (!issuePrefix) throw new Error("Hiring-template fixture requires the actual company issue prefix");
const evidence: HiringTemplateEvidence = {
leadId: f.agent.id, chatIssueId: "", hireName: "", marker: "", projectId: "", inputs: [], expectedCeoFiles: {},
expectedSourceHashes: {}, servedSourceHashes: {}, assignedSkills: [], coderExample: "",
agents: [], tasks: [], runs: [], readRuns: [], connectionId: account.connectionId, binding: account.binding,
};
let source: Awaited<ReturnType<typeof readHiringTemplateSources>> | undefined;
let scenario: ReturnType<typeof hiringTemplateScenario> | undefined;
async function loadObservation() {
const observed = await Promise.all([api.get<HiringAgent[]>(`${company}/agents`), tasks(), allRuns()]);
const [agents, taskRows, runs] = observed;
const apiState = evidence.chatIssueId ? await readHiringTurnApiState(api, evidence.chatIssueId, allRuns) : undefined;
const readRuns = await Promise.all(runs.map(async run => {
const events = await collectRunEvents<{ seq?: number; eventType?: string; payload?: unknown; createdAt?: string }>(
(afterSeq, limit) => api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`),
);
return { runId: run.id, agentId: run.agentId, events };
}));
// Bracket event collection with a fresh ledger/wake/comment observation.
const finalApiState = evidence.chatIssueId ? await readHiringTurnApiState(api, evidence.chatIssueId, allRuns) : undefined;
return { agents, tasks: taskRows, runs, readRuns, apiState, finalApiState };
}
async function refresh(settle = false) {
const observed = settle && evidence.chatIssueId
? await waitForSettledHiringObservation(loadObservation) : await loadObservation();
Object.assign(evidence, { agents: observed.agents, tasks: observed.tasks, runs: observed.runs,
readRuns: observed.readRuns, turnApiState: observed.finalApiState });
}
try {
await api.patch(`${company}/budgets`, { budgetMonthlyCents: 1_000 });
await api.patch(`/api/agents/${f.agent.id}/budgets`, { budgetMonthlyCents: 1_000 });
source = await readHiringTemplateSources(api, f.company.id, f.agent.id);
Object.assign(evidence, source);
await input.evidence("hiring-template-source.json", { ...source, definitionDigest: hiringTemplateDefinitionDigest });
if (Object.entries(source.expectedSourceHashes).some(([file, hash]) => source!.servedSourceHashes[file] !== hash)) {
throw new Error("Hiring-template served source differs from the evaluated revision; comparison is uncomparable");
}
const project = await api.post<{ id: string; name: string }>(`${company}/projects`, {
name: `Label fixtures ${input.nonce}`, description: "Repository-free JSON normalization fixtures.",
});
scenario = hiringTemplateScenario(input.nonce, project.name);
Object.assign(evidence, { hireName: scenario.hireName, marker: scenario.marker, inputs: scenario.inputs, projectId: project.id,
coderExample: renderHiringCoderExample(source.coderReference, scenario.hireName, f.company.name, String((await api.get<{ title: string }>(`/api/agents/${f.agent.id}`)).title), issuePrefix) });
await turn(scenario.initialPrompt, 2);
evidence.chatIssueId = context.issue().id;
const initial = await tasks();
if (initial.length !== 1) throw new Error("Hiring-template first turn must create exactly one coder task");
evidence.first = await readChatOutputDocument(api, initial[0]!.id, scenario.marker) as HiringDocument;
await refresh();
const hired = evidence.agents.find(agent => agent.name === scenario!.hireName);
if (!hired) throw new Error("Hiring-template coder was not created");
evidence.hiredInstructions = await readHiringInstructions(api, hired.id);
evidence.hiredSkills = await readHiringSkillSelections(api, f.company.id, hired.id);
await input.capture("hiring-template-created", "Production CEO hired a coder and delivered its first fixture", "hiring-template-created.png");
await input.evidence("hiring-template-initial.json", evidence);
await turn(scenario.reusePrompt(initial[0]!.identifier ?? initial[0]!.id), 4);
const second = (await tasks()).find(task => task.id !== evidence.first!.issueId);
if (!second) throw new Error("Hiring-template reuse task is absent");
evidence.second = await readChatOutputDocument(api, second.id, `REUSE${scenario.marker}`) as HiringDocument;
evidence.firstAfterReuse = await api.get<HiringDocument>(`/api/issues/${evidence.first.issueId}/documents/${encodeURIComponent(evidence.first.key)}`);
await turn(scenario.statusPrompt(initial[0]!.identifier ?? initial[0]!.id, second.identifier ?? second.id), 5);
evidence.hiredInstructionsAfterReuse = await readHiringInstructions(api, hired.id);
evidence.hiredSkillsAfterReuse = await readHiringSkillSelections(api, f.company.id, hired.id);
await refresh(true);
const result = gradeHiringTemplate(evidence);
for (const check of result.checks) input.check?.(`hiringTemplates.${check.dimension}.${check.id}`, check.passed, check.detail);
await input.evidence("hiring-template.json", { schema: HIRING_TEMPLATE_GRADER_VERSION, definitionDigest: hiringTemplateDefinitionDigest,
budgetGuard: { companyMonthlyCents: 1_000, leadMonthlyCents: 1_000 }, scenario, source, evidence, result });
const failed = result.checks.filter(check => !check.passed);
if (!result.outcomePassed) throw new Error(`Hiring-template workflow outcome failed: ${failed.filter(check => check.dimension === "outcome").map(check => check.id).join(", ")}`);
if (result.comparisonStatus === "uncomparable") throw new Error(`Hiring-template source coverage is uncomparable: ${failed.filter(check => check.dimension === "coverage").map(check => check.id).join(", ")}`);
return { evidence, refresh: async () => { await refresh(true); return evidence; } };
} finally {
let observationError: string | undefined;
try { await refresh(Boolean(scenario)); } catch (error) { observationError = String(error); }
await input.evidence("hiring-template.json", { schema: HIRING_TEMPLATE_GRADER_VERSION, definitionDigest: hiringTemplateDefinitionDigest,
budgetGuard: { companyMonthlyCents: 1_000, leadMonthlyCents: 1_000 },
scenario, source, evidence, result: gradeHiringTemplate(evidence), observationError });
}
}