The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(issues): explain cross-task agent writes with attribution, audit receipts, and actionable denials (#10843)
Dottae8ae5286eb92
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 6d9f1eb77b..6695377594 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -81,6 +81,18 @@ export {type ResponsibleUserSource,type OriginatingActor,} from "./issue-attribution.js";+export {+ ISSUE_WRITE_DENIAL_CODES,+ describeIssueWriteDenial,+ isIssueWriteDenialCode,+ issueWriteDenialApiMessage,+ issueWriteDenialCodeForResponsibleUserDenial,+ issueWriteDenialResponse,+ type IssueWriteDenialCode,+ type IssueWriteDenialContext,+ type IssueWriteDenialCopy,+ type IssueWriteDenialTone,+} from "./issue-write-denial.js";export {RESPONSIBLE_USER_DENIAL_CODES,describeResponsibleUserDenial,diff --git a/packages/shared/src/issue-write-denial.test.ts b/packages/shared/src/issue-write-denial.test.tsnew file mode 100644index 0000000000..2cf4d4977f--- /dev/null+++ b/packages/shared/src/issue-write-denial.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from "vitest";++import {+ ISSUE_WRITE_DENIAL_CODES,+ describeIssueWriteDenial,+ isIssueWriteDenialCode,+ issueWriteDenialApiMessage,+ issueWriteDenialCodeForResponsibleUserDenial,+ issueWriteDenialResponse,+} from "./issue-write-denial.js";++describe("describeIssueWriteDenial", () => {+ it("answers all three plan §6 obligations for every code", () => {+ for (const code of ISSUE_WRITE_DENIAL_CODES) {+ const copy = describeIssueWriteDenial(code);+ expect(copy.code, code).toBe(code);+ // Boundary that fired, who can act, sanctioned path — none may be empty.+ expect(copy.boundary.trim().length, code).toBeGreaterThan(0);+ expect(copy.whoCanAct.trim().length, code).toBeGreaterThan(0);+ expect(copy.sanctionedPath.trim().length, code).toBeGreaterThan(0);+ expect(copy.title.trim().length, code).toBeGreaterThan(0);+ expect(copy.description.trim().length, code).toBeGreaterThan(0);+ }+ });++ it("never leaks a raw id or placeholder when labels are unknown", () => {+ for (const code of ISSUE_WRITE_DENIAL_CODES) {+ const copy = describeIssueWriteDenial(code);+ const prose = `${copy.description} ${copy.whoCanAct} ${copy.sanctionedPath}`;+ expect(prose, code).not.toMatch(/undefined|null/);+ // Unknown labels degrade to generic nouns, never a bare id.+ expect(prose, code).toMatch(/this task|this agent|the current assignee|the responsible user/);+ }+ });++ it("keeps the boundary free of parentheses and distinct from the title", () => {+ for (const code of ISSUE_WRITE_DENIAL_CODES) {+ const copy = describeIssueWriteDenial(code, { cap: 20 });+ // Surfaces render the boundary inside their own parens — nesting stutters.+ expect(copy.boundary, code).not.toMatch(/[()]/);+ // A title echoed verbatim as its own boundary reads as a mistake.+ expect(copy.boundary.toLowerCase(), code).not.toBe(copy.title.toLowerCase());+ }+ });++ it("names the actor, assignee, and task when they are known", () => {+ const copy = describeIssueWriteDenial("issue_write_not_visible", {+ actorLabel: "Fable",+ assigneeLabel: "CodexCoder",+ issueIdentifier: "TASK-482",+ });+ expect(copy.description).toContain("TASK-482");+ expect(copy.description).toContain("Fable");+ expect(copy.whoCanAct).toContain("CodexCoder");+ });++ it("points a visibility denial at the sanctioned child-issue path", () => {+ const copy = describeIssueWriteDenial("issue_write_not_visible");+ // The incident detour was discovering exactly this workaround.+ expect(copy.sanctionedPath).toContain("child issue");+ });++ it("frames the per-run cap as a rate backstop, not a permission decision", () => {+ const copy = describeIssueWriteDenial("cross_issue_influence_cap_exceeded", {+ cap: 20,+ count: 21,+ actorLabel: "Fable",+ });+ expect(copy.status).toBe(429);+ expect(copy.tone).toBe("cap");+ expect(copy.boundary).toContain("20");+ expect(copy.description).toContain("attempt 21");+ expect(copy.description).toContain("still allowed");+ expect(copy.sanctionedPath).toContain("next heartbeat");+ });++ it("defaults the cap to the shipped limit when context omits it", () => {+ const copy = describeIssueWriteDenial("cross_issue_influence_cap_exceeded");+ expect(copy.boundary).toContain("20");+ expect(copy.description).not.toContain("attempt");+ });++ it("gives the run-context denial a copy-pasteable fix", () => {+ const copy = describeIssueWriteDenial("cross_issue_influence_run_context_required");+ expect(copy.sanctionedPath).toContain("X-Paperclip-Run-Id");+ expect(copy.sanctionedPath).toContain("PAPERCLIP_RUN_ID");+ });++ it("tells a spoof attempt that the write itself was fine", () => {+ const copy = describeIssueWriteDenial("issue_write_attribution_spoof_rejected", {+ actorLabel: "Fable",+ responsibleUserName: "Dotta",+ });+ expect(copy.status).toBe(422);+ expect(copy.whoCanAct).toContain("Fable");+ expect(copy.sanctionedPath).toContain("Dotta");+ expect(copy.sanctionedPath).toContain("onBehalfOfUserId");+ });++ it("routes a run lock to comments, which stay open", () => {+ const copy = describeIssueWriteDenial("issue_write_assignee_run_lock", {+ assigneeLabel: "CodexCoder",+ });+ expect(copy.status).toBe(409);+ expect(copy.tone).toBe("lock");+ expect(copy.sanctionedPath).toContain("Comment instead");+ expect(copy.sanctionedPath).toContain("CodexCoder");+ });++ it("reuses responsible-user ceiling copy and keeps on-behalf-of terminology", () => {+ const ceiling = describeIssueWriteDenial("issue_write_responsible_user_ceiling", {+ responsibleUserName: "Dotta",+ issueIdentifier: "TASK-517",+ });+ expect(ceiling.title).toBe("Responsible user not authorized");+ expect(ceiling.description).toContain("on behalf");+ expect(ceiling.description).toContain("TASK-517");+ expect(ceiling.description).not.toContain("impersonat");+ expect(ceiling.whoCanAct).toContain("Dotta");++ const unavailable = describeIssueWriteDenial("issue_write_responsible_user_unavailable", {+ responsibleUserName: "Dotta",+ });+ expect(unavailable.title).toBe("Responsible user unavailable");+ expect(unavailable.sanctionedPath).toContain("blocked");+ });++ it("falls back to generic phrasing when the responsible user is unknown", () => {+ const copy = describeIssueWriteDenial("issue_write_responsible_user_ceiling");+ expect(copy.description).toContain("the responsible user");+ });+});++describe("issueWriteDenialCodeForResponsibleUserDenial", () => {+ it("bridges both authorization-layer ceiling codes", () => {+ expect(issueWriteDenialCodeForResponsibleUserDenial("RESPONSIBLE_USER_UNAUTHORIZED"))+ .toBe("issue_write_responsible_user_ceiling");+ expect(issueWriteDenialCodeForResponsibleUserDenial("RESPONSIBLE_USER_UNAVAILABLE"))+ .toBe("issue_write_responsible_user_unavailable");+ });+});++describe("isIssueWriteDenialCode", () => {+ it("accepts shipped codes and rejects everything else", () => {+ expect(isIssueWriteDenialCode("issue_write_not_visible")).toBe(true);+ expect(isIssueWriteDenialCode("RESPONSIBLE_USER_UNAUTHORIZED")).toBe(false);+ expect(isIssueWriteDenialCode(null)).toBe(false);+ expect(isIssueWriteDenialCode(undefined)).toBe(false);+ expect(isIssueWriteDenialCode("")).toBe(false);+ });+});++describe("issueWriteDenialApiMessage", () => {+ it("keeps boundary, who-can-act, and sanctioned path in the flattened error", () => {+ const copy = describeIssueWriteDenial("issue_write_not_visible", {+ actorLabel: "Fable",+ issueIdentifier: "TASK-482",+ });+ const message = issueWriteDenialApiMessage(copy);+ expect(message).toContain(copy.boundary);+ expect(message).toContain("Who can act:");+ expect(message).toContain("Try this:");+ expect(message).toContain(copy.sanctionedPath);+ });+});++describe("issueWriteDenialResponse", () => {+ it("pairs the status with a machine-readable details payload", () => {+ const { status, body } = issueWriteDenialResponse("cross_issue_influence_cap_exceeded", {+ cap: 20,+ count: 21,+ });+ expect(status).toBe(429);+ expect(body.details.code).toBe("cross_issue_influence_cap_exceeded");+ expect(body.details.boundary).toContain("20");+ expect(body.error).toContain("Who can act:");+ });++ it("uses the status each code declares", () => {+ expect(issueWriteDenialResponse("issue_write_assignee_run_lock").status).toBe(409);+ expect(issueWriteDenialResponse("issue_write_attribution_spoof_rejected").status).toBe(422);+ expect(issueWriteDenialResponse("issue_write_not_visible").status).toBe(403);+ });+});diff --git a/packages/shared/src/issue-write-denial.ts b/packages/shared/src/issue-write-denial.tsnew file mode 100644index 0000000000..737bab7bd7--- /dev/null+++ b/packages/shared/src/issue-write-denial.ts@@ -0,0 +1,333 @@+/**+ * Copy contract for denied issue writes (open cross-task writes: failure UX).+ *+ * Cross-issue issue writes are default-open for standard-trust agents on issues+ * they can already read (see SPEC-implementation §9.3). The remaining walls are+ * rare — but a real incident burned a full detour discovering a workaround+ * behind an opaque 403, so every one of them must say three things:+ *+ * 1. which boundary fired,+ * 2. who *can* act,+ * 3. the sanctioned path forward.+ *+ * This module is the single source of truth for that copy, so the API error+ * body an agent reads and the notice a human sees in the UI are the same words.+ * It is the issue-write sibling of `responsible-user-denial.ts`: the two+ * responsible-user ceiling codes delegate to that module's copy so terminology+ * ("on behalf of {user}", never "impersonate") stays consistent.+ */++import {+ describeResponsibleUserDenial,+ responsibleUserLabel,+ type ResponsibleUserDenialCode,+} from "./responsible-user-denial.js";++export const ISSUE_WRITE_DENIAL_CODES = [+ "issue_write_not_visible",+ "issue_write_actor_class_excluded",+ "issue_write_responsible_user_ceiling",+ "issue_write_responsible_user_unavailable",+ "issue_write_assignee_run_lock",+ "cross_issue_influence_cap_exceeded",+ "cross_issue_influence_run_context_required",+ "issue_write_attribution_spoof_rejected",+] as const;++export type IssueWriteDenialCode = (typeof ISSUE_WRITE_DENIAL_CODES)[number];++/**+ * Why the write stopped, which drives icon + colour. `boundary` is an+ * authorization wall, `lock` is run-lifecycle machinery that will clear on its+ * own, `cap` is a rate backstop, and `attribution` is a rejected spoof.+ */+export type IssueWriteDenialTone = "boundary" | "lock" | "cap" | "attribution";++export interface IssueWriteDenialCopy {+ code: IssueWriteDenialCode;+ /** HTTP status the server pairs with this code. */+ status: 403 | 409 | 422 | 429;+ tone: IssueWriteDenialTone;+ /** The boundary that fired, as a short noun phrase for a banner title. */+ boundary: string;+ /** Short heading. */+ title: string;+ /** What happened and why, in one or two sentences. */+ description: string;+ /** Who is able to perform this write instead. */+ whoCanAct: string;+ /** The supported way to get the work moving. */+ sanctionedPath: string;+}++export interface IssueWriteDenialContext {+ /** Display name of the agent or user that attempted the write. */+ actorLabel?: string | null;+ /** Display name of the responsible ("on behalf of") user for the attempt. */+ responsibleUserName?: string | null;+ /** Display name of the target issue's current assignee. */+ assigneeLabel?: string | null;+ /** Target issue identifier, e.g. `TASK-482`. */+ issueIdentifier?: string | null;+ /** Per-run cross-issue influence cap. */+ cap?: number | null;+ /** Attempt count that tripped the cap. */+ count?: number | null;+ /** ISO timestamp at which log-only rollout becomes enforcement. */+ enforceAt?: string | null;+}++export function isIssueWriteDenialCode(+ code: string | null | undefined,+): code is IssueWriteDenialCode {+ return ISSUE_WRITE_DENIAL_CODES.includes(code as IssueWriteDenialCode);+}++/**+ * Bridge the two responsible-user ceiling codes emitted by the authorization+ * layer into this module's code space, so a single UI notice covers every way+ * an issue write can be refused.+ */+export function issueWriteDenialCodeForResponsibleUserDenial(+ code: ResponsibleUserDenialCode,+): IssueWriteDenialCode {+ return code === "RESPONSIBLE_USER_UNAVAILABLE"+ ? "issue_write_responsible_user_unavailable"+ : "issue_write_responsible_user_ceiling";+}++/** "this task" when the identifier is unknown, so copy never shows a raw id. */+function issueLabel(identifier: string | null | undefined): string {+ const trimmed = identifier?.trim();+ return trimmed && trimmed.length > 0 ? trimmed : "this task";+}++/** "the assignee" when the name is unknown. */+function assigneeLabel(name: string | null | undefined): string {+ const trimmed = name?.trim();+ return trimmed && trimmed.length > 0 ? trimmed : "the current assignee";+}++/** "this agent" when the name is unknown. */+function actorLabel(name: string | null | undefined): string {+ const trimmed = name?.trim();+ return trimmed && trimmed.length > 0 ? trimmed : "this agent";+}++/**+ * The escape hatch an earlier incident had to discover by trial and error. Naming it in+ * every boundary denial is the point of plan §6 — an agent that reads the error+ * should not need a detour to find the supported path.+ */+const CHILD_ISSUE_PATH =+ "create a child issue with the request in its description (issue creation is a " ++ "separate, open write path) and let its assignee act";++export function describeIssueWriteDenial(+ code: IssueWriteDenialCode,+ context: IssueWriteDenialContext = {},+): IssueWriteDenialCopy {+ const issue = issueLabel(context.issueIdentifier);+ const actor = actorLabel(context.actorLabel);+ const assignee = assigneeLabel(context.assigneeLabel);+ const responsible = responsibleUserLabel(context.responsibleUserName);++ switch (code) {+ case "issue_write_not_visible":+ return {+ code,+ status: 403,+ tone: "boundary",+ boundary: "Issue visibility",+ title: "Task is outside this actor's visibility",+ description:+ `Issue writes are open by default, but only for tasks the actor can already ` ++ `read. ${issue} is not visible to ${actor}, so its comment, update, child, and ` ++ `assignment channels are all closed — the wall is visibility, not the write itself.`,+ whoCanAct:+ `${assignee}, and any agent or board member the task is visible to.`,+ sanctionedPath:+ `Ask the board to widen visibility for ${actor}, or ${CHILD_ISSUE_PATH}.`,+ };++ case "issue_write_actor_class_excluded":+ return {+ code,+ status: 403,+ tone: "boundary",+ boundary: "Actor-class boundary",+ title: "This actor class cannot write to tasks",+ description:+ `Default-open issue writes are a standard-trust privilege. Low-trust, ` ++ `skill-test, and task-bridge scopes keep their existing tight walls, so ` ++ `${actor} cannot write to ${issue} no matter who it acts for.`,+ whoCanAct:+ `A standard-trust agent in this company, or a board member.`,+ sanctionedPath:+ `Report the request upward and let a standard-trust agent make the write — ` ++ `actor-class scope cannot be widened per task.`,+ };++ case "issue_write_responsible_user_ceiling": {+ const ceiling = describeResponsibleUserDenial("RESPONSIBLE_USER_UNAUTHORIZED", {+ userName: context.responsibleUserName,+ });+ return {+ code,+ status: 403,+ tone: "boundary",+ boundary: "Responsible-user ceiling",+ title: ceiling.title,+ description: `${ceiling.description} The write to ${issue} was refused for that reason.`,+ whoCanAct:+ `${responsible} once authorized, or anyone already permitted to write to ${issue}.`,+ sanctionedPath: ceiling.recommendedAction,+ };+ }++ case "issue_write_responsible_user_unavailable": {+ const unavailable = describeResponsibleUserDenial("RESPONSIBLE_USER_UNAVAILABLE", {+ userName: context.responsibleUserName,+ });+ return {+ code,+ status: 403,+ tone: "boundary",+ // Distinct from the title, which already says "unavailable" — the+ // boundary names the *mechanism*, so the two do not read as a stutter.+ boundary: "Responsible-user availability",+ title: unavailable.title,+ description: `${unavailable.description} The write to ${issue} was refused for that reason.`,+ whoCanAct: `A board member, or ${actor} once it has an active responsible user.`,+ sanctionedPath: unavailable.recommendedAction,+ };+ }++ case "issue_write_assignee_run_lock":+ return {+ code,+ status: 409,+ tone: "lock",+ boundary: "Run checkout lock",+ title: "Another agent's run owns this task",+ description:+ `${assignee} has ${issue} checked out and a run is live. Checkout and run ` ++ `ownership stay assignee-scoped even though writes are open, so field edits ` ++ `belong to the run that holds the lock until it finishes.`,+ whoCanAct:+ `${assignee}'s live run, or an agent holding the manage-active-checkouts permission.`,+ sanctionedPath:+ `Comment instead of patching — comments stay open and wake ${assignee} — or ` ++ `wait for the run to release the lock and retry.`,+ };++ case "cross_issue_influence_cap_exceeded": {+ const cap = context.cap ?? 20;+ const attempt = context.count ?? null;+ return {+ code,+ status: 429,+ tone: "cap",+ // No parentheses: surfaces render the boundary inside their own parens.+ boundary: `Per-run cross-issue cap of ${cap} writes`,+ title: "This run has spent its cross-issue write budget",+ description:+ `A single heartbeat run may make at most ${cap} cross-issue comments or task ` ++ `updates combined${attempt !== null ? `; this was attempt ${attempt}` : ""}. The cap ` ++ `bounds runaway comment sprays and loops — it is a rate backstop, not a ` ++ `permission decision, so ${actor} is still allowed to write to ${issue}.`,+ whoCanAct:+ `${actor} on its next heartbeat run, or ${assignee} on ${issue} directly.`,+ sanctionedPath:+ `Consolidate what is left into one comment on your own task, or end the run and ` ++ `continue on the next heartbeat — the budget resets per run.`,+ };+ }++ case "cross_issue_influence_run_context_required":+ return {+ code,+ status: 403,+ tone: "boundary",+ boundary: "Heartbeat run context",+ title: "Cross-issue writes need a run to attribute them to",+ description:+ `Every agent comment and task update is attributed to a heartbeat run so the ` ++ `cross-issue cap can be counted and the audit trail can name who acted for whom. ` ++ `This request arrived without a valid run, so it could not be contained.`,+ whoCanAct: `${actor}, once the request carries its own run id.`,+ sanctionedPath:+ `Send the \`X-Paperclip-Run-Id\` header with your current run (\`$PAPERCLIP_RUN_ID\`) ` ++ `and retry.`,++ };++ case "issue_write_attribution_spoof_rejected":+ return {+ code,+ status: 422,+ tone: "attribution",+ boundary: "Server-derived attribution",+ title: "Responsible user cannot be chosen by the caller",+ description:+ `\`onBehalfOfUserId\` is derived from the authenticated actor, never from the ` ++ `request body — an agent cannot pick the human whose authority it rides. The ` ++ `attempt was recorded in the audit log.`,+ whoCanAct:+ `${actor} itself: the write is allowed, only the chosen attribution is not.`,+ sanctionedPath:+ `Remove \`onBehalfOfUserId\` from the request and retry; the server fills in ` ++ `${responsible} from your run.`,+ };+ }+}++/**+ * Flatten a denial into the single `error` string an API client sees.+ *+ * Agents typically surface only `error`, so all three §6 obligations — boundary,+ * who can act, sanctioned path — have to survive the flattening.+ */+export function issueWriteDenialApiMessage(copy: IssueWriteDenialCopy): string {+ return [+ `${copy.title} (${copy.boundary}).`,+ copy.description,+ `Who can act: ${copy.whoCanAct}`,+ `Try this: ${copy.sanctionedPath}`,+ ].join(" ");+}++/**+ * Build the full `{ error, details }` body for a denied issue write. Keeping the+ * machine-readable `code` next to the prose lets the board UI render the same+ * copy without parsing sentences.+ */+export function issueWriteDenialResponse(+ code: IssueWriteDenialCode,+ context: IssueWriteDenialContext = {},+): {+ status: IssueWriteDenialCopy["status"];+ body: {+ error: string;+ details: {+ code: IssueWriteDenialCode;+ boundary: string;+ whoCanAct: string;+ sanctionedPath: string;+ } & Record<string, unknown>;+ };+} {+ const copy = describeIssueWriteDenial(code, context);+ return {+ status: copy.status,+ body: {+ error: issueWriteDenialApiMessage(copy),+ details: {+ code: copy.code,+ boundary: copy.boundary,+ whoCanAct: copy.whoCanAct,+ sanctionedPath: copy.sanctionedPath,+ },+ },+ };+}diff --git a/server/src/__tests__/cross-issue-influence-limit.test.ts b/server/src/__tests__/cross-issue-influence-limit.test.tsindex 801239a075..e6e42533f8 100644--- a/server/src/__tests__/cross-issue-influence-limit.test.ts+++ b/server/src/__tests__/cross-issue-influence-limit.test.ts@@ -86,16 +86,24 @@ describe("cross-issue influence limit rollout", () => {count: 21,cap: 20,});- expect(crossIssueInfluenceLimitError(rejected)).toEqual({- error: "Cross-issue influence cap exceeded: this run is limited to 20 cross-issue comments or updates",- details: {- code: "cross_issue_influence_cap_exceeded",- cap: 20,- count: 21,- mode: "enforce",- enforceAt: CROSS_ISSUE_INFLUENCE_ENFORCE_AT.toISOString(),- },+ const capError = crossIssueInfluenceLimitError(rejected, {+ actorLabel: "Fable",+ issueIdentifier: "TASK-482",+ });+ expect(capError.details).toMatchObject({+ code: "cross_issue_influence_cap_exceeded",+ cap: 20,+ count: 21,+ mode: "enforce",+ enforceAt: CROSS_ISSUE_INFLUENCE_ENFORCE_AT.toISOString(),});+ // Plan §6: the 429 names the boundary, who can act, and the way forward.+ expect(capError.error).toContain("20");+ expect(capError.error).toContain("Who can act:");+ expect(capError.error).toContain("Try this:");+ expect(capError.error).toContain("next heartbeat");+ expect(capError.details.boundary).toContain("20");+ expect(capError.details.whoCanAct).toContain("Fable");});it("uses one durable counter for cross-issue comments and PATCH updates", async () => {diff --git a/server/src/__tests__/external-object-routes.test.ts b/server/src/__tests__/external-object-routes.test.tsindex 14b142b7df..e27357b043 100644--- a/server/src/__tests__/external-object-routes.test.ts+++ b/server/src/__tests__/external-object-routes.test.ts@@ -273,7 +273,7 @@ describe("external object routes", () => {.send({});expect(res.status).toBe(409);- expect(res.body.error).toBe("Issue is checked out by another agent");+ expect(res.body.details.code).toBe("issue_write_assignee_run_lock");expect(mockExternalObjectsService.refreshIssueObjects).not.toHaveBeenCalled();});diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.tsindex 7798b5e844..a2c3e5d69c 100644--- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts+++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts@@ -783,7 +783,11 @@ describe("agent issue mutation checkout ownership", () => {const res = await sendRequest(await createApp(peerActor()));expect(res.status, JSON.stringify(res.body)).toBe(409);- expect(res.body.error).toBe("Issue is checked out by another agent");+ // Plan §6: the run lock names the boundary and routes to the open channel.+ expect(res.body.details.code).toBe("issue_write_assignee_run_lock");+ expect(res.body.details.boundary).toBe("Run checkout lock");+ expect(res.body.error).toContain("Who can act:");+ expect(res.body.error).toContain("Comment instead");expect(mockIssueService.assertCheckoutOwner).not.toHaveBeenCalled();expect(mockIssueService.update).not.toHaveBeenCalled();expect(mockIssueService.addComment).not.toHaveBeenCalled();diff --git a/server/src/__tests__/issue-comment-attribution-audit-routes.test.ts b/server/src/__tests__/issue-comment-attribution-audit-routes.test.tsindex 493c7e862a..36d17da5c5 100644--- a/server/src/__tests__/issue-comment-attribution-audit-routes.test.ts+++ b/server/src/__tests__/issue-comment-attribution-audit-routes.test.ts@@ -254,6 +254,10 @@ describeEmbeddedPostgres("issue comment attribution and patch audit routes", ().send({ body: "Spoof attempt", onBehalfOfUserId: "someone-else" });expect(response.status).toBe(422);+ // Plan §6: the refusal says the write itself was fine and names the fix.+ expect(response.body.details.code).toBe("issue_write_attribution_spoof_rejected");+ expect(response.body.details.sanctionedPath).toContain("onBehalfOfUserId");+ expect(response.body.error).toContain("Who can act:");expect(await db.select().from(issueComments)).toHaveLength(0);const event = await db.select()diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.tsindex e2d4cb7ad6..981548bea8 100644--- a/server/src/__tests__/issue-comment-reopen-routes.test.ts+++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts@@ -682,7 +682,11 @@ describe.sequential("issue comment reopen routes", () => {.send({ body: "Please continue this closed issue.", ...intent });expect(res.status, JSON.stringify(res.body)).toBe(403);- expect(res.body).toEqual({ error: "Issue is outside this actor's authorization boundary" });+ expect(res.body.details.code).toBe("issue_write_not_visible");+ // Plan §6: name the boundary, who can act, and the sanctioned path.+ expect(res.body.error).toContain("Issue visibility");+ expect(res.body.error).toContain("Who can act:");+ expect(res.body.details.sanctionedPath).toContain("child issue");expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:comment" }));expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:mutate" }));expect(mockIssueService.update).not.toHaveBeenCalled();diff --git a/server/src/__tests__/low-trust-red-team-routes.test.ts b/server/src/__tests__/low-trust-red-team-routes.test.tsindex bc4c9f4496..8288f55744 100644--- a/server/src/__tests__/low-trust-red-team-routes.test.ts+++ b/server/src/__tests__/low-trust-red-team-routes.test.ts@@ -827,13 +827,13 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>.patch(`/api/issues/${fixture.issues.reviewRoot.id}`).send({ status: "blocked" });expect(checkedOutPeerUpdate.status, JSON.stringify(checkedOutPeerUpdate.body)).toBe(409);- expect(checkedOutPeerUpdate.body.error).toBe("Issue is checked out by another agent");+ expect(checkedOutPeerUpdate.body.details.code).toBe("issue_write_assignee_run_lock");const documentWrite = await request(standardApp).put(`/api/issues/${fixture.issues.reviewRoot.id}/documents/upward-write`).send({ format: "markdown", body: "No upward document write" });expect(documentWrite.status, JSON.stringify(documentWrite.body)).toBe(409);- expect(documentWrite.body.error).toBe("Issue is checked out by another agent");+ expect(documentWrite.body.details.code).toBe("issue_write_assignee_run_lock");for (const closedParent of [{ assigneeAgentId: null, intent: { reopen: true } },@@ -972,7 +972,7 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>.post(`/api/issues/${targetIssue!.id}/comments`).send({ body: "I was not mentioned." });expect(unmentionedComment.status, JSON.stringify(unmentionedComment.body)).toBe(403);- expect(unmentionedComment.body.error).toBe("Issue is outside this actor's authorization boundary");+ expect(unmentionedComment.body.details.code).toBe("issue_write_actor_class_excluded");});it("propagates denied low-trust policy conflicts on control-plane guards", async () => {diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.tsindex 811efef137..1dc8714f03 100644--- a/server/src/routes/issues.ts+++ b/server/src/routes/issues.ts@@ -95,6 +95,10 @@ import {type SourceTrustMetadata,type SuccessfulRunHandoffState,type WorkspaceRuntimeService,+ issueWriteDenialCodeForResponsibleUserDenial,+ issueWriteDenialResponse,+ type IssueWriteDenialCode,+ type IssueWriteDenialContext,} from "@paperclipai/shared";import { trackAgentTaskCompleted } from "@paperclipai/shared/telemetry";import { getTelemetryClient } from "../telemetry.js";@@ -2785,7 +2789,14 @@ export function issueRoutes(});if (!decision || decision.allowed) return true;- res.status(429).json(crossIssueInfluenceLimitError(decision));+ const labels = await issueWriteDenialLabels(req, {+ identifier: issue.identifier ?? null,+ assigneeAgentId: null,+ });+ res.status(429).json(crossIssueInfluenceLimitError(decision, {+ actorLabel: labels.actorLabel,+ issueIdentifier: labels.issueIdentifier,+ }));return false;}@@ -3648,6 +3659,73 @@ export function issueRoutes(});}+ /**+ * Map an authorization denial onto the issue-write copy contract (plan §6).+ *+ * The two responsible-user ceiling codes are the most specific signal, so they+ * win. Actor-class walls (low-trust, skill-test, task-bridge scopes) stay shut+ * by design and get their own copy. Everything else reaching a write channel is+ * a visibility denial, because the default-open rule puts `issue:read` structurally+ * upstream of every standard-trust write.+ */+ function issueWriteDenialCodeForDecision(+ decision: Awaited<ReturnType<typeof decideIssueAccess>>,+ ): IssueWriteDenialCode {+ if (decision.code) return issueWriteDenialCodeForResponsibleUserDenial(decision.code);+ if (decision.reason === "deny_low_trust_boundary" || decision.reason === "deny_policy_restricted") {+ return "issue_write_actor_class_excluded";+ }+ return "issue_write_not_visible";+ }++ /**+ * Best-effort display names for denial copy. Denials are rare, so one extra+ * query buys an error that names who can act instead of printing raw uuids.+ * Any failure degrades to the copy contract's generic nouns.+ */+ async function issueWriteDenialLabels(+ req: Request,+ issue: { identifier?: string | null; assigneeAgentId: string | null },+ ): Promise<IssueWriteDenialContext> {+ const actorAgentId = req.actor.type === "agent" ? req.actor.agentId ?? null : null;+ const ids = [actorAgentId, issue.assigneeAgentId].filter((id): id is string => Boolean(id));+ const nameById = new Map<string, string>();+ if (ids.length > 0) {+ try {+ const rows = await db+ .select({ id: agents.id, name: agents.name })+ .from(agents)+ .where(inArray(agents.id, ids));+ for (const row of rows) if (row.name) nameById.set(row.id, row.name);+ } catch (err) {+ logger.warn({ err }, "failed to resolve agent names for issue write denial copy");+ }+ }+ return {+ actorLabel: actorAgentId ? nameById.get(actorAgentId) ?? null : null,+ assigneeLabel: issue.assigneeAgentId ? nameById.get(issue.assigneeAgentId) ?? null : null,+ issueIdentifier: issue.identifier ?? null,+ responsibleUserName: null,+ };+ }++ /** Respond to a denied issue write with copy that names boundary, who, and path. */+ async function denyIssueWrite(+ req: Request,+ res: Response,+ issue: { identifier?: string | null; assigneeAgentId: string | null },+ code: IssueWriteDenialCode,+ extraDetails: Record<string, unknown> = {},+ ) {+ const labels = await issueWriteDenialLabels(req, issue);+ const { status, body } = issueWriteDenialResponse(code, labels);+ res.status(status).json({+ error: body.error,+ details: { ...body.details, ...extraDetails },+ });+ return false as const;+ }+async function assertIssueReadAllowed(req: Request, res: Response, issue: Parameters<typeof decideIssueAccess>[1]) {const decision = await decideIssueAccess(req, issue, "issue:read");if (decision.allowed) return true;@@ -3667,8 +3745,7 @@ export function issueRoutes(if ((await resolveTaskWatchdogMutationScope(db, req.actor)).kind !== "none") return true;const decision = await decideIssueAccess(req, issue, "issue:mutate");if (decision.allowed) return true;- res.status(403).json({ error: "Issue is outside this actor's authorization boundary" });- return false;+ return denyIssueWrite(req, res, issue, issueWriteDenialCodeForDecision(decision));}async function assertAgentIssueCommentAllowed(@@ -3682,6 +3759,8 @@ export function issueRoutes(status: string;assigneeAgentId: string | null;assigneeUserId: string | null;+ /** Used only to name the task in denial copy (plan §6). */+ identifier?: string | null;},) {if (req.actor.type !== "agent") return true;@@ -3707,8 +3786,7 @@ export function issueRoutes(}const boundaryDecision = await decideIssueAccess(req, issue, "issue:comment");if (!boundaryDecision.allowed) {- res.status(403).json({ error: "Issue is outside this actor's authorization boundary" });- return false;+ return denyIssueWrite(req, res, issue, issueWriteDenialCodeForDecision(boundaryDecision));}return boundaryDecision;}@@ -3771,6 +3849,8 @@ export function issueRoutes(status: string;assigneeAgentId: string | null;assigneeUserId: string | null;+ /** Used only to name the task in denial copy (plan §6). */+ identifier?: string | null;},options: { allowVisibleIssueWrite?: boolean } = {},) {@@ -3805,8 +3885,7 @@ export function issueRoutes(}const boundaryDecision = await decideIssueAccess(req, issue, "issue:mutate");if (!boundaryDecision.allowed) {- res.status(403).json({ error: "Issue is outside this actor's authorization boundary" });- return false;+ return denyIssueWrite(req, res, issue, issueWriteDenialCodeForDecision(boundaryDecision));}if (issue.assigneeAgentId === null) {return true;@@ -3816,15 +3895,17 @@ export function issueRoutes(return true;}if (issue.status === "in_progress") {- res.status(409).json({- error: "Issue is checked out by another agent",- details: {- issueId: issue.id,- assigneeAgentId: issue.assigneeAgentId,- actorAgentId,- },+ // Run/checkout ownership stays assignee-scoped even though writes are+ // open, so this lock clears on its own — the copy routes to comments.+ return denyIssueWrite(req, res, issue, "issue_write_assignee_run_lock", {+ issueId: issue.id,+ assigneeAgentId: issue.assigneeAgentId,+ actorAgentId,});- } else if (!options.allowVisibleIssueWrite) {+ }+ // Past the run lock the issue is idle, so only channels that have not+ // adopted the default-open rule still refuse another agent's issue.+ if (!options.allowVisibleIssueWrite) {res.status(403).json({error: "Agent cannot mutate another agent's issue",details: {@@ -3835,8 +3916,9 @@ export function issueRoutes(securityPrinciples: ["Least Privilege", "Complete Mediation", "Fail Securely"],},});+ return false;}- return issue.status !== "in_progress" && options.allowVisibleIssueWrite === true;+ return true;}if (issue.status !== "in_progress") {return true;@@ -8258,7 +8340,7 @@ export function issueRoutes(surface: "issue.patch.comment",requestedValue: readNonEmptyString(req.body.onBehalfOfUserId),});- res.status(422).json({ error: "Agent comments cannot set onBehalfOfUserId" });+ await denyIssueWrite(req, res, existing, "issue_write_attribution_spoof_rejected");return;}const issueMutationAccess = await assertAgentIssueMutationAllowed(@@ -10720,7 +10802,7 @@ export function issueRoutes(surface: "issue.comment.create",requestedValue: readNonEmptyString(req.body.onBehalfOfUserId),});- res.status(422).json({ error: "Agent comments cannot set onBehalfOfUserId" });+ await denyIssueWrite(req, res, issue, "issue_write_attribution_spoof_rejected");return;}const commentAccessDecision = await assertAgentIssueCommentAllowed(req, res, issue);diff --git a/server/src/services/cross-issue-influence-limit.ts b/server/src/services/cross-issue-influence-limit.tsindex 4fcf829d0f..aef4a56876 100644--- a/server/src/services/cross-issue-influence-limit.ts+++ b/server/src/services/cross-issue-influence-limit.ts@@ -1,7 +1,7 @@import { and, count, eq } from "drizzle-orm";import type { Db } from "@paperclipai/db";import { activityLog, heartbeatRuns } from "@paperclipai/db";-import { isUuidLike } from "@paperclipai/shared";+import { isUuidLike, issueWriteDenialResponse } from "@paperclipai/shared";import { forbidden } from "../errors.js";import { logger } from "../middleware/logger.js";@@ -22,10 +22,10 @@ export type CrossIssueInfluenceDecision = {};export function crossIssueInfluenceRunContextError() {- return forbidden(- "Agent issue comments and updates require a valid heartbeat run so cross-issue influence can be contained",- { code: "cross_issue_influence_run_context_required" },- );+ // Copy comes from the shared issue-write denial contract (the open cross-task write design (failure UX))+ // so the agent reading this 403 is told the fix, not just the refusal.+ const { body } = issueWriteDenialResponse("cross_issue_influence_run_context_required");+ return forbidden(body.error, body.details);}function readRunSourceIssueId(contextSnapshot: unknown) {@@ -172,11 +172,22 @@ export async function observeCrossIssueInfluence(});}-export function crossIssueInfluenceLimitError(decision: CrossIssueInfluenceDecision) {+export function crossIssueInfluenceLimitError(+ decision: CrossIssueInfluenceDecision,+ context: { actorLabel?: string | null; assigneeLabel?: string | null; issueIdentifier?: string | null } = {},+) {+ // The cap is a rate backstop, not a permission decision — the shared copy+ // contract says so explicitly, and names the next run as the way forward.+ const { body } = issueWriteDenialResponse("cross_issue_influence_cap_exceeded", {+ ...context,+ cap: decision.cap,+ count: decision.count,+ enforceAt: decision.enforceAt,+ });return {- error: `Cross-issue influence cap exceeded: this run is limited to ${decision.cap} cross-issue comments or updates`,+ error: body.error,details: {- code: "cross_issue_influence_cap_exceeded",+ ...body.details,cap: decision.cap,count: decision.count,mode: decision.mode,diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 14fd0b03ff..8e19f35102 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -52,6 +52,7 @@ import { CompanySettings } from "./pages/CompanySettings";import { CompanyEnvironments } from "./pages/CompanyEnvironments";import { BootstrapSetupUxLab } from "./pages/BootstrapSetupUxLab";import { ResponsibleUserDenialUxLab } from "./pages/ResponsibleUserDenialUxLab";+import { CrossIssueCollaborationUxLab } from "./pages/CrossIssueCollaborationUxLab";import { CompanySettingsPluginPage } from "./pages/CompanySettingsPluginPage";import { CompanyAccess, CompanyAccessLegacyRoute } from "./pages/CompanyAccess";import { AdvancedToolsRoute } from "./pages/tools/AdvancedToolsRoute";@@ -548,6 +549,7 @@ export function App() {<Route path="tests/perf/long-thread" element={<IssueChatLongThreadPerf />} /><Route path="ux-lab/bootstrap-setup" element={<BootstrapSetupUxLab />} /><Route path="ux-lab/responsible-user-denial" element={<ResponsibleUserDenialUxLab />} />+ <Route path="ux-lab/cross-issue-collaboration" element={<CrossIssueCollaborationUxLab />} /><Route element={<CloudAccessGate />}><Route index element={<CompanyRootRedirect />} />diff --git a/ui/src/components/CommentAttributionChip.test.tsx b/ui/src/components/CommentAttributionChip.test.tsxnew file mode 100644index 0000000000..eda9c4e37d--- /dev/null+++ b/ui/src/components/CommentAttributionChip.test.tsx@@ -0,0 +1,57 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { renderToStaticMarkup } from "react-dom/server";+import { TooltipProvider } from "@/components/ui/tooltip";+import { CommentAttributionChip, commentAttributionTooltip } from "./CommentAttributionChip";++/** The chip uses the app's Radix tooltip, which requires an ancestor provider. */+function render(node: React.ReactNode) {+ return renderToStaticMarkup(<TooltipProvider>{node}</TooltipProvider>);+}++describe("CommentAttributionChip", () => {+ it("renders 'for {user}' beside the author name", () => {+ const html = render(<CommentAttributionChip agentName="Fable" userName="Dotta" />);++ // Composes with the header's author name to read "Fable · for Dotta".+ expect(html).toContain("for Dotta");+ expect(html).toContain('data-testid="comment-attribution-chip"');+ expect(html).toContain('aria-label="Posted on behalf of Dotta"');+ });++ it("does not repeat the agent name on the chip face", () => {+ const html = render(<CommentAttributionChip agentName="Fable" userName="Dotta" />);+ expect(html).not.toContain("Fable");+ });++ it("renders nothing without a responsible user", () => {+ const empty = render(null);+ expect(render(<CommentAttributionChip agentName="Fable" userName={null} />)).toBe(empty);+ expect(render(<CommentAttributionChip agentName="Fable" userName=" " />)).toBe(empty);+ expect(render(<CommentAttributionChip userName={undefined} />)).toBe(empty);+ });++ it("is keyboard focusable so the tooltip is not hover-only", () => {+ // Badge renders a span; without tabIndex a sighted keyboard user could never+ // open the explanation of whose authority the comment rode.+ expect(render(<CommentAttributionChip userName="Dotta" />)).toContain('tabindex="0"');+ });++ it("trims a padded user name", () => {+ expect(render(<CommentAttributionChip userName=" Dotta " />)).toContain("for Dotta");+ });+});++describe("commentAttributionTooltip", () => {+ it("names both the agent and the user it acted for", () => {+ const copy = commentAttributionTooltip("Fable", "Dotta");+ expect(copy).toContain("Fable posted this on behalf of Dotta");+ expect(copy).toContain("not assigned to this task");+ expect(copy).toContain("never exceeds it");+ });++ it("keeps on-behalf-of terminology, never 'impersonate'", () => {+ expect(commentAttributionTooltip("Fable", "Dotta")).not.toContain("impersonat");+ });+});diff --git a/ui/src/components/CommentAttributionChip.tsx b/ui/src/components/CommentAttributionChip.tsxnew file mode 100644index 0000000000..951912cc5d--- /dev/null+++ b/ui/src/components/CommentAttributionChip.tsx@@ -0,0 +1,72 @@+import { UserCheck } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "../lib/utils";++/**+ * "for {user}" chip on an agent comment posted to a task the agent does not own+ * (the open cross-task write design (attribution)).+ *+ * Cross-issue agent writes are open by default, so a thread can now contain+ * comments from agents that are not the assignee. The chip answers the question+ * that raises — *whose authority is this riding?* — by naming the responsible+ * user the run acted on behalf of. Rendered beside the already-visible author+ * name, it reads as "Fable · for Dotta"; the agent's own identity comes from the+ * surrounding header, so this component never repeats it.+ *+ * Terminology matches the rest of the app: "on behalf of {user}" / "responsible+ * user", never "impersonate".+ */+/**+ * Tooltip copy for the chip. Exported so the wording is unit-testable without+ * driving Radix's portal open.+ */+export function commentAttributionTooltip(agentName: string, userName: string): string {+ return (+ `${agentName} posted this on behalf of ${userName}. ${agentName} is not assigned to ` ++ `this task — its authority to write here comes from ${userName}, and never exceeds it.`+ );+}++export function CommentAttributionChip({+ agentName,+ userName,+ className,+}: {+ /** Author agent's display name — used in the tooltip, not the chip face. */+ agentName?: string | null;+ /** Responsible user's display name. Without it there is nothing to attribute. */+ userName?: string | null;+ className?: string;+}) {+ const user = userName?.trim();+ if (!user) return null;+ const agent = agentName?.trim() || "This agent";++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge+ variant="outline"+ data-testid="comment-attribution-chip"+ aria-label={`Posted on behalf of ${user}`}+ // `Badge` renders a span, which is not focusable — without this a+ // sighted keyboard user can never open the explanation. Radix opens+ // the tooltip on focus as well as hover.+ tabIndex={0}+ className={cn(+ "inline-flex max-w-40 items-center gap-1 whitespace-nowrap border-border px-1.5 py-0",+ "text-(length:--text-nano) font-medium tracking-normal text-muted-foreground",+ className,+ )}+ >+ <UserCheck className="h-3 w-3 shrink-0" aria-hidden="true" />+ <span className="truncate">for {user}</span>+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs text-xs">+ {commentAttributionTooltip(agent, user)}+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsxindex 7ef8f2d5c9..af884ca0c4 100644--- a/ui/src/components/IssueChatThread.tsx+++ b/ui/src/components/IssueChatThread.tsx@@ -185,6 +185,8 @@ import {type RecoveryResolveOutcome,} from "./IssueRecoveryActionCard";import { SourceTrustBadge } from "./SourceTrustBadge";+import { CommentAttributionChip } from "./CommentAttributionChip";+import { resolveCommentAttribution } from "../lib/comment-attribution";interface IssueChatMessageContext {feedbackDataSharingPreference: FeedbackDataSharingPreference;@@ -235,6 +237,11 @@ interface IssueChatMessageContext {) => Promise<void> | void;onUploadImage?: (file: File) => Promise<string>;issueStatus?: string;+ /**+ * Current assignee. Agent comments from anyone else are cross-issue writes, so+ * they carry a "for {user}" attribution chip (the open cross-task write design (attribution)).+ */+ issueAssigneeAgentId?: string | null;successfulRunHandoff?: SuccessfulRunHandoffState | null;externalReferences?: MarkdownExternalReferenceMap;/** Linkify `PAP-C7` case chips in comment bodies (experimental Cases flag). */@@ -463,6 +470,8 @@ interface IssueChatThreadProps {title?: string | null;} | null;assigneeUserId?: string | null;+ /** Current assignee agent, used to mark cross-issue agent comments (the open cross-task write design (attribution)). */+ issueAssigneeAgentId?: string | null;onResumeFromBacklog?: () => Promise<void> | void;resumeFromBacklogPending?: boolean;companyId?: string | null;@@ -1676,6 +1685,8 @@ function IssueChatAssistantMessage({stoppingRunLabel = "Stopping...",stopRunVariant = "stop",runFinalizationActions = [],+ userLabelMap,+ issueAssigneeAgentId,} = useContext(IssueChatCtx);const custom = message.metadata.custom as Record<string, unknown>;const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;@@ -1692,6 +1703,12 @@ function IssueChatAssistantMessage({const agentIcon = agentId ? agentMap?.get(agentId)?.icon : undefined;const commentId = typeof custom.commentId === "string" ? custom.commentId : null;const sourceTrust = isSourceTrustMetadata(custom.sourceTrust) ? custom.sourceTrust : null;+ const attribution = resolveCommentAttribution({+ authorAgentId,+ onBehalfOfUserId: typeof custom.onBehalfOfUserId === "string" ? custom.onBehalfOfUserId : null,+ issueAssigneeAgentId,+ resolveUserLabel: (userId) => userLabelMap?.get(userId),+ });const notices = Array.isArray(custom.notices)? custom.notices.filter((notice): notice is string => typeof notice === "string" && notice.length > 0): [];@@ -1878,6 +1895,10 @@ function IssueChatAssistantMessage({)}</span><span className="text-sm font-medium text-foreground">{authorName}</span>+ {/* Reads as "Fable · for Dotta" beside the author name (the open cross-task write design (attribution)). */}+ {attribution ? (+ <CommentAttributionChip agentName={authorName} userName={attribution.userName} />+ ) : null}<SourceTrustBadge sourceTrust={sourceTrust} artifactLabel="comment" />{followUpRequested ? (<Badge variant="outline" className="text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow)">@@ -4326,6 +4347,7 @@ export function IssueChatThread({companyId,projectId,issueStatus,+ issueAssigneeAgentId = null,agentMap,currentUserId,userLabelMap,@@ -4931,6 +4953,7 @@ export function IssueChatThread({onSubmitInteractionVerdicts: stableOnSubmitInteractionVerdicts,onUploadImage: stableOnUploadImage,issueStatus,+ issueAssigneeAgentId,successfulRunHandoff,externalReferences,linkCaseReferences,@@ -4959,6 +4982,7 @@ export function IssueChatThread({stableOnSubmitInteractionVerdicts,stableOnUploadImage,issueStatus,+ issueAssigneeAgentId,successfulRunHandoff,externalReferences,linkCaseReferences,diff --git a/ui/src/components/IssueFieldChangeReceipt.test.tsx b/ui/src/components/IssueFieldChangeReceipt.test.tsxnew file mode 100644index 0000000000..0468b59b32--- /dev/null+++ b/ui/src/components/IssueFieldChangeReceipt.test.tsx@@ -0,0 +1,129 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { renderToStaticMarkup } from "react-dom/server";+import type { ActivityEvent } from "@paperclipai/shared";+import { IssueFieldChangeReceipt } from "./IssueFieldChangeReceipt";++function event(overrides: Partial<ActivityEvent> = {}) {+ return {+ action: "issue.updated",+ details: null,+ responsibleUserId: null,+ ...overrides,+ } as Pick<ActivityEvent, "action" | "details" | "responsibleUserId">;+}++describe("IssueFieldChangeReceipt", () => {+ it("shows before and after for each changed field", () => {+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({+ details: {+ changes: {+ status: { from: "todo", to: "in_progress" },+ priority: { from: "medium", to: "high" },+ },+ },+ })}+ />,+ );++ expect(html).toContain("Status");+ expect(html).toContain("todo");+ expect(html).toContain("in progress");+ expect(html).toContain("Priority");+ expect(html).toContain("high");+ expect(html).toContain('data-testid="issue-change-row-status"');+ });++ it("names the responsible user and the authorization reason", () => {+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({+ responsibleUserId: "user-1",+ details: {+ changes: { status: { from: "todo", to: "done" } },+ authorizationReason: "allow_visible_issue_write",+ },+ })}+ resolveUserLabel={() => "Dotta"}+ />,+ );++ expect(html).toContain("Dotta");+ expect(html).toContain("authorized by default-open write on a visible task");+ });++ it("resolves an assignee change to agent names", () => {+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({+ details: {+ changes: {+ assigneeAgentId: {+ from: "3108ef8e-5ed0-41d9-b561-6b41c41b8545",+ to: "6670e11b-91d3-4429-82e0-436b88b51808",+ },+ },+ },+ })}+ resolveAgentLabel={(id) =>+ id.startsWith("3108") ? "ClaudeCoder" : "UXDesigner"}+ />,+ );++ expect(html).toContain("Assignee");+ expect(html).toContain("ClaudeCoder");+ expect(html).toContain("UXDesigner");+ });++ it("marks server-truncated long text as a preview", () => {+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({+ details: {+ changes: { description: { from: "old", to: "new", updated: true } },+ },+ })}+ />,+ );++ expect(html).toContain("Description");+ expect(html).toContain("preview");+ });++ it("renders a board edit's receipt the same way as an agent's", () => {+ // Plan §3b: audit is required for human PATCHes too, not only agent ones.+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({+ details: {+ changes: { title: { from: "Old title", to: "New title" } },+ authorizationReason: "allow_board_actor",+ },+ })}+ />,+ );++ expect(html).toContain("Title");+ expect(html).toContain("authorized by board actor");+ });++ it("renders nothing for events with no receipt", () => {+ expect(renderToStaticMarkup(<IssueFieldChangeReceipt event={event()} />)).toBe("");+ // Pre-receipt rows carried loose fields but no `changes` receipt.+ expect(renderToStaticMarkup(+ <IssueFieldChangeReceipt event={event({ details: { status: "done" } })} />,+ )).toBe("");+ });++ it("still explains authorization when only a reason was recorded", () => {+ const html = renderToStaticMarkup(+ <IssueFieldChangeReceipt+ event={event({ details: { authorizationReason: "allow_self" } })}+ />,+ );+ expect(html).toContain("authorized by own task");+ });+});diff --git a/ui/src/components/IssueFieldChangeReceipt.tsx b/ui/src/components/IssueFieldChangeReceipt.tsxnew file mode 100644index 0000000000..fb88c9a45b--- /dev/null+++ b/ui/src/components/IssueFieldChangeReceipt.tsx@@ -0,0 +1,97 @@+import { ArrowRight, ShieldCheck } from "lucide-react";+import type { ActivityEvent } from "@paperclipai/shared";+import {+ issueAuthorizationReasonLabel,+ readIssueChangeReceipt,+} from "../lib/issue-change-receipt";+import { cn } from "../lib/utils";++/**+ * Field-level audit receipt under an `issue.updated` row in the activity stream+ * (the open cross-task write design (audit) — Dotta's hard requirement).+ *+ * Opening cross-issue writes means a task's fields can be changed by an agent+ * that does not own it. The board's answer to "who moved this, and were they+ * allowed to?" must be visible on the task itself, not only in the audit log —+ * so every PATCH, agent *and* human, shows what changed, the responsible user+ * behind it, and the authorization reason that let it through.+ *+ * Renders nothing when the event carries no receipt, so pre-receipt activity+ * rows are unaffected.+ */+export function IssueFieldChangeReceipt({+ event,+ resolveAgentLabel,+ resolveUserLabel,+ className,+}: {+ event: Pick<ActivityEvent, "action" | "details" | "responsibleUserId">;+ resolveAgentLabel?: (agentId: string) => string | null | undefined;+ resolveUserLabel?: (userId: string) => string | null | undefined;+ className?: string;+}) {+ const rows = readIssueChangeReceipt(event.details, { resolveAgentLabel, resolveUserLabel });+ const reason = issueAuthorizationReasonLabel(+ typeof event.details?.authorizationReason === "string"+ ? event.details.authorizationReason+ : null,+ );+ const responsibleUserName = event.responsibleUserId+ ? resolveUserLabel?.(event.responsibleUserId) ?? null+ : null;++ if (rows.length === 0 && !reason) return null;++ return (+ <div+ data-testid="issue-field-change-receipt"+ className={cn("space-y-1 border-l-2 border-border/70 pl-2", className)}+ >+ {rows.length > 0 ? (+ <dl className="space-y-0.5">+ {rows.map((row) => (+ <div+ key={row.field}+ data-testid={`issue-change-row-${row.field}`}+ className="flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-xs"+ >+ <dt className="text-muted-foreground">{row.label}</dt>+ <dd className="flex min-w-0 flex-wrap items-baseline gap-x-1.5">+ <span className="min-w-0 break-words text-muted-foreground line-through decoration-muted-foreground/50">+ {row.from}+ </span>+ <ArrowRight className="size-3 shrink-0 text-muted-foreground/70" aria-hidden="true" />+ <span className="min-w-0 break-words font-medium text-foreground">{row.to}</span>+ {/* Long text is stored as a preview, so the receipt says so+ rather than implying the whole value is shown. */}+ {row.truncated ? (+ <span className="text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">+ preview+ </span>+ ) : null}+ </dd>+ </div>+ ))}+ </dl>+ ) : null}+ {reason ? (+ // Inline flow, not flex: as separate flex items the icon wraps onto its+ // own line and orphans above the reason at narrow widths. Inline keeps it+ // glued to the first word.+ <p className="min-w-0 text-(length:--text-micro) leading-4 text-muted-foreground">+ <ShieldCheck+ className="mr-1 inline size-3 align-(--va-0_125em)"+ aria-hidden="true"+ />+ {responsibleUserName ? (+ <>+ for <span className="text-foreground">{responsibleUserName}</span>+ {" · "}+ </>+ ) : null}+ authorized by {reason}+ </p>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/IssueWriteDenialNotice.test.tsx b/ui/src/components/IssueWriteDenialNotice.test.tsxnew file mode 100644index 0000000000..3b760c412f--- /dev/null+++ b/ui/src/components/IssueWriteDenialNotice.test.tsx@@ -0,0 +1,103 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { renderToStaticMarkup } from "react-dom/server";+import { ISSUE_WRITE_DENIAL_CODES } from "@paperclipai/shared";+import { IssueWriteDenialNotice } from "./IssueWriteDenialNotice";+import { issueWriteDenialForActivity } from "../lib/issue-write-denial-activity";++describe("IssueWriteDenialNotice", () => {+ it("answers all three plan §6 obligations for every code", () => {+ for (const code of ISSUE_WRITE_DENIAL_CODES) {+ const html = renderToStaticMarkup(<IssueWriteDenialNotice code={code} />);+ expect(html, code).toContain("Who can act:");+ expect(html, code).toContain("Try this:");+ expect(html, code).toContain(`data-denial-code="${code}"`);+ }+ });++ it("names the boundary that fired alongside the title", () => {+ const html = renderToStaticMarkup(+ <IssueWriteDenialNotice+ code="issue_write_not_visible"+ context={{ actorLabel: "Fable", issueIdentifier: "TASK-482" }}+ />,+ );++ expect(html).toContain("Issue visibility");+ expect(html).toContain("TASK-482");+ expect(html).toContain("Fable");+ // The workaround the incident had to discover is now stated outright.+ expect(html).toContain("child issue");+ });++ it("tones a run lock as transient rather than a permission wall", () => {+ const lock = renderToStaticMarkup(+ <IssueWriteDenialNotice+ code="issue_write_assignee_run_lock"+ context={{ assigneeLabel: "CodexCoder" }}+ />,+ );+ expect(lock).toContain('data-denial-tone="lock"');+ expect(lock).toContain("Comment instead");++ const wall = renderToStaticMarkup(+ <IssueWriteDenialNotice code="issue_write_not_visible" />,+ );+ expect(wall).toContain('data-denial-tone="boundary"');+ });++ it("shows the cap and attempt count on a rate denial", () => {+ const html = renderToStaticMarkup(+ <IssueWriteDenialNotice+ code="cross_issue_influence_cap_exceeded"+ context={{ cap: 20, count: 21, actorLabel: "Fable" }}+ />,+ );+ expect(html).toContain('data-denial-tone="cap"');+ expect(html).toContain("20");+ expect(html).toContain("attempt 21");+ });+});++describe("issueWriteDenialForActivity", () => {+ it("maps the cap-rejected activity event onto the cap denial", () => {+ const result = issueWriteDenialForActivity(+ "issue.cross_issue_influence_cap_rejected",+ { identifier: "TASK-482", cap: 20, count: 21, enforceAt: "2026-08-11T00:00:00.000Z" },+ { actorLabel: "Fable" },+ );++ expect(result?.code).toBe("cross_issue_influence_cap_exceeded");+ expect(result?.context).toMatchObject({+ actorLabel: "Fable",+ issueIdentifier: "TASK-482",+ cap: 20,+ count: 21,+ });+ });++ it("maps a rejected attribution spoof", () => {+ expect(issueWriteDenialForActivity("issue.attribution_spoof_rejected", { identifier: "TASK-1" })?.code)+ .toBe("issue_write_attribution_spoof_rejected");+ });++ it("ignores activity actions that are not denials", () => {+ expect(issueWriteDenialForActivity("issue.updated", {})).toBeNull();+ expect(issueWriteDenialForActivity("issue.comment_added", {})).toBeNull();+ // An observed (allowed) cross-issue write is not a denial.+ expect(issueWriteDenialForActivity("issue.cross_issue_influence_observed", {})).toBeNull();+ });++ it("tolerates missing or malformed details", () => {+ const result = issueWriteDenialForActivity("issue.attribution_spoof_rejected", null);+ expect(result?.context).toMatchObject({ issueIdentifier: null, cap: null, count: null });++ const bad = issueWriteDenialForActivity("issue.cross_issue_influence_cap_rejected", {+ identifier: 42,+ cap: "twenty",+ });+ expect(bad?.context.issueIdentifier).toBeNull();+ expect(bad?.context.cap).toBeNull();+ });+});diff --git a/ui/src/components/IssueWriteDenialNotice.tsx b/ui/src/components/IssueWriteDenialNotice.tsxnew file mode 100644index 0000000000..fe721c0406--- /dev/null+++ b/ui/src/components/IssueWriteDenialNotice.tsx@@ -0,0 +1,114 @@+import { Clock, EyeOff, ShieldX, UserCog } from "lucide-react";+import {+ describeIssueWriteDenial,+ type IssueWriteDenialCode,+ type IssueWriteDenialContext,+ type IssueWriteDenialTone,+} from "@paperclipai/shared";+import { cn } from "../lib/utils";++/**+ * Renders actionable copy for a denied issue write (the open cross-task write design (failure UX)).+ *+ * Cross-issue writes are open by default, so the walls that remain are rare —+ * which is exactly why hitting one has to be self-explaining. A real incident+ * burned a full detour discovering a workaround behind an opaque 403; this notice always+ * states the boundary that fired, who *can* act, and the sanctioned path.+ *+ * Copy comes from the shared `describeIssueWriteDenial` contract, so the words a+ * human reads here match the API error body an agent reads.+ */++const TONE_ICONS: Record<IssueWriteDenialTone, typeof ShieldX> = {+ boundary: ShieldX,+ lock: Clock,+ cap: Clock,+ attribution: UserCog,+};++const TONE_CLASSES: Record<IssueWriteDenialTone, { surface: string; icon: string; action: string }> = {+ // A real authorization wall — the strongest signal.+ boundary: {+ surface:+ "border-red-300/70 bg-red-50/90 text-red-950 dark:border-red-500/40 dark:bg-red-500/10 dark:text-red-100",+ icon: "text-red-600 dark:text-red-300",+ action: "text-red-800 dark:text-red-200",+ },+ // Run-lifecycle machinery that clears on its own; not a permission problem.+ lock: {+ surface:+ "border-amber-300/70 bg-amber-50/90 text-amber-950 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100",+ icon: "text-amber-600 dark:text-amber-300",+ action: "text-amber-800 dark:text-amber-200",+ },+ // A rate backstop — the write was allowed, the budget was not.+ cap: {+ surface:+ "border-amber-300/70 bg-amber-50/90 text-amber-950 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100",+ icon: "text-amber-600 dark:text-amber-300",+ action: "text-amber-800 dark:text-amber-200",+ },+ // Rejected attribution: the write is fine, the claimed identity is not.+ // Neutral surface, but the action lines stay near-foreground — on a muted+ // background `text-muted-foreground` drops below comfortable contrast.+ attribution: {+ surface:+ "border-border bg-muted/60 text-foreground dark:border-border dark:bg-muted/30",+ icon: "text-muted-foreground",+ action: "text-foreground/80",+ },+};++/** Codes whose primary failure is that the target is simply not visible. */+const VISIBILITY_CODES: ReadonlySet<IssueWriteDenialCode> = new Set([+ "issue_write_not_visible",+]);++export function IssueWriteDenialNotice({+ code,+ context,+ className,+}: {+ code: IssueWriteDenialCode;+ context?: IssueWriteDenialContext;+ className?: string;+}) {+ const copy = describeIssueWriteDenial(code, context ?? {});+ const tone = TONE_CLASSES[copy.tone];+ const Icon = VISIBILITY_CODES.has(code) ? EyeOff : TONE_ICONS[copy.tone];++ return (+ <div+ role="status"+ data-testid="issue-write-denial-notice"+ data-denial-code={copy.code}+ data-denial-tone={copy.tone}+ className={cn("rounded-md border px-3 py-2.5 text-sm shadow-sm", tone.surface, className)}+ >+ <div className="flex items-start gap-2">+ <Icon className={cn("mt-0.5 size-4 shrink-0", tone.icon)} aria-hidden="true" />+ <div className="min-w-0 space-y-1">+ <p className="font-medium leading-5">+ {copy.title}+ {/* Naming the boundary is obligation 1 of plan §6. */}+ <span className="ml-1.5 font-normal opacity-80">({copy.boundary})</span>+ </p>+ <p className="leading-5">{copy.description}</p>+ {/* Inline flow, not flex rows: a flex `dd` is an unbreakable line box,+ so a long value drops whole and orphans its label. Inline keeps the+ label and the first words of the value together at every width. */}+ <dl className={cn("space-y-0.5 text-xs leading-5", tone.action)}>+ <div className="min-w-0">+ <dt className="inline font-medium">Who can act:</dt>{" "}+ <dd className="inline">{copy.whoCanAct}</dd>+ </div>+ <div className="min-w-0">+ <dt className="inline font-medium">Try this:</dt>{" "}+ <dd className="inline">{copy.sanctionedPath}</dd>+ </div>+ </dl>+ </div>+ </div>+ </div>+ );+}diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsxindex a0575b3ba0..35f507b468 100644--- a/ui/src/components/TaskChatThread.tsx+++ b/ui/src/components/TaskChatThread.tsx@@ -98,6 +98,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {reassignOptions,currentAssigneeValue,issueStatus,+ issueAssigneeAgentId = null,onAcceptInteraction,onRejectInteraction,onSubmitInteractionAnswers,@@ -128,8 +129,14 @@ export function TaskChatThread(props: TaskChatThreadProps) {[linkedRunMetaById, workModeChanges, issueWorkMode],);const commentItems = useMemo(- () => commentsToTaskChatItems(comments, { agentMap, userLabelMap, currentUserId, agentModeLabelFor }),- [comments, agentMap, userLabelMap, currentUserId, agentModeLabelFor],+ () => commentsToTaskChatItems(comments, {+ agentMap,+ userLabelMap,+ currentUserId,+ issueAssigneeAgentId,+ agentModeLabelFor,+ }),+ [comments, agentMap, userLabelMap, currentUserId, issueAssigneeAgentId, agentModeLabelFor],);// Every run we might need a transcript for (history + live), deduped by id.diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsxindex e164abf8cc..549877d381 100644--- a/ui/src/components/task-chat/TaskChatBubble.tsx+++ b/ui/src/components/task-chat/TaskChatBubble.tsx@@ -3,6 +3,7 @@ import { cn } from "@/lib/utils";import { MarkdownBody } from "@/components/MarkdownBody";import { Avatar, AvatarFallback } from "@/components/ui/avatar";import { AgentIcon } from "@/components/AgentIconPicker";+import { CommentAttributionChip } from "@/components/CommentAttributionChip";import {Attachment,AttachmentContent,@@ -75,6 +76,12 @@ export function TaskChatBubble({ item, attachedTurn }: TaskChatBubbleProps) {)}</Avatar><span className="text-sm font-semibold text-foreground">{item.authorName}</span>+ {item.onBehalfOfUserName ? (+ <CommentAttributionChip+ agentName={item.authorName}+ userName={item.onBehalfOfUserName}+ />+ ) : null}{item.modeLabel ? (<span className="rounded-full border border-border px-2 py-px text-(length:--text-micro) font-medium text-muted-foreground">{item.modeLabel}diff --git a/ui/src/components/task-chat/task-chat-adapter.ts b/ui/src/components/task-chat/task-chat-adapter.tsindex cc1bfb635e..552b5099cc 100644--- a/ui/src/components/task-chat/task-chat-adapter.ts+++ b/ui/src/components/task-chat/task-chat-adapter.ts@@ -9,12 +9,18 @@*/import type { Agent } from "@paperclipai/shared";import type { IssueChatComment } from "@/lib/issue-chat-messages";+import { resolveCommentAttribution } from "@/lib/comment-attribution";import type { TaskChatAuthorKind, TaskChatItem } from "./task-chat-model";export interface TaskChatAdapterContext {agentMap?: Map<string, Agent>;userLabelMap?: ReadonlyMap<string, string> | null;currentUserId?: string | null;+ /**+ * Task's current assignee. Agent comments from anyone else are cross-issue+ * writes and get a "for {user}" attribution chip (the open cross-task write design (attribution)).+ */+ issueAssigneeAgentId?: string | null;/*** Capitalized mode chip for agent-authored bubbles ("Agent mode" / "Plan* mode" / "Ask mode") — resolved per comment, so each reply is tagged with@@ -52,10 +58,17 @@ export function commentsToTaskChatItems(const kind = authorKind(comment);let authorName: string | undefined;let agentIcon: string | null | undefined;+ let onBehalfOfUserName: string | undefined;if (kind === "agent") {const agentId = effectiveAgentId(comment);authorName = (agentId && ctx.agentMap?.get(agentId)?.name) || "Agent";agentIcon = agentId ? ctx.agentMap?.get(agentId)?.icon : undefined;+ onBehalfOfUserName = resolveCommentAttribution({+ authorAgentId: agentId,+ onBehalfOfUserId: comment.onBehalfOfUserId ?? null,+ issueAssigneeAgentId: ctx.issueAssigneeAgentId,+ resolveUserLabel: (userId) => ctx.userLabelMap?.get(userId),+ })?.userName;} else if (kind === "human") {authorName =(comment.authorUserId && ctx.userLabelMap?.get(comment.authorUserId)) || undefined;@@ -75,6 +88,7 @@ export function commentsToTaskChatItems(timestamp: formatTaskChatTimestamp(comment.createdAt),optimistic,agentIcon,+ onBehalfOfUserName,modeLabel: kind === "agent" ? ctx.agentModeLabelFor?.(comment) : undefined,});}diff --git a/ui/src/components/task-chat/task-chat-model.ts b/ui/src/components/task-chat/task-chat-model.tsindex 00d99f35ad..bbf42b6459 100644--- a/ui/src/components/task-chat/task-chat-model.ts+++ b/ui/src/components/task-chat/task-chat-model.ts@@ -76,6 +76,12 @@ export interface TaskChatMessageItem {modeLabel?: string;/** Assigned agent icon name (AgentIconName) for the avatar header. */agentIcon?: string | null;+ /**+ * Responsible user's display name, set only when this agent comment is a+ * cross-issue write (the author is not the assignee). Renders as a+ * "for {user}" chip beside the author name (the open cross-task write design (attribution)).+ */+ onBehalfOfUserName?: string;/*** Agent text streamed inside a run turn (interstitial updates between tool* calls). Ephemeral in the redesigned view (PAP-361): while streaming itdiff --git a/ui/src/lib/activity-format.ts b/ui/src/lib/activity-format.tsindex 97545ec48a..6ff6c0c4eb 100644--- a/ui/src/lib/activity-format.ts+++ b/ui/src/lib/activity-format.ts@@ -113,6 +113,9 @@ const ISSUE_ACTIVITY_LABELS: Record<string, string> = {"issue.successful_run_handoff_required": "Run finished without a clear next step","issue.successful_run_handoff_resolved": "Next step chosen","issue.successful_run_handoff_escalated": "Run finished without a next step - recovery escalated",+ "issue.cross_issue_influence_cap_rejected": "hit the per-run cross-task write cap",+ "issue.cross_issue_influence_observed": "made a cross-task write",+ "issue.attribution_spoof_rejected": "tried to choose its own responsible user","issue.recovery_action_opened": "Opened a source-scoped recovery action","issue.recovery_action_resolved": "Resolved the recovery action","issue.recovery_action_escalated": "Escalated the recovery action",diff --git a/ui/src/lib/comment-attribution.test.ts b/ui/src/lib/comment-attribution.test.tsnew file mode 100644index 0000000000..f719a7df6a--- /dev/null+++ b/ui/src/lib/comment-attribution.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";++import { resolveCommentAttribution } from "./comment-attribution";++const labels = new Map([["user-dotta", "Dotta"]]);+const resolveUserLabel = (id: string) => labels.get(id) ?? null;++describe("resolveCommentAttribution", () => {+ it("chips a non-assignee agent comment with the responsible user's name", () => {+ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: "user-dotta",+ issueAssigneeAgentId: "agent-codex",+ resolveUserLabel,+ })).toEqual({ userName: "Dotta" });+ });++ it("stays silent for the assignee's own comments", () => {+ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: "user-dotta",+ issueAssigneeAgentId: "agent-fable",+ resolveUserLabel,+ })).toBeNull();+ });++ it("stays silent for human and system comments", () => {+ expect(resolveCommentAttribution({+ authorAgentId: null,+ onBehalfOfUserId: "user-dotta",+ issueAssigneeAgentId: "agent-codex",+ resolveUserLabel,+ })).toBeNull();+ });++ it("stays silent when the server recorded no responsible user", () => {+ // Pre-migration comments have a null column; they must not render a chip.+ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: null,+ issueAssigneeAgentId: "agent-codex",+ resolveUserLabel,+ })).toBeNull();+ });++ it("chips an unassigned task's agent comment", () => {+ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: "user-dotta",+ issueAssigneeAgentId: null,+ resolveUserLabel,+ })).toEqual({ userName: "Dotta" });+ });++ it("degrades to a generic label instead of leaking a raw user id", () => {+ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: "user-unknown",+ issueAssigneeAgentId: "agent-codex",+ resolveUserLabel,+ })).toEqual({ userName: "the responsible user" });++ expect(resolveCommentAttribution({+ authorAgentId: "agent-fable",+ onBehalfOfUserId: "user-dotta",+ issueAssigneeAgentId: "agent-codex",+ })).toEqual({ userName: "the responsible user" });+ });+});diff --git a/ui/src/lib/comment-attribution.ts b/ui/src/lib/comment-attribution.tsnew file mode 100644index 0000000000..0f5c8ead12--- /dev/null+++ b/ui/src/lib/comment-attribution.ts@@ -0,0 +1,28 @@+import { responsibleUserLabel } from "@paperclipai/shared";++/**+ * Decide whether an agent comment needs a "for {user}" attribution chip, and+ * what name it should carry (the open cross-task write design (attribution)).+ *+ * Cross-issue agent writes are open by default, so a thread can hold comments+ * from agents that do not own the task. Those are the ones worth marking: for the+ * assignee's own comments the responsible user is already implied by the task's+ * own attribution, and chipping every bubble would be noise.+ */+export function resolveCommentAttribution(input: {+ /** Author agent, or null for human/system comments. */+ authorAgentId: string | null;+ /** Responsible user persisted for the comment by the server. */+ onBehalfOfUserId: string | null;+ /** The task's current assignee agent. */+ issueAssigneeAgentId?: string | null;+ /** Resolve a user id to a display name, when the directory is loaded. */+ resolveUserLabel?: (userId: string) => string | null | undefined;+}): { userName: string } | null {+ const { authorAgentId, onBehalfOfUserId, issueAssigneeAgentId, resolveUserLabel } = input;+ if (!authorAgentId || !onBehalfOfUserId) return null;+ // The assignee acting on its own task is the ordinary case, not a cross-issue write.+ if (issueAssigneeAgentId && authorAgentId === issueAssigneeAgentId) return null;+ // Falls back to "the responsible user" so the chip never shows a raw id.+ return { userName: responsibleUserLabel(resolveUserLabel?.(onBehalfOfUserId)) };+}diff --git a/ui/src/lib/issue-change-receipt.test.ts b/ui/src/lib/issue-change-receipt.test.tsnew file mode 100644index 0000000000..b7d43c447a--- /dev/null+++ b/ui/src/lib/issue-change-receipt.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from "vitest";++import {+ formatIssueChangeValue,+ issueAuthorizationReasonLabel,+ issueChangeFieldLabel,+ readIssueChangeReceipt,+} from "./issue-change-receipt";++describe("issueChangeFieldLabel", () => {+ it("uses curated labels for id-bearing fields", () => {+ expect(issueChangeFieldLabel("assigneeAgentId")).toBe("Assignee");+ expect(issueChangeFieldLabel("blockedByIssueIds")).toBe("Blockers");+ expect(issueChangeFieldLabel("workMode")).toBe("Work mode");+ });++ it("humanizes unknown camelCase and snake_case fields", () => {+ expect(issueChangeFieldLabel("status")).toBe("Status");+ expect(issueChangeFieldLabel("someNewField")).toBe("Some new field");+ expect(issueChangeFieldLabel("some_new_field")).toBe("Some new field");+ });+});++describe("formatIssueChangeValue", () => {+ it("renders empty values as 'none' rather than blank", () => {+ expect(formatIssueChangeValue(null)).toBe("none");+ expect(formatIssueChangeValue(undefined)).toBe("none");+ expect(formatIssueChangeValue("")).toBe("none");+ expect(formatIssueChangeValue(" ")).toBe("none");+ expect(formatIssueChangeValue([])).toBe("none");+ });++ it("humanizes enum-ish values", () => {+ expect(formatIssueChangeValue("in_progress")).toBe("in progress");+ expect(formatIssueChangeValue("high")).toBe("high");+ });++ it("renders booleans and numbers plainly", () => {+ expect(formatIssueChangeValue(true)).toBe("yes");+ expect(formatIssueChangeValue(false)).toBe("no");+ expect(formatIssueChangeValue(0)).toBe("0");+ expect(formatIssueChangeValue(3)).toBe("3");+ });++ it("resolves agent and user ids to names when a directory is available", () => {+ expect(formatIssueChangeValue("3108ef8e-5ed0-41d9-b561-6b41c41b8545", {+ field: "assigneeAgentId",+ resolveAgentLabel: () => "ClaudeCoder",+ })).toBe("ClaudeCoder");++ expect(formatIssueChangeValue("user-1", {+ field: "responsibleUserId",+ resolveUserLabel: () => "Dotta",+ })).toBe("Dotta");+ });++ it("shortens unresolved uuids instead of printing them whole", () => {+ expect(formatIssueChangeValue("3108ef8e-5ed0-41d9-b561-6b41c41b8545", {+ field: "assigneeAgentId",+ })).toBe("3108ef8e");+ });++ it("summarizes arrays by count past a scannable length", () => {+ expect(formatIssueChangeValue(["a", "b"])).toBe("a, b");+ expect(formatIssueChangeValue(["a", "b", "c", "d"])).toBe("4 items");+ expect(formatIssueChangeValue([{ a: 1 }])).toBe("1 items");+ });++ it("truncates long free text", () => {+ const long = "x".repeat(200);+ const formatted = formatIssueChangeValue(long);+ expect(formatted.endsWith("…")).toBe(true);+ expect(formatted.length).toBeLessThan(long.length);+ });++ it("reports structural objects as 'updated'", () => {+ expect(formatIssueChangeValue({ mode: "isolated_workspace" })).toBe("updated");+ });+});++describe("readIssueChangeReceipt", () => {+ it("turns a change receipt into sorted display rows", () => {+ const rows = readIssueChangeReceipt({+ changes: {+ status: { from: "todo", to: "in_progress" },+ priority: { from: "medium", to: "high" },+ },+ });++ expect(rows.map((row) => row.label)).toEqual(["Priority", "Status"]);+ expect(rows[1]).toMatchObject({+ field: "status",+ from: "todo",+ to: "in progress",+ truncated: false,+ });+ });++ it("flags server-truncated long text", () => {+ const rows = readIssueChangeReceipt({+ changes: { description: { from: "old text", to: "new text", updated: true } },+ });+ expect(rows[0]).toMatchObject({ label: "Description", truncated: true });+ });++ it("returns nothing for events without a receipt", () => {+ expect(readIssueChangeReceipt(null)).toEqual([]);+ expect(readIssueChangeReceipt(undefined)).toEqual([]);+ expect(readIssueChangeReceipt({})).toEqual([]);+ // Older activity rows carried no `changes` key at all.+ expect(readIssueChangeReceipt({ status: "done" })).toEqual([]);+ });++ it("ignores malformed change entries instead of throwing", () => {+ const rows = readIssueChangeReceipt({+ changes: {+ status: { from: "todo", to: "done" },+ bogus: "not-an-entry",+ alsoBogus: { from: "only-from" },+ },+ });+ expect(rows).toHaveLength(1);+ expect(rows[0].field).toBe("status");+ });++ it("survives a non-object changes value", () => {+ expect(readIssueChangeReceipt({ changes: "nope" })).toEqual([]);+ expect(readIssueChangeReceipt({ changes: ["nope"] })).toEqual([]);+ });+});++describe("issueAuthorizationReasonLabel", () => {+ it("explains the default-open rule in words", () => {+ expect(issueAuthorizationReasonLabel("allow_visible_issue_write"))+ .toBe("default-open write on a visible task");+ expect(issueAuthorizationReasonLabel("allow_board_actor")).toBe("board actor");+ });++ it("degrades unknown reasons rather than hiding them", () => {+ expect(issueAuthorizationReasonLabel("some_future_reason")).toBe("some future reason");+ });++ it("returns null when no reason was recorded", () => {+ expect(issueAuthorizationReasonLabel(null)).toBeNull();+ expect(issueAuthorizationReasonLabel(undefined)).toBeNull();+ expect(issueAuthorizationReasonLabel(" ")).toBeNull();+ });+});diff --git a/ui/src/lib/issue-change-receipt.ts b/ui/src/lib/issue-change-receipt.tsnew file mode 100644index 0000000000..7f58a2c231--- /dev/null+++ b/ui/src/lib/issue-change-receipt.ts@@ -0,0 +1,185 @@+import type { IssueChangeReceiptEntry } from "@paperclipai/shared";++/**+ * Read + format the field-level change receipts carried on an `issue.updated`+ * activity event (the open cross-task write design (audit), built on the field-change receipts the API already records).+ *+ * Every issue PATCH — agent and board alike — must leave an auditable record of+ * who changed what, when, and under which authorization. The server writes that+ * receipt; this module turns it into something a human can scan in the activity+ * stream without opening the audit log.+ *+ * The server already drops `updatedAt` and truncates long text (flagging it with+ * `updated: true`), so this module renders what it is given rather than+ * re-deciding what is interesting.+ */++/** Field names whose raw ids carry no meaning in a scannable summary. */+const FIELD_LABELS: Record<string, string> = {+ assigneeAgentId: "Assignee",+ assigneeUserId: "Assignee (user)",+ responsibleUserId: "Responsible user",+ blockedByIssueIds: "Blockers",+ labelIds: "Labels",+ parentId: "Parent",+ projectId: "Project",+ goalId: "Goal",+ workMode: "Work mode",+ billingCode: "Billing code",+ checkoutRunId: "Checkout run",+ executionRunId: "Execution run",+ hiddenAt: "Hidden",+ startedAt: "Started",+ completedAt: "Completed",+ cancelledAt: "Cancelled",+ requestDepth: "Request depth",+ sourceTrust: "Source trust",+ executionPolicy: "Execution policy",+ executionWorkspaceId: "Execution workspace",+ projectWorkspaceId: "Project workspace",+};++/** Human label for a changed field, e.g. `assigneeAgentId` → "Assignee". */+export function issueChangeFieldLabel(field: string): string {+ const known = FIELD_LABELS[field];+ if (known) return known;+ // camelCase / snake_case → "Sentence case".+ const spaced = field+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/_/g, " ")+ .toLowerCase()+ .trim();+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);+}++const VALUE_PREVIEW_BUDGET = 72;++/**+ * Render one side of a change for display. Never returns an empty string, so a+ * receipt row always reads as "from → to" rather than trailing into nothing.+ */+export function formatIssueChangeValue(+ value: unknown,+ options: { resolveAgentLabel?: (id: string) => string | null | undefined;+ resolveUserLabel?: (id: string) => string | null | undefined;+ field?: string } = {},+): string {+ if (value === null || value === undefined || value === "") return "none";+ if (typeof value === "boolean") return value ? "yes" : "no";+ if (typeof value === "number") return String(value);++ if (Array.isArray(value)) {+ if (value.length === 0) return "none";+ const strings = value.filter((entry): entry is string => typeof entry === "string");+ if (strings.length !== value.length) return `${value.length} items`;+ return strings.length <= 3+ ? strings.map((id) => shortenId(id)).join(", ")+ : `${strings.length} items`;+ }++ if (value instanceof Date) return value.toLocaleString();++ if (typeof value === "string") {+ const trimmed = value.trim();+ if (!trimmed) return "none";+ // Ids resolve to names when the directory is loaded; otherwise they shorten.+ const resolved = options.field?.toLowerCase().includes("agent")+ ? options.resolveAgentLabel?.(trimmed)+ : options.field?.toLowerCase().includes("user")+ ? options.resolveUserLabel?.(trimmed)+ : null;+ if (resolved) return resolved;+ if (isIsoTimestamp(trimmed)) return new Date(trimmed).toLocaleString();+ if (looksLikeId(trimmed)) return shortenId(trimmed);+ const humanized = trimmed.includes(" ") ? trimmed : trimmed.replace(/_/g, " ");+ return truncate(humanized);+ }++ // Objects (execution policy, workspace settings) are structural — the receipt+ // records that they moved, and the audit log holds the full value.+ return "updated";+}++function truncate(value: string): string {+ const chars = Array.from(value);+ if (chars.length <= VALUE_PREVIEW_BUDGET) return value;+ return `${chars.slice(0, VALUE_PREVIEW_BUDGET).join("")}…`;+}++function isIsoTimestamp(value: string): boolean {+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value) && !Number.isNaN(Date.parse(value));+}++function looksLikeId(value: string): boolean {+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);+}++function shortenId(value: string): string {+ return looksLikeId(value) ? value.slice(0, 8) : truncate(value);+}++export interface IssueChangeReceiptRow {+ field: string;+ label: string;+ from: string;+ to: string;+ /** Server flagged the values as truncated previews of long text. */+ truncated: boolean;+}++function isChangeEntry(value: unknown): value is IssueChangeReceiptEntry {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && "from" in (value as object) && "to" in (value as object);+}++/**+ * Parse `details.changes` off an activity event into display rows. Returns an+ * empty array for events with no receipt (older rows, non-PATCH actions), so+ * callers can render nothing without special-casing.+ */+export function readIssueChangeReceipt(+ details: Record<string, unknown> | null | undefined,+ options: Parameters<typeof formatIssueChangeValue>[1] = {},+): IssueChangeReceiptRow[] {+ const changes = details?.changes;+ if (!changes || typeof changes !== "object" || Array.isArray(changes)) return [];++ const rows: IssueChangeReceiptRow[] = [];+ for (const [field, entry] of Object.entries(changes as Record<string, unknown>)) {+ if (!isChangeEntry(entry)) continue;+ rows.push({+ field,+ label: issueChangeFieldLabel(field),+ from: formatIssueChangeValue(entry.from, { ...options, field }),+ to: formatIssueChangeValue(entry.to, { ...options, field }),+ truncated: entry.updated === true,+ });+ }+ // Stable, scannable order regardless of JSON key order (jsonb reorders keys).+ return rows.sort((a, b) => a.label.localeCompare(b.label));+}++/** Authorization reasons, as recorded by the server's write-policy decision. */+const AUTHORIZATION_REASON_LABELS: Record<string, string> = {+ allow_visible_issue_write: "default-open write on a visible task",+ allow_scoped_agent_write: "scoped agent write",+ allow_board_actor: "board actor",+ allow_self: "own task",+ allow_issue_mention_grant: "mention grant",+ allow_direct_parent_report: "direct parent report",+ allow_low_trust_boundary: "low-trust boundary allowance",+ allow_explicit_grant: "explicit permission grant",+ allow_instance_admin: "instance admin",+ allow_local_board: "local board",+ internal_agent_write: "internal agent write",+};++/**+ * Human phrasing for the authorization reason on a write receipt. Unknown+ * reasons degrade to their humanized code rather than disappearing — an+ * unexplained write is worse than an ugly one.+ */+export function issueAuthorizationReasonLabel(reason: string | null | undefined): string | null {+ const trimmed = reason?.trim();+ if (!trimmed) return null;+ return AUTHORIZATION_REASON_LABELS[trimmed] ?? trimmed.replace(/_/g, " ");+}diff --git a/ui/src/lib/issue-chat-messages.ts b/ui/src/lib/issue-chat-messages.tsindex 4329399164..7246201183 100644--- a/ui/src/lib/issue-chat-messages.ts+++ b/ui/src/lib/issue-chat-messages.ts@@ -512,6 +512,8 @@ function createCommentMessage(args: {authorType: effectiveCommentAuthorType(comment),authorAgentId,authorUserId: comment.authorUserId,+ // Responsible user this agent comment rode the authority of (the open cross-task write design (attribution)).+ onBehalfOfUserId: comment.onBehalfOfUserId ?? null,companyId: companyId ?? comment.companyId,projectId: projectId ?? null,runId: effectiveCommentRunId(comment),diff --git a/ui/src/lib/issue-write-denial-activity.ts b/ui/src/lib/issue-write-denial-activity.tsnew file mode 100644index 0000000000..6ba2988b92--- /dev/null+++ b/ui/src/lib/issue-write-denial-activity.ts@@ -0,0 +1,33 @@+import type { IssueWriteDenialCode, IssueWriteDenialContext } from "@paperclipai/shared";++/**+ * Map the activity events the server writes when it refuses an issue write onto+ * the shared denial copy contract (the open cross-task write design (failure UX)).+ *+ * These are the denials that leave a durable trace on the task, so they are the+ * ones the board can read after the fact — the agent already saw the same words+ * in the API error body.+ */+const DENIAL_ACTIVITY_CODES: Record<string, IssueWriteDenialCode> = {+ "issue.cross_issue_influence_cap_rejected": "cross_issue_influence_cap_exceeded",+ "issue.attribution_spoof_rejected": "issue_write_attribution_spoof_rejected",+};++export function issueWriteDenialForActivity(+ action: string,+ details: Record<string, unknown> | null | undefined,+ labels: Pick<IssueWriteDenialContext, "actorLabel" | "assigneeLabel" | "responsibleUserName"> = {},+): { code: IssueWriteDenialCode; context: IssueWriteDenialContext } | null {+ const code = DENIAL_ACTIVITY_CODES[action];+ if (!code) return null;+ return {+ code,+ context: {+ ...labels,+ issueIdentifier: typeof details?.identifier === "string" ? details.identifier : null,+ cap: typeof details?.cap === "number" ? details.cap : null,+ count: typeof details?.count === "number" ? details.count : null,+ enforceAt: typeof details?.enforceAt === "string" ? details.enforceAt : null,+ },+ };+}diff --git a/ui/src/pages/CrossIssueCollaborationUxLab.tsx b/ui/src/pages/CrossIssueCollaborationUxLab.tsxnew file mode 100644index 0000000000..ab8c3bb401--- /dev/null+++ b/ui/src/pages/CrossIssueCollaborationUxLab.tsx@@ -0,0 +1,284 @@+import type { ReactNode } from "react";+import { ISSUE_WRITE_DENIAL_CODES } from "@paperclipai/shared";+import { Avatar, AvatarFallback } from "@/components/ui/avatar";+import { Card } from "@/components/ui/card";+import { CommentAttributionChip } from "@/components/CommentAttributionChip";+import { IssueFieldChangeReceipt } from "@/components/IssueFieldChangeReceipt";+import { IssueWriteDenialNotice } from "@/components/IssueWriteDenialNotice";+import { Identity } from "@/components/Identity";+import { cn } from "@/lib/utils";++/**+ * UX lab for the three surfaces that make open+ * cross-issue collaboration legible — the "for {user}" attribution chip, the+ * field-edit audit receipt in the activity stream, and actionable denial copy.+ *+ * Route: /ux-lab/cross-issue-collaboration. Public (no session) so the states+ * can be captured for UX review without seeding a live thread.+ */++function LabSection({+ index,+ title,+ description,+ children,+ columns = 2,+}: {+ index: string;+ title: string;+ description: string;+ children: ReactNode;+ columns?: 1 | 2;+}) {+ return (+ <section className="rounded-2xl border border-border/70 bg-background/85 p-5 shadow-sm">+ <div className="mb-4">+ <div className="text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">+ {index}+ </div>+ <h2 className="mt-1 text-base font-semibold text-foreground">{title}</h2>+ <p className="mt-1 text-sm text-muted-foreground">{description}</p>+ </div>+ <div className={cn("grid gap-4", columns === 2 && "lg:grid-cols-2")}>{children}</div>+ </section>+ );+}++function Frame({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div className="space-y-2">+ <div className="text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">+ {label}+ </div>+ <Card className="block border-border/60 p-3">{children}</Card>+ </div>+ );+}++/** A faithful copy of an agent comment bubble header + body (IssueChatThread.tsx). */+function AgentCommentBubble({+ authorName,+ onBehalfOf,+ body,+}: {+ authorName: string;+ onBehalfOf?: string | null;+ body: string;+}) {+ return (+ <div className="flex flex-col items-start py-1.5">+ <div className="mb-1 flex items-center gap-1.5 px-1">+ <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">+ <Avatar size="sm" className="size-5">+ <AvatarFallback className="text-(length:--text-nano)">+ {authorName.slice(0, 2).toUpperCase()}+ </AvatarFallback>+ </Avatar>+ </span>+ <span className="text-sm font-medium text-foreground">{authorName}</span>+ {onBehalfOf ? (+ <CommentAttributionChip agentName={authorName} userName={onBehalfOf} />+ ) : null}+ </div>+ <div className="min-w-0 max-w-(--pct-85) break-words border border-border bg-card px-3 py-2 text-sm text-foreground [border-radius:14px_14px_14px_4px]">+ {body}+ </div>+ </div>+ );+}++/** A faithful copy of an activity row in the issue run ledger (IssueDetail.tsx). */+function ActivityRow({+ actorName,+ verb,+ children,+}: {+ actorName: string;+ verb: string;+ children?: ReactNode;+}) {+ return (+ <div className="space-y-1.5 rounded-lg border border-border/60 px-3 py-2 text-xs text-muted-foreground">+ <div className="flex items-center gap-1.5">+ <Identity name={actorName} size="sm" />+ <span>{verb}</span>+ <span className="ml-auto shrink-0">2m ago</span>+ </div>+ {children}+ </div>+ );+}++const AGENT_NAMES = new Map([+ ["3108ef8e-5ed0-41d9-b561-6b41c41b8545", "ClaudeCoder"],+ ["6670e11b-91d3-4429-82e0-436b88b51808", "UXDesigner"],+]);++export function CrossIssueCollaborationUxLab() {+ const resolveAgentLabel = (id: string) => AGENT_NAMES.get(id) ?? null;+ const resolveUserLabel = (id: string) => (id === "user-dotta" ? "Dotta" : null);++ return (+ <div className="min-h-screen bg-muted/20 p-6">+ <div className="mx-auto max-w-5xl space-y-6">+ <header>+ <div className="text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">+ Open cross-task collaboration+ </div>+ <h1 className="mt-1 text-xl font-semibold text-foreground">+ Open cross-task collaboration — attribution, audit, and denial copy+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Agents may now write to any task they can read. These are the three surfaces that keep+ that legible: whose authority a comment rode, what an edit changed, and — when a write+ is refused — which boundary fired and what to do instead.+ </p>+ </header>++ <LabSection+ index="1 · Attribution chip (plan §3a)"+ title="“Fable · for Dotta” on a cross-task agent comment"+ description="An agent commenting on a task it is not assigned to names the responsible user whose authority it rode. The assignee's own comments stay unchipped — that is the ordinary case, and chipping every bubble would be noise."+ >+ <Frame label="Assignee's own comment — no chip">+ <AgentCommentBubble+ authorName="CodexCoder"+ body="Rebased onto master and re-ran the containment suite; all green."+ />+ </Frame>+ <Frame label="Cross-task comment — chipped">+ <AgentCommentBubble+ authorName="Fable"+ onBehalfOf="Dotta"+ body="Dotta asked me to flag that the retry window here overlaps TASK-482. Worth a look before you close this."+ />+ </Frame>+ <Frame label="Responsible user not in the loaded directory">+ <AgentCommentBubble+ authorName="Fable"+ onBehalfOf="the responsible user"+ body="Falls back to a generic label rather than printing a raw user id."+ />+ </Frame>+ <Frame label="Long user name truncates in the chip">+ <AgentCommentBubble+ authorName="Fable"+ onBehalfOf="Alexandra Konstantinopoulos-Whitfield"+ body="The chip caps its width and truncates; the tooltip carries the full name."+ />+ </Frame>+ </LabSection>++ <LabSection+ index="2 · Field-edit audit receipt (plan §3b)"+ title="Every PATCH says who changed what, and under which authorization"+ description="Required for agent and board edits alike. Before/after per field, the responsible user behind the write, and the authorization reason that let it through."+ >+ <Frame label="Cross-task agent edit">+ <ActivityRow actorName="Fable" verb="changed the status from todo to in progress">+ <IssueFieldChangeReceipt+ event={{+ action: "issue.updated",+ responsibleUserId: "user-dotta",+ details: {+ authorizationReason: "allow_visible_issue_write",+ changes: {+ status: { from: "todo", to: "in_progress" },+ priority: { from: "medium", to: "high" },+ },+ },+ }}+ resolveAgentLabel={resolveAgentLabel}+ resolveUserLabel={resolveUserLabel}+ />+ </ActivityRow>+ </Frame>+ <Frame label="Board (human) edit — audited the same way">+ <ActivityRow actorName="Dotta" verb="updated the issue">+ <IssueFieldChangeReceipt+ event={{+ action: "issue.updated",+ responsibleUserId: "user-dotta",+ details: {+ authorizationReason: "allow_board_actor",+ changes: {+ assigneeAgentId: {+ from: "3108ef8e-5ed0-41d9-b561-6b41c41b8545",+ to: "6670e11b-91d3-4429-82e0-436b88b51808",+ },+ description: { from: "Old brief…", to: "New brief…", updated: true },+ },+ },+ }}+ resolveAgentLabel={resolveAgentLabel}+ resolveUserLabel={resolveUserLabel}+ />+ </ActivityRow>+ </Frame>+ <Frame label="Reassignment, blockers, and work mode in one write">+ <ActivityRow actorName="CTO" verb="updated the issue">+ <IssueFieldChangeReceipt+ event={{+ action: "issue.updated",+ responsibleUserId: "user-dotta",+ details: {+ authorizationReason: "allow_visible_issue_write",+ changes: {+ blockedByIssueIds: { from: [], to: ["TASK-491", "TASK-492"] },+ workMode: { from: "planning", to: "standard" },+ assigneeAgentId: {+ from: null,+ to: "3108ef8e-5ed0-41d9-b561-6b41c41b8545",+ },+ },+ },+ }}+ resolveAgentLabel={resolveAgentLabel}+ resolveUserLabel={resolveUserLabel}+ />+ </ActivityRow>+ </Frame>+ <Frame label="Older activity row — no receipt, renders unchanged">+ <ActivityRow actorName="CodexCoder" verb="checked out the issue" />+ </Frame>+ </LabSection>++ <LabSection+ index="3 · Actionable denial copy (plan §6)"+ title="Every wall names the boundary, who can act, and the sanctioned path"+ description="A real incident burned a full detour discovering a workaround behind an opaque 403. These are all the ways an issue write can now be refused — the same copy the API error body carries."+ columns={1}+ >+ <Frame label="Before — what the incident actually saw">+ <div className="text-xs">+ <span className="text-red-600 dark:text-red-400">+ 403 Forbidden: Issue is outside this actor's authorization boundary+ </span>+ <p className="mt-1 text-muted-foreground">+ No boundary named, nobody named, no path forward. The workaround (create a child+ issue) had to be discovered by trial and error.+ </p>+ </div>+ </Frame>+ {ISSUE_WRITE_DENIAL_CODES.map((code) => (+ <Frame key={code} label={`After — ${code}`}>+ <IssueWriteDenialNotice+ code={code}+ context={{+ actorLabel: "Fable",+ assigneeLabel: "CodexCoder",+ responsibleUserName: "Dotta",+ issueIdentifier: "TASK-482",+ cap: 20,+ count: 21,+ }}+ />+ </Frame>+ ))}+ </LabSection>+ </div>+ </div>+ );+}++export default CrossIssueCollaborationUxLab;diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex f30deedbab..e87f6afb90 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -111,6 +111,9 @@ import type { MarkdownExternalReferenceMap } from "../components/MarkdownBody";import { IssuesList } from "../components/IssuesList";import { AgentIcon } from "../components/AgentIconPicker";import { IssueReferenceActivitySummary } from "../components/IssueReferenceActivitySummary";+import { IssueFieldChangeReceipt } from "../components/IssueFieldChangeReceipt";+import { IssueWriteDenialNotice } from "../components/IssueWriteDenialNotice";+import { issueWriteDenialForActivity } from "../lib/issue-write-denial-activity";import { IssueRelatedWorkPanel } from "../components/IssueRelatedWorkPanel";import {IssueMonitorBanner,@@ -874,6 +877,8 @@ type IssueDetailChatTabProps = {companyId: string;projectId: string | null;issueStatus: Issue["status"];+ /** Marks cross-issue agent comments in the thread (the open cross-task write design (attribution)). */+ issueAssigneeAgentId: Issue["assigneeAgentId"];issueWorkMode: IssueWorkMode;executionRunId: string | null;blockedBy: Issue["blockedBy"];@@ -980,6 +985,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({projectId,issueWorkMode,issueStatus,+ issueAssigneeAgentId,executionRunId,blockedBy,liveIssueIds,@@ -1259,6 +1265,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({companyId={companyId}projectId={projectId}issueStatus={issueStatus}+ issueAssigneeAgentId={issueAssigneeAgentId}agentMap={agentMap}currentUserId={currentUserId}userLabelMap={userLabelMap}@@ -1540,6 +1547,24 @@ function IssueDetailActivityTab({<span className="ml-auto shrink-0">{relativeTime(evt.createdAt)}</span></div><IssueReferenceActivitySummary event={evt} />+ {/* Field-level who/what/why receipt for agent and board edits alike. */}+ <IssueFieldChangeReceipt+ event={evt}+ resolveAgentLabel={(agentId) => agentMap.get(agentId)?.name ?? null}+ resolveUserLabel={(userId) => userProfileMap.get(userId)?.label ?? null}+ />+ {/* A refused write explains itself here, not just in the API error. */}+ {(() => {+ const denial = issueWriteDenialForActivity(evt.action, evt.details, {+ actorLabel: evt.agentId ? agentMap.get(evt.agentId)?.name ?? null : null,+ responsibleUserName: evt.responsibleUserId+ ? userProfileMap.get(evt.responsibleUserId)?.label ?? null+ : null,+ });+ return denial ? (+ <IssueWriteDenialNotice code={denial.code} context={denial.context} />+ ) : null;+ })()}</div>);}}@@ -4929,6 +4954,7 @@ export function IssueDetail() {companyId={issue.companyId}projectId={issue.projectId ?? null}issueStatus={issue.status}+ issueAssigneeAgentId={issue.assigneeAgentId}issueWorkMode={issue.workMode ?? "standard"}executionRunId={issue.executionRunId ?? null}blockedBy={issue.blockedBy ?? []}