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
fix: give commentary its own default read permission (#16903)
Dottae5927e1db909
diff --git a/doc/DATABASE.md b/doc/DATABASE.mdindex 829ef7fe90..d7d4577f53 100644--- a/doc/DATABASE.md+++ b/doc/DATABASE.md@@ -765,7 +765,9 @@ Project `privacy_owner_user_id` records who may manage its audience independentlThe Audit viewer uses the existing company/kind/created index.List reads select bounded previews; details load a single full body. Both readsand list counts apply company and source-task visibility. The viewer requires-no experimental toggle or commentary schema migration.+no experimental toggle. A permission-only migration grants `commentary:view` to+existing active human company members, including viewers, without changing+existing grants or the commentary schema.`agent_commentary` stores company-scoped, attributed complaints and suggestionsas free-form text in the instance database. Legacy agents use the defaultdiff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.mdindex 376e58a648..ce6dbbe985 100644--- a/doc/SPEC-implementation.md+++ b/doc/SPEC-implementation.md@@ -2253,7 +2253,13 @@ their existing operator recovery requirements.Audit → Commentary is a board-only page with agent/type filters, text search,50-message pages and full-message dialogs. Filters, page offsets and selectedmessages have shareable URLs. Read endpoints require company membership,-`audit:view_agent_actions` and source-task visibility.+`commentary:view` and source-task visibility. All human company roles, including+viewers, receive this permission by default. An upgrade migration grants it to+existing active human members while preserving existing commentary grants.+Human invitation approval adds the commentary default when a saved grant list+omits it, including invitations created before the upgrade, and preserves explicit scopes.+The separate `audit:view_agent_actions` permission continues to govern agent-action+audit reads, detailed audit filters and CSV exports.`agent_commentary` stores company-scoped, attributed complaints and suggestionsas free-form text in the instance database. Legacy agents use the defaultdiff --git a/doc/SPEC.md b/doc/SPEC.mdindex 4bf2bf192d..083796c20d 100644--- a/doc/SPEC.md+++ b/doc/SPEC.md@@ -775,8 +775,9 @@ opt-in plugin. See [the experimental contract](connections/AI-CONNECTION-ROUTERSThe Audit → Commentary tab exposes searchable suggestions and complaints,with agent/type filters, message previews and full attributed context. The viewer-preserves company, audit-permission and task-privacy boundaries independently-of the agent submission path.+preserves company, commentary-permission and task-privacy boundaries independently+of the agent submission path. All human company members can read commentary by+default, including viewers, without receiving agent-action audit access.`agent_commentary` stores company-scoped, attributed complaints and suggestionsas free-form text in the instance database. Legacy agents use the defaultdiff --git a/doc/agent-commentary.md b/doc/agent-commentary.mdindex 8aa6c2072c..b73a39ae10 100644--- a/doc/agent-commentary.md+++ b/doc/agent-commentary.md@@ -75,7 +75,13 @@ URLs (`?entry=<message-id>` opens a message directly).The board-only read API is `GET /api/companies/:companyId/agent-commentary`(`agentId`, `kind`, `q`, `limit` up to 100, `offset`) and`GET /api/companies/:companyId/agent-commentary/:id`. Both require company access-and `audit:view_agent_actions`. Source-task privacy filters previews, counts and+and `commentary:view`. All human company roles, including viewers, receive this+permission by default. The upgrade migration grants it to existing active human+members without changing existing commentary grants. Human invitation approval+adds the default to saved grant lists that omit it, including older invitations,+while preserving an explicit commentary grant's scope. Commentary access does not+grant agent-action audit access, detailed audit filters or audit CSV exports;+those retain `audit:view_agent_actions`. Source-task privacy filters previews, counts anddetails. List results contain at most 280 charactersper message; the full body is loaded only on opening a message. Feedback whosesource task was deleted stays hidden, using the task binding retained on its run.diff --git a/maps/agent-access-map/activity.md b/maps/agent-access-map/activity.mdindex 8d1ca6ec7c..4ce0ea3e78 100644--- a/maps/agent-access-map/activity.md+++ b/maps/agent-access-map/activity.md@@ -175,7 +175,10 @@ API: `present` — `GET /api/companies/{companyId}/agent-commentary` andAgent access: `restricted` — the browsing API is board-only. Agent submissioncontinues through the existing POST and native submit tools.-Policy: Company membership, `audit:view_agent_actions`, and source-task visibility. Counts and previews+Policy: Company membership, `commentary:view`, and source-task visibility. All human company roles,+including viewers, receive the permission by default, with an upgrade grant for existing active human members.+Human invitation approval adds the default to older saved grant lists without widening existing scopes.+Agent-action audit access remains separate. Counts and previewsuse the same visibility predicate as full messages; cross-company IDs return 404.Feedback stays hidden after source-task deletion, even when its task foreign key clears.diff --git a/maps/feature-map/activity.md b/maps/feature-map/activity.mdindex 9827f2ff82..1833177cc1 100644--- a/maps/feature-map/activity.md+++ b/maps/feature-map/activity.md@@ -61,7 +61,8 @@ the routine rather than treating that component test as a reachable journey.Open Audit → Commentary (`/activity/commentary`). Search message text, filter by agent and suggestion/complaint,page through 50-message previews, and open a row to read the full message with its task/run links.Filters, page offsets and the selected entry are retained in the URL. Read access requires board company access and-`audit:view_agent_actions`; task privacy applies to previews, counts and full messages.+`commentary:view`, granted by default to all human company roles and backfilled for existing active+human members. Task privacy applies to previews, counts and full messages; agent-action audit access is separate.All Audit tab destinations resolve in both the classic and streamlined layouts.Storybook: [production page and message journeys](../../ui/storybook/stories/activity/agent-commentary.stories.tsx)diff --git a/packages/db/src/migrations/0359_commentary_view_human_defaults.sql b/packages/db/src/migrations/0359_commentary_view_human_defaults.sqlnew file mode 100644index 0000000000..f6d6234ab4--- /dev/null+++ b/packages/db/src/migrations/0359_commentary_view_human_defaults.sql@@ -0,0 +1,24 @@+INSERT INTO "principal_permission_grants" (+ "company_id",+ "principal_type",+ "principal_id",+ "permission_key",+ "scope",+ "granted_by_user_id"+)+SELECT+ "company_id",+ 'user',+ "principal_id",+ 'commentary:view',+ NULL,+ NULL+FROM "company_memberships"+WHERE "principal_type" = 'user'+ AND "status" = 'active'+ON CONFLICT (+ "company_id",+ "principal_type",+ "principal_id",+ "permission_key"+) DO NOTHING;diff --git a/packages/db/src/migrations/meta/0354_snapshot.json b/packages/db/src/migrations/meta/0359_snapshot.jsonsimilarity index 99%rename from packages/db/src/migrations/meta/0354_snapshot.jsonrename to packages/db/src/migrations/meta/0359_snapshot.jsonindex dc932d2c6b..981f0bb974 100644--- a/packages/db/src/migrations/meta/0354_snapshot.json+++ b/packages/db/src/migrations/meta/0359_snapshot.json@@ -1,6 +1,6 @@{- "id": "ab82fb6d-abee-4334-9723-8d9684319aaf",- "prevId": "c2924a97-9a78-4207-8e5b-dd3c2ef4560b",+ "id": "3b540468-0848-4a5d-a539-022ec5d0eb94",+ "prevId": "87e839fc-31a1-460b-84d0-e2e7b9d9e546","version": "7","dialect": "postgresql","tables": {@@ -15075,6 +15075,110 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.company_observability": {+ "name": "company_observability",+ "schema": "",+ "columns": {+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "destination": {+ "name": "destination",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "capture": {+ "name": "capture",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "credentials_secret_id": {+ "name": "credentials_secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "header_names": {+ "name": "header_names",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "last_test": {+ "name": "last_test",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "company_observability_company_id_companies_id_fk": {+ "name": "company_observability_company_id_companies_id_fk",+ "tableFrom": "company_observability",+ "columnsFrom": [+ "company_id"+ ],+ "tableTo": "companies",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "company_observability_credentials_secret_id_company_secrets_id_fk": {+ "name": "company_observability_credentials_secret_id_company_secrets_id_fk",+ "tableFrom": "company_observability",+ "columnsFrom": [+ "credentials_secret_id"+ ],+ "tableTo": "company_secrets",+ "columnsTo": [+ "id"+ ],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },"public.company_onboarding_seeds": {"name": "company_onboarding_seeds","schema": "",diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex 974119e8df..30391799d3 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -2500,6 +2500,13 @@"when": 1792444400633,"tag": "0358_issue_assignment_status_version","breakpoints": true+ },+ {+ "idx": 359,+ "version": "7",+ "when": 1792445691138,+ "tag": "0359_commentary_view_human_defaults",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.tsindex 9ddd40d90b..75e600397e 100644--- a/packages/shared/src/constants.ts+++ b/packages/shared/src/constants.ts@@ -1011,6 +1011,7 @@ export const PERMISSION_KEYS = ["tools:manage_profiles","tools:view_audit","audit:view_agent_actions",+ "commentary:view","tools:use","tools:manage_runtime","inbox:manage",diff --git a/server/src/__tests__/agent-action-audit-routes.test.ts b/server/src/__tests__/agent-action-audit-routes.test.tsindex 332720a8a2..4791eeeaaa 100644--- a/server/src/__tests__/agent-action-audit-routes.test.ts+++ b/server/src/__tests__/agent-action-audit-routes.test.ts@@ -21,9 +21,9 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } froconst support = await getEmbeddedPostgresTestSupport();const describePostgres = support.supported ? describe : describe.skip;type Db = ReturnType<typeof createDb>;+let activityRoutes: typeof import("../routes/activity.js").activityRoutes;async function createApp(db: Db, actor: Express.Request["actor"]) {- const { activityRoutes } = await import("../routes/activity.js");const app = express();app.use(express.json());app.use((req, _res, next) => {@@ -42,9 +42,10 @@ describePostgres("agent action audit routes", () => {let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;beforeAll(async () => {+ ({ activityRoutes } = await import("../routes/activity.js"));tempDb = await startEmbeddedPostgresTestDatabase("paperclip-agent-action-audit-");db = createDb(tempDb.connectionString);- }, 20_000);+ });afterEach(async () => {await db.delete(activityLog);@@ -151,6 +152,23 @@ describePostgres("agent action audit routes", () => {]).returning();}+ it("keeps agent audit reads, filters and CSV exports closed to commentary-only viewers", async () => {+ const { company } = await seed();+ const userId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId: company.id, principalType: "user", principalId: userId, membershipRole: "viewer", status: "active",+ });+ await db.insert(principalPermissionGrants).values({+ companyId: company.id, principalType: "user", principalId: userId, permissionKey: "commentary:view",+ });+ const app = await createApp(db, { type: "board", userId, companyIds: [company.id], source: "session" });+ const url = `/api/companies/${company.id}/audit/agent-actions`;+ for (const path of [url, `${url}?actorScope=all&action=issue`, `${url}.csv`]) {+ expect((await request(app).get(path).expect(403)).body.error).toContain("audit:view_agent_actions");+ }+ expect((await request(app).get(`${url}?actorScope=all`).expect(200)).body.accessTier).toBe("basic");+ });+it("denies agents and board users without the audit permission", async () => {const { company, agent } = await seed();const agentResponse = await request(await createApp(db, {diff --git a/server/src/__tests__/agent-commentary-reader.test.ts b/server/src/__tests__/agent-commentary-reader.test.tsindex 0ac24dbb27..d29c8ce546 100644--- a/server/src/__tests__/agent-commentary-reader.test.ts+++ b/server/src/__tests__/agent-commentary-reader.test.ts@@ -9,6 +9,8 @@ import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.jimport { agentCommentaryReader } from "../services/agent-commentary-reader.js";import { agentCommentaryRoutes } from "../routes/agent-commentary.js";import { errorHandler } from "../middleware/error-handler.js";+import { accessService } from "../services/access.js";+import { grantsForHumanRole } from "../services/company-member-roles.js";describe("agent commentary browsing", () => {let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;@@ -113,7 +115,7 @@ describe("agent commentary browsing", () => {expect((await reader.list(companyId, query({ q: "Deleted private task feedback" }), eq(issues.id, visibleTaskId))).total).toBe(0);});- it("enforces board membership, audit permission and filter bounds at the HTTP boundary", async () => {+ it("enforces board membership, commentary permission and filter bounds at the HTTP boundary", async () => {let actor: Record<string, unknown> = { type: "board", source: "local_implicit", userId: "operator" };const app = express();app.use((req, _res, next) => { req.actor = actor as typeof req.actor; next(); });@@ -130,11 +132,39 @@ describe("agent commentary browsing", () => {expect((await request(app).get(url)).status).toBe(403);expect((await request(app).get(`${url}/${firstId}`)).status).toBe(403);actor = { type: "board", source: "session", userId: "viewer", companyIds: [companyId] };- expect((await request(app).get(url)).status).toBe(403);+ const denied = await request(app).get(url).expect(403);+ expect(denied.body.error).toContain("commentary:view");+ await request(app).get(`${url}/${firstId}`).expect(403);actor = { type: "board", source: "session", userId: "operator", isInstanceAdmin: true, companyIds: [foreignCompanyId] };expect((await request(app).get(url)).status).toBe(403);});- it("applies actual task privacy to HTTP previews, counts, searches and details for audit-authorized board users", async () => {+ it.each(["owner", "admin", "operator", "viewer"] as const)("lets a default %s read commentary independently of audit access", async (role) => {+ const userId = randomUUID();+ const access = accessService(db);+ await access.ensureMembership(companyId, "user", userId, role);+ await access.setPrincipalGrants(companyId, "user", userId, grantsForHumanRole(role), null);+ const app = express();+ app.use((req, _res, next) => {+ req.actor = { type: "board", source: "session", userId, companyIds: [companyId] };+ next();+ });+ app.use("/api", agentCommentaryRoutes(db));+ app.use(errorHandler);+ const url = `/api/companies/${companyId}/agent-commentary`;+ expect((await request(app).get(url).expect(200)).body.total).toBe(3);+ expect((await request(app).get(`${url}/${firstId}`).expect(200)).body.body).toBe(longBody);+ await expect(access.canUser(companyId, userId, "audit:view_agent_actions")).resolves.toBe(role === "operator");+ await request(app).get(`/api/companies/${foreignCompanyId}/agent-commentary`).expect(403);+ await request(app).get(`${url}/${foreignId}`).expect(404);++ await access.setPrincipalGrants(companyId, "user", userId, [+ { permissionKey: "audit:view_agent_actions", scope: null },+ ], null);+ expect((await request(app).get(url).expect(403)).body.error).toContain("commentary:view");+ await request(app).get(`${url}/${firstId}`).expect(403);+ });++ it("applies actual task privacy to HTTP previews, counts, searches and details for commentary-authorized board users", async () => {vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");const userId = randomUUID(), ownerId = randomUUID();await db.insert(authUsers).values([userId, ownerId].map((id) => ({@@ -145,7 +175,7 @@ describe("agent commentary browsing", () => {companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "viewer",});await db.insert(principalPermissionGrants).values({- companyId, principalType: "user", principalId: userId, permissionKey: "audit:view_agent_actions",+ companyId, principalType: "user", principalId: userId, permissionKey: "commentary:view",});await db.update(issues).set({ visibility: "private", privacyRootIssueId: privateTaskId, responsibleUserId: ownerId }).where(eq(issues.id, privateTaskId));const app = express();diff --git a/server/src/__tests__/commentary-permission-migration.test.ts b/server/src/__tests__/commentary-permission-migration.test.tsnew file mode 100644index 0000000000..02d0bc50fe--- /dev/null+++ b/server/src/__tests__/commentary-permission-migration.test.ts@@ -0,0 +1,53 @@+import { randomUUID } from "node:crypto";+import { readFile } from "node:fs/promises";+import { eq, sql } from "drizzle-orm";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { companies, companyMemberships, createDb, principalPermissionGrants } from "@paperclipai/db";+import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";++describe("commentary permission upgrade", () => {+ let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ let db: ReturnType<typeof createDb>;++ beforeAll(async () => {+ temporary = await startEmbeddedPostgresTestDatabase("paperclip-commentary-permission-");+ db = createDb(temporary.connectionString);+ }, 90_000);++ afterAll(async () => { await temporary?.cleanup(); });++ it("grants existing active humans commentary access once without widening audit or existing scopes", async () => {+ const companyId = randomUUID(), otherCompanyId = randomUUID();+ await db.insert(companies).values([+ { id: companyId, name: "Commentary upgrade", issuePrefix: "UPG" },+ { id: otherCompanyId, name: "Other company", issuePrefix: "OTH" },+ ]);+ const activeHumans = ["owner", "admin", "operator", "viewer", "member", null].map((membershipRole) => ({+ companyId, principalType: "user", principalId: randomUUID(), membershipRole, status: "active",+ }));+ const excluded = [+ { companyId, principalType: "user", principalId: randomUUID(), membershipRole: "viewer", status: "inactive" },+ { companyId, principalType: "agent", principalId: randomUUID(), membershipRole: "member", status: "active" },+ { companyId: otherCompanyId, principalType: "user", principalId: activeHumans[0].principalId, membershipRole: "owner", status: "inactive" },+ ];+ await db.insert(companyMemberships).values([...activeHumans, ...excluded]);+ const [existing] = await db.insert(principalPermissionGrants).values({+ companyId, principalType: "user", principalId: activeHumans[0].principalId,+ permissionKey: "commentary:view", scope: { agentIds: [randomUUID()] }, grantedByUserId: "custom-author",+ }).returning();+ const migration = await readFile(new URL(+ "../../../packages/db/src/migrations/0359_commentary_view_human_defaults.sql", import.meta.url,+ ), "utf8");+ await db.execute(sql.raw(migration));+ const first = await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));+ expect(first).toHaveLength(activeHumans.length);+ expect(first.every((grant) => grant.permissionKey === "commentary:view")).toBe(true);+ expect(first.map((grant) => grant.principalId).sort()).toEqual(activeHumans.map((member) => member.principalId).sort());+ expect(first.find((grant) => grant.id === existing.id)).toEqual(existing);+ expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, otherCompanyId))).toEqual([]);++ await db.execute(sql.raw(migration));+ const second = await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));+ expect(second.sort((a, b) => a.id.localeCompare(b.id))).toEqual(first.sort((a, b) => a.id.localeCompare(b.id)));+ });+});diff --git a/server/src/__tests__/invite-accept-existing-member.test.ts b/server/src/__tests__/invite-accept-existing-member.test.tsindex 8dc36cdc0b..0a7eb97cb5 100644--- a/server/src/__tests__/invite-accept-existing-member.test.ts+++ b/server/src/__tests__/invite-accept-existing-member.test.ts@@ -168,7 +168,7 @@ function createAppWithActor(db: Record<string, unknown>, actor: Record<string, ureturn app;}-function createDirectHumanInviteDbStub() {+function createDirectHumanInviteDbStub(defaultsPayload: Record<string, unknown> = { human: { role: "owner" } }) {const insertedValues: unknown[] = [];const updateValues: unknown[] = [];const invite = {@@ -177,7 +177,7 @@ function createDirectHumanInviteDbStub() {inviteType: "company_join",allowedJoinTypes: "human",tokenHash: "hash",- defaultsPayload: { human: { role: "owner" } },+ defaultsPayload,expiresAt: new Date("2027-03-10T00:00:00.000Z"),invitedByUserId: "inviter-user",revokedAt: null,@@ -427,6 +427,23 @@ describe("POST /invites/:token/accept", () => {);});+ it("grants commentary when accepting a pre-upgrade operator invite without widening its saved scopes", async () => {+ const legacyGrants = [+ { permissionKey: "tasks:assign", scope: { projectId: "project-1" } },+ { permissionKey: "audit:view_agent_actions", scope: null },+ ];+ const { db } = createDirectHumanInviteDbStub({ human: { role: "operator", grants: legacyGrants } });+ const app = createAppWithActor(db, {+ type: "board", source: "session", userId: "invitee-user", companyIds: [], memberships: [],+ });+ const res = await request(app).post("/api/invites/pcp_invite_test/accept").send({ requestType: "human" }).expect(202);+ expect(res.body.status).toBe("approved");+ expect(accessServiceMock.ensureMembership).toHaveBeenCalledWith("company-1", "user", "invitee-user", "operator", "active");+ expect(accessServiceMock.setPrincipalGrants).toHaveBeenCalledWith(+ "company-1", "user", "invitee-user", [...legacyGrants, { permissionKey: "commentary:view", scope: null }], "inviter-user",+ );+ });+it("replays a consumed human invite for the same user and repairs company access", async () => {const { db, updateValues } = createAcceptedHumanInviteReplayDbStub();const app = createAppWithActor(db, {diff --git a/server/src/__tests__/invite-join-grants.test.ts b/server/src/__tests__/invite-join-grants.test.tsindex e7b555f20c..95b257cb1f 100644--- a/server/src/__tests__/invite-join-grants.test.ts+++ b/server/src/__tests__/invite-join-grants.test.ts@@ -79,6 +79,7 @@ describe("human invite roles", () => {{ permissionKey: "tools:manage_runtime", scope: null },{ permissionKey: "tools:use", scope: null },{ permissionKey: "tools:admin", scope: null },+ { permissionKey: "commentary:view", scope: null },]);});@@ -95,6 +96,7 @@ describe("human invite roles", () => {{ permissionKey: "tools:manage_runtime", scope: null },{ permissionKey: "tools:use", scope: null },{ permissionKey: "tools:admin", scope: null },+ { permissionKey: "commentary:view", scope: null },]);});@@ -113,9 +115,17 @@ describe("human invite roles", () => {{ permissionKey: "tools:admin", scope: null },{ permissionKey: "tools:view_audit", scope: null },{ permissionKey: "audit:view_agent_actions", scope: null },+ { permissionKey: "commentary:view", scope: null },]);});+ it("lets viewers read commentary without granting agent audit access", () => {+ expect(grantsForHumanRole("viewer")).toEqual([+ { permissionKey: "commentary:view", scope: null },+ ]);+ expect(humanJoinGrantsFromDefaults(null, "viewer")).toEqual(grantsForHumanRole("viewer"));+ });+it("defaults legacy or missing roles to operator", () => {expect(normalizeHumanRole("member")).toBe("operator");expect(resolveHumanInviteRole(null)).toBe("operator");@@ -135,7 +145,17 @@ describe("human invite roles", () => {expect(humanJoinGrantsFromDefaults(null, "operator")).toEqual(grantsForHumanRole("operator"));});- it("preserves explicit human invite grants", () => {+ it.each(["owner", "admin", "operator", "viewer"] as const)("adds commentary access to saved pre-upgrade %s invite grants", (role) => {+ const legacyGrants = grantsForHumanRole(role).filter((grant) => grant.permissionKey !== "commentary:view");+ expect(humanJoinGrantsFromDefaults({ human: { role, grants: legacyGrants } }, role)).toEqual(grantsForHumanRole(role));+ });++ it("preserves an explicitly scoped commentary grant", () => {+ const grants = [{ permissionKey: "commentary:view", scope: { agentIds: ["agent-1"] } }];+ expect(humanJoinGrantsFromDefaults({ human: { grants } }, "operator")).toEqual(grants);+ });++ it("preserves explicit human invite scopes and adds the commentary default", () => {expect(humanJoinGrantsFromDefaults({@@ -155,6 +175,7 @@ describe("human invite roles", () => {permissionKey: "users:invite",scope: { companyId: "company-1" },},+ { permissionKey: "commentary:view", scope: null },]);});});diff --git a/server/src/routes/agent-commentary.ts b/server/src/routes/agent-commentary.tsindex b3b71215e4..35aa021c61 100644--- a/server/src/routes/agent-commentary.ts+++ b/server/src/routes/agent-commentary.ts@@ -17,8 +17,8 @@ export function agentCommentaryRoutes(db: Db) {assertBoard(req);assertCompanyAccess(req, companyId);if (req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin- && (!req.actor.userId || !await access.canUser(companyId, req.actor.userId, "audit:view_agent_actions"))) {- throw forbidden("Missing permission: audit:view_agent_actions");+ && (!req.actor.userId || !await access.canUser(companyId, req.actor.userId, "commentary:view"))) {+ throw forbidden("Missing permission: commentary:view");}return issueReadSqlCondition(db, req.actor);}diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.tsindex d756fa04c8..a2fc87792a 100644--- a/server/src/routes/openapi.ts+++ b/server/src/routes/openapi.ts@@ -5702,7 +5702,7 @@ registry.registerPath({path: "/api/companies/{companyId}/agent-commentary",tags: ["agents"],summary: "Browse agent suggestions and complaints",- description: "Board-only. Requires company membership, audit:view_agent_actions. Source-task privacy filters both previews and counts. Returns items, total, limit and offset; previews contain at most 280 characters and omit full bodies.",+ description: "Board-only. Requires company membership and commentary:view, granted by default to all human company roles. Source-task privacy filters both previews and counts. Returns items, total, limit and offset; previews contain at most 280 characters and omit full bodies.",request: { params: z.object({ companyId: z.string() }), query: agentCommentaryQuerySchema },responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },});diff --git a/server/src/services/company-member-roles.ts b/server/src/services/company-member-roles.tsindex 91ebd0f67e..4460a436d7 100644--- a/server/src/services/company-member-roles.ts+++ b/server/src/services/company-member-roles.ts@@ -39,6 +39,7 @@ export function grantsForHumanRole({ permissionKey: "tools:manage_runtime", scope: null },{ permissionKey: "tools:use", scope: null },{ permissionKey: "tools:admin", scope: null },+ { permissionKey: "commentary:view", scope: null },];case "admin":return [@@ -53,6 +54,7 @@ export function grantsForHumanRole({ permissionKey: "tools:manage_runtime", scope: null },{ permissionKey: "tools:use", scope: null },{ permissionKey: "tools:admin", scope: null },+ { permissionKey: "commentary:view", scope: null },];case "operator":return [@@ -69,9 +71,10 @@ export function grantsForHumanRole({ permissionKey: "tools:admin", scope: null },{ permissionKey: "tools:view_audit", scope: null },{ permissionKey: "audit:view_agent_actions", scope: null },+ { permissionKey: "commentary:view", scope: null },];case "viewer":- return [];+ return [{ permissionKey: "commentary:view", scope: null }];}}diff --git a/server/src/services/invite-grants.ts b/server/src/services/invite-grants.tsindex 2f41ea9003..901795a804 100644--- a/server/src/services/invite-grants.ts+++ b/server/src/services/invite-grants.ts@@ -64,5 +64,9 @@ export function humanJoinGrantsFromDefaults(scope: Record<string, unknown> | null;}> {const grants = grantsFromDefaults(defaultsPayload, "human");- return grants.length > 0 ? grants : grantsForHumanRole(membershipRole);+ if (grants.length === 0) return grantsForHumanRole(membershipRole);+ if (!grants.some((grant) => grant.permissionKey === "commentary:view")) {+ grants.push({ permissionKey: "commentary:view", scope: null });+ }+ return grants;}