Skip to content

feat(iam): Refinement drafts and an Analyst role that cannot approve them - #720

Merged
pikann merged 19 commits into
Paca-AI:masterfrom
msammu07:feature/analyst-role-refinement
Nov 9, 2026
Merged

pikann merged 19 commits into
Paca-AI:masterfrom
msammu07:feature/analyst-role-refinement

Conversation

@msammu07

@msammu07 msammu07 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Summary

First of two PRs for the PM / business analyst agent (part of #719). This one adds the permission model: a Refinement status for draft tasks and a seeded Analyst project role that can create and refine drafts but cannot approve them. The agent skill itself comes in the follow-up PR.

What changes:

  • IAM attribute task.status_category: registered in the attribute registry, loaded and expanded for task resources, and derived from the requested status on create/update so a policy can condition on where a task is going, not only where it is. Scope SQL supports it for list filtering.
  • Analyst project role: seeded from the default-roles manifest (defaultroles/policies/project_analyst.json). Reads the project and code; task writes allowed only while the task is (and stays) in the refinement category; no assignment and no sprint changes, so drafts stay unassigned and out of sprints.
  • Refinement status: seeded for new projects; migration 000082_add_refinement_status_and_analyst_role.sql adds it (and the Analyst role) to existing projects. Idempotent, skips projects that already have a refinement-category status, and avoids a name clash with an existing "Refinement" status.
  • Auto-assign skips tasks in Refinement; new sprint boards collapse the Refinement column (like Backlog).
  • Annotation create-task route now authorizes the task it would create (status, type, sprint, assignees), so a role conditioned on them cannot be side-stepped through that route. A route-coverage test guards every task-creating route.
  • Web: quick-add on board and list views now creates tasks in the project's default status instead of the first non-done status (which would otherwise be Refinement once it is seeded first).
  • Docs: docs/ai-agent/pm-agent.md (design, both PRs), docs/guides/roles-and-policies.md and the paca-role-policy skill document the Analyst role and task.status_category, including an opt-in Deny recipe to stop Editor-role agents moving drafts.

Type of Change

  • Other (feature: IAM role, status, migration) + Documentation

Tests

  • TestIAMAnalystRoleEndToEnd (authorization matrix through the HTTP API), TestRefinementAnalystMigration (incl. re-run and existing refinement status), TestScopedTaskListStatusCategory, TestProcessTask_SkipsDraftsInRefinement, TestDefaultSprintBoardCollapsesBacklogAndRefinement, route-coverage test for task-creating routes, defaultCreateStatusId web test.
  • go test -p 1 ./... in services/api with PACA_TEST_PG_DSN set: the only failures are tests that also fail on current master locally (TestGitStore_ChangeRequestsAndTaskLinks, TestIAMMigrationKeyMapping, TestPluginManifestActionsMigration, TestProjectRoleResourcesMigration, TestRolesAPI_EndToEnd, TestRolesAssignMigration, TestSeedPlatformRoles_ReconcilesMigratedRoles, TestServiceAccountsAPI_EndToEnd); no new failures. apps/web: 1490/1490 pass. services/agent-runner: pass.

Checklist

  • The change is focused and scoped: permission model only; the agent skill is a separate PR.
  • Related documentation is updated.
  • New structure or direction is explained clearly (design doc included).
  • I avoided unnecessary detail or premature abstraction: reuses the existing refinement status category and IAM conditions.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

The Analyst role's core guarantee — "cannot move a draft out of Refinement / cannot assign or sprint it" — rests on require.TaskChange, and that guard is skipped entirely when the request body has trailing bytes after the JSON object. A PATCH /tasks/{id} with {"status_id":"<backlog>"} {} passes the old-state check and applies the new status, so the guarantee this PR documents and tests does not hold at runtime. The root cause is shared pre-existing middleware, but this PR is what makes it a security boundary, so it needs to be fixed (or explicitly scoped out) before the role ships.

Reviewed changes

  • task.status_category condition attribute — registered in the IAM schema, loaded from task_statuses.category, and derived by a new taskLoader.Expand from a requested task.status_id so it applies on create and on the new state of an update; mismatch/cross-project status denies.
  • Analyst project role — new non-system template with read/docs/chat grants, an unconditioned tasks:write collection grant, a tasks:write grant on project/P/task/* conditioned on task.status_category = refinement, and Deny statements for any assignee or sprint.
  • Refinement status — seeded first for new projects (Backlog stays default) and added to existing projects by migration 000082, which also inserts the Analyst role; both steps idempotent.
  • Auto-assign now skips refinement-category tasks, and new sprint boards collapse the Refinement column alongside Backlog.
  • Annotation create-task route now runs require.TaskCreate(), and a new route-coverage test pins which routes carry the task-attribute gate.
  • Web quick-add on board/list views now prefers the project's default status instead of the first non-done status, so the new first-position Refinement column does not become the create target.
  • Docs — PM-agent design doc, roles-and-policies.md Analyst/attribute sections and opt-in Deny recipe, paca-role-policy condition-key entry.

🚨 The "agents cannot approve drafts" guarantee is bypassable by appending bytes to an update body

RequireRequestAttrsFromRequest treats a body it cannot parse as "no attributes" and, for an update, returns without calling AuthorizeChange at all. Its peek decoder flags trailing bytes (dec.More()), but the handler's own middleware.BindJSON decodes only the first JSON value and ignores what follows, so the two disagree: the guard skips the new-state check while the service applies the change. An agent that can reach the API with its own credentials (the MCP server already uses those credentials; a provider_cli sandbox can call the API directly) can therefore move a draft to Backlog, assign it, or put it in a sprint — exactly what the Analyst policy is supposed to prevent.

Technical details
# TaskChange is skipped for bodies with trailing bytes

## Affected sites
- `services/api/internal/transport/http/middleware/authz_attrs.go:70-75` — the peek decoder sets `body = nil` when `dec.Decode` fails **or `dec.More()`** (trailing bytes).
- `services/api/internal/transport/http/middleware/authz_attrs.go:86-94` — for `create=false`, `len(attrs) == 0` calls `next.ServeHTTP` without any `AuthorizeChange`.
- `services/api/internal/transport/http/middleware/validate.go:13-18` (`BindJSON`) and `services/api/internal/transport/http/handler/task_handler.go:1267-1304` — the handler decodes the first JSON value and applies `status_id` / `sprint_id` / `assignee_ids` straight into `taskdom.UpdateTaskInput`; trailing bytes are ignored.
- `services/api/internal/transport/http/middleware/authz_attrs.go:102-117` (`peekBodyLimit`) — restores the full body, so the handler still sees the trailing bytes.
- Route: `services/api/internal/transport/http/router/router.go:760` — `require.ProjectEntity(...)` (old state) + `require.TaskChange()`; the entity gate passes for a refinement task, `TaskChange` is skipped.
- Same shape in `RequireItemTasks` / `RequireViewIDs` (view positions), unrelated to approval but the same skip.

## Required outcome
- A request whose peeked body cannot be parsed as exactly one JSON object must **fail closed** on updates (deny or 400), never fall through to the handler with the attribute check skipped. `{"status_id":"<backlog>"} {}` must not reach `UpdateTask`.
- The peek decoder and the handler's decoder must agree on what is a valid body; otherwise the attribute gate can always be bypassed by a body the former rejects and the latter accepts.

## Suggested approach (optional)
- In `RequireRequestAttrsFromRequest`, distinguish "not a JSON object" (handler will 400) from "valid object plus trailing data" (handler will succeed). Reset the body and let the handler reject malformed JSON; for trailing data, deny (or return the same 400 the handler would if `BindJSON` rejected trailing bytes).
- Consider making `BindJSON` reject trailing values (`dec.Decode` then `dec.More()`) so the handler and the guard share one notion of a valid body; that is the durable fix and also closes the other `RequireRequestAttrs` users.
- Add a regression test that PATCHes a task with `{"status_id":"..."} {}` as a caller whose role is conditioned on a different status and asserts it is denied.

## Open questions for the human
- Is direct API access by an agent with its own token considered reachable in the `provider_cli` sandbox? If yes this is critical; if the threat model excludes it, the documented "guaranteed by IAM" claim in `docs/ai-agent/pm-agent.md` still needs to be narrowed.

⚠️ Existing Playwright spec still asserts a project starts with exactly three roles

apps/e2e/tests/iam/role-scope-rules.spec.ts:301 compares the project role list to exactly Admin, Editor, Viewer, so it will fail as soon as the fourth built-in role exists. Because e2e-ci.yml only triggers on apps/e2e/** changes, this PR's CI stays green and the failure surfaces on the next full Playwright run — update the spec in this PR together with the role change.

Technical details
# Stale four-role expectation in the e2e suite

## Affected sites
- `apps/e2e/tests/iam/role-scope-rules.spec.ts:301-311` — `expect(roles.map((r) => r.name).sort()).toEqual(["Admin", "Editor", "Viewer"])`; `listProjectRoles` requests `page_size=100`, so the Analyst role is returned too.
- `apps/e2e/tests/iam/role-scope-rules.spec.ts:312-323` — the property loop would pass for Analyst; only the array equality is wrong.
- Trigger gap: `.github/workflows/e2e-ci.yml` runs only on `apps/e2e/**`, so this is not caught by PR CI.

## Required outcome
- The expectation includes `Analyst`, and the test title/description no longer says "exactly Admin, Editor and Viewer". If the intent is a fixed shipped set, match `["Admin", "Analyst", "Editor", "Viewer"]`.

## Suggested approach (optional)
- Update the array and title, and assert Analyst is the fourth non-system project role.

ℹ️ Built-in role documentation still says every project gets three roles

The PR updates docs/guides/roles-and-policies.md, but the other role references still describe the pre-Analyst set, which is now wrong for users reading the authorization guide, not just for the code comments.

Technical details
# Stale three-role wording

## Affected sites
- `docs/guides/iam-authorization.md:222-228` — the built-in role table omits `Analyst`, and the following sentence says "Every new project gets its own `Admin`, `Editor` and `Viewer`".
- `docs/architecture/authorization.md:125` — "Project templates (`Admin`, `Editor`, `Viewer`) are instantiated into every new project".
- `services/api/internal/bootstrap/defaultroles/defaultroles.go:9` — package comment lists the project templates as `Admin, Editor, Viewer`.
- `services/api/internal/service/project/project_service.go:285-286` — `Create`'s comment lists `Admin, Editor, Member, Viewer`.
- `services/api/internal/transport/http/handler/sprint_handler.go:43` — says sprint default views collapse "backlog status collapsed columns"; it now includes refinement too.
- `apps/e2e/tests/helpers/e2e-api.ts:127` — comment says a project starts with the roles Admin, Editor and Viewer.
- `services/api/test/e2e/list_pagination_test.go:363` — failure message says "want the shipped three plus three more" (the guard is `TotalCount < 6`, so it still passes, but the message is wrong).

## Required outcome
- The user-facing authorization guide lists Analyst and describes its restriction; the remaining comments/docstrings say four templates (and `project_service.go` drops the stale `Member`).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

The attribute gates peeked at a request body and treated one with
trailing data as setting no attributes, so an update skipped
AuthorizeChange while the handler, decoding only the first JSON value,
applied it. `{"status_id":"<backlog>"} {}` let an Analyst move a draft
out of Refinement, assign it or put it in a sprint.

The gates also looked up exact lower-case keys in a map, while handlers
decode into structs, which encoding/json matches case-insensitively:
`{"STATUS_ID":...}` or `{"status_id":A,"Status_Id":B}` reached the
handler unchecked or checked against a different value.

- decodeSingleJSON: one JSON value, then only whitespace. BindJSON and
  the gates both use it; the gates answer trailing data with a 400.
- jsonFoldKey / foldBodyKeys: the gates fold body keys as encoding/json
  does, and two keys that fold alike are a 400. A test pins the folding
  to the stdlib's struct-field matching.
- Annotation create-task binds through BindJSON.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor suggestion below.

Reviewed changes

Reviewed the four commits since the prior pullfrog review (a4034b6), which close the trailing-bytes authorization bypass and finish the role and documentation updates.

  • Single-value JSON decoding shared by gates and handlers — new decodeSingleJSON makes BindJSON, RequireRequestAttrs, RequireItemTasks, and RequireViewIDs reject anything but whitespace after the body's JSON value, so an update can no longer reach the handler with the attribute check skipped. Every task/doc/view/inventory route that carries an attribute gate now decodes through it, and the annotation create-task handler switched to BindJSON.
  • encoding/json-compatible body-key folding — jsonFoldKey/foldBodyKeys re-key the peeked body the way struct decoding matches fields (ASCII case plus Unicode simple fold) and refuse two keys that fold alike, so SPRINT_ID, Status_Id, and ſtatus_id can no longer slip past the extractor. A test pins the folding against the standard library.
  • Trailing-data regression coverage — cases for a second JSON value, garbage bytes, mixed-case and long-s keys, duplicate spellings, and trailing whitespace were added to the task, view, and bulk-item gate tests.
  • Four-role expectations — the Playwright project-roles spec now expects Admin, Analyst, Editor, Viewer and asserts Analyst is non-system; the e2e helper comment, authorization docs, defaultroles comment, project-service comment, sprint-board comment, and pagination message were updated to the four-template set.
  • view-utils doc comment restored — applyStatusFilterToColumnDefs's doc block is back above its signature and defaultCreateStatusId keeps its own; the prior inline thread is resolved.

ℹ️ Gherkin specs still describe a project as starting with three roles

The Playwright spec and the e2e helper comment were updated for the Analyst role, but the Gherkin feature files that the e2e suite treats as the specification of record still say a new project starts with Admin, Editor and Viewer. The suite is runner-plain Playwright (no Cucumber), so this will not fail CI, but the spec now contradicts the test it describes.

Technical details
# Gherkin specs still describe three roles

## Affected sites
- `apps/e2e/features/iam/role-scope-rules.feature:6` — the feature intro says new projects start with `Admin`, `Editor` and `Viewer`.
- `apps/e2e/features/iam/role-scope-rules.feature:58-59` — the scenario title and step say "exactly Admin, Editor and Viewer".
- `apps/e2e/features/iam/role-scope-rules.feature:61` — the is-system step lists only `Editor` and `Viewer` as non-system.
- `apps/e2e/features/projects/management.feature:342` — the scenario title says the three roles are pre-seeded.
- `apps/e2e/tests/projects/management.spec.ts:599` — the matching test title (the test only asserts presence, so it still passes).

## Required outcome
- The feature files and the remaining stale test title match the shipped four-role set, including `Analyst`.

## Suggested approach (optional)
- `apps/e2e/tests/iam/role-scope-rules.spec.ts` already expects `Admin, Analyst, Editor, Viewer`; mirror that in `role-scope-rules.feature` and add `Analyst` to the non-system list.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann pikann left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thank you for the contribution! 🚀

@pikann
pikann merged commit 2e93cee into Paca-AI:master Nov 9, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] PM / business analyst agent with human-approved Refinement drafts

2 participants