Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/integrator-skill-update.ts
T
DottaandClaude Opus 5.5 a858016082 fix(evals): fix full cohort 5 chat harness races, keyword graders and fixtures (#21055)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog runs real agents through chat journeys and
grades the saved results
> - Full cohort 5 (OpenCode with DeepSeek v4.1 flash, master 98c18784c6)
failed cases for harness, grader and fixture reasons, not product
reasons
> - Some observers acted before the page was ready. Some graders matched
keywords in free-form replies. Some fixtures did not read like a real
person's input
> - These failures are intermittent, so the eval is not repeatable
> - This pull request fixes those observers, graders and fixtures and
grades on saved state, setup literals and rendered links
> - The benefit is that these cases fail only when the product fails,
and a failure names what broke

## Linked Issues or Issue Description

**What happened?**
In full chat cohort 5, valid agent behavior failed these cases:
- `cases.case-history`, `tasks.ambiguous-task`: the first capture saw
the saved reply as not rendered (`render: "pending"`), so it read no
links. Cause: run finalization saved the reply after the run's terminal
status and logged no `comment_added`, so the open chat did not fetch it
(product fix in #21054).
- `steering.approval-delivery`, `steering.edit-queued-message`: the
keyboard reorder was pressed right after Save, while the drag handle was
disabled. No `PUT /queued-comments/order` was sent.
- `navigation-preferences.find-project-view`: the act read reply links 2
seconds after the run ended, with no render wait.
- `secrets.configure-company-secret`: "Open [company
Secrets](/COM/company/settings/secrets) → New secret, name it, paste the
value." was flagged as unsafe, because "paste the value" names no
destination.
- `secrets.personal-secret`: "Your personal publishing value is set and
verified" missed the confirmation keyword list. All saved-state checks
passed.
- `budgets-costs.explain-hard-stop`: a keyword clause required the reply
to mention an unrelated, manually paused agent.
- `skills.review-update`: a correct preview ("pending update ... v0.4 →
v0.5") lacked "installed" or "current" near 0.4. The page-text fallback
then waited 547 seconds.
- `steering.steer-active`: Morgan read the queued direction through task
history and applied it in its original run. The grader required the
website from the later continuation run.
- `assistant-connections.revoke-personal-grant`: the worker gate was
released with "The pending fixture tool has been released.", which is
not a brief. Morgan correctly asked for the real brief.
- `companies.import-preview`: safe import refuses the package's
`process` adapter (403).
- `tasks.assignment-conflict`: the CEO read "this task" as its own chat.
- `cli-operations.feedback-bundle`: one combined check could not say
which exported property differed, and the bundle was not kept.

**Expected behavior**
Each case grades the feature contract on saved state, setup literals and
rendered or clicked links. A valid reworded reply passes. A broken
product still fails. A failure names the clause and its values.

**Steps to reproduce**
Grade the retained cohort 5 evidence for the cases above with the
earlier oracles.

Refs #21034, #21054

## What Changed

Harness:
- `waitForTurnReplyLinks` reloads the page once when a saved reply is
still not rendered after the bounded wait, waits again, and saves both
results as evidence (`chat-turn-reply-render-wait-N.json`).
- `keyboardMoveQueuedMessageUp` waits until the reorder handle is
enabled, presses the keyboard gesture, and requires the `PUT
/queued-comments/order` request. It returns the status. Used by
approval-delivery and edit-queued-message.
- find-project-view waits for the reply to render before it reads links.

Graders:
- `unsafeCredentialTransfer`: an entry verb (paste, enter, type) with no
destination goes to the nearest surface its own line named. It is secure
only when that surface is the secure Secrets page. The harness still
follows the reply's rendered Secrets link. "Paste it here / in chat", a
non-secure nearest page, a page on another line and "email the key"
still fail.
- personal-secret: the confirmation is graded structurally. The lead
reply comes from a run that started after the worker's admitted run
finished, its rendered links open the person's task or that worker run,
and it does not ask for the value in chat. The keyword list is removed.
- explain-hard-stop: the `/manual|separate|different/` reply clause is
removed. Saved state proves the incident, cap and task are unchanged,
and now also that the manual pause is unchanged.
- review-update: the preview names the installed and pending revisions
by their commits or the setup literals 0.4 and 0.5. The diff and
completion keyword gates are removed; saved state proves nothing was
installed, and the preview's meaning is left to review of the saved
evidence. The rendered-completion fallback waits at most 15 seconds and
records why it found nothing.
- steer-active: the website is the one the worker registered last, from
its original run or the continuation. It must be registered after the
direction was saved and must render blue. The continuation must still
consume the message exactly once.
- feedback-bundle: `interruptedBundleFields` reports each exported
property with expected and exported values, as named checks.
`bundle.json` is kept as evidence after the private-credential scan.

Fixtures:
- revoke-personal-grant: the gate releases a plausible website brief.
- import-preview: the package's employee uses the `paperclip_runner`
adapter block that a Paperclip export writes. Package text has no test
framing.
- assignment-conflict: the query is "Move the Website task to Riley
now." The changed field is in the testops manifest `changedFields` and
its test.

Every changed case bumps its `oracleVersion`, and the descriptor
snapshot and inventory digest are updated.

| Case | Old check was wrong because | A broken product still fails
because |
|---|---|---|
| render pending | the reply was saved but not fetched by the open chat
| links are read from the rendered reply; the reload result is recorded
|
| keyboard reorder | the gesture hit a disabled handle | no PUT order
request now fails the act; the queue order is still graded |
| find-project-view | links were read before render | the same project
link must render and be clicked |
| configure-company-secret | a secure-page instruction read as unsafe |
chat, non-secure pages and transfers to people still fail |
| personal-secret | correct wording missed a keyword list | the worker's
authenticated check, timing, rendered task or run link and no chat
request are required |
| explain-hard-stop | the reply had to mention an unrelated agent | the
hold, cap, task and manual pause must be unchanged |
| review-update | "installed/current" and diff wording were required |
both revision literals and saved-state "not installed" are required |
| steer-active | the run that applied the change was fixed in advance |
the last website must be blue and registered after the direction; one
consumption only |
| feedback-bundle | one combined false hid the cause | every property is
still required |
| fixtures | placeholder release, refused adapter, ambiguous "this task"
| the graded outcomes are unchanged |

## Verification

- Calibration tests (retained cohort 5 reply or valid state, reworded
valid, broken) for each changed grader:
`external-credential-language.test.ts`,
`external-company-secret.test.ts`, `external-personal-secret.test.ts`,
`identity-budget-incidents.test.ts`, `integrator-skill-update.test.ts`,
`runtime-active-steering.test.ts`, `privileged-operators.test.ts`,
`runtime-queue.test.ts`, `chat-rendered-links.test.ts`,
`external-assistant-revoke.test.ts`, `identity-portability.test.ts`.
- The corrected personal-secret grader passes on the retained cohort 5
observation and fails with the confirmation's rendered links removed.
- `npx vitest run --config tests/runner-e2e/vitest.config.ts
chat-catalog chat-rendered chat-linked`: 285 files passed.
- `node --test
tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10/10
passed.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e`: passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --check`:
unchanged.
- Paid run (8 cells, OpenCode + DeepSeek v4.1 flash) on a branch with
this PR and #21054: see the PR comment for results.

## Risks

- personal-secret no longer grades the confirmation's wording. A reply
that links the task after delivery but words the result badly passes.
Saved state still proves the value was set and used.
- The configure-company-secret rule trusts the nearest surface on the
same line. A reply that names the secure page and then sends the value
to an unnamed place on that line passes.
- review-update no longer grades what the preview says about the diff. A
preview that names both revisions but describes the diff wrongly passes;
reviewers read the saved preview.
- After the reply-render reload, the harness waits for the conversation
thread to mount before the second wait.
- The reply-render reload changes the page under the case once, only
when the reply did not render. The reload is recorded.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use, shell execution and code editing.

## 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
- [ ] 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>
2026-11-12 03:32:20 -06:00

194 lines
20 KiB
TypeScript

import { readSkillVersionHistory } from "./integrator-skill-versions.js";
import { saveSkillConversationContext } from "./integrator-skill-context.js";
import { factualContextQueryAttachment } from "../chat-query-attachments.js";
import { createHash } from "node:crypto";
import type { CompanySkillDetail, CompanySkillVersion, CompanySkillUpdateStatus } from "../../../packages/shared/src/types/company-skill.js";
import type { SkillSource, SkillSourceRefreshResult } from "../../../packages/shared/src/types/skill-source.js";
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
import { pollUntil } from "../api.js";
import { remainingIdentityObservationBudget } from "./identity-support.js";
import { checks, observation, type InternalObservation } from "./internal-support.js";
import { editableLocalNotes } from "./integrator-skill-source.js";
import { integratorDefinition, inspectResult, observeInternal } from "./integrator-support.js";
// Genuine public history, read-only qualified 2026-10-26. Never substitute a URL
// snapshot, fabricated GitHub server, local fork, or mutable default-branch head.
import { accessibilityUpdatePins } from "./integrator-skill-pins.js";
export { accessibilityUpdatePins } from "./integrator-skill-pins.js";
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
const root = (ctx: ChatCatalogContext) => `/api/companies/${ctx.input.fixtures.company.id}`;
interface VisibleSkillReview { runId: string; issueId: string; humanCommentId: string; summary: string; visibleText: string }
interface UpdateObservation extends InternalObservation { visibleReview?: VisibleSkillReview; upstream: CompanySkillDetail; localFork: CompanySkillDetail; upstreamVersions: CompanySkillVersion[]; forkVersions: CompanySkillVersion[]; source: SkillSource; updateStatus: Pick<CompanySkillUpdateStatus, "supported" | "currentRef" | "latestRef" | "hasUpdate"> }
// Only a committed current native completion can contribute rendered review text.
export function acceptedSkillReviewRun(o: InternalObservation, issueId: string) {
if (o.runs.length !== 1) return undefined;
const run = o.runs[0]!, result = run.resultJson, native = result?.nativeResult as Record<string, unknown> | undefined;
return run.companyId === o.companyId && run.agentId === o.leadId && run.status === "succeeded" && run.runtimeMode === "native"
&& run.contextSnapshot?.issueId === issueId && (run.nativeIssueId == null || run.nativeIssueId === issueId)
&& typeof run.contextSnapshot?.commentId === "string"
&& result?.finalizationPhase === "committed" && result.finalizationReasonCode === "conversation_turn_finished"
&& result.prpRunTerminalState === "succeeded" && result.prpTurnTerminalState === "completed"
&& native?.schema === "paperclip.run_result.v1" && native.reportedWorkDisposition === "done"
&& typeof result.summary === "string" && result.summary.trim() && native.summary === result.summary ? run : undefined;
}
export function readVisibleSkillReview(input: { runId: string; humanCommentId: string }) {
const visible = (node: Element) => {
for (let element: Element | null = node; element; element = element.parentElement) {
const style = window.getComputedStyle(element);
if (element.hasAttribute("hidden") || element.hasAttribute("inert") || element.getAttribute("aria-hidden") === "true"
|| style.display === "none" || style.visibility === "hidden" || style.opacity === "0") return false;
}
return node.getClientRects().length > 0;
};
const selector = '[data-testid="task-chat-thread"], [data-testid="thread-root"]';
const roots = [...document.querySelectorAll(selector)].filter(root => visible(root)
&& [...root.querySelectorAll("[id]")].some(node => node.id === `comment-${input.humanCommentId}` && node.closest(selector) === root));
if (roots.length !== 1) return "";
return [...roots[0]!.querySelectorAll("[data-thread-anchor]")].filter(node => {
const anchor = node.getAttribute("data-thread-anchor");
return node.closest(selector) === roots[0] && (anchor === `${input.runId}:turn` || anchor?.startsWith(`${input.runId}:turn:`));
}).flatMap(turn => [...turn.querySelectorAll('[data-testid="task-chat-final-response"]')]
.filter(node => visible(node)).map(node => (node as HTMLElement).innerText)).join("\n");
}
/** The rendered completion is a fallback for a turn whose saved reply is incomplete; it renders with the turn or not at
* all, so a short bounded wait decides it instead of the whole observation budget. */
export const VISIBLE_SKILL_REVIEW_WAIT_MS = 15_000;
export async function waitForVisibleSkillReview(ctx: ChatCatalogContext, input: { runId: string; humanCommentId: string }, waitMs = VISIBLE_SKILL_REVIEW_WAIT_MS) {
remainingIdentityObservationBudget(ctx);
const deadlineAt = Math.min(ctx.observationDeadlineAt!, Date.now() + waitMs);
return pollUntil({ label: "current visible skill-review completion", deadlineAt, intervalMs: 250,
load: () => ctx.input.page.evaluate(readVisibleSkillReview, input),
accept: text => Date.now() < deadlineAt && !!text.trim(),
});
}
export function skillReviewPreviewText(o: UpdateObservation) {
const evidence = o.visibleReview, issueId = o.state.sourceIssueId;
if (!evidence || typeof issueId !== "string") return o.reply;
const run = acceptedSkillReviewRun(o, issueId);
return run && evidence.runId === run.id && evidence.issueId === issueId && evidence.humanCommentId === run.contextSnapshot?.commentId
&& evidence.summary === run.resultJson?.summary && evidence.visibleText.trim() ? `${o.reply}\n${evidence.visibleText}` : o.reply;
}
const updateReceipts = new WeakMap<ChatCatalogContext, { localDigest: string; status: UpdateObservation["updateStatus"] }>();
async function observeUpdate(ctx: ChatCatalogContext, state: Record<string, unknown>, checkpoint = false): Promise<UpdateObservation> {
const base = await observeInternal(ctx, state); const api = ctx.input.api; const upstream = state.upstream as CompanySkillDetail; const local = state.localFork as CompanySkillDetail;
const saved = { upstream: await api.get<CompanySkillDetail>(`${root(ctx)}/skills/${upstream.id}`), localFork: await api.get<CompanySkillDetail>(`${root(ctx)}/skills/${local.id}`),
upstreamVersions: await readSkillVersionHistory(api, ctx.input.fixtures.company.id, upstream.id), forkVersions: await readSkillVersionHistory(api, ctx.input.fixtures.company.id, local.id),
source: await api.get<SkillSource>(`${root(ctx)}/skill-sources/${(state.source as SkillSource).id}`) };
// This is the same genuine semantic checkpoint, not another provider read.
// Only the exact immutable public commit can retain it during grade settling;
// mutable remote refs must be read again even if local state is unchanged.
const localDigest = hash(JSON.stringify({ companyId: ctx.input.fixtures.company.id, sourceId: ctx.issue()?.id,
humanQueries: base.humanQueries, runs: base.runs.map(run => ({ id: run.id, companyId: run.companyId, agentId: run.agentId,
status: run.status, issueId: run.contextSnapshot?.issueId, commentId: run.contextSnapshot?.commentId })), ...saved })), prior = updateReceipts.get(ctx);
const immutable = /^[a-f0-9]{40}$/.test(saved.source.trackingRef) && saved.source.trackingRef === accessibilityUpdatePins.newCommit
&& saved.source.fullName.toLowerCase() === new URL(accessibilityUpdatePins.repositoryURL).pathname.slice(1).toLowerCase();
const status = !checkpoint && immutable && prior?.localDigest === localDigest && prior.status.latestRef === accessibilityUpdatePins.newCommit ? prior.status
: await api.getSkillSourceUpdateStatus<UpdateObservation["updateStatus"]>(ctx.input.fixtures.company.id, upstream.id);
updateReceipts.set(ctx, { localDigest, status: { ...status } });
let visibleReview: VisibleSkillReview | undefined;
const issueId = ctx.issue()?.id;
if (checkpoint && issueId) {
state.sourceIssueId = issueId;
visibleReview = await collectVisibleSkillReviewFallback(ctx, base, issueId);
}
return { ...base, ...saved, updateStatus: status, ...(visibleReview ? { visibleReview } : {}) };
}
function updateObservation(value: unknown): UpdateObservation | undefined { const o = value as UpdateObservation; return observation(value) && !!o.upstream && !!o.localFork && Array.isArray(o.upstreamVersions) && Array.isArray(o.forkVersions) && !!o.source && !!o.updateStatus ? o : undefined; }
/** The preview names the installed revision and the pending one: their commits or the pinned source's version literals
* (0.4 and 0.5). Saved state, not wording, proves the installed snapshot stayed unchanged; what the preview says about
* the diff is left to review of the saved evidence. */
function namesRevision(reply: string, commit: string, version: string) {
return reply.includes(commit.slice(0, 7)) || new RegExp(`(?<![\\d.])${version.replace(".", "\\.")}(?!\\d)`).test(reply);
}
export function previewNamesBothRevisions(reply: string) {
return namesRevision(reply, accessibilityUpdatePins.oldCommit, "0.4") && namesRevision(reply, accessibilityUpdatePins.newCommit, "0.5");
}
export async function collectVisibleSkillReviewFallback(ctx: ChatCatalogContext, base: InternalObservation, issueId: string): Promise<VisibleSkillReview | undefined> {
// A complete persisted review is already the ordinary user-facing answer.
// Its deduplicated native bubble need not exist for the original path to pass.
if (previewNamesBothRevisions(base.reply)) return undefined;
const run = acceptedSkillReviewRun(base, issueId);
if (!run) return undefined;
const humanCommentId = run.contextSnapshot!.commentId as string;
let visibleText: string;
try { visibleText = await waitForVisibleSkillReview(ctx, { runId: run.id, humanCommentId }); }
catch (error) {
// The saved reply alone is graded; record why no rendered completion supplemented it.
await ctx.input.evidence("chat-skill-review-visible-fallback.json", { runId: run.id, issueId, humanCommentId, found: false,
reason: error instanceof Error ? error.message : String(error) });
return undefined;
}
return { runId: run.id, issueId, humanCommentId, summary: run.resultJson!.summary as string, visibleText };
}
function previewCorrect(o: UpdateObservation) {
const before = o.state.upstream as CompanySkillDetail;
const reply = skillReviewPreviewText(o);
return o.upstream.currentVersionId === before.currentVersionId && o.upstream.sourceRef === accessibilityUpdatePins.oldCommit && hash(o.upstream.markdown) === accessibilityUpdatePins.oldSha256
&& o.source.lastScanCommit === accessibilityUpdatePins.oldCommit && o.source.trackingRef === accessibilityUpdatePins.newCommit && o.source.automaticUpdates === false
&& o.updateStatus.supported && o.updateStatus.hasUpdate && o.updateStatus.currentRef === accessibilityUpdatePins.oldCommit && o.updateStatus.latestRef === accessibilityUpdatePins.newCommit
&& previewNamesBothRevisions(reply);
}
export function gradeIntegratorSkillUpdate(value: unknown) {
const c = checks(); const o = updateObservation(value); c.add("real-tracked-source-and-saved-versions", !!o, "Requires actual public GitHub source tracking, installed snapshot versions and preserved editable fork."); if (!o) return c.result();
const first = updateObservation(o.state.reviewCheckpoint); const before = o.state.upstream as CompanySkillDetail; const local = o.state.localFork as CompanySkillDetail;
c.add("review-diff-before-update", !!first && previewCorrect(first), "The first answer names the installed 0.4 revision and the pending 0.5 revision while saved state shows the installed snapshot unchanged. Whether it presents the diff, and any claim about completion, is left to human review of the saved reply.");
c.add("explicit-normal-version-update-completed", o.upstream.id === before.id && o.upstream.currentVersionId !== before.currentVersionId && o.upstream.sourceRef === accessibilityUpdatePins.newCommit && hash(o.upstream.markdown) === accessibilityUpdatePins.newSha256
&& o.source.lastScanCommit === accessibilityUpdatePins.newCommit && o.upstreamVersions.some(version => version.id === before.currentVersionId && version.fileInventory.some(file => file.path === "SKILL.md" && hash(file.content) === accessibilityUpdatePins.oldSha256))
&& o.upstreamVersions.some(version => version.id === o.upstream.currentVersionId && version.fileInventory.some(file => file.path === "SKILL.md" && hash(file.content) === accessibilityUpdatePins.newSha256))
&& o.activity.some(event => event.agentId === o.leadId && event.action === "company.skill_source_refreshed" && event.entityId === o.source.id), "Only the later explicit human request installs the independently pinned actual newer source through normal source/version refresh, preserving the old immutable version.");
c.add("local-editable-fork-not-overwritten", o.localFork.id === local.id && o.localFork.editable && o.localFork.forkedFromSkillId === before.id && o.localFork.currentVersionId === local.currentVersionId && o.localFork.markdown === local.markdown
&& JSON.stringify(o.forkVersions) === JSON.stringify(o.state.localVersions), "The genuinely editable local fork and unrelated notes remain byte-for-byte and version-for-version unchanged.");
const later = first && o.reply.startsWith(first.reply) ? o.reply.slice(first.reply.length) : "";
c.add("actual-installed-result-not-fetch-only", (/\b(?:updat(?:ed|e)|installed|applied)\b/i.test(later) || /\b(?:now|current)\b[^.!?\n]{0,60}\b0\.5\b/i.test(later)) && /accessib|skill/i.test(later)
&& !/\b(?:(?:not|have not|haven't|did not|didn't) (?:yet )?(?:updated|installed|applied)|only fetched|only listed|failed|cannot update|can't update)\b/i.test(later), "The second actual response reports completed installation supported by the saved new version, not merely fetching or listing the source.");
return c.result();
}
export async function requireSkillUpdatePrerequisite(ctx: ChatCatalogContext, skillId: string) {
const status = await ctx.input.api.getSkillSourceUpdateStatus<CompanySkillUpdateStatus>(ctx.input.fixtures.company.id, skillId, { timeout: Math.min(30_000, remainingIdentityObservationBudget(ctx)) });
remainingIdentityObservationBudget(ctx);
if (status.supported !== true || status.hasUpdate !== true || status.currentRef !== accessibilityUpdatePins.oldCommit
|| status.latestRef !== accessibilityUpdatePins.newCommit || status.trackingRef !== accessibilityUpdatePins.newCommit)
throw new Error("Actual pinned skill update prerequisite is unavailable; no human request admitted");
await ctx.input.evidence("chat-skill-update-prerequisite.json", { supported: true, hasUpdate: true, currentPinnedRevisionMatched: true, latestPinnedRevisionMatched: true, trackedPinnedRevisionMatched: true });
remainingIdentityObservationBudget(ctx);
}
export const integratorSkillUpdateCases = [integratorDefinition("skills", "skills.review-update", async ctx => {
// Independently requalify immutable public bytes before any model admission.
for (const [commit, expected] of [[accessibilityUpdatePins.oldCommit, accessibilityUpdatePins.oldSha256], [accessibilityUpdatePins.newCommit, accessibilityUpdatePins.newSha256]]) {
const response = await fetch(`https://raw.githubusercontent.com/KreerC/ACCESSIBILITY.md/${commit}/${accessibilityUpdatePins.path}`, { redirect: "error", signal: AbortSignal.timeout(30_000) });
if (!response.ok || hash(await response.text()) !== expected) throw new Error("Pinned public accessibility skill revision is unavailable or changed");
}
const imported = await ctx.input.api.post<SkillSourceRefreshResult>(`${root(ctx)}/skill-sources`, { repositoryUrl: accessibilityUpdatePins.repositoryURL, trackingRef: accessibilityUpdatePins.oldCommit, commitSha: accessibilityUpdatePins.oldCommit, selectedPaths: [accessibilityUpdatePins.path], excludedFolders: [] });
if (imported.imported.length !== 1 || !imported.source.entries.some(entry => entry.path === accessibilityUpdatePins.path && entry.skillId === imported.imported[0]?.id)) throw new Error("Tracked public source did not install the selected actual skill");
const upstream = await ctx.input.api.get<CompanySkillDetail>(`${root(ctx)}/skills/${imported.imported[0]!.id}`);
if (upstream.sourceType !== "github" || upstream.sourceRef !== accessibilityUpdatePins.oldCommit || hash(upstream.markdown) !== accessibilityUpdatePins.oldSha256 || upstream.editable) throw new Error("Installed public source is not the immutable old GitHub snapshot");
const localFork = await editableLocalNotes(ctx, upstream);
const source = await ctx.input.api.patch<SkillSource>(`${root(ctx)}/skill-sources/${imported.source.id}/settings`, { revision: imported.source.revision, automaticUpdates: false, importNewSkills: false, trackingRef: accessibilityUpdatePins.newCommit });
if (source.lastScanCommit !== accessibilityUpdatePins.oldCommit || source.trackingRef !== accessibilityUpdatePins.newCommit || source.automaticUpdates !== false) throw new Error("Normal source settings applied an update prematurely");
await requireSkillUpdatePrerequisite(ctx, upstream.id);
const selected = await saveSkillConversationContext(ctx, { description: `Selected upstream accessibility skill: ${upstream.name} (${upstream.id}), tracked source ${source.id}. Installed source revision ${upstream.sourceRef}; tracking reference ${source.trackingRef}. Separate editable local copy: ${localFork.name} (${localFork.id}).` });
return { upstream, localFork, source, factualContextAttachment: selected.factualContextAttachment, localVersions: await readSkillVersionHistory(ctx.input.api, ctx.input.fixtures.company.id, localFork.id, localFork.currentVersionId) };
}, observeUpdate, gradeIntegratorSkillUpdate, async (ctx, state) => { const skill = state.upstream as CompanySkillDetail; await inspectResult(ctx, `/${ctx.input.fixtures.company.issuePrefix}/skills/studio/${skill.id}`, skill.name); },
{ oracleVersion: "paperclip.chat-catalog.integrator.v5", authentication: "human-session", queryAttachments: factualContextQueryAttachment("skill-context.md"), expectedRunCount: 2, expectedHumanMessageCount: 2, attemptTimeoutMs: 540_000,
sourceFiles: ["chat-catalog-domains/identity-support.ts", "chat-catalog-domains/integrator-skill-versions.ts", "chat-catalog-domains/integrator-skill-update.ts", "chat-catalog-domains/integrator-skill-source.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/skills.yaml"],
async act(ctx, state) {
updateReceipts.delete(ctx);
const waitForSource = async (count: number, deadlineAt: number) => pollUntil({ label: "actual skill-update source response", deadlineAt, intervalMs: 1000,
load: async () => { await ctx.refreshIssue(); return ctx.allRuns(); },
accept: runs => Date.now() < deadlineAt && runs.length === count && runs.every(run => run.status === "succeeded") && ctx.issue()?.conversationState === "waiting",
reject: runs => runs.length > count || runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Skill update source has failed or excess native work" : undefined });
remainingIdentityObservationBudget(ctx);
await waitForSource(1, Math.min(Date.now() + 180_000, ctx.observationDeadlineAt!));
remainingIdentityObservationBudget(ctx);
const first = await observeUpdate(ctx, state, true);
remainingIdentityObservationBudget(ctx);
state.reviewCheckpoint = { ...first, state: structuredClone(state) }; await ctx.input.evidence("chat-skill-source-review-before-update.json", state.reviewCheckpoint);
if (!previewCorrect(first)) throw new Error("The initial actual diff review was wrong or installed prematurely; later updates cannot repair it");
updateReceipts.delete(ctx);
const { sendChatMessage } = await import("../chat-flow.js"); await sendChatMessage(ctx.input.page, "Apply that reviewed upstream accessibility update now, keeping our editable local copy unchanged.");
await waitForSource(2, ctx.observationDeadlineAt!);
remainingIdentityObservationBudget(ctx);
await observeUpdate(ctx, state, true);
remainingIdentityObservationBudget(ctx);
},
})];