mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 12:50:37 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The chat-feature eval catalog runs real chat journeys. It grades saved state, rendered links and run ledgers. > - Chat-eval cohort 15 (OpenCode with `openrouter/deepseek/deepseek-v4.1-flash-1017`, master `36101ebcb9`) failed four cases where the agent did the right thing or where our own server text misled it. > - One failure was a harness race introduced by #21667. Two failures came from graders that read free-form text with keyword regexes. One failure came from an unprefixed approval link in the server's completion feedback, plus a grader that required a literal prefix. > - This pull request fixes the harness step, replaces the free-form graders with saved-state and clicked-link checks, and makes the server emit company-prefixed board links. > - The benefit is that these cases measure the feature again. The retained correct outcomes pass, and the relevant broken outcomes still fail. ## Linked Issues or Issue Description Refs #21667 **What happened?** In chat-eval cohort 15, four cases failed: - `projects.share-project`: the harness followed the agent's ID-based project link. The app then rewrote the URL to the project slug and redrew the page. The owner step timed out because Riley's option in the people picker was "detached from the DOM". #21667 introduced this path. - `skills.author-skill`: the saved skill was a correct, richer checklist. Per-sentence keyword regexes rejected it. For example, "ignore the mouse" tripped the forbidden word "ignore". - `inbox-search.show-decisions`: the reply linked the right approval and tasks and said the question was "addressed to a different teammate". A regex required the word "Riley". - `agents.hire-needs-approval`: both replies linked `/approvals/<id>` without the company prefix. The agent copied that link from `server/src/services/native-runtime/native-completion-feedback.ts`. The grader required a literal `/<prefix>/approvals/<id>`, although the board redirects the unprefixed route. **Expected behavior** Correct agent behaviour passes. Grading uses saved state, setup literals and rendered or clicked links, not free-form wording. The server gives agents canonical company-prefixed board links. **Steps to reproduce** 1. Use the retained cohort-15 evidence for the four cases. 2. Run the old graders on the retained skill markdown and decisions reply. Both fail. 3. For share-project, open a project configuration page by ID while the app rewrites the route after a delay, then use the access picker before the rewrite completes. 4. For hire-needs-approval, finish a task with a pending linked approval. The feedback links `/approvals/<id>`. **Paperclip version or commit** master `36101ebcb9` (cohort 15); fixed on top of current master. ## What Changed - `projects.share-project` (`internal-privacy.ts`, `runtime-support.ts`): after the harness follows the agent's link, it waits until the URL settles on the project's canonical route key. This reuses the #21667 approach for agent profiles: `settleAgentProfileRoute` now calls a shared `settleRouteKey`, and `projectRouteKey` follows the app's `projectRouteRef`. The owner's picker selection (`addProjectAccessMember`) now retries as one unit. If the dialog or picker closes, or an option detaches, it reopens them, searches again and selects again. It continues only when the picker shows the person and Add is enabled. - `skills.author-skill` (`integrator-skills.ts`): removed the keyword-regex checklist grader, the waiver regexes, and the reply regexes for "global activation" and "attached to me" claims. The saved-state checks stay: one agent-created writable skill, its current revision authored by the responding agent, the same bytes on the skill and the revision, the Skills/Studio inspection with reload, and assignment scope from saved assignments and audit rows. The checklist check now requires the setup literals `375`, `WCAG` and `AA` as whole tokens in the saved SKILL.md and in the rendered editor. Whether the skill still asks for keyboard-only navigation and visible labels, and whether it waives a check, is left to human review. Oracle version `skill-authoring.v10`. - `inbox-search.show-decisions` (`internal-decision-search.ts`): removed all reply regexes, including the `Riley` requirement and the wording-based separation checks. The grade now uses saved state (pending decisions unchanged, answered history unchanged, each person's own attention queue and resolver) and rendered links to the exact approval, the question's task and the history task. Oracle version `decision-search.v3`. - Product (`native-completion-feedback.ts`): the completion feedback now links `/<prefix>/approvals/<id>` and `/<prefix>/issues/<identifier>`. This fixes the approval link and the four sibling task links in the same file. - `agents.hire-needs-approval` (`runtime-hiring.ts`): the harness now clicks each reply's rendered link to its approval and records where the UI lands. The grade accepts a prefixed link, or an unprefixed link that the board redirect lands on `/<prefix>/approvals/<id>` with the proposed hire visible. Without such a link, the harness still opens the approval directly so later phases keep their evidence, and the grade fails. Oracle version `runtime-hiring.v4`. - No eval YAML changed, so the TestOps manifest does not change. `chat-catalog-descriptors.json` records the three oracle version bumps. ## Verification - Red/green tests (each new test fails on the old code and passes on the new code): - `internal-privacy-share-route.test.ts` (real Chromium): the project page rewrites its route after 0, 400 and 1500 ms, and one case closes the picker while its first results render. With the old flow, the 400 ms rewrite and the closed picker both time out on the option click (the cohort-15 failure). With the fix, Riley is added on the settled route in all cases. - `integrator-skills.test.ts`: the retained cohort-15 SKILL.md passes. The old grader rejects it. A stale skill body, another author, and a lost 375 width still fail. - `internal-decision-search.test.ts`: the retained cohort-15 reply and a reworded reply pass. The old grader rejects the retained reply. A missing or wrong approval, question-task or history-task link fails. - `native-completion-feedback.test.ts`: a pending linked approval produces `[the pending approval](/<prefix>/approvals/<id>)`, and a pending review stage produces a prefixed task link. The old code produces `/approvals/<id>`. - `runtime-hiring.test.ts`: unprefixed links that the redirect lands on the right approval pass. The old grader rejects them. A link that did not land, landed on another approval, was not clicked, or is another href still fails. - `npx vitest run --config tests/runner-e2e/vitest.config.ts chat-catalog`: all passed (one negative control in `internal.test.ts` changed from a reply wording to "approved while listing"). - `pnpm test:e2e:runner:typecheck` and `server` `tsc --noEmit`: passed. - `server` vitest for `native-completion-feedback`, `native-current-wake-completion-feedback` and `heartbeat/run-completion`: 201 tests passed. - Narrow paid run of the four full case ids on this branch: run 43657390762 (results are added in a comment). ## Risks - Low risk. The product change only adds the company prefix to links in agent feedback text. It adds one indexed company read, and only on the branches that return a link. - Less is graded automatically, by design. `skills.author-skill` no longer checks that the skill keeps the keyboard-only and visible-label checks or that it does not waive a check. `inbox-search.show-decisions` no longer checks how the reply names resolvers or separates the person's decision from others' and from history. `skills.author-skill` no longer checks whether the reply describes the assignment scope truthfully. A person reviews this meaning. Saved state and links still catch the plausible broken outcomes listed above. - `agents.hire-needs-approval` now needs a reply link that really opens the approval. A reply without a link to its approval fails as before. ## Model Used - Claude, model ID `claude-opus-5-5` (Claude Code agent with tool use and code execution). ## 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>
371 lines
30 KiB
TypeScript
371 lines
30 KiB
TypeScript
import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely } from "../chat-catalog-contract.js";
|
|
import { expect, type Page } from "@playwright/test";
|
|
import { deriveProjectUrlKey, hasNonAsciiContent, normalizeProjectUrlKey } from "../../../packages/shared/src/project-url-key.js";
|
|
import { settleRouteKey } from "./runtime-support.js";
|
|
import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js";
|
|
import { createAuthenticatedPerson, enrollPrerequisitePerson } from "./identity-auth.js";
|
|
import { makeDefinition, fixtureWorker } from "./internal-definition.js";
|
|
import { internalResultLink, project, task, entity, observation, checks, observeInternal, hasLink, sameTask, type Entity, type InternalObservation } from "./internal-support.js";
|
|
import { pollUntil } from "../api.js";
|
|
|
|
type Person = Awaited<ReturnType<typeof createAuthenticatedPerson>>;
|
|
interface PrivateRecord extends Entity { visibility?: "private" | "open"; privacyOwnerUserId?: string | null; personalOwnerUserId?: string | null }
|
|
interface PrivacyObservation extends InternalObservation {
|
|
protectedProject: PrivateRecord | null;
|
|
observer: { projectStatus: number; taskStatus: number; projectsStatus: number; searchStatus: number; projectsBody: string; searchBody: string };
|
|
leadStatus: number; unrelatedAgentStatus: number; unrelatedPublicStatus: number;
|
|
}
|
|
export async function mainPerson(ctx: ChatCatalogContext) {
|
|
const session = await ctx.input.api.get<{ user?: { id: string } }>("/api/auth/get-session");
|
|
if (!session.user?.id) throw new Error("Privacy fixtures require the real signed-in responsible person");
|
|
return session.user.id;
|
|
}
|
|
export async function observerPerson(ctx: ChatCatalogContext) {
|
|
const browser = ctx.input.page.context().browser();
|
|
if (!browser || !ctx.input.privateSecrets) throw new Error("Independent authenticated observer requires a browser and attempt-private redaction sink");
|
|
const observer = await createAuthenticatedPerson({ api: ctx.input.api, browser, secrets: ctx.input.privateSecrets, name: "Riley" });
|
|
try { await enrollPrerequisitePerson(ctx, observer, "viewer"); }
|
|
catch (error) { await observer.dispose(); throw error; }
|
|
return observer;
|
|
}
|
|
export async function personRead(person: Person, path: string) {
|
|
const response = await person.request(path);
|
|
const body = response.ok ? await response.text() : "";
|
|
if (!response.ok) await response.body?.cancel();
|
|
return { status: response.status, body };
|
|
}
|
|
const privacyProbeKeys = new WeakMap<ChatCatalogContext, Map<string, Promise<{ id: string; token: string }>>>();
|
|
async function privacyProbeKey(ctx: ChatCatalogContext, agentId: string) {
|
|
if (!ctx.input.privateSecrets) throw new Error("Privacy probes require attempt-private credential redaction");
|
|
let keys = privacyProbeKeys.get(ctx); if (!keys) { keys = new Map(); privacyProbeKeys.set(ctx, keys); }
|
|
let pending = keys.get(agentId);
|
|
if (!pending) {
|
|
pending = ctx.input.api.postSensitive<{ id: string; token: string }>(`/api/agents/${agentId}/keys`, { name: `privacy-probe-${ctx.input.nonce}` })
|
|
.then(key => { ctx.input.privateSecrets!.push(key.token); return key; });
|
|
keys.set(agentId, pending);
|
|
}
|
|
return pending;
|
|
}
|
|
export async function cleanupPrivacyProbes(ctx: ChatCatalogContext) {
|
|
const keys = privacyProbeKeys.get(ctx); privacyProbeKeys.delete(ctx);
|
|
for (const [agentId, pending] of keys ?? []) {
|
|
const key = await pending; await ctx.input.api.delete(`/api/agents/${agentId}/keys/${key.id}`, { allowNotFound: true });
|
|
}
|
|
}
|
|
export async function agentStatus(ctx: ChatCatalogContext, agentId: string, path: string) {
|
|
const key = await privacyProbeKey(ctx, agentId);
|
|
const url = new URL(path, ctx.input.api.baseURL);
|
|
if (url.origin !== ctx.input.api.baseURL || !url.pathname.startsWith("/api/")) throw new Error("Privacy probe escaped its isolated API");
|
|
const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(15_000), headers: { Authorization: `Bearer ${key.token}` } });
|
|
await response.body?.cancel(); return response.status;
|
|
}
|
|
function privacyObservation(value: unknown): PrivacyObservation | undefined {
|
|
const o = observation(value) as PrivacyObservation | undefined;
|
|
return o && !!o.observer && typeof o.leadStatus === "number" && typeof o.unrelatedAgentStatus === "number" ? o : undefined;
|
|
}
|
|
export function gradePrivateProject(value: unknown) {
|
|
const c = checks(); const o = privacyObservation(value);
|
|
c.add("complete-multi-principal-evidence", !!o, "A privacy result needs real signed-in observer, acting-agent and unrelated-agent API evidence.");
|
|
if (!o) return c.result();
|
|
const p = o.protectedProject; const probe = o.state.inheritanceTask ? entity(o.state, "inheritanceTask") : undefined;
|
|
c.add("agent-created-owned-private-project", !!p && p.visibility === "private" && p.companyId === o.companyId
|
|
&& typeof o.state.ownerId === "string" && !!o.state.ownerId && p.privacyOwnerUserId === o.state.ownerId && o.projects.filter(row => /acquisition/i.test(row.name ?? "")).length === 1
|
|
&& o.activity.some(row => row.action === "project.created" && row.entityId === p.id && row.agentId === o.leadId),
|
|
"One newly requested private project derives ownership from the authorized person and is actually created by the CEO.");
|
|
c.add("acting-agent-retains-access", o.leadStatus === 200, "The acting CEO can independently read its saved private result under its own agent principal.");
|
|
c.add("observer-cannot-discover-or-read", o.observer.projectsStatus === 200 && o.observer.searchStatus === 200 && [403, 404].includes(o.observer.projectStatus) && [403, 404].includes(o.observer.taskStatus)
|
|
&& !!p && !o.observer.projectsBody.includes(p.id) && !o.observer.searchBody.includes(p.id)
|
|
&& !!probe && !o.observer.searchBody.includes(probe.id) && !o.observer.searchBody.includes(String(o.state.privateMarker)),
|
|
"The unrelated real company member cannot discover the project or its inherited private task through lists, search or copied resource IDs.");
|
|
c.add("unrelated-agent-excluded", o.unrelatedPublicStatus === 200 && [403, 404].includes(o.unrelatedAgentStatus), "A separate agent without project membership cannot read the new private project.");
|
|
c.add("inheritance-probe-owned-by-project", !!p && !!probe && probe.projectId === p.id && o.tasks.some(row => row.id === probe.id && row.projectId === p.id),
|
|
"A separate labeled production-API probe verifies the new project's task access inheritance; it is not a preseeded project result.");
|
|
c.add("authorized-project-link", !!p && hasLink(o, "projects", p), "The actual authorized person receives the exact saved project link in Chat.");
|
|
return c.result();
|
|
}
|
|
function privateProject(): ChatCatalogCase {
|
|
let observer: Person | undefined;
|
|
const base = makeDefinition("projects.private-project", async ctx => {
|
|
const ownerId = await mainPerson(ctx); observer = await observerPerson(ctx);
|
|
const unrelated = await fixtureWorker(ctx); await ctx.input.api.patch(`/api/agents/${unrelated.id}`, { name: "Unrelated observer bot" });
|
|
return { ownerId, observerId: observer.id, unrelatedAgent: unrelated, privateMarker: `Protected acquisition ${ctx.input.nonce}` };
|
|
}, gradePrivateProject);
|
|
return { ...base, authentication: "human-session", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"],
|
|
async act(ctx, state) {
|
|
const first = await pollUntil({ label: "Agent-created private project", deadlineAt: Date.now() + 150_000,
|
|
load: () => observeInternal(ctx, state), accept: o => o.projects.filter(row => /acquisition/i.test(row.name ?? "")).length === 1
|
|
&& o.runs.length === 1 && o.runs.every(row => row.status === "succeeded") && ctx.issue()?.conversationState === "waiting" });
|
|
const p = first.projects.find(row => /acquisition/i.test(row.name ?? ""))!;
|
|
state.project = p;
|
|
state.inheritanceTask = await task(ctx, String(state.privateMarker), p.id, { description: "Independent private-project inheritance probe; not requested work or agent output." });
|
|
await ctx.input.evidence("chat-catalog-private-project-inheritance-probe.json", { projectId: p.id, task: state.inheritanceTask,
|
|
purpose: "Independently test access inheritance after the model-created project; setup did not create the requested project." });
|
|
},
|
|
async observe(ctx, state) {
|
|
if (!observer) throw new Error("Authenticated privacy observer is unavailable");
|
|
const o = await observeInternal(ctx, state); const p = state.project ? o.projects.find(row => row.id === entity(state, "project").id) as PrivateRecord | undefined : undefined;
|
|
const inheritanceTask = state.inheritanceTask ? entity(state, "inheritanceTask") : undefined;
|
|
const root = `/api/companies/${o.companyId}`;
|
|
const [privateRead, taskRead, visibleProjects, search, leadStatus, unrelatedAgentStatus, unrelatedPublicStatus] = await Promise.all([
|
|
p ? personRead(observer, `/api/projects/${p.id}`) : { status: 0, body: "" },
|
|
inheritanceTask ? personRead(observer, `/api/issues/${inheritanceTask.id}`) : { status: 0, body: "" },
|
|
personRead(observer, `${root}/projects?includeArchived=true`), personRead(observer, `${root}/search?q=${encodeURIComponent(String(state.privateMarker))}`),
|
|
p ? agentStatus(ctx, o.leadId, `/api/projects/${p.id}`) : 0,
|
|
p ? agentStatus(ctx, entity(state, "unrelatedAgent").id, `/api/projects/${p.id}`) : 0,
|
|
agentStatus(ctx, entity(state, "unrelatedAgent").id, `${root}/projects`),
|
|
]);
|
|
return { ...o, protectedProject: p ?? null, observer: { projectStatus: privateRead.status, taskStatus: taskRead.status,
|
|
projectsStatus: visibleProjects.status, searchStatus: search.status, projectsBody: visibleProjects.body,
|
|
searchBody: search.status === 200 ? JSON.stringify((JSON.parse(search.body) as { results: unknown[] }).results) : "" }, leadStatus, unrelatedAgentStatus, unrelatedPublicStatus } satisfies PrivacyObservation;
|
|
},
|
|
async verifyResult(ctx, state, value) {
|
|
await base.verifyResult(ctx, state, value);
|
|
if (!observer) throw new Error("Missing independent browser observer");
|
|
const p = entity(state, "project"); const observerPage = await observer.context.newPage();
|
|
try {
|
|
await observerPage.goto(new URL(`/${ctx.input.fixtures.company.issuePrefix}/projects/${p.id}`, ctx.input.api.baseURL).href, { waitUntil: "domcontentloaded" });
|
|
await expect(observerPage.getByRole("heading", { name: p.name!, exact: true })).toHaveCount(0);
|
|
await expect(observerPage.getByText(/not found|not available|access denied|do not have access|couldn't load/i).first()).toBeVisible();
|
|
await ctx.input.evidence("chat-catalog-private-project-observer-browser.json", { observerId: observer.id, projectId: p.id,
|
|
denied: true, outcome: "The copied project link presents an access error, without the protected project heading." });
|
|
} finally { await observerPage.close(); }
|
|
},
|
|
async cleanup(ctx) { try { await cleanupPrivacyProbes(ctx); } finally { await observer?.dispose(); observer = undefined; } },
|
|
};
|
|
}
|
|
export const projectPrivacyCases: readonly ChatCatalogCase[] = [privateProject(), shareProject()];
|
|
|
|
interface AccessMember extends Entity { subjectType?: string; subjectId?: string; source?: string }
|
|
interface ShareProjectObservation extends InternalObservation {
|
|
sharedProject: PrivateRecord | null; members: AccessMember[]; observerProjectStatus: number; observerProtectedTaskStatus: number;
|
|
}
|
|
/** A same-origin link to the project's configuration page, which carries its Manage access control. */
|
|
export function isProjectAccessLink(o: Pick<InternalObservation, "origin">, href: string, row: Entity) {
|
|
try {
|
|
const url = new URL(href, o.origin);
|
|
if (url.origin !== new URL(o.origin).origin) return false;
|
|
const parts = url.pathname.replace(/\/+$/, "").split("/").map(decodeURIComponent); const at = parts.indexOf("projects");
|
|
return at >= 0 && [row.id, row.urlKey].filter(Boolean).includes(parts[at + 1]) && parts[at + 2] === "configuration" && parts.length === at + 3;
|
|
} catch { return false; }
|
|
}
|
|
/** The key the app's projectRouteRef rewrites a project route to. */
|
|
export function projectRouteKey(project: Entity) {
|
|
const key = project.urlKey ?? deriveProjectUrlKey(project.name, project.id);
|
|
return key === normalizeProjectUrlKey(project.name) && hasNonAsciiContent(project.name) ? project.id : key;
|
|
}
|
|
export async function settleProjectRoute(page: Page, project: Entity, options: { timeout?: number } = {}) {
|
|
await settleRouteKey(page, "projects", projectRouteKey(project), options);
|
|
}
|
|
/**
|
|
* Opens Manage access's person picker, selects the named person and adds them. Opening the dialog focuses the
|
|
* picker, which opens its search panel by itself, so the picker is clicked only while that panel is closed (a second
|
|
* click would close it). A redraw can close the panel or detach its options mid-selection; the whole selection
|
|
* then retries, reopening the dialog if it closed, until the picker shows the person and Add is enabled.
|
|
*/
|
|
export async function addProjectAccessMember(page: Page, name: string, options: { timeout?: number } = {}) {
|
|
const manageAccess = page.getByRole("button", { name: "Manage access", exact: true });
|
|
const dialog = page.getByRole("dialog", { name: "Private project access", exact: true });
|
|
const picker = dialog.getByRole("combobox");
|
|
const pickerPanel = page.getByRole("dialog", { name: "Add a person or agent", exact: true });
|
|
const search = pickerPanel.getByPlaceholder("Search people and agents", { exact: true });
|
|
const add = dialog.getByRole("button", { name: "Add", exact: true });
|
|
await expect(async () => {
|
|
if (!await dialog.isVisible()) await manageAccess.click({ timeout: 2_000 });
|
|
await expect(dialog).toBeVisible({ timeout: 2_000 });
|
|
if (!await search.isVisible()) await picker.click({ timeout: 2_000 });
|
|
await expect(search).toBeVisible({ timeout: 2_000 });
|
|
await search.fill(name, { timeout: 2_000 });
|
|
await pickerPanel.getByRole("option", { name: new RegExp(`\\b${name}\\b`) }).first().click({ timeout: 2_000 });
|
|
await expect(picker).toContainText(name, { timeout: 2_000 });
|
|
await expect(add).toBeEnabled({ timeout: 2_000 });
|
|
}).toPass({ timeout: options.timeout ?? 45_000 });
|
|
await add.click();
|
|
}
|
|
export function gradeShareProject(value: unknown) {
|
|
const c = checks(); const base = observation(value); const o = base as ShareProjectObservation | undefined;
|
|
const before = o?.state.beforeShare as { project?: PrivateRecord; observerProjectStatus?: number; protectedTaskStatus?: number; agentMutationStatus?: number; leadReadStatus?: number;
|
|
members?: AccessMember[]; links?: string[] } | undefined;
|
|
const accessLink = o?.state.ownerAccessLink as { href?: string | null; opened?: boolean } | undefined;
|
|
c.add("complete-owner-sharing-evidence", !!o && !!before && Array.isArray(o.members) && Array.isArray(before?.members) && Array.isArray(before?.links),
|
|
"Sharing requires independent before/after access, the rendered handoff links and actual owner-action attribution.");
|
|
if (!o || !before || !Array.isArray(o.members) || !Array.isArray(before.members) || !Array.isArray(before.links)) return c.result();
|
|
const p = o.sharedProject;
|
|
const shared = entity(o.state, "project");
|
|
c.add("agent-respects-existing-audience", before.project?.visibility === "private" && [403, 404].includes(before.observerProjectStatus ?? 0)
|
|
&& before.leadReadStatus === 200 && before.agentMutationStatus === 403
|
|
&& !before.members.some(row => row.subjectType === "user" && row.subjectId === o.state.observerId)
|
|
&& !o.activity.some(row => row.entityId === shared.id && row.actorType !== "user" && (row.action === "project.access_member_added"
|
|
|| (row.action === "project.updated" && Array.isArray(row.details?.changedKeys) && (row.details.changedKeys as unknown[]).includes("visibility")))),
|
|
"The CEO can read the project but cannot grant its audience; saved membership and activity show no grant or audience change by an agent.");
|
|
c.add("owner-access-page-linked", !!accessLink?.opened && typeof accessLink.href === "string"
|
|
&& before.links.includes(accessLink.href) && isProjectAccessLink(o, accessLink.href, shared),
|
|
"The first reply renders a link to the project's access settings, and clicking it opens the Manage access control for the owner.");
|
|
c.add("owner-grants-only-riley", !!p && p.visibility === "private" && o.observerProjectStatus === 200
|
|
&& o.members.some(row => row.subjectType === "user" && row.subjectId === o.state.observerId)
|
|
&& o.activity.some(row => row.action === "project.access_member_added" && row.entityId === p.id
|
|
&& row.actorType === "user" && row.actorId === o.state.ownerId && row.details?.subjectId === o.state.observerId),
|
|
"A visible owner action grants the intended same-company Riley through project membership, without making the project public.");
|
|
c.add("separate-task-privacy-retained", [403, 404].includes(before.protectedTaskStatus ?? 0) && [403, 404].includes(o.observerProtectedTaskStatus)
|
|
&& o.tasks.some(row => row.id === entity(o.state, "protectedTask").id && (row as PrivateRecord).visibility === "private"),
|
|
"The separately protected task remains private and unreadable to Riley after project sharing.");
|
|
c.add("saved-project-link", !!p && hasLink(o, "projects", p), "The conversation identifies the exact project being shared.");
|
|
return c.result();
|
|
}
|
|
async function agentMutationStatus(ctx: ChatCatalogContext, path: string, data: unknown) {
|
|
const id = ctx.input.fixtures.agent.id;
|
|
const key = await privacyProbeKey(ctx, id);
|
|
const url = new URL(path, ctx.input.api.baseURL);
|
|
if (url.origin !== ctx.input.api.baseURL || !url.pathname.startsWith("/api/")) throw new Error("Privacy mutation probe escaped fixture API");
|
|
const response = await fetch(url, { method: "POST", redirect: "error", signal: AbortSignal.timeout(15_000),
|
|
headers: { Authorization: `Bearer ${key.token}`, "content-type": "application/json" }, body: JSON.stringify(data) });
|
|
await response.body?.cancel(); return response.status;
|
|
}
|
|
function shareProject(): ChatCatalogCase {
|
|
let observer: Person | undefined;
|
|
const base = makeDefinition("projects.share-project", async ctx => {
|
|
const ownerId = await mainPerson(ctx); observer = await observerPerson(ctx);
|
|
const p = await project(ctx, "Acquisition research", { visibility: "private", description: "Private acquisition research for the authorized owner." });
|
|
await ctx.input.api.post(`/api/projects/${p.id}/access-members`, { subjectType: "agent", subjectId: ctx.input.fixtures.agent.id });
|
|
const protectedTask = await ctx.input.api.post<Entity>(`/api/companies/${ctx.input.fixtures.company.id}/issues`, {
|
|
title: "Separately protected acquisition note", description: `Independent protected task ${ctx.input.nonce}`, visibility: "private", status: "backlog",
|
|
});
|
|
return { project: p, ownerId, observerId: observer.id, protectedTask };
|
|
}, gradeShareProject);
|
|
return { ...base, authentication: "human-session", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"],
|
|
async act(ctx, state) {
|
|
if (!observer) throw new Error("Missing independent observer");
|
|
const first = await pollUntil({ label: "Existing private-project owner handoff", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000),
|
|
load: () => observeInternal(ctx, state), accept: o => chatCatalogNativePhaseIsTimely(ctx) && o.runs.length === 1 && o.runs.every(row => row.status === "succeeded")
|
|
&& ctx.issue()?.conversationState === "waiting" });
|
|
const p = entity(state, "project"); const protectedTask = entity(state, "protectedTask");
|
|
const leadReadStatus = await agentStatus(ctx, first.leadId, `/api/projects/${p.id}`);
|
|
const agentMutation = await agentMutationStatus(ctx, `/api/projects/${p.id}/access-members`, { subjectType: "user", subjectId: observer.id });
|
|
state.beforeShare = { project: first.projects.find(row => row.id === p.id), reply: first.reply, leadReadStatus, agentMutationStatus: agentMutation,
|
|
observerProjectStatus: (await personRead(observer, `/api/projects/${p.id}`)).status,
|
|
protectedTaskStatus: (await personRead(observer, `/api/issues/${protectedTask.id}`)).status };
|
|
await ctx.input.evidence("chat-catalog-before-owner-project-sharing.json", state.beforeShare);
|
|
if (agentMutation !== 403 || ![403, 404].includes((state.beforeShare as { observerProjectStatus: number }).observerProjectStatus))
|
|
throw new Error("Private-project audience changed without the authorized human control");
|
|
// The reply can settle before its links render in the thread; wait briefly for them.
|
|
const linked = await pollUntil({ label: "Owner handoff project access link rendered", deadlineAt: Date.now() + 20_000,
|
|
load: () => observeInternal(ctx, state), accept: o => o.links.some(link => isProjectAccessLink(o, link, p)) }).catch(() => first);
|
|
const accessHref = linked.links.find(link => isProjectAccessLink(linked, link, p)) ?? null;
|
|
const href = accessHref ?? linked.links.find(link => hasLink({ ...linked, links: [link] }, "projects", p));
|
|
if (!href) throw new Error("Owner handoff omitted the actual project link");
|
|
(state.beforeShare as Record<string, unknown>).members = await ctx.input.api.get<AccessMember[]>(`/api/projects/${p.id}/access-members`);
|
|
(state.beforeShare as Record<string, unknown>).links = linked.links;
|
|
const sourceUrl = ctx.input.page.url();
|
|
await internalResultLink(ctx, linked, href).first().click();
|
|
const manageAccess = ctx.input.page.getByRole("button", { name: "Manage access", exact: true });
|
|
// The app rewrites /projects/<id>/… to /projects/<urlKey>/… and redraws, which closes an open access dialog.
|
|
await settleProjectRoute(ctx.input.page, p);
|
|
if (accessHref) {
|
|
await ctx.input.page.waitForURL(url => isProjectAccessLink(linked, url.href, p));
|
|
await expect(manageAccess).toBeVisible();
|
|
} else {
|
|
// Without an access-settings link the grade fails; still complete the owner step so later phases keep their evidence.
|
|
await ctx.input.page.getByText("Configuration", { exact: true }).last().click();
|
|
}
|
|
state.ownerAccessLink = { href: accessHref, opened: !!accessHref };
|
|
await ctx.input.evidence("chat-catalog-owner-project-access-link.json", { ...(state.ownerAccessLink as object), url: ctx.input.page.url() });
|
|
await manageAccess.click();
|
|
await addProjectAccessMember(ctx.input.page, "Riley");
|
|
await pollUntil({ label: "Owner-added Riley project membership", deadlineAt: Date.now() + 30_000,
|
|
load: () => ctx.input.api.get<AccessMember[]>(`/api/projects/${p.id}/access-members`),
|
|
accept: rows => rows.some(row => row.subjectType === "user" && row.subjectId === observer!.id) });
|
|
await ctx.input.page.goto(sourceUrl, { waitUntil: "domcontentloaded" });
|
|
await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
},
|
|
async observe(ctx, state): Promise<ShareProjectObservation> {
|
|
if (!observer) throw new Error("Missing independent observer");
|
|
const o = await observeInternal(ctx, state); const p = entity(state, "project");
|
|
const [members, projectRead, taskRead] = await Promise.all([
|
|
ctx.input.api.get<AccessMember[]>(`/api/projects/${p.id}/access-members`), personRead(observer, `/api/projects/${p.id}`),
|
|
personRead(observer, `/api/issues/${entity(state, "protectedTask").id}`),
|
|
]);
|
|
return { ...o, sharedProject: o.projects.find(row => row.id === p.id) as PrivateRecord ?? null, members,
|
|
observerProjectStatus: projectRead.status, observerProtectedTaskStatus: taskRead.status };
|
|
},
|
|
async verifyResult(ctx, state, value) {
|
|
await base.verifyResult(ctx, state, value);
|
|
if (!observer) throw new Error("Missing independent browser observer");
|
|
const p = entity(state, "project"); const observerPage = await observer.context.newPage();
|
|
try {
|
|
await observerPage.goto(new URL(`/${ctx.input.fixtures.company.issuePrefix}/projects/${p.id}`, ctx.input.api.baseURL).href, { waitUntil: "domcontentloaded" });
|
|
await expect(observerPage.getByRole("heading", { name: p.name!, exact: true }).first()).toBeVisible();
|
|
await ctx.input.evidence("chat-catalog-owner-project-sharing-opened.json", { observerId: observer.id, projectId: p.id, url: observerPage.url(), visible: true });
|
|
} finally { await observerPage.close(); }
|
|
},
|
|
async cleanup(ctx) { try { await cleanupPrivacyProbes(ctx); } finally { await observer?.dispose(); observer = undefined; } },
|
|
};
|
|
}
|
|
|
|
interface TaskSharingObservation extends InternalObservation {
|
|
members: AccessMember[]; taskReadStatus: number; observerTaskStatus: number; observerCompanyStatus: number; agentGrantStatus: number;
|
|
}
|
|
export function gradeTaskSharing(value: unknown) {
|
|
const c = checks(); const o = observation(value) as TaskSharingObservation | undefined;
|
|
c.add("independent-task-audience-evidence", !!o && Array.isArray(o.members) && typeof o.agentGrantStatus === "number", "Saved task membership and independent human and agent access probes are required.");
|
|
if (!o || !Array.isArray(o.members)) return c.result();
|
|
const before = entity(o.state, "task"); const current = o.tasks.find(row => row.id === before.id) as PrivateRecord | undefined;
|
|
c.add("read-is-not-sharing-authority", o.taskReadStatus === 200 && o.agentGrantStatus === 403 && o.observerCompanyStatus === 200
|
|
&& [403, 404].includes(o.observerTaskStatus), "The CEO can read but cannot grant access; the healthy enrolled Riley remains denied the copied private-task ID.");
|
|
c.add("audience-preserved", !!current && current.visibility === "private" && sameTask(before, current)
|
|
&& !o.members.some(row => row.subjectType === "user" && (row.subjectId === o.state.observerId || (row.source !== "owner" && row.subjectId !== o.state.ownerId)))
|
|
&& !o.activity.some(row => row.entityId === before.id && /access_member_added|access_grant|visibility/.test(row.action ?? "") && row.agentId === o.leadId),
|
|
"Neither a grant to Riley or any other person nor public visibility is fabricated through ordinary agent mutation.");
|
|
c.add("exact-human-sharing-handoff", hasLink(o, "issues", before),
|
|
"The reply links the actual named private task, whose page holds its owner's sharing control.");
|
|
return c.result();
|
|
}
|
|
function sharePrivateTask(): ChatCatalogCase {
|
|
let observer: Person | undefined;
|
|
const base = makeDefinition("tasks.share-private-task", async ctx => {
|
|
const ownerId = await mainPerson(ctx); observer = await observerPerson(ctx);
|
|
const p = await project(ctx, "Launch");
|
|
const t = await task(ctx, "Private launch task", p.id, { visibility: "private", description: "Private launch work; only its owner may change its audience." });
|
|
await ctx.input.api.post(`/api/issues/${t.id}/access-grants`, { subjectType: "agent", subjectId: ctx.input.fixtures.agent.id });
|
|
return { project: p, task: t, ownerId, observerId: observer.id };
|
|
}, gradeTaskSharing);
|
|
return { ...base, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.share-private-task.v2", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"],
|
|
async observe(ctx, state): Promise<TaskSharingObservation> {
|
|
if (!observer) throw new Error("Missing actual Riley observer");
|
|
const o = await observeInternal(ctx, state); const t = entity(state, "task");
|
|
const [members, observerRead, observerCompany, taskReadStatus, agentGrantStatus] = await Promise.all([
|
|
ctx.input.api.get<AccessMember[]>(`/api/issues/${t.id}/access-grants`), personRead(observer, `/api/issues/${t.id}`),
|
|
personRead(observer, `/api/companies/${ctx.input.fixtures.company.id}`), agentStatus(ctx, o.leadId, `/api/issues/${t.id}`),
|
|
agentMutationStatus(ctx, `/api/issues/${t.id}/access-grants`, { subjectType: "user", subjectId: observer.id }),
|
|
]);
|
|
return { ...o, members, observerTaskStatus: observerRead.status, observerCompanyStatus: observerCompany.status, taskReadStatus, agentGrantStatus };
|
|
},
|
|
async verifyResult(ctx, state, value) {
|
|
await base.verifyResult(ctx, state, value);
|
|
if (!observer) throw new Error("Missing actual Riley browser");
|
|
const t = entity(state, "task"); const o = observation(value)!;
|
|
const href = o.links.find(link => hasLink({ ...o, links: [link] }, "issues", t));
|
|
if (!href) throw new Error("Owner handoff omitted the actual private task link");
|
|
const sourceUrl = ctx.input.page.url();
|
|
await internalResultLink(ctx, o, href).first().click();
|
|
await expect(ctx.input.page.getByRole("heading", { name: t.title!, exact: true }).first()).toBeVisible();
|
|
await ctx.input.page.getByRole("button", { name: "More task actions", exact: true }).click();
|
|
const share = ctx.input.page.getByRole("button", { name: "Share…", exact: true });
|
|
await expect(share).toBeEnabled();
|
|
await share.click();
|
|
await expect(ctx.input.page.getByRole("dialog", { name: "Who can access this task", exact: true })).toBeVisible();
|
|
await ctx.input.evidence("chat-catalog-owner-task-share-control.json", { taskId: t.id, url: ctx.input.page.url(), shareControlOpened: true });
|
|
await ctx.input.page.keyboard.press("Escape");
|
|
await ctx.input.page.goto(sourceUrl, { waitUntil: "domcontentloaded" });
|
|
await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
const page = await observer.context.newPage();
|
|
try {
|
|
await page.goto(new URL(`/${ctx.input.fixtures.company.issuePrefix}/issues/${t.id}`, ctx.input.api.baseURL).href, { waitUntil: "domcontentloaded" });
|
|
await expect(page.getByText(/not found|access denied|forbidden|unable to load|could not load/i).first()).toBeVisible();
|
|
await expect(page.getByRole("heading", { name: t.title!, exact: true })).toHaveCount(0);
|
|
await ctx.input.evidence("chat-catalog-task-sharing-denied-browser.json", { taskId: t.id, observerId: observer.id, denied: true });
|
|
} finally { await page.close(); }
|
|
},
|
|
async cleanup(ctx) { try { await cleanupPrivacyProbes(ctx); } finally { await observer?.dispose(); observer = undefined; } },
|
|
};
|
|
}
|
|
export const taskPrivacyCases: readonly ChatCatalogCase[] = [sharePrivateTask()];
|