diff --git a/README.md b/README.md index f23a09edd..af0a52bc2 100644 --- a/README.md +++ b/README.md @@ -402,7 +402,7 @@ directory for `claude-code`, and an `[mcp_servers.pad]` table in project-scoped, it's install-on-request only — `--all` and `pad mcp status` cover the per-user clients (including Codex) and skip it. -**Tool catalog (v0.98)** — ten resource × action tools plus `pad_set_workspace`. Undeclared input keys are rejected with a structured error rather than silently dropped, and field values are typed against the collection schema on the server: +**Tool catalog (v0.99)** — ten resource × action tools plus `pad_set_workspace`. Undeclared input keys are rejected with a structured error rather than silently dropped, and field values are typed against the collection schema on the server: | Tool | Actions | |---|---| @@ -426,7 +426,7 @@ Plus resources at `pad://workspaces`, `pad://workspace/{ws}/dashboard`, and `pad://_meta/version`. **Stability contract.** The catalog is versioned -(`tool_surface_version: "0.98"`) and advertised in the initialize handshake and at +(`tool_surface_version: "0.99"`) and advertised in the initialize handshake and at `pad://_meta/version`, so external agents can pin against it; the per-version changelog lives in [`internal/mcp/version.go`](internal/mcp/version.go). Errors come back as structured envelopes (`{error: {code, message, hint, ...}}`) from a diff --git a/cmd/pad/cmd_item.go b/cmd/pad/cmd_item.go index 7ce576543..670c04710 100644 --- a/cmd/pad/cmd_item.go +++ b/cmd/pad/cmd_item.go @@ -4400,6 +4400,7 @@ func unstarCmd() *cobra.Command { func starredCmd() *cobra.Command { var all bool + var limit int cmd := &cobra.Command{ Use: "starred", @@ -4410,7 +4411,19 @@ func starredCmd() *cobra.Command { client, _ := getClient() ws := getWorkspace() - items, err := client.ListStarredItems(ws, all) + // --limit asks for one page from the start and says on stderr when + // more exist; without it every page is read (BUG-3790). + var items []models.Item + var err error + if limit > 0 { + var page cli.ItemListPage + items, page, err = client.ListStarredItemsPage(ws, all, limit) + if err == nil && page.HasMore { + fmt.Fprintf(os.Stderr, "More starred items exist than --limit %d shows.\n", limit) + } + } else { + items, err = client.ListStarredItems(ws, all) + } if err != nil { return err } @@ -4438,6 +4451,7 @@ func starredCmd() *cobra.Command { } cmd.Flags().BoolVar(&all, "all", false, "include completed/terminal items") + cmd.Flags().IntVar(&limit, "limit", 0, "at most this many, from the most recently starred (default: all)") return cmd } diff --git a/cmd/pad/testdata/mcp_wire/remote_initialize.json b/cmd/pad/testdata/mcp_wire/remote_initialize.json index 4d60ba6d7..e37591b79 100644 --- a/cmd/pad/testdata/mcp_wire/remote_initialize.json +++ b/cmd/pad/testdata/mcp_wire/remote_initialize.json @@ -8,7 +8,7 @@ }, "padToolSurface": { "tool_surface_stable": true, - "version": "0.98" + "version": "0.99" } }, "prompts": {}, @@ -21,5 +21,5 @@ "name": "pad-mcp", "version": "" }, - "instructions": "Pad is a project tracker for developers and AI agents — issues (TASK, BUG), plans (PLAN), ideas (IDEA), docs (DOC), conventions, comments, and dependencies. Use this server when a user mentions:\n\n- Issue refs like `TASK-5`, `BUG-12`, `PLAN-3`, `IDEA-8` — they are stable, human-readable IDs and the canonical way to address items. Use them, never slugs; they are what audit trails and PR titles show.\n- Tasks / issues / items / plans / progress / \"what's on my plate\" / \"what to work on next\" / standup / changelog / retrospective.\n- Project conventions, decision records, or \"how should this team do X.\"\n\nIf the user is asking general code questions with no project-management thread, you don't need this server.\n\n## Tool surface (v0.98)\n\nTen resource × action tools, plus `pad_set_workspace`. Eleven tools total.\n\nInputs are validated strictly: an undeclared top-level key is rejected with a structured `validation_failed` naming it, never accepted and silently dropped.\n\n- `pad_item` — Items: create / update / delete / get / list / move / restore / link / unlink / deps / context / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / reminders / unremind / link-pr / unlink-pr / claim / release / patch. On create/update, field values may be passed as a `fields` OBJECT (the same shape reads return, e.g. `{\"status\":\"done\",\"effort\":\"l\"}`) — it merges into the same path as the dedicated params and `field: [\"key=value\"]`; the same key in two places with CONFLICTING values is refused, not silently resolved. `list` accepts `unparented: true` to keep items with no parent or implements relationship (mutually exclusive with `parent`). `list` results are SUMMARY-shaped by default on both transports — no content bodies; pass `full: true` for complete bodies (token-expensive), or prefer `get` for a single item's body. `update` field writes are a server-side field-level merge (only the keys you set change); pass `expected_seq` for optimistic concurrency — the `seq` you last read, which is on every item AND every list summary — and a stale value fails with a structured 409 `update_conflict` whose details carry `actual_seq` to retry with. PREFER IT over `expected_updated_at`, which cannot tell two writes inside one second apart; that one still works, and if you send both, seq decides. To change PART of a body, prefer `patch`: `edits: [{old, new}]`, where each `old` is exact text occurring once in the current body (read it with `get` and `lines: \"A-B\"` to quote it). The answer is a unified `diff`: read it, because anchors guarantee position, not meaning. A moved `expected_seq` is applied over and reported as `rebased` with the intervening writes. On an item open in a browser editor, the editor applies the patch to its live document, merging with the typing there, and the answer says `content_state: \"applied_pending_flush\"`. `patch_anchor_missing` / `patch_anchor_ambiguous` mean re-read and quote current text; `patch_unstable_roundtrip` means the open editor would also change content you did not edit, so send a whole-body update; `patch_room_open` means an older editor that cannot apply patches holds the item. Every patch answer carries a `patch_id`; `patch` with `undo: \u003cpatch_id\u003e` inverts it, and is refused when the text it changed has changed since. Send an `op_key` (any unique string, e.g. a UUID) with a patch whenever you might retry it: the same request with the same key returns the first answer instead of applying twice. `patch_outcome_unknown` means an earlier attempt's editor never confirmed it and is gone; read `details.diff` before deciding. `content` REPLACES the whole body, so send `expected_seq` with it: `get` the item, edit that body, and send it back with the `seq` you read. An `update_conflict` whose details carry `content_write` means someone changed the item after your read. Do NOT resend your body, because it would undo their change: re-read, apply your edit to the current content, and send that with the new seq. `replace: true` overwrites on purpose instead. A content write with neither carries `warnings.unguarded_content_write`, and a later release refuses it. A token cannot see a browser tab's unsaved edits, so `content` sent WITH one is refused with 409 `content_pending_flush` while any exist; re-reading will not clear it. Wait for the editor to save, or pass `overwrite_pending_edits: true` to replace them. `content_state: \"superseded_set_aside\"` is different and wins when both apply: an editor upgrade set aside edits no tab can restore, so EVERY content write is refused (token or not; `details.set_aside_rows`) and waiting never clears it. Tell the user, or pass `overwrite_pending_edits: true` to discard them. Writing `content` while a browser tab has the item open routes the markdown through that live document; the stored row updates only on a later collab-snapshot flush, which nothing guarantees. The 200 echoes what you SENT with `warnings.content_outcome: \"applied_pending_flush\"`, which describes your WRITE (it went to the document, not the row). A `get` (or a `list` with `full: true`; a default list carries no content) before the flush returns the PREVIOUS content: that is lag, not a failed write, so do not re-send. A read whose body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"`, also when someone ELSE's tab holds the edits and you wrote nothing: same value, but it describes the ROW, not your request. Treat it as re-read later, never as re-send, and do not wait on it in a loop: the server normally recovers the stored copy itself about a minute after the last tab leaves the item, but that is not guaranteed (a recovery can fail, and an operator can turn it off), and otherwise the row catches up only when a tab next opens the item. The stored form may also not be byte-identical to what you sent, since the markdown round-trips through the editor (bullet markers, emphasis characters, list numbering and blank-line runs normalise; already-canonical markdown survives unchanged), so compare on meaning rather than bytes. `move` changes an item's COLLECTION within its workspace: system metadata (implementation notes, decision log, linked PR) survives it, and any field value the target schema has no home for is dropped AND reported in the move's activity entry — check there rather than assuming a move is lossless. A carried unique-field collision is dropped, named in `warnings.not_unique`. Three system keys — `implementation_notes`, `decision_log`, `convention` — cannot be set through `field` on update or move; the call is refused with `validation_failed`, naming the key and the write path that does maintain it (`note`, `decide`, and library activation respectively). `github_pr` is refused as well (BUG-2696): a `field` value arrived as a string, so the PR data was stored double-encoded and no link appeared. Its writers are `action=link-pr` (`pr_number` + `pr_url`, metadata you supply; nothing is fetched from GitHub) and `action=unlink-pr`. On `create` they are refused too (BUG-3163), with the same `validation_failed`: create the item first, then use `note` / `decide` on it; convention metadata comes from library activation. `context` (`intent`, `role`, `budget`): one brief before you start work, with parents, matching convention bodies, deps and links. `history` returns read-only item version metadata (newest-first), bounded to the NEWEST 50 versions by default (max 300 — pass `limit` to change the window); pass `full: true` to include each version's resolved content body (token-expensive). There is no `offset`: versions are stored as reverse patches, so only a newest-end window is cheap to reconstruct. Unassign or detach with the `clear_assigned_user` / `clear_agent_role` / `clear_parent` booleans; an empty `assign` / `role` / `parent` does NOT clear. `remind` / `ack-reminder`: a fired reminder shows in `pad_project` next / ready (the delivery path on an instance with no webhook) until acknowledged, and one on a completed item is hidden there. `claim` / `release`: claim an item before you work it; a loser's 409 is `lease_held` (pick another, don't retry), and a lease bumps neither `updated_at` nor `seq`. A claim answers your `worker_id`; pass it to resume elsewhere. next / ready skip items other workers hold. `edit-comment` / `delete-comment` take a `comment_id` from `list-comments` (whose rows carry `edited`); only a comment's author may edit it. Correct a comment in place rather than appending a correction. Deleting a comment that has replies leaves a placeholder (`deleted: true`, empty body) so the replies keep their parent; editing, replying to or reacting to it answers 409 `comment_deleted`.\n\n**List filters must name a field (v0.75).** A `pad_item` `list` filter on a key no collection in scope declares, and no item stores, is refused with `validation_failed` (\"invalid list filter\"), where it used to return an empty list; a stored undeclared key still filters. Check the schema; don't retry.\n\n**Library words in a blank workspace (v0.67).** A brand-new blank workspace lists one convention trigger (`always`) and one scope (`all`). Activating a library entry, or creating a convention or playbook with a trigger or scope the library itself uses, adds that word to the collection's options and says so in `warnings.options_added`. A trigger you invent is still refused until the workspace owner adds it to the collection's schema.\n\n**App attribution (v0.65).** An item an installed app created, a comment an app wrote and a history row an app's write made carry `via_app` (the install id) and `via_app_name` (the app's name). On an item they name the app that CREATED it, not the last writer. They are absent for anything a person or an agent wrote.\n\n**Relation fields (v0.31).** A `relation` value may be a UUID, an issue ref (`COLO-3`) or the target's EXACT TITLE, tried in that order (a title that is also a ref resolves as the ref). A title matches only inside the declared collection, among items you can see; found only elsewhere, it is refused naming that collection; several matches are `ambiguous`. Full rules: docs/mcp.md.\n\nReads carry a `relation_targets` member beside `fields`: field key → `{id, ref, title}`, so you can render a relation without a request per value. `fields` still holds the canonical id, which is what you write back. An entry with an `id` and NO `ref`/`title` means the target is gone **or** you may not see it — the two are deliberately indistinguishable, so do not render it as either \"deleted\" or \"hidden\"; \"unavailable\" is the honest word. An entry with `stored_as_text: true` differs: the stored value is not UUID-shaped, so it was never an id (an imported title, legacy text). Render it as text, not as unavailable.\n\n**`multi_relation` fields (v0.33).** An ORDERED LIST of references, each resolved like a `relation` (UUID, ref, or exact title in the declared collection). Declare one as `owners:multi_relation:people`; the target collection is required. Rules: `[]` means absent; a blank element is refused by index; order is part of the value; duplicates are refused after resolution (`duplicate_referent`); any failing element refuses the whole write; `required` needs one resolved element; a cross-workspace copy drops the whole value (in `warnings.dropped_fields`). `relation_targets` holds an ARRAY of `{id, ref, title}` in stored order (`id`-only where unresolved); scalar keys stay single objects. Full rules: docs/mcp.md.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete / list-archived / restore. `delete` archives: the collection and its items leave every view, and `restore` brings them back. An `update` that removes a field or a select option still in use answers with `warnings.orphaned`: tell the user how many items keep the removed value.\n- `pad_project` — Project intelligence: dashboard / next / ready / stale / standup / changelog / report / activity. Use `ready` for the ranked top items to work on next (blocked work is left out) and `stale` for items needing attention; `activity` to catch up on what other agents/users changed since you last worked (non-streaming feed with item refs + change details).\n- `pad_role` — Agent roles: list / create / update / delete.\n- `pad_search` — Full-text search across items: query.\n- `pad_playbook` — Invokable procedures: list / get / run / match. Use `run` to bind args against a playbook's declared spec and get the rendered body back; side-effect-free. `run` refuses a playbook whose status isn't `active` (a draft still being authored) with a `playbook_not_active` error — pass `allow_draft: true` to override. Both `run` and `get` echo the playbook's `status`. Both may also carry `content_state` (`\"applied_pending_flush\"`, or `\"superseded_set_aside\"` as under `pad_item`), meaning the BODY you are about to execute is behind the item's live collaborative document — an editor holds unflushed edits, so the steps may be superseded. It is a reason to re-read or to ask, not a reason to refuse to run; the body is still the best the server has. `match` finds a playbook from text.\n- `pad_library` — Convention + playbook library (the global catalog of pre-built entries workspaces activate): list / get / activate.\n- `pad_attachment` — Read-only attachment metadata: list / show. `list` enumerates a workspace's attachments (filter by item / category / collection / attached / unattached); `show` returns one attachment's MIME, size, filename, and ETag via a HEAD request. Uploading and general file downloads stay CLI-only; bounded image bytes are available through the attachment resource below.\n- `pad_meta` — Server introspection: server-info / version / tool-surface / bootstrap. The `bootstrap` action returns one-shot workspace context (user + collections + always-on conventions + a metadata-only `convention_index` of every active convention + roles + playbook metadata + dashboard + recent activity).\n- `pad_set_workspace` — Load workspace context; response embeds the bootstrap blob so you load context in one call. Whether it also pins a session default: see Workspace context below. Takes `workspace: \u003cslug\u003e` only (no `action`).\n\nFor the ten resource × action tools, always pass `action` as a top-level field. Per-action required parameters are documented in each tool's description.\n\n## Resources are cheaper than tool calls\n\nRead these directly when you need workspace state (described in the resource listings): `pad://workspaces`, `pad://workspace/{ws}/dashboard`, `.../collections`, `.../items` (use `pad_item` `list` to filter), `.../items/{ref}` (markdown), `.../attachments/{id}` (images only, at most 1 MiB, as base64 `thumb-md`), `.../bootstrap` (the same payload as `pad_meta` `bootstrap`), and `pad://_meta/version`. A host can prefetch them once per session.\n\nLoad the bootstrap resource once per workspace and reuse its collections, conventions, roles, and playbook metadata. Refresh it after switching workspaces, after changing those configuration surfaces, when Pad reports stale schema/context, or when the user asks. For changing work state, read the affected item or use a targeted project tool instead of fetching the whole bootstrap again.\n\n## Workspace context\n\nEvery action that operates within a workspace accepts an optional `workspace` parameter. Resolution order:\n\n1. Explicit `workspace` argument on the call (always wins).\n2. On a single-user local server only: the session default set via `pad_set_workspace`.\n3. On a single-user local server only: the CWD-linked workspace from `.pad.toml`.\n\nA multi-user/remote server does **not** persist a session default — pass `workspace` explicitly on every call. If none resolves, the action returns a structured `no_workspace` error with `available_workspaces`, on both the local and the remote transport.\n\n## Update flow: read first, then patch\n\nFor `pad_item.action: update`, the server merges your patch with the item's current state. Pass only the fields you want to change. When changing `status`, ALWAYS include a `comment` explaining why — it builds the audit trail that helps the team understand history.\n\n## One error code you must not retry\n\nErrors come back as a structured envelope with a `code`. Most failures are worth a retry after you fix something, and a `server_error` may be transient. `stored_state_unreadable` is neither.\n\nIt means the ITEM'S STORED DATA cannot be decoded — your input was fine. Today it fires when `note` / `decide` would append to an `implementation_notes` / `decision_log` value that is not a list of entries. The operation is refused precisely because completing it would overwrite that value. The refusal is fully deterministic, so retrying — immediately or after a backoff — fails identically every time and changes nothing.\n\nWhen you see it: tell the user which item is affected, and stop. Whether you can inspect the bad value depends on which layer is broken — if the item's whole `fields` blob fails to parse, `action: get` hands it back as a raw string; if one structured key is at fault, you won't see it at all, because the blob is normalized on this surface and a value that doesn't decode is dropped from the top-level arrays. A human can always read it with `pad item show \u003cref\u003e --format json`. Do not route around the refusal by writing the field some other way; that is the write that caused it.\n\n## Project conventions\n\nWorkspaces can declare conventions (e.g. \"run `make test` before PR\", \"use conventional commit format\"). The bootstrap blob gives you two views:\n\n- `conventions` — full bodies of the always-on (`trigger=always`) rules. Follow these unconditionally.\n- `convention_index` — METADATA ONLY (`ref`, `title`, `trigger`, `role`; no bodies) for **every** active convention, including the triggered ones whose bodies are NOT in `conventions`. This is your map of what triggered rules exist.\n\nBefore performing meaningful work with a specific trigger (e.g. `on-implement` before writing code), consult `convention_index`: if it lists entries for that trigger, pull their bodies on demand; if it lists none, skip the query.\n\n```\npad_item.action: list, collection: \"conventions\", status: \"active\"\n```\n\nFilter by trigger (`always`, `on-implement`, `on-task-complete`, etc.) when relevant — the `convention_index` triggers tell you which filters are worth running.\n\n`\"conventions\"` above is the DEFAULT collection slug and a workspace may have renamed it, in which case that literal returns nothing while `convention_index` still lists entries — the bootstrap payload resolves by declaration, not by name. When the two disagree, address the items by the `ref`s the index gave you, or find the collection with `pad_collection.action: list`. The same applies to `\"playbooks\"`; `pad_playbook` resolves by declaration and is unaffected.\n\n## Pushes and the session monitor (security note)\n\nPad can push an item into a Claude Code session (`pad push`, or the web item view's push composer). That is terminal instruction injection by design, so receiving is **consent-gated** (PLAN-2613, since v0.15.0): a session receives pushes only after it has connected (`/pad:connect` in the plugin, or a repo-level `push.auto_arm = true` in `.pad.toml` — which a per-user `auto_arm = false` in `~/.pad/config.toml` vetoes), and pushes are self-addressed only — the sender is always the receiving session's own user. This MCP connection is not a session: it cannot arm one, receive a push, or run the monitor, and the `pad_item` / `pad_project` tools expose no push action. If a user asks you to \"push\" something to their terminal, tell them it happens from their own terminal (`pad push \u003cref\u003e -m \"...\"` — the sending session need not be connected, the receiving ones must have consented); do not try to emulate it by writing comments or instructions into items.\n\n## Adding a workspace to this connection\n\nIf the user references a workspace this connection can't see (you'll get a 403 from workspace tools, or the workspace won't appear in `pad_workspace.list`), tell the user you can't see that workspace with your current permissions, then walk them through how to grant access: open Pad in their browser → switch to that workspace → avatar menu → \"Connect project...\" A 6-digit claim code will appear. Have them paste it back in chat, then call `pad_workspace.claim` with `{workspace: \"\u003cslug\u003e\", code: \"\u003c6 digits\u003e\"}`. The workspace joins this connection's allow-list and stays until the user revokes it via `/console/connected-apps`. No re-auth required.\n\nFor brand-new workspaces, `pad_workspace.create` with `{name: \"\u003cname\u003e\"}` (and optional `template`) creates the workspace AND auto-adds it to this connection's allow-list in one call — no claim code needed. Only works when the connection currently carries the \"may create workspaces\" grant — granted at consent time, or enabled later on the connections page. If the grant is present and set to false, the create is **refused with a 403 and no workspace is made** — retrying won't help and neither will the claim flow, since there is nothing to claim. Tell the user this connection isn't permitted to create workspaces, and offer them the two ways forward: create the workspace themselves in the browser and grant access with a claim code, or re-authorize this connection with \"Let this app create new workspaces\" enabled (`/console/connected-apps` can also flip it on an existing connection).\n\n## New workspace: offer to set it up\n\nThe bootstrap blob carries `needs_onboarding: bool` — true when the workspace has zero user-created items (template seeds don't count). When it's true, **lead with an active offer before anything else**: *\"This workspace is brand new and isn't set up yet. Want me to set it up? I'll ask a few quick questions and adapt it to your project.\"*\n\nThis is an **offer, not an auto-run** — wait for the user to say yes before running onboarding. If they accept, run the `onboard` playbook (use the `pad_onboard` prompt, or load the body via `pad_playbook` `action: get`, `ref: onboard`). If they decline, or already declined earlier in the session, respect that and skip the offer. The flag flips to false the moment any item exists, so it won't nag past first setup.\n\n## Built-in updates: mention once\n\nThe bootstrap blob may carry `builtin_updates: int` (absent when there are none): how many of the conventions and playbooks Pad ships have newer text in Pad's library than this workspace's copy. When it is present, mention it **once per session**, in one line, then carry on. **Never apply an update yourself**: a person reviews each one and accepts it or not.\n\n## Multi-step workflows\n\nFour prompts ship with the server: `pad_plan`, `pad_ideate`, `pad_retro`, `pad_onboard`. Use them when the user wants help planning, brainstorming, retrospecting, or onboarding into a workspace — they encode the multi-step Pad-aware playbook for each.\n" + "instructions": "Pad is a project tracker for developers and AI agents — issues (TASK, BUG), plans (PLAN), ideas (IDEA), docs (DOC), conventions, comments, and dependencies. Use this server when a user mentions:\n\n- Issue refs like `TASK-5`, `BUG-12`, `PLAN-3`, `IDEA-8` — they are stable, human-readable IDs and the canonical way to address items. Use them, never slugs; they are what audit trails and PR titles show.\n- Tasks / issues / items / plans / progress / \"what's on my plate\" / \"what to work on next\" / standup / changelog / retrospective.\n- Project conventions, decision records, or \"how should this team do X.\"\n\nIf the user is asking general code questions with no project-management thread, you don't need this server.\n\n## Tool surface (v0.99)\n\nTen resource × action tools, plus `pad_set_workspace`. Eleven tools total.\n\nInputs are validated strictly: an undeclared top-level key is rejected with a structured `validation_failed` naming it, never accepted and silently dropped.\n\n- `pad_item` — Items: create / update / delete / get / list / move / restore / link / unlink / deps / context / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / reminders / unremind / link-pr / unlink-pr / claim / release / patch. On create/update, field values may be passed as a `fields` OBJECT (the same shape reads return, e.g. `{\"status\":\"done\",\"effort\":\"l\"}`) — it merges into the same path as the dedicated params and `field: [\"key=value\"]`; the same key in two places with CONFLICTING values is refused, not silently resolved. `list` accepts `unparented: true` to keep items with no parent or implements relationship (mutually exclusive with `parent`). `list` results are SUMMARY-shaped by default on both transports — no content bodies; pass `full: true` for complete bodies (token-expensive), or prefer `get` for a single item's body. `update` field writes are a server-side field-level merge (only the keys you set change); pass `expected_seq` for optimistic concurrency — the `seq` you last read, which is on every item AND every list summary — and a stale value fails with a structured 409 `update_conflict` whose details carry `actual_seq` to retry with. PREFER IT over `expected_updated_at`, which cannot tell two writes inside one second apart; that one still works, and if you send both, seq decides. To change PART of a body, prefer `patch`: `edits: [{old, new}]`, where each `old` is exact text occurring once in the current body (read it with `get` and `lines: \"A-B\"` to quote it). The answer is a unified `diff`: read it, because anchors guarantee position, not meaning. A moved `expected_seq` is applied over and reported as `rebased` with the intervening writes. On an item open in a browser editor, the editor applies the patch to its live document, merging with the typing there, and the answer says `content_state: \"applied_pending_flush\"`. `patch_anchor_missing` / `patch_anchor_ambiguous` mean re-read and quote current text; `patch_unstable_roundtrip` means the open editor would also change content you did not edit, so send a whole-body update; `patch_room_open` means an older editor that cannot apply patches holds the item. Every patch answer carries a `patch_id`; `patch` with `undo: \u003cpatch_id\u003e` inverts it, and is refused when the text it changed has changed since. Send an `op_key` (any unique string, e.g. a UUID) with a patch whenever you might retry it: the same request with the same key returns the first answer instead of applying twice. `patch_outcome_unknown` means an earlier attempt's editor never confirmed it and is gone; read `details.diff` before deciding. `content` REPLACES the whole body, so send `expected_seq` with it: `get` the item, edit that body, and send it back with the `seq` you read. An `update_conflict` whose details carry `content_write` means someone changed the item after your read. Do NOT resend your body, because it would undo their change: re-read, apply your edit to the current content, and send that with the new seq. `replace: true` overwrites on purpose instead. A content write with neither carries `warnings.unguarded_content_write`, and a later release refuses it. A token cannot see a browser tab's unsaved edits, so `content` sent WITH one is refused with 409 `content_pending_flush` while any exist; re-reading will not clear it. Wait for the editor to save, or pass `overwrite_pending_edits: true` to replace them. `content_state: \"superseded_set_aside\"` is different and wins when both apply: an editor upgrade set aside edits no tab can restore, so EVERY content write is refused (token or not; `details.set_aside_rows`) and waiting never clears it. Tell the user, or pass `overwrite_pending_edits: true` to discard them. Writing `content` while a browser tab has the item open routes the markdown through that live document; the stored row updates only on a later collab-snapshot flush, which nothing guarantees. The 200 echoes what you SENT with `warnings.content_outcome: \"applied_pending_flush\"`, which describes your WRITE (it went to the document, not the row). A `get` (or a `list` with `full: true`; a default list carries no content) before the flush returns the PREVIOUS content: that is lag, not a failed write, so do not re-send. A read whose body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"`, also when someone ELSE's tab holds the edits and you wrote nothing: same value, but it describes the ROW, not your request. Treat it as re-read later, never as re-send, and do not wait on it in a loop: the server normally recovers the stored copy itself about a minute after the last tab leaves the item, but that is not guaranteed (a recovery can fail, and an operator can turn it off), and otherwise the row catches up only when a tab next opens the item. The stored form may also not be byte-identical to what you sent, since the markdown round-trips through the editor (bullet markers, emphasis characters, list numbering and blank-line runs normalise; already-canonical markdown survives unchanged), so compare on meaning rather than bytes. `move` changes an item's COLLECTION within its workspace: system metadata (implementation notes, decision log, linked PR) survives it, and any field value the target schema has no home for is dropped AND reported in the move's activity entry — check there rather than assuming a move is lossless. A carried unique-field collision is dropped, named in `warnings.not_unique`. Three system keys — `implementation_notes`, `decision_log`, `convention` — cannot be set through `field` on update or move; the call is refused with `validation_failed`, naming the key and the write path that does maintain it (`note`, `decide`, and library activation respectively). `github_pr` is refused as well (BUG-2696): a `field` value arrived as a string, so the PR data was stored double-encoded and no link appeared. Its writers are `action=link-pr` (`pr_number` + `pr_url`, metadata you supply; nothing is fetched from GitHub) and `action=unlink-pr`. On `create` they are refused too (BUG-3163), with the same `validation_failed`: create the item first, then use `note` / `decide` on it; convention metadata comes from library activation. `context` (`intent`, `role`, `budget`): one brief before you start work, with parents, matching convention bodies, deps and links. `history` returns read-only item version metadata (newest-first), bounded to the NEWEST 50 versions by default (max 300 — pass `limit` to change the window); pass `full: true` to include each version's resolved content body (token-expensive). There is no `offset`: versions are stored as reverse patches, so only a newest-end window is cheap to reconstruct. Unassign or detach with the `clear_assigned_user` / `clear_agent_role` / `clear_parent` booleans; an empty `assign` / `role` / `parent` does NOT clear. `remind` / `ack-reminder`: a fired reminder shows in `pad_project` next / ready (the delivery path on an instance with no webhook) until acknowledged, and one on a completed item is hidden there. `claim` / `release`: claim an item before you work it; a loser's 409 is `lease_held` (pick another, don't retry), and a lease bumps neither `updated_at` nor `seq`. A claim answers your `worker_id`; pass it to resume elsewhere. next / ready skip items other workers hold. `edit-comment` / `delete-comment` take a `comment_id` from `list-comments` (whose rows carry `edited`); only a comment's author may edit it. Correct a comment in place rather than appending a correction. Deleting a comment that has replies leaves a placeholder (`deleted: true`, empty body) so the replies keep their parent; editing, replying to or reacting to it answers 409 `comment_deleted`.\n\n**List filters must name a field (v0.75).** A `pad_item` `list` filter on a key no collection in scope declares, and no item stores, is refused with `validation_failed` (\"invalid list filter\"), where it used to return an empty list; a stored undeclared key still filters. Check the schema; don't retry.\n\n**Library words in a blank workspace (v0.67).** A brand-new blank workspace lists one convention trigger (`always`) and one scope (`all`). Activating a library entry, or creating a convention or playbook with a trigger or scope the library itself uses, adds that word to the collection's options and says so in `warnings.options_added`. A trigger you invent is still refused until the workspace owner adds it to the collection's schema.\n\n**App attribution (v0.65).** An item an installed app created, a comment an app wrote and a history row an app's write made carry `via_app` (the install id) and `via_app_name` (the app's name). On an item they name the app that CREATED it, not the last writer. They are absent for anything a person or an agent wrote.\n\n**Relation fields (v0.31).** A `relation` value may be a UUID, an issue ref (`COLO-3`) or the target's EXACT TITLE, tried in that order (a title that is also a ref resolves as the ref). A title matches only inside the declared collection, among items you can see; found only elsewhere, it is refused naming that collection; several matches are `ambiguous`. Full rules: docs/mcp.md.\n\nReads carry a `relation_targets` member beside `fields`: field key → `{id, ref, title}`, so you can render a relation without a request per value. `fields` still holds the canonical id, which is what you write back. An entry with an `id` and NO `ref`/`title` means the target is gone **or** you may not see it — the two are deliberately indistinguishable, so do not render it as either \"deleted\" or \"hidden\"; \"unavailable\" is the honest word. An entry with `stored_as_text: true` differs: the stored value is not UUID-shaped, so it was never an id (an imported title, legacy text). Render it as text, not as unavailable.\n\n**`multi_relation` fields (v0.33).** An ORDERED LIST of references, each resolved like a `relation` (UUID, ref, or exact title in the declared collection). Declare one as `owners:multi_relation:people`; the target collection is required. Rules: `[]` means absent; a blank element is refused by index; order is part of the value; duplicates are refused after resolution (`duplicate_referent`); any failing element refuses the whole write; `required` needs one resolved element; a cross-workspace copy drops the whole value (in `warnings.dropped_fields`). `relation_targets` holds an ARRAY of `{id, ref, title}` in stored order (`id`-only where unresolved); scalar keys stay single objects. Full rules: docs/mcp.md.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete / list-archived / restore. `delete` archives: the collection and its items leave every view, and `restore` brings them back. An `update` that removes a field or a select option still in use answers with `warnings.orphaned`: tell the user how many items keep the removed value.\n- `pad_project` — Project intelligence: dashboard / next / ready / stale / standup / changelog / report / activity. Use `ready` for the ranked top items to work on next (blocked work is left out) and `stale` for items needing attention; `activity` to catch up on what other agents/users changed since you last worked (non-streaming feed with item refs + change details).\n- `pad_role` — Agent roles: list / create / update / delete.\n- `pad_search` — Full-text search across items: query.\n- `pad_playbook` — Invokable procedures: list / get / run / match. Use `run` to bind args against a playbook's declared spec and get the rendered body back; side-effect-free. `run` refuses a playbook whose status isn't `active` (a draft still being authored) with a `playbook_not_active` error — pass `allow_draft: true` to override. Both `run` and `get` echo the playbook's `status`. Both may also carry `content_state` (`\"applied_pending_flush\"`, or `\"superseded_set_aside\"` as under `pad_item`), meaning the BODY you are about to execute is behind the item's live collaborative document — an editor holds unflushed edits, so the steps may be superseded. It is a reason to re-read or to ask, not a reason to refuse to run; the body is still the best the server has. `match` finds a playbook from text.\n- `pad_library` — Convention + playbook library (the global catalog of pre-built entries workspaces activate): list / get / activate.\n- `pad_attachment` — Read-only attachment metadata: list / show. `list` enumerates a workspace's attachments (filter by item / category / collection / attached / unattached); `show` returns one attachment's MIME, size, filename, and ETag via a HEAD request. Uploading and general file downloads stay CLI-only; bounded image bytes are available through the attachment resource below.\n- `pad_meta` — Server introspection: server-info / version / tool-surface / bootstrap. The `bootstrap` action returns one-shot workspace context (user + collections + always-on conventions + a metadata-only `convention_index` of every active convention + roles + playbook metadata + dashboard + recent activity).\n- `pad_set_workspace` — Load workspace context; response embeds the bootstrap blob so you load context in one call. Whether it also pins a session default: see Workspace context below. Takes `workspace: \u003cslug\u003e` only (no `action`).\n\nFor the ten resource × action tools, always pass `action` as a top-level field. Per-action required parameters are documented in each tool's description.\n\n## Resources are cheaper than tool calls\n\nRead these directly when you need workspace state (described in the resource listings): `pad://workspaces`, `pad://workspace/{ws}/dashboard`, `.../collections`, `.../items` (use `pad_item` `list` to filter), `.../items/{ref}` (markdown), `.../attachments/{id}` (images only, at most 1 MiB, as base64 `thumb-md`), `.../bootstrap` (the same payload as `pad_meta` `bootstrap`), and `pad://_meta/version`. A host can prefetch them once per session.\n\nLoad the bootstrap resource once per workspace and reuse its collections, conventions, roles, and playbook metadata. Refresh it after switching workspaces, after changing those configuration surfaces, when Pad reports stale schema/context, or when the user asks. For changing work state, read the affected item or use a targeted project tool instead of fetching the whole bootstrap again.\n\n## Workspace context\n\nEvery action that operates within a workspace accepts an optional `workspace` parameter. Resolution order:\n\n1. Explicit `workspace` argument on the call (always wins).\n2. On a single-user local server only: the session default set via `pad_set_workspace`.\n3. On a single-user local server only: the CWD-linked workspace from `.pad.toml`.\n\nA multi-user/remote server does **not** persist a session default — pass `workspace` explicitly on every call. If none resolves, the action returns a structured `no_workspace` error with `available_workspaces`, on both the local and the remote transport.\n\n## Update flow: read first, then patch\n\nFor `pad_item.action: update`, the server merges your patch with the item's current state. Pass only the fields you want to change. When changing `status`, ALWAYS include a `comment` explaining why — it builds the audit trail that helps the team understand history.\n\n## One error code you must not retry\n\nErrors come back as a structured envelope with a `code`. Most failures are worth a retry after you fix something, and a `server_error` may be transient. `stored_state_unreadable` is neither.\n\nIt means the ITEM'S STORED DATA cannot be decoded — your input was fine. Today it fires when `note` / `decide` would append to an `implementation_notes` / `decision_log` value that is not a list of entries. The operation is refused precisely because completing it would overwrite that value. The refusal is fully deterministic, so retrying — immediately or after a backoff — fails identically every time and changes nothing.\n\nWhen you see it: tell the user which item is affected, and stop. Whether you can inspect the bad value depends on which layer is broken — if the item's whole `fields` blob fails to parse, `action: get` hands it back as a raw string; if one structured key is at fault, you won't see it at all, because the blob is normalized on this surface and a value that doesn't decode is dropped from the top-level arrays. A human can always read it with `pad item show \u003cref\u003e --format json`. Do not route around the refusal by writing the field some other way; that is the write that caused it.\n\n## Project conventions\n\nWorkspaces can declare conventions (e.g. \"run `make test` before PR\", \"use conventional commit format\"). The bootstrap blob gives you two views:\n\n- `conventions` — full bodies of the always-on (`trigger=always`) rules. Follow these unconditionally.\n- `convention_index` — METADATA ONLY (`ref`, `title`, `trigger`, `role`; no bodies) for **every** active convention, including the triggered ones whose bodies are NOT in `conventions`. This is your map of what triggered rules exist.\n\nBefore performing meaningful work with a specific trigger (e.g. `on-implement` before writing code), consult `convention_index`: if it lists entries for that trigger, pull their bodies on demand; if it lists none, skip the query.\n\n```\npad_item.action: list, collection: \"conventions\", status: \"active\"\n```\n\nFilter by trigger (`always`, `on-implement`, `on-task-complete`, etc.) when relevant — the `convention_index` triggers tell you which filters are worth running.\n\n`\"conventions\"` above is the DEFAULT collection slug and a workspace may have renamed it, in which case that literal returns nothing while `convention_index` still lists entries — the bootstrap payload resolves by declaration, not by name. When the two disagree, address the items by the `ref`s the index gave you, or find the collection with `pad_collection.action: list`. The same applies to `\"playbooks\"`; `pad_playbook` resolves by declaration and is unaffected.\n\n## Pushes and the session monitor (security note)\n\nPad can push an item into a Claude Code session (`pad push`, or the web item view's push composer). That is terminal instruction injection by design, so receiving is **consent-gated** (PLAN-2613, since v0.15.0): a session receives pushes only after it has connected (`/pad:connect` in the plugin, or a repo-level `push.auto_arm = true` in `.pad.toml` — which a per-user `auto_arm = false` in `~/.pad/config.toml` vetoes), and pushes are self-addressed only — the sender is always the receiving session's own user. This MCP connection is not a session: it cannot arm one, receive a push, or run the monitor, and the `pad_item` / `pad_project` tools expose no push action. If a user asks you to \"push\" something to their terminal, tell them it happens from their own terminal (`pad push \u003cref\u003e -m \"...\"` — the sending session need not be connected, the receiving ones must have consented); do not try to emulate it by writing comments or instructions into items.\n\n## Adding a workspace to this connection\n\nIf the user references a workspace this connection can't see (you'll get a 403 from workspace tools, or the workspace won't appear in `pad_workspace.list`), tell the user you can't see that workspace with your current permissions, then walk them through how to grant access: open Pad in their browser → switch to that workspace → avatar menu → \"Connect project...\" A 6-digit claim code will appear. Have them paste it back in chat, then call `pad_workspace.claim` with `{workspace: \"\u003cslug\u003e\", code: \"\u003c6 digits\u003e\"}`. The workspace joins this connection's allow-list and stays until the user revokes it via `/console/connected-apps`. No re-auth required.\n\nFor brand-new workspaces, `pad_workspace.create` with `{name: \"\u003cname\u003e\"}` (and optional `template`) creates the workspace AND auto-adds it to this connection's allow-list in one call — no claim code needed. Only works when the connection currently carries the \"may create workspaces\" grant — granted at consent time, or enabled later on the connections page. If the grant is present and set to false, the create is **refused with a 403 and no workspace is made** — retrying won't help and neither will the claim flow, since there is nothing to claim. Tell the user this connection isn't permitted to create workspaces, and offer them the two ways forward: create the workspace themselves in the browser and grant access with a claim code, or re-authorize this connection with \"Let this app create new workspaces\" enabled (`/console/connected-apps` can also flip it on an existing connection).\n\n## New workspace: offer to set it up\n\nThe bootstrap blob carries `needs_onboarding: bool` — true when the workspace has zero user-created items (template seeds don't count). When it's true, **lead with an active offer before anything else**: *\"This workspace is brand new and isn't set up yet. Want me to set it up? I'll ask a few quick questions and adapt it to your project.\"*\n\nThis is an **offer, not an auto-run** — wait for the user to say yes before running onboarding. If they accept, run the `onboard` playbook (use the `pad_onboard` prompt, or load the body via `pad_playbook` `action: get`, `ref: onboard`). If they decline, or already declined earlier in the session, respect that and skip the offer. The flag flips to false the moment any item exists, so it won't nag past first setup.\n\n## Built-in updates: mention once\n\nThe bootstrap blob may carry `builtin_updates: int` (absent when there are none): how many of the conventions and playbooks Pad ships have newer text in Pad's library than this workspace's copy. When it is present, mention it **once per session**, in one line, then carry on. **Never apply an update yourself**: a person reviews each one and accepts it or not.\n\n## Multi-step workflows\n\nFour prompts ship with the server: `pad_plan`, `pad_ideate`, `pad_retro`, `pad_onboard`. Use them when the user wants help planning, brainstorming, retrospecting, or onboarding into a workspace — they encode the multi-step Pad-aware playbook for each.\n" } diff --git a/cmd/pad/testdata/mcp_wire/remote_tools_list.json b/cmd/pad/testdata/mcp_wire/remote_tools_list.json index a6b8f162e..3b04bcf7a 100644 --- a/cmd/pad/testdata/mcp_wire/remote_tools_list.json +++ b/cmd/pad/testdata/mcp_wire/remote_tools_list.json @@ -339,7 +339,7 @@ "type": "string" }, "limit": { - "description": "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions.", + "description": "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions. starred takes no limit: it returns at most 300, most recently starred first, with has_more when more exist.", "type": "number" }, "lines": { diff --git a/cmd/pad/testdata/mcp_wire/stdio_initialize.json b/cmd/pad/testdata/mcp_wire/stdio_initialize.json index 4d60ba6d7..e37591b79 100644 --- a/cmd/pad/testdata/mcp_wire/stdio_initialize.json +++ b/cmd/pad/testdata/mcp_wire/stdio_initialize.json @@ -8,7 +8,7 @@ }, "padToolSurface": { "tool_surface_stable": true, - "version": "0.98" + "version": "0.99" } }, "prompts": {}, @@ -21,5 +21,5 @@ "name": "pad-mcp", "version": "" }, - "instructions": "Pad is a project tracker for developers and AI agents — issues (TASK, BUG), plans (PLAN), ideas (IDEA), docs (DOC), conventions, comments, and dependencies. Use this server when a user mentions:\n\n- Issue refs like `TASK-5`, `BUG-12`, `PLAN-3`, `IDEA-8` — they are stable, human-readable IDs and the canonical way to address items. Use them, never slugs; they are what audit trails and PR titles show.\n- Tasks / issues / items / plans / progress / \"what's on my plate\" / \"what to work on next\" / standup / changelog / retrospective.\n- Project conventions, decision records, or \"how should this team do X.\"\n\nIf the user is asking general code questions with no project-management thread, you don't need this server.\n\n## Tool surface (v0.98)\n\nTen resource × action tools, plus `pad_set_workspace`. Eleven tools total.\n\nInputs are validated strictly: an undeclared top-level key is rejected with a structured `validation_failed` naming it, never accepted and silently dropped.\n\n- `pad_item` — Items: create / update / delete / get / list / move / restore / link / unlink / deps / context / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / reminders / unremind / link-pr / unlink-pr / claim / release / patch. On create/update, field values may be passed as a `fields` OBJECT (the same shape reads return, e.g. `{\"status\":\"done\",\"effort\":\"l\"}`) — it merges into the same path as the dedicated params and `field: [\"key=value\"]`; the same key in two places with CONFLICTING values is refused, not silently resolved. `list` accepts `unparented: true` to keep items with no parent or implements relationship (mutually exclusive with `parent`). `list` results are SUMMARY-shaped by default on both transports — no content bodies; pass `full: true` for complete bodies (token-expensive), or prefer `get` for a single item's body. `update` field writes are a server-side field-level merge (only the keys you set change); pass `expected_seq` for optimistic concurrency — the `seq` you last read, which is on every item AND every list summary — and a stale value fails with a structured 409 `update_conflict` whose details carry `actual_seq` to retry with. PREFER IT over `expected_updated_at`, which cannot tell two writes inside one second apart; that one still works, and if you send both, seq decides. To change PART of a body, prefer `patch`: `edits: [{old, new}]`, where each `old` is exact text occurring once in the current body (read it with `get` and `lines: \"A-B\"` to quote it). The answer is a unified `diff`: read it, because anchors guarantee position, not meaning. A moved `expected_seq` is applied over and reported as `rebased` with the intervening writes. On an item open in a browser editor, the editor applies the patch to its live document, merging with the typing there, and the answer says `content_state: \"applied_pending_flush\"`. `patch_anchor_missing` / `patch_anchor_ambiguous` mean re-read and quote current text; `patch_unstable_roundtrip` means the open editor would also change content you did not edit, so send a whole-body update; `patch_room_open` means an older editor that cannot apply patches holds the item. Every patch answer carries a `patch_id`; `patch` with `undo: \u003cpatch_id\u003e` inverts it, and is refused when the text it changed has changed since. Send an `op_key` (any unique string, e.g. a UUID) with a patch whenever you might retry it: the same request with the same key returns the first answer instead of applying twice. `patch_outcome_unknown` means an earlier attempt's editor never confirmed it and is gone; read `details.diff` before deciding. `content` REPLACES the whole body, so send `expected_seq` with it: `get` the item, edit that body, and send it back with the `seq` you read. An `update_conflict` whose details carry `content_write` means someone changed the item after your read. Do NOT resend your body, because it would undo their change: re-read, apply your edit to the current content, and send that with the new seq. `replace: true` overwrites on purpose instead. A content write with neither carries `warnings.unguarded_content_write`, and a later release refuses it. A token cannot see a browser tab's unsaved edits, so `content` sent WITH one is refused with 409 `content_pending_flush` while any exist; re-reading will not clear it. Wait for the editor to save, or pass `overwrite_pending_edits: true` to replace them. `content_state: \"superseded_set_aside\"` is different and wins when both apply: an editor upgrade set aside edits no tab can restore, so EVERY content write is refused (token or not; `details.set_aside_rows`) and waiting never clears it. Tell the user, or pass `overwrite_pending_edits: true` to discard them. Writing `content` while a browser tab has the item open routes the markdown through that live document; the stored row updates only on a later collab-snapshot flush, which nothing guarantees. The 200 echoes what you SENT with `warnings.content_outcome: \"applied_pending_flush\"`, which describes your WRITE (it went to the document, not the row). A `get` (or a `list` with `full: true`; a default list carries no content) before the flush returns the PREVIOUS content: that is lag, not a failed write, so do not re-send. A read whose body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"`, also when someone ELSE's tab holds the edits and you wrote nothing: same value, but it describes the ROW, not your request. Treat it as re-read later, never as re-send, and do not wait on it in a loop: the server normally recovers the stored copy itself about a minute after the last tab leaves the item, but that is not guaranteed (a recovery can fail, and an operator can turn it off), and otherwise the row catches up only when a tab next opens the item. The stored form may also not be byte-identical to what you sent, since the markdown round-trips through the editor (bullet markers, emphasis characters, list numbering and blank-line runs normalise; already-canonical markdown survives unchanged), so compare on meaning rather than bytes. `move` changes an item's COLLECTION within its workspace: system metadata (implementation notes, decision log, linked PR) survives it, and any field value the target schema has no home for is dropped AND reported in the move's activity entry — check there rather than assuming a move is lossless. A carried unique-field collision is dropped, named in `warnings.not_unique`. Three system keys — `implementation_notes`, `decision_log`, `convention` — cannot be set through `field` on update or move; the call is refused with `validation_failed`, naming the key and the write path that does maintain it (`note`, `decide`, and library activation respectively). `github_pr` is refused as well (BUG-2696): a `field` value arrived as a string, so the PR data was stored double-encoded and no link appeared. Its writers are `action=link-pr` (`pr_number` + `pr_url`, metadata you supply; nothing is fetched from GitHub) and `action=unlink-pr`. On `create` they are refused too (BUG-3163), with the same `validation_failed`: create the item first, then use `note` / `decide` on it; convention metadata comes from library activation. `context` (`intent`, `role`, `budget`): one brief before you start work, with parents, matching convention bodies, deps and links. `history` returns read-only item version metadata (newest-first), bounded to the NEWEST 50 versions by default (max 300 — pass `limit` to change the window); pass `full: true` to include each version's resolved content body (token-expensive). There is no `offset`: versions are stored as reverse patches, so only a newest-end window is cheap to reconstruct. Unassign or detach with the `clear_assigned_user` / `clear_agent_role` / `clear_parent` booleans; an empty `assign` / `role` / `parent` does NOT clear. `remind` / `ack-reminder`: a fired reminder shows in `pad_project` next / ready (the delivery path on an instance with no webhook) until acknowledged, and one on a completed item is hidden there. `claim` / `release`: claim an item before you work it; a loser's 409 is `lease_held` (pick another, don't retry), and a lease bumps neither `updated_at` nor `seq`. A claim answers your `worker_id`; pass it to resume elsewhere. next / ready skip items other workers hold. `edit-comment` / `delete-comment` take a `comment_id` from `list-comments` (whose rows carry `edited`); only a comment's author may edit it. Correct a comment in place rather than appending a correction. Deleting a comment that has replies leaves a placeholder (`deleted: true`, empty body) so the replies keep their parent; editing, replying to or reacting to it answers 409 `comment_deleted`.\n\n**List filters must name a field (v0.75).** A `pad_item` `list` filter on a key no collection in scope declares, and no item stores, is refused with `validation_failed` (\"invalid list filter\"), where it used to return an empty list; a stored undeclared key still filters. Check the schema; don't retry.\n\n**Library words in a blank workspace (v0.67).** A brand-new blank workspace lists one convention trigger (`always`) and one scope (`all`). Activating a library entry, or creating a convention or playbook with a trigger or scope the library itself uses, adds that word to the collection's options and says so in `warnings.options_added`. A trigger you invent is still refused until the workspace owner adds it to the collection's schema.\n\n**App attribution (v0.65).** An item an installed app created, a comment an app wrote and a history row an app's write made carry `via_app` (the install id) and `via_app_name` (the app's name). On an item they name the app that CREATED it, not the last writer. They are absent for anything a person or an agent wrote.\n\n**Relation fields (v0.31).** A `relation` value may be a UUID, an issue ref (`COLO-3`) or the target's EXACT TITLE, tried in that order (a title that is also a ref resolves as the ref). A title matches only inside the declared collection, among items you can see; found only elsewhere, it is refused naming that collection; several matches are `ambiguous`. Full rules: docs/mcp.md.\n\nReads carry a `relation_targets` member beside `fields`: field key → `{id, ref, title}`, so you can render a relation without a request per value. `fields` still holds the canonical id, which is what you write back. An entry with an `id` and NO `ref`/`title` means the target is gone **or** you may not see it — the two are deliberately indistinguishable, so do not render it as either \"deleted\" or \"hidden\"; \"unavailable\" is the honest word. An entry with `stored_as_text: true` differs: the stored value is not UUID-shaped, so it was never an id (an imported title, legacy text). Render it as text, not as unavailable.\n\n**`multi_relation` fields (v0.33).** An ORDERED LIST of references, each resolved like a `relation` (UUID, ref, or exact title in the declared collection). Declare one as `owners:multi_relation:people`; the target collection is required. Rules: `[]` means absent; a blank element is refused by index; order is part of the value; duplicates are refused after resolution (`duplicate_referent`); any failing element refuses the whole write; `required` needs one resolved element; a cross-workspace copy drops the whole value (in `warnings.dropped_fields`). `relation_targets` holds an ARRAY of `{id, ref, title}` in stored order (`id`-only where unresolved); scalar keys stay single objects. Full rules: docs/mcp.md.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete / list-archived / restore. `delete` archives: the collection and its items leave every view, and `restore` brings them back. An `update` that removes a field or a select option still in use answers with `warnings.orphaned`: tell the user how many items keep the removed value.\n- `pad_project` — Project intelligence: dashboard / next / ready / stale / standup / changelog / report / activity. Use `ready` for the ranked top items to work on next (blocked work is left out) and `stale` for items needing attention; `activity` to catch up on what other agents/users changed since you last worked (non-streaming feed with item refs + change details).\n- `pad_role` — Agent roles: list / create / update / delete.\n- `pad_search` — Full-text search across items: query.\n- `pad_playbook` — Invokable procedures: list / get / run / match. Use `run` to bind args against a playbook's declared spec and get the rendered body back; side-effect-free. `run` refuses a playbook whose status isn't `active` (a draft still being authored) with a `playbook_not_active` error — pass `allow_draft: true` to override. Both `run` and `get` echo the playbook's `status`. Both may also carry `content_state` (`\"applied_pending_flush\"`, or `\"superseded_set_aside\"` as under `pad_item`), meaning the BODY you are about to execute is behind the item's live collaborative document — an editor holds unflushed edits, so the steps may be superseded. It is a reason to re-read or to ask, not a reason to refuse to run; the body is still the best the server has. `match` finds a playbook from text.\n- `pad_library` — Convention + playbook library (the global catalog of pre-built entries workspaces activate): list / get / activate.\n- `pad_attachment` — Read-only attachment metadata: list / show. `list` enumerates a workspace's attachments (filter by item / category / collection / attached / unattached); `show` returns one attachment's MIME, size, filename, and ETag via a HEAD request. Uploading and general file downloads stay CLI-only; bounded image bytes are available through the attachment resource below.\n- `pad_meta` — Server introspection: server-info / version / tool-surface / bootstrap. The `bootstrap` action returns one-shot workspace context (user + collections + always-on conventions + a metadata-only `convention_index` of every active convention + roles + playbook metadata + dashboard + recent activity).\n- `pad_set_workspace` — Load workspace context; response embeds the bootstrap blob so you load context in one call. Whether it also pins a session default: see Workspace context below. Takes `workspace: \u003cslug\u003e` only (no `action`).\n\nFor the ten resource × action tools, always pass `action` as a top-level field. Per-action required parameters are documented in each tool's description.\n\n## Resources are cheaper than tool calls\n\nRead these directly when you need workspace state (described in the resource listings): `pad://workspaces`, `pad://workspace/{ws}/dashboard`, `.../collections`, `.../items` (use `pad_item` `list` to filter), `.../items/{ref}` (markdown), `.../attachments/{id}` (images only, at most 1 MiB, as base64 `thumb-md`), `.../bootstrap` (the same payload as `pad_meta` `bootstrap`), and `pad://_meta/version`. A host can prefetch them once per session.\n\nLoad the bootstrap resource once per workspace and reuse its collections, conventions, roles, and playbook metadata. Refresh it after switching workspaces, after changing those configuration surfaces, when Pad reports stale schema/context, or when the user asks. For changing work state, read the affected item or use a targeted project tool instead of fetching the whole bootstrap again.\n\n## Workspace context\n\nEvery action that operates within a workspace accepts an optional `workspace` parameter. Resolution order:\n\n1. Explicit `workspace` argument on the call (always wins).\n2. On a single-user local server only: the session default set via `pad_set_workspace`.\n3. On a single-user local server only: the CWD-linked workspace from `.pad.toml`.\n\nA multi-user/remote server does **not** persist a session default — pass `workspace` explicitly on every call. If none resolves, the action returns a structured `no_workspace` error with `available_workspaces`, on both the local and the remote transport.\n\n## Update flow: read first, then patch\n\nFor `pad_item.action: update`, the server merges your patch with the item's current state. Pass only the fields you want to change. When changing `status`, ALWAYS include a `comment` explaining why — it builds the audit trail that helps the team understand history.\n\n## One error code you must not retry\n\nErrors come back as a structured envelope with a `code`. Most failures are worth a retry after you fix something, and a `server_error` may be transient. `stored_state_unreadable` is neither.\n\nIt means the ITEM'S STORED DATA cannot be decoded — your input was fine. Today it fires when `note` / `decide` would append to an `implementation_notes` / `decision_log` value that is not a list of entries. The operation is refused precisely because completing it would overwrite that value. The refusal is fully deterministic, so retrying — immediately or after a backoff — fails identically every time and changes nothing.\n\nWhen you see it: tell the user which item is affected, and stop. Whether you can inspect the bad value depends on which layer is broken — if the item's whole `fields` blob fails to parse, `action: get` hands it back as a raw string; if one structured key is at fault, you won't see it at all, because the blob is normalized on this surface and a value that doesn't decode is dropped from the top-level arrays. A human can always read it with `pad item show \u003cref\u003e --format json`. Do not route around the refusal by writing the field some other way; that is the write that caused it.\n\n## Project conventions\n\nWorkspaces can declare conventions (e.g. \"run `make test` before PR\", \"use conventional commit format\"). The bootstrap blob gives you two views:\n\n- `conventions` — full bodies of the always-on (`trigger=always`) rules. Follow these unconditionally.\n- `convention_index` — METADATA ONLY (`ref`, `title`, `trigger`, `role`; no bodies) for **every** active convention, including the triggered ones whose bodies are NOT in `conventions`. This is your map of what triggered rules exist.\n\nBefore performing meaningful work with a specific trigger (e.g. `on-implement` before writing code), consult `convention_index`: if it lists entries for that trigger, pull their bodies on demand; if it lists none, skip the query.\n\n```\npad_item.action: list, collection: \"conventions\", status: \"active\"\n```\n\nFilter by trigger (`always`, `on-implement`, `on-task-complete`, etc.) when relevant — the `convention_index` triggers tell you which filters are worth running.\n\n`\"conventions\"` above is the DEFAULT collection slug and a workspace may have renamed it, in which case that literal returns nothing while `convention_index` still lists entries — the bootstrap payload resolves by declaration, not by name. When the two disagree, address the items by the `ref`s the index gave you, or find the collection with `pad_collection.action: list`. The same applies to `\"playbooks\"`; `pad_playbook` resolves by declaration and is unaffected.\n\n## Pushes and the session monitor (security note)\n\nPad can push an item into a Claude Code session (`pad push`, or the web item view's push composer). That is terminal instruction injection by design, so receiving is **consent-gated** (PLAN-2613, since v0.15.0): a session receives pushes only after it has connected (`/pad:connect` in the plugin, or a repo-level `push.auto_arm = true` in `.pad.toml` — which a per-user `auto_arm = false` in `~/.pad/config.toml` vetoes), and pushes are self-addressed only — the sender is always the receiving session's own user. This MCP connection is not a session: it cannot arm one, receive a push, or run the monitor, and the `pad_item` / `pad_project` tools expose no push action. If a user asks you to \"push\" something to their terminal, tell them it happens from their own terminal (`pad push \u003cref\u003e -m \"...\"` — the sending session need not be connected, the receiving ones must have consented); do not try to emulate it by writing comments or instructions into items.\n\n## Adding a workspace to this connection\n\nIf the user references a workspace this connection can't see (you'll get a 403 from workspace tools, or the workspace won't appear in `pad_workspace.list`), tell the user you can't see that workspace with your current permissions, then walk them through how to grant access: open Pad in their browser → switch to that workspace → avatar menu → \"Connect project...\" A 6-digit claim code will appear. Have them paste it back in chat, then call `pad_workspace.claim` with `{workspace: \"\u003cslug\u003e\", code: \"\u003c6 digits\u003e\"}`. The workspace joins this connection's allow-list and stays until the user revokes it via `/console/connected-apps`. No re-auth required.\n\nFor brand-new workspaces, `pad_workspace.create` with `{name: \"\u003cname\u003e\"}` (and optional `template`) creates the workspace AND auto-adds it to this connection's allow-list in one call — no claim code needed. Only works when the connection currently carries the \"may create workspaces\" grant — granted at consent time, or enabled later on the connections page. If the grant is present and set to false, the create is **refused with a 403 and no workspace is made** — retrying won't help and neither will the claim flow, since there is nothing to claim. Tell the user this connection isn't permitted to create workspaces, and offer them the two ways forward: create the workspace themselves in the browser and grant access with a claim code, or re-authorize this connection with \"Let this app create new workspaces\" enabled (`/console/connected-apps` can also flip it on an existing connection).\n\n## New workspace: offer to set it up\n\nThe bootstrap blob carries `needs_onboarding: bool` — true when the workspace has zero user-created items (template seeds don't count). When it's true, **lead with an active offer before anything else**: *\"This workspace is brand new and isn't set up yet. Want me to set it up? I'll ask a few quick questions and adapt it to your project.\"*\n\nThis is an **offer, not an auto-run** — wait for the user to say yes before running onboarding. If they accept, run the `onboard` playbook (use the `pad_onboard` prompt, or load the body via `pad_playbook` `action: get`, `ref: onboard`). If they decline, or already declined earlier in the session, respect that and skip the offer. The flag flips to false the moment any item exists, so it won't nag past first setup.\n\n## Built-in updates: mention once\n\nThe bootstrap blob may carry `builtin_updates: int` (absent when there are none): how many of the conventions and playbooks Pad ships have newer text in Pad's library than this workspace's copy. When it is present, mention it **once per session**, in one line, then carry on. **Never apply an update yourself**: a person reviews each one and accepts it or not.\n\n## Multi-step workflows\n\nFour prompts ship with the server: `pad_plan`, `pad_ideate`, `pad_retro`, `pad_onboard`. Use them when the user wants help planning, brainstorming, retrospecting, or onboarding into a workspace — they encode the multi-step Pad-aware playbook for each.\n" + "instructions": "Pad is a project tracker for developers and AI agents — issues (TASK, BUG), plans (PLAN), ideas (IDEA), docs (DOC), conventions, comments, and dependencies. Use this server when a user mentions:\n\n- Issue refs like `TASK-5`, `BUG-12`, `PLAN-3`, `IDEA-8` — they are stable, human-readable IDs and the canonical way to address items. Use them, never slugs; they are what audit trails and PR titles show.\n- Tasks / issues / items / plans / progress / \"what's on my plate\" / \"what to work on next\" / standup / changelog / retrospective.\n- Project conventions, decision records, or \"how should this team do X.\"\n\nIf the user is asking general code questions with no project-management thread, you don't need this server.\n\n## Tool surface (v0.99)\n\nTen resource × action tools, plus `pad_set_workspace`. Eleven tools total.\n\nInputs are validated strictly: an undeclared top-level key is rejected with a structured `validation_failed` naming it, never accepted and silently dropped.\n\n- `pad_item` — Items: create / update / delete / get / list / move / restore / link / unlink / deps / context / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / reminders / unremind / link-pr / unlink-pr / claim / release / patch. On create/update, field values may be passed as a `fields` OBJECT (the same shape reads return, e.g. `{\"status\":\"done\",\"effort\":\"l\"}`) — it merges into the same path as the dedicated params and `field: [\"key=value\"]`; the same key in two places with CONFLICTING values is refused, not silently resolved. `list` accepts `unparented: true` to keep items with no parent or implements relationship (mutually exclusive with `parent`). `list` results are SUMMARY-shaped by default on both transports — no content bodies; pass `full: true` for complete bodies (token-expensive), or prefer `get` for a single item's body. `update` field writes are a server-side field-level merge (only the keys you set change); pass `expected_seq` for optimistic concurrency — the `seq` you last read, which is on every item AND every list summary — and a stale value fails with a structured 409 `update_conflict` whose details carry `actual_seq` to retry with. PREFER IT over `expected_updated_at`, which cannot tell two writes inside one second apart; that one still works, and if you send both, seq decides. To change PART of a body, prefer `patch`: `edits: [{old, new}]`, where each `old` is exact text occurring once in the current body (read it with `get` and `lines: \"A-B\"` to quote it). The answer is a unified `diff`: read it, because anchors guarantee position, not meaning. A moved `expected_seq` is applied over and reported as `rebased` with the intervening writes. On an item open in a browser editor, the editor applies the patch to its live document, merging with the typing there, and the answer says `content_state: \"applied_pending_flush\"`. `patch_anchor_missing` / `patch_anchor_ambiguous` mean re-read and quote current text; `patch_unstable_roundtrip` means the open editor would also change content you did not edit, so send a whole-body update; `patch_room_open` means an older editor that cannot apply patches holds the item. Every patch answer carries a `patch_id`; `patch` with `undo: \u003cpatch_id\u003e` inverts it, and is refused when the text it changed has changed since. Send an `op_key` (any unique string, e.g. a UUID) with a patch whenever you might retry it: the same request with the same key returns the first answer instead of applying twice. `patch_outcome_unknown` means an earlier attempt's editor never confirmed it and is gone; read `details.diff` before deciding. `content` REPLACES the whole body, so send `expected_seq` with it: `get` the item, edit that body, and send it back with the `seq` you read. An `update_conflict` whose details carry `content_write` means someone changed the item after your read. Do NOT resend your body, because it would undo their change: re-read, apply your edit to the current content, and send that with the new seq. `replace: true` overwrites on purpose instead. A content write with neither carries `warnings.unguarded_content_write`, and a later release refuses it. A token cannot see a browser tab's unsaved edits, so `content` sent WITH one is refused with 409 `content_pending_flush` while any exist; re-reading will not clear it. Wait for the editor to save, or pass `overwrite_pending_edits: true` to replace them. `content_state: \"superseded_set_aside\"` is different and wins when both apply: an editor upgrade set aside edits no tab can restore, so EVERY content write is refused (token or not; `details.set_aside_rows`) and waiting never clears it. Tell the user, or pass `overwrite_pending_edits: true` to discard them. Writing `content` while a browser tab has the item open routes the markdown through that live document; the stored row updates only on a later collab-snapshot flush, which nothing guarantees. The 200 echoes what you SENT with `warnings.content_outcome: \"applied_pending_flush\"`, which describes your WRITE (it went to the document, not the row). A `get` (or a `list` with `full: true`; a default list carries no content) before the flush returns the PREVIOUS content: that is lag, not a failed write, so do not re-send. A read whose body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"`, also when someone ELSE's tab holds the edits and you wrote nothing: same value, but it describes the ROW, not your request. Treat it as re-read later, never as re-send, and do not wait on it in a loop: the server normally recovers the stored copy itself about a minute after the last tab leaves the item, but that is not guaranteed (a recovery can fail, and an operator can turn it off), and otherwise the row catches up only when a tab next opens the item. The stored form may also not be byte-identical to what you sent, since the markdown round-trips through the editor (bullet markers, emphasis characters, list numbering and blank-line runs normalise; already-canonical markdown survives unchanged), so compare on meaning rather than bytes. `move` changes an item's COLLECTION within its workspace: system metadata (implementation notes, decision log, linked PR) survives it, and any field value the target schema has no home for is dropped AND reported in the move's activity entry — check there rather than assuming a move is lossless. A carried unique-field collision is dropped, named in `warnings.not_unique`. Three system keys — `implementation_notes`, `decision_log`, `convention` — cannot be set through `field` on update or move; the call is refused with `validation_failed`, naming the key and the write path that does maintain it (`note`, `decide`, and library activation respectively). `github_pr` is refused as well (BUG-2696): a `field` value arrived as a string, so the PR data was stored double-encoded and no link appeared. Its writers are `action=link-pr` (`pr_number` + `pr_url`, metadata you supply; nothing is fetched from GitHub) and `action=unlink-pr`. On `create` they are refused too (BUG-3163), with the same `validation_failed`: create the item first, then use `note` / `decide` on it; convention metadata comes from library activation. `context` (`intent`, `role`, `budget`): one brief before you start work, with parents, matching convention bodies, deps and links. `history` returns read-only item version metadata (newest-first), bounded to the NEWEST 50 versions by default (max 300 — pass `limit` to change the window); pass `full: true` to include each version's resolved content body (token-expensive). There is no `offset`: versions are stored as reverse patches, so only a newest-end window is cheap to reconstruct. Unassign or detach with the `clear_assigned_user` / `clear_agent_role` / `clear_parent` booleans; an empty `assign` / `role` / `parent` does NOT clear. `remind` / `ack-reminder`: a fired reminder shows in `pad_project` next / ready (the delivery path on an instance with no webhook) until acknowledged, and one on a completed item is hidden there. `claim` / `release`: claim an item before you work it; a loser's 409 is `lease_held` (pick another, don't retry), and a lease bumps neither `updated_at` nor `seq`. A claim answers your `worker_id`; pass it to resume elsewhere. next / ready skip items other workers hold. `edit-comment` / `delete-comment` take a `comment_id` from `list-comments` (whose rows carry `edited`); only a comment's author may edit it. Correct a comment in place rather than appending a correction. Deleting a comment that has replies leaves a placeholder (`deleted: true`, empty body) so the replies keep their parent; editing, replying to or reacting to it answers 409 `comment_deleted`.\n\n**List filters must name a field (v0.75).** A `pad_item` `list` filter on a key no collection in scope declares, and no item stores, is refused with `validation_failed` (\"invalid list filter\"), where it used to return an empty list; a stored undeclared key still filters. Check the schema; don't retry.\n\n**Library words in a blank workspace (v0.67).** A brand-new blank workspace lists one convention trigger (`always`) and one scope (`all`). Activating a library entry, or creating a convention or playbook with a trigger or scope the library itself uses, adds that word to the collection's options and says so in `warnings.options_added`. A trigger you invent is still refused until the workspace owner adds it to the collection's schema.\n\n**App attribution (v0.65).** An item an installed app created, a comment an app wrote and a history row an app's write made carry `via_app` (the install id) and `via_app_name` (the app's name). On an item they name the app that CREATED it, not the last writer. They are absent for anything a person or an agent wrote.\n\n**Relation fields (v0.31).** A `relation` value may be a UUID, an issue ref (`COLO-3`) or the target's EXACT TITLE, tried in that order (a title that is also a ref resolves as the ref). A title matches only inside the declared collection, among items you can see; found only elsewhere, it is refused naming that collection; several matches are `ambiguous`. Full rules: docs/mcp.md.\n\nReads carry a `relation_targets` member beside `fields`: field key → `{id, ref, title}`, so you can render a relation without a request per value. `fields` still holds the canonical id, which is what you write back. An entry with an `id` and NO `ref`/`title` means the target is gone **or** you may not see it — the two are deliberately indistinguishable, so do not render it as either \"deleted\" or \"hidden\"; \"unavailable\" is the honest word. An entry with `stored_as_text: true` differs: the stored value is not UUID-shaped, so it was never an id (an imported title, legacy text). Render it as text, not as unavailable.\n\n**`multi_relation` fields (v0.33).** An ORDERED LIST of references, each resolved like a `relation` (UUID, ref, or exact title in the declared collection). Declare one as `owners:multi_relation:people`; the target collection is required. Rules: `[]` means absent; a blank element is refused by index; order is part of the value; duplicates are refused after resolution (`duplicate_referent`); any failing element refuses the whole write; `required` needs one resolved element; a cross-workspace copy drops the whole value (in `warnings.dropped_fields`). `relation_targets` holds an ARRAY of `{id, ref, title}` in stored order (`id`-only where unresolved); scalar keys stay single objects. Full rules: docs/mcp.md.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete / list-archived / restore. `delete` archives: the collection and its items leave every view, and `restore` brings them back. An `update` that removes a field or a select option still in use answers with `warnings.orphaned`: tell the user how many items keep the removed value.\n- `pad_project` — Project intelligence: dashboard / next / ready / stale / standup / changelog / report / activity. Use `ready` for the ranked top items to work on next (blocked work is left out) and `stale` for items needing attention; `activity` to catch up on what other agents/users changed since you last worked (non-streaming feed with item refs + change details).\n- `pad_role` — Agent roles: list / create / update / delete.\n- `pad_search` — Full-text search across items: query.\n- `pad_playbook` — Invokable procedures: list / get / run / match. Use `run` to bind args against a playbook's declared spec and get the rendered body back; side-effect-free. `run` refuses a playbook whose status isn't `active` (a draft still being authored) with a `playbook_not_active` error — pass `allow_draft: true` to override. Both `run` and `get` echo the playbook's `status`. Both may also carry `content_state` (`\"applied_pending_flush\"`, or `\"superseded_set_aside\"` as under `pad_item`), meaning the BODY you are about to execute is behind the item's live collaborative document — an editor holds unflushed edits, so the steps may be superseded. It is a reason to re-read or to ask, not a reason to refuse to run; the body is still the best the server has. `match` finds a playbook from text.\n- `pad_library` — Convention + playbook library (the global catalog of pre-built entries workspaces activate): list / get / activate.\n- `pad_attachment` — Read-only attachment metadata: list / show. `list` enumerates a workspace's attachments (filter by item / category / collection / attached / unattached); `show` returns one attachment's MIME, size, filename, and ETag via a HEAD request. Uploading and general file downloads stay CLI-only; bounded image bytes are available through the attachment resource below.\n- `pad_meta` — Server introspection: server-info / version / tool-surface / bootstrap. The `bootstrap` action returns one-shot workspace context (user + collections + always-on conventions + a metadata-only `convention_index` of every active convention + roles + playbook metadata + dashboard + recent activity).\n- `pad_set_workspace` — Load workspace context; response embeds the bootstrap blob so you load context in one call. Whether it also pins a session default: see Workspace context below. Takes `workspace: \u003cslug\u003e` only (no `action`).\n\nFor the ten resource × action tools, always pass `action` as a top-level field. Per-action required parameters are documented in each tool's description.\n\n## Resources are cheaper than tool calls\n\nRead these directly when you need workspace state (described in the resource listings): `pad://workspaces`, `pad://workspace/{ws}/dashboard`, `.../collections`, `.../items` (use `pad_item` `list` to filter), `.../items/{ref}` (markdown), `.../attachments/{id}` (images only, at most 1 MiB, as base64 `thumb-md`), `.../bootstrap` (the same payload as `pad_meta` `bootstrap`), and `pad://_meta/version`. A host can prefetch them once per session.\n\nLoad the bootstrap resource once per workspace and reuse its collections, conventions, roles, and playbook metadata. Refresh it after switching workspaces, after changing those configuration surfaces, when Pad reports stale schema/context, or when the user asks. For changing work state, read the affected item or use a targeted project tool instead of fetching the whole bootstrap again.\n\n## Workspace context\n\nEvery action that operates within a workspace accepts an optional `workspace` parameter. Resolution order:\n\n1. Explicit `workspace` argument on the call (always wins).\n2. On a single-user local server only: the session default set via `pad_set_workspace`.\n3. On a single-user local server only: the CWD-linked workspace from `.pad.toml`.\n\nA multi-user/remote server does **not** persist a session default — pass `workspace` explicitly on every call. If none resolves, the action returns a structured `no_workspace` error with `available_workspaces`, on both the local and the remote transport.\n\n## Update flow: read first, then patch\n\nFor `pad_item.action: update`, the server merges your patch with the item's current state. Pass only the fields you want to change. When changing `status`, ALWAYS include a `comment` explaining why — it builds the audit trail that helps the team understand history.\n\n## One error code you must not retry\n\nErrors come back as a structured envelope with a `code`. Most failures are worth a retry after you fix something, and a `server_error` may be transient. `stored_state_unreadable` is neither.\n\nIt means the ITEM'S STORED DATA cannot be decoded — your input was fine. Today it fires when `note` / `decide` would append to an `implementation_notes` / `decision_log` value that is not a list of entries. The operation is refused precisely because completing it would overwrite that value. The refusal is fully deterministic, so retrying — immediately or after a backoff — fails identically every time and changes nothing.\n\nWhen you see it: tell the user which item is affected, and stop. Whether you can inspect the bad value depends on which layer is broken — if the item's whole `fields` blob fails to parse, `action: get` hands it back as a raw string; if one structured key is at fault, you won't see it at all, because the blob is normalized on this surface and a value that doesn't decode is dropped from the top-level arrays. A human can always read it with `pad item show \u003cref\u003e --format json`. Do not route around the refusal by writing the field some other way; that is the write that caused it.\n\n## Project conventions\n\nWorkspaces can declare conventions (e.g. \"run `make test` before PR\", \"use conventional commit format\"). The bootstrap blob gives you two views:\n\n- `conventions` — full bodies of the always-on (`trigger=always`) rules. Follow these unconditionally.\n- `convention_index` — METADATA ONLY (`ref`, `title`, `trigger`, `role`; no bodies) for **every** active convention, including the triggered ones whose bodies are NOT in `conventions`. This is your map of what triggered rules exist.\n\nBefore performing meaningful work with a specific trigger (e.g. `on-implement` before writing code), consult `convention_index`: if it lists entries for that trigger, pull their bodies on demand; if it lists none, skip the query.\n\n```\npad_item.action: list, collection: \"conventions\", status: \"active\"\n```\n\nFilter by trigger (`always`, `on-implement`, `on-task-complete`, etc.) when relevant — the `convention_index` triggers tell you which filters are worth running.\n\n`\"conventions\"` above is the DEFAULT collection slug and a workspace may have renamed it, in which case that literal returns nothing while `convention_index` still lists entries — the bootstrap payload resolves by declaration, not by name. When the two disagree, address the items by the `ref`s the index gave you, or find the collection with `pad_collection.action: list`. The same applies to `\"playbooks\"`; `pad_playbook` resolves by declaration and is unaffected.\n\n## Pushes and the session monitor (security note)\n\nPad can push an item into a Claude Code session (`pad push`, or the web item view's push composer). That is terminal instruction injection by design, so receiving is **consent-gated** (PLAN-2613, since v0.15.0): a session receives pushes only after it has connected (`/pad:connect` in the plugin, or a repo-level `push.auto_arm = true` in `.pad.toml` — which a per-user `auto_arm = false` in `~/.pad/config.toml` vetoes), and pushes are self-addressed only — the sender is always the receiving session's own user. This MCP connection is not a session: it cannot arm one, receive a push, or run the monitor, and the `pad_item` / `pad_project` tools expose no push action. If a user asks you to \"push\" something to their terminal, tell them it happens from their own terminal (`pad push \u003cref\u003e -m \"...\"` — the sending session need not be connected, the receiving ones must have consented); do not try to emulate it by writing comments or instructions into items.\n\n## Adding a workspace to this connection\n\nIf the user references a workspace this connection can't see (you'll get a 403 from workspace tools, or the workspace won't appear in `pad_workspace.list`), tell the user you can't see that workspace with your current permissions, then walk them through how to grant access: open Pad in their browser → switch to that workspace → avatar menu → \"Connect project...\" A 6-digit claim code will appear. Have them paste it back in chat, then call `pad_workspace.claim` with `{workspace: \"\u003cslug\u003e\", code: \"\u003c6 digits\u003e\"}`. The workspace joins this connection's allow-list and stays until the user revokes it via `/console/connected-apps`. No re-auth required.\n\nFor brand-new workspaces, `pad_workspace.create` with `{name: \"\u003cname\u003e\"}` (and optional `template`) creates the workspace AND auto-adds it to this connection's allow-list in one call — no claim code needed. Only works when the connection currently carries the \"may create workspaces\" grant — granted at consent time, or enabled later on the connections page. If the grant is present and set to false, the create is **refused with a 403 and no workspace is made** — retrying won't help and neither will the claim flow, since there is nothing to claim. Tell the user this connection isn't permitted to create workspaces, and offer them the two ways forward: create the workspace themselves in the browser and grant access with a claim code, or re-authorize this connection with \"Let this app create new workspaces\" enabled (`/console/connected-apps` can also flip it on an existing connection).\n\n## New workspace: offer to set it up\n\nThe bootstrap blob carries `needs_onboarding: bool` — true when the workspace has zero user-created items (template seeds don't count). When it's true, **lead with an active offer before anything else**: *\"This workspace is brand new and isn't set up yet. Want me to set it up? I'll ask a few quick questions and adapt it to your project.\"*\n\nThis is an **offer, not an auto-run** — wait for the user to say yes before running onboarding. If they accept, run the `onboard` playbook (use the `pad_onboard` prompt, or load the body via `pad_playbook` `action: get`, `ref: onboard`). If they decline, or already declined earlier in the session, respect that and skip the offer. The flag flips to false the moment any item exists, so it won't nag past first setup.\n\n## Built-in updates: mention once\n\nThe bootstrap blob may carry `builtin_updates: int` (absent when there are none): how many of the conventions and playbooks Pad ships have newer text in Pad's library than this workspace's copy. When it is present, mention it **once per session**, in one line, then carry on. **Never apply an update yourself**: a person reviews each one and accepts it or not.\n\n## Multi-step workflows\n\nFour prompts ship with the server: `pad_plan`, `pad_ideate`, `pad_retro`, `pad_onboard`. Use them when the user wants help planning, brainstorming, retrospecting, or onboarding into a workspace — they encode the multi-step Pad-aware playbook for each.\n" } diff --git a/cmd/pad/testdata/mcp_wire/stdio_tools_list.json b/cmd/pad/testdata/mcp_wire/stdio_tools_list.json index 40fb5bb61..312a6e36f 100644 --- a/cmd/pad/testdata/mcp_wire/stdio_tools_list.json +++ b/cmd/pad/testdata/mcp_wire/stdio_tools_list.json @@ -339,7 +339,7 @@ "type": "string" }, "limit": { - "description": "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions.", + "description": "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions. starred takes no limit: it returns at most 300, most recently starred first, with has_more when more exist.", "type": "number" }, "lines": { diff --git a/docs/api.md b/docs/api.md index 053d5a9b7..b59c34a3f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -73,7 +73,9 @@ REST API at `/api/v1/`. Key endpoints: - `GET/POST/DELETE /workspaces/{ws}/webhooks` — webhook management - `PATCH/DELETE /workspaces/{ws}/items/{slug}/comments/{id}` — comment edit/delete addressed through its item (TASK-2695): 404 unless the comment is on that item, then the same handler, ACL and events as `/workspaces/{ws}/comments/{id}` (edit author-only, delete item-edit). A delete of a comment that still has replies leaves a TOMBSTONE on either route (BUG-3252, 204 like any delete): the body is emptied and the reactions removed, author and timestamps are kept, the comment serialises with `deleted: true`, and its replies keep their parent. An edit, reply or reaction addressed to a tombstone answers 409 `comment_deleted`, deleting it again answers 404, and deleting its last reply removes it in the same transaction. Tombstones are left out of the decision trail and the workspace export. A server before the tombstone answered 409 `comment_has_replies` instead, and the CLI and MCP still classify that code. The CLI and every MCP transport use this form; `GET /server/capabilities` advertises it as `item_scoped_comment_writes`. Every serialised comment carries a derived `edited` bool - `GET /workspaces/{ws}/changes?since=` — the web sync delta: items updated at or after `since` (archived ones included; their ids are also in `deleted`), with full bodies, and `server_time`, the next `since`. **Bounded and paged by a cursor** (BUG-3791). `limit` defaults to, and is capped at, 1000, as on the item lists. When more remain the body says `has_more: true` with `next_cursor`; ask again with `?cursor=` alone (a `since` beside it must equal the walk's). The cursor is a position in the workspace's write order (`seq`, then id), so a change committed during the walk comes back in a later page, and a row can appear twice. Every page repeats the FIRST page's `server_time`, which is a safe next `since` only once a page says `has_more: false`. Visibility is applied before the window, so a page's count and `has_more` never reflect rows the caller cannot see. **Contract change:** a client that ignores `has_more` gets the first 1000 changes of a longer delta and loses the rest when it advances to `server_time`; the web client (`walkChanges`) walks every page, and fails to a full refresh past 50 -- `GET /workspaces/{ws}/items/{slug}/children` — child items linked to a parent +- `GET /workspaces/{ws}/items/{slug}/children` — child items linked to a parent, in the manual order (sort_order, created_at, id). **Bounded and paged like the item lists** (BUG-3789): `limit` defaults to and is capped at 1000, `offset` skips rows, and `X-Pad-Has-More` / `X-Pad-Next-Offset` carry the paging state; the body stays a bare array. Visibility is applied before the window, so the page and has-more count only children the caller may see. The web client walks every page +- `GET /workspaces/{ws}/starred` — the caller's starred items, most recently starred first (ties by id); `include_terminal=true` keeps closed ones, `summary=true` leaves out bodies. **Bounded and paged** the same way (BUG-3790), after the visibility and terminal filters; bodies are loaded only for the page returned. `pad item starred` and the web client walk every page +- `GET /api/v1/s/{token}` — public share link resolution. For a COLLECTION share the items are **bounded and paged** (BUG-3792): `limit` (default and cap 1000) and `offset` query parameters, and the body carries `has_more` and `next_offset` (the headers are set too). The web share page follows `next_offset` until `has_more` is false and merges the pages' items and `attachment_refs` - `GET /workspaces/{ws}/items/{slug}/progress` — child item completion progress - `GET/POST /workspaces/{ws}/items/{slug}/links` — item relationships (blocks/blocked-by, parent/child) - `GET /workspaces/{ws}/items/{slug}/context?intent=&role=&budget=` (PLAN-3598) — one deterministic brief for working an item: `item` (fields, body, seq), `parents` (the visible ancestor chain, nearest first, each with `acceptance_criteria` parsed by `internal/acceptance` and the nearest one's body), `conventions` (active ones whose trigger is `always` or the intent's, with bodies, sorted must → should → nice-to-have then ref), `playbooks` (metadata only), `deps` (`blocks` / `blocked_by` with statuses), `decisions` (TASK-3618: only the answers their set would surface, i.e. the question is current and the Noul reaches the set's threshold, `decision.AttentionThreshold` or `decision.ConventionThreshold`; each carries `current`, and a surfaced answer whose item has moved on stays, with `current: false` and a `stale_decision` conflict. The rest are only counted: `decisions_below_threshold`, and `decisions_stale_question` for answers to a question no longer asked as it was), `links` (other link types, ref/title/status, no bodies), `omitted`, and `conflicts`. Every part carries its ref and seq. **Intent** resolves against the conventions collection's declared trigger options: `on-` if declared, else ``; neither is 400 `unknown_intent` with `details.valid_intents`. No intent means `always` only. A caller who cannot see the conventions collection gets no validation and no list (the intent is taken as `on-`), so the 400 cannot reveal its declared triggers. **Role** must be a role slug in the workspace (400 `unknown_role`); with one, a convention scoped to another role (by its agent-role column, the one bootstrap labels with) is left out, and without one every role's are included, as bootstrap does. **Budget** (characters of serialized parts, default 40000, capped at 400000) admits whole parts in a fixed order: parents, conventions, playbooks, deps, decisions, links. The first part that does not fit and every part after it are listed in `omitted` (`part`, `ref`, `seq`, `size`, `reason: "budget"`), so a later small part never slips in after a refused one. The item always ships, even past the budget. **Visibility:** the item uses the single-item read check, so an archived item is served read-only to a caller who can read it, exactly as the single-item GET serves it, and an unreadable item is the same 404 as a missing one; every ancestor, dependency and linked item uses `itemVisibleFor` plus the app token's collection ceiling and live rows only; conventions and playbooks use bootstrap's visibility sets. A part the caller cannot see is absent and NOT counted in `omitted`. **`conflicts`** is structural only (no semantic comparison of rules): `open_blocker`, `open_under_closed_parent`, `stale_decision`, and `role_and_global_convention` (a role-scoped and a global convention matching the same trigger under the same title) diff --git a/docs/mcp.md b/docs/mcp.md index 8f0fa8ed5..5b9799330 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -26,7 +26,7 @@ Surface: **Stability contract.** Two version constants live in `internal/mcp/version.go`, advertised in the handshake under `capabilities.experimental.padCmdhelp` and `capabilities.experimental.padToolSurface`: - `CmdhelpVersion` (the constant in `internal/mcp/version.go` is the current value) — the cmdhelp CLI help-tree contract. Bump when CLI flag/arg schemas change incompatibly. -- `ToolSurfaceVersion` (the constant in `internal/mcp/version.go` is the current value; this list is its changelog, newest first) — the MCP tool catalog contract. Bump when tool names, action enums, or parameter shapes change incompatibly. **v0.98** (BUG-3704) makes `pad_item` `list` say when it is truncated: it asks for one row past its limit and, when that row comes back, returns `limit` rows with `has_more: true` on the structured result and a second text block telling the agent to narrow the filters or raise `limit` (max 300). It never pages for the agent. A list that fits is unchanged. Additive, on the v0.53 grounds. **v0.97** (TASK-3613) adds an optional `worker_id` to `pad_item` (`claim`, `release`) and `pad_project` (`next`, `ready`): a lease is now held under a worker id plus the account, the holder label is display only, a claim answers with the caller's `worker_id`, and passing it back resumes the lease from another connection (see **Leases** above). `lease_held` details gain `worker` (the short id). The remote default holder label is the bare client name. ADDITIVE bump on the v0.53 grounds. **v0.96** (PLAN-3598 slice (c)) adds `pad_item.action=context` (`ref`; optional `intent`, `role`, `budget`), read-only, which returns one brief for working an item: the body of `GET /items/{ref}/context`, with the item and its seq, its parent chain with parsed acceptance criteria, the conventions whose trigger matches the intent (plus the always-on ones), matching playbooks, deps, decisions, links, conflicts, and what was omitted for size. New codes are `unknown_intent` (400, with `details.valid_intents`) and `unknown_role` (400). Both transports (`pad item context [--intent] [--role] [--budget]`). ADDITIVE bump on the v0.53 grounds. **v0.95** (TASK-3611) adds `pad_item.action=link-pr` (`ref`, `pr_number`, `pr_url`; optional `pr_title`, `pr_state`, `pr_branch`, `pr_repo`), which links a pull request from metadata the agent supplies, fetching nothing from GitHub, through the typed `github_pr` member; and `action=unlink-pr` (`ref`), which removes the link and refuses an item with none, as `pad github unlink` does. Both transports (`pad github link --pr-number N --pr-url U ...`, new flags). ADDITIVE bump on the v0.53 grounds. **v0.94** (TASK-3611) adds `pad_item.action=reminders` (`ref`), which lists an item's reminders with their ids (armed, fired, acknowledged), and `action=unremind` (`reminder_id`), which disarms one, on both transports. Listing is read-only; disarming needs edit permission on the item, as on the CLI. Re-arm stays CLI-only (`pad item remind --rearm`). ADDITIVE bump on the v0.53 grounds. **v0.93** (TASK-3611) makes `pad_item.action=create` and `update` over the local stdio transport WRITE a `fields` value that is an object or array, which they used to refuse (BUG-2850): the stdio door passes those keys, and every other non-string value (numbers and booleans, which `--field key=value` delivered as text unless the schema typed them), to the CLI as one `--fields-json` object (a new additive flag on `pad item create` / `update`), keeping their JSON types, as the remote door sends them. Any other action still refuses one. ADDITIVE bump on the v0.53 grounds. **v0.92** (TASK-3585) adds `op_key` to `pad_item.action=comment`, `note` and `decide`: retrying the same request with the same key answers the comment or entry the first attempt made instead of appending again, recorded in the write's own transaction. On the item-update route a key is accepted only with an append (and `source`); any other member alongside it is refused 400. `idempotency_target_gone` (410: the item or comment the key wrote has since been deleted) is now a structured code on both transports, with its own hint; at 0.91 it reached MCP as a generic error. No name, enum or param moved. ADDITIVE bump on the v0.53 grounds. **v0.91** (TASK-3585) adds `op_key` to `pad_item.action=create`: retrying the same create with the same key answers the item the first attempt created (as it stands now) instead of creating a second one; the answer is recorded in the create's own transaction. A key reused for a different create is refused `idempotency_key_reused`; one still in flight answers `idempotency_in_flight` (both codes already existed, and are structured on both transports for any route). A replay whose item has since been deleted answers HTTP 410 `idempotency_target_gone`, which at 0.91 reached MCP as a generic error. No name, enum or param moved. ADDITIVE bump on the v0.53 grounds. **v0.90** (TASK-3585) adds `pad_item.action=patch` `op_key`, an idempotency key: the same request retried with the same key returns its first answer instead of applying again; new codes `idempotency_key_reused` (422), `idempotency_in_flight` (409) and `patch_outcome_unknown` (409, with `seq` and the diff since). ADDITIVE bump on the v0.53 grounds. **v0.89** (PLAN-3578 step 3) adds `pad_item.action=patch` `undo` (a `patch_id`), which inverts that patch, anchored on the text around each edit as it landed, refusing when that text has changed since, and the code `patch_not_found` (404). ADDITIVE bump on the v0.53 grounds. **v0.88** (PLAN-3578 step 2) makes `pad_item.action=patch` on an item open in a browser editor APPLY (the editor applies it as a narrowed replace of its live document; the answer adds `content_state: "applied_pending_flush"`) where it was refused `patch_room_open`, and adds the code `patch_unstable_roundtrip`. `patch_room_open` now means only an older editor holds the item. BEHAVIOR bump on the v0.84 grounds. **v0.87** (PLAN-3578 step 1) adds `pad_item.action=patch {ref, edits:[{old, new, line_hint?}], expected_seq?}`: exact-text edits to the body (each `old` occurs exactly once, applied in order, all or nothing) answered with `{seq, patch_id, version_id, rebased, intervening?, diff}`. A moved `expected_seq` is applied over and reported, never refused. Refusals write nothing: `patch_anchor_missing`, `patch_anchor_ambiguous` (`details.lines`), `patch_room_open`. `get` gains `lines` for numbered body lines with `seq`. ADDITIVE bump on the v0.38 grounds. **v0.86** (PLAN-3555 phase 1) adds `pad_item.action=update` `replace` (bool): the deliberate overwrite of content with no version token, refused with `expected_seq` / `expected_updated_at` or without `content`. A content write with neither carries `warnings.unguarded_content_write: true`, and a later release refuses it. A seq `update_conflict` on a content write gains `details.content_write`, `changed_at` and `changed_by_kind`, a message naming both seqs that says not to resend the body, and the same "re-read and merge, do not resend" hint on both transports. ADDITIVE bump on the v0.53 grounds. **v0.85** (BUG-3544) makes `pad_workspace.action=invite` on an instance with no account yet (the setup window, reachable over local stdio) answer 409 `setup_required` ("This Pad instance must be initialized with pad auth setup") and write nothing, where it answered 500 (`server_error`) from the invitation's inviter foreign key. BEHAVIOR bump on the v0.58 / v0.45 grounds. **v0.84** (BUG-3542) makes a `pad_item` content update answer 409 `content_not_applied` with `details.apply_reason: "unconfirmed_edits"` when a browser tab holding the item open still has typing the server has not stored; token or not, other fields land and the content does not. Wait, re-read and resend; `overwrite_pending_edits: true` is the only override. BEHAVIOR bump on the v0.39 / v0.43 grounds. **v0.83** (TASK-3539) makes `pad_collection` create and update REFUSE a `schema` in which a field has no key, two fields share a key, or a select field lists an empty option or the same option twice, with 400 `validation_error` naming it (`field key "status" is defined more than once`). BEHAVIOR bump on the v0.43 / v0.48 grounds: a write door refuses a call it used to accept. Write-only: a schema already stored with a repeat still reads, and an update that sends no schema still applies. **v0.82** (PLAN-3535 PR 2) makes the items of a REFERENCE collection (`tracks_work: false`) stop counting as open work on every agent surface: `pad_project` next / ready / stale / standup / changelog, the dashboard and bootstrap dashboard, item progress, the `open_children` close guard and the attention decision set leave them out, and a report with no `collections` leaves the collection out as it already did a system one. Sidebar counts, item lists, search and links are unchanged; a collection without the key counts as work. BEHAVIOR bump on the v0.49 grounds. **v0.81** (PLAN-3535 PR 1) adds a `tracks_work` boolean to `pad_collection` create and update: false makes the collection REFERENCE material whose items stop counting toward parent progress, close blocking, Insights and open-work counts (applied by the follow-up PRs). On update it sets that one settings key server-side and leaves the rest alone; omitted, create picks work iff the done field can finish and update leaves it unchanged. ADDITIVE. **v0.80** (BUG-3533) makes `pad_item.action=import` work over remote `/mcp`: it answered `validation_failed` "artifact is required" on every call, because the catalog action dropped `artifact` from the input the HTTP dispatcher reads. Stdio is unchanged. ADDITIVE bump. **v0.79** (TASK-2863) lets a read-only grant (`read` / `pad:read`) run a playbook: `pad_playbook.action=run` stores nothing, and was refused only because it is a POST. It is the one POST a read grant may make (an exact-path allowlist); `match` and every write stay refused. BEHAVIOR bump, additive in effect. **v0.78** (TASK-2308) answers a remote `/mcp` WRITE action from an OAuth connection that can only read (`pad:read`), in a `tools/call` request of up to 1 MiB, with HTTP 403 and a `WWW-Authenticate` `error="insufficient_scope"` challenge naming `scope="pad:read pad:write"` and the metadata document, before dispatch, where it got a `permission_denied` tool result; that challenge is what lets a client re-authorize with the wider grant. Every such call was already refused, so nothing that worked is refused now. A read-scoped PAT keeps the tool error (it cannot re-authorize), as does a larger request, and the ChatGPT mount keeps its own challenge. The 401 challenge also names `scope`. BEHAVIOR bump. **v0.77** (BUG-2772) records a remote `/mcp` write as an AGENT write named by the client's declared MCP `clientInfo.name`, where it was recorded as the human, and gives a remote call a per-connection default lease holder (`claude-code#3f9a12c4`); see "Remote caller identity" below. A claim on an item another holder leases now answers `lease_held` with `details.holder` and `details.expires_at` on both transports, where remote said `conflict` and stdio `server_error` (BUG-3496). BEHAVIOR bump. **v0.76** (TASK-1809) makes a `pad_item` `claim` / `release` with no `holder` hold the lease under the caller's agent name (the `X-Pad-Agent` the CLI sends), else the account's email, where it was the email alone: several agents on one account silently shared one lease, a second claim answering 200 by refreshing the first. It now answers 409 `lease_held` naming the first agent. `pad_project.action=next` / `ready` leave out items whose live lease a claim by the caller would lose (same identity, the claim's own predicate, filtered before the cap of three; reminders are not filtered). Remote /mcp sends no agent name, so its default is still the email (TASK-3495). A lease taken before the upgrade is another holder's to the same agent for up to its TTL. BEHAVIOR bump on the v0.70 grounds. **v0.75** (BUG-3480) makes `pad_item.action=list` on both transports refuse a filter key no schema in scope declares and no item in scope stores (400 `validation_failed`, "invalid list filter ..."), where it answered an empty list, and refuse a key that is not a field key, which the store used to drop (answering the unfiltered list). BEHAVIOR bump on the v0.43 / v0.29 grounds; see the item list endpoint bullet under API. **v0.74** (TASK-2188) makes `pad_collection.action=update` answer, on both transports, with an `omitempty` `warnings.orphaned` [{field, option?, items}] naming each field, or select option, its schema removed that live items still hold. Nothing is refused. ADDITIVE, the v0.67 grounds; 0.73 is BUG-3480's. **v0.72** (TASK-2189) adds `pad_collection` `list-archived` (read-only) and `restore` (owner-only, by slug or id), backed by the new `GET /workspaces/{ws}/archived-collections` and `POST /workspaces/{ws}/archived-collections/{ref}/restore`: an agent's archive is recoverable by an agent. ADDITIVE. **v0.71** (TASK-3462 U3a) adds an `omitempty` `builtin_updates` count to the bootstrap on every door that returns it (the conventions and playbooks Pad ships whose library text changed since the workspace's copy, among the items the caller sees in full), and a server-instructions section telling the agent to mention it once and never apply an update itself. ADDITIVE. **v0.70** (BUG-3453) makes `pad_project.action=next` / `ready` fill any slot the existing tiers leave empty with ordinary open items from non-system collections that declare `priority` or `severity` (an initial status like `new` counts), ranked below every item admitted before, so a full list is unchanged and a moved-in backlog with no priorities is no longer "nothing ready". BEHAVIOR bump on the v0.49 grounds. **v0.69** (TASK-2314) makes every REMOTE route that needs a workspace and lacks one answer `no_workspace` with `available_workspaces` and a hint, as stdio always did, where it answered `validation_failed` "workspace is required"; the single-workspace default now runs before the `assign` / `role` resolvers. BEHAVIOR bump on the v0.42 / v0.45 grounds. **v0.68** (BUG-3448) makes the item resource render a structured field as compact JSON instead of Go's map syntax, keep a number above 2^53 to its digits and render a JSON null as `null`; the agent projection stops rounding large numbers. BEHAVIOR bump on the v0.62 / v0.64 grounds: an output shape changed, no name, enum or param moved; scalar fields render as before. **v0.67** (BUG-3446) lets a create in a system conventions or playbooks collection ADD a trigger/scope word the library itself uses to the select options instead of refusing it, so `pad_library.activate` and B3's literal create succeed in a `blank` workspace, and adds an `omitempty` `warnings.options_added` to the create result on both transports. A word the library does not use is refused as before. ADDITIVE. **v0.66** (BUG-2136) makes `pad_workspace.action=invite` always create a pending invitation, never add an existing account directly; see `internal/mcp/version.go`. **v0.65** (TASK-3413, SPEC-6 U9c) adds `omitempty` `via_app` and `via_app_name` to items an installed app CREATED (items.created_via_app, never the last app writer), comments an app wrote and version rows an app's write made, on both transports (`pad_item` get, list summary and full, comments, history summary and full). The name is the app's bot display name, else its origin, and survives uninstall. ADDITIVE. **v0.64** (BUG-3379) adds an `omitempty` `imported: true` to comments, attachment rows and version rows a workspace import wrote, on both transports (`pad_item` comments, `pad_attachment.list`, and `pad_item.history` with `full: true`; history summary rows and attachment `show` do not carry it): import keeps the export's author strings and uploader ids verbatim, and the flag says they were not verified here. ADDITIVE. **v0.63** (TASK-3321) adds an `omitempty` `actor_name` to every `pad_item.action=history` summary row on both transports, the display name of who made the change, where rows said only `user` or `agent`. ADDITIVE. **v0.62** (BUG-3326) makes remote /mcp `pad_set_workspace` embed the workspace bootstrap, as stdio always did: the in-process bootstrap resource read, run as the token's user under the same scope/consent perimeter, so a workspace the caller cannot read embeds nothing. ADDITIVE; no name, enum or param changed, and stdio is unchanged. **v0.61** (TASK-3321 U0b) marks `pad_workspace` destructiveHint:true and openWorldHint:true, because `invite` sends an email to an arbitrary address, and `pad_playbook` openWorldHint:true, because `match` sends text to the decision provider. Annotation-only BEHAVIOR bump on the v0.20 grounds; every other tool's block is unchanged. **v0.60** (TASK-2198 U4) makes `content_state: "applied_pending_flush"` clear ON ITS OWN on every door that carries it: after the item's collab room closes (or a one-minute sweep finds it dormant) the server rebuilds the body from the op-log and stores it, moving `seq` (a held `expected_seq` then answers `update_conflict` instead of `content_pending_flush`) and adding a `system` / `recovery` version. BEHAVIOR bump on the v0.59 / v0.39 grounds; no name, enum or param changed. Not a guarantee (failures, set-aside rows, `PAD_MATERIALIZE=off`), so re-read later, never re-send, still stands. **v0.59** (BUG-3252, tombstone ruled over cascade) makes `pad_item.action=delete-comment` on a comment with replies SUCCEED, leaving a tombstone (body emptied, author and timestamps kept, additive `deleted: true`) its replies stay under; it is removed when its last reply is deleted. `edit-comment` on a tombstone answers 409 `comment_deleted` on every transport. BEHAVIOR bump on the v0.58 grounds; `comment_has_replies` stays classified for older servers. **v0.58** (BUG-3252) makes `pad_item.action=delete-comment` on a comment that still has replies answer 409 `comment_has_replies` (details `comment_id`, `reply_count`) on every transport instead of `server_error`: `comments.parent_id` has no ON DELETE, so the delete failed the FK inside the store. Nothing is deleted either way. Tombstone was then ruled over cascade; v0.59 replaced this refusal with it. BEHAVIOR bump on the v0.45 grounds. **v0.57** (TASK-2695) adds `pad_item` `edit-comment` (ref, comment_id, message) and `delete-comment` (ref, comment_id) on all three transports, backed by the item-scoped routes `PATCH/DELETE /workspaces/{ws}/items/{ref}/comments/{id}`, which answer 404 unless the comment is on `ref` and otherwise run the workspace routes' handlers (edit author-only, delete item-edit). CLI: `pad item comment-edit` / `comment-delete`, refused against a server without the `item_scoped_comment_writes` capability. Every serialised comment gains a derived `edited` bool (updated_at > created_at), and `pad item comments` prints each comment's id. ADDITIVE. **v0.56** (BUG-3244) gives `content_state` a second value, `superseded_set_aside`, on every MCP door that carries it (`pad_item` get / full list, `pad_playbook` run, the item resource's line above the body): edits an editor schema-version rebuild set aside, which opening the item will NOT restore, so the resource line and the `content_pending_flush` hint (chosen by `details.set_aside_rows`) name `pad item set-aside` and `overwrite_pending_edits` instead. ADDITIVE bump: no name, enum or param changed, but an agent branching on the one-word vocabulary meets a word whose remedy differs. Reading or discarding the rows alone is not on the catalog. **v0.55** (BUG-2659) sends `pad_item.action=search`'s `collection` to /search as typed, and /search resolves it exact-first per workspace in scope (the item routes' resolver). In a workspace holding both `task` and `tasks`, `collection: "task"` now answers from `task` instead of `tasks`; every other workspace is unchanged, because the shorthand still resolves server-side. Stdio reaches it through the CLI, which sends the name as typed only to a server advertising `search_collection_resolution`. BEHAVIOR bump on the v0.36 / v0.40 grounds. **v0.54** (BUG-3217) keeps a `fields` number's literal through MCP on both transports (mcp-go's argument decode rounded anything above 2^53, and stdio's `--field` stringify carried the rounded value), and REFUSES a `fields` number beside a `field` entry for the same key when they differ as exact numbers — two values that differ only above 2^53 used to collapse into one rounded write; a matching pair (3.0 beside n=3) still collapses. BEHAVIOR bump on the v0.48 grounds. **v0.53** (BUG-2819) adds `filename_source` (caller / normalised / substituted / derived / unknown) to every `pad_attachment.action=list` row on both transports, because a stored filename cannot say whether the caller sent it or the server substituted it. ADDITIVE, the v0.28 / v0.13 disposition; `show` does not carry it, and `mcp_audit_log.tool_name_source` reaches no catalog action. Rows written before it read `unknown`, never `caller`. **v0.52** (BUG-2367 item 4) refuses a move or copy (every migrate door) that would change an item between open, done and abandoned unless the caller names the destination done field. Only the STATE is compared, so two values that both mean done carry. Move answers 400 `state_change_requires_value` with details `{field, options, from, to}`; bulk move puts it in a `failed[]` row; the copy answers 400 `validation_error` with the same sentence; the preflight emits a needs_value row with reason `state_change`, which the web dialog picker renders. A destination with no done select field is exempt. BEHAVIOR bump. **v0.51** (BUG-2367) stops every migrate door (single move, bulk move, cross-workspace copy and its preflight) carrying a value into a field the destination marks `computed` (preflight drop reason `target_computed`) or a value that collides on a destination `unique_scope` field. Provenance decides, the TASK-2878 rule: a CARRIED collision is dropped and reported (`not_unique`), a supplied override or injected default that collides is refused 409 `conflict`, and a required field emptied by the drop is refused as required, which is the existing needs_value route. Before it, single move answered 500 on the indexed `invocation_slug`, bulk move leaked the SQL error, and an unindexed unique field stored a duplicate. Reporting is additive and omitempty: `warnings.not_unique` [{key, value, holder?, message}] on the move response, bulk `updated[]` rows and the copy response, and a `detail` sentence on the preflight's dropped row. `holder` is present only when the caller may see that item, so the drop is not an existence oracle. BEHAVIOR bump on the v0.43 / v0.29 grounds. **v0.50** (BUG-3014) adds an ADDITIVE `omitempty` `stored_as_text: true` to a `relation_targets` entry whose stored value is not UUID-shaped (a title a bundle import carried verbatim, or legacy free text). Such a value was never an id and used to hydrate as a plain id-only entry, which reads as "gone or hidden"; an id-only entry without the flag keeps that meaning, and a UUID-shaped value, resolved or not, is byte-identical to v0.49. The predicate is syntactic, decided from the stored bytes and never from a lookup, so it discloses nothing, and deliberately not coupled to the resolver ladder. The CLI prints `"" (text, not a reference)` and the web chip says the same. **v0.49** (BUG-2410) makes `pad_project.action=report` with no `collections` param leave out SYSTEM collections (`Collection.IsSystem`: Conventions and Playbooks), which were counted in Insights' created, WIP and status totals; naming one explicitly still includes it. BEHAVIOR bump on the v0.40 / v0.42 grounds: a default call's content changed for every caller (web Insights, print, `pad project report`, both MCP transports, all through the one store rule). **v0.48** (BUG-3163) makes `pad_item.action=create` REFUSE a `field` / `fields` entry naming any reserved metadata key (`implementation_notes`, `decision_log`, `github_pr`, `convention`) on every transport, with 400 `validation_error`, creating nothing: create was the last door that stored one, as a string no extractor reads. Library activation, its one system writer, moves to an additive typed `convention` create member (not on the catalog; `pad_library.activate` is unchanged), and the CLI verifies from the stored fields that it landed, because an older server ignores the member and answers 201. BEHAVIOR bump on the v0.47 grounds. **v0.47** (BUG-2696) makes `pad_item.action=update` REFUSE a field setter naming `github_pr` on every transport (400 `validation_error` naming `pad github link` / `unlink`), closing the exemption v0.23 left: that door stored the PR as an unreadable string, so no link ever rendered. The writer is a new additive, typed update member (`github_pr` object + `clear_github_pr`) used by `pad github link` / `unlink` / `project reconcile`, deliberately NOT on the catalog (a remote PR-link action waits on the catalog-trim decision). BEHAVIOR bump; item create is BUG-3163. **v0.46** (BUG-3156) makes `pad_item.action=bulk-update` over stdio and remote REFUSE, per item, a status or priority change on an item whose collection does not declare that field, writing nothing for that item: the answer WebMCP has given since v0.44, so the three transports agree. Rows keep each transport's shape (stdio `failed[]` with `validation_error`, remote `results[]` with `validation_failed` and the server message in `hint`). The mechanism is the update door's new `refuse_undeclared_fields` member, which both bulk-update transports set; `pad_item.update` does not, and still accepts-and-warns. A server that predates the member ignores it, which is the old accept-and-warn. BEHAVIOR bump on the v0.44 / v0.43 grounds. **v0.45** (BUG-2829) reports an HTTP 413 as `too_large` on BOTH transports, with the server's own code in `details.reason`, where it used to be `server_error`: three deliberate caps are reachable from the catalog (a title rename's link cascade, an oversized outbox event, an oversized artifact import), and the old code read as transient and invited a retry that fails identically. Remote maps 413 in `classifyHTTPStatusKind`; stdio gets it from a structured marker the CLI root writes for any 413, and `too_large` joins `allowedStructuredErrorCodes`, which a test now proves contains every code any CLI marker writer emits. BEHAVIOR bump on the v0.42 grounds; no name, enum or param shape changed. **v0.44** (BUG-3154) makes `pad_item.action=bulk-update` over the WebMCP browser transport REFUSE, per item, a status or priority change on an item whose collection does not declare that field: the item lands in the bulk response's `failed` array with `validation_error` naming the collection and field, nothing is written, and the rest of the call applies. The door is `POST /items/bulk` (`set-priority`, and `move` with a `status`, with or without a `collection`, where the target's schema decides), where the request carries an operation and a value and the SERVER chooses the key; it used to store an orphan field and report the item updated. BEHAVIOR bump on the v0.43 / v0.40 grounds. The transports disagreed after it, stated rather than implied: stdio and remote issued a per-item PATCH, the single-item update door, which ACCEPTED the key with `warnings.undeclared_fields` (v0.27), until v0.46 converged them. **v0.43** (BUG-2379) makes `pad_item.action=move` REFUSE a field override naming a field the destination schema does not declare, with 400 `malformed_override` — the same check, code and message the cross-workspace copy already used. BEHAVIOR bump on the v0.40 / v0.29 grounds: a write door refuses a call it used to accept, where it used to store the key as an orphan field no schema renders. Create and update still ACCEPT undeclared keys with `warnings.undeclared_fields` (v0.27), because callers round-trip the whole fields blob; an override is a fresh assertion about the destination schema, not round-tripped state. **v0.42** (BUG-3142 + BUG-3147) changes the error CODE a LOCAL STDIO caller receives for two failure families that used to arrive as retryable `server_error`: an argv refusal (cobra/pflag: unknown flag, arg count, …) is now `validation_failed` with its message kept, and a 429 on any command is now `rate_limited` with `details.retry_after_seconds`, via the structured marker line the CLI writes at its root. It also stops the refusal that caused most of the first family: `BuildCLIArgs` now emits flags first and the positionals behind `--`, so free text starting with `-` (`item search "-ship it"`) is no longer parsed as a flag. BEHAVIOR bump; no name, enum or param shape changed, and the remote transport is untouched. **v0.41** (PLAN-3114 U5 / TASK-3120) adds a `match` action to `pad_playbook`: given free `text`, a Choice question over the workspace's ACTIVE playbooks plus a reserved `"none"` option returns the best match's ref (or `"none"`), confidence, per-option probabilities and the model. No provider configured → 404 `decision_provider_unavailable`; a provider error or an out-of-set answer → 502 `decision_provider_error`. Pure ADDITIVE bump (new action + param, nothing existing moved), read-only and side-effect-free. **v0.40** (BUG-3028) gives a scalar `relation` ONE stored form for "no target", the key ABSENT, converging on multi_relation's rule. A blank (`""` or whitespace) a write SETS — create, `fields_patch`, a changed value in full `fields`, a move/copy override — is normalised to absent before validation, so a `required` relation is refused as required (a patch blanking it now gets the answer deleting it always got). A legacy blank a write only CARRIES — an untouched key under `fields_patch` (normalised by the store under its write lock, via `ItemUpdate.BlankRelationKeys`), an unchanged value in full `fields`, move, copy, artifact import — is normalised after validation and never refused. An empty list filter on a scalar relation key of a collection-scoped list (`owner=`) matches all three spellings. BEHAVIOR bump; no shape change. Workspace import (`store.ImportWorkspace`) still stores blobs verbatim; its legacy blanks normalise on the next write. **v0.39** (BUG-3133) refuses `pad_item.update` that sets content WITH a version token (`expected_seq` / `expected_updated_at`) while the item's op-log holds content-bearing rows above its flush watermark, with 409 `content_pending_flush` (details `ref`, `pending_rows`). BEHAVIOR bump on the v0.35 / v0.36 grounds, carrying one additive param: `overwrite_pending_edits` lifts it, on the API, the CLI (`--overwrite-pending-edits`; `pad item edit --force` sets it on the save) and MCP alike, because an agent must be able to clear the refusal without a browser. The token guards the ROW and a tab's unflushed typing is not in it, so the write used to replace those edits — through the applier's setContent with a tab open, and by the direct path's op-log prune, which DELETES them, with none. Its own code rather than `update_conflict` because re-reading returns the same row and seq. A write without a token, without content, or to an item with nothing pending is unchanged, except that a direct write now reports `warnings.pruned_pending_edits` (additive, omitempty) when its prune deleted such rows. The check runs in the write's own tx; on the direct path it is under the item lock and appendMu and exact, on the applier path a tab can still type in the one server hop between the check and setContent. (v0.37 and v0.38 — the `agent` projection on `pad_item.get` and `claim` / `release` — are in `internal/mcp/version.go`; this paragraph had stopped at v0.36.) **v0.36** (BUG-3082) stops a REF-SHAPED `relation` value falling back to matching by item NUMBER when its prefix names a collection that is LIVE in the workspace; such a value is now `not_found`. BEHAVIOR bump on the v0.35 / v0.30 / v0.29 / v0.16 grounds — no tool name, action enum or param shape changed, but a write door refuses a value it used to accept. It finishes v0.29: that entry closed free-text corruption ("red" resolving to whatever is slugged `red` today) and left the same corruption open for anything shaped like a REF, which is the spelling the docs tell callers to prefer. Item numbers are workspace-unique and sequential ACROSS collections, so `CONVE-1` and `SECRE-1` are never both real — the fallback dropped the prefix, matched on the number alone, and landed on an item that was usually inside the field's declared collection, so the wrong-collection check above it passed and NOTHING was raised: a caller wrote `CONVE-1`, the item stored a different item's UUID, and the write answered 201 with the substitution visible only in `relation_targets`. The predicate is about the PREFIX rather than the item because a collection RENAME changes its prefix and a relation already written as the old ref must keep resolving (BUG-2873) — that ref's prefix names nothing afterwards, so the fallback still fires for it, while a prefix that IS live and simply holds no item at that number is the caller naming a real collection that does not contain what they said. A SOFT-DELETED collection counts as absent IN THAT PREDICATE, for the same reason a renamed one does — a claim about the fallback only: the exact-prefix lookup ahead of it never filtered on the collection’s own `deleted_at`, so an item whose collection was soft-deleted still matches THERE and never reaches the predicate. That is left alone rather than made consistent, because it cannot retarget — the downstream collection check refuses it. RESIDUAL, stated rather than implied and pinned by a test: a ref pasted from ANOTHER workspace whose prefix also names no collection here still resolves by number, because nothing in the value distinguishes it from a rename's leftover. No escape hatch, for v0.29's reason. Out of scope and unchanged: `GetItemByRef`, the navigational read path, where landing on the moved item is the helpful answer. **v0.35** (BUG-3079) makes an injected schema DEFAULT take the same `validateFieldType` check a caller-supplied value takes; one that fails is DISCARDED and named in `warnings.dropped_fields` instead of being stored. BEHAVIOR bump on the v0.30 / v0.29 / v0.16 grounds — no tool name, action enum or param shape changed, but a write door stores something different from what it stored before. Unlike v0.29, which turned an accepted value into a refusal, this turns a stored value into a reported drop: a create that used to land WITH a bad field still lands, without it. What it closes is two doors disagreeing about one value, decided only by who put it there. It also widens `dropped_fields` from the single relation case v0.29 introduced to a field of ANY type. No escape hatch, for v0.29's reason. ONE exception, which is the rule finishing its sentence rather than a carve-out: dropping leaves a REQUIRED field absent, which is exactly what the required check reports, so such a write is refused — naming the default as the cause, because a bare "field is required" points its reader at a request that never mentioned the field. **v0.34** (BUG-3037) adds an `expected_seq` param to `pad_item.action=update` — the STRONG optimistic-concurrency token, preferred over `expected_updated_at`. ADDITIVE (the v0.13 / v0.11 / v0.8 disposition): nothing existing moved and `expected_updated_at` still works. It is needed rather than nice because `updated_at` is stored at ONE-SECOND resolution, so two writes to a row inside one second both match the token and NEITHER conflicts — the loser is accepted and silently overwrites the winner, both callers seeing success. That is the shape of agent traffic, so the token agents were offered could not refuse the race it exists to refuse. `seq` is bumped on every mutation of the row under the write lock. Raising `updated_at`'s resolution instead was measured and REJECTED: the column is TEXT on both dialects and compared LEXICALLY in SQL (the since-cursor read plus eight `ORDER BY` sites), and Go's `RFC3339Nano` omits trailing zeros, so a sub-second value sorts BEFORE a whole-second value of the same second and the cursor would start skipping rows. The read side is what makes the token reachable: `seq` now serialises without `omitempty` on `models.Item` AND on the item SUMMARY shape (`cli.ItemSummary`), which is what `pad_item.list` returns by default since v0.9 — a token absent from the shape a caller reads is a token that caller cannot send. A value below 1 is a 400, not a 409: the server never issues one, so a 409 would read as contention that never clears. **v0.30** (BUG-2870) is a BEHAVIOR bump on the v0.29/v0.27/v0.26/v0.16/v0.10/v0.9 grounds — no tool name, action enum or param shape changed. **Every door refuses a padded KEY now**, and each was accepting it differently: /mcp trimmed it and wrote the declared field, the CLI stored a ghost field beside it — so both refuse something they used to accept. What is /mcp-only is the VALUE half, which it used to trim and type and now passes through to the same validation the CLI has always applied. A caller writing canonical entries sees no difference at either door. A second, separately-noticeable fix rides with it: `detectFieldConflicts` swallowed `parseFieldArray`'s refusal as "the caller owns this error surface", which held only while the sole possible error was a shape error — `reshapeItemFields` returns early with no `fields` object, so on the no-`fields` path (this bug's own path) four existing refusals were landing as successes. No escape hatch, for v0.29's reason: there is no legitimate call this refuses, only calls whose two readings a door used to choose between silently. **v0.29** (PLAN-2857 U1 / TASK-2878) is a BEHAVIOR bump on the v0.27/v0.26/v0.16/v0.10/v0.9 grounds (NOT v0.28's, which was purely additive) — no tool name, action enum, or param shape changed, but a `relation` field value must now name a live item in the collection that field declares, so every write door refuses values it used to store. Refused: names nothing (`not_found`), names an item in the wrong collection, the field declares no target collection (`target_missing`), or the value is a SLUG — a deliberate divergence from `ResolveItem`'s UUID→ref→slug ladder, since a slug is neither an ID nor stable and free text like "red" resolving to whatever is slugged `red` today is exactly the corruption this closes. Ordinary `validation_error`, no new code and no new details key, because stdio classifies errors by matching CLI stderr prose. A CARRIED value — already on the item, asserted by nobody — is never refused, since refusing would make every legacy item un-updatable, un-movable and un-copyable: within a workspace it resolves and SURVIVES, across a workspace boundary it is dropped without a lookup (a source-workspace id cannot mean anything in the destination) and reported through the same `warnings.dropped_fields` channel BUG-2674 established. No escape hatch, deliberately: unlike v0.10's `allow_draft` there is no legitimate call this refuses, and the case with a real claim to leniency is already exempt by provenance rather than by a flag. **v0.28** (IDEA-2641 / GitHub #1010) adds two ADDITIVE `pad_item` actions and two optional params: `remind` arms a one-shot reminder at an RFC3339 `remind_at` INSTANT, and `ack-reminder` acknowledges a fired one by `reminder_id`. Purely additive — nothing existing moved, and a v0.27 consumer that enumerates neither action is unaffected; same disposition as v0.13 / v0.11 / v0.8, which likewise wired existing CLI verbs onto the catalog. Agents already RECEIVED reminders (the poll surface is `pad_project.next` / `ready`, long exposed); what was missing is the half where an agent that defers work can say when it wants to be asked again. `remind_at` REFUSES a bare date rather than reading it as midnight — the `date` schema type accepts `YYYY-MM-DD` so a caller will try it, but a bare date names a 24-hour span and choosing an hour inside it would fire at a time nobody picked. Re-arm and disarm stay CLI-only: both address a reminder by an id the agent would have to list first, and no listing action exists on this surface yet — a door with no handle. **v0.27** (BUG-2850) types field values SERVER-SIDE at all eight validate sites, carries the `fields` object to the remote door with its JSON types intact, accepts undeclared keys while NAMING them in `warnings.undeclared_fields`, and replaces five accreted conflict guards with one canonical pass; the merge refuses several ambiguities it used to resolve silently. (This entry was missing from CLAUDE.md — the 0.27 unit swept `instructions.md` and `README.md` and not this file.) **v0.27** (BUG-2850) types field values server-side at all eight `Validate*` call sites so a declared number/json field is writable from the remote transport at all, carries the `fields` OBJECT with its JSON types intact, names undeclared keys back in `warnings.undeclared_fields` (accepted rather than refused — a census of 1012 items found 14 such keys across 168 live values, so refusing would have broken read-modify-write on items nobody had edited wrongly), and replaces the accreted per-site conflict guards with ONE check over a canonical view of every source; that check refuses ambiguities v0.26 resolved silently, chiefly two names for one target in a single call (`parent`/`plan`, `assign`/`assigned_user_id`, `role`/`agent_role_id`), refused even when the values match because the names address one thing through incomparable vocabularies and the two doors resolved them differently. **v0.26** (IDEA-2756) is a BEHAVIOR bump on the v0.9/v0.16/v0.25 grounds — no tool name, action enum, or param shape changed, but `pad_workspace.create` now refuses a call it used to permit. Closest precedent is v0.10, which likewise turned a server-side gate into a structured refusal; unlike v0.10 there is no `allow_draft`-style override, because the gate encodes a decision the USER made at consent time and a bypass param would be the app overriding its own grant. `POST /workspaces/import` is gated by the same shared helper (import mints a workspace through `store.ImportWorkspace`), though it has no MCP action today. **v0.25** (TASK-2657 / BUG-2702) resolves `pad_library.activate`'s destination collection from the target's declared artifact kind rather than the literal `conventions` / `playbooks` slugs, so activating into a workspace that renamed either collection lands correctly; a lookup ERROR is surfaced rather than silently falling back. **v0.24** (#1066) adds the `fields` OBJECT param to `pad_item` create/update — an alias merging into the same path as `field`/the dedicated params, so the shape reads return is finally a valid write shape; the same key supplied twice with conflicting values is REFUSED (refuse-on-ambiguity, the v0.18/v0.19 disposition), equal duplicates collapse to one write, and non-writer actions refuse a `fields` param loudly. It also makes input validation STRICT for every catalog tool: undeclared top-level keys are rejected with a structured error naming them, instead of being accepted and silently dropped by `BuildCLIArgs` — which is the mechanism that made the `fields` object a session-scoped silent no-op in the first place. Compat carve-out: `pad_item`'s v0.16 `assigned_user_id` / `agent_role_id` remote-transport clear form stays accepted (documented, undeprecated, deliberately never schema-declared). The strict half changes behaviour for inputs that previously "succeeded", but that reliance was indistinguishable from a caller bug (the key never did anything), so the break is the fix; one bump covers both halves. **v0.23** (BUG-2627 part 2 + BUG-2675) refuses system-metadata keys through `fields_patch` on all three doors at once, `github_pr` exempt on update (move/copy still refuse it), and adds the retry-hostile `stored_state_unreadable` code. **v0.22** (BUG-2674) stops `pad_item.action=move` destroying system metadata and refuses `field` setters naming the reserved keys there. **v0.21** bounds `pad_item.action=history` (BUG-2608): the `limit` param now covers it, default 50 / max 300, applied in the CATALOG action so it reaches both transports (HTTP reads the input; stdio gets the CLI's new `--limit` via BuildCLIArgs). The window is the NEWEST N and there is deliberately no `offset` — versions are reverse patches, so only a newest-end window is cheap to reconstruct. Additive param bump; a v0.20 consumer sending no limit now receives the newest 50 rather than every version, which is the fix. Summary mode additionally asks the server to skip patch resolution rather than resolving bodies the dispatcher discards. **v0.19** adds a `clear_parent` boolean to `pad_item` (BUG-2078) — an ADDITIVE param bump, same grounds as v0.18; nothing existing changed shape. The server has supported clearing a parent since BUG-2013 (`extractParentLink` treats a present-but-empty `parent` key in `fields_patch` as detach), but neither client surface could reach it — `--parent ""` was a silent no-op on the CLI and the MCP `parent` param has the same "empty means not provided" convention every other declared string on the tool has. Boolean rather than overloading the empty string, same two reasons as v0.18: keeps that invariant intact for every other param, and only a boolean reaches LOCAL STDIO via `BuildCLIArgs`, mapping to a new `--clear-parent` bareword flag exactly as `clear_assigned_user` maps to `--clear-assigned-user`. Update-only, same asymmetry as v0.18. A simultaneous `parent` + `clear_parent` — including via `field: ["parent=..."]` or the `plan` alias `extractParentLink` also accepts — is REFUSED on both transports, not silently resolved (codex round 1). Also refused, not silently applied: `clear_parent` against a collection whose schema declares its own `parent`/`plan` field — `extractParentLink` skips hierarchy handling entirely for a schema-shadowed key and lets it fall through as an ordinary field write, so the wire shape `{"parent":""}` can no longer distinguish clear-hierarchy intent from a legitimate blank-a-real-field write once it reaches the server; the ambiguity is created at the client surface that accepted `clear_parent`, so that surface refuses rather than guessing (codex round 2). **v0.18** adds `clear_assigned_user` / `clear_agent_role` booleans to `pad_item` (IDEA-2584) — an ADDITIVE param bump (v0.5/v0.6 precedent); nothing existing changed shape and v0.16/v0.17's empty-string forms still work, undeprecated. v0.16 and v0.17 made the clear WORK; nothing advertised it, because the params that do it were never in the catalog, so an agent reading the schema reached for `assign: ""` (a no-op, and it stays one). Booleans rather than declaring the string params, for two reasons: an empty DECLARED string is inert everywhere else on the tool, so giving one a destructive meaning would let a param-padding client silently unassign everything; and only a boolean can reach LOCAL STDIO, since `BuildCLIArgs` emits the CLI's real flags and a param with no flag behind it is dropped — these map to new `--clear-assigned-user` / `--clear-agent-role` bareword flags, exactly as `allow_draft` maps to `--allow-draft`. Update-only, deliberately asymmetric with create (clearing at create has no honest behaviour but a no-op; a test fails if someone adds them there). Server-side it is wiring, not new semantics: `models.ItemUpdate.ClearAssignedUser`/`ClearAgentRole` already existed with store support since BUG-2566. **v0.17** closes the transport gap v0.16 documented: local stdio MCP shells out to the CLI, which wrote `--field assigned_user_id=` into the item's FIELDS BLOB while the column stayed stale and then printed "Updated TASK-9". `cmd/pad/cmd_item.go` now lifts `columnFieldKeys` onto the columns on create AND update, mirroring `liftFieldsToColumns` and its INVARIANT. Two compat changes, ruled separately: non-empty values move to the column and stop writing the blob key (relying on the old behaviour is relying on a shadowing defect), and empty values clear (falls out of the lift, inherits BUG-2566). Existing stray blob keys are left alone — the fix stops minting new ones. Another behaviour-only bump (BUG-2583). **v0.16** lets an MCP agent UNASSIGN an item over the REMOTE transport (TASK-2571). No tool/action/param shape changed — this is a BEHAVIOR bump on the same grounds as v0.9: an empty-string `assigned_user_id` / `agent_role_id`, passed at the top level or as `field: ["assigned_user_id="]`, was silently dropped by two dispatch-path filters (`mapItemUpdate`, `liftFieldsToColumns`) and is now forwarded as a clear-to-NULL. The store has had defined clear semantics for exactly these two columns since BUG-2566 and HTTP inherited them, so this is uniformity restoration — MCP was the only surface with no way to unassign. Compat posture accepted deliberately: today's `""` senders get a no-op, and a no-op is the surprising reading. The empty-string filter on `tags` at the same call site STAYS (codex #547 r3 P2) — `tags: ""` is a corrupt JSONB/TEXT write, not a clear; same-looking guard, opposite justification. `clear_assigned_user` / `clear_agent_role` schema flags (option (b)) deliberately skipped as additive sugar, though codex review reopened the case — the catalog exposes `assign` / `role`, NOT the ID params, so an agent reading the schema still can't discover the clear (IDEA-2584); an empty `assign` is deliberately left inert because every other schema-declared string on that mapper treats empty as not-provided. **Transport scope:** v0.16 fixed the REMOTE /mcp transport only; v0.17 (BUG-2583) closed the local-stdio half at the CLI. **v0.15** adds the `unparented` boolean to `pad_item.list`, mutually exclusive with `parent`, for structural loose-item filtering (TASK-2096). **v0.14** added a `history` action to `pad_item` (read-only item version history — newest-first metadata; content body omitted for token thrift) and an `expected_updated_at` param for optimistic concurrency on `update` (round-trip the `updated_at` you last read; a stale value fails with a structured 409 `code=update_conflict`). The `update` action's field writes are now a server-side field-level MERGE (only the keys you set change) rather than a full-blob replace, closing the concurrent-update lost-write race (IDEA-1480 / TASK-2022) — pure addition to the action enum + param vocabulary; existing `pad_item` actions/params are unchanged and backwards-compatible. **v0.13** adds `ready` + `stale` actions to `pad_project`, mirroring the existing CLI `pad project ready` / `pad project stale` (TASK-2019): `ready` (read-only) returns the actionable backlog — the query-oriented counterpart to `next`, reusing the dashboard's suggested-next logic; `stale` (read-only) lists items needing attention (stalled, blocked, overdue, or out of the active workflow). Both HTTP dispatchers already existed (`dispatch_http_project.go`); this just wires them onto the catalog. `pad project reconcile` stays CLI-only (shells out to `gh` for live PR state — a local-git dependency MCP agents lack). Pure addition of two read-only actions — existing actions unchanged; backwards-compatible for v0.12 consumers that don't enumerate the new actions. **v0.12** adds an `activity` action to `pad_project`, mirroring the new CLI `pad project activity [--limit N] [--actor user|agent] [--since DATE]` (TASK-2018) — the non-streaming, bounded query counterpart to the CLI-only `pad project watch` SSE stream. Read-only snapshot of the workspace's enriched activity feed (item refs, titles, field-level change details) backed by the existing `GET /workspaces/{ws}/activity` endpoint (previously web-UI-only, now extended with a server-side `since` date filter so `limit`/`actor`/`since` behave identically across CLI, stdio MCP, and cloud HTTP), so agents can catch up on what other agents/users did since they last worked. Adds `actor` + `limit` params to the `pad_project` vocabulary (`since` already existed for changelog); pure addition — existing actions unchanged; backwards-compatible for v0.11 consumers that don't enumerate the new action. **v0.11** adds the read-only `pad_attachment` tool (the tenth resource × action tool) with `list` + `show` actions, mirroring the CLI `pad attachment list` / `pad attachment show` (TASK-2017): `list` enumerates a workspace's attachments (optional filters: item / category / collection / attached / unattached / sort / limit / offset); `show` returns one attachment's metadata (MIME, size, filename, ETag, last-modified) via a HEAD request without transferring bytes. Both HTTP dispatchers already existed (`dispatch_http_attachments.go`); this just wires them onto the catalog. Upload / download / view stay CLI-only (filesystem-bound, excluded per the catalog's exclusion rules). Pure addition — existing tools/actions unchanged; backwards-compatible for v0.10 consumers that don't enumerate the new tool. The base64 image RESOURCE for multimodal agents (`pad://workspace/{ws}/attachments/{id}`) shipped later in TASK-2077 (PR #930) as a bounded, image-only resource; TASK-2101 brought it — and the full read-only resource set — to the remote /mcp transport via the in-process `HTTPResourceFetcher`, so resources are no longer local-stdio-only. **v0.10** enforces the draft-playbook gate server-side: `pad_playbook.run` (and the underlying `POST /playbooks/{ref}/run`) now refuses a playbook whose `status` isn't `active` with a structured `playbook_not_active` error, adds an `allow_draft` boolean param (bareword `--allow-draft` on the CLI) as the escape hatch, and echoes the playbook `status` on both the `run` and `get` responses (BUG-2020). **v0.9** makes `pad_item.list` summary-shaped by default (drops item `content`, adds a default result limit of 50 / hard max 300 on MCP; CLI `--full` restores the complete shape) — a behavior change to the tool's return shape, hence the bump, though tool names, action enums, and parameter shapes are unchanged (TASK-2000). **v0.8** adds `restore` + `deleted` actions to `pad_workspace`, mirroring the CLI `pad workspace restore` / `pad workspace deleted` (TASK-1972): `deleted` (read-only) lists the caller's soft-deleted workspaces still inside the 30-day restore window; `restore` (mutating, not destructive, owner-only) un-soft-deletes a workspace by `slug` while it's still restorable. Both reuse the existing `slug` param — no new params; pure addition. **v0.7** adds `export` + `import` actions to `pad_item`, mirroring the CLI `pad item export` / `pad item import` (covers playbooks AND conventions). `export` (read-only) takes `ref` and returns the portable artifact text — it forces the CLI's stdout sink (`-o -`) so the bytes come back as the result instead of a file. `import` (mutating, not destructive) takes a new `artifact` param (the full artifact text) and returns `{ref, slug, warnings}`; the ExecDispatcher can't pipe stdin, so it spills the artifact to a temp file and dispatches `item import `. v0.6 added the `pad_item.backlinks` action; v0.5 added `pad_library`. v0.3 (PLAN-1377 / TASK-1380) introduced `pad_meta.action: bootstrap`, `pad_set_workspace`'s embedded-bootstrap response, and the `pad://workspace/{ws}/bootstrap` resource. **v0.4 (PLAN-1410)** is a comprehensive bootstrap-payload trim — same tool catalog, slimmer JSON shape inside bootstrap responses: `BootstrapCollection` projection drops `id`/`workspace_id`/timestamps/`settings` and emits `schema` as a nested object; `BootstrapRole` projection drops UUIDs/timestamps/`tools`; convention `slug` dropped; top-level `recent_activity` (a duplicate of `dashboard.recent_activity`) removed; new `BootstrapDashboard` wrapper caps five sub-arrays (`attention`, `recent_activity`, `active_items`, `active_plans`, `by_role`) at 5 entries each with parallel `*_overflow_count` fields; redundant schema labels omitted when `label == TitleCase(key)`. Cumulative size reduction: ~40% on a representative workspace, ~54% on the fixture (see PLAN-1410's Result section for per-section deltas). Compatibility: most changes are subtractive (dropped fields) or additive (overflow counts), but **one type change is breaking**: `collections[].schema` went from a JSON-encoded string to a nested JSON object — clients that JSON.parse()'d the string need to consume it directly as an object now. The dropped fields (UUIDs, timestamps, settings, duplicate `recent_activity`, convention `slug`) have canonical alternatives (slugs for addressing; `pad collection list` / `pad role list` for the full models when needed). +- `ToolSurfaceVersion` (the constant in `internal/mcp/version.go` is the current value; this list is its changelog, newest first) — the MCP tool catalog contract. Bump when tool names, action enums, or parameter shapes change incompatibly. **v0.99** (BUG-3790) bounds `pad_item` `starred` the same way: at most 300 items, most recently starred first, with `has_more: true` and the truncation note when more exist. It never pages. Both transports ask for one row past the cap (remote `GET /starred?limit=301`, stdio `pad item starred --limit 301`, a new CLI flag; without `--limit` the CLI walks every page). Starred used to return everything. Additive, on the v0.53 grounds. **v0.98** (BUG-3704) makes `pad_item` `list` say when it is truncated: it asks for one row past its limit and, when that row comes back, returns `limit` rows with `has_more: true` on the structured result and a second text block telling the agent to narrow the filters or raise `limit` (max 300). It never pages for the agent. A list that fits is unchanged. Additive, on the v0.53 grounds. **v0.97** (TASK-3613) adds an optional `worker_id` to `pad_item` (`claim`, `release`) and `pad_project` (`next`, `ready`): a lease is now held under a worker id plus the account, the holder label is display only, a claim answers with the caller's `worker_id`, and passing it back resumes the lease from another connection (see **Leases** above). `lease_held` details gain `worker` (the short id). The remote default holder label is the bare client name. ADDITIVE bump on the v0.53 grounds. **v0.96** (PLAN-3598 slice (c)) adds `pad_item.action=context` (`ref`; optional `intent`, `role`, `budget`), read-only, which returns one brief for working an item: the body of `GET /items/{ref}/context`, with the item and its seq, its parent chain with parsed acceptance criteria, the conventions whose trigger matches the intent (plus the always-on ones), matching playbooks, deps, decisions, links, conflicts, and what was omitted for size. New codes are `unknown_intent` (400, with `details.valid_intents`) and `unknown_role` (400). Both transports (`pad item context [--intent] [--role] [--budget]`). ADDITIVE bump on the v0.53 grounds. **v0.95** (TASK-3611) adds `pad_item.action=link-pr` (`ref`, `pr_number`, `pr_url`; optional `pr_title`, `pr_state`, `pr_branch`, `pr_repo`), which links a pull request from metadata the agent supplies, fetching nothing from GitHub, through the typed `github_pr` member; and `action=unlink-pr` (`ref`), which removes the link and refuses an item with none, as `pad github unlink` does. Both transports (`pad github link --pr-number N --pr-url U ...`, new flags). ADDITIVE bump on the v0.53 grounds. **v0.94** (TASK-3611) adds `pad_item.action=reminders` (`ref`), which lists an item's reminders with their ids (armed, fired, acknowledged), and `action=unremind` (`reminder_id`), which disarms one, on both transports. Listing is read-only; disarming needs edit permission on the item, as on the CLI. Re-arm stays CLI-only (`pad item remind --rearm`). ADDITIVE bump on the v0.53 grounds. **v0.93** (TASK-3611) makes `pad_item.action=create` and `update` over the local stdio transport WRITE a `fields` value that is an object or array, which they used to refuse (BUG-2850): the stdio door passes those keys, and every other non-string value (numbers and booleans, which `--field key=value` delivered as text unless the schema typed them), to the CLI as one `--fields-json` object (a new additive flag on `pad item create` / `update`), keeping their JSON types, as the remote door sends them. Any other action still refuses one. ADDITIVE bump on the v0.53 grounds. **v0.92** (TASK-3585) adds `op_key` to `pad_item.action=comment`, `note` and `decide`: retrying the same request with the same key answers the comment or entry the first attempt made instead of appending again, recorded in the write's own transaction. On the item-update route a key is accepted only with an append (and `source`); any other member alongside it is refused 400. `idempotency_target_gone` (410: the item or comment the key wrote has since been deleted) is now a structured code on both transports, with its own hint; at 0.91 it reached MCP as a generic error. No name, enum or param moved. ADDITIVE bump on the v0.53 grounds. **v0.91** (TASK-3585) adds `op_key` to `pad_item.action=create`: retrying the same create with the same key answers the item the first attempt created (as it stands now) instead of creating a second one; the answer is recorded in the create's own transaction. A key reused for a different create is refused `idempotency_key_reused`; one still in flight answers `idempotency_in_flight` (both codes already existed, and are structured on both transports for any route). A replay whose item has since been deleted answers HTTP 410 `idempotency_target_gone`, which at 0.91 reached MCP as a generic error. No name, enum or param moved. ADDITIVE bump on the v0.53 grounds. **v0.90** (TASK-3585) adds `pad_item.action=patch` `op_key`, an idempotency key: the same request retried with the same key returns its first answer instead of applying again; new codes `idempotency_key_reused` (422), `idempotency_in_flight` (409) and `patch_outcome_unknown` (409, with `seq` and the diff since). ADDITIVE bump on the v0.53 grounds. **v0.89** (PLAN-3578 step 3) adds `pad_item.action=patch` `undo` (a `patch_id`), which inverts that patch, anchored on the text around each edit as it landed, refusing when that text has changed since, and the code `patch_not_found` (404). ADDITIVE bump on the v0.53 grounds. **v0.88** (PLAN-3578 step 2) makes `pad_item.action=patch` on an item open in a browser editor APPLY (the editor applies it as a narrowed replace of its live document; the answer adds `content_state: "applied_pending_flush"`) where it was refused `patch_room_open`, and adds the code `patch_unstable_roundtrip`. `patch_room_open` now means only an older editor holds the item. BEHAVIOR bump on the v0.84 grounds. **v0.87** (PLAN-3578 step 1) adds `pad_item.action=patch {ref, edits:[{old, new, line_hint?}], expected_seq?}`: exact-text edits to the body (each `old` occurs exactly once, applied in order, all or nothing) answered with `{seq, patch_id, version_id, rebased, intervening?, diff}`. A moved `expected_seq` is applied over and reported, never refused. Refusals write nothing: `patch_anchor_missing`, `patch_anchor_ambiguous` (`details.lines`), `patch_room_open`. `get` gains `lines` for numbered body lines with `seq`. ADDITIVE bump on the v0.38 grounds. **v0.86** (PLAN-3555 phase 1) adds `pad_item.action=update` `replace` (bool): the deliberate overwrite of content with no version token, refused with `expected_seq` / `expected_updated_at` or without `content`. A content write with neither carries `warnings.unguarded_content_write: true`, and a later release refuses it. A seq `update_conflict` on a content write gains `details.content_write`, `changed_at` and `changed_by_kind`, a message naming both seqs that says not to resend the body, and the same "re-read and merge, do not resend" hint on both transports. ADDITIVE bump on the v0.53 grounds. **v0.85** (BUG-3544) makes `pad_workspace.action=invite` on an instance with no account yet (the setup window, reachable over local stdio) answer 409 `setup_required` ("This Pad instance must be initialized with pad auth setup") and write nothing, where it answered 500 (`server_error`) from the invitation's inviter foreign key. BEHAVIOR bump on the v0.58 / v0.45 grounds. **v0.84** (BUG-3542) makes a `pad_item` content update answer 409 `content_not_applied` with `details.apply_reason: "unconfirmed_edits"` when a browser tab holding the item open still has typing the server has not stored; token or not, other fields land and the content does not. Wait, re-read and resend; `overwrite_pending_edits: true` is the only override. BEHAVIOR bump on the v0.39 / v0.43 grounds. **v0.83** (TASK-3539) makes `pad_collection` create and update REFUSE a `schema` in which a field has no key, two fields share a key, or a select field lists an empty option or the same option twice, with 400 `validation_error` naming it (`field key "status" is defined more than once`). BEHAVIOR bump on the v0.43 / v0.48 grounds: a write door refuses a call it used to accept. Write-only: a schema already stored with a repeat still reads, and an update that sends no schema still applies. **v0.82** (PLAN-3535 PR 2) makes the items of a REFERENCE collection (`tracks_work: false`) stop counting as open work on every agent surface: `pad_project` next / ready / stale / standup / changelog, the dashboard and bootstrap dashboard, item progress, the `open_children` close guard and the attention decision set leave them out, and a report with no `collections` leaves the collection out as it already did a system one. Sidebar counts, item lists, search and links are unchanged; a collection without the key counts as work. BEHAVIOR bump on the v0.49 grounds. **v0.81** (PLAN-3535 PR 1) adds a `tracks_work` boolean to `pad_collection` create and update: false makes the collection REFERENCE material whose items stop counting toward parent progress, close blocking, Insights and open-work counts (applied by the follow-up PRs). On update it sets that one settings key server-side and leaves the rest alone; omitted, create picks work iff the done field can finish and update leaves it unchanged. ADDITIVE. **v0.80** (BUG-3533) makes `pad_item.action=import` work over remote `/mcp`: it answered `validation_failed` "artifact is required" on every call, because the catalog action dropped `artifact` from the input the HTTP dispatcher reads. Stdio is unchanged. ADDITIVE bump. **v0.79** (TASK-2863) lets a read-only grant (`read` / `pad:read`) run a playbook: `pad_playbook.action=run` stores nothing, and was refused only because it is a POST. It is the one POST a read grant may make (an exact-path allowlist); `match` and every write stay refused. BEHAVIOR bump, additive in effect. **v0.78** (TASK-2308) answers a remote `/mcp` WRITE action from an OAuth connection that can only read (`pad:read`), in a `tools/call` request of up to 1 MiB, with HTTP 403 and a `WWW-Authenticate` `error="insufficient_scope"` challenge naming `scope="pad:read pad:write"` and the metadata document, before dispatch, where it got a `permission_denied` tool result; that challenge is what lets a client re-authorize with the wider grant. Every such call was already refused, so nothing that worked is refused now. A read-scoped PAT keeps the tool error (it cannot re-authorize), as does a larger request, and the ChatGPT mount keeps its own challenge. The 401 challenge also names `scope`. BEHAVIOR bump. **v0.77** (BUG-2772) records a remote `/mcp` write as an AGENT write named by the client's declared MCP `clientInfo.name`, where it was recorded as the human, and gives a remote call a per-connection default lease holder (`claude-code#3f9a12c4`); see "Remote caller identity" below. A claim on an item another holder leases now answers `lease_held` with `details.holder` and `details.expires_at` on both transports, where remote said `conflict` and stdio `server_error` (BUG-3496). BEHAVIOR bump. **v0.76** (TASK-1809) makes a `pad_item` `claim` / `release` with no `holder` hold the lease under the caller's agent name (the `X-Pad-Agent` the CLI sends), else the account's email, where it was the email alone: several agents on one account silently shared one lease, a second claim answering 200 by refreshing the first. It now answers 409 `lease_held` naming the first agent. `pad_project.action=next` / `ready` leave out items whose live lease a claim by the caller would lose (same identity, the claim's own predicate, filtered before the cap of three; reminders are not filtered). Remote /mcp sends no agent name, so its default is still the email (TASK-3495). A lease taken before the upgrade is another holder's to the same agent for up to its TTL. BEHAVIOR bump on the v0.70 grounds. **v0.75** (BUG-3480) makes `pad_item.action=list` on both transports refuse a filter key no schema in scope declares and no item in scope stores (400 `validation_failed`, "invalid list filter ..."), where it answered an empty list, and refuse a key that is not a field key, which the store used to drop (answering the unfiltered list). BEHAVIOR bump on the v0.43 / v0.29 grounds; see the item list endpoint bullet under API. **v0.74** (TASK-2188) makes `pad_collection.action=update` answer, on both transports, with an `omitempty` `warnings.orphaned` [{field, option?, items}] naming each field, or select option, its schema removed that live items still hold. Nothing is refused. ADDITIVE, the v0.67 grounds; 0.73 is BUG-3480's. **v0.72** (TASK-2189) adds `pad_collection` `list-archived` (read-only) and `restore` (owner-only, by slug or id), backed by the new `GET /workspaces/{ws}/archived-collections` and `POST /workspaces/{ws}/archived-collections/{ref}/restore`: an agent's archive is recoverable by an agent. ADDITIVE. **v0.71** (TASK-3462 U3a) adds an `omitempty` `builtin_updates` count to the bootstrap on every door that returns it (the conventions and playbooks Pad ships whose library text changed since the workspace's copy, among the items the caller sees in full), and a server-instructions section telling the agent to mention it once and never apply an update itself. ADDITIVE. **v0.70** (BUG-3453) makes `pad_project.action=next` / `ready` fill any slot the existing tiers leave empty with ordinary open items from non-system collections that declare `priority` or `severity` (an initial status like `new` counts), ranked below every item admitted before, so a full list is unchanged and a moved-in backlog with no priorities is no longer "nothing ready". BEHAVIOR bump on the v0.49 grounds. **v0.69** (TASK-2314) makes every REMOTE route that needs a workspace and lacks one answer `no_workspace` with `available_workspaces` and a hint, as stdio always did, where it answered `validation_failed` "workspace is required"; the single-workspace default now runs before the `assign` / `role` resolvers. BEHAVIOR bump on the v0.42 / v0.45 grounds. **v0.68** (BUG-3448) makes the item resource render a structured field as compact JSON instead of Go's map syntax, keep a number above 2^53 to its digits and render a JSON null as `null`; the agent projection stops rounding large numbers. BEHAVIOR bump on the v0.62 / v0.64 grounds: an output shape changed, no name, enum or param moved; scalar fields render as before. **v0.67** (BUG-3446) lets a create in a system conventions or playbooks collection ADD a trigger/scope word the library itself uses to the select options instead of refusing it, so `pad_library.activate` and B3's literal create succeed in a `blank` workspace, and adds an `omitempty` `warnings.options_added` to the create result on both transports. A word the library does not use is refused as before. ADDITIVE. **v0.66** (BUG-2136) makes `pad_workspace.action=invite` always create a pending invitation, never add an existing account directly; see `internal/mcp/version.go`. **v0.65** (TASK-3413, SPEC-6 U9c) adds `omitempty` `via_app` and `via_app_name` to items an installed app CREATED (items.created_via_app, never the last app writer), comments an app wrote and version rows an app's write made, on both transports (`pad_item` get, list summary and full, comments, history summary and full). The name is the app's bot display name, else its origin, and survives uninstall. ADDITIVE. **v0.64** (BUG-3379) adds an `omitempty` `imported: true` to comments, attachment rows and version rows a workspace import wrote, on both transports (`pad_item` comments, `pad_attachment.list`, and `pad_item.history` with `full: true`; history summary rows and attachment `show` do not carry it): import keeps the export's author strings and uploader ids verbatim, and the flag says they were not verified here. ADDITIVE. **v0.63** (TASK-3321) adds an `omitempty` `actor_name` to every `pad_item.action=history` summary row on both transports, the display name of who made the change, where rows said only `user` or `agent`. ADDITIVE. **v0.62** (BUG-3326) makes remote /mcp `pad_set_workspace` embed the workspace bootstrap, as stdio always did: the in-process bootstrap resource read, run as the token's user under the same scope/consent perimeter, so a workspace the caller cannot read embeds nothing. ADDITIVE; no name, enum or param changed, and stdio is unchanged. **v0.61** (TASK-3321 U0b) marks `pad_workspace` destructiveHint:true and openWorldHint:true, because `invite` sends an email to an arbitrary address, and `pad_playbook` openWorldHint:true, because `match` sends text to the decision provider. Annotation-only BEHAVIOR bump on the v0.20 grounds; every other tool's block is unchanged. **v0.60** (TASK-2198 U4) makes `content_state: "applied_pending_flush"` clear ON ITS OWN on every door that carries it: after the item's collab room closes (or a one-minute sweep finds it dormant) the server rebuilds the body from the op-log and stores it, moving `seq` (a held `expected_seq` then answers `update_conflict` instead of `content_pending_flush`) and adding a `system` / `recovery` version. BEHAVIOR bump on the v0.59 / v0.39 grounds; no name, enum or param changed. Not a guarantee (failures, set-aside rows, `PAD_MATERIALIZE=off`), so re-read later, never re-send, still stands. **v0.59** (BUG-3252, tombstone ruled over cascade) makes `pad_item.action=delete-comment` on a comment with replies SUCCEED, leaving a tombstone (body emptied, author and timestamps kept, additive `deleted: true`) its replies stay under; it is removed when its last reply is deleted. `edit-comment` on a tombstone answers 409 `comment_deleted` on every transport. BEHAVIOR bump on the v0.58 grounds; `comment_has_replies` stays classified for older servers. **v0.58** (BUG-3252) makes `pad_item.action=delete-comment` on a comment that still has replies answer 409 `comment_has_replies` (details `comment_id`, `reply_count`) on every transport instead of `server_error`: `comments.parent_id` has no ON DELETE, so the delete failed the FK inside the store. Nothing is deleted either way. Tombstone was then ruled over cascade; v0.59 replaced this refusal with it. BEHAVIOR bump on the v0.45 grounds. **v0.57** (TASK-2695) adds `pad_item` `edit-comment` (ref, comment_id, message) and `delete-comment` (ref, comment_id) on all three transports, backed by the item-scoped routes `PATCH/DELETE /workspaces/{ws}/items/{ref}/comments/{id}`, which answer 404 unless the comment is on `ref` and otherwise run the workspace routes' handlers (edit author-only, delete item-edit). CLI: `pad item comment-edit` / `comment-delete`, refused against a server without the `item_scoped_comment_writes` capability. Every serialised comment gains a derived `edited` bool (updated_at > created_at), and `pad item comments` prints each comment's id. ADDITIVE. **v0.56** (BUG-3244) gives `content_state` a second value, `superseded_set_aside`, on every MCP door that carries it (`pad_item` get / full list, `pad_playbook` run, the item resource's line above the body): edits an editor schema-version rebuild set aside, which opening the item will NOT restore, so the resource line and the `content_pending_flush` hint (chosen by `details.set_aside_rows`) name `pad item set-aside` and `overwrite_pending_edits` instead. ADDITIVE bump: no name, enum or param changed, but an agent branching on the one-word vocabulary meets a word whose remedy differs. Reading or discarding the rows alone is not on the catalog. **v0.55** (BUG-2659) sends `pad_item.action=search`'s `collection` to /search as typed, and /search resolves it exact-first per workspace in scope (the item routes' resolver). In a workspace holding both `task` and `tasks`, `collection: "task"` now answers from `task` instead of `tasks`; every other workspace is unchanged, because the shorthand still resolves server-side. Stdio reaches it through the CLI, which sends the name as typed only to a server advertising `search_collection_resolution`. BEHAVIOR bump on the v0.36 / v0.40 grounds. **v0.54** (BUG-3217) keeps a `fields` number's literal through MCP on both transports (mcp-go's argument decode rounded anything above 2^53, and stdio's `--field` stringify carried the rounded value), and REFUSES a `fields` number beside a `field` entry for the same key when they differ as exact numbers — two values that differ only above 2^53 used to collapse into one rounded write; a matching pair (3.0 beside n=3) still collapses. BEHAVIOR bump on the v0.48 grounds. **v0.53** (BUG-2819) adds `filename_source` (caller / normalised / substituted / derived / unknown) to every `pad_attachment.action=list` row on both transports, because a stored filename cannot say whether the caller sent it or the server substituted it. ADDITIVE, the v0.28 / v0.13 disposition; `show` does not carry it, and `mcp_audit_log.tool_name_source` reaches no catalog action. Rows written before it read `unknown`, never `caller`. **v0.52** (BUG-2367 item 4) refuses a move or copy (every migrate door) that would change an item between open, done and abandoned unless the caller names the destination done field. Only the STATE is compared, so two values that both mean done carry. Move answers 400 `state_change_requires_value` with details `{field, options, from, to}`; bulk move puts it in a `failed[]` row; the copy answers 400 `validation_error` with the same sentence; the preflight emits a needs_value row with reason `state_change`, which the web dialog picker renders. A destination with no done select field is exempt. BEHAVIOR bump. **v0.51** (BUG-2367) stops every migrate door (single move, bulk move, cross-workspace copy and its preflight) carrying a value into a field the destination marks `computed` (preflight drop reason `target_computed`) or a value that collides on a destination `unique_scope` field. Provenance decides, the TASK-2878 rule: a CARRIED collision is dropped and reported (`not_unique`), a supplied override or injected default that collides is refused 409 `conflict`, and a required field emptied by the drop is refused as required, which is the existing needs_value route. Before it, single move answered 500 on the indexed `invocation_slug`, bulk move leaked the SQL error, and an unindexed unique field stored a duplicate. Reporting is additive and omitempty: `warnings.not_unique` [{key, value, holder?, message}] on the move response, bulk `updated[]` rows and the copy response, and a `detail` sentence on the preflight's dropped row. `holder` is present only when the caller may see that item, so the drop is not an existence oracle. BEHAVIOR bump on the v0.43 / v0.29 grounds. **v0.50** (BUG-3014) adds an ADDITIVE `omitempty` `stored_as_text: true` to a `relation_targets` entry whose stored value is not UUID-shaped (a title a bundle import carried verbatim, or legacy free text). Such a value was never an id and used to hydrate as a plain id-only entry, which reads as "gone or hidden"; an id-only entry without the flag keeps that meaning, and a UUID-shaped value, resolved or not, is byte-identical to v0.49. The predicate is syntactic, decided from the stored bytes and never from a lookup, so it discloses nothing, and deliberately not coupled to the resolver ladder. The CLI prints `"" (text, not a reference)` and the web chip says the same. **v0.49** (BUG-2410) makes `pad_project.action=report` with no `collections` param leave out SYSTEM collections (`Collection.IsSystem`: Conventions and Playbooks), which were counted in Insights' created, WIP and status totals; naming one explicitly still includes it. BEHAVIOR bump on the v0.40 / v0.42 grounds: a default call's content changed for every caller (web Insights, print, `pad project report`, both MCP transports, all through the one store rule). **v0.48** (BUG-3163) makes `pad_item.action=create` REFUSE a `field` / `fields` entry naming any reserved metadata key (`implementation_notes`, `decision_log`, `github_pr`, `convention`) on every transport, with 400 `validation_error`, creating nothing: create was the last door that stored one, as a string no extractor reads. Library activation, its one system writer, moves to an additive typed `convention` create member (not on the catalog; `pad_library.activate` is unchanged), and the CLI verifies from the stored fields that it landed, because an older server ignores the member and answers 201. BEHAVIOR bump on the v0.47 grounds. **v0.47** (BUG-2696) makes `pad_item.action=update` REFUSE a field setter naming `github_pr` on every transport (400 `validation_error` naming `pad github link` / `unlink`), closing the exemption v0.23 left: that door stored the PR as an unreadable string, so no link ever rendered. The writer is a new additive, typed update member (`github_pr` object + `clear_github_pr`) used by `pad github link` / `unlink` / `project reconcile`, deliberately NOT on the catalog (a remote PR-link action waits on the catalog-trim decision). BEHAVIOR bump; item create is BUG-3163. **v0.46** (BUG-3156) makes `pad_item.action=bulk-update` over stdio and remote REFUSE, per item, a status or priority change on an item whose collection does not declare that field, writing nothing for that item: the answer WebMCP has given since v0.44, so the three transports agree. Rows keep each transport's shape (stdio `failed[]` with `validation_error`, remote `results[]` with `validation_failed` and the server message in `hint`). The mechanism is the update door's new `refuse_undeclared_fields` member, which both bulk-update transports set; `pad_item.update` does not, and still accepts-and-warns. A server that predates the member ignores it, which is the old accept-and-warn. BEHAVIOR bump on the v0.44 / v0.43 grounds. **v0.45** (BUG-2829) reports an HTTP 413 as `too_large` on BOTH transports, with the server's own code in `details.reason`, where it used to be `server_error`: three deliberate caps are reachable from the catalog (a title rename's link cascade, an oversized outbox event, an oversized artifact import), and the old code read as transient and invited a retry that fails identically. Remote maps 413 in `classifyHTTPStatusKind`; stdio gets it from a structured marker the CLI root writes for any 413, and `too_large` joins `allowedStructuredErrorCodes`, which a test now proves contains every code any CLI marker writer emits. BEHAVIOR bump on the v0.42 grounds; no name, enum or param shape changed. **v0.44** (BUG-3154) makes `pad_item.action=bulk-update` over the WebMCP browser transport REFUSE, per item, a status or priority change on an item whose collection does not declare that field: the item lands in the bulk response's `failed` array with `validation_error` naming the collection and field, nothing is written, and the rest of the call applies. The door is `POST /items/bulk` (`set-priority`, and `move` with a `status`, with or without a `collection`, where the target's schema decides), where the request carries an operation and a value and the SERVER chooses the key; it used to store an orphan field and report the item updated. BEHAVIOR bump on the v0.43 / v0.40 grounds. The transports disagreed after it, stated rather than implied: stdio and remote issued a per-item PATCH, the single-item update door, which ACCEPTED the key with `warnings.undeclared_fields` (v0.27), until v0.46 converged them. **v0.43** (BUG-2379) makes `pad_item.action=move` REFUSE a field override naming a field the destination schema does not declare, with 400 `malformed_override` — the same check, code and message the cross-workspace copy already used. BEHAVIOR bump on the v0.40 / v0.29 grounds: a write door refuses a call it used to accept, where it used to store the key as an orphan field no schema renders. Create and update still ACCEPT undeclared keys with `warnings.undeclared_fields` (v0.27), because callers round-trip the whole fields blob; an override is a fresh assertion about the destination schema, not round-tripped state. **v0.42** (BUG-3142 + BUG-3147) changes the error CODE a LOCAL STDIO caller receives for two failure families that used to arrive as retryable `server_error`: an argv refusal (cobra/pflag: unknown flag, arg count, …) is now `validation_failed` with its message kept, and a 429 on any command is now `rate_limited` with `details.retry_after_seconds`, via the structured marker line the CLI writes at its root. It also stops the refusal that caused most of the first family: `BuildCLIArgs` now emits flags first and the positionals behind `--`, so free text starting with `-` (`item search "-ship it"`) is no longer parsed as a flag. BEHAVIOR bump; no name, enum or param shape changed, and the remote transport is untouched. **v0.41** (PLAN-3114 U5 / TASK-3120) adds a `match` action to `pad_playbook`: given free `text`, a Choice question over the workspace's ACTIVE playbooks plus a reserved `"none"` option returns the best match's ref (or `"none"`), confidence, per-option probabilities and the model. No provider configured → 404 `decision_provider_unavailable`; a provider error or an out-of-set answer → 502 `decision_provider_error`. Pure ADDITIVE bump (new action + param, nothing existing moved), read-only and side-effect-free. **v0.40** (BUG-3028) gives a scalar `relation` ONE stored form for "no target", the key ABSENT, converging on multi_relation's rule. A blank (`""` or whitespace) a write SETS — create, `fields_patch`, a changed value in full `fields`, a move/copy override — is normalised to absent before validation, so a `required` relation is refused as required (a patch blanking it now gets the answer deleting it always got). A legacy blank a write only CARRIES — an untouched key under `fields_patch` (normalised by the store under its write lock, via `ItemUpdate.BlankRelationKeys`), an unchanged value in full `fields`, move, copy, artifact import — is normalised after validation and never refused. An empty list filter on a scalar relation key of a collection-scoped list (`owner=`) matches all three spellings. BEHAVIOR bump; no shape change. Workspace import (`store.ImportWorkspace`) still stores blobs verbatim; its legacy blanks normalise on the next write. **v0.39** (BUG-3133) refuses `pad_item.update` that sets content WITH a version token (`expected_seq` / `expected_updated_at`) while the item's op-log holds content-bearing rows above its flush watermark, with 409 `content_pending_flush` (details `ref`, `pending_rows`). BEHAVIOR bump on the v0.35 / v0.36 grounds, carrying one additive param: `overwrite_pending_edits` lifts it, on the API, the CLI (`--overwrite-pending-edits`; `pad item edit --force` sets it on the save) and MCP alike, because an agent must be able to clear the refusal without a browser. The token guards the ROW and a tab's unflushed typing is not in it, so the write used to replace those edits — through the applier's setContent with a tab open, and by the direct path's op-log prune, which DELETES them, with none. Its own code rather than `update_conflict` because re-reading returns the same row and seq. A write without a token, without content, or to an item with nothing pending is unchanged, except that a direct write now reports `warnings.pruned_pending_edits` (additive, omitempty) when its prune deleted such rows. The check runs in the write's own tx; on the direct path it is under the item lock and appendMu and exact, on the applier path a tab can still type in the one server hop between the check and setContent. (v0.37 and v0.38 — the `agent` projection on `pad_item.get` and `claim` / `release` — are in `internal/mcp/version.go`; this paragraph had stopped at v0.36.) **v0.36** (BUG-3082) stops a REF-SHAPED `relation` value falling back to matching by item NUMBER when its prefix names a collection that is LIVE in the workspace; such a value is now `not_found`. BEHAVIOR bump on the v0.35 / v0.30 / v0.29 / v0.16 grounds — no tool name, action enum or param shape changed, but a write door refuses a value it used to accept. It finishes v0.29: that entry closed free-text corruption ("red" resolving to whatever is slugged `red` today) and left the same corruption open for anything shaped like a REF, which is the spelling the docs tell callers to prefer. Item numbers are workspace-unique and sequential ACROSS collections, so `CONVE-1` and `SECRE-1` are never both real — the fallback dropped the prefix, matched on the number alone, and landed on an item that was usually inside the field's declared collection, so the wrong-collection check above it passed and NOTHING was raised: a caller wrote `CONVE-1`, the item stored a different item's UUID, and the write answered 201 with the substitution visible only in `relation_targets`. The predicate is about the PREFIX rather than the item because a collection RENAME changes its prefix and a relation already written as the old ref must keep resolving (BUG-2873) — that ref's prefix names nothing afterwards, so the fallback still fires for it, while a prefix that IS live and simply holds no item at that number is the caller naming a real collection that does not contain what they said. A SOFT-DELETED collection counts as absent IN THAT PREDICATE, for the same reason a renamed one does — a claim about the fallback only: the exact-prefix lookup ahead of it never filtered on the collection’s own `deleted_at`, so an item whose collection was soft-deleted still matches THERE and never reaches the predicate. That is left alone rather than made consistent, because it cannot retarget — the downstream collection check refuses it. RESIDUAL, stated rather than implied and pinned by a test: a ref pasted from ANOTHER workspace whose prefix also names no collection here still resolves by number, because nothing in the value distinguishes it from a rename's leftover. No escape hatch, for v0.29's reason. Out of scope and unchanged: `GetItemByRef`, the navigational read path, where landing on the moved item is the helpful answer. **v0.35** (BUG-3079) makes an injected schema DEFAULT take the same `validateFieldType` check a caller-supplied value takes; one that fails is DISCARDED and named in `warnings.dropped_fields` instead of being stored. BEHAVIOR bump on the v0.30 / v0.29 / v0.16 grounds — no tool name, action enum or param shape changed, but a write door stores something different from what it stored before. Unlike v0.29, which turned an accepted value into a refusal, this turns a stored value into a reported drop: a create that used to land WITH a bad field still lands, without it. What it closes is two doors disagreeing about one value, decided only by who put it there. It also widens `dropped_fields` from the single relation case v0.29 introduced to a field of ANY type. No escape hatch, for v0.29's reason. ONE exception, which is the rule finishing its sentence rather than a carve-out: dropping leaves a REQUIRED field absent, which is exactly what the required check reports, so such a write is refused — naming the default as the cause, because a bare "field is required" points its reader at a request that never mentioned the field. **v0.34** (BUG-3037) adds an `expected_seq` param to `pad_item.action=update` — the STRONG optimistic-concurrency token, preferred over `expected_updated_at`. ADDITIVE (the v0.13 / v0.11 / v0.8 disposition): nothing existing moved and `expected_updated_at` still works. It is needed rather than nice because `updated_at` is stored at ONE-SECOND resolution, so two writes to a row inside one second both match the token and NEITHER conflicts — the loser is accepted and silently overwrites the winner, both callers seeing success. That is the shape of agent traffic, so the token agents were offered could not refuse the race it exists to refuse. `seq` is bumped on every mutation of the row under the write lock. Raising `updated_at`'s resolution instead was measured and REJECTED: the column is TEXT on both dialects and compared LEXICALLY in SQL (the since-cursor read plus eight `ORDER BY` sites), and Go's `RFC3339Nano` omits trailing zeros, so a sub-second value sorts BEFORE a whole-second value of the same second and the cursor would start skipping rows. The read side is what makes the token reachable: `seq` now serialises without `omitempty` on `models.Item` AND on the item SUMMARY shape (`cli.ItemSummary`), which is what `pad_item.list` returns by default since v0.9 — a token absent from the shape a caller reads is a token that caller cannot send. A value below 1 is a 400, not a 409: the server never issues one, so a 409 would read as contention that never clears. **v0.30** (BUG-2870) is a BEHAVIOR bump on the v0.29/v0.27/v0.26/v0.16/v0.10/v0.9 grounds — no tool name, action enum or param shape changed. **Every door refuses a padded KEY now**, and each was accepting it differently: /mcp trimmed it and wrote the declared field, the CLI stored a ghost field beside it — so both refuse something they used to accept. What is /mcp-only is the VALUE half, which it used to trim and type and now passes through to the same validation the CLI has always applied. A caller writing canonical entries sees no difference at either door. A second, separately-noticeable fix rides with it: `detectFieldConflicts` swallowed `parseFieldArray`'s refusal as "the caller owns this error surface", which held only while the sole possible error was a shape error — `reshapeItemFields` returns early with no `fields` object, so on the no-`fields` path (this bug's own path) four existing refusals were landing as successes. No escape hatch, for v0.29's reason: there is no legitimate call this refuses, only calls whose two readings a door used to choose between silently. **v0.29** (PLAN-2857 U1 / TASK-2878) is a BEHAVIOR bump on the v0.27/v0.26/v0.16/v0.10/v0.9 grounds (NOT v0.28's, which was purely additive) — no tool name, action enum, or param shape changed, but a `relation` field value must now name a live item in the collection that field declares, so every write door refuses values it used to store. Refused: names nothing (`not_found`), names an item in the wrong collection, the field declares no target collection (`target_missing`), or the value is a SLUG — a deliberate divergence from `ResolveItem`'s UUID→ref→slug ladder, since a slug is neither an ID nor stable and free text like "red" resolving to whatever is slugged `red` today is exactly the corruption this closes. Ordinary `validation_error`, no new code and no new details key, because stdio classifies errors by matching CLI stderr prose. A CARRIED value — already on the item, asserted by nobody — is never refused, since refusing would make every legacy item un-updatable, un-movable and un-copyable: within a workspace it resolves and SURVIVES, across a workspace boundary it is dropped without a lookup (a source-workspace id cannot mean anything in the destination) and reported through the same `warnings.dropped_fields` channel BUG-2674 established. No escape hatch, deliberately: unlike v0.10's `allow_draft` there is no legitimate call this refuses, and the case with a real claim to leniency is already exempt by provenance rather than by a flag. **v0.28** (IDEA-2641 / GitHub #1010) adds two ADDITIVE `pad_item` actions and two optional params: `remind` arms a one-shot reminder at an RFC3339 `remind_at` INSTANT, and `ack-reminder` acknowledges a fired one by `reminder_id`. Purely additive — nothing existing moved, and a v0.27 consumer that enumerates neither action is unaffected; same disposition as v0.13 / v0.11 / v0.8, which likewise wired existing CLI verbs onto the catalog. Agents already RECEIVED reminders (the poll surface is `pad_project.next` / `ready`, long exposed); what was missing is the half where an agent that defers work can say when it wants to be asked again. `remind_at` REFUSES a bare date rather than reading it as midnight — the `date` schema type accepts `YYYY-MM-DD` so a caller will try it, but a bare date names a 24-hour span and choosing an hour inside it would fire at a time nobody picked. Re-arm and disarm stay CLI-only: both address a reminder by an id the agent would have to list first, and no listing action exists on this surface yet — a door with no handle. **v0.27** (BUG-2850) types field values SERVER-SIDE at all eight validate sites, carries the `fields` object to the remote door with its JSON types intact, accepts undeclared keys while NAMING them in `warnings.undeclared_fields`, and replaces five accreted conflict guards with one canonical pass; the merge refuses several ambiguities it used to resolve silently. (This entry was missing from CLAUDE.md — the 0.27 unit swept `instructions.md` and `README.md` and not this file.) **v0.27** (BUG-2850) types field values server-side at all eight `Validate*` call sites so a declared number/json field is writable from the remote transport at all, carries the `fields` OBJECT with its JSON types intact, names undeclared keys back in `warnings.undeclared_fields` (accepted rather than refused — a census of 1012 items found 14 such keys across 168 live values, so refusing would have broken read-modify-write on items nobody had edited wrongly), and replaces the accreted per-site conflict guards with ONE check over a canonical view of every source; that check refuses ambiguities v0.26 resolved silently, chiefly two names for one target in a single call (`parent`/`plan`, `assign`/`assigned_user_id`, `role`/`agent_role_id`), refused even when the values match because the names address one thing through incomparable vocabularies and the two doors resolved them differently. **v0.26** (IDEA-2756) is a BEHAVIOR bump on the v0.9/v0.16/v0.25 grounds — no tool name, action enum, or param shape changed, but `pad_workspace.create` now refuses a call it used to permit. Closest precedent is v0.10, which likewise turned a server-side gate into a structured refusal; unlike v0.10 there is no `allow_draft`-style override, because the gate encodes a decision the USER made at consent time and a bypass param would be the app overriding its own grant. `POST /workspaces/import` is gated by the same shared helper (import mints a workspace through `store.ImportWorkspace`), though it has no MCP action today. **v0.25** (TASK-2657 / BUG-2702) resolves `pad_library.activate`'s destination collection from the target's declared artifact kind rather than the literal `conventions` / `playbooks` slugs, so activating into a workspace that renamed either collection lands correctly; a lookup ERROR is surfaced rather than silently falling back. **v0.24** (#1066) adds the `fields` OBJECT param to `pad_item` create/update — an alias merging into the same path as `field`/the dedicated params, so the shape reads return is finally a valid write shape; the same key supplied twice with conflicting values is REFUSED (refuse-on-ambiguity, the v0.18/v0.19 disposition), equal duplicates collapse to one write, and non-writer actions refuse a `fields` param loudly. It also makes input validation STRICT for every catalog tool: undeclared top-level keys are rejected with a structured error naming them, instead of being accepted and silently dropped by `BuildCLIArgs` — which is the mechanism that made the `fields` object a session-scoped silent no-op in the first place. Compat carve-out: `pad_item`'s v0.16 `assigned_user_id` / `agent_role_id` remote-transport clear form stays accepted (documented, undeprecated, deliberately never schema-declared). The strict half changes behaviour for inputs that previously "succeeded", but that reliance was indistinguishable from a caller bug (the key never did anything), so the break is the fix; one bump covers both halves. **v0.23** (BUG-2627 part 2 + BUG-2675) refuses system-metadata keys through `fields_patch` on all three doors at once, `github_pr` exempt on update (move/copy still refuse it), and adds the retry-hostile `stored_state_unreadable` code. **v0.22** (BUG-2674) stops `pad_item.action=move` destroying system metadata and refuses `field` setters naming the reserved keys there. **v0.21** bounds `pad_item.action=history` (BUG-2608): the `limit` param now covers it, default 50 / max 300, applied in the CATALOG action so it reaches both transports (HTTP reads the input; stdio gets the CLI's new `--limit` via BuildCLIArgs). The window is the NEWEST N and there is deliberately no `offset` — versions are reverse patches, so only a newest-end window is cheap to reconstruct. Additive param bump; a v0.20 consumer sending no limit now receives the newest 50 rather than every version, which is the fix. Summary mode additionally asks the server to skip patch resolution rather than resolving bodies the dispatcher discards. **v0.19** adds a `clear_parent` boolean to `pad_item` (BUG-2078) — an ADDITIVE param bump, same grounds as v0.18; nothing existing changed shape. The server has supported clearing a parent since BUG-2013 (`extractParentLink` treats a present-but-empty `parent` key in `fields_patch` as detach), but neither client surface could reach it — `--parent ""` was a silent no-op on the CLI and the MCP `parent` param has the same "empty means not provided" convention every other declared string on the tool has. Boolean rather than overloading the empty string, same two reasons as v0.18: keeps that invariant intact for every other param, and only a boolean reaches LOCAL STDIO via `BuildCLIArgs`, mapping to a new `--clear-parent` bareword flag exactly as `clear_assigned_user` maps to `--clear-assigned-user`. Update-only, same asymmetry as v0.18. A simultaneous `parent` + `clear_parent` — including via `field: ["parent=..."]` or the `plan` alias `extractParentLink` also accepts — is REFUSED on both transports, not silently resolved (codex round 1). Also refused, not silently applied: `clear_parent` against a collection whose schema declares its own `parent`/`plan` field — `extractParentLink` skips hierarchy handling entirely for a schema-shadowed key and lets it fall through as an ordinary field write, so the wire shape `{"parent":""}` can no longer distinguish clear-hierarchy intent from a legitimate blank-a-real-field write once it reaches the server; the ambiguity is created at the client surface that accepted `clear_parent`, so that surface refuses rather than guessing (codex round 2). **v0.18** adds `clear_assigned_user` / `clear_agent_role` booleans to `pad_item` (IDEA-2584) — an ADDITIVE param bump (v0.5/v0.6 precedent); nothing existing changed shape and v0.16/v0.17's empty-string forms still work, undeprecated. v0.16 and v0.17 made the clear WORK; nothing advertised it, because the params that do it were never in the catalog, so an agent reading the schema reached for `assign: ""` (a no-op, and it stays one). Booleans rather than declaring the string params, for two reasons: an empty DECLARED string is inert everywhere else on the tool, so giving one a destructive meaning would let a param-padding client silently unassign everything; and only a boolean can reach LOCAL STDIO, since `BuildCLIArgs` emits the CLI's real flags and a param with no flag behind it is dropped — these map to new `--clear-assigned-user` / `--clear-agent-role` bareword flags, exactly as `allow_draft` maps to `--allow-draft`. Update-only, deliberately asymmetric with create (clearing at create has no honest behaviour but a no-op; a test fails if someone adds them there). Server-side it is wiring, not new semantics: `models.ItemUpdate.ClearAssignedUser`/`ClearAgentRole` already existed with store support since BUG-2566. **v0.17** closes the transport gap v0.16 documented: local stdio MCP shells out to the CLI, which wrote `--field assigned_user_id=` into the item's FIELDS BLOB while the column stayed stale and then printed "Updated TASK-9". `cmd/pad/cmd_item.go` now lifts `columnFieldKeys` onto the columns on create AND update, mirroring `liftFieldsToColumns` and its INVARIANT. Two compat changes, ruled separately: non-empty values move to the column and stop writing the blob key (relying on the old behaviour is relying on a shadowing defect), and empty values clear (falls out of the lift, inherits BUG-2566). Existing stray blob keys are left alone — the fix stops minting new ones. Another behaviour-only bump (BUG-2583). **v0.16** lets an MCP agent UNASSIGN an item over the REMOTE transport (TASK-2571). No tool/action/param shape changed — this is a BEHAVIOR bump on the same grounds as v0.9: an empty-string `assigned_user_id` / `agent_role_id`, passed at the top level or as `field: ["assigned_user_id="]`, was silently dropped by two dispatch-path filters (`mapItemUpdate`, `liftFieldsToColumns`) and is now forwarded as a clear-to-NULL. The store has had defined clear semantics for exactly these two columns since BUG-2566 and HTTP inherited them, so this is uniformity restoration — MCP was the only surface with no way to unassign. Compat posture accepted deliberately: today's `""` senders get a no-op, and a no-op is the surprising reading. The empty-string filter on `tags` at the same call site STAYS (codex #547 r3 P2) — `tags: ""` is a corrupt JSONB/TEXT write, not a clear; same-looking guard, opposite justification. `clear_assigned_user` / `clear_agent_role` schema flags (option (b)) deliberately skipped as additive sugar, though codex review reopened the case — the catalog exposes `assign` / `role`, NOT the ID params, so an agent reading the schema still can't discover the clear (IDEA-2584); an empty `assign` is deliberately left inert because every other schema-declared string on that mapper treats empty as not-provided. **Transport scope:** v0.16 fixed the REMOTE /mcp transport only; v0.17 (BUG-2583) closed the local-stdio half at the CLI. **v0.15** adds the `unparented` boolean to `pad_item.list`, mutually exclusive with `parent`, for structural loose-item filtering (TASK-2096). **v0.14** added a `history` action to `pad_item` (read-only item version history — newest-first metadata; content body omitted for token thrift) and an `expected_updated_at` param for optimistic concurrency on `update` (round-trip the `updated_at` you last read; a stale value fails with a structured 409 `code=update_conflict`). The `update` action's field writes are now a server-side field-level MERGE (only the keys you set change) rather than a full-blob replace, closing the concurrent-update lost-write race (IDEA-1480 / TASK-2022) — pure addition to the action enum + param vocabulary; existing `pad_item` actions/params are unchanged and backwards-compatible. **v0.13** adds `ready` + `stale` actions to `pad_project`, mirroring the existing CLI `pad project ready` / `pad project stale` (TASK-2019): `ready` (read-only) returns the actionable backlog — the query-oriented counterpart to `next`, reusing the dashboard's suggested-next logic; `stale` (read-only) lists items needing attention (stalled, blocked, overdue, or out of the active workflow). Both HTTP dispatchers already existed (`dispatch_http_project.go`); this just wires them onto the catalog. `pad project reconcile` stays CLI-only (shells out to `gh` for live PR state — a local-git dependency MCP agents lack). Pure addition of two read-only actions — existing actions unchanged; backwards-compatible for v0.12 consumers that don't enumerate the new actions. **v0.12** adds an `activity` action to `pad_project`, mirroring the new CLI `pad project activity [--limit N] [--actor user|agent] [--since DATE]` (TASK-2018) — the non-streaming, bounded query counterpart to the CLI-only `pad project watch` SSE stream. Read-only snapshot of the workspace's enriched activity feed (item refs, titles, field-level change details) backed by the existing `GET /workspaces/{ws}/activity` endpoint (previously web-UI-only, now extended with a server-side `since` date filter so `limit`/`actor`/`since` behave identically across CLI, stdio MCP, and cloud HTTP), so agents can catch up on what other agents/users did since they last worked. Adds `actor` + `limit` params to the `pad_project` vocabulary (`since` already existed for changelog); pure addition — existing actions unchanged; backwards-compatible for v0.11 consumers that don't enumerate the new action. **v0.11** adds the read-only `pad_attachment` tool (the tenth resource × action tool) with `list` + `show` actions, mirroring the CLI `pad attachment list` / `pad attachment show` (TASK-2017): `list` enumerates a workspace's attachments (optional filters: item / category / collection / attached / unattached / sort / limit / offset); `show` returns one attachment's metadata (MIME, size, filename, ETag, last-modified) via a HEAD request without transferring bytes. Both HTTP dispatchers already existed (`dispatch_http_attachments.go`); this just wires them onto the catalog. Upload / download / view stay CLI-only (filesystem-bound, excluded per the catalog's exclusion rules). Pure addition — existing tools/actions unchanged; backwards-compatible for v0.10 consumers that don't enumerate the new tool. The base64 image RESOURCE for multimodal agents (`pad://workspace/{ws}/attachments/{id}`) shipped later in TASK-2077 (PR #930) as a bounded, image-only resource; TASK-2101 brought it — and the full read-only resource set — to the remote /mcp transport via the in-process `HTTPResourceFetcher`, so resources are no longer local-stdio-only. **v0.10** enforces the draft-playbook gate server-side: `pad_playbook.run` (and the underlying `POST /playbooks/{ref}/run`) now refuses a playbook whose `status` isn't `active` with a structured `playbook_not_active` error, adds an `allow_draft` boolean param (bareword `--allow-draft` on the CLI) as the escape hatch, and echoes the playbook `status` on both the `run` and `get` responses (BUG-2020). **v0.9** makes `pad_item.list` summary-shaped by default (drops item `content`, adds a default result limit of 50 / hard max 300 on MCP; CLI `--full` restores the complete shape) — a behavior change to the tool's return shape, hence the bump, though tool names, action enums, and parameter shapes are unchanged (TASK-2000). **v0.8** adds `restore` + `deleted` actions to `pad_workspace`, mirroring the CLI `pad workspace restore` / `pad workspace deleted` (TASK-1972): `deleted` (read-only) lists the caller's soft-deleted workspaces still inside the 30-day restore window; `restore` (mutating, not destructive, owner-only) un-soft-deletes a workspace by `slug` while it's still restorable. Both reuse the existing `slug` param — no new params; pure addition. **v0.7** adds `export` + `import` actions to `pad_item`, mirroring the CLI `pad item export` / `pad item import` (covers playbooks AND conventions). `export` (read-only) takes `ref` and returns the portable artifact text — it forces the CLI's stdout sink (`-o -`) so the bytes come back as the result instead of a file. `import` (mutating, not destructive) takes a new `artifact` param (the full artifact text) and returns `{ref, slug, warnings}`; the ExecDispatcher can't pipe stdin, so it spills the artifact to a temp file and dispatches `item import `. v0.6 added the `pad_item.backlinks` action; v0.5 added `pad_library`. v0.3 (PLAN-1377 / TASK-1380) introduced `pad_meta.action: bootstrap`, `pad_set_workspace`'s embedded-bootstrap response, and the `pad://workspace/{ws}/bootstrap` resource. **v0.4 (PLAN-1410)** is a comprehensive bootstrap-payload trim — same tool catalog, slimmer JSON shape inside bootstrap responses: `BootstrapCollection` projection drops `id`/`workspace_id`/timestamps/`settings` and emits `schema` as a nested object; `BootstrapRole` projection drops UUIDs/timestamps/`tools`; convention `slug` dropped; top-level `recent_activity` (a duplicate of `dashboard.recent_activity`) removed; new `BootstrapDashboard` wrapper caps five sub-arrays (`attention`, `recent_activity`, `active_items`, `active_plans`, `by_role`) at 5 entries each with parallel `*_overflow_count` fields; redundant schema labels omitted when `label == TitleCase(key)`. Cumulative size reduction: ~40% on a representative workspace, ~54% on the fixture (see PLAN-1410's Result section for per-section deltas). Compatibility: most changes are subtractive (dropped fields) or additive (overflow counts), but **one type change is breaking**: `collections[].schema` went from a JSON-encoded string to a nested JSON object — clients that JSON.parse()'d the string need to consume it directly as an object now. The dropped fields (UUIDs, timestamps, settings, duplicate `recent_activity`, convention `slug`) have canonical alternatives (slugs for addressing; `pad collection list` / `pad role list` for the full models when needed). Post-0.30 without a bump (BUG-2995): a successful content write through the designated applier used to answer with the item's PREVIOUS content — on that path the markdown goes to a live tab's Y.Doc and the row write runs with `Content` nil, so the response described the item as it stood before the request. It now carries the content as SENT plus an additive `omitempty` `warnings.content_outcome: "applied_pending_flush"`. No bump, on the BUG-2304 rather than the v0.9 grounds: v0.9 bumped because list rows LOST fields consumers read, whereas here nothing is removed or retyped — what changed is the VALUE of one field on one path, which a caller does observe. The claim is that no DOCUMENTED OR SUPPORTED reliance breaks, not that none can exist: a consumer could have detected the applier path by noticing the response echoed something other than what it sent, and that stops working — but it was never documented, a genuinely lost write produced the same mismatch, and `warnings.content_outcome` answers that question properly in the same change. Reads are unchanged: during the window a `get` (or `list` with `full: true`) still answers from the row, so the warning means re-read later, not re-send. diff --git a/internal/cli/client.go b/internal/cli/client.go index 4763fb942..c1b83661a 100644 --- a/internal/cli/client.go +++ b/internal/cli/client.go @@ -623,14 +623,49 @@ func (c *Client) UnstarItem(wsSlug, itemSlug string) error { return c.delete("/workspaces/" + url.PathEscape(wsSlug) + "/items/" + url.PathEscape(itemSlug) + "/star") } -// ListStarredItems returns the current user's starred items in a workspace. -func (c *Client) ListStarredItems(wsSlug string, includeTerminal bool) ([]models.Item, error) { - var result []models.Item - path := "/workspaces/" + url.PathEscape(wsSlug) + "/starred" +// ListStarredItemsPage returns at most limit of the current user's starred +// items, from the start of the list, and whether more exist (BUG-3790: MCP +// asks for one row past its cap and states the truncation; it never pages). +func (c *Client) ListStarredItemsPage(wsSlug string, includeTerminal bool, limit int) ([]models.Item, ItemListPage, error) { + q := url.Values{} if includeTerminal { - path += "?include_terminal=true" + q.Set("include_terminal", "true") + } + q.Set("limit", strconv.Itoa(limit)) + var page []models.Item + h, err := c.getWithHeader("/workspaces/"+url.PathEscape(wsSlug)+"/starred?"+q.Encode(), &page) + return page, itemListPage(h), err +} + +// ListStarredItems returns the current user's starred items in a workspace, +// following the server's next-offset until has-more is false (BUG-3790: the +// list is bounded per page). +func (c *Client) ListStarredItems(wsSlug string, includeTerminal bool) ([]models.Item, error) { + q := url.Values{} + if includeTerminal { + q.Set("include_terminal", "true") + } + var all []models.Item + for offset := 0; ; { + if offset > 0 { + q.Set("offset", strconv.Itoa(offset)) + } + var page []models.Item + path := "/workspaces/" + url.PathEscape(wsSlug) + "/starred" + if len(q) > 0 { + path += "?" + q.Encode() + } + h, err := c.getWithHeader(path, &page) + if err != nil { + return nil, err + } + all = append(all, page...) + p := itemListPage(h) + if !p.HasMore || p.NextOffset <= offset { + return all, nil + } + offset = p.NextOffset } - return result, c.get(path, &result) } // CreateWatch creates (or replaces the predicate on) a durable watch for diff --git a/internal/mcp/bug3790_starred_truncation_test.go b/internal/mcp/bug3790_starred_truncation_test.go new file mode 100644 index 000000000..455c0db8a --- /dev/null +++ b/internal/mcp/bug3790_starred_truncation_test.go @@ -0,0 +1,111 @@ +package mcp + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/PerpetualSoftware/pad/internal/models" + "github.com/mark3labs/mcp-go/mcp" +) + +// BUG-3790 (lead ruling): pad_item starred never pages. Both transports ask +// for one row past the list cap, and a result that had the extra row comes +// back trimmed to the cap with has_more and the truncation note. + +func bug3790Check(t *testing.T, res *mcp.CallToolResult, wantItems int, wantMore bool) { + t.Helper() + obj, ok := res.StructuredContent.(map[string]any) + if !ok { + t.Fatalf("structured content %T", res.StructuredContent) + } + if got := len(obj["items"].([]any)); got != wantItems { + t.Fatalf("items %d, want %d", got, wantItems) + } + more, _ := obj["has_more"].(bool) + if more != wantMore { + t.Fatalf("has_more %v, want %v", more, wantMore) + } + note := len(res.Content) == 2 && strings.Contains(res.Content[1].(mcp.TextContent).Text, "More items match") + if note != wantMore { + t.Fatalf("note present %v, want %v", note, wantMore) + } +} + +// Stdio: the CLI is asked for --limit 301. +func TestBUG3790_StdioStarredAsksOnePastTheCapAndSaysTruncation(t *testing.T) { + for _, tc := range []struct { + rows, want int + more bool + }{{3, 3, false}, {300, 300, false}, {301, 300, true}} { + t.Run(fmt.Sprintf("rows=%d", tc.rows), func(t *testing.T) { + disp := &listRowsDispatcher{rows: tc.rows} + env := ActionEnv{Doc: liveCmdhelpDoc(t), Workspace: NewWorkspaceState("docapp"), Dispatcher: disp} + res, err := actionItemStarred(context.Background(), map[string]any{"all": true}, env) + if err != nil || res == nil || res.IsError { + t.Fatalf("actionItemStarred: %v %v", res, err) + } + args := strings.Join(disp.gotArgs, " ") + if !strings.Contains(args, "--limit 301") || !strings.Contains(args, "--all") { + t.Fatalf("args %q: want --limit 301 and --all", args) + } + bug3790Check(t, res, tc.want, tc.more) + }) + } +} + +// Remote: the HTTP dispatcher sends ?limit=301 to /starred. +func TestBUG3790_RemoteStarredAsksOnePastTheCapAndSaysTruncation(t *testing.T) { + for _, tc := range []struct { + rows, want int + more bool + }{{3, 3, false}, {301, 300, true}} { + t.Run(fmt.Sprintf("rows=%d", tc.rows), func(t *testing.T) { + var gotURL string + h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotURL = r.URL.String() + items := make([]map[string]any, tc.rows) + for i := range items { + items[i] = map[string]any{"ref": fmt.Sprintf("TASK-%d", i+1)} + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(items) + }) + disp := &HTTPHandlerDispatcher{ + Handler: h, + UserResolver: func(context.Context) *models.User { return &models.User{ID: "u1", Name: "U"} }, + } + env := ActionEnv{Doc: liveCmdhelpDoc(t), Workspace: NewWorkspaceState("docapp"), Dispatcher: disp} + res, err := actionItemStarred(context.Background(), map[string]any{}, env) + if err != nil || res == nil || res.IsError { + t.Fatalf("actionItemStarred: %v %v", res, err) + } + if !strings.HasPrefix(gotURL, "/api/v1/workspaces/docapp/starred?") || !strings.Contains(gotURL, "limit=301") { + t.Fatalf("remote asked %q; want /starred with limit=301", gotURL) + } + bug3790Check(t, res, tc.want, tc.more) + }) + } +} + +// CONVE-19: the tool's starred action IS the truncating action, not a bare +// pass-through to the CLI. +func TestBUG3790_PadItemStarredIsBoundToTheTruncatingAction(t *testing.T) { + handler, ok := padItemTool.Actions["starred"] + if !ok { + t.Fatal("pad_item has no starred action") + } + disp := &listRowsDispatcher{rows: 301} + env := ActionEnv{Doc: liveCmdhelpDoc(t), Workspace: NewWorkspaceState("docapp"), Dispatcher: disp} + res, err := handler(context.Background(), map[string]any{}, env) + if err != nil || res == nil || res.IsError { + t.Fatalf("starred: %v %v", res, err) + } + if !strings.Contains(strings.Join(disp.gotArgs, " "), "--limit 301") { + t.Fatalf("args %v: the bound handler did not ask one past the cap", disp.gotArgs) + } + bug3790Check(t, res, 300, true) +} diff --git a/internal/mcp/catalog_item.go b/internal/mcp/catalog_item.go index e3ed8263c..5efb94ca0 100644 --- a/internal/mcp/catalog_item.go +++ b/internal/mcp/catalog_item.go @@ -115,7 +115,7 @@ var padItemTool = ToolDef{ // Stars "star": passThrough([]string{"item", "star"}), "unstar": passThrough([]string{"item", "unstar"}), - "starred": passThrough([]string{"item", "starred"}), + "starred": actionItemStarred, // Comments. reply-comment isn't a separate CLI verb — the // `comment` command takes a --reply-to flag, exposed here as @@ -291,7 +291,7 @@ var padItemSchemaParams = []ParamDef{ // ── List / starred ── {Name: "all", Type: "bool", Description: "Include archived/done items in list responses. Optional for: list, starred."}, - {Name: "limit", Type: "number", Description: "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions."}, + {Name: "limit", Type: "number", Description: "Maximum results. Optional for: list, backlinks, history. Each defaults to 50, max 300. For history the window is the NEWEST N versions. starred takes no limit: it returns at most 300, most recently starred first, with has_more when more exist."}, {Name: "offset", Type: "number", Description: "Skip the first N results (paging). Optional for: backlinks."}, {Name: "sort", Type: "string", Description: "Sort field. Optional for: list."}, {Name: "group_by", Type: "string", Description: "Group-by field. Optional for: list."}, @@ -900,6 +900,24 @@ func actionItemList(ctx context.Context, input map[string]any, env ActionEnv) (* return markItemListTruncation(res, limit), nil } +// actionItemStarred handles pad_item.action=starred. Like list it never pages +// (BUG-3790, lead ruling, as BUG-3704 ruled for list): it asks for one row past +// the list cap, on both transports (the HTTP mapper sends it as ?limit=, stdio +// as pad item starred --limit), and a result that had the extra row says +// has_more with the truncation note. +func actionItemStarred(ctx context.Context, input map[string]any, env ActionEnv) (*CallToolResult, error) { + out := make(map[string]any, len(input)+1) + for k, v := range input { + out[k] = v + } + out["limit"] = mcpItemListMaxLimit + 1 + res, err := env.Dispatch(ctx, []string{"item", "starred"}, out) + if err != nil || res == nil || res.IsError { + return res, err + } + return markItemListTruncation(res, mcpItemListMaxLimit), nil +} + // itemListTruncatedNote is the text an agent sees when its list was cut short. const itemListTruncatedNote = "More items match than this list shows (has_more). Narrow the filters, or raise limit (max %d)." diff --git a/internal/mcp/catalog_readonly_test.go b/internal/mcp/catalog_readonly_test.go index 7c8ee6ac8..932453ceb 100644 --- a/internal/mcp/catalog_readonly_test.go +++ b/internal/mcp/catalog_readonly_test.go @@ -757,6 +757,7 @@ func liveCmdhelpDoc(t *testing.T) *cmdhelp.Document { Flags: map[string]cmdhelp.Flag{ "workspace": {Type: "string"}, "all": {Type: "bool"}, + "limit": {Type: "int"}, // BUG-3790 }, }, "item comment": { diff --git a/internal/mcp/dispatch_http_routes.go b/internal/mcp/dispatch_http_routes.go index 8d10372aa..a7393add8 100644 --- a/internal/mcp/dispatch_http_routes.go +++ b/internal/mcp/dispatch_http_routes.go @@ -783,9 +783,17 @@ func mapItemStarred(input map[string]any) (string, string, []byte, error) { if workspace == "" { return "", "", nil, errWorkspaceRequired } - urlPath := "/api/v1/workspaces/" + url.PathEscape(workspace) + "/starred" + q := url.Values{} if all, _ := input["all"].(bool); all { - urlPath += "?include_terminal=true" + q.Set("include_terminal", "true") + } + // actionItemStarred always sets it, one past the MCP cap (BUG-3790). + if n, ok := numericInput(input["limit"]); ok && int(n) > 0 { + q.Set("limit", strconv.Itoa(int(n))) + } + urlPath := "/api/v1/workspaces/" + url.PathEscape(workspace) + "/starred" + if len(q) > 0 { + urlPath += "?" + q.Encode() } return http.MethodGet, urlPath, nil, nil } diff --git a/internal/mcp/instructions.md b/internal/mcp/instructions.md index 5abf43cec..b55e745d6 100644 --- a/internal/mcp/instructions.md +++ b/internal/mcp/instructions.md @@ -6,7 +6,7 @@ Pad is a project tracker for developers and AI agents — issues (TASK, BUG), pl If the user is asking general code questions with no project-management thread, you don't need this server. -## Tool surface (v0.98) +## Tool surface (v0.99) Ten resource × action tools, plus `pad_set_workspace`. Eleven tools total. diff --git a/internal/mcp/version.go b/internal/mcp/version.go index 6d16d4ca4..e21748a59 100644 --- a/internal/mcp/version.go +++ b/internal/mcp/version.go @@ -1738,6 +1738,16 @@ const CmdhelpVersion = "0.1" // caller cannot read embeds nothing; a failed fetch stays non-fatal, // as on stdio. Stdio is unchanged. // +// 0.99 — BUG-3790, starred truncation. ADDITIVE bump on the v0.53 +// grounds: `pad_item.action=starred` returns at most 300 items, most +// recently starred first, and when more exist says `has_more: true` +// on the structured result plus the same truncation note as list. It +// never pages (lead ruling, as for list). Both transports ask for one +// row past the cap: remote as GET /starred?limit=301, stdio as +// `pad item starred --limit 301` (a new CLI flag; without it the CLI +// walks every page). Starred used to return everything. The `limit` +// param's description names starred; no name, enum or param moved. +// // 0.98 — BUG-3704, item list truncation. ADDITIVE bump on the v0.53 // grounds: `pad_item.action=list` asks for one row past its limit and, // when that row comes back, returns `limit` rows with `has_more: true` @@ -2177,7 +2187,7 @@ const CmdhelpVersion = "0.1" // this surface can receive it; the entry exists so a future action does // not collapse it to permission_denied. When an action that can reach // it is added, that addition is the contract change and owns the bump. -const ToolSurfaceVersion = "0.98" +const ToolSurfaceVersion = "0.99" // MetaVersionURI is the canonical URI of the queryable version document. // Lives outside the pad://workspace/{ws}/... namespace because it's a diff --git a/internal/server/bug3789_bounded_lists_test.go b/internal/server/bug3789_bounded_lists_test.go new file mode 100644 index 000000000..ecb63aa0e --- /dev/null +++ b/internal/server/bug3789_bounded_lists_test.go @@ -0,0 +1,398 @@ +package server + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sort" + "testing" + + "github.com/PerpetualSoftware/pad/internal/models" +) + +// BUG-3789, BUG-3790, BUG-3792: the children list, the starred list and a +// shared collection are bounded like the item lists (BUG-3704). A missing or +// invalid limit is the maximum, an explicit one is clamped, and the paging +// state comes back in headers (and, on the share payload, in the body). + +type bug3789Page struct { + items []models.Item + more string + next string + rawBody []byte +} + +func bug3789Get(t *testing.T, srv *Server, path, cookie string) bug3789Page { + t.Helper() + rr := doRequest(srv, "GET", path, nil) + if cookie != "" { + rr = doRequestWithCookie(srv, "GET", path, nil, cookie) + } + if rr.Code != http.StatusOK { + t.Fatalf("%s: %d %s", path, rr.Code, rr.Body.String()) + } + var items []models.Item + _ = json.Unmarshal(rr.Body.Bytes(), &items) + return bug3789Page{items, rr.Header().Get(itemListHasMoreHeader), rr.Header().Get(itemListNextOffsetHeader), rr.Body.Bytes()} +} + +// walk follows next-offset from offset 0, asking for pageSize rows a page. +func bug3789Walk(t *testing.T, srv *Server, base, cookie string, pageSize int) ([]models.Item, int) { + t.Helper() + sep := "?" + if containsByte(base, '?') { + sep = "&" + } + var all []models.Item + offset, pages := 0, 0 + for { + p := bug3789Get(t, srv, fmt.Sprintf("%s%slimit=%d&offset=%d", base, sep, pageSize, offset), cookie) + pages++ + all = append(all, p.items...) + if p.more == "false" { + if p.next != "" { + t.Fatalf("last page carries next-offset %q", p.next) + } + return all, pages + } + if p.more != "true" || p.next != fmt.Sprint(offset+pageSize) { + t.Fatalf("page at %d: has-more %q next %q", offset, p.more, p.next) + } + offset += pageSize + if pages > 100 { + t.Fatal("walk did not end") + } + } +} + +func containsByte(s string, b byte) bool { + for i := 0; i < len(s); i++ { + if s[i] == b { + return true + } + } + return false +} + +func TestBUG3789_ChildrenAreBoundedAndPaged(t *testing.T) { + bothBackends(t, func(t *testing.T, srv *Server) { + slug, wsID := task3462Workspace(t, srv, "Children 3789", "startup") + tasks, _ := srv.store.GetCollectionBySlug(wsID, "tasks") + parent, err := srv.store.CreateItem(wsID, tasks.ID, models.ItemCreate{Title: "Parent", Fields: `{"status":"open"}`}) + if err != nil { + t.Fatal(err) + } + n := maxItemListQueryLimit + 1 + for i := 0; i < n; i++ { + child, err := srv.store.CreateItem(wsID, tasks.ID, models.ItemCreate{Title: fmt.Sprintf("Child %04d", i), Fields: `{"status":"open"}`}) + if err != nil { + t.Fatal(err) + } + if _, err := srv.store.CreateItemLink(wsID, models.ItemLinkCreate{TargetID: parent.ID, LinkType: "parent"}, child.ID); err != nil { + t.Fatal(err) + } + } + // Every child ties on the list order's leading keys. + if _, err := srv.store.DB().Exec(srv.store.D().Rebind(`UPDATE items SET sort_order = 0, created_at = '2026-01-01T00:00:00Z' WHERE collection_id = ? AND id <> ?`), tasks.ID, parent.ID); err != nil { + t.Fatal(err) + } + base := "/api/v1/workspaces/" + slug + "/items/" + parent.Slug + "/children" + for _, q := range []string{"", "?limit=0", "?limit=-5", "?limit=abc", "?limit=5000"} { + p := bug3789Get(t, srv, base+q, "") + if len(p.items) != maxItemListQueryLimit || p.more != "true" || p.next != fmt.Sprint(maxItemListQueryLimit) { + t.Fatalf("%s: %d rows, has-more %q, next %q", q, len(p.items), p.more, p.next) + } + } + all, _ := bug3789Walk(t, srv, base, "", 400) + seen := map[string]int{} + for _, it := range all { + seen[it.ID]++ + } + if len(seen) != n || len(all) != n { + t.Fatalf("walk returned %d rows, %d distinct; want %d each", len(all), len(seen), n) + } + }) +} + +// A restricted member's children window counts only children they may see, +// and has_children reflects only visible grandchildren. +func TestBUG3789_ChildrenWindowIsOverVisibleRows(t *testing.T) { + srv := testServer(t) + ownerCookie := bootstrapFirstUser(t, srv, "owner@test.com", "Owner") + rr := doRequestWithCookie(srv, "POST", "/api/v1/workspaces", map[string]string{"name": "Vis 3789"}, ownerCookie) + if rr.Code != http.StatusCreated { + t.Fatalf("create workspace: %d %s", rr.Code, rr.Body.String()) + } + var ws models.Workspace + parseJSON(t, rr, &ws) + tasks, _ := srv.store.GetCollectionBySlug(ws.ID, "tasks") + ideas, _ := srv.store.GetCollectionBySlug(ws.ID, "ideas") + mk := func(collID, title string, parent *models.Item) *models.Item { + it, err := srv.store.CreateItem(ws.ID, collID, models.ItemCreate{Title: title}) + if err != nil { + t.Fatal(err) + } + if parent != nil { + if _, err := srv.store.CreateItemLink(ws.ID, models.ItemLinkCreate{TargetID: parent.ID, LinkType: "parent"}, it.ID); err != nil { + t.Fatal(err) + } + } + return it + } + parent := mk(tasks.ID, "Parent", nil) + visible := mk(tasks.ID, "Visible child", parent) + for i := 0; i < 3; i++ { + mk(ideas.ID, fmt.Sprintf("Hidden child %d", i), parent) + } + mk(ideas.ID, "Hidden grandchild", visible) + if _, err := srv.store.DB().Exec(srv.store.D().Rebind(`UPDATE items SET sort_order = 0, created_at = '2026-01-01T00:00:00Z' WHERE workspace_id = ?`), ws.ID); err != nil { + t.Fatal(err) + } + // The visible child sorts first. + if _, err := srv.store.DB().Exec(srv.store.D().Rebind(`UPDATE items SET sort_order = -1 WHERE id = ?`), visible.ID); err != nil { + t.Fatal(err) + } + + m, err := srv.store.CreateUser(models.UserCreate{Email: "restricted@test.com", Name: "Restricted", Password: "correct-horse-battery-staple"}) + if err != nil { + t.Fatal(err) + } + if err := srv.store.AddWorkspaceMember(ws.ID, m.ID, "viewer"); err != nil { + t.Fatal(err) + } + if err := srv.store.SetMemberCollectionAccess(ws.ID, m.ID, "specific", []string{tasks.ID}); err != nil { + t.Fatal(err) + } + cookie, err := srv.store.CreateSession(m.ID, "web-test", "192.0.2.1", "", webSessionTTL) + if err != nil { + t.Fatal(err) + } + base := "/api/v1/workspaces/" + ws.Slug + "/items/" + parent.Slug + "/children" + p := bug3789Get(t, srv, base+"?limit=1", cookie) + if len(p.items) != 1 || p.items[0].ID != visible.ID || p.more != "false" { + t.Fatalf("restricted page: %d rows, has-more %q; want only the visible child and has-more false", len(p.items), p.more) + } + if p.items[0].HasChildren { + t.Fatal("has_children counts a grandchild the member cannot see") + } + owner := bug3789Get(t, srv, base, ownerCookie) + if len(owner.items) != 4 { + t.Fatalf("owner sees %d children, want 4", len(owner.items)) + } + for _, it := range owner.items { + if it.ID == visible.ID && !it.HasChildren { + t.Fatal("owner: has_children misses the grandchild") + } + } +} + +func TestBUG3790_StarredIsBoundedPagedAndLoadsBodiesForThePage(t *testing.T) { + srv := testServer(t) + ownerCookie := bootstrapFirstUser(t, srv, "owner@test.com", "Owner") + rr := doRequestWithCookie(srv, "POST", "/api/v1/workspaces", map[string]string{"name": "Stars 3790"}, ownerCookie) + if rr.Code != http.StatusCreated { + t.Fatalf("create workspace: %d %s", rr.Code, rr.Body.String()) + } + var ws models.Workspace + parseJSON(t, rr, &ws) + owner, _ := srv.store.GetUserByEmail("owner@test.com") + tasks, _ := srv.store.GetCollectionBySlug(ws.ID, "tasks") + n := maxItemListQueryLimit + 1 + for i := 0; i < n; i++ { + it, err := srv.store.CreateItem(ws.ID, tasks.ID, models.ItemCreate{Title: fmt.Sprintf("Star %04d", i), Content: fmt.Sprintf("body %04d", i), Fields: `{"status":"open"}`}) + if err != nil { + t.Fatal(err) + } + if err := srv.store.StarItem(owner.ID, it.ID); err != nil { + t.Fatal(err) + } + } + // Every star ties on starred-at. + if _, err := srv.store.DB().Exec(`UPDATE item_stars SET created_at = '2026-01-01T00:00:00Z'`); err != nil { + t.Fatal(err) + } + base := "/api/v1/workspaces/" + ws.Slug + "/starred" + for _, q := range []string{"", "?limit=0", "?limit=abc", "?limit=5000"} { + p := bug3789Get(t, srv, base+q, ownerCookie) + if len(p.items) != maxItemListQueryLimit || p.more != "true" || p.next != fmt.Sprint(maxItemListQueryLimit) { + t.Fatalf("%s: %d rows, has-more %q, next %q", q, len(p.items), p.more, p.next) + } + } + all, _ := bug3789Walk(t, srv, base, ownerCookie, 300) + seen := map[string]bool{} + for _, it := range all { + if seen[it.ID] { + t.Fatalf("%s returned twice", it.Title) + } + seen[it.ID] = true + if it.Content != "body "+it.Title[len("Star "):] { + t.Fatalf("%s: body %q", it.Title, it.Content) + } + } + if len(seen) != n { + t.Fatalf("walk returned %d distinct, want %d", len(seen), n) + } + summary := bug3789Get(t, srv, base+"?summary=true&limit=5", ownerCookie) + for _, it := range summary.items { + if it.Content != "" { + t.Fatalf("summary carries a body: %q", it.Content) + } + } +} + +func TestBUG3792_SharedCollectionIsBoundedAndPaged(t *testing.T) { + bothBackends(t, func(t *testing.T, srv *Server) { + _, wsID := task3462Workspace(t, srv, "Share 3792", "startup") + tasks, _ := srv.store.GetCollectionBySlug(wsID, "tasks") + n := maxItemListQueryLimit + 1 + for i := 0; i < n; i++ { + if _, err := srv.store.CreateItem(wsID, tasks.ID, models.ItemCreate{Title: fmt.Sprintf("Shared %04d", i), Fields: `{"status":"open"}`}); err != nil { + t.Fatal(err) + } + } + creator, err := srv.store.CreateUser(models.UserCreate{Email: "sharer@test.com", Name: "Sharer", Password: "correct-horse-battery-staple"}) + if err != nil { + t.Fatal(err) + } + link, err := srv.store.CreateShareLink(wsID, "collection", tasks.ID, "view", creator.ID, nil) + if err != nil { + t.Fatal(err) + } + get := func(q string) (items []map[string]any, hasMore bool, next float64) { + t.Helper() + req := httptest.NewRequest("GET", "/api/v1/s/"+link.Token+q, nil) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("%s: %d %s", q, rr.Code, rr.Body.String()) + } + var body struct { + Items []map[string]any `json:"items"` + HasMore bool `json:"has_more"` + NextOffset float64 `json:"next_offset"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + return body.Items, body.HasMore, body.NextOffset + } + for _, q := range []string{"", "?limit=0", "?limit=abc", "?limit=5000"} { + items, more, next := get(q) + if len(items) != maxItemListQueryLimit || !more || next != maxItemListQueryLimit { + t.Fatalf("%s: %d items, has_more %v, next %v", q, len(items), more, next) + } + } + seen := map[string]bool{} + for offset := 0; ; { + items, more, next := get(fmt.Sprintf("?limit=400&offset=%d", offset)) + for _, it := range items { + ref := fmt.Sprint(it["ref"]) + if seen[ref] { + t.Fatalf("%s returned twice", ref) + } + seen[ref] = true + } + if !more { + break + } + offset = int(next) + } + if len(seen) != n { + t.Fatalf("walk returned %d items, want %d", len(seen), n) + } + }) +} + +// Rows that tie on every leading sort key come back in id order. The links and +// stars are written in DESCENDING id order, so the scan order the database +// would fall back to without the id tie-break is the reverse: an order that is +// not total lets offset pages repeat or skip rows (SQLite happens to keep +// paging consistent by scan order; Postgres does not promise it). +func TestBUG3789_TiesComeBackInIDOrder(t *testing.T) { + srv := testServer(t) + ownerCookie := bootstrapFirstUser(t, srv, "owner@test.com", "Owner") + rr := doRequestWithCookie(srv, "POST", "/api/v1/workspaces", map[string]string{"name": "Ties 3789"}, ownerCookie) + if rr.Code != http.StatusCreated { + t.Fatalf("create workspace: %d %s", rr.Code, rr.Body.String()) + } + var ws models.Workspace + parseJSON(t, rr, &ws) + owner, _ := srv.store.GetUserByEmail("owner@test.com") + tasks, _ := srv.store.GetCollectionBySlug(ws.ID, "tasks") + parent, err := srv.store.CreateItem(ws.ID, tasks.ID, models.ItemCreate{Title: "Parent"}) + if err != nil { + t.Fatal(err) + } + var ids []string + for i := 0; i < 6; i++ { + it, err := srv.store.CreateItem(ws.ID, tasks.ID, models.ItemCreate{Title: fmt.Sprintf("Tie %d", i)}) + if err != nil { + t.Fatal(err) + } + ids = append(ids, it.ID) + } + sort.Strings(ids) + for i := len(ids) - 1; i >= 0; i-- { + if _, err := srv.store.CreateItemLink(ws.ID, models.ItemLinkCreate{TargetID: parent.ID, LinkType: "parent"}, ids[i]); err != nil { + t.Fatal(err) + } + if err := srv.store.StarItem(owner.ID, ids[i]); err != nil { + t.Fatal(err) + } + } + if _, err := srv.store.DB().Exec(srv.store.D().Rebind(`UPDATE items SET sort_order = 0, created_at = '2026-01-01T00:00:00Z' WHERE collection_id = ? AND id <> ?`), tasks.ID, parent.ID); err != nil { + t.Fatal(err) + } + if _, err := srv.store.DB().Exec(`UPDATE item_stars SET created_at = '2026-01-01T00:00:00Z'`); err != nil { + t.Fatal(err) + } + for _, path := range []string{ + "/api/v1/workspaces/" + ws.Slug + "/items/" + parent.Slug + "/children", + "/api/v1/workspaces/" + ws.Slug + "/starred", + } { + all, pages := bug3789Walk(t, srv, path, ownerCookie, 2) + var got []string + for _, it := range all { + got = append(got, it.ID) + } + if pages != 3 || fmt.Sprint(got) != fmt.Sprint(ids) { + t.Fatalf("%s: %d pages, order %v; want 3 pages in id order %v", path, pages, got, ids) + } + } +} + +// Lead check (#2153): an offset past the end is an empty page that serialises +// as [] (not null), with has-more false, on both bare-array lists. +func TestBUG3789_AnOffsetPastTheEndIsAnEmptyArray(t *testing.T) { + srv := testServer(t) + ownerCookie := bootstrapFirstUser(t, srv, "owner@test.com", "Owner") + rr := doRequestWithCookie(srv, "POST", "/api/v1/workspaces", map[string]string{"name": "End 3789"}, ownerCookie) + if rr.Code != http.StatusCreated { + t.Fatalf("create workspace: %d %s", rr.Code, rr.Body.String()) + } + var ws models.Workspace + parseJSON(t, rr, &ws) + owner, _ := srv.store.GetUserByEmail("owner@test.com") + tasks, _ := srv.store.GetCollectionBySlug(ws.ID, "tasks") + parent, _ := srv.store.CreateItem(ws.ID, tasks.ID, models.ItemCreate{Title: "Parent"}) + child, _ := srv.store.CreateItem(ws.ID, tasks.ID, models.ItemCreate{Title: "Child"}) + if _, err := srv.store.CreateItemLink(ws.ID, models.ItemLinkCreate{TargetID: parent.ID, LinkType: "parent"}, child.ID); err != nil { + t.Fatal(err) + } + if err := srv.store.StarItem(owner.ID, child.ID); err != nil { + t.Fatal(err) + } + for _, path := range []string{ + "/api/v1/workspaces/" + ws.Slug + "/starred?offset=5", + "/api/v1/workspaces/" + ws.Slug + "/items/" + parent.Slug + "/children?offset=5", + } { + p := bug3789Get(t, srv, path, ownerCookie) + if body := string(p.rawBody); body != "[]\n" && body != "[]" { + t.Fatalf("%s: body %q, want []", path, body) + } + if p.more != "false" || p.next != "" { + t.Fatalf("%s: has-more %q next %q", path, p.more, p.next) + } + } +} diff --git a/internal/server/handlers_items.go b/internal/server/handlers_items.go index 60e67ce6e..988ede690 100644 --- a/internal/server/handlers_items.go +++ b/internal/server/handlers_items.go @@ -3921,16 +3921,8 @@ func (s *Server) handleGetItemChildren(w http.ResponseWriter, r *http.Request) { return } - children, err := s.store.GetChildItems(item.ID) - if err != nil { - writeInternalError(w, err) - return - } - if children == nil { - children = []models.Item{} - } - - // Filter children by collection visibility and item-level grants + // Visibility is applied in the query and the list is windowed (BUG-3789), + // so the has-more probe counts only children the caller may see. visibleIDs, visErr := s.visibleCollectionIDs(r, workspaceID) if visErr != nil { writeInternalError(w, visErr) @@ -3941,36 +3933,36 @@ func (s *Server) handleGetItemChildren(w http.ResponseWriter, r *http.Request) { writeInternalError(w, grantErr) return } + limit, offset := parseListWindow(r) + params := store.ChildListParams{Limit: limit + 1, Offset: offset} if visibleIDs != nil { - filtered := children[:0] - for _, child := range children { - if !isCollectionVisible(child.CollectionID, visibleIDs) { - continue - } - if !s.isItemVisibleToGuest(r, workspaceID, &child, fullCollIDs, grantedItemIDs) { - continue - } - filtered = append(filtered, child) - } - children = filtered + params.CollectionIDs = visibleIDs + params.FullCollectionIDs, params.GrantedItemIDs = fullCollIDs, grantedItemIDs + } + children, err := s.store.ListChildItems(item.ID, params) + if err != nil { + writeInternalError(w, err) + return + } + children = setListWindowHeaders(w, children, limit, offset) + if children == nil { + children = []models.Item{} } s.enrichItemsWithParent(r, workspaceID, children, visibleIDs) if visibleIDs != nil { // Visibility-aware has_children: only count visible grandchildren + // One visible grandchild decides it; the probe reads one row + // (BUG-3789: it read every grandchild, with bodies, per child). + probe := params + probe.Limit, probe.Offset = 1, 0 for i := range children { - grandchildren, _ := s.store.GetChildItems(children[i].ID) - children[i].HasChildren = false - for _, gc := range grandchildren { - if !isCollectionVisible(gc.CollectionID, visibleIDs) { - continue - } - if !s.isItemVisibleToGuest(r, workspaceID, &gc, fullCollIDs, grantedItemIDs) { - continue - } - children[i].HasChildren = true - break + grandchildren, err := s.store.ListChildItems(children[i].ID, probe) + if err != nil { + writeInternalError(w, err) + return } + children[i].HasChildren = len(grandchildren) > 0 } } else { s.store.PopulateHasChildren(children) @@ -4565,6 +4557,33 @@ func (s *Server) listItemsPage(w http.ResponseWriter, workspaceID string, params return items, nil } +// parseListWindow reads ?limit= and ?offset= for a bounded list that is not an +// item list (BUG-3789, BUG-3790, BUG-3792), as parseItemListParams reads them +// for the item lists (BUG-3704): a missing, zero, negative or invalid limit is +// the maximum, an explicit one is clamped to it, and a bad offset is 0. +func parseListWindow(r *http.Request) (limit, offset int) { + limit = maxItemListQueryLimit + if l, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && l > 0 && l < limit { + limit = l + } + if o, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && o > 0 { + offset = o + } + return limit, offset +} + +// setListWindowHeaders takes rows read one past limit, trims the probe row and +// sets the paging headers the item lists set (BUG-3704). +func setListWindowHeaders[T any](w http.ResponseWriter, rows []T, limit, offset int) []T { + if len(rows) > limit { + w.Header().Set(itemListHasMoreHeader, "true") + w.Header().Set(itemListNextOffsetHeader, strconv.Itoa(offset+limit)) + return rows[:limit] + } + w.Header().Set(itemListHasMoreHeader, "false") + return rows +} + // maxListFilterKeys bounds the field filters (field filters and any-of // filters together) one list request may carry (BUG-3703). const maxListFilterKeys = 50 diff --git a/internal/server/handlers_share_links.go b/internal/server/handlers_share_links.go index a65f31d43..ef1826a75 100644 --- a/internal/server/handlers_share_links.go +++ b/internal/server/handlers_share_links.go @@ -659,14 +659,22 @@ func (s *Server) handleResolveShareLink(w http.ResponseWriter, r *http.Request) // share page renders items in the order they arrive, because the public // payload carries no sort columns. ListItems' default (pinned, then // updated_at DESC) reshuffled a shared collection on every edit. + // Bounded and paged (BUG-3792): an anonymous reader used to get every + // item with its body in one response. The order ends on the id, so + // offset pages neither repeat nor skip rows. + limit, offset := parseListWindow(r) items, err := s.store.ListItems(link.WorkspaceID, models.ItemListParams{ ScopeCollectionID: coll.ID, Sort: "sort_order:asc,created_at:asc,_id:asc", + Limit: limit + 1, + Offset: offset, }) if err != nil { writeInternalError(w, err) return } + hasMore := len(items) > limit + items = setListWindowHeaders(w, items, limit, offset) // Build public item list with only safe fields. content is the // item's markdown body, included so the public viewer can render an // inline read-only row expand (TASK-1678 / TASK-1684) without a @@ -758,7 +766,11 @@ func (s *Server) handleResolveShareLink(w http.ResponseWriter, r *http.Request) "type": "collection", "collection": publicCollection, "items": publicItems, - "permission": "view", + // The page's place in the list (BUG-3792); the viewer asks again + // with ?offset=next_offset until has_more is false. + "has_more": hasMore, + "next_offset": offset + len(items), + "permission": "view", "share_link": map[string]interface{}{ "target_type": link.TargetType, }, diff --git a/internal/server/handlers_stars.go b/internal/server/handlers_stars.go index 7d99291d4..6f83d9ad6 100644 --- a/internal/server/handlers_stars.go +++ b/internal/server/handlers_stars.go @@ -133,7 +133,7 @@ func (s *Server) handleUnstarItem(w http.ResponseWriter, r *http.Request) { }) } -// handleListStarredItems returns all starred items for the authenticated user in a workspace. +// handleListStarredItems returns one bounded page of the authenticated user's starred items in a workspace (BUG-3790). // GET /api/v1/workspaces/{slug}/starred // Query params: // - include_terminal=true — include items in terminal statuses (default: false) @@ -156,7 +156,8 @@ func (s *Server) handleListStarredItems(w http.ResponseWriter, r *http.Request) includeTerminal := r.URL.Query().Get("include_terminal") == "true" - items, err := s.store.ListStarredItems(userID, workspaceID, includeTerminal) + // Bodies are loaded below for the returned page only (BUG-3790). + items, err := s.store.ListStarredItemsWithoutBodies(userID, workspaceID, includeTerminal) if err != nil { writeInternalError(w, err) return @@ -208,12 +209,33 @@ func (s *Server) handleListStarredItems(w http.ResponseWriter, r *http.Request) } items = filtered + // The list is bounded and paged like the item lists (BUG-3790). The + // window comes after the visibility and terminal filters, which run in Go, + // so has-more counts only rows this caller is served. + limit, offset := parseListWindow(r) + if offset >= len(items) { + items = nil + } else { + items = items[offset:min(len(items), offset+limit+1)] + } + items = setListWindowHeaders(w, items, limit, offset) + // Hydrate items with parent links and computed refs s.enrichItemsWithParent(r, workspaceID, items, visibleIDs) - if r.URL.Query().Get("summary") == "true" { + if r.URL.Query().Get("summary") != "true" { + ids := make([]string, len(items)) for i := range items { - items[i].Content = "" + ids[i] = items[i].ID + } + bodies, err := s.store.ItemBodies(ids) + if err != nil { + writeInternalError(w, err) + return + } + for i := range items { + b := bodies[items[i].ID] + items[i].Content, items[i].ContentState = b.Content, b.ContentState } } diff --git a/internal/store/item_stars.go b/internal/store/item_stars.go index 28ad884fd..a01a0d9cd 100644 --- a/internal/store/item_stars.go +++ b/internal/store/item_stars.go @@ -94,8 +94,25 @@ func (s *Store) AreItemsStarred(userID string, itemIDs []string) (map[string]boo // collection and assignment info. Only non-deleted items are returned. // If includeTerminal is false, items in terminal statuses are excluded. func (s *Store) ListStarredItems(userID, workspaceID string, includeTerminal bool) ([]models.Item, error) { + return s.listStarredItems(userID, workspaceID, includeTerminal, true) +} + +// ListStarredItemsWithoutBodies is ListStarredItems with every body (and its +// content_state) left empty (BUG-3790): the starred door windows the list after +// filtering it, and loads bodies only for the page it returns (ItemBodies). +func (s *Store) ListStarredItemsWithoutBodies(userID, workspaceID string, includeTerminal bool) ([]models.Item, error) { + return s.listStarredItems(userID, workspaceID, includeTerminal, false) +} + +func (s *Store) listStarredItems(userID, workspaceID string, includeTerminal, withBodies bool) ([]models.Item, error) { + // No content_state beside an empty body: it would describe content this + // query does not return (BUG-3000). + bodyCols := "'', ''" + if withBodies { + bodyCols = "i.content, " + contentStateSQL + } query := ` - SELECT i.id, i.workspace_id, i.collection_id, i.title, i.slug, i.content, ` + contentStateSQL + `, i.fields, i.tags, + SELECT i.id, i.workspace_id, i.collection_id, i.title, i.slug, ` + bodyCols + `, i.fields, i.tags, i.pinned, i.sort_order, i.parent_id, i.assigned_user_id, i.agent_role_id, i.role_sort_order, i.created_by, i.last_modified_by, i.source, i.item_number, i.seq, i.created_at, i.updated_at, @@ -110,7 +127,7 @@ func (s *Store) ListStarredItems(userID, workspaceID string, includeTerminal boo WHERE s.user_id = ? AND i.workspace_id = ? AND i.deleted_at IS NULL - ORDER BY s.created_at DESC + ORDER BY s.created_at DESC, i.id ASC ` rows, err := s.db.Query(s.q(query), userID, workspaceID) @@ -234,3 +251,36 @@ func (s *Store) DeleteStarsForItem(itemID string) error { } return nil } + +// ItemBody is one item's body and its content_state. +type ItemBody struct { + Content string + ContentState string +} + +// ItemBodies loads the body and content_state of the given items, keyed by id +// (BUG-3790: a door that windows a body-less list fills in only its page). +func (s *Store) ItemBodies(ids []string) (map[string]ItemBody, error) { + out := make(map[string]ItemBody, len(ids)) + if len(ids) == 0 { + return out, nil + } + args := make([]any, len(ids)) + for i, id := range ids { + args[i] = id + } + rows, err := s.db.Query(s.q(`SELECT i.id, i.content, `+contentStateSQL+` FROM items i WHERE i.id IN (`+placeholders(len(ids))+`)`), args...) + if err != nil { + return nil, fmt.Errorf("item bodies: %w", err) + } + defer rows.Close() + for rows.Next() { + var id string + var b ItemBody + if err := rows.Scan(&id, &b.Content, &b.ContentState); err != nil { + return nil, fmt.Errorf("item bodies: %w", err) + } + out[id] = b + } + return out, rows.Err() +} diff --git a/internal/store/items.go b/internal/store/items.go index ead1adbb6..a43323d98 100644 --- a/internal/store/items.go +++ b/internal/store/items.go @@ -5478,6 +5478,83 @@ func (s *Store) getChildItems(q childQueryer, parentItemID string, includeDelete return scanItems(rows) } +// ChildListParams selects one page of ListChildItems (BUG-3789). +type ChildListParams struct { + // Limit and Offset window the children in their list order. Limit <= 0 + // returns every child: in-process callers (progress, guards) need them + // whole, and only the HTTP door bounds the list. + Limit, Offset int + // CollectionIDs nil means every collection; non-nil restricts to those + // (empty: none). With FullCollectionIDs or GrantedItemIDs non-nil, a child + // must also be a granted item or sit in a full-grant collection, as + // isItemVisibleToGuest decides it. + CollectionIDs []string + FullCollectionIDs []string + GrantedItemIDs []string +} + +// ListChildItems is GetChildItems with the caller's visibility applied in the +// query and an optional window over it (BUG-3789). Visibility is in the +// query, not after it, so a window and its has-more probe count only rows the +// caller may see. The order ends on the id, so offset pages neither repeat +// nor skip children that tie on sort_order and created_at. +func (s *Store) ListChildItems(parentItemID string, p ChildListParams) ([]models.Item, error) { + if p.CollectionIDs != nil && len(p.CollectionIDs) == 0 { + return nil, nil + } + query := ` + SELECT DISTINCT i.id, i.workspace_id, i.collection_id, i.title, i.slug, i.content, ` + contentStateSQL + `, i.fields, i.tags, + i.pinned, i.sort_order, i.parent_id, i.assigned_user_id, i.agent_role_id, i.role_sort_order, + i.created_by, i.last_modified_by, i.source, + i.item_number, i.seq, i.created_at, i.updated_at, + c.slug, c.name, c.icon, c.prefix, + COALESCE(au.name, ''), COALESCE(au.email, ''), + COALESCE(ar.name, ''), COALESCE(ar.slug, ''), COALESCE(ar.icon, ''), i.deleted_at + FROM items i + JOIN collections c ON c.id = i.collection_id + JOIN item_links il ON il.source_id = i.id AND il.link_type IN (` + childLinkTypeSQL() + `) AND il.target_id = ? + LEFT JOIN users au ON au.id = i.assigned_user_id + LEFT JOIN agent_roles ar ON ar.id = i.agent_role_id + WHERE i.deleted_at IS NULL AND c.deleted_at IS NULL` + args := []interface{}{parentItemID} + if p.CollectionIDs != nil { + query += " AND i.collection_id IN (" + placeholders(len(p.CollectionIDs)) + ")" + for _, id := range p.CollectionIDs { + args = append(args, id) + } + if p.FullCollectionIDs != nil || p.GrantedItemIDs != nil { + var alts []string + if len(p.FullCollectionIDs) > 0 { + alts = append(alts, "i.collection_id IN ("+placeholders(len(p.FullCollectionIDs))+")") + for _, id := range p.FullCollectionIDs { + args = append(args, id) + } + } + if len(p.GrantedItemIDs) > 0 { + alts = append(alts, "i.id IN ("+placeholders(len(p.GrantedItemIDs))+")") + for _, id := range p.GrantedItemIDs { + args = append(args, id) + } + } + if len(alts) == 0 { + return nil, nil + } + query += " AND (" + strings.Join(alts, " OR ") + ")" + } + } + query += " ORDER BY i.sort_order ASC, i.created_at ASC, i.id ASC" + if p.Limit > 0 { + query += " LIMIT ? OFFSET ?" + args = append(args, p.Limit, max(p.Offset, 0)) + } + rows, err := s.db.Query(s.q(query), args...) + if err != nil { + return nil, fmt.Errorf("list child items: %w", err) + } + defer rows.Close() + return scanItems(rows) +} + // GetChildItemsForParents returns the live child items for each of the given // parent item IDs, grouped by parent ID, in ONE query — collapsing the // per-parent GetChildItems N+1 the dashboard used to run once per active plan diff --git a/web/src/lib/api/bug3789ListWalks.test.ts b/web/src/lib/api/bug3789ListWalks.test.ts new file mode 100644 index 000000000..50193ba7c --- /dev/null +++ b/web/src/lib/api/bug3789ListWalks.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { api } from './client'; +import { walkOffsetPages } from './listWalk'; +import { walkSharePages, type SharePage } from './shareWalk'; + +// BUG-3789 / BUG-3790 / BUG-3792: the children list, the starred list and a +// shared collection are bounded per page, so the client walks every page. + +const row = (id: string) => ({ id }); +const coll = (items: string[], more: boolean, next?: number, refs?: Record): SharePage => + ({ type: 'collection', collection: { name: 'C' }, items: items.map((ref) => ({ ref, title: ref })), has_more: more, next_offset: next, attachment_refs: refs }) as unknown as SharePage; + +describe('walkOffsetPages', () => { + it('asks page after page until a short page, de-duplicating by id', async () => { + const asked: [number, number][] = []; + const pages = [[row('a'), row('b')], [row('b'), row('c')], [row('d')]]; + const got = await walkOffsetPages(async (limit, offset) => { + asked.push([limit, offset]); + return pages[asked.length - 1]; + }, 2); + expect(asked).toEqual([[2, 0], [2, 2], [2, 4]]); + expect(got.map((r) => r.id)).toEqual(['a', 'b', 'c', 'd']); + }); + + it('an exact multiple costs one empty page', async () => { + const pages = [[row('a'), row('b')], []]; + let n = 0; + const got = await walkOffsetPages(async () => pages[n++], 2); + expect(n).toBe(2); + expect(got).toHaveLength(2); + }); + + it('fails past the page bound', async () => { + let n = 0; + await expect(walkOffsetPages(async () => [row(`r${n++}`), row(`s${n++}`)], 2, 3)).rejects.toThrow('3 pages'); + }); +}); + +describe('walkSharePages', () => { + it('follows next_offset and merges items and attachment refs', async () => { + const asked: number[] = []; + const pages = [coll(['A', 'B'], true, 2, { x: { mime_type: 'image/png', filename: 'x' } }), coll(['C'], false, 3, { y: { mime_type: 'image/png', filename: 'y' } })]; + const got = (await walkSharePages(async (o) => { + asked.push(o); + return pages[asked.length - 1]; + })) as SharePage; + expect(asked).toEqual([0, 2]); + expect(got.items?.map((i) => i.ref)).toEqual(['A', 'B', 'C']); + expect(Object.keys(got.attachment_refs ?? {})).toEqual(['x', 'y']); + expect(got.has_more).toBe(false); + expect(got.next_offset).toBeUndefined(); + }); + + it('an item share, a refusal or an older server is one page', async () => { + for (const first of [{ type: 'item', item: { title: 't' } }, { require_password: true }, { type: 'collection', items: [] }] as SharePage[]) { + let n = 0; + expect(await walkSharePages(async () => (n++, first))).toBe(first); + expect(n).toBe(1); + } + }); + + it('fails past the bound, and on has_more without a usable next_offset', async () => { + await expect(walkSharePages(async (o) => coll([`I${o}`], true, o + 1), 3)).rejects.toThrow('3 pages'); + await expect(walkSharePages(async () => coll(['A'], true, undefined))).rejects.toThrow(); + }); +}); + +// CONVE-19: the API methods the pages call are the walks. +describe('API wiring (BUG-3789 / BUG-3790 / BUG-3792)', () => { + afterEach(() => vi.unstubAllGlobals()); + + function stub(bodies: unknown[]) { + const urls: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + urls.push(String(url)); + return new Response(JSON.stringify(bodies[urls.length - 1]), { status: 200, headers: { 'Content-Type': 'application/json' } }); + }) + ); + return urls; + } + const full = (p: string) => Array.from({ length: 1000 }, (_, i) => row(`${p}${i}`)); + const tail = (u: string) => u.slice(u.indexOf('/workspaces/') >= 0 ? u.indexOf('/workspaces/') : u.indexOf('/s/')); + + it('children walks by offset', async () => { + const urls = stub([full('c'), [row('last')]]); + const got = await api.items.children('ws', 'p'); + expect(got).toHaveLength(1001); + expect(urls.map(tail)).toEqual(['/workspaces/ws/items/p/children?limit=1000&offset=0', '/workspaces/ws/items/p/children?limit=1000&offset=1000']); + }); + + it('starred walks by offset and keeps its params', async () => { + const urls = stub([full('s'), []]); + await api.items.starred('ws', { include_terminal: true, summary: true }); + expect(urls.map(tail)).toEqual([ + '/workspaces/ws/starred?include_terminal=true&summary=true&limit=1000&offset=0', + '/workspaces/ws/starred?include_terminal=true&summary=true&limit=1000&offset=1000' + ]); + }); + + it('share.get walks a shared collection', async () => { + const urls = stub([coll(['A'], true, 1000), coll(['B'], false, 1001)]); + const got = await api.share.get('tok'); + expect(got.items?.map((i) => i.ref)).toEqual(['A', 'B']); + expect(urls.map(tail)).toEqual(['/s/tok', '/s/tok?offset=1000']); + }); +}); diff --git a/web/src/lib/api/client.ts b/web/src/lib/api/client.ts index daaff51fb..95b4651d6 100644 --- a/web/src/lib/api/client.ts +++ b/web/src/lib/api/client.ts @@ -111,6 +111,8 @@ import { runSessionExpiryKeepers } from '$lib/stores/sessionExpiryKeep'; import { reportWorkspaceWrite } from './workspaceWrites'; import { noteServerDate } from './serverClock'; import { walkChanges, type ChangesPageQuery } from './changesWalk'; +import { walkSharePages, type SharePage } from './shareWalk'; +import { walkOffsetPages } from './listWalk'; import { uploadImportBundle } from './importUpload'; import { reserveKeepalive } from './keepaliveBudget'; @@ -2220,17 +2222,19 @@ export const api = { })}` ), - /** Get child items linked to a parent item */ + /** Get EVERY child item linked to a parent item, walking the bounded + * pages (BUG-3789). */ children: (ws: string, slug: string) => - request(`/workspaces/${ws}/items/${slug}/children`), + walkOffsetPages((limit, offset) => + request(`/workspaces/${ws}/items/${slug}/children${qs({ limit, offset })}`) + ), /** Get completion progress for an item's children */ progress: (ws: string, slug: string) => request<{total: number; done: number; percentage: number}>(`/workspaces/${ws}/items/${slug}/progress`), /** @deprecated Use children() */ - tasks: (ws: string, slug: string) => - request(`/workspaces/${ws}/items/${slug}/children`), + tasks: (ws: string, slug: string) => api.items.children(ws, slug), /** @deprecated Use progress() per-item instead */ plansProgress: (ws: string) => @@ -2308,7 +2312,9 @@ export const api = { /** List all starred items in a workspace for the current user, most * recently starred first. `summary` leaves out each body (TASK-2231). */ starred: (ws: string, params?: {include_terminal?: boolean; summary?: boolean}) => - request(`/workspaces/${ws}/starred${qs(params)}`), + walkOffsetPages((limit, offset) => + request(`/workspaces/${ws}/starred${qs({ ...params, limit, offset })}`) + ), /** * Push an instruction about this item to the caller's OWN agent @@ -2925,19 +2931,24 @@ export const api = { // ── Public Share (no auth) ────────────────────────────────────────────── share: { - get: (token: string, password?: string): Promise => { + /** A shared item, or EVERY page of a shared collection (BUG-3792). */ + get: (token: string, password?: string): Promise => + walkSharePages((offset) => api.share.page(token, password, offset)), + /** One page of a share link; a collection's items start at `offset`. */ + page: (token: string, password?: string, offset = 0): Promise => { const headers: Record = {}; if (password) headers['X-Share-Password'] = password; + const qs = offset > 0 ? `?offset=${offset}` : ''; // Under the API deadline (BUG-3216). A GET, so a timeout is idempotent. return withRequestDeadline( async (signal) => { - const resp = await fetch(`${BASE}/s/${token}`, { credentials: 'same-origin', headers, signal }); + const resp = await fetch(`${BASE}/s/${token}${qs}`, { credentials: 'same-origin', headers, signal }); if (!resp.ok) { const body = await resp.json().catch(() => null); if (body?.error) throw new PadApiError(body.error); throw new Error(`API error: ${resp.status}`); } - return (await resp.json()) as SharePayload; + return (await resp.json()) as SharePage; }, { idempotent: true } ); diff --git a/web/src/lib/api/listWalk.ts b/web/src/lib/api/listWalk.ts new file mode 100644 index 000000000..8ce2f3017 --- /dev/null +++ b/web/src/lib/api/listWalk.ts @@ -0,0 +1,32 @@ +/** The server's page ceiling for bounded lists (BUG-3704, BUG-3789). */ +export const LIST_PAGE_SIZE = 1000; + +/** The most pages one list walk follows before failing (50,000 rows). */ +export const MAX_LIST_PAGES = 50; + +/** + * Pull every page of a bounded bare-array list by offset (BUG-3789, BUG-3790). + * The body carries no paging state, and `request` does not expose the + * has-more headers, so a page shorter than the size asked for is the last; + * a list of exactly a multiple of the size costs one empty request. Rows are + * de-duplicated by id, first occurrence kept, since a row that moves between + * requests can come back in a later page. + */ +export async function walkOffsetPages( + fetchPage: (limit: number, offset: number) => Promise, + pageSize = LIST_PAGE_SIZE, + maxPages = MAX_LIST_PAGES +): Promise { + const out: T[] = []; + const seen = new Set(); + for (let page = 0; page < maxPages; page++) { + const rows = await fetchPage(pageSize, page * pageSize); + for (const row of rows) { + if (seen.has(row.id)) continue; + seen.add(row.id); + out.push(row); + } + if (rows.length < pageSize) return out; + } + throw new Error(`list did not finish within ${maxPages} pages`); +} diff --git a/web/src/lib/api/shareWalk.ts b/web/src/lib/api/shareWalk.ts new file mode 100644 index 000000000..ce3def11f --- /dev/null +++ b/web/src/lib/api/shareWalk.ts @@ -0,0 +1,43 @@ +import type { SharePayload } from '$lib/types'; + +/** + * The most pages one shared-collection load follows (BUG-3792). At the + * server's 1000-item page that is 50,000 items; past it the load fails rather + * than rendering a collection with items silently missing. + */ +export const MAX_SHARE_PAGES = 50; + +/** A shared collection's page: SharePayload plus its place in the list. */ +export type SharePage = SharePayload & { has_more?: boolean; next_offset?: number }; + +/** + * Load every page of a shared collection and merge them (BUG-3792). The + * server bounds each page and says `has_more` with the `next_offset` to ask + * for; items arrive in the owner's order, so pages are appended. Attachment + * refs are minted per page and merged. A single-item share, a refusal + * (require_auth / require_password) or an older server without `has_more` is + * one page. + */ +export async function walkSharePages( + fetchPage: (offset: number) => Promise, + maxPages = MAX_SHARE_PAGES +): Promise { + const first = await fetchPage(0); + if (first.type !== 'collection' || !first.has_more) return first; + const items = [...(first.items ?? [])]; + const refs = { ...(first.attachment_refs ?? {}) }; + let page = first; + for (let n = 1; page.has_more; n++) { + const next = page.next_offset; + if (n >= maxPages || typeof next !== 'number' || next <= 0) { + throw new Error(`shared collection did not finish within ${maxPages} pages`); + } + page = await fetchPage(next); + items.push(...(page.items ?? [])); + Object.assign(refs, page.attachment_refs ?? {}); + } + const merged: SharePage = { ...first, items, has_more: false }; + delete merged.next_offset; + if (Object.keys(refs).length > 0) merged.attachment_refs = refs; + return merged; +} diff --git a/web/src/routes/s/[token]/+page.svelte b/web/src/routes/s/[token]/+page.svelte index b91f009c3..2e9012792 100644 --- a/web/src/routes/s/[token]/+page.svelte +++ b/web/src/routes/s/[token]/+page.svelte @@ -2,7 +2,7 @@ import { safeText } from '$lib/fields/fieldShape'; import { page } from '$app/state'; import { onMount } from 'svelte'; - import { api, withRequestDeadline } from '$lib/api/client'; + import { api, PadApiError } from '$lib/api/client'; import { authStore } from '$lib/stores/auth.svelte'; import { renderMarkedWithAttachments, sanitizeMarkdownHtml } from '$lib/utils/markdown'; import { renderAttachmentUnavailable } from '$lib/markdown/attachments'; @@ -501,21 +501,18 @@ passwordError = ''; passwordLoading = true; try { - // Under the API deadline (BUG-3216): `passwordLoading` is held across it. - const { resp, data } = await withRequestDeadline( - async (signal) => { - const resp = await fetch(`/api/v1/s/${token}`, { - credentials: 'same-origin', - headers: { 'X-Share-Password': passwordInput }, - signal - }); - return { resp, data: await resp.json() }; - }, - { idempotent: true } - ); - if (!resp.ok) { - passwordError = data?.error?.message ?? 'Incorrect password'; - return; + // Through the share loader, so a collection past one page arrives + // whole (BUG-3792, Codex r1); each page is under the API deadline + // (BUG-3216), and `passwordLoading` is held across them. + let data: SharePayload; + try { + data = await api.share.get(token, passwordInput); + } catch (e: any) { + if (e instanceof PadApiError) { + passwordError = e.message || 'Incorrect password'; + return; + } + throw e; } if (data.require_password) { passwordError = 'Incorrect password'; diff --git a/web/src/routes/s/[token]/bug3792SharePassword.svelte.test.ts b/web/src/routes/s/[token]/bug3792SharePassword.svelte.test.ts new file mode 100644 index 000000000..e54f5e325 --- /dev/null +++ b/web/src/routes/s/[token]/bug3792SharePassword.svelte.test.ts @@ -0,0 +1,52 @@ +// BUG-3792 (Codex r1 Medium): a password-protected share's retry goes through +// api.share.get, the loader that walks every page of a shared collection. It +// used to fetch the first page by hand, so a protected collection past one page +// rendered incomplete. +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render } from '@testing-library/svelte'; + +const share = vi.hoisted(() => ({ calls: [] as unknown[][] })); + +vi.mock('$lib/api/client', () => { + class PadApiError extends Error {} + return { + PadApiError, + withRequestDeadline: vi.fn(), + api: { + share: { + get: vi.fn(async (...args: unknown[]) => { + share.calls.push(args); + if (args[1] === undefined) return { require_password: true }; + return { type: 'collection', collection: { name: 'Protected' }, items: [{ ref: 'TASK-1', title: 'One' }] }; + }) + } + } + }; +}); + +import { page } from '$app/state'; +import SharePage from './+page.svelte'; + +async function settle() { + for (let i = 0; i < 20; i++) await Promise.resolve(); +} + +afterEach(() => { + cleanup(); + share.calls = []; +}); + +describe('share page: the password retry walks the share through api.share.get (BUG-3792)', () => { + it('submits the password to the paged loader', async () => { + page.params = { token: 'tok' }; + const { container } = render(SharePage); + await settle(); + const input = container.querySelector('form.password-form input') as HTMLInputElement; + expect(input, 'the password form did not render').not.toBeNull(); + await fireEvent.input(input, { target: { value: 'pw' } }); + await fireEvent.submit(container.querySelector('form.password-form')!); + await settle(); + expect(share.calls).toEqual([['tok'], ['tok', 'pw']]); + expect(container.querySelector('form.password-form')).toBeNull(); + }); +});