From 15c9f76366fc03bfbb03c8ddaff432cdaf4789c5 Mon Sep 17 00:00:00 2001 From: xarmian Date: Thu, 8 Oct 2026 03:59:26 -0400 Subject: [PATCH] feat: archived collections can be listed, restored and undone; the archive confirm shows the count (TASK-2189) (#1874) * feat: archived collections can be listed and restored (TASK-2189, server, CLI, MCP v0.72) Claude-Session: https://claude.ai/code/session_01Q9WssCjFuHjSfLABoW4tmS * feat(web): archive shows the item count, guards big collections, and can be undone or restored (TASK-2189) Claude-Session: https://claude.ai/code/session_01Q9WssCjFuHjSfLABoW4tmS * fix: list-archived is read-only, an unknown count needs typing, instructions say v0.72; store tests on both dialects incl. a restore race (TASK-2189) codex r1. Claude-Session: https://claude.ai/code/session_01Q9WssCjFuHjSfLABoW4tmS * test: README tool-surface version 0.72; classify the archive Undo's restore continuations (TASK-2189) Claude-Session: https://claude.ai/code/session_01Q9WssCjFuHjSfLABoW4tmS --- CLAUDE.md | 9 +- README.md | 6 +- cmd/pad/cmd_collection.go | 66 ++++++- cmd/pad/groups.go | 2 + .../testdata/mcp_wire/remote_initialize.json | 4 +- .../testdata/mcp_wire/remote_tools_list.json | 6 +- .../testdata/mcp_wire/stdio_initialize.json | 4 +- .../testdata/mcp_wire/stdio_tools_list.json | 6 +- internal/cli/client.go | 17 ++ internal/mcp/catalog_collection.go | 31 ++-- internal/mcp/catalog_readonly_test.go | 12 ++ internal/mcp/chatgpt_catalog.go | 96 +++++----- internal/mcp/dispatch_http_routes.go | 9 + internal/mcp/instructions.md | 4 +- internal/mcp/tool_surface.go | 2 + internal/mcp/version.go | 11 +- internal/models/collection.go | 13 ++ internal/server/handlers_collections.go | 90 +++++++++ internal/server/server.go | 7 + .../task2189_collection_restore_test.go | 171 ++++++++++++++++++ internal/store/collections_archive.go | 76 ++++++++ internal/store/collections_archive_test.go | 94 ++++++++++ web/src/lib/api/client.ts | 12 +- .../collections/ArchivedCollections.svelte | 141 +++++++++++++++ .../collections/EditCollectionModal.svelte | 73 +++++++- .../collections/archiveRestore.svelte.test.ts | 169 +++++++++++++++++ .../childIdentityFencePopulation.test.ts | 8 + web/src/lib/types/index.ts | 15 ++ .../[workspace]/settings/+page.svelte | 8 + 29 files changed, 1072 insertions(+), 90 deletions(-) create mode 100644 internal/server/task2189_collection_restore_test.go create mode 100644 internal/store/collections_archive.go create mode 100644 internal/store/collections_archive_test.go create mode 100644 web/src/lib/components/collections/ArchivedCollections.svelte create mode 100644 web/src/lib/components/collections/archiveRestore.svelte.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 05b125a34..6e97f92ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,7 +80,8 @@ skills/pad/SKILL.md — Claude Code skill (embedded in binary) REST API at `/api/v1/`. Key endpoints: - **A workspace that does not resolve for the caller answers `404 not_found` with `details: {"scope": "workspace"}`** (BUG-3069) — a non-member and a deleted workspace alike, so it is not an existence oracle. A 404 about something INSIDE a workspace the caller can read (an item, a collection, a guest's ungranted item) carries no such marker. Code, status and message are unchanged from before the marker, so a consumer keyed on `not_found` is unaffected; key on `details.scope` to tell the two apart. A workspace addressed by UUID that the caller is not a member of answers `403 forbidden` instead, a separate refusal -- `GET/POST /workspaces/{ws}/collections` — collection CRUD +- `GET/POST /workspaces/{ws}/collections` — collection CRUD. `DELETE /collections/{slug}` ARCHIVES: a soft delete of the collection row, its items untouched and only hidden with it; nothing purges an archived collection (TASK-2189) +- `GET /workspaces/{ws}/archived-collections`, `POST /workspaces/{ws}/archived-collections/{ref}/restore` — list archived collections (id, name, slug, prefix, icon, live `item_count`, `archived_at`) and restore one by id or slug, its items with it (TASK-2189). Owner-only, like the archive. A restore cannot collide: slugs are allocated unique across archived rows too, so a newer same-named collection took `x-2`. 404 for a ref that is not an archived collection of this workspace. The restore publishes `collection_updated`, and the item-sync epoch fingerprints the live collection set, so delta clients resync and receive the restored items. CLI: `pad collection archived` / `pad collection restore `; MCP `pad_collection` `list-archived` / `restore` (v0.72) - `GET/POST /workspaces/{ws}/collections/{coll}/items` — item CRUD - **Field filters on the list:** any query parameter that is not a known list parameter filters on that field. A value containing a comma is an OR over its trimmed pieces (`?status=open,done`, which is what `pad item list --status open,done` sends). **Documented limit (BUG-3167):** over the query string, a literal value that itself contains a comma cannot be filtered for exactly, because the comma is the delimiter. A repeated-parameter form was declined, because an older server reads only the first value and silently narrows the result. The census when this was written found 0 comma-containing option values (2,025 select/multi_select options across 27 workspaces). In-process callers are unaffected: `store.ListItems` matches `ItemListParams.Fields` EXACTLY and takes an OR only through `FieldsAnyOf`, so the uniqueness check, playbook routing, and schema-driven completed-work and bootstrap queries match a comma value as itself - `GET/PATCH/DELETE /workspaces/{ws}/items/{slug}` — item by slug @@ -344,7 +345,7 @@ Collection names accept singular forms: `task`→`tasks`, `idea`→`ideas`, `doc ## MCP server -Pad runs as a local Model Context Protocol server so Claude Desktop / Cursor / Windsurf can call non-interactive `pad` commands as tools. The same catalog is also served as remote MCP over HTTP at `/mcp` (Streamable HTTP): always on Pad Cloud, and on a self-hosted install off by default until an admin turns it on (`GET/PUT /api/v1/admin/mcp` above; OAuth plus PATs when the issuer URL is https, PATs only on http; operator docs in `docs/deployment.md`). The tool surface is a **hand-curated catalog** (currently v0.71) in `internal/mcp/catalog_*.go` — one ToolDef per resource (`pad_item`, `pad_workspace`, `pad_collection`, `pad_project`, `pad_role`, `pad_search`, `pad_meta`, `pad_playbook`, `pad_library`, `pad_attachment`) with an `action` enum dispatching to underlying CLI commands. v0.33 (PLAN-2857 U4 / TASK-2999) adds a **`multi_relation`** field type — an ORDERED LIST of references, each element resolving through the same UUID→ref→exact-title ladder a scalar `relation` uses, declared through the DSL as `owners:multi_relation:people` (third part = target collection; a bare `owners:multi_relation` is refused at parse time rather than minting a field no write can satisfy). The TYPE is additive — every rule is reachable only through a field whose schema says `multi_relation`, which no existing schema can contain — so the bump is owed by the READ shape: `relation_targets[key]` now carries EITHER the scalar object v0.31 emitted OR a JSON **ARRAY** of those objects, in stored order and one per stored element (an `id`-only entry for an element that names nothing, so a position lines up with the same position in `fields`). A scalar entry is byte-identical to v0.31's — pinned against a literal, not against another call into the same code — so a consumer with no such fields sees nothing new, while one that acquires such a field must handle the array. ONE map, not a parallel `multi_relation_targets` key: the field's type already says which shape to expect. Value rules, all NEW rather than inherited because scalar `relation` had nothing coherent to inherit (see BUG-3028 — a required scalar relation WAS satisfied by `""`, with three stored spellings of "no target", until v0.40 converged it on this same key-absent rule): exactly ONE stored form for none, the key ABSENT, with `[]` normalising to it at the write door; an empty or whitespace-only ELEMENT REFUSED rather than skipped, naming its index; `required` meaning >=1 RESOLVED element; order part of the value; duplicates REFUSED with a new `duplicate_referent` reason, detected AFTER resolution because two elements naming one item are usually different strings. Any failing element refuses the WHOLE write — never a partial list — and a cross-workspace copy drops the value whole, reported once, so an import can never change an element count. **0.32 is RESERVED for PR #1337**, which claims it and was opened first; this unit took 0.33 rather than contest the number, so 0.32 may be skipped if #1337 is abandoned — a gap is cheaper than a collision resolved under merge pressure. v0.31 (PLAN-2857 U6 / TASK-2996) lets a `relation` value be an EXACT TITLE, scoped to the collection that field declares, alongside the UUID and ref v0.29 accepted; adds a `relation_targets` member to reads hydrating each stored id to `{id, ref, title}`; and makes the `fields` DSL take the target collection slug as a relation's third part. The first two are additive — a title is a THIRD spelling, and `relation_targets` is `omitempty` — so the bump is owed by the DSL: `fields="owner:relation"` used to be ACCEPTED and is now REFUSED, because the old parser put the third part into `Options` for every type and therefore built a relation with NO target, a field every subsequent write refused with `target_missing`. Scoping is the point: a title unique only workspace-wide refuses and names the collection searched, and two matches inside the declared collection get their own `ambiguous` reason rather than `not_found`, which would state the opposite of what happened. The ladder is UUID, then ref, then title, so an item literally TITLED `COLO-3` is unreachable by title while the ref resolves. An id-only `relation_targets` entry means the target is GONE **or** the caller may not SEE it — the two are made indistinguishable deliberately, matching the write side's `wrong_collection`→`not_found` collapse, so no consumer may render it as either. v0.30 (BUG-2870) makes one `--field key=value` entry mean ONE thing at every door. Six sites parsed that entry independently — `item create`, `item list`, `item update`, `item move` and `item copy` in `cmd/pad`, plus `ingestFieldKVP` on the remote door — in four spellings, so `field:[" effort=l"]` stored an undeclared field literally named `" effort"` through the CLI while the remote door trimmed and wrote `effort`: the same call storing two different keys, decided by the transport. All six now call `items.SplitFieldEntry`, under two deliberately asymmetric rules — a padded KEY is REFUSED everywhere (trimming silently retargets the write to a field the caller did not type), a VALUE is carried VERBATIM everywhere (trimming reinterprets a caller's bytes, and on a text field the padding is content). The catalog's conflict pass is re-grounded on the same change, since its rules were derived from that trimming: comparisons are RAW, a padded entry is refused in the pass rather than skipped, `parseFieldArray`'s refusal is PROPAGATED rather than swallowed (it had no second owner on the no-`fields` path, where four existing refusals were landing as successes), and canonicalization and the re-emission path are gone — nothing rewrites a caller's key any more. v0.29 (PLAN-2857 / TASK-2878) makes a `relation` field value have to NAME A LIVE ITEM in the collection that field declares. `internal/items` only ever checked the SHAPE of a relation ("must be a string") because that package is DB-free, so any string at all was accepted and stored and no client could render it honestly. Every write door now refuses a value that names nothing, names an item in the WRONG collection, sits in a field declaring no target collection, or is a SLUG (deliberate divergence from `ResolveItem` — a slug is neither an ID nor stable). A CARRIED value, already on the item and asserted by nobody, is never refused: within a workspace it resolves and survives; across a boundary it is dropped without a lookup and reported in `warnings.dropped_fields`. v0.28 (IDEA-2641) adds two ADDITIVE `pad_item` actions — `remind` (arm a one-shot reminder at an RFC3339 `remind_at` instant) and `ack-reminder` (acknowledge a fired one by `reminder_id`). Agents already RECEIVED reminders, since the poll surface is `pad_project.next` / `ready`; what was missing is the other half — deferring work is exactly when an agent knows it wants to be asked again. A bare date is refused rather than read as midnight. Re-arm and disarm stay CLI-only until a listing action exists to discover an id. v0.27 (BUG-2850) typed field values server-side, carried the `fields` object with its JSON types intact, named undeclared keys back in `warnings.undeclared_fields`, and replaced the per-site conflict guards with one check that refuses two names for one target in a single call. v0.26 (IDEA-2756) makes `pad_workspace.create` REFUSE with a 403 when the calling OAuth connection's grant carries `may_create_workspaces=false` — that consent checkbox previously gated only the post-creation auto-add, so a connection whose user declined it created workspaces anyway — invisible to it when the connection carried an explicit allow-list, visible when it carried the `all_current_workspaces` wildcard; the consent mismatch is the defect in both cases. The same gate covers `POST /workspaces/import` (a second door onto `store.ImportWorkspace` → `CreateWorkspace`, with no MCP action today). No escape-hatch param, deliberately: the gate expresses the USER's consent decision, so only the user can lift it — by re-authorizing, or by enabling the flag on the existing connection at `/console/connected-apps`. v0.25 (TASK-2657 / BUG-2702) makes `pad_library.activate` resolve its destination collection from the target's declared artifact kind rather than the literal `conventions` / `playbooks` slugs, and surfaces a lookup ERROR instead of falling back. v0.24 (#1066) makes the `pad_item` `fields` OBJECT a real write form on create/update — reads return `fields` as a native object (BUG-991 normalization), and writing that shape back was a silent no-op: not a declared param, no `additionalProperties`, so it was accepted, never mapped by `BuildCLIArgs`, and dropped while the PATCH still bumped `updated_at`. The alias merges into the same path as `field: ["key=value"]` / the dedicated params (`catalog_item_fields.go`), refusing the same key in two places with conflicting values; and input validation is now STRICT across all catalog tools — an undeclared top-level key fails with a structured `validation_failed` naming it, instead of being silently dropped (a small documented compat list survives: pad_item's v0.16 `assigned_user_id` / `agent_role_id` remote clear form). One bump covers both halves — they are one contract change. v0.23 (BUG-2627 part 2 + BUG-2675, PR #1166) refuses raw `field` setters naming system-metadata keys in `fields_patch` on every transport (`github_pr` exempt on UPDATE only — the sole remote writer, itself broken — until v0.47 closed it: BUG-2696) and adds the retry-hostile `stored_state_unreadable` error code. v0.22 (BUG-2674, PR #1165) makes reserved metadata survive a move and refuses `field` setters naming those keys on move/copy — see `internal/mcp/version.go` for both full entries. v0.21 (BUG-2608) bounds `pad_item.action=history`, which was unbounded on every surface: the `limit` param now covers it (default 50, max 300 — the NEWEST N versions, with no `offset`, because reverse-patch storage makes only a newest-end window cheap to reconstruct), applied in the CATALOG action so it lands on both transports, and summary mode now asks the server to skip patch resolution (`?summary=true`) instead of resolving every body and discarding it. Additive param bump — `limit` already existed and nothing changed shape. v0.20 (BUG-2302 + BUG-2305, one bump) adds explicit MCP tool annotations (`readOnlyHint`/`destructiveHint`/`idempotentHint` derived from the catalog's own write-shape knowledge, fixing read-only tools that advertised `destructiveHint:true`) and makes `pad_item.list` summary-shaped on the REMOTE /mcp transport too (the hand-written `dispatchItemList` projects via `cli.ToItemSummaries`; `full=true` opts back into complete bodies) — see `internal/mcp/version.go` for the authoritative per-version changelog. Post-0.20 without a bump (BUG-2304): `item backlinks` / `item history` / `project report` gained HTTP route coverage — they were advertised but answered "not yet implemented over HTTP transport" — and a catalog↔route parity test (`dispatch_http_parity_test.go`) now drives every catalog action and fails on any future advertised-but-unrouted action; no names, enums, or shapes changed, hence no bump. v0.19 adds a `clear_parent` boolean to `pad_item` — the canonical, schema-discoverable way to detach an item from its parent, backed by a new `--clear-parent` bareword flag on `pad item update` (BUG-2078). v0.18 adds `clear_assigned_user` / `clear_agent_role` booleans to `pad_item` — the canonical, schema-discoverable way to unassign, backed by new `--clear-assigned-user` / `--clear-agent-role` bareword flags on `pad item update` (IDEA-2584). Update-only, deliberately asymmetric with create. v0.17 carries the empty-string clear to the LOCAL STDIO transport, which shells out to the CLI — `cmd/pad/cmd_item.go` now lifts `assigned_user_id` / `agent_role_id` onto their columns instead of into the fields blob, on create and update (BUG-2583). v0.16 makes an empty-string `assigned_user_id` / `agent_role_id` CLEAR the assignment instead of being silently dropped, so an MCP agent can finally unassign an item (TASK-2571). v0.15 adds the `pad_item.list` `unparented` boolean, mutually exclusive with `parent`, for items with no parent or implements relationship (TASK-2096). v0.2 introduced the catalog (PLAN-969 / TASK-981); v0.3 added `pad_playbook`, `pad_meta.action: bootstrap`, `pad_set_workspace`'s embedded-bootstrap response, and the `pad://workspace/{ws}/bootstrap` resource (PLAN-1377 / TASK-1380); v0.4 trimmed the bootstrap payload by ~40% (PLAN-1410) — slim `BootstrapCollection` + `BootstrapRole` projections (no UUIDs/timestamps/settings; nested `schema` object; redundant labels omitted), removed top-level `recent_activity` duplicate, dropped convention `slug`, and added a `BootstrapDashboard` wrapper that caps five sub-arrays (`attention`, `recent_activity`, `active_items`, `active_plans`, `by_role`) at 5 entries each with parallel `*_overflow_count` fields. The pre-catalog v0.1 cmdhelp leaf walker is retired. +Pad runs as a local Model Context Protocol server so Claude Desktop / Cursor / Windsurf can call non-interactive `pad` commands as tools. The same catalog is also served as remote MCP over HTTP at `/mcp` (Streamable HTTP): always on Pad Cloud, and on a self-hosted install off by default until an admin turns it on (`GET/PUT /api/v1/admin/mcp` above; OAuth plus PATs when the issuer URL is https, PATs only on http; operator docs in `docs/deployment.md`). The tool surface is a **hand-curated catalog** (currently v0.72) in `internal/mcp/catalog_*.go` — one ToolDef per resource (`pad_item`, `pad_workspace`, `pad_collection`, `pad_project`, `pad_role`, `pad_search`, `pad_meta`, `pad_playbook`, `pad_library`, `pad_attachment`) with an `action` enum dispatching to underlying CLI commands. v0.33 (PLAN-2857 U4 / TASK-2999) adds a **`multi_relation`** field type — an ORDERED LIST of references, each element resolving through the same UUID→ref→exact-title ladder a scalar `relation` uses, declared through the DSL as `owners:multi_relation:people` (third part = target collection; a bare `owners:multi_relation` is refused at parse time rather than minting a field no write can satisfy). The TYPE is additive — every rule is reachable only through a field whose schema says `multi_relation`, which no existing schema can contain — so the bump is owed by the READ shape: `relation_targets[key]` now carries EITHER the scalar object v0.31 emitted OR a JSON **ARRAY** of those objects, in stored order and one per stored element (an `id`-only entry for an element that names nothing, so a position lines up with the same position in `fields`). A scalar entry is byte-identical to v0.31's — pinned against a literal, not against another call into the same code — so a consumer with no such fields sees nothing new, while one that acquires such a field must handle the array. ONE map, not a parallel `multi_relation_targets` key: the field's type already says which shape to expect. Value rules, all NEW rather than inherited because scalar `relation` had nothing coherent to inherit (see BUG-3028 — a required scalar relation WAS satisfied by `""`, with three stored spellings of "no target", until v0.40 converged it on this same key-absent rule): exactly ONE stored form for none, the key ABSENT, with `[]` normalising to it at the write door; an empty or whitespace-only ELEMENT REFUSED rather than skipped, naming its index; `required` meaning >=1 RESOLVED element; order part of the value; duplicates REFUSED with a new `duplicate_referent` reason, detected AFTER resolution because two elements naming one item are usually different strings. Any failing element refuses the WHOLE write — never a partial list — and a cross-workspace copy drops the value whole, reported once, so an import can never change an element count. **0.32 is RESERVED for PR #1337**, which claims it and was opened first; this unit took 0.33 rather than contest the number, so 0.32 may be skipped if #1337 is abandoned — a gap is cheaper than a collision resolved under merge pressure. v0.31 (PLAN-2857 U6 / TASK-2996) lets a `relation` value be an EXACT TITLE, scoped to the collection that field declares, alongside the UUID and ref v0.29 accepted; adds a `relation_targets` member to reads hydrating each stored id to `{id, ref, title}`; and makes the `fields` DSL take the target collection slug as a relation's third part. The first two are additive — a title is a THIRD spelling, and `relation_targets` is `omitempty` — so the bump is owed by the DSL: `fields="owner:relation"` used to be ACCEPTED and is now REFUSED, because the old parser put the third part into `Options` for every type and therefore built a relation with NO target, a field every subsequent write refused with `target_missing`. Scoping is the point: a title unique only workspace-wide refuses and names the collection searched, and two matches inside the declared collection get their own `ambiguous` reason rather than `not_found`, which would state the opposite of what happened. The ladder is UUID, then ref, then title, so an item literally TITLED `COLO-3` is unreachable by title while the ref resolves. An id-only `relation_targets` entry means the target is GONE **or** the caller may not SEE it — the two are made indistinguishable deliberately, matching the write side's `wrong_collection`→`not_found` collapse, so no consumer may render it as either. v0.30 (BUG-2870) makes one `--field key=value` entry mean ONE thing at every door. Six sites parsed that entry independently — `item create`, `item list`, `item update`, `item move` and `item copy` in `cmd/pad`, plus `ingestFieldKVP` on the remote door — in four spellings, so `field:[" effort=l"]` stored an undeclared field literally named `" effort"` through the CLI while the remote door trimmed and wrote `effort`: the same call storing two different keys, decided by the transport. All six now call `items.SplitFieldEntry`, under two deliberately asymmetric rules — a padded KEY is REFUSED everywhere (trimming silently retargets the write to a field the caller did not type), a VALUE is carried VERBATIM everywhere (trimming reinterprets a caller's bytes, and on a text field the padding is content). The catalog's conflict pass is re-grounded on the same change, since its rules were derived from that trimming: comparisons are RAW, a padded entry is refused in the pass rather than skipped, `parseFieldArray`'s refusal is PROPAGATED rather than swallowed (it had no second owner on the no-`fields` path, where four existing refusals were landing as successes), and canonicalization and the re-emission path are gone — nothing rewrites a caller's key any more. v0.29 (PLAN-2857 / TASK-2878) makes a `relation` field value have to NAME A LIVE ITEM in the collection that field declares. `internal/items` only ever checked the SHAPE of a relation ("must be a string") because that package is DB-free, so any string at all was accepted and stored and no client could render it honestly. Every write door now refuses a value that names nothing, names an item in the WRONG collection, sits in a field declaring no target collection, or is a SLUG (deliberate divergence from `ResolveItem` — a slug is neither an ID nor stable). A CARRIED value, already on the item and asserted by nobody, is never refused: within a workspace it resolves and survives; across a boundary it is dropped without a lookup and reported in `warnings.dropped_fields`. v0.28 (IDEA-2641) adds two ADDITIVE `pad_item` actions — `remind` (arm a one-shot reminder at an RFC3339 `remind_at` instant) and `ack-reminder` (acknowledge a fired one by `reminder_id`). Agents already RECEIVED reminders, since the poll surface is `pad_project.next` / `ready`; what was missing is the other half — deferring work is exactly when an agent knows it wants to be asked again. A bare date is refused rather than read as midnight. Re-arm and disarm stay CLI-only until a listing action exists to discover an id. v0.27 (BUG-2850) typed field values server-side, carried the `fields` object with its JSON types intact, named undeclared keys back in `warnings.undeclared_fields`, and replaced the per-site conflict guards with one check that refuses two names for one target in a single call. v0.26 (IDEA-2756) makes `pad_workspace.create` REFUSE with a 403 when the calling OAuth connection's grant carries `may_create_workspaces=false` — that consent checkbox previously gated only the post-creation auto-add, so a connection whose user declined it created workspaces anyway — invisible to it when the connection carried an explicit allow-list, visible when it carried the `all_current_workspaces` wildcard; the consent mismatch is the defect in both cases. The same gate covers `POST /workspaces/import` (a second door onto `store.ImportWorkspace` → `CreateWorkspace`, with no MCP action today). No escape-hatch param, deliberately: the gate expresses the USER's consent decision, so only the user can lift it — by re-authorizing, or by enabling the flag on the existing connection at `/console/connected-apps`. v0.25 (TASK-2657 / BUG-2702) makes `pad_library.activate` resolve its destination collection from the target's declared artifact kind rather than the literal `conventions` / `playbooks` slugs, and surfaces a lookup ERROR instead of falling back. v0.24 (#1066) makes the `pad_item` `fields` OBJECT a real write form on create/update — reads return `fields` as a native object (BUG-991 normalization), and writing that shape back was a silent no-op: not a declared param, no `additionalProperties`, so it was accepted, never mapped by `BuildCLIArgs`, and dropped while the PATCH still bumped `updated_at`. The alias merges into the same path as `field: ["key=value"]` / the dedicated params (`catalog_item_fields.go`), refusing the same key in two places with conflicting values; and input validation is now STRICT across all catalog tools — an undeclared top-level key fails with a structured `validation_failed` naming it, instead of being silently dropped (a small documented compat list survives: pad_item's v0.16 `assigned_user_id` / `agent_role_id` remote clear form). One bump covers both halves — they are one contract change. v0.23 (BUG-2627 part 2 + BUG-2675, PR #1166) refuses raw `field` setters naming system-metadata keys in `fields_patch` on every transport (`github_pr` exempt on UPDATE only — the sole remote writer, itself broken — until v0.47 closed it: BUG-2696) and adds the retry-hostile `stored_state_unreadable` error code. v0.22 (BUG-2674, PR #1165) makes reserved metadata survive a move and refuses `field` setters naming those keys on move/copy — see `internal/mcp/version.go` for both full entries. v0.21 (BUG-2608) bounds `pad_item.action=history`, which was unbounded on every surface: the `limit` param now covers it (default 50, max 300 — the NEWEST N versions, with no `offset`, because reverse-patch storage makes only a newest-end window cheap to reconstruct), applied in the CATALOG action so it lands on both transports, and summary mode now asks the server to skip patch resolution (`?summary=true`) instead of resolving every body and discarding it. Additive param bump — `limit` already existed and nothing changed shape. v0.20 (BUG-2302 + BUG-2305, one bump) adds explicit MCP tool annotations (`readOnlyHint`/`destructiveHint`/`idempotentHint` derived from the catalog's own write-shape knowledge, fixing read-only tools that advertised `destructiveHint:true`) and makes `pad_item.list` summary-shaped on the REMOTE /mcp transport too (the hand-written `dispatchItemList` projects via `cli.ToItemSummaries`; `full=true` opts back into complete bodies) — see `internal/mcp/version.go` for the authoritative per-version changelog. Post-0.20 without a bump (BUG-2304): `item backlinks` / `item history` / `project report` gained HTTP route coverage — they were advertised but answered "not yet implemented over HTTP transport" — and a catalog↔route parity test (`dispatch_http_parity_test.go`) now drives every catalog action and fails on any future advertised-but-unrouted action; no names, enums, or shapes changed, hence no bump. v0.19 adds a `clear_parent` boolean to `pad_item` — the canonical, schema-discoverable way to detach an item from its parent, backed by a new `--clear-parent` bareword flag on `pad item update` (BUG-2078). v0.18 adds `clear_assigned_user` / `clear_agent_role` booleans to `pad_item` — the canonical, schema-discoverable way to unassign, backed by new `--clear-assigned-user` / `--clear-agent-role` bareword flags on `pad item update` (IDEA-2584). Update-only, deliberately asymmetric with create. v0.17 carries the empty-string clear to the LOCAL STDIO transport, which shells out to the CLI — `cmd/pad/cmd_item.go` now lifts `assigned_user_id` / `agent_role_id` onto their columns instead of into the fields blob, on create and update (BUG-2583). v0.16 makes an empty-string `assigned_user_id` / `agent_role_id` CLEAR the assignment instead of being silently dropped, so an MCP agent can finally unassign an item (TASK-2571). v0.15 adds the `pad_item.list` `unparented` boolean, mutually exclusive with `parent`, for items with no parent or implements relationship (TASK-2096). v0.2 introduced the catalog (PLAN-969 / TASK-981); v0.3 added `pad_playbook`, `pad_meta.action: bootstrap`, `pad_set_workspace`'s embedded-bootstrap response, and the `pad://workspace/{ws}/bootstrap` resource (PLAN-1377 / TASK-1380); v0.4 trimmed the bootstrap payload by ~40% (PLAN-1410) — slim `BootstrapCollection` + `BootstrapRole` projections (no UUIDs/timestamps/settings; nested `schema` object; redundant labels omitted), removed top-level `recent_activity` duplicate, dropped convention `slug`, and added a `BootstrapDashboard` wrapper that caps five sub-arrays (`attention`, `recent_activity`, `active_items`, `active_plans`, `by_role`) at 5 entries each with parallel `*_overflow_count` fields. The pre-catalog v0.1 cmdhelp leaf walker is retired. cmdhelp is still consumed at dispatch time — `BuildCLIArgs` reads individual command schemas to translate the catalog's snake_case input map into CLI args. cmdhelp no longer drives tool naming or count. @@ -358,7 +359,7 @@ pad mcp status # Install state across supported clients ``` Surface: -- **Tools:** the v0.71 catalog — ten resource × action tools (`pad_item`, `pad_workspace`, `pad_collection`, `pad_project`, `pad_role`, `pad_search`, `pad_meta`, `pad_playbook`, `pad_library`, `pad_attachment`) plus `pad_set_workspace` (takes a `workspace` slug only — no action enum). The ten resource × action tools take `action: ` to choose what they do. `pad_item` (v0.19) exposes `clear_parent` as the canonical parent-detach (update only); (v0.18) exposes `clear_assigned_user` / `clear_agent_role` booleans as the canonical unassign (update only); (v0.17) treats an empty-string `assigned_user_id` / `agent_role_id` as a clear on BOTH transports via `field: ["assigned_user_id="]` — the direct param form is remote-only, since it isn't schema-declared and stdio's BuildCLIArgs drops unknown keys (IDEA-2584); v0.16 fixed remote only; (v0.15) adds the `unparented` list parameter; v0.14 added `history` + `expected_updated_at`. `pad_project` (v0.13) adds `ready` (actionable backlog) + `stale` (items needing attention); `pad_project.activity` (v0.12) is the non-streaming, bounded activity feed — catch up on what other agents/users changed since you last worked. `pad_attachment` is the read-only attachment-metadata surface — `list`/`show` (upload/download/view stay CLI-only). `pad_library` is the convention+playbook library surface — `list`/`get`/`activate`. `pad_playbook` is the playbook surface from PLAN-1377 — `list`/`get`/`run` mirror the CLI's `pad playbook` subcommands; `run` is side-effect-free and returns the body + bound args for the agent to execute. v0.4 (PLAN-1410) didn't change the tool/action surface; it trimmed the bootstrap JSON those tools/resources return — see the Stability contract subsection below for details. +- **Tools:** the v0.72 catalog — ten resource × action tools (`pad_item`, `pad_workspace`, `pad_collection`, `pad_project`, `pad_role`, `pad_search`, `pad_meta`, `pad_playbook`, `pad_library`, `pad_attachment`) plus `pad_set_workspace` (takes a `workspace` slug only — no action enum). The ten resource × action tools take `action: ` to choose what they do. `pad_item` (v0.19) exposes `clear_parent` as the canonical parent-detach (update only); (v0.18) exposes `clear_assigned_user` / `clear_agent_role` booleans as the canonical unassign (update only); (v0.17) treats an empty-string `assigned_user_id` / `agent_role_id` as a clear on BOTH transports via `field: ["assigned_user_id="]` — the direct param form is remote-only, since it isn't schema-declared and stdio's BuildCLIArgs drops unknown keys (IDEA-2584); v0.16 fixed remote only; (v0.15) adds the `unparented` list parameter; v0.14 added `history` + `expected_updated_at`. `pad_project` (v0.13) adds `ready` (actionable backlog) + `stale` (items needing attention); `pad_project.activity` (v0.12) is the non-streaming, bounded activity feed — catch up on what other agents/users changed since you last worked. `pad_attachment` is the read-only attachment-metadata surface — `list`/`show` (upload/download/view stay CLI-only). `pad_library` is the convention+playbook library surface — `list`/`get`/`activate`. `pad_playbook` is the playbook surface from PLAN-1377 — `list`/`get`/`run` mirror the CLI's `pad playbook` subcommands; `run` is side-effect-free and returns the body + bound args for the agent to execute. v0.4 (PLAN-1410) didn't change the tool/action surface; it trimmed the bootstrap JSON those tools/resources return — see the Stability contract subsection below for details. - **Resources:** `pad://workspace/{ws}/items/{ref}`, `pad://workspace/{ws}/items`, `pad://workspace/{ws}/dashboard`, `pad://workspace/{ws}/collections`, `pad://workspace/{ws}/attachments/{id}` (bounded base64 image via `thumb-md`; non-images and image bytes over 1 MiB (pre-base64) rejected), `pad://workspace/{ws}/bootstrap` (one-shot workspace overview — user + collections + always-on conventions + roles + playbook metadata + dashboard + recent activity), plus the server-wide `pad://_meta/version`. - **Prompts:** `pad_plan`, `pad_ideate`, `pad_retro`, `pad_onboard` — multi-step workflows lifted from `skills/pad/SKILL.md`. @@ -366,7 +367,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` (currently `"0.1"`) — the cmdhelp CLI help-tree contract. Bump when CLI flag/arg schemas change incompatibly. -- `ToolSurfaceVersion` (currently `"0.71"`) — the MCP tool catalog contract. Bump when tool names, action enums, or parameter shapes change incompatibly. **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` (currently `"0.72"`) — the MCP tool catalog contract. Bump when tool names, action enums, or parameter shapes change incompatibly. **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/README.md b/README.md index 3a5793298..4579c2f43 100644 --- a/README.md +++ b/README.md @@ -390,13 +390,13 @@ 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.71)** — 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.72)** — 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 | |---|---| | `pad_item` | `create`, `update`, `delete`, `get`, `list`, `move`, `restore`, `link`, `unlink`, `deps`, `star`, `unstar`, `starred`, `comment`, `list-comments`, `edit-comment`, `delete-comment`, `backlinks`, `bulk-update`, `note`, `decide`, `export`, `import`, `history`, `remind`, `ack-reminder`, `claim`, `release` | | `pad_workspace` | `list`, `members`, `invite`, `storage`, `audit-log`, `create`, `claim`, `deleted`, `restore` | -| `pad_collection` | `list`, `create`, `update`, `delete` | +| `pad_collection` | `list`, `create`, `update`, `delete`, `list-archived`, `restore` | | `pad_project` | `dashboard`, `next`, `ready`, `stale`, `standup`, `changelog`, `report`, `activity` | | `pad_role` | `list`, `create`, `update`, `delete` | | `pad_search` | `query` | @@ -414,7 +414,7 @@ Plus resources at `pad://workspaces`, `pad://workspace/{ws}/dashboard`, and `pad://_meta/version`. **Stability contract.** The catalog is versioned -(`tool_surface_version: "0.71"`) and advertised in the initialize handshake and at +(`tool_surface_version: "0.72"`) 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_collection.go b/cmd/pad/cmd_collection.go index e27375d94..2c6cc74ea 100644 --- a/cmd/pad/cmd_collection.go +++ b/cmd/pad/cmd_collection.go @@ -389,7 +389,7 @@ issue-ID equivalent for collections themselves.`, func collectionsDeleteCmd() *cobra.Command { return &cobra.Command{ Use: "delete ", - Short: "Soft-delete a non-default collection (owner-only, irreversible from CLI)", + Short: "Archive a non-default collection and hide its items (owner-only; restore with 'pad collection restore')", Long: `Soft-delete a collection by slug. Constraints: @@ -398,11 +398,11 @@ Constraints: marked is_default=true). For seeded collections, use 'pad collection update' to adapt them (rename, reshape schema, swap icon) instead. - - Items in the collection are NOT cascaded — they remain in the - database with the soft-deleted collection_id. The web UI hides - them; the API still surfaces them if queried directly. - - No 'undelete' subcommand or restore endpoint exists; recovery - is only possible from a database backup.`, + - Items in the collection are NOT deleted — they stay in the + database, hidden with the collection. + - Reversible: 'pad collection archived' lists archived collections + and 'pad collection restore ' brings one back with its items + (TASK-2189).`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, _ := getClient() @@ -411,7 +411,59 @@ Constraints: if err := client.DeleteCollection(ws, collSlug); err != nil { return err } - fmt.Printf("Deleted collection %s\n", collSlug) + fmt.Printf("Archived collection %s (restore with: pad collection restore %s)\n", collSlug, collSlug) + return nil + }, + } +} + +// --- archived / restore (TASK-2189) --- + +func collectionsArchivedCmd() *cobra.Command { + return &cobra.Command{ + Use: "archived", + Short: "List archived collections and their item counts (owner-only)", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + client, _ := getClient() + ws := getWorkspace() + list, err := client.ListArchivedCollections(ws) + if err != nil { + return err + } + if formatFlag == "json" { + return cli.PrintJSON(list) + } + if len(list) == 0 { + fmt.Println("No archived collections.") + return nil + } + for _, a := range list { + fmt.Printf("%-24s %-8s %5d items archived %s\n", a.Slug, a.Prefix, a.ItemCount, a.ArchivedAt) + } + return nil + }, + } +} + +func collectionsRestoreCmd() *cobra.Command { + return &cobra.Command{ + Use: "restore ", + Short: "Restore an archived collection, with its items (owner-only)", + Long: `Restore an archived collection by its slug (or id). Its items come back +with it: archiving never deleted them. See 'pad collection archived'.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, _ := getClient() + ws := getWorkspace() + coll, err := client.RestoreCollection(ws, args[0]) + if err != nil { + return err + } + if formatFlag == "json" { + return cli.PrintJSON(coll) + } + fmt.Printf("Restored collection %s\n", coll.Slug) return nil }, } diff --git a/cmd/pad/groups.go b/cmd/pad/groups.go index ee9e18683..11019b74e 100644 --- a/cmd/pad/groups.go +++ b/cmd/pad/groups.go @@ -169,6 +169,8 @@ func collectionCmd() *cobra.Command { collectionsCreateCmd(), collectionsUpdateCmd(), collectionsDeleteCmd(), + collectionsArchivedCmd(), + collectionsRestoreCmd(), ) return cmd } diff --git a/cmd/pad/testdata/mcp_wire/remote_initialize.json b/cmd/pad/testdata/mcp_wire/remote_initialize.json index 3ca6b24b6..13d0ea88d 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.71" + "version": "0.72" } }, "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.71)\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 / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / claim / release. 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. 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, and the stored copy is updated only by a later collab-snapshot flush — usually from the tab that applied it, though any such write updates the row, and nothing guarantees one happens: the 200 echoes the content you SENT and carries `warnings.content_outcome: \"applied_pending_flush\"`, which describes that WRITE — the content went to the document, not the row — rather than being a live reading of the row, which a concurrent flush may already have updated. A `get` (or a `list` with `full: true` — a default list carries no content at all) before such a flush lands reads the stored copy and answers with the PREVIOUS content, which is the lag rather than a failed write, so do not re-send on the strength of it. You do not have to infer that from the write, and you will also see it when someone ELSE's tab holds the unflushed edits and you wrote nothing: a read that serves a body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"` — same value as the write warning, different question (what the ROW is, not what your REQUEST did). 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 writer is `pad github link` / `unlink`, which needs a local git checkout, and there is no PR-link action on this surface yet, so treat linking a PR as something to hand to a human rather than a call to retry. 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. `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`: a loser's 409 is `lease_held`, and a lease bumps neither `updated_at` nor `seq`. `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`. (Two older forms still work and are not deprecated: `field: [\"assigned_user_id=\"]` on either transport, and a direct `assigned_user_id: \"\"` param over remote `/mcp` only — prefer the boolean, which is the only one this schema advertises.)\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 item's EXACT TITLE — in that order, so an item literally titled `COLO-3` is unreachable by title while the ref resolves. Title matching is scoped to the collection the field declares: a title that is unique only workspace-wide is REFUSED, naming the collection searched, and a title matching two or more items inside the declared collection is refused as `ambiguous` rather than `not_found` — it matched too much, not too little. Only items YOU can see count towards any of that, so a match you have no access to never changes your answer.\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).** A field declared `multi_relation` holds an ORDERED LIST of references — `[\"\u003cuuid\u003e\", \"COLO-3\", \"Red\"]` — and every element resolves through the same UUID → ref → exact-title ladder, with the same collection scoping. Declare one through the `fields` DSL as `owners:multi_relation:people`: the third part is the TARGET COLLECTION, and omitting it is refused at parse time rather than building a field no write can ever satisfy.\n\nFour rules differ from a scalar `relation`, and none of them is guessable from the scalar behaviour:\n\n- **There is exactly one stored form for \"no references\": the key ABSENT.** Send `[]` and the write normalises it to that. A `required` `multi_relation` means at least one element that RESOLVED, so `[]` and an absent key both refuse.\n- **An empty or whitespace-only ELEMENT is refused**, naming its index — it is not skipped the way an empty scalar value is. Remove the element rather than blanking it.\n- **Order is part of the value.** `[\"a\",\"b\"]` and `[\"b\",\"a\"]` are different values, and a write preserves the order you sent.\n- **Duplicates are refused**, with reason `duplicate_referent`, naming the SECOND occurrence. Two elements can be different strings naming one item — a UUID and a ref, a ref and a title — so this is decided after resolution, and the two forms you sent may look nothing alike.\n\nIf ANY element fails, the whole write is refused and nothing is stored — never a partial list. On a cross-workspace copy the value is dropped WHOLE and reported once in `warnings.dropped_fields`, so an import can never change an element count.\n\nIn `relation_targets`, a `multi_relation` key carries a JSON **ARRAY** of the same `{id, ref, title}` objects, in stored order and one per stored element — including an `id`-only entry for an element that names nothing, so a position in the list lines up with the same position in `fields`. A scalar key is unchanged: still a single object, byte-identical to v0.31. Decide which shape to expect from the field's declared type, not by probing.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete.\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:\n\n- `pad://workspace/{ws}/dashboard` — computed project overview (active items, plans, attention, suggested next).\n- `pad://workspace/{ws}/collections` — collection types + schemas.\n- `pad://workspace/{ws}/items` — list of all items (use `pad_item.action: list` for filtering).\n- `pad://workspace/{ws}/items/{ref}` — single item rendered as markdown.\n- `pad://workspace/{ws}/attachments/{id}` — image attachment as a bounded base64 `thumb-md` resource; rejects non-images and image bytes over 1 MiB (pre-base64).\n- `pad://workspace/{ws}/bootstrap` — one-shot workspace context (same payload as `pad_meta.action: bootstrap` and `pad_set_workspace`'s embedded response).\n- `pad://_meta/version` — server version + stability tiers.\n\nResources support host-side prefetch — if the host can fetch them once at session start, you don't pay per turn.\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.72)\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 / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / claim / release. 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. 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, and the stored copy is updated only by a later collab-snapshot flush — usually from the tab that applied it, though any such write updates the row, and nothing guarantees one happens: the 200 echoes the content you SENT and carries `warnings.content_outcome: \"applied_pending_flush\"`, which describes that WRITE — the content went to the document, not the row — rather than being a live reading of the row, which a concurrent flush may already have updated. A `get` (or a `list` with `full: true` — a default list carries no content at all) before such a flush lands reads the stored copy and answers with the PREVIOUS content, which is the lag rather than a failed write, so do not re-send on the strength of it. You do not have to infer that from the write, and you will also see it when someone ELSE's tab holds the unflushed edits and you wrote nothing: a read that serves a body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"` — same value as the write warning, different question (what the ROW is, not what your REQUEST did). 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 writer is `pad github link` / `unlink`, which needs a local git checkout, and there is no PR-link action on this surface yet, so treat linking a PR as something to hand to a human rather than a call to retry. 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. `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`: a loser's 409 is `lease_held`, and a lease bumps neither `updated_at` nor `seq`. `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`. (Two older forms still work and are not deprecated: `field: [\"assigned_user_id=\"]` on either transport, and a direct `assigned_user_id: \"\"` param over remote `/mcp` only — prefer the boolean, which is the only one this schema advertises.)\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 item's EXACT TITLE — in that order, so an item literally titled `COLO-3` is unreachable by title while the ref resolves. Title matching is scoped to the collection the field declares: a title that is unique only workspace-wide is REFUSED, naming the collection searched, and a title matching two or more items inside the declared collection is refused as `ambiguous` rather than `not_found` — it matched too much, not too little. Only items YOU can see count towards any of that, so a match you have no access to never changes your answer.\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).** A field declared `multi_relation` holds an ORDERED LIST of references — `[\"\u003cuuid\u003e\", \"COLO-3\", \"Red\"]` — and every element resolves through the same UUID → ref → exact-title ladder, with the same collection scoping. Declare one through the `fields` DSL as `owners:multi_relation:people`: the third part is the TARGET COLLECTION, and omitting it is refused at parse time rather than building a field no write can ever satisfy.\n\nFour rules differ from a scalar `relation`, and none of them is guessable from the scalar behaviour:\n\n- **There is exactly one stored form for \"no references\": the key ABSENT.** Send `[]` and the write normalises it to that. A `required` `multi_relation` means at least one element that RESOLVED, so `[]` and an absent key both refuse.\n- **An empty or whitespace-only ELEMENT is refused**, naming its index — it is not skipped the way an empty scalar value is. Remove the element rather than blanking it.\n- **Order is part of the value.** `[\"a\",\"b\"]` and `[\"b\",\"a\"]` are different values, and a write preserves the order you sent.\n- **Duplicates are refused**, with reason `duplicate_referent`, naming the SECOND occurrence. Two elements can be different strings naming one item — a UUID and a ref, a ref and a title — so this is decided after resolution, and the two forms you sent may look nothing alike.\n\nIf ANY element fails, the whole write is refused and nothing is stored — never a partial list. On a cross-workspace copy the value is dropped WHOLE and reported once in `warnings.dropped_fields`, so an import can never change an element count.\n\nIn `relation_targets`, a `multi_relation` key carries a JSON **ARRAY** of the same `{id, ref, title}` objects, in stored order and one per stored element — including an `id`-only entry for an element that names nothing, so a position in the list lines up with the same position in `fields`. A scalar key is unchanged: still a single object, byte-identical to v0.31. Decide which shape to expect from the field's declared type, not by probing.\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.\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:\n\n- `pad://workspace/{ws}/dashboard` — computed project overview (active items, plans, attention, suggested next).\n- `pad://workspace/{ws}/collections` — collection types + schemas.\n- `pad://workspace/{ws}/items` — list of all items (use `pad_item.action: list` for filtering).\n- `pad://workspace/{ws}/items/{ref}` — single item rendered as markdown.\n- `pad://workspace/{ws}/attachments/{id}` — image attachment as a bounded base64 `thumb-md` resource; rejects non-images and image bytes over 1 MiB (pre-base64).\n- `pad://workspace/{ws}/bootstrap` — one-shot workspace context (same payload as `pad_meta.action: bootstrap` and `pad_set_workspace`'s embedded response).\n- `pad://_meta/version` — server version + stability tiers.\n\nResources support host-side prefetch — if the host can fetch them once at session start, you don't pay per turn.\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 bad93cebb..90dccf2ae 100644 --- a/cmd/pad/testdata/mcp_wire/remote_tools_list.json +++ b/cmd/pad/testdata/mcp_wire/remote_tools_list.json @@ -77,7 +77,7 @@ "idempotentHint": false, "openWorldHint": false }, - "description": "Collection management — list, create, update, and delete collection types.\n\nActions:\n list — List collections in the workspace with their schemas + counts.\n Required: workspace.\n create — Create a new collection.\n Required: workspace, name.\n Optional: fields OR schema (mutually exclusive), icon, description,\n layout, default_view, board_group_by.\n DSL example: fields=\"status:select:open,done; priority:select:high,medium,low\"\n Relation in the DSL: the third part is the TARGET COLLECTION slug,\n not an options list, and it is required —\n fields=\"reviewer:relation:people\". A relation with no target is\n refused rather than built, because such a field cannot accept any\n value.\n Schema example: schema={\"fields\":[{\"key\":\"status\",\"type\":\"select\",\"options\":[\"new\",\"done\"],\"terminal_options\":[\"done\"]}]}\n Prefer schema when terminal_options matters (driving dashboard\n active/complete counts) or when fields need defaults, computed\n flags, or suffixes — the DSL cannot express those.\n update — Update an existing collection's name, icon, description, prefix,\n schema, or sort order. Workspace owner only.\n Required: workspace, slug.\n Optional: name, icon, description, prefix, fields OR schema\n (mutually exclusive), sort_order. Only fields you\n explicitly set are mutated; everything else is left\n untouched.\n This is the adaptation primitive for the onboarding playbook\n (/pad onboard) — rewrite seeded collections to match the\n project's actual vocabulary instead of template defaults.\n delete — Soft-delete a collection. Owner-only. No restore endpoint\n exists — recovery requires a database backup. Required:\n workspace, slug.\n Constraints:\n - Cannot delete a default (template-seeded) collection.\n Adapt those via update instead (rename, reshape schema).\n - Items in the collection are NOT cascaded — they remain\n in the database with the soft-deleted collection_id.\n The web UI hides them; raw API queries still surface\n them.\n\nSchema for an individual collection is included in the list response — read it\nfrom there rather than calling list again. v0.2 does not expose a dedicated\nread-by-slug action; if you need that, file a feature request.\n\nUse pad_collection when an agent needs to discover collection types or set up\na new one. For item-level CRUD inside a collection, use pad_item.", + "description": "Collection management — list, create, update, archive (delete) and restore collection types.\n\nActions:\n list — List collections in the workspace with their schemas + counts.\n Required: workspace.\n create — Create a new collection.\n Required: workspace, name.\n Optional: fields OR schema (mutually exclusive), icon, description,\n layout, default_view, board_group_by.\n DSL example: fields=\"status:select:open,done; priority:select:high,medium,low\"\n Relation in the DSL: the third part is the TARGET COLLECTION slug,\n not an options list, and it is required —\n fields=\"reviewer:relation:people\". A relation with no target is\n refused rather than built, because such a field cannot accept any\n value.\n Schema example: schema={\"fields\":[{\"key\":\"status\",\"type\":\"select\",\"options\":[\"new\",\"done\"],\"terminal_options\":[\"done\"]}]}\n Prefer schema when terminal_options matters (driving dashboard\n active/complete counts) or when fields need defaults, computed\n flags, or suffixes — the DSL cannot express those.\n update — Update an existing collection's name, icon, description, prefix,\n schema, or sort order. Workspace owner only.\n Required: workspace, slug.\n Optional: name, icon, description, prefix, fields OR schema\n (mutually exclusive), sort_order. Only fields you\n explicitly set are mutated; everything else is left\n untouched.\n This is the adaptation primitive for the onboarding playbook\n (/pad onboard) — rewrite seeded collections to match the\n project's actual vocabulary instead of template defaults.\n delete — Archive a collection: it and its items leave every view. Owner-only.\n Reversible with restore. Required: workspace, slug.\n Constraints:\n - Cannot delete a default (template-seeded) collection.\n Adapt those via update instead (rename, reshape schema).\n - Items in the collection are NOT deleted — they stay in the\n database, hidden with the collection, and come back with it.\n list-archived — The workspace's archived collections, each with its slug,\n id, prefix, item_count and archived_at. Owner-only.\n Required: workspace.\n restore — Restore an archived collection, with its items. Owner-only.\n Required: workspace, slug (the archived collection's slug from\n list-archived, or its id).\n\nSchema for an individual collection is included in the list response — read it\nfrom there rather than calling list again. v0.2 does not expose a dedicated\nread-by-slug action; if you need that, file a feature request.\n\nUse pad_collection when an agent needs to discover collection types or set up\na new one. For item-level CRUD inside a collection, use pad_item.", "inputSchema": { "properties": { "action": { @@ -86,6 +86,8 @@ "create", "delete", "list", + "list-archived", + "restore", "update" ], "type": "string" @@ -138,7 +140,7 @@ "type": "object" }, "slug": { - "description": "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update and action=delete; identifies which collection to mutate.", + "description": "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update, action=delete and action=restore; identifies which collection to mutate. For restore, the archived collection's slug (from list-archived) or its id.", "type": "string" }, "sort_order": { diff --git a/cmd/pad/testdata/mcp_wire/stdio_initialize.json b/cmd/pad/testdata/mcp_wire/stdio_initialize.json index 3ca6b24b6..13d0ea88d 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.71" + "version": "0.72" } }, "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.71)\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 / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / claim / release. 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. 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, and the stored copy is updated only by a later collab-snapshot flush — usually from the tab that applied it, though any such write updates the row, and nothing guarantees one happens: the 200 echoes the content you SENT and carries `warnings.content_outcome: \"applied_pending_flush\"`, which describes that WRITE — the content went to the document, not the row — rather than being a live reading of the row, which a concurrent flush may already have updated. A `get` (or a `list` with `full: true` — a default list carries no content at all) before such a flush lands reads the stored copy and answers with the PREVIOUS content, which is the lag rather than a failed write, so do not re-send on the strength of it. You do not have to infer that from the write, and you will also see it when someone ELSE's tab holds the unflushed edits and you wrote nothing: a read that serves a body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"` — same value as the write warning, different question (what the ROW is, not what your REQUEST did). 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 writer is `pad github link` / `unlink`, which needs a local git checkout, and there is no PR-link action on this surface yet, so treat linking a PR as something to hand to a human rather than a call to retry. 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. `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`: a loser's 409 is `lease_held`, and a lease bumps neither `updated_at` nor `seq`. `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`. (Two older forms still work and are not deprecated: `field: [\"assigned_user_id=\"]` on either transport, and a direct `assigned_user_id: \"\"` param over remote `/mcp` only — prefer the boolean, which is the only one this schema advertises.)\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 item's EXACT TITLE — in that order, so an item literally titled `COLO-3` is unreachable by title while the ref resolves. Title matching is scoped to the collection the field declares: a title that is unique only workspace-wide is REFUSED, naming the collection searched, and a title matching two or more items inside the declared collection is refused as `ambiguous` rather than `not_found` — it matched too much, not too little. Only items YOU can see count towards any of that, so a match you have no access to never changes your answer.\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).** A field declared `multi_relation` holds an ORDERED LIST of references — `[\"\u003cuuid\u003e\", \"COLO-3\", \"Red\"]` — and every element resolves through the same UUID → ref → exact-title ladder, with the same collection scoping. Declare one through the `fields` DSL as `owners:multi_relation:people`: the third part is the TARGET COLLECTION, and omitting it is refused at parse time rather than building a field no write can ever satisfy.\n\nFour rules differ from a scalar `relation`, and none of them is guessable from the scalar behaviour:\n\n- **There is exactly one stored form for \"no references\": the key ABSENT.** Send `[]` and the write normalises it to that. A `required` `multi_relation` means at least one element that RESOLVED, so `[]` and an absent key both refuse.\n- **An empty or whitespace-only ELEMENT is refused**, naming its index — it is not skipped the way an empty scalar value is. Remove the element rather than blanking it.\n- **Order is part of the value.** `[\"a\",\"b\"]` and `[\"b\",\"a\"]` are different values, and a write preserves the order you sent.\n- **Duplicates are refused**, with reason `duplicate_referent`, naming the SECOND occurrence. Two elements can be different strings naming one item — a UUID and a ref, a ref and a title — so this is decided after resolution, and the two forms you sent may look nothing alike.\n\nIf ANY element fails, the whole write is refused and nothing is stored — never a partial list. On a cross-workspace copy the value is dropped WHOLE and reported once in `warnings.dropped_fields`, so an import can never change an element count.\n\nIn `relation_targets`, a `multi_relation` key carries a JSON **ARRAY** of the same `{id, ref, title}` objects, in stored order and one per stored element — including an `id`-only entry for an element that names nothing, so a position in the list lines up with the same position in `fields`. A scalar key is unchanged: still a single object, byte-identical to v0.31. Decide which shape to expect from the field's declared type, not by probing.\n\n- `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore.\n- `pad_collection` — Collections: list / create / update / delete.\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:\n\n- `pad://workspace/{ws}/dashboard` — computed project overview (active items, plans, attention, suggested next).\n- `pad://workspace/{ws}/collections` — collection types + schemas.\n- `pad://workspace/{ws}/items` — list of all items (use `pad_item.action: list` for filtering).\n- `pad://workspace/{ws}/items/{ref}` — single item rendered as markdown.\n- `pad://workspace/{ws}/attachments/{id}` — image attachment as a bounded base64 `thumb-md` resource; rejects non-images and image bytes over 1 MiB (pre-base64).\n- `pad://workspace/{ws}/bootstrap` — one-shot workspace context (same payload as `pad_meta.action: bootstrap` and `pad_set_workspace`'s embedded response).\n- `pad://_meta/version` — server version + stability tiers.\n\nResources support host-side prefetch — if the host can fetch them once at session start, you don't pay per turn.\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.72)\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 / star / unstar / starred / comment / list-comments / edit-comment / delete-comment / backlinks / bulk-update / note / decide / export / import / history / remind / ack-reminder / claim / release. 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. 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, and the stored copy is updated only by a later collab-snapshot flush — usually from the tab that applied it, though any such write updates the row, and nothing guarantees one happens: the 200 echoes the content you SENT and carries `warnings.content_outcome: \"applied_pending_flush\"`, which describes that WRITE — the content went to the document, not the row — rather than being a live reading of the row, which a concurrent flush may already have updated. A `get` (or a `list` with `full: true` — a default list carries no content at all) before such a flush lands reads the stored copy and answers with the PREVIOUS content, which is the lag rather than a failed write, so do not re-send on the strength of it. You do not have to infer that from the write, and you will also see it when someone ELSE's tab holds the unflushed edits and you wrote nothing: a read that serves a body the server knows is behind the live document carries `content_state: \"applied_pending_flush\"` — same value as the write warning, different question (what the ROW is, not what your REQUEST did). 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 writer is `pad github link` / `unlink`, which needs a local git checkout, and there is no PR-link action on this surface yet, so treat linking a PR as something to hand to a human rather than a call to retry. 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. `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`: a loser's 409 is `lease_held`, and a lease bumps neither `updated_at` nor `seq`. `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`. (Two older forms still work and are not deprecated: `field: [\"assigned_user_id=\"]` on either transport, and a direct `assigned_user_id: \"\"` param over remote `/mcp` only — prefer the boolean, which is the only one this schema advertises.)\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 item's EXACT TITLE — in that order, so an item literally titled `COLO-3` is unreachable by title while the ref resolves. Title matching is scoped to the collection the field declares: a title that is unique only workspace-wide is REFUSED, naming the collection searched, and a title matching two or more items inside the declared collection is refused as `ambiguous` rather than `not_found` — it matched too much, not too little. Only items YOU can see count towards any of that, so a match you have no access to never changes your answer.\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).** A field declared `multi_relation` holds an ORDERED LIST of references — `[\"\u003cuuid\u003e\", \"COLO-3\", \"Red\"]` — and every element resolves through the same UUID → ref → exact-title ladder, with the same collection scoping. Declare one through the `fields` DSL as `owners:multi_relation:people`: the third part is the TARGET COLLECTION, and omitting it is refused at parse time rather than building a field no write can ever satisfy.\n\nFour rules differ from a scalar `relation`, and none of them is guessable from the scalar behaviour:\n\n- **There is exactly one stored form for \"no references\": the key ABSENT.** Send `[]` and the write normalises it to that. A `required` `multi_relation` means at least one element that RESOLVED, so `[]` and an absent key both refuse.\n- **An empty or whitespace-only ELEMENT is refused**, naming its index — it is not skipped the way an empty scalar value is. Remove the element rather than blanking it.\n- **Order is part of the value.** `[\"a\",\"b\"]` and `[\"b\",\"a\"]` are different values, and a write preserves the order you sent.\n- **Duplicates are refused**, with reason `duplicate_referent`, naming the SECOND occurrence. Two elements can be different strings naming one item — a UUID and a ref, a ref and a title — so this is decided after resolution, and the two forms you sent may look nothing alike.\n\nIf ANY element fails, the whole write is refused and nothing is stored — never a partial list. On a cross-workspace copy the value is dropped WHOLE and reported once in `warnings.dropped_fields`, so an import can never change an element count.\n\nIn `relation_targets`, a `multi_relation` key carries a JSON **ARRAY** of the same `{id, ref, title}` objects, in stored order and one per stored element — including an `id`-only entry for an element that names nothing, so a position in the list lines up with the same position in `fields`. A scalar key is unchanged: still a single object, byte-identical to v0.31. Decide which shape to expect from the field's declared type, not by probing.\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.\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:\n\n- `pad://workspace/{ws}/dashboard` — computed project overview (active items, plans, attention, suggested next).\n- `pad://workspace/{ws}/collections` — collection types + schemas.\n- `pad://workspace/{ws}/items` — list of all items (use `pad_item.action: list` for filtering).\n- `pad://workspace/{ws}/items/{ref}` — single item rendered as markdown.\n- `pad://workspace/{ws}/attachments/{id}` — image attachment as a bounded base64 `thumb-md` resource; rejects non-images and image bytes over 1 MiB (pre-base64).\n- `pad://workspace/{ws}/bootstrap` — one-shot workspace context (same payload as `pad_meta.action: bootstrap` and `pad_set_workspace`'s embedded response).\n- `pad://_meta/version` — server version + stability tiers.\n\nResources support host-side prefetch — if the host can fetch them once at session start, you don't pay per turn.\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 81705f9a8..128e92260 100644 --- a/cmd/pad/testdata/mcp_wire/stdio_tools_list.json +++ b/cmd/pad/testdata/mcp_wire/stdio_tools_list.json @@ -77,7 +77,7 @@ "idempotentHint": false, "openWorldHint": false }, - "description": "Collection management — list, create, update, and delete collection types.\n\nActions:\n list — List collections in the workspace with their schemas + counts.\n Required: workspace.\n create — Create a new collection.\n Required: workspace, name.\n Optional: fields OR schema (mutually exclusive), icon, description,\n layout, default_view, board_group_by.\n DSL example: fields=\"status:select:open,done; priority:select:high,medium,low\"\n Relation in the DSL: the third part is the TARGET COLLECTION slug,\n not an options list, and it is required —\n fields=\"reviewer:relation:people\". A relation with no target is\n refused rather than built, because such a field cannot accept any\n value.\n Schema example: schema={\"fields\":[{\"key\":\"status\",\"type\":\"select\",\"options\":[\"new\",\"done\"],\"terminal_options\":[\"done\"]}]}\n Prefer schema when terminal_options matters (driving dashboard\n active/complete counts) or when fields need defaults, computed\n flags, or suffixes — the DSL cannot express those.\n update — Update an existing collection's name, icon, description, prefix,\n schema, or sort order. Workspace owner only.\n Required: workspace, slug.\n Optional: name, icon, description, prefix, fields OR schema\n (mutually exclusive), sort_order. Only fields you\n explicitly set are mutated; everything else is left\n untouched.\n This is the adaptation primitive for the onboarding playbook\n (/pad onboard) — rewrite seeded collections to match the\n project's actual vocabulary instead of template defaults.\n delete — Soft-delete a collection. Owner-only. No restore endpoint\n exists — recovery requires a database backup. Required:\n workspace, slug.\n Constraints:\n - Cannot delete a default (template-seeded) collection.\n Adapt those via update instead (rename, reshape schema).\n - Items in the collection are NOT cascaded — they remain\n in the database with the soft-deleted collection_id.\n The web UI hides them; raw API queries still surface\n them.\n\nSchema for an individual collection is included in the list response — read it\nfrom there rather than calling list again. v0.2 does not expose a dedicated\nread-by-slug action; if you need that, file a feature request.\n\nUse pad_collection when an agent needs to discover collection types or set up\na new one. For item-level CRUD inside a collection, use pad_item.", + "description": "Collection management — list, create, update, archive (delete) and restore collection types.\n\nActions:\n list — List collections in the workspace with their schemas + counts.\n Required: workspace.\n create — Create a new collection.\n Required: workspace, name.\n Optional: fields OR schema (mutually exclusive), icon, description,\n layout, default_view, board_group_by.\n DSL example: fields=\"status:select:open,done; priority:select:high,medium,low\"\n Relation in the DSL: the third part is the TARGET COLLECTION slug,\n not an options list, and it is required —\n fields=\"reviewer:relation:people\". A relation with no target is\n refused rather than built, because such a field cannot accept any\n value.\n Schema example: schema={\"fields\":[{\"key\":\"status\",\"type\":\"select\",\"options\":[\"new\",\"done\"],\"terminal_options\":[\"done\"]}]}\n Prefer schema when terminal_options matters (driving dashboard\n active/complete counts) or when fields need defaults, computed\n flags, or suffixes — the DSL cannot express those.\n update — Update an existing collection's name, icon, description, prefix,\n schema, or sort order. Workspace owner only.\n Required: workspace, slug.\n Optional: name, icon, description, prefix, fields OR schema\n (mutually exclusive), sort_order. Only fields you\n explicitly set are mutated; everything else is left\n untouched.\n This is the adaptation primitive for the onboarding playbook\n (/pad onboard) — rewrite seeded collections to match the\n project's actual vocabulary instead of template defaults.\n delete — Archive a collection: it and its items leave every view. Owner-only.\n Reversible with restore. Required: workspace, slug.\n Constraints:\n - Cannot delete a default (template-seeded) collection.\n Adapt those via update instead (rename, reshape schema).\n - Items in the collection are NOT deleted — they stay in the\n database, hidden with the collection, and come back with it.\n list-archived — The workspace's archived collections, each with its slug,\n id, prefix, item_count and archived_at. Owner-only.\n Required: workspace.\n restore — Restore an archived collection, with its items. Owner-only.\n Required: workspace, slug (the archived collection's slug from\n list-archived, or its id).\n\nSchema for an individual collection is included in the list response — read it\nfrom there rather than calling list again. v0.2 does not expose a dedicated\nread-by-slug action; if you need that, file a feature request.\n\nUse pad_collection when an agent needs to discover collection types or set up\na new one. For item-level CRUD inside a collection, use pad_item.", "inputSchema": { "properties": { "action": { @@ -86,6 +86,8 @@ "create", "delete", "list", + "list-archived", + "restore", "update" ], "type": "string" @@ -138,7 +140,7 @@ "type": "object" }, "slug": { - "description": "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update and action=delete; identifies which collection to mutate.", + "description": "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update, action=delete and action=restore; identifies which collection to mutate. For restore, the archived collection's slug (from list-archived) or its id.", "type": "string" }, "sort_order": { diff --git a/internal/cli/client.go b/internal/cli/client.go index d29a0a91a..f503cb943 100644 --- a/internal/cli/client.go +++ b/internal/cli/client.go @@ -230,6 +230,23 @@ func (c *Client) DeleteCollection(wsSlug, collSlug string) error { return c.delete("/workspaces/" + wsSlug + "/collections/" + collSlug) } +// ListArchivedCollections returns the workspace's archived collections +// (TASK-2189). +func (c *Client) ListArchivedCollections(wsSlug string) ([]models.ArchivedCollection, error) { + var out []models.ArchivedCollection + err := c.get("/workspaces/"+wsSlug+"/archived-collections", &out) + return out, err +} + +// RestoreCollection un-archives a collection by slug or id (TASK-2189). +func (c *Client) RestoreCollection(wsSlug, collRef string) (*models.Collection, error) { + var out models.Collection + if err := c.post("/workspaces/"+wsSlug+"/archived-collections/"+url.PathEscape(collRef)+"/restore", nil, &out); err != nil { + return nil, err + } + return &out, nil +} + // --- Items --- // ListItems returns items across all collections in a workspace. diff --git a/internal/mcp/catalog_collection.go b/internal/mcp/catalog_collection.go index 5e462cefc..f9b83b633 100644 --- a/internal/mcp/catalog_collection.go +++ b/internal/mcp/catalog_collection.go @@ -1,8 +1,9 @@ package mcp -// padCollectionTool exposes collection management. Four actions: -// list (read-only), create (admin-mutating), update (admin-mutating), -// delete (admin-mutating). +// padCollectionTool exposes collection management. Six actions: +// list and list-archived (read-only), create, update, delete (archive) and +// restore (admin-mutating). restore and list-archived are TASK-2189: an +// agent's archive is recoverable by an agent. // // `update` (TASK-1510) and `delete` (TASK-1511) are the adaptation // primitives for the `/pad onboard` playbook (PLAN-1496): the agent @@ -30,7 +31,7 @@ var padCollectionTool = ToolDef{ { Name: "slug", Type: "string", - Description: "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update and action=delete; identifies which collection to mutate.", + Description: "Collection slug (e.g. \"tasks\", \"conventions\"). Required for action=update, action=delete and action=restore; identifies which collection to mutate. For restore, the archived collection's slug (from list-archived) or its id.", }, { Name: "name", @@ -91,10 +92,13 @@ var padCollectionTool = ToolDef{ "create": passThrough([]string{"collection", "create"}), "update": passThrough([]string{"collection", "update"}), "delete": passThrough([]string{"collection", "delete"}), + // TASK-2189: an agent's archive is recoverable by an agent. + "list-archived": passThrough([]string{"collection", "archived"}), + "restore": passThrough([]string{"collection", "restore"}), }, } -const padCollectionToolDescription = `Collection management — list, create, update, and delete collection types. +const padCollectionToolDescription = `Collection management — list, create, update, archive (delete) and restore collection types. Actions: list — List collections in the workspace with their schemas + counts. @@ -123,16 +127,19 @@ Actions: This is the adaptation primitive for the onboarding playbook (/pad onboard) — rewrite seeded collections to match the project's actual vocabulary instead of template defaults. - delete — Soft-delete a collection. Owner-only. No restore endpoint - exists — recovery requires a database backup. Required: - workspace, slug. + delete — Archive a collection: it and its items leave every view. Owner-only. + Reversible with restore. Required: workspace, slug. Constraints: - Cannot delete a default (template-seeded) collection. Adapt those via update instead (rename, reshape schema). - - Items in the collection are NOT cascaded — they remain - in the database with the soft-deleted collection_id. - The web UI hides them; raw API queries still surface - them. + - Items in the collection are NOT deleted — they stay in the + database, hidden with the collection, and come back with it. + list-archived — The workspace's archived collections, each with its slug, + id, prefix, item_count and archived_at. Owner-only. + Required: workspace. + restore — Restore an archived collection, with its items. Owner-only. + Required: workspace, slug (the archived collection's slug from + list-archived, or its id). Schema for an individual collection is included in the list response — read it from there rather than calling list again. v0.2 does not expose a dedicated diff --git a/internal/mcp/catalog_readonly_test.go b/internal/mcp/catalog_readonly_test.go index cde6005c5..8227048c6 100644 --- a/internal/mcp/catalog_readonly_test.go +++ b/internal/mcp/catalog_readonly_test.go @@ -95,6 +95,9 @@ func TestReadOnlyCatalog_ActionsMatchCmdhelp(t *testing.T) { {"pad_collection", "create"}: {"collection", "create"}, {"pad_collection", "update"}: {"collection", "update"}, {"pad_collection", "delete"}: {"collection", "delete"}, + // TASK-2189: archive is reversible. + {"pad_collection", "list-archived"}: {"collection", "archived"}, + {"pad_collection", "restore"}: {"collection", "restore"}, {"pad_project", "dashboard"}: {"project", "dashboard"}, {"pad_project", "next"}: {"project", "next"}, @@ -258,6 +261,9 @@ func TestReadOnlyCatalog_ActionsDispatchExpectedCmdPath(t *testing.T) { {"pad_collection", "create"}: {"collection", "create"}, {"pad_collection", "update"}: {"collection", "update"}, {"pad_collection", "delete"}: {"collection", "delete"}, + // TASK-2189: archive is reversible. + {"pad_collection", "list-archived"}: {"collection", "archived"}, + {"pad_collection", "restore"}: {"collection", "restore"}, {"pad_project", "dashboard"}: {"project", "dashboard"}, {"pad_project", "next"}: {"project", "next"}, @@ -528,6 +534,12 @@ func liveCmdhelpDoc(t *testing.T) *cmdhelp.Document { Args: mkArgs("slug"), Flags: mkFlags("workspace"), }, + "collection archived": {Summary: "list archived cols", Flags: mkFlags("workspace")}, + "collection restore": { + Summary: "restore col", + Args: mkArgs("slug"), + Flags: mkFlags("workspace"), + }, // Project "project dashboard": {Summary: "dash", Flags: mkFlags("workspace")}, "project next": {Summary: "next", Flags: mkFlags("workspace")}, diff --git a/internal/mcp/chatgpt_catalog.go b/internal/mcp/chatgpt_catalog.go index fe6a07afe..720534200 100644 --- a/internal/mcp/chatgpt_catalog.go +++ b/internal/mcp/chatgpt_catalog.go @@ -309,53 +309,55 @@ var ChatGPTCatalog = []ChatGPTTool{ // ChatGPTExclusions are the /mcp operations deliberately not on the ChatGPT // surface, each with its reason (TASK-3321 U1-T, lead-ruled). var ChatGPTExclusions = map[ChatGPTSource]string{ - {Tool: chatGPTSetWorkspaceSource}: "on this shared server it persists no session workspace, so it would only duplicate get_workspace_overview, the connect step", - {"pad_item", "bulk-update"}: "batch overwrite with a large blast radius and little chat value", - {"pad_item", "move"}: "drops fields the target collection does not declare; confusing in chat", - {"pad_item", "delete-comment"}: "destructive, rarely needed", - {"pad_item", "edit-comment"}: "overwrite; deferred to v2", - {"pad_item", "unlink"}: "deferred to v2", - {"pad_item", "claim"}: "agent lease semantics, not a chat concept", - {"pad_item", "release"}: "agent lease semantics, not a chat concept", - {"pad_item", "remind"}: "deferred to v2", - {"pad_item", "ack-reminder"}: "deferred to v2", - {"pad_item", "star"}: "personal UI state", - {"pad_item", "unstar"}: "personal UI state", - {"pad_item", "starred"}: "personal UI state", - {"pad_item", "note"}: "structured implementation-note writer for coding agents", - {"pad_item", "decide"}: "structured decision-log writer for coding agents", - {"pad_item", "import"}: "artifact files, not chat", - {"pad_item", "export"}: "artifact files, not chat", - {"pad_item", "backlinks"}: "deferred to v2", - {"pad_workspace", "create"}: "cloud signup creates the first workspace; a user with none is pointed at app.getpad.dev", - {"pad_workspace", "invite"}: "sends email to an arbitrary address; kept to the web app", - {"pad_workspace", "claim"}: "workspace lifecycle; web app", - {"pad_workspace", "restore"}: "workspace lifecycle; web app", - {"pad_workspace", "deleted"}: "workspace lifecycle; web app", - {"pad_workspace", "members"}: "returns member emails (fails data minimization)", - {"pad_workspace", "audit-log"}: "returns IP addresses and user agents (fails data minimization)", - {"pad_workspace", "storage"}: "administration", - {"pad_collection", "create"}: "workspace configuration; web app or onboarding", - {"pad_collection", "update"}: "workspace configuration; web app or onboarding", - {"pad_collection", "delete"}: "workspace configuration; web app or onboarding", - {"pad_role", "create"}: "workspace configuration; web app or onboarding", - {"pad_role", "update"}: "workspace configuration; web app or onboarding", - {"pad_role", "delete"}: "workspace configuration; web app or onboarding", - {"pad_role", "list"}: "agent-role configuration, not used in chat", - {"pad_project", "changelog"}: "deferred to v2 (long output)", - {"pad_project", "standup"}: "deferred to v2 (long output)", - {"pad_project", "report"}: "deferred to v2 (long output)", - {"pad_project", "stale"}: "overlaps ready_items and the dashboard's attention list; v2", - {"pad_library", "list"}: "workspace configuration", - {"pad_library", "get"}: "workspace configuration", - {"pad_library", "activate"}: "workspace configuration (creates items)", - {"pad_meta", "server-info"}: "operator diagnostics (fails data minimization)", - {"pad_meta", "tool-surface"}: "operator diagnostics (fails data minimization)", - {"pad_meta", "version"}: "operator diagnostics (fails data minimization)", - {"pad_playbook", "match"}: "needs the decision provider and sends text to it; v2", - {"pad_playbook", "run"}: "returns a body for an agent to execute; get_playbook serves read-and-follow", - {"pad_attachment", "list"}: "metadata only with no display story yet; v2", - {"pad_attachment", "show"}: "metadata only with no display story yet; v2", + {Tool: chatGPTSetWorkspaceSource}: "on this shared server it persists no session workspace, so it would only duplicate get_workspace_overview, the connect step", + {"pad_item", "bulk-update"}: "batch overwrite with a large blast radius and little chat value", + {"pad_item", "move"}: "drops fields the target collection does not declare; confusing in chat", + {"pad_item", "delete-comment"}: "destructive, rarely needed", + {"pad_item", "edit-comment"}: "overwrite; deferred to v2", + {"pad_item", "unlink"}: "deferred to v2", + {"pad_item", "claim"}: "agent lease semantics, not a chat concept", + {"pad_item", "release"}: "agent lease semantics, not a chat concept", + {"pad_item", "remind"}: "deferred to v2", + {"pad_item", "ack-reminder"}: "deferred to v2", + {"pad_item", "star"}: "personal UI state", + {"pad_item", "unstar"}: "personal UI state", + {"pad_item", "starred"}: "personal UI state", + {"pad_item", "note"}: "structured implementation-note writer for coding agents", + {"pad_item", "decide"}: "structured decision-log writer for coding agents", + {"pad_item", "import"}: "artifact files, not chat", + {"pad_item", "export"}: "artifact files, not chat", + {"pad_item", "backlinks"}: "deferred to v2", + {"pad_workspace", "create"}: "cloud signup creates the first workspace; a user with none is pointed at app.getpad.dev", + {"pad_workspace", "invite"}: "sends email to an arbitrary address; kept to the web app", + {"pad_workspace", "claim"}: "workspace lifecycle; web app", + {"pad_workspace", "restore"}: "workspace lifecycle; web app", + {"pad_workspace", "deleted"}: "workspace lifecycle; web app", + {"pad_workspace", "members"}: "returns member emails (fails data minimization)", + {"pad_workspace", "audit-log"}: "returns IP addresses and user agents (fails data minimization)", + {"pad_workspace", "storage"}: "administration", + {"pad_collection", "create"}: "workspace configuration; web app or onboarding", + {"pad_collection", "update"}: "workspace configuration; web app or onboarding", + {"pad_collection", "delete"}: "workspace configuration; web app or onboarding", + {"pad_collection", "list-archived"}: "workspace configuration; web app or onboarding", + {"pad_collection", "restore"}: "workspace configuration; web app or onboarding", + {"pad_role", "create"}: "workspace configuration; web app or onboarding", + {"pad_role", "update"}: "workspace configuration; web app or onboarding", + {"pad_role", "delete"}: "workspace configuration; web app or onboarding", + {"pad_role", "list"}: "agent-role configuration, not used in chat", + {"pad_project", "changelog"}: "deferred to v2 (long output)", + {"pad_project", "standup"}: "deferred to v2 (long output)", + {"pad_project", "report"}: "deferred to v2 (long output)", + {"pad_project", "stale"}: "overlaps ready_items and the dashboard's attention list; v2", + {"pad_library", "list"}: "workspace configuration", + {"pad_library", "get"}: "workspace configuration", + {"pad_library", "activate"}: "workspace configuration (creates items)", + {"pad_meta", "server-info"}: "operator diagnostics (fails data minimization)", + {"pad_meta", "tool-surface"}: "operator diagnostics (fails data minimization)", + {"pad_meta", "version"}: "operator diagnostics (fails data minimization)", + {"pad_playbook", "match"}: "needs the decision provider and sends text to it; v2", + {"pad_playbook", "run"}: "returns a body for an agent to execute; get_playbook serves read-and-follow", + {"pad_attachment", "list"}: "metadata only with no display story yet; v2", + {"pad_attachment", "show"}: "metadata only with no display story yet; v2", } // ChatGPTExperimentalCapabilities is the ChatGPT server's diff --git a/internal/mcp/dispatch_http_routes.go b/internal/mcp/dispatch_http_routes.go index 3bfac3d4f..05b7b9ae0 100644 --- a/internal/mcp/dispatch_http_routes.go +++ b/internal/mcp/dispatch_http_routes.go @@ -355,6 +355,15 @@ func init() { method: http.MethodDelete, pathTemplate: "/api/v1/workspaces/{workspace}/collections/{slug}", }.toRouteMapper(), + // TASK-2189: archive is now reversible, by an agent too. + "collection archived": routeSpec{ + method: http.MethodGet, + pathTemplate: "/api/v1/workspaces/{workspace}/archived-collections", + }.toRouteMapper(), + "collection restore": routeSpec{ + method: http.MethodPost, + pathTemplate: "/api/v1/workspaces/{workspace}/archived-collections/{slug}/restore", + }.toRouteMapper(), "role list": routeSpec{ method: http.MethodGet, pathTemplate: "/api/v1/workspaces/{workspace}/agent-roles", diff --git a/internal/mcp/instructions.md b/internal/mcp/instructions.md index 1886c832d..9ea7827c2 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.71) +## Tool surface (v0.72) Ten resource × action tools, plus `pad_set_workspace`. Eleven tools total. @@ -36,7 +36,7 @@ If ANY element fails, the whole write is refused and nothing is stored — never In `relation_targets`, a `multi_relation` key carries a JSON **ARRAY** of the same `{id, ref, title}` objects, in stored order and one per stored element — including an `id`-only entry for an element that names nothing, so a position in the list lines up with the same position in `fields`. A scalar key is unchanged: still a single object, byte-identical to v0.31. Decide which shape to expect from the field's declared type, not by probing. - `pad_workspace` — Workspaces: list / members / invite / storage / audit-log / create / claim / deleted / restore. -- `pad_collection` — Collections: list / create / update / delete. +- `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. - `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). - `pad_role` — Agent roles: list / create / update / delete. - `pad_search` — Full-text search across items: query. diff --git a/internal/mcp/tool_surface.go b/internal/mcp/tool_surface.go index 98a2a5870..42d99f5e4 100644 --- a/internal/mcp/tool_surface.go +++ b/internal/mcp/tool_surface.go @@ -94,6 +94,8 @@ var readOnlyActions = map[string]map[string]bool{ }, "pad_collection": { "list": true, + // TASK-2189: restore is a write; list-archived is read-only. + "list-archived": true, }, "pad_project": { "dashboard": true, diff --git a/internal/mcp/version.go b/internal/mcp/version.go index 574e6fac0..17e4e1454 100644 --- a/internal/mcp/version.go +++ b/internal/mcp/version.go @@ -1738,6 +1738,15 @@ const CmdhelpVersion = "0.1" // caller cannot read embeds nothing; a failed fetch stays non-fatal, // as on stdio. Stdio is unchanged. // +// 0.72 — TASK-2189 (lead ruling). ADDITIVE bump on the v0.8 / v0.13 +// grounds (existing CLI verbs wired onto the catalog): `pad_collection` +// gains `list-archived` (read-only: the workspace's archived +// collections with slug, id, prefix, item_count and archived_at) and +// `restore` (owner-only: un-archive a collection, named by `slug` or +// id, with its items, which the archive never deleted). The `delete` +// description no longer says "No restore endpoint exists": an agent's +// archive is now recoverable by an agent. Nothing existing moved. +// // 0.71 — TASK-3462 U3a (lead ruling). ADDITIVE bump on the v0.63 / // v0.53 grounds: the bootstrap every bootstrap door returns // (`pad_set_workspace`'s embed, `pad_meta.action=bootstrap`, the @@ -1853,7 +1862,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.71" +const ToolSurfaceVersion = "0.72" // 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/models/collection.go b/internal/models/collection.go index 3710fa621..ae99cb8e8 100644 --- a/internal/models/collection.go +++ b/internal/models/collection.go @@ -289,3 +289,16 @@ func (u *CollectionUpdate) UnmarshalJSON(data []byte) error { return nil } + +// ArchivedCollection is one archived (soft-deleted) collection, as the +// restore surfaces list it (TASK-2189). ItemCount counts its live items: an +// archive hides them behind the collection's deleted_at and deletes none. +type ArchivedCollection struct { + ID string `json:"id"` + Name string `json:"name"` + Slug string `json:"slug"` + Prefix string `json:"prefix"` + Icon string `json:"icon,omitempty"` + ItemCount int `json:"item_count"` + ArchivedAt string `json:"archived_at"` +} diff --git a/internal/server/handlers_collections.go b/internal/server/handlers_collections.go index 408a9d4d1..36c8eb988 100644 --- a/internal/server/handlers_collections.go +++ b/internal/server/handlers_collections.go @@ -714,3 +714,93 @@ func uniqueCollectionConflictMessage(err error) string { return "This change conflicts with an existing unique value" } } + +// handleListArchivedCollections answers GET /workspaces/{ws}/archived-collections +// (TASK-2189): the workspace's archived collections with their item counts. +// Owner-only, like the archive it lists. +func (s *Server) handleListArchivedCollections(w http.ResponseWriter, r *http.Request) { + if !requireMinRole(w, r, "owner") { + return + } + workspaceID, ok := s.getWorkspaceID(w, r) + if !ok { + return + } + list, err := s.store.ListArchivedCollections(workspaceID) + if err != nil { + writeInternalError(w, err) + return + } + // The live list's visibility rule (a restricted owner sees only the + // collections granted to them), so this is not a door onto hidden ones. + visibleIDs, err := s.visibleCollectionIDs(r, workspaceID) + if err != nil { + writeInternalError(w, err) + return + } + if visibleIDs != nil { + kept := list[:0] + for _, a := range list { + if isCollectionVisible(a.ID, visibleIDs) { + kept = append(kept, a) + } + } + list = kept + } + writeJSON(w, http.StatusOK, list) +} + +// handleRestoreCollection answers POST +// /workspaces/{ws}/archived-collections/{collRef}/restore (TASK-2189), by id or +// slug: it +// un-archives the collection, and its items come back with it, since the +// archive never deleted them. 404 for an id that is not an archived collection +// of this workspace. Owner-only, like the archive it reverses. +func (s *Server) handleRestoreCollection(w http.ResponseWriter, r *http.Request) { + if !requireMinRole(w, r, "owner") { + return + } + workspaceID, ok := s.getWorkspaceID(w, r) + if !ok { + return + } + const notArchived = "No archived collection with that slug or id in this workspace" + id, err := s.store.ResolveArchivedCollection(workspaceID, chi.URLParam(r, "collRef")) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "not_found", notArchived) + return + } + if err != nil { + writeInternalError(w, err) + return + } + // The archive's own visibility rule: a collection the caller could not + // archive (hidden from a restricted owner) is not theirs to restore, and + // answers the same 404 as one that does not exist. + visible, err := s.checkCollectionFullyVisible(r, workspaceID, id) + if err != nil { + writeInternalError(w, err) + return + } + if !visible { + writeError(w, http.StatusNotFound, "not_found", notArchived) + return + } + coll, err := s.store.RestoreCollection(workspaceID, id) + if errors.Is(err, sql.ErrNoRows) { + writeError(w, http.StatusNotFound, "not_found", notArchived) + return + } + if err != nil { + writeInternalError(w, err) + return + } + // The archive's own side effect, reversed: the collection's grants apply + // again and its items re-enter views, so connections re-check (TASK-3365). + // The event tells open clients to refetch collections; the item-sync + // epoch fingerprints the live collection set, so delta clients resync and + // receive the restored items (BUG-3428). + s.invalidateWorkspaceAccess(workspaceID) + s.publishCollectionEvent(events.CollectionUpdated, workspaceID, coll.ID, coll.Slug, "", true) + writeJSON(w, http.StatusOK, coll) +} diff --git a/internal/server/server.go b/internal/server/server.go index 543948053..50f867d0a 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -2081,6 +2081,13 @@ func (s *Server) setupRouter() { }) // Collections (v2) + // Archived collections (TASK-2189): list and restore. A + // sibling of /collections rather than inside it, because + // /collections/{collSlug} resolves LIVE collections only + // and a collection could itself be slugged "archived". + r.Get("/archived-collections", s.handleListArchivedCollections) + r.Post("/archived-collections/{collRef}/restore", s.handleRestoreCollection) + r.Route("/collections", func(r chi.Router) { r.Get("/", s.handleListCollections) r.Post("/", s.handleCreateCollection) diff --git a/internal/server/task2189_collection_restore_test.go b/internal/server/task2189_collection_restore_test.go new file mode 100644 index 000000000..c381dddad --- /dev/null +++ b/internal/server/task2189_collection_restore_test.go @@ -0,0 +1,171 @@ +package server + +import ( + "net/http" + "testing" + + "github.com/PerpetualSoftware/pad/internal/models" +) + +// TASK-2189: archiving a collection hides it and its items; nothing could +// bring them back. GET archived-collections lists what is archived and POST +// .../restore brings one back, items included (the archive never deleted them). + +func archivedList(t *testing.T, srv *Server, ws string) []models.ArchivedCollection { + t.Helper() + rr := doRequest(srv, "GET", "/api/v1/workspaces/"+ws+"/archived-collections", nil) + if rr.Code != http.StatusOK { + t.Fatalf("list archived: %d %s", rr.Code, rr.Body.String()) + } + var out []models.ArchivedCollection + parseJSON(t, rr, &out) + return out +} + +func seedCollectionWithItems(t *testing.T, srv *Server, ws, name string, n int) models.Collection { + t.Helper() + rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/collections", map[string]any{"name": name}) + if rr.Code != http.StatusCreated { + t.Fatalf("create collection: %d %s", rr.Code, rr.Body.String()) + } + var coll models.Collection + parseJSON(t, rr, &coll) + for i := 0; i < n; i++ { + irr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/collections/"+coll.Slug+"/items", map[string]any{"title": name + " item"}) + if irr.Code != http.StatusCreated { + t.Fatalf("create item: %d %s", irr.Code, irr.Body.String()) + } + } + return coll +} + +func itemCount(t *testing.T, srv *Server, ws, collSlug string) (int, int) { + t.Helper() + rr := doRequest(srv, "GET", "/api/v1/workspaces/"+ws+"/collections/"+collSlug+"/items", nil) + if rr.Code != http.StatusOK { + return rr.Code, -1 + } + var items []models.Item + parseJSON(t, rr, &items) + return rr.Code, len(items) +} + +func TestRestoreCollection_TASK2189_RoundTripWithItems(t *testing.T) { + srv := testServer(t) + ws := createWSWithCollections(t, srv) + coll := seedCollectionWithItems(t, srv, ws, "Field Notes", 3) + + if rr := doRequest(srv, "DELETE", "/api/v1/workspaces/"+ws+"/collections/"+coll.Slug, nil); rr.Code != http.StatusNoContent { + t.Fatalf("archive: %d %s", rr.Code, rr.Body.String()) + } + if code, _ := itemCount(t, srv, ws, coll.Slug); code != http.StatusNotFound { + t.Fatalf("archived collection's items answered %d, want 404", code) + } + list := archivedList(t, srv, ws) + if len(list) != 1 || list[0].ID != coll.ID || list[0].Slug != coll.Slug || list[0].ItemCount != 3 || list[0].ArchivedAt == "" { + t.Fatalf("archived list = %+v, want the collection with 3 items", list) + } + + // The sync epoch fingerprints the live collection set: a restore must move + // it, so delta clients resync and receive the restored items (BUG-3428). + epoch := func() string { + rr := doRequest(srv, "GET", "/api/v1/workspaces/"+ws+"/items-changes?since=0", nil) + var body struct { + AccessEpoch string `json:"access_epoch"` + } + parseJSON(t, rr, &body) + return body.AccessEpoch + } + before := epoch() + + rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/archived-collections/"+coll.Slug+"/restore", nil) + if rr.Code != http.StatusOK { + t.Fatalf("restore by slug: %d %s", rr.Code, rr.Body.String()) + } + if code, n := itemCount(t, srv, ws, coll.Slug); code != http.StatusOK || n != 3 { + t.Fatalf("after restore: %d with %d items, want 200 with 3", code, n) + } + if len(archivedList(t, srv, ws)) != 0 { + t.Fatal("a restored collection is still listed as archived") + } + if after := epoch(); after == before { + t.Fatalf("the item-sync epoch did not move on restore (%q): delta clients would never see the items", after) + } + + // By id, too; and a second restore of a live collection is a 404. + if rr := doRequest(srv, "DELETE", "/api/v1/workspaces/"+ws+"/collections/"+coll.Slug, nil); rr.Code != http.StatusNoContent { + t.Fatalf("re-archive: %d", rr.Code) + } + if rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/archived-collections/"+coll.ID+"/restore", nil); rr.Code != http.StatusOK { + t.Fatalf("restore by id: %d %s", rr.Code, rr.Body.String()) + } + if rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/archived-collections/"+coll.Slug+"/restore", nil); rr.Code != http.StatusNotFound { + t.Fatalf("restoring a LIVE collection answered %d, want 404", rr.Code) + } + if rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/archived-collections/no-such-thing/restore", nil); rr.Code != http.StatusNotFound { + t.Fatalf("restoring an unknown ref answered %d, want 404", rr.Code) + } +} + +// A newer collection with the archived one's name took `x-2`, so a restore +// brings the old one back beside it, both reachable. +func TestRestoreCollection_TASK2189_BesideANewerSameNamedCollection(t *testing.T) { + srv := testServer(t) + ws := createWSWithCollections(t, srv) + old := seedCollectionWithItems(t, srv, ws, "Notes", 1) + if rr := doRequest(srv, "DELETE", "/api/v1/workspaces/"+ws+"/collections/"+old.Slug, nil); rr.Code != http.StatusNoContent { + t.Fatalf("archive: %d", rr.Code) + } + newer := seedCollectionWithItems(t, srv, ws, "Notes", 2) + if newer.Slug == old.Slug { + t.Fatalf("the newer collection reused the archived slug %q", old.Slug) + } + if rr := doRequest(srv, "POST", "/api/v1/workspaces/"+ws+"/archived-collections/"+old.Slug+"/restore", nil); rr.Code != http.StatusOK { + t.Fatalf("restore: %d %s", rr.Code, rr.Body.String()) + } + if _, n := itemCount(t, srv, ws, old.Slug); n != 1 { + t.Fatalf("restored collection has %d items, want 1", n) + } + if _, n := itemCount(t, srv, ws, newer.Slug); n != 2 { + t.Fatalf("newer collection has %d items, want 2", n) + } +} + +// A restricted owner can neither list nor restore an archived collection they +// could not see live; the visible one works. +func TestRestoreCollection_TASK2189_RestrictedOwnerVisibility(t *testing.T) { + f := newRestrictedOwnerVisibilityFixture(t) + for _, c := range []*models.Collection{f.hiddenColl, f.visibleColl} { + if err := f.srv.store.DeleteCollection(c.ID, ""); err != nil { + t.Fatalf("archive %s: %v", c.Slug, err) + } + } + rr := doRequestWithHeaders(f.srv, "GET", "/api/v1/workspaces/"+f.ws.Slug+"/archived-collections", nil, f.bearerHeaders()) + if rr.Code != http.StatusOK { + t.Fatalf("list: %d %s", rr.Code, rr.Body.String()) + } + var list []models.ArchivedCollection + parseJSON(t, rr, &list) + if len(list) != 1 || list[0].ID != f.visibleColl.ID { + t.Fatalf("restricted owner's archived list = %+v, want only the visible collection", list) + } + hidden := doRequestWithHeaders(f.srv, "POST", "/api/v1/workspaces/"+f.ws.Slug+"/archived-collections/"+f.hiddenColl.ID+"/restore", nil, f.bearerHeaders()) + if hidden.Code != http.StatusNotFound { + t.Fatalf("restoring a hidden collection answered %d, want 404", hidden.Code) + } + still, err := f.srv.store.ListArchivedCollections(f.ws.ID) + if err != nil { + t.Fatal(err) + } + hiddenStillArchived := false + for _, a := range still { + hiddenStillArchived = hiddenStillArchived || a.ID == f.hiddenColl.ID + } + if !hiddenStillArchived { + t.Fatal("the hidden collection was restored by a caller who cannot see it") + } + visible := doRequestWithHeaders(f.srv, "POST", "/api/v1/workspaces/"+f.ws.Slug+"/archived-collections/"+f.visibleColl.ID+"/restore", nil, f.bearerHeaders()) + if visible.Code != http.StatusOK { + t.Fatalf("restoring the visible collection answered %d: %s", visible.Code, visible.Body.String()) + } +} diff --git a/internal/store/collections_archive.go b/internal/store/collections_archive.go new file mode 100644 index 000000000..86d7829e1 --- /dev/null +++ b/internal/store/collections_archive.go @@ -0,0 +1,76 @@ +package store + +import ( + "database/sql" + "fmt" + + "github.com/PerpetualSoftware/pad/internal/models" +) + +// TASK-2189: archiving a collection (DeleteCollection) is a soft delete of the +// collection row; its items are untouched and only hidden by that row's +// deleted_at, and nothing purges an archived collection. These two make that +// reversible: list what is archived, and restore one by clearing deleted_at. +// +// A restore cannot collide: slugs are allocated unique across archived rows +// too (uniqueSlugQ), so a newer collection with the same name took `x-2`; and +// prefixes are not unique even among live collections (item numbers are +// workspace-unique, so refs stay unambiguous). + +// ListArchivedCollections returns the workspace's archived collections, most +// recently archived first, each with its count of live items. +func (s *Store) ListArchivedCollections(workspaceID string) ([]models.ArchivedCollection, error) { + rows, err := s.db.Query(s.q(` + SELECT c.id, c.name, c.slug, c.prefix, c.icon, c.deleted_at, + (SELECT COUNT(*) FROM items i WHERE i.collection_id = c.id AND i.deleted_at IS NULL) + FROM collections c + WHERE c.workspace_id = ? AND c.deleted_at IS NOT NULL + ORDER BY c.deleted_at DESC, c.id`), workspaceID) + if err != nil { + return nil, fmt.Errorf("list archived collections: %w", err) + } + defer rows.Close() + out := []models.ArchivedCollection{} + for rows.Next() { + var a models.ArchivedCollection + var icon sql.NullString + if err := rows.Scan(&a.ID, &a.Name, &a.Slug, &a.Prefix, &icon, &a.ArchivedAt, &a.ItemCount); err != nil { + return nil, fmt.Errorf("scan archived collection: %w", err) + } + a.Icon = icon.String + out = append(out, a) + } + return out, rows.Err() +} + +// ResolveArchivedCollection returns the id of this workspace's ARCHIVED +// collection named by ref, its id or its slug (slugs are unique per workspace +// across archived rows too, so either names at most one). sql.ErrNoRows when +// ref names none (unknown, another workspace's, or live), so a caller cannot +// tell those apart. +func (s *Store) ResolveArchivedCollection(workspaceID, ref string) (string, error) { + var id string + err := s.db.QueryRow(s.q(` + SELECT id FROM collections + WHERE workspace_id = ? AND (id = ? OR slug = ?) AND deleted_at IS NOT NULL`), workspaceID, ref, ref).Scan(&id) + return id, err +} + +// RestoreCollection un-archives this workspace's archived collection id. +// sql.ErrNoRows when it is not one (already restored by a racing call, or +// never archived). +func (s *Store) RestoreCollection(workspaceID, id string) (*models.Collection, error) { + ts := now() + res, err := s.db.Exec(s.q(` + UPDATE collections SET deleted_at = NULL, updated_at = ? + WHERE id = ? AND workspace_id = ? AND deleted_at IS NOT NULL`), ts, id, workspaceID) + if err != nil { + return nil, fmt.Errorf("restore collection: %w", err) + } + if n, err := res.RowsAffected(); err != nil { + return nil, fmt.Errorf("restore collection: %w", err) + } else if n == 0 { + return nil, sql.ErrNoRows + } + return s.GetCollection(id) +} diff --git a/internal/store/collections_archive_test.go b/internal/store/collections_archive_test.go new file mode 100644 index 000000000..b1d8060eb --- /dev/null +++ b/internal/store/collections_archive_test.go @@ -0,0 +1,94 @@ +package store_test + +import ( + "database/sql" + "errors" + "sync" + "testing" + + "github.com/PerpetualSoftware/pad/internal/models" + "github.com/PerpetualSoftware/pad/internal/store" + "github.com/PerpetualSoftware/pad/internal/store/storetest" +) + +// TASK-2189: list and restore archived collections, on both dialects (the +// deleted_at scan and the item-count subquery), and a restore race. + +func TestArchivedCollections_SQLite(t *testing.T) { archivedCollections(t, storetest.NewSQLite(t)) } +func TestArchivedCollections_Postgres(t *testing.T) { archivedCollections(t, storetest.NewPostgres(t)) } + +func archivedCollections(t *testing.T, s *store.Store) { + ws, err := s.CreateWorkspace(models.WorkspaceCreate{Name: "Archive 2189"}) + if err != nil { + t.Fatal(err) + } + coll, err := s.CreateCollection(ws.ID, models.CollectionCreate{Name: "Field Notes"}) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if _, err := s.CreateItem(ws.ID, coll.ID, models.ItemCreate{Title: "note"}); err != nil { + t.Fatal(err) + } + } + if err := s.DeleteCollection(coll.ID, ""); err != nil { + t.Fatal(err) + } + + list, err := s.ListArchivedCollections(ws.ID) + if err != nil { + t.Fatal(err) + } + if len(list) != 1 || list[0].ID != coll.ID || list[0].ItemCount != 2 || list[0].ArchivedAt == "" { + t.Fatalf("archived = %+v, want the collection with 2 items and a time", list) + } + + // A live slug, an unknown ref and another workspace's ref name nothing. + other, err := s.CreateWorkspace(models.WorkspaceCreate{Name: "Other 2189"}) + if err != nil { + t.Fatal(err) + } + for _, c := range []struct{ ws, ref string }{{ws.ID, "nope"}, {other.ID, coll.ID}, {other.ID, coll.Slug}} { + if _, err := s.ResolveArchivedCollection(c.ws, c.ref); !errors.Is(err, sql.ErrNoRows) { + t.Errorf("ResolveArchivedCollection(%s, %s) = %v, want ErrNoRows", c.ws, c.ref, err) + } + } + + // Two concurrent restores: exactly one wins, the other is told there is + // nothing archived to restore. + id, err := s.ResolveArchivedCollection(ws.ID, coll.Slug) + if err != nil || id != coll.ID { + t.Fatalf("resolve by slug = %q, %v", id, err) + } + var wg sync.WaitGroup + var mu sync.Mutex + wins, losses := 0, 0 + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, err := s.RestoreCollection(ws.ID, id) + mu.Lock() + defer mu.Unlock() + switch { + case err == nil: + wins++ + case errors.Is(err, sql.ErrNoRows): + losses++ + default: + t.Errorf("restore: %v", err) + } + }() + } + wg.Wait() + if wins != 1 || losses != 1 { + t.Fatalf("concurrent restores: %d won, %d lost; want exactly one of each", wins, losses) + } + live, err := s.GetCollection(coll.ID) + if err != nil || live == nil || live.DeletedAt != nil { + t.Fatalf("after restore: %+v %v, want the live collection", live, err) + } + if list, _ := s.ListArchivedCollections(ws.ID); len(list) != 0 { + t.Fatalf("still listed as archived: %+v", list) + } +} diff --git a/web/src/lib/api/client.ts b/web/src/lib/api/client.ts index 5e383f755..e7f6fccb8 100644 --- a/web/src/lib/api/client.ts +++ b/web/src/lib/api/client.ts @@ -100,7 +100,8 @@ import type { TutorialsResponse, UIDismissalKey, UIDismissalsResponse, - ImportOutcome + ImportOutcome, + ArchivedCollection } from '$lib/types'; import { reportWorkspaceWrite } from './workspaceWrites'; import { noteServerDate } from './serverClock'; @@ -1533,6 +1534,15 @@ export const api = { list: (ws: string) => request(`/workspaces/${ws}/collections`), + // TASK-2189: archive is reversible. Owner-only, like the archive. + archived: (ws: string) => + request(`/workspaces/${ws}/archived-collections`), + // By id or slug; its items come back with it. + restore: (ws: string, ref: string) => + request(`/workspaces/${ws}/archived-collections/${encodeURIComponent(ref)}/restore`, { + method: 'POST' + }), + create: (ws: string, data: CollectionCreate) => request(`/workspaces/${ws}/collections`, { method: 'POST', diff --git a/web/src/lib/components/collections/ArchivedCollections.svelte b/web/src/lib/components/collections/ArchivedCollections.svelte new file mode 100644 index 000000000..29e44152d --- /dev/null +++ b/web/src/lib/components/collections/ArchivedCollections.svelte @@ -0,0 +1,141 @@ + + +{#if loaded && archived.length > 0} +
+

Archived collections

+

Archived collections and their items are hidden, not deleted. Restore brings both back.

+
    + {#each archived as a (a.id)} +
  • + + {a.name} + /{a.slug} + {a.item_count} {a.item_count === 1 ? 'item' : 'items'} + archived {new Date(a.archived_at).toLocaleDateString()} + +
  • + {/each} +
+
+{/if} + + diff --git a/web/src/lib/components/collections/EditCollectionModal.svelte b/web/src/lib/components/collections/EditCollectionModal.svelte index 8e44ac0bd..040d7dfcc 100644 --- a/web/src/lib/components/collections/EditCollectionModal.svelte +++ b/web/src/lib/components/collections/EditCollectionModal.svelte @@ -76,12 +76,24 @@ let confirmArchive = $state(false); let archiving = $state(false); + // TASK-2189: archiving a big collection asks for its name to be typed, as + // deleting a workspace asks for its slug. Below the threshold, the count + // in the confirm is the guard. + const TYPED_ARCHIVE_THRESHOLD = 25; + let archiveTyped = $state(''); + const archiveItemCount = $derived(collection.item_count); + // An UNKNOWN count fails closed (codex r1): the confirm cannot say how + // much is going, so the typed guard stands in for the number. + const archiveNeedsTyping = $derived(archiveItemCount === undefined || archiveItemCount >= TYPED_ARCHIVE_THRESHOLD); + const archiveConfirmed = $derived(!archiveNeedsTyping || archiveTyped.trim() === collection.name); async function handleArchive() { if (!confirmArchive) { confirmArchive = true; + archiveTyped = ''; return; } + if (!archiveConfirmed) return; archiving = true; // Target the SEEDED collection identity, NOT the live props — the props // may now identify a different collection while this form still shows @@ -100,8 +112,27 @@ // delete -> list -> delete, so the second DELETE — destructive — would // otherwise be issued on behalf of a user who is gone. const isSameIdentity = authStore.identityFence(); + // The Undo outlives this modal, so it carries what it restores and the + // identity it was offered to, checked again at CLICK time: the workspace + // delete's pattern (BUG-3006), since the toast store is global. + const epochAtArchive = authStore.identityEpoch; const finishArchived = () => { - toastStore.show(`Archived "${editedCollectionName}"`, 'success'); + toastStore.show(`Archived "${editedCollectionName}"`, 'success', 12000, undefined, { + label: 'Undo', + onAction: () => { + if (authStore.identityEpoch !== epochAtArchive) return; + api.collections + .restore(editedWsSlug, editedCollectionId) + .then(() => { + if (authStore.identityEpoch !== epochAtArchive) return; + toastStore.show(`Restored "${editedCollectionName}"`, 'success'); + }) + .catch(() => { + if (authStore.identityEpoch !== epochAtArchive) return; + toastStore.show(`Failed to restore "${editedCollectionName}"`, 'error'); + }); + } + }); onupdated(undefined, editedCollectionId, editedCollectionSlug, editedWsSlug); onclose(); }; @@ -794,22 +825,39 @@

Danger zone

- Archiving removes this collection and all its items from the workspace. - This can't be undone from the UI. + Archiving hides this collection and all its items from the workspace. + Nothing is deleted: restore it any time from Settings › Collections.

{#if confirmArchive}

- Archive "{collection.name}" and all its items? + {#if archiveItemCount !== undefined} + Archive "{collection.name}" and its + {archiveItemCount} {archiveItemCount === 1 ? 'item' : 'items'}? + {:else} + Archive "{collection.name}" and all its items? + {/if}

+ {#if archiveNeedsTyping} + + {/if}
@@ -1249,6 +1297,21 @@ gap: var(--space-3); } + .danger-zone-typed { + display: flex; + flex-direction: column; + gap: var(--space-1); + font-size: 0.85em; + color: var(--text-secondary); + } + .danger-zone-typed input { + padding: var(--space-1) var(--space-2); + border: 1px solid var(--border); + border-radius: var(--radius-sm, 6px); + background: var(--bg-primary); + color: var(--text-primary); + font: inherit; + } .danger-zone-confirm-msg { margin: 0; font-size: 0.9em; diff --git a/web/src/lib/components/collections/archiveRestore.svelte.test.ts b/web/src/lib/components/collections/archiveRestore.svelte.test.ts new file mode 100644 index 000000000..c5d0b0137 --- /dev/null +++ b/web/src/lib/components/collections/archiveRestore.svelte.test.ts @@ -0,0 +1,169 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { flushSync, mount, unmount, tick } from 'svelte'; +import type { ArchivedCollection, Collection } from '$lib/types'; + +/** + * TASK-2189: archiving a collection showed no count, had a two-click guard + * whatever its size, and could not be undone. Now the confirm names the item + * count, a big collection needs its name typed, the success toast carries an + * Undo that restores it, and Settings lists archived collections to restore. + */ +const api = vi.hoisted(() => ({ + del: vi.fn(), + restore: vi.fn(), + archived: vi.fn() +})); +const toastShow = vi.hoisted(() => vi.fn()); + +vi.mock('$lib/api/client', () => ({ + api: { + collections: { + update: vi.fn(), + list: vi.fn().mockResolvedValue([]), + delete: (...a: unknown[]) => api.del(...a), + restore: (...a: unknown[]) => api.restore(...a), + archived: (...a: unknown[]) => api.archived(...a) + }, + items: { listByCollection: vi.fn().mockResolvedValue([]) } + }, + isConflictOrNotFound: () => false +})); +vi.mock('$lib/stores/toast.svelte', () => ({ + toastStore: { show: toastShow, dismiss: vi.fn(), get toasts() { return []; } } +})); + +const { default: EditCollectionModal } = await import('./EditCollectionModal.svelte'); +const { default: ArchivedCollections } = await import('./ArchivedCollections.svelte'); + +let host: HTMLElement; +let app: Record | null = null; + +async function settle(): Promise { + flushSync(); + for (let i = 0; i < 8; i++) { + await Promise.resolve(); + await tick(); + } + flushSync(); +} + +function coll(itemCount: number): Collection { + return { + id: 'c1', + slug: 'field-notes', + name: 'Field Notes', + icon: '', + description: '', + prefix: 'FN', + schema: JSON.stringify({ fields: [] }), + settings: '{}', + is_default: false, + item_count: itemCount, + updated_at: '2026-10-08T00:00:00Z' + } as unknown as Collection; +} + +function button(text: RegExp): HTMLButtonElement | undefined { + return [...document.querySelectorAll('button')].find((b) => text.test(b.textContent?.trim() ?? '')); +} + +beforeEach(() => { + host = document.createElement('div'); + document.body.appendChild(host); + api.del.mockReset().mockResolvedValue(undefined); + api.restore.mockReset().mockResolvedValue({ id: 'c1', slug: 'field-notes', name: 'Field Notes' }); + api.archived.mockReset(); + toastShow.mockReset(); +}); + +afterEach(() => { + if (app) unmount(app as never); + app = null; + host.remove(); +}); + +async function openConfirm(itemCount: number) { + app = mount(EditCollectionModal, { + target: host, + props: { open: true, collection: coll(itemCount), wsSlug: 'ws', onclose: () => {}, onupdated: () => {} } + }) as Record; + await settle(); + button(/^Archive collection$/)!.click(); + await settle(); +} + +describe('archive confirm', () => { + it('names the item count, and a small collection needs no typing', async () => { + await openConfirm(3); + expect(document.body.textContent?.replace(/\s+/g, ' ')).toContain('Archive "Field Notes" and its 3 items?'); + expect(document.body.textContent).not.toMatch(/can't be undone/); + expect(document.body.textContent).toContain('restore it any time'); + expect(document.querySelector('.danger-zone-typed')).toBeNull(); + expect(button(/^Yes, archive$/)!.disabled).toBe(false); + }); + + it('a collection of 25 or more items needs its name typed first', async () => { + await openConfirm(25); + const yes = button(/^Yes, archive$/)!; + expect(yes.disabled).toBe(true); + const input = document.querySelector('.danger-zone-typed input')!; + input.value = 'Field Note'; + input.dispatchEvent(new Event('input', { bubbles: true })); + await settle(); + expect(yes.disabled).toBe(true); + input.value = 'Field Notes'; + input.dispatchEvent(new Event('input', { bubbles: true })); + await settle(); + expect(yes.disabled).toBe(false); + yes.click(); + await settle(); + expect(api.del).toHaveBeenCalledTimes(1); + }); + + it('an UNKNOWN item count fails closed: the name must be typed', async () => { + await openConfirm(undefined as unknown as number); + expect(document.querySelector('.danger-zone-typed')).not.toBeNull(); + expect(button(/^Yes, archive$/)!.disabled).toBe(true); + }); + + it('the success toast carries an Undo that restores the collection by id', async () => { + await openConfirm(2); + button(/^Yes, archive$/)!.click(); + await settle(); + const call = toastShow.mock.calls.find((c) => String(c[0]).startsWith('Archived')); + expect(call, 'an Archived toast').toBeTruthy(); + const action = call![4] as { label: string; onAction: () => void }; + expect(action.label).toBe('Undo'); + action.onAction(); + await settle(); + expect(api.restore).toHaveBeenCalledWith('ws', 'c1'); + expect(toastShow.mock.calls.some((c) => String(c[0]).startsWith('Restored'))).toBe(true); + }); +}); + +describe('Settings › Collections › Archived collections', () => { + const archived: ArchivedCollection[] = [ + { id: 'c1', name: 'Field Notes', slug: 'field-notes', prefix: 'FN', item_count: 214, archived_at: '2026-10-08T00:00:00Z' } + ]; + + it('lists archived collections with their counts and restores one', async () => { + api.archived.mockResolvedValue(archived); + const onrestored = vi.fn(); + app = mount(ArchivedCollections, { target: host, props: { wsSlug: 'ws', refreshKey: 'a', onrestored } }) as Record; + await settle(); + expect(document.body.textContent).toContain('Field Notes'); + expect(document.body.textContent).toContain('214 items'); + button(/^Restore$/)!.click(); + await settle(); + expect(api.restore).toHaveBeenCalledWith('ws', 'c1'); + expect(onrestored).toHaveBeenCalledOnce(); + expect(document.querySelector('[data-testid="archived-collections"]')).toBeNull(); + }); + + it('renders nothing when nothing is archived', async () => { + api.archived.mockResolvedValue([]); + app = mount(ArchivedCollections, { target: host, props: { wsSlug: 'ws', refreshKey: 'a' } }) as Record; + await settle(); + expect(document.querySelector('[data-testid="archived-collections"]')).toBeNull(); + }); +}); diff --git a/web/src/lib/components/items/childIdentityFencePopulation.test.ts b/web/src/lib/components/items/childIdentityFencePopulation.test.ts index 3fc8fdc91..00fa8fd0f 100644 --- a/web/src/lib/components/items/childIdentityFencePopulation.test.ts +++ b/web/src/lib/components/items/childIdentityFencePopulation.test.ts @@ -297,6 +297,14 @@ const KNOWN_CONTINUATIONS: Record = { 'lib/components/items/CopyItemDialog.svelte::::tick.then': 'ui: focus', 'lib/components/items/CopyItemDialog.svelte::resetForOpen::loadDestCollections.then': 'fenced: flowGen and identityFence() captured in resetForOpen; selects the BUG-3200 preset only from the list loadDestCollections fenced', + // TASK-2189: the archive toast's Undo. The toast outlives the modal, so it + // carries the identity epoch captured at archive time, as the workspace + // delete's Undo does (BUG-3006), and both continuations re-check it before + // toasting. + 'lib/components/collections/EditCollectionModal.svelte::onAction::api.collections.restore.then': + 'fenced: authStore.identityEpoch compared with the epoch captured at archive time (TASK-2189)', + 'lib/components/collections/EditCollectionModal.svelte::onAction::api.collections.restore.catch': + 'fenced: authStore.identityEpoch compared with the epoch captured at archive time (TASK-2189)', }; diff --git a/web/src/lib/types/index.ts b/web/src/lib/types/index.ts index 58edd42c0..e1b3422fe 100644 --- a/web/src/lib/types/index.ts +++ b/web/src/lib/types/index.ts @@ -3167,3 +3167,18 @@ export interface ImportOutcome { workspace_name?: string; owner_username?: string; } + +/** + * An archived collection, from `GET /workspaces/{ws}/archived-collections` + * (TASK-2189). Archiving hides the collection and its items; nothing is + * deleted, and `api.collections.restore` brings both back. + */ +export interface ArchivedCollection { + id: string; + name: string; + slug: string; + prefix: string; + icon?: string; + item_count: number; + archived_at: string; +} diff --git a/web/src/routes/[username]/[workspace]/settings/+page.svelte b/web/src/routes/[username]/[workspace]/settings/+page.svelte index 7340f2bd0..2d8dfabe9 100644 --- a/web/src/routes/[username]/[workspace]/settings/+page.svelte +++ b/web/src/routes/[username]/[workspace]/settings/+page.svelte @@ -12,6 +12,7 @@ import { parseSchema } from '$lib/types'; import CreateCollectionModal from '$lib/components/collections/CreateCollectionModal.svelte'; import EditCollectionModal from '$lib/components/collections/EditCollectionModal.svelte'; + import ArchivedCollections from '$lib/components/collections/ArchivedCollections.svelte'; import StorageTab from '$lib/components/settings/StorageTab.svelte'; import AppsTab from '$lib/components/settings/apps/AppsTab.svelte'; import Chip from '$lib/components/common/Chip.svelte'; @@ -1236,6 +1237,13 @@ onclose={() => (showCreateModal = false)} /> {/if} + {#if isOwner} + c.id).join(',')} + onrestored={() => void refreshCollections(wsSlug)} + /> + {/if} {#if editingCollection && isOwner}