mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat catalog evals check that a chat agent does real product
work, and they grade saved state, not reply wording
> - Full cohort 6 (OpenCode with DeepSeek V4.1 Flash on master
b7693e2076) had five false failures where the product behaviour was
correct
> - Three more failures kept no run logs or ledger, and one was labelled
as transient infrastructure when the product had cancelled the run
> - A false failure hides real product defects, and missing evidence
stops diagnosis
> - This pull request corrects the five graders on saved state and fixes
the evidence gaps
> - The benefit is that the cohort result shows real product behaviour,
and each failure keeps the evidence to explain it
## Linked Issues or Issue Description
**What happened?**
Five chat eval cases failed although saved state showed correct
behaviour. Three run-bound failures and one early Playwright exit saved
no run logs or run ledger. A reassignment cancellation was classified as
`transient_infrastructure`.
**Expected behavior**
Each grader accepts the valid behaviour and still rejects the broken
product. Every failed attempt keeps its run ledger and the logs it can
read.
**Steps to reproduce**
Run the cohort 6 cases on master. Read the failed checks and the missing
`chat-catalog-runs.json` files.
## What Changed
- `budgets-costs.spend-breakdown` (oracle v5). Old check: only unranged
cost reports, the task cost summary, or the single run record counted.
The lead read the run through `GET
/api/companies/{companyId}/heartbeat-runs` filtered to Morgan with
`limit: 200` (saved input digest `36e47c51…`). New check: a run-list
read counts when its saved input digest names a full list that reaches
the original run (unfiltered or filtered to its agent, with a limit past
the runs ahead of it at read time). Still fails: no accounting read, a
list that cannot reach the run, another agent's list, a summary list, a
denied read, a read in another run.
- `status-cards.explain-card` (oracle v6). Old check: only `GET
/api/issues/{id}` counted as a live read. The lead read COM-1 through
`search_tasks`, and the saved result showed the task as done. New check:
a dedicated task tool result that holds the source task id with its live
status counts. Still fails: an empty search, another task, a different
status, a `call_api` result, an error result, a result with no paired
tool use.
- `secrets.personal-secret` (oracle v20). Old check: `JSON.parse` of the
whole bash output. The worker appended `EXIT_CODE=0`. New check: the one
JSON object in the output that carries `receiptId`, which must still
equal the fixture endpoint's authorised call receipt. Still fails: a
wrong receipt, a failed check, two different receipts, no JSON object,
key=value text.
- `skills.fork-read-only` (oracle `integrator.skill-fork.v2`). Old
check: a wording list (`unchanged|read-only|protected|not changed`)
rejected "untouched". New check: the reply names the saved fork or links
its Studio page. Saved state already proves the upstream is unchanged
and the fork exists. Still fails: no fork, a reply without the fork name
or link, a link to another skill, an edited upstream.
- `steering.discard-queued-message` (oracle v6). Old check: the label
string must not appear anywhere in the final plan. The revised plan kept
a "superseded" note with the label. New check: the person asked for a
section labelled with the attempt nonce (a setup literal). A heading
with that label must exist in the plan before the consuming run or in
that run's saves, and the final saved revision must have no heading with
it. Body mentions are allowed. The base plan is the revision before the
consuming run first saved the label, so repeated saves by that run do
not matter. Still fails: the labelled heading kept, renamed but still
labelled, or never saved.
- Failure evidence: the failure path saves
`chat-catalog-failure-run-ledger.json` before retirement, continues when
retirement fails, and reads a failed run's log and events independently
with a separate `logError` / `eventsError` when one run has no log.
Before, one cancelled never-started run (log 404) dropped the logs of
every run (`cases.cases-disabled`, `defer-and-reopen`,
`approve-tool-once`, `assignment-conflict`).
- Interruption act: the click and its `waitForResponse` are awaited
together. Before, the response promise could reject while the click
waited, and the unhandled rejection stopped the worker with no evidence
(`interrupt-with-direction`).
- A product-cancelled run is reported as `Observed run was cancelled by
<source> (<errorCode>)` and classifies as `candidate_failure`. Failed
and timed-out runs keep `Observed provider run failed`.
## Verification
- Calibration tests for each grader: the retained cohort 6 shape, a
reworded valid shape, and broken shapes.
- Regrade of retained cohort 6 evidence: spend-breakdown and
fork-read-only observations pass; the explain-card initial run reads the
source live; the discard plan revisions pass and the unrevised plan
fails.
- `npx vitest run` on the changed and related runner-e2e domain tests:
283 passed, 4 skipped. All 148 identity, integrator, runtime and
personal-secret domain test files pass.
- `pnpm test:e2e:runner:typecheck` passes.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --check`:
`changed: false`.
- Paid run: see the PR comment.
## Risks
- Low. Only eval graders and harness evidence change. The run-list rule
depends on the list order (newest first) and the default and maximum
limits from `packages/shared`.
- A product-cancelled run no longer retries automatically as transient
infrastructure.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.
## 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>
100 lines
12 KiB
TypeScript
100 lines
12 KiB
TypeScript
import { readSkillVersionHistory } from "./integrator-skill-versions.js";
|
||
import { saveSkillConversationContext } from "./integrator-skill-context.js";
|
||
import { factualContextQueryAttachment } from "../chat-query-attachments.js";
|
||
import type { CompanySkillDetail, CompanySkillFileDetail, CompanySkillListItem, CompanySkillVersion } from "../../../packages/shared/src/types/company-skill.js";
|
||
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
|
||
import { checks, observation, project, type InternalObservation } from "./internal-support.js";
|
||
import { integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js";
|
||
import { sourceSkillMarkdown, mobileChecks, openVettedSkillSource, skillSourceRequests, recordVettedSourceImport, closeVettedSkillSource, importReadOnlySkill, editableLocalNotes } from "./integrator-skill-source.js";
|
||
interface ImportObservation extends InternalObservation {
|
||
skills: CompanySkillDetail[]; skillVersions: Record<string, CompanySkillVersion[]>;
|
||
sourceRequests: ReturnType<typeof skillSourceRequests>; importedFile?: CompanySkillFileDetail;
|
||
}
|
||
const root = (ctx: ChatCatalogContext) => `/api/companies/${ctx.input.fixtures.company.id}/skills`;
|
||
async function observeImports(ctx: ChatCatalogContext, state: Record<string, unknown>): Promise<ImportObservation> {
|
||
const base = await observeInternal(ctx, state); const api = ctx.input.api;
|
||
const rows = await api.get<CompanySkillListItem[]>(root(ctx));
|
||
const skills = await Promise.all(rows.map(row => api.get<CompanySkillDetail>(`${root(ctx)}/${row.id}`)));
|
||
const skillVersions: Record<string, CompanySkillVersion[]> = Object.fromEntries(await Promise.all(skills.map(async row => [row.id, await readSkillVersionHistory(api, ctx.input.fixtures.company.id, row.id, row.currentVersionId)])));
|
||
let importedFile: CompanySkillFileDetail | undefined;
|
||
if (ctx.scenario.id === "skills.find-and-install") {
|
||
const imported = skills.find(row => row.sourceLocator === state.sourceURL);
|
||
if (imported) importedFile = await api.get<CompanySkillFileDetail>(`${root(ctx)}/${imported.id}/files?path=SKILL.md`);
|
||
if (imported && importedFile?.skillId === imported.id && importedFile.path === "SKILL.md" && importedFile.encoding !== "base64" && importedFile.content === imported.markdown
|
||
&& base.activity.some(event => event.action === "company.skills_imported" && event.agentId === base.leadId && event.details?.source === state.sourceURL && event.details?.importedCount === 1)) await recordVettedSourceImport(ctx, String(state.sourceURL), importedFile.content);
|
||
}
|
||
return { ...base, skills, skillVersions, importedFile, sourceRequests: skillSourceRequests(ctx) };
|
||
}
|
||
function importObservation(value: unknown): ImportObservation | undefined {
|
||
const o = value as ImportObservation;
|
||
return observation(value) && Array.isArray(o.skills) && !!o.skillVersions && Array.isArray(o.sourceRequests) ? o : undefined;
|
||
}
|
||
export function preservesMobileChecks(markdown: string) {
|
||
const lines = markdown.split(/\n+|(?<=[.!?])\s+/).filter(text => !/\b(?:skip|omit|ignore|do not|don't|optional)\b/i.test(text));
|
||
return lines.some(text => /touch/i.test(text) && /44\s*(?:by|x|×)\s*44/i.test(text) && /at least|minimum|>=|≥/.test(text))
|
||
&& lines.some(text => /portrait/i.test(text) && /landscape/i.test(text))
|
||
&& lines.some(text => /mobile Safari/i.test(text) && /checkout/i.test(text));
|
||
}
|
||
function changedFork(o: ImportObservation) {
|
||
const upstream = o.state.upstream as CompanySkillDetail | undefined;
|
||
return o.skills.find(row => row.forkedFromSkillId === upstream?.id && row.editable && preservesMobileChecks(row.markdown)
|
||
&& o.activity.some(event => event.entityId === row.id && event.agentId === o.leadId && ["company.skill_forked", "company.skill_file_updated", "company.skill_created"].includes(event.action ?? "")));
|
||
}
|
||
export function gradeIntegratorSkillImports(value: unknown) {
|
||
const c = checks(); const o = importObservation(value);
|
||
c.add("actual-source-library-and-version-evidence", !!o, "Requires the actual public source-import receipt, company library detail, independently retrieved imported bytes and available revision history.");
|
||
if (!o) return c.result();
|
||
c.add("permitted-source-prerequisite", o.state.importAllowed === true && (o.scenarioId === "skills.fork-read-only" ? o.state.upstreamQualified === true : o.sourceRequests.length >= 1), "Effective policy permits import; actual synthetic-source read or pinned immutable public upstream qualification is required for the selected fixture.");
|
||
if (o.scenarioId === "skills.find-and-install") {
|
||
const installed = o.skills.filter(row => row.sourceLocator === o.state.sourceURL); const skill = installed[0];
|
||
c.add("one-intended-source-installation", installed.length === 1 && !!skill && skill.companyId === o.companyId && skill.sourceType === "local_path" && skill.markdown === sourceSkillMarkdown
|
||
&& o.importedFile?.skillId === skill.id && o.importedFile.path === "SKILL.md" && o.importedFile.encoding !== "base64" && o.importedFile.content === sourceSkillMarkdown
|
||
&& (!skill.currentVersionId || o.skillVersions[skill.id]?.some(row => row.id === skill.currentVersionId && row.fileInventory.some(file => file.path === "SKILL.md" && file.content === sourceSkillMarkdown))), "One intended skill retains the approved local source locator and exact independently read SKILL.md bytes. A current immutable version, when present, must agree; ordinary local import does not promise one.");
|
||
c.add("agent-imported-approved-source", o.activity.some(event => event.action === "company.skills_imported" && event.agentId === o.leadId && event.details?.source === o.state.sourceURL
|
||
&& event.details?.importedCount === 1), "The responding agent imports the actual authorized source through the supported company route.");
|
||
c.add("truthful-installation-and-usage", !!skill && (o.reply.includes(skill.name) || !!resultHref(o, skill.id, "studio")) && skill.usedByAgents.length === 0
|
||
&& !/\b(?:board|human|admin(?:istrator)?)\b[^.!?\n]{0,40}\b(?:approval (?:is )?required|must approve|need(?:s)? to approve)\b/i.test(o.reply)
|
||
&& !/\b(?:enabled|assigned|activated)\b[^.!?\n]{0,30}\b(?:all|every)\s+agents?\b/i.test(o.reply), "The response identifies the saved skill by its saved name or a link to its page, without a fictional approval gate or global usage assignment.");
|
||
} else if (o.scenarioId === "skills.fork-read-only") {
|
||
const before = o.state.upstream as CompanySkillDetail | undefined; const original = o.skills.find(row => row.id === before?.id); const fork = changedFork(o);
|
||
c.add("upstream-remains-read-only-and-identical", !!before && !!original && original.editable === false && original.sourceType === "github" && original.sourceRef === before.sourceRef && original.sourceLocator === before.sourceLocator
|
||
&& original.currentVersionId === before.currentVersionId && original.markdown === before.markdown
|
||
&& JSON.stringify(o.skillVersions[original.id]) === JSON.stringify(o.state.upstreamVersions), "The real protected upstream package and full revision history remain unchanged.");
|
||
c.add("editable-provenance-preserving-mobile-fork", !!fork && !!before && fork.id !== before.id && fork.forkedFromSkillId === before.id && fork.forkedFromCompanyId === o.companyId
|
||
&& fork.markdown.includes(before.markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")) && preservesMobileChecks(fork.markdown)
|
||
&& o.skillVersions[fork.id]?.some(version => version.id === fork.currentVersionId && version.authorAgentId === o.leadId && version.fileInventory.some(file => file.path === "SKILL.md" && file.content === fork.markdown)), "A saved editable fork retains upstream provenance, the original substantive checklist and all actual mobile additions.");
|
||
const localBefore = o.state.localFork as CompanySkillDetail | undefined; const localNow = o.skills.find(row => row.id === localBefore?.id);
|
||
c.add("unrelated-local-notes-preserved", !!localBefore && !!localNow && localNow.markdown.includes("ORCHID customer escalation notes unchanged")
|
||
&& (localNow.id === fork?.id || localNow.currentVersionId === localBefore.currentVersionId && localNow.markdown === localBefore.markdown), "Existing local notes survive whether the agent edits the existing copy or selects a separate fork.");
|
||
c.add("correct-copy-explained", !!fork && (o.reply.includes(fork.name) || !!resultHref(o, fork.id, "studio")),
|
||
"Chat points the person at the saved editable copy by its saved name or a link to its page; the saved upstream and fork state above prove which copy changed.");
|
||
} else c.add("owned-import-oracle", false, "No independent import/fork oracle exists for this scenario.");
|
||
return c.result();
|
||
}
|
||
function define(id: "skills.find-and-install" | "skills.fork-read-only") {
|
||
return integratorDefinition("skills", id, async ctx => {
|
||
const source = id === "skills.find-and-install" ? await openVettedSkillSource(ctx) : undefined;
|
||
try {
|
||
const decision = await ctx.input.api.post<{ allowed: boolean }>(`/api/companies/${ctx.input.fixtures.company.id}/skill-policy/evaluate`, { principal: { agentId: ctx.input.fixtures.agent.id }, action: "skills.import", resource: { sourceType: source ? "workspace" : "git", ...(source ? { sourceLocator: source.url } : {}) } });
|
||
if (!decision.allowed) throw new Error("Source fixture does not have the canonical permitted skill policy");
|
||
const p = await project(ctx, "Launch");
|
||
if (source) {
|
||
await ctx.input.api.post(`/api/projects/${p.id}/workspaces`, { name: "Vetted synthetic source", cwd: source.workspaceRoot, isPrimary: true });
|
||
const existing = await ctx.input.api.get<CompanySkillListItem[]>(root(ctx));
|
||
if (existing.some(row => row.sourceLocator === source.url)) throw new Error("Source registration imported the evaluated skill before canonical admission");
|
||
const selected = await saveSkillConversationContext(ctx, { projectId: p.id, description: `Our vetted synthetic accessibility-review source is the one owned directory ${source.url}. It contains Markdown-only SKILL.md, and has not been imported into the company.` });
|
||
return { project: p, sourceURL: source.url, importAllowed: true, factualContextAttachment: selected.factualContextAttachment };
|
||
}
|
||
const upstream = await importReadOnlySkill(ctx); const localFork = await editableLocalNotes(ctx, upstream);
|
||
const selected = await saveSkillConversationContext(ctx, { projectId: p.id, description: `Selected read-only checklist skill: ${upstream.name} (${upstream.id}), source ${upstream.sourceLocator}, revision ${upstream.sourceRef}. Existing editable local notes: ${localFork.name} (${localFork.id}). Our mobile checks: ${mobileChecks.join(" ")}` });
|
||
return { project: p, sourceURL: upstream.sourceLocator, importAllowed: true, upstreamQualified: true, upstream, localFork, factualContextAttachment: selected.factualContextAttachment, upstreamVersions: await readSkillVersionHistory(ctx.input.api, ctx.input.fixtures.company.id, upstream.id, upstream.currentVersionId) };
|
||
} catch (error) { await closeVettedSkillSource(ctx); throw error; }
|
||
}, observeImports, gradeIntegratorSkillImports, async (ctx, _state, value) => {
|
||
const o = importObservation(value); const skill = o && (id === "skills.find-and-install" ? o.skills.find(row => row.sourceLocator === o.state.sourceURL) : changedFork(o));
|
||
if (!o || !skill) throw new Error("No actual saved skill copy for browser inspection");
|
||
await inspectResult(ctx, `/${ctx.input.fixtures.company.issuePrefix}/skills/studio/${skill.id}`, skill.name, resultHref(o, skill.id, "studio"));
|
||
}, { oracleVersion: id === "skills.find-and-install" ? "paperclip.chat-catalog.integrator.skill-import.v2" : "paperclip.chat-catalog.integrator.skill-fork.v2", authentication: "human-session", queryAttachments: factualContextQueryAttachment("skill-context.md"), sourceFiles: ["chat-catalog-domains/integrator-skill-versions.ts", "chat-catalog-domains/integrator-skill-imports.ts", "chat-catalog-domains/integrator-skill-source.ts", "chat-catalog-domains/integrator-skills.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/skills.yaml"],
|
||
async cleanup(ctx) { await closeVettedSkillSource(ctx); } });
|
||
}
|
||
export const integratorSkillImportCases = [define("skills.find-and-install"), define("skills.fork-read-only")];
|