fix(reminders): acknowledge a fired reminder by item ref (BUG-4501)

pad item ack, the MCP ack-reminder action and the new POST /items/{ref}/reminders/ack acknowledge an item's single fired, unacknowledged reminder by item ref. Several such reminders are refused with 409 ambiguous_reminder listing their ids, and none is acknowledged. The by-id form is unchanged.

Claude-Session: https://claude.ai/code/session_01Pa22hKB7tBpTaVu7Jk6tmg
This commit is contained in:
xarmian
2026-11-12 05:41:10 +00:00
parent e39645a66e
commit 7735ee40fc
25 changed files with 429 additions and 42 deletions
+2 -2
View File
@@ -402,7 +402,7 @@ directory for `claude-code`, and an `[mcp_servers.pad]` table in
project-scoped, it's install-on-request only — `--all` and `pad mcp status` cover
the per-user clients (including Codex) and skip it.
**Tool catalog (v0.112)** — eleven 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.113)** — eleven 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 |
|---|---|
@@ -427,7 +427,7 @@ Plus resources at `pad://workspaces`, `pad://workspace/{ws}/dashboard`,
and `pad://_meta/version`.
**Stability contract.** The catalog is versioned
(`tool_surface_version: "0.112"`) and advertised in the initialize handshake and at
(`tool_surface_version: "0.113"`) 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
+2
View File
@@ -304,6 +304,8 @@ func TestChatArmHasNoMCPPath(t *testing.T) {
// no window before they dispatch (TASK-4105); the shared `to` is a
// number for chat read.
switch action {
case "ack-reminder":
delete(input, "ref") // ref and reminder_id are alternatives.
case "schedule-forecast":
input["forecast"] = "2031-03-12"
case "schedule-edit":
+17 -4
View File
@@ -5,9 +5,11 @@ import (
"text/tabwriter"
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/PerpetualSoftware/pad/internal/cli"
"github.com/PerpetualSoftware/pad/internal/models"
)
// `pad remind` (alias `pad item remind`) and friends — the CLI half of IDEA-2641 / GitHub #1010.
@@ -191,11 +193,16 @@ reminder existed and went out.`,
func ackCmd() *cobra.Command {
return &cobra.Command{
Use: "ack <reminder-id>",
Short: "Acknowledge a fired reminder",
Example: ` pad item ack <reminder-id>`,
Use: "ack <reminder-id|ref>",
Short: "Acknowledge a fired reminder by id or item ref",
Example: ` pad item ack 67ec8261-505f-4ddc-8d40-fbb1393bb649
pad item ack TASK-9`,
Long: `Acknowledge a reminder that has fired, removing it from 'pad project next'.
Pass a reminder UUID or an item ref. An item ref acknowledges its sole fired,
unacknowledged reminder that is not managed by a schedule. If several match,
nothing is acknowledged: use a reminder id from the refusal instead.
Nothing else acknowledges a reminder. In particular, completing the item does
NOT: a reminder may have been armed precisely to fire after the work was done,
and consuming it on a status change would throw that away. A reminder on a
@@ -206,7 +213,13 @@ table, still unacknowledged, exactly as you left it.`,
client, _ := getClient()
ws := getWorkspace()
r, err := client.AckReminder(ws, args[0])
var r *models.Reminder
var err error
if _, parseErr := uuid.Parse(args[0]); parseErr == nil {
r, err = client.AckReminder(ws, args[0])
} else {
r, err = client.AckItemReminder(ws, args[0])
}
if err != nil {
return err
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/PerpetualSoftware/pad/internal/cli"
)
func TestItemAckAmbiguityEmitsStructuredError(t *testing.T) {
var out bytes.Buffer
writeRootStructuredError(&out, &cli.APIError{Code: "ambiguous_reminder", Message: "2 fired reminders; ack by id"})
if !strings.Contains(out.String(), cli.StructuredErrorMarker) || !strings.Contains(out.String(), `"code":"ambiguous_reminder"`) {
t.Fatalf("missing ambiguity marker: %s", out.String())
}
}
func TestItemAckRoutesUUIDAndRef(t *testing.T) {
for _, tc := range []struct{ arg, path string }{
{"67ec8261-505f-4ddc-8d40-fbb1393bb649", "/reminders/67ec8261-505f-4ddc-8d40-fbb1393bb649/ack"},
{"TASK-9", "/items/TASK-9/reminders/ack"},
} {
t.Run(tc.arg, func(t *testing.T) {
setTempHomeMain(t)
var method, path string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
method, path = r.Method, r.URL.Path
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"67ec8261-505f-4ddc-8d40-fbb1393bb649","acked_at":"2026-11-12T12:00:00Z"}`))
}))
t.Cleanup(srv.Close)
t.Setenv("PAD_URL", srv.URL)
t.Setenv("PAD_TOKEN", "pad_envtoken")
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(cwd, ".pad.toml"), []byte("workspace = \"ws1\"\n"), 0644); err != nil {
t.Fatal(err)
}
cmd := ackCmd()
cmd.SetArgs([]string{tc.arg})
captureStdout(t, func() { err = cmd.Execute() })
if err != nil {
t.Fatal(err)
}
if method != "POST" || path != "/api/v1/workspaces/ws1"+tc.path {
t.Fatalf("got %s %s, want POST %s", method, path, tc.path)
}
})
}
}
+2
View File
@@ -86,6 +86,8 @@ func writeRootStructuredError(w io.Writer, err error) {
if errors.As(err, &commitmentErr) {
structured := false
switch commitmentErr.Code {
case "ambiguous_reminder":
structured = true
case "invalid_body":
structured = cli.IsCommitmentRoute(commitmentErr.RequestPath)
case "hard_deadline", "deadline_owner_required", "commitment_changed",
+1 -1
View File
@@ -92,7 +92,7 @@ func TestReminderCommandsExposeTheArgsMCPExpects(t *testing.T) {
// declaring it required would be a machine-readable claim the command
// contradicts.
{"item remind", []string{"ref"}, []bool{false}},
{"item ack", []string{"reminder-id"}, []bool{true}},
{"item ack", []string{"value"}, []bool{true}},
{"item reminders", []string{"ref"}, []bool{true}},
{"item unremind", []string{"reminder-id"}, []bool{true}},
} {
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -74,6 +74,7 @@ REST API at `/api/v1/`. Key endpoints:
- `GET /workspaces/{ws}/builtins` — every item made from a built-in with its state, for the library page: one join, and an item is listed only when the caller sees its whole collection (an item-grant guest is shown none)
- `POST /workspaces/{ws}/attachments/{id}/attach {item}` — bind an UNATTACHED attachment (item_id NULL, what `pad attachment upload -` leaves) and its variants to an item (TASK-2247). Share pages serve only attachments the shared item (or an item in the shared collection) owns, so an embedded `-` upload renders as a placeholder there until it is attached. Never a move: an attached row answers 409 when the caller can see its owner, otherwise the shared attachment 404. The caller must be able to see and edit the item, and must have uploaded the attachment or be a workspace owner; restricted members and guests cannot read unattached rows, so they get the 404. Advertised as `attachment_attach` in `GET /server/capabilities`; the CLI (`pad attachment attach <id> <item-ref>`) refuses against a server without it. Not on MCP (`pad_attachment` has no upload)
- `GET/POST /workspaces/{ws}/items/{slug}/reminders` — item reminders (IDEA-2641). POST arms one; `remind_at` is an RFC3339 **instant** and a bare date is refused, not read as midnight
- `POST /workspaces/{ws}/items/{itemSlug}/reminders/ack` (BUG-4501) — acknowledge by item ref. Uses the same visibility, archived/deleted and edit-permission checks as arming a reminder. Candidates are fired, unacknowledged reminders with no `schedule_id`. Exactly one returns **200** with the acknowledged Reminder, the same shape as the id route. None returns **404 `not_found`**, `No fired, unacknowledged reminder on <ref>`. More than one returns **409 `ambiguous_reminder`**, with the count and instruction to acknowledge by id in the message and candidate ids in `details.reminder_ids`; nothing is acknowledged. Managed reminders are excluded, even when fired. If the candidate is re-armed before the ack, the response is **409 `reminder_not_fired`**; if removed, **404 `not_found`**, as on the id route. CLI: `pad item ack <reminder-id|ref>` (UUIDs retain the id route).
- `PATCH/DELETE /workspaces/{ws}/reminders/{id}`, `POST /workspaces/{ws}/reminders/{id}/ack` — re-arm (clears both fire marks), disarm, acknowledge. Permission is the ITEM's; the reminder has no separate owner. A reminder with a `schedule_id` is MANAGED by the item's schedule: re-arm, ack and delete answer `409 reminder_managed` (`details.schedule_id`), after the visibility, archived and edit checks and before the body is read. Resolve it with `POST .../commitment/resolve`, or change or delete the schedule instead (see **Item schedules**). `schedule_id` and `occurrence_at` are additive members of reminder objects wherever they appear (the item reminders list, pending reminders on the dashboard and bootstrap, the `item.reminder_due` payload's `reminder`). The `item.reminder_due` payload's `reminder` also carries `fire_stamp`, a nanosecond UTC stamp taken once in the transaction that won the fire (omitted everywhere else, and on a snapshot that is not a fire). The reminder notification's dedupe key is built from it (`reminder:<id>:<fire_stamp>`, and `reminder:<id>:<occurrence_at>:<fire_stamp>` for a managed row), so a re-armed reminder that fires again, even inside the same second, is a new notification, and a redelivery of one fire is the same one
- `POST /workspaces/{ws}/items/{slug}/claim` and `/release`: the item execution lease (#1221). Body `{holder?, worker_id?, ttl_seconds?}` (ttl on claim only: default 900, 1 to 86400, else 400). Needs edit permission and a signed-in user. A re-claim by the live holder extends the expiry and keeps `acquired_at` (the heartbeat). Release is idempotent: an absent or expired lease answers `released: false`. Expiry is absence on every read, with no reaper. **Identity (TASK-3613):** `X-Pad-Agent` and `X-Pad-Worker` also identify event-stream presence; see **Sessions and presence** below. A lease is held under a WORKER ID plus the account. `worker_id` is `"wk_"` + 32 lowercase hex (128 random bits) that the client mints once per agent session (the CLI stores it in its session registry and sends it as `X-Pad-Worker`); a malformed one is `400 invalid_worker_id`. It comes from the body, else `X-Pad-Worker`, else a `?worker_id=` query, else, for a remote MCP call, an id derived from the account and the MCP session. A lease with a worker id is the caller's iff the worker id AND the account match; `holder` (default: the `X-Pad-Agent` name, else the email) is then display only. A lease without one (a name-only caller, or one claimed before migration 142) keeps the older rule: label plus account, with an unrecorded account honoured on the label alone (BUG-3341). A worker refreshing its own name-only lease binds it. A name-only caller never matches a worker-bound lease, even under the same label: that is refused `409 lease_held`, and the message says how to get a worker id. A contended claim or release answers `409 lease_held` with `details: {ref, holder, worker?, acquired_at, expires_at}`, where `worker` is the SHORT id (`wk_3f2a`). The full id appears only in the claim's own success answer (`worker_id`, for resume); reads (`item.lease`, list decoration) show `holder` and the short `worker`. `GET /next` and the dashboard's `suggested_next` leave out items whose live lease a claim by the same identity would lose, by the same predicate (`store.leaseOurs`).
- `GET/POST /workspaces/{ws}/items/{slug}/verifications` — verification evidence tied to a revision (TASK-3617). One row is one verdict (`pass` / `fail` / `cant_tell`) on one acceptance criterion (`AC-N`) of the item that CARRIES the criteria, optionally at a `code_revision` (full 40-hex SHA) and naming the item that did the work (`via`). POST takes `{run_id?, code_revision?, via?, results: [{criterion, verdict, evidence?, evidence_url?}]}` (at most 100 results; evidence at most 2048 bytes; `evidence_url` an absolute http(s) URL) and is atomic: one bad result refuses the batch. A criterion that is missing, still a placeholder, or appears more than once in the BODY is `400 unknown_criterion`, with `details.criteria` listing the valid ids; a criterion named twice in one REQUEST is a malformed request, `400 validation_error`. A `via` that does not resolve in the workspace, or names an item the caller cannot see, is one answer: `400 unknown_via`. The write is guarded by the item's seq: the criterion hashes are stored against the body they were parsed from, and an item that keeps changing during the write answers `409 item_changed`. Needs edit permission on the item; the read follows item visibility. Writes log a `verified` activity (metadata: `run_id`, a verdict count, never evidence text) and publish `item_updated`. GET returns `{ref, criteria, verifications}`, the newest verdict per criterion in body order, or the whole history with `?all=1`. Each row's `state` is computed at read time from the criterion, never from the item's seq: `criterion_removed` (no longer a real criterion), `criterion_changed` (its text changed since the verdict; whitespace is collapsed first, so re-wrapping is not a change), `superseded` (a newer verdict exists), else `current`. `possibly_stale: {via: "PR #N", merged_sha, merged_at}` is ADVISORY and never changes `state`: a merged `github_pr` on the item, or on its visible `via` item, merged after the verdict at a different SHA. It needs `github_pr.merge_sha` / `merged_at`, which `pad github link` and `pad reconcile` now record (`merge_sha` must be a full 40-hex SHA, `merged_at` RFC3339, or the PR write is `400`). Rows are append-only and travel with a workspace export/import (so `pad db migrate-to-pg` carries them), verbatim except for the remapped item and via ids; the verifier's user id does not travel, and a malformed bundle row is dropped rather than failing the import. They survive an archive and restore, are removed by a hard delete of the item, are not cloned by a copy (the copy's dropped bucket does not report them yet), and outlive a deleted `via` item (whose ref is then omitted)
+4 -4
View File
File diff suppressed because one or more lines are too long
+7
View File
@@ -3570,6 +3570,13 @@ func (c *Client) AckReminder(wsSlug, reminderID string) (*models.Reminder, error
return &result, c.post("/workspaces/"+url.PathEscape(wsSlug)+"/reminders/"+url.PathEscape(reminderID)+"/ack", nil, &result)
}
// AckItemReminder acknowledges the item's sole fired, unacknowledged unmanaged reminder.
// Multiple candidates are refused without acknowledging any of them.
func (c *Client) AckItemReminder(wsSlug, itemRef string) (*models.Reminder, error) {
var result models.Reminder
return &result, c.post("/workspaces/"+url.PathEscape(wsSlug)+"/items/"+url.PathEscape(itemRef)+"/reminders/ack", nil, &result)
}
// DeleteReminder disarms a reminder by removing it.
func (c *Client) DeleteReminder(wsSlug, reminderID string) error {
return c.delete("/workspaces/" + url.PathEscape(wsSlug) + "/reminders/" + url.PathEscape(reminderID))
+62
View File
@@ -0,0 +1,62 @@
package mcp
import (
"context"
"strings"
"testing"
)
func TestAckReminderByRefDispatch(t *testing.T) {
for _, tc := range []struct{ key, value, path string }{
{"ref", "TASK-9", "/items/TASK-9/reminders/ack"},
{"reminder_id", "67ec8261-505f-4ddc-8d40-fbb1393bb649", "/reminders/67ec8261-505f-4ddc-8d40-fbb1393bb649/ack"},
} {
t.Run(tc.key, func(t *testing.T) {
in := map[string]any{tc.key: tc.value}
res, seen := remoteCall(t, "ack-reminder", in)
if res.IsError || len(seen) != 1 {
t.Fatalf("result = %+v, requests = %+v", res, seen)
}
if seen[0].Method != "POST" || seen[0].Path != "/api/v1/workspaces/docapp"+tc.path {
t.Fatalf("request = %+v", seen[0])
}
local, disp := stdioCall(t, "ack-reminder", in)
if local.IsError {
t.Fatalf("local = %+v", local)
}
if pos := cliPositionals(disp.gotArgs); len(pos) != 1 || pos[0] != tc.value {
t.Fatalf("CLI args = %v", disp.gotArgs)
}
})
}
}
func TestAckReminderRejectsBothParams(t *testing.T) {
in := map[string]any{"ref": "TASK-9", "reminder_id": "67ec8261-505f-4ddc-8d40-fbb1393bb649"}
res, seen := remoteCall(t, "ack-reminder", in)
if !res.IsError || len(seen) != 0 {
t.Fatalf("result = %+v, requests = %+v", res, seen)
}
if code := envelopeFrom(res).Error.Code; code != ErrValidationFailed {
t.Fatalf("code = %s", code)
}
res, disp := stdioCall(t, "ack-reminder", in)
if !res.IsError || len(disp.gotArgs) != 0 {
t.Fatalf("local result = %+v, args = %v", res, disp.gotArgs)
}
}
func TestAmbiguousReminderErrorParity(t *testing.T) {
body := `{"error":{"code":"ambiguous_reminder","message":"2 fired reminders; ack by id","details":{"reminder_ids":["r1","r2"]}}}`
httpResult := classifyHTTPStatus(context.Background(), "item ack", 409, []byte(body), nil)
stdioResult := extractStructuredCLIError(structuredErrorMarker + body)
if stdioResult == nil {
t.Fatal("structured CLI error was not extracted")
}
for _, res := range []*CallToolResult{httpResult, stdioResult} {
p := envelopeFrom(res).Error
if string(p.Code) != "ambiguous_reminder" || !strings.Contains(string(p.Details), "r1") {
t.Fatalf("error = %+v", p)
}
}
}
+25 -6
View File
@@ -100,7 +100,7 @@ var padItemTool = ToolDef{
// parameter makes it one. The rest of the schedule surface rides
// `pad item remind <subcommand>`; see catalog_item_schedule.go.
"remind": actionItemRemind,
"ack-reminder": passThrough([]string{"item", "ack"}),
"ack-reminder": actionItemAckReminder,
"reminders": passThrough([]string{"item", "reminders"}),
"unremind": passThrough([]string{"item", "unremind"}),
@@ -191,7 +191,7 @@ var padItemTool = ToolDef{
// keeping the schema simple to maintain.
var padItemSchemaParams = []ParamDef{
// ── Targeting ──
{Name: "ref", Type: "string", Description: "Item reference (e.g. TASK-5, PLAYB-3). Required for every action naming one item, except create, list, starred, import, agenda, bulk-update (use `refs`) and ack-reminder / unremind (use `reminder_id`: an item can carry several reminders)."},
{Name: "ref", Type: "string", Description: "Item reference (e.g. TASK-5). Required for actions naming one item, except create, list, starred, import, agenda, bulk-update (use refs) and unremind. ack-reminder: ref OR reminder_id; multiple fired reminders require an id."},
{Name: "refs", Type: "array<string>", Description: "Item references for batch operations. Required: bulk-update (one or more refs)."},
{Name: "target", Type: "string", Description: "The OTHER end of a relationship. Required: link, unlink. blocks: the item being blocked; blocked-by: the blocker; supersedes: the superseded item."},
{Name: "link_type", Type: "string", Description: "Type of relationship for action=link/unlink.", Enum: []string{"blocks", "blocked-by", "supersedes", "implements", "split-from"}},
@@ -218,7 +218,7 @@ var padItemSchemaParams = []ParamDef{
{Name: "pr_state", Type: "string", Description: "The pull request's state as you know it (e.g. open, merged, closed). For: link-pr. Pad does not check it against GitHub."},
{Name: "pr_branch", Type: "string", Description: "The pull request's head branch. For: link-pr."},
{Name: "pr_repo", Type: "string", Description: "The pull request's repository, owner/name. For: link-pr."},
{Name: "reminder_id", Type: "string", Description: "A reminder's id: the `id` returned when it was armed, or a row's `id` from action=reminders. Required: ack-reminder, unremind."},
{Name: "reminder_id", Type: "string", Description: "Reminder id from arming or action=reminders. Required for unremind. ack-reminder accepts reminder_id OR ref, never both."},
// ── Schedules ── (TASK-4105)
{Name: "every", Type: "string", Description: "Repeat rule: daily, weekdays, weekly, biweekly, monthly, monthly-last, quarterly, yearly, or an RRULE. For remind (schedule) and schedule-edit."},
@@ -480,9 +480,9 @@ Actions:
schedule-delete — Irreversibly delete schedule/rule/history/managed reminder; stops pending firing. ref required. Keeps item/comments/one-shot reminders.
agenda — Occurrences/dated items: from, to (RFC3339, <=92 days); tz optional.
no_date_scope:personal_only means undated work is not listed, never empty. /me/agenda priority_list/waiting_on/no_date contain work assigned to the caller, else created by them, for their human/agent audience.
ack-reminder — Acknowledge fired reminder; leaves next/ready. Required: reminder_id
(fired suggestion/arming response, NOT item ref). Only this acknowledges; completing
the item does not. Reminders may fire after work finishes.
ack-reminder — Acknowledge by reminder_id OR ref, never both; leaves next/ready.
ref requires one fired, unacknowledged unmanaged reminder; multiple refuse, ack by id.
Only this acknowledges; completing the item does not. Reminders may fire after work finishes.
reminders — Armed/fired/acknowledged reminders; ref required. Row id is reminder_id for unremind/ack-reminder (fired only).
unremind — Disarm/delete by reminder_id (from reminders or arming response).
claim — Atomic execution lease. Required: ref. Optional: holder, worker_id, ttl
@@ -607,6 +607,25 @@ var itemLinkRoutes = map[string]itemLinkRoute{
},
}
func actionItemAckReminder(ctx context.Context, input map[string]any, env ActionEnv) (*CallToolResult, error) {
ref, _ := input["ref"].(string)
id, _ := input["reminder_id"].(string)
if (ref == "") == (id == "") {
return errStructured("pad_item.ack-reminder", fmt.Errorf("provide either reminder_id or ref, never both")), nil
}
out := make(map[string]any, len(input)+1)
for k, v := range input {
out[k] = v
}
// cmdhelp names an alternation (<reminder-id|ref>) "value".
// Keep the original parameter so HTTP dispatch preserves its meaning.
out["value"] = id
if ref != "" {
out["value"] = ref
}
return env.Dispatch(ctx, []string{"item", "ack"}, out)
}
// actionItemLink dispatches pad_item.action=link to the appropriate
// CLI cmdPath based on link_type. Renames the schema's uniform `ref`
// and `target` to the type-specific positional arg names (source_ref/
+2 -3
View File
@@ -391,8 +391,7 @@ func TestReadOnlyCatalog_ActionsDispatchExpectedCmdPath(t *testing.T) {
"code": "123456",
// pad_attachment.show needs an attachment_id positional.
"attachment_id": "att-1",
// pad_item.ack-reminder addresses a REMINDER, not an item — an item
// can carry several, so `ref` cannot name one (IDEA-2641).
// Exercise the by-id ack form; the per-action fixture removes ref.
"reminder_id": "rem-1",
"remind_at": "2026-08-01T09:00:00Z",
// pad_item.schedule-resolve needs the state and the occurrence it
@@ -804,7 +803,7 @@ func liveCmdhelpDoc(t *testing.T) *cmdhelp.Document {
}()},
"item ack": {
Summary: "acknowledge a fired reminder",
Args: mkArgs("reminder-id"),
Args: mkArgs("value"),
Flags: mkFlags("workspace"),
},
"item reminders": {
+7 -4
View File
@@ -493,10 +493,13 @@ func init() {
pathTemplate: "/api/v1/workspaces/{workspace}/agenda",
queryParams: map[string]string{"from": "from", "to": "to", "tz": "tz", "stale": "stale"},
}.toRouteMapper(),
"item ack": routeSpec{
method: http.MethodPost,
pathTemplate: "/api/v1/workspaces/{workspace}/reminders/{reminder_id}/ack",
}.toRouteMapper(),
"item ack": func(input map[string]any) (string, string, []byte, error) {
path := "/api/v1/workspaces/{workspace}/reminders/{reminder_id}/ack"
if ref, _ := input["ref"].(string); ref != "" {
path = "/api/v1/workspaces/{workspace}/items/{ref}/reminders/ack"
}
return (routeSpec{method: http.MethodPost, pathTemplate: path}).toRouteMapper()(input)
},
// TASK-3611: list an item's reminders, and disarm one by id.
"item reminders": routeSpec{
method: http.MethodGet,
+1
View File
@@ -519,6 +519,7 @@ const storedStateUnreadableHint = "Retrying will not help — the item's stored
// declarations block at the top of this file should also be added
// for type safety in test assertions.
var allowedStructuredErrorCodes = map[string]struct{}{
"ambiguous_reminder": {}, // BUG-4501: acknowledge by id to disambiguate.
"invalid_body": {},
"schedule_linked": {},
"deadline_approval_required": {},
+1 -1
View File
@@ -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.112)
## Tool surface (v0.113)
Eleven resource × action tools, plus `pad_set_workspace`. Twelve tools total.
+2
View File
@@ -26,6 +26,8 @@ import (
// is refused before dispatch.
func task4105FixtureFor(name string, in map[string]any) {
switch name {
case "pad_item.ack-reminder":
delete(in, "ref") // BUG-4501: ref and reminder_id are alternatives.
case "pad_item.schedule-forecast":
in["forecast"] = "2031-03-12"
case "item remind forecast set":
+3 -1
View File
@@ -2327,7 +2327,9 @@ const CmdhelpVersion = "0.1"
// v0.111 — TASK-4354: agenda and bootstrap return grouped date roles without
// kind, independent actionable groups and per-section completeness.
// v0.112 adds schedule-forecast: a hand-set estimate, set or clear, with provenance.
const ToolSurfaceVersion = "0.112"
// v0.113 — BUG-4501: additive ack-reminder by ref when exactly one unmanaged
// fired reminder is unacknowledged; reminder_id remains supported, both refuse.
const ToolSurfaceVersion = "0.113"
// MetaVersionURI is the canonical URI of the queryable version document.
// Lives outside the pad://workspace/{ws}/... namespace because it's a
+46 -4
View File
@@ -2,6 +2,7 @@ package server
import (
"errors"
"fmt"
"net/http"
"time"
@@ -174,6 +175,43 @@ func (s *Server) handleRearmReminder(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, updated)
}
// handleAckItemReminder acknowledges the sole pending, unmanaged reminder on an item.
// POST /api/v1/workspaces/{slug}/items/{itemSlug}/reminders/ack
func (s *Server) handleAckItemReminder(w http.ResponseWriter, r *http.Request) {
workspaceID, ok := s.getWorkspaceID(w, r)
if !ok {
return
}
item := s.resolveVisibleItem(w, r, workspaceID)
if item == nil {
return
}
if !s.requireEditPermission(w, r, workspaceID, item.ID, item.CollectionID) {
return
}
reminders, err := s.store.ListRemindersForItem(workspaceID, item.ID)
if err != nil {
writeInternalError(w, err)
return
}
var ids []string
for _, reminder := range reminders {
if reminder.PendingAck() && reminder.ScheduleID == nil {
ids = append(ids, reminder.ID)
}
}
switch len(ids) {
case 0:
writeError(w, http.StatusNotFound, "not_found", "No fired, unacknowledged reminder on "+item.Ref)
case 1:
s.ackReminder(w, workspaceID, ids[0])
default:
writeError2(w, http.StatusConflict, "ambiguous_reminder",
fmt.Sprintf("%d fired, unacknowledged reminders on %s; acknowledge by id instead", len(ids), item.Ref),
map[string]interface{}{"reminder_ids": ids})
}
}
// handleAckReminder acknowledges a fired reminder.
// POST /api/v1/workspaces/{slug}/reminders/{reminderID}/ack
func (s *Server) handleAckReminder(w http.ResponseWriter, r *http.Request) {
@@ -186,7 +224,12 @@ func (s *Server) handleAckReminder(w http.ResponseWriter, r *http.Request) {
return
}
acked, err := s.store.AckReminder(workspaceID, reminder.ID)
s.ackReminder(w, workspaceID, reminder.ID)
}
// ackReminder keeps the by-id and by-item doors' store and race handling identical.
func (s *Server) ackReminder(w http.ResponseWriter, workspaceID, reminderID string) {
acked, err := s.store.AckReminder(workspaceID, reminderID)
if errors.Is(err, store.ErrReminderManaged) {
writeReminderManaged(w, "")
return
@@ -202,9 +245,8 @@ func (s *Server) handleAckReminder(w http.ResponseWriter, r *http.Request) {
// fresh read tells apart. The earlier form decided 409-vs-200 from the
// row resolveReminderForWrite read before the UPDATE, and a fire or
// re-arm landing in between made it answer for a state that had
// already stopped holding. The variable is still called `reminder`
// above only because the resolver's permission checks need it.
current, err := s.store.GetReminder(workspaceID, reminder.ID)
// already stopped holding.
current, err := s.store.GetReminder(workspaceID, reminderID)
if err != nil {
writeInternalError(w, err)
return
@@ -0,0 +1,174 @@
package server
import (
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"github.com/PerpetualSoftware/pad/internal/models"
)
func TestAckItemReminderCandidates(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
fired, armed, acked int
managed bool
status int
code string
}{
{"one", 1, 1, 1, false, 200, ""},
{"zero", 0, 0, 0, false, 404, "not_found"},
{"two", 2, 0, 0, false, 409, "ambiguous_reminder"},
{"armed only", 0, 1, 0, false, 404, "not_found"},
{"acked only", 0, 0, 1, false, 404, "not_found"},
{"managed only", 0, 0, 0, true, 404, "not_found"},
{"one and managed", 1, 0, 0, true, 200, ""},
} {
t.Run(tc.name, func(t *testing.T) {
srv := testServer(t)
slug := createWSWithCollections(t, srv)
item := createItem(t, srv, slug, "tasks", map[string]interface{}{"title": "Ack by ref"})
ws, err := srv.store.GetWorkspaceBySlug(slug)
if err != nil {
t.Fatal(err)
}
var candidates []string
for i := 0; i < tc.fired+tc.acked; i++ {
r := armViaAPI(t, srv, slug, item, pastInstant)
if _, err := srv.store.DB().Exec(`UPDATE item_reminders SET fired_at=? WHERE id=?`, pastInstant, r.ID); err != nil {
t.Fatal(err)
}
if i < tc.fired {
candidates = append(candidates, r.ID)
} else if _, err := srv.store.AckReminder(ws.ID, r.ID); err != nil {
t.Fatal(err)
}
}
for i := 0; i < tc.armed; i++ {
armViaAPI(t, srv, slug, item, futureInstant)
}
if tc.managed {
sc, err := srv.store.CreateSchedule(ws.ID, item.ID, models.ScheduleCreate{Kind: "check", Dtstart: "2031-03-10T09:00", Tz: "UTC"})
if err != nil {
t.Fatal(err)
}
if _, err := srv.store.DB().Exec(`UPDATE item_reminders SET fired_at=? WHERE schedule_id=?`, pastInstant, sc.ID); err != nil {
t.Fatal(err)
}
}
before, err := srv.store.ListRemindersForItem(ws.ID, item.ID)
if err != nil {
t.Fatal(err)
}
rr := doRequest(srv, "POST", "/api/v1/workspaces/"+slug+"/items/"+item.Ref+"/reminders/ack", nil)
if rr.Code != tc.status {
t.Fatalf("got %d %s, want %d", rr.Code, rr.Body.String(), tc.status)
}
if tc.code != "" {
var body struct {
Error struct {
Code, Message string
Details struct {
IDs []string `json:"reminder_ids"`
}
}
}
parseJSON(t, rr, &body)
if body.Error.Code != tc.code {
t.Errorf("code = %s", body.Error.Code)
}
if tc.status == 404 && body.Error.Message != "No fired, unacknowledged reminder on "+item.Ref {
t.Errorf("message = %q", body.Error.Message)
}
if tc.status == 409 {
if !strings.Contains(body.Error.Message, "2") || !strings.Contains(body.Error.Message, "id") {
t.Errorf("message = %q", body.Error.Message)
}
ids, _ := json.Marshal(body.Error.Details.IDs)
for _, id := range candidates {
if !strings.Contains(string(ids), id) {
t.Errorf("missing candidate %s in %s", id, ids)
}
}
}
} else {
var got models.Reminder
parseJSON(t, rr, &got)
if got.ID != candidates[0] || got.AckedAt == nil {
t.Errorf("acked = %+v", got)
}
}
for _, old := range before {
got, err := srv.store.GetReminder(ws.ID, old.ID)
if err != nil {
t.Fatal(err)
}
wantAcked := old.AckedAt != nil || (tc.status == 200 && old.ID == candidates[0])
if (got.AckedAt != nil) != wantAcked {
t.Errorf("reminder %s acked = %v, want %v", got.ID, got.AckedAt, wantAcked)
}
}
})
}
}
func TestAckItemReminderPermissions(t *testing.T) {
t.Parallel()
srv := testServer(t)
owner := mustUser(t, srv, "ack-owner@example.com", "ackowner", "")
ws := mustWorkspace(t, srv, "Ack permissions", owner.ID)
coll := mustCollection(t, srv, ws.ID, "Tasks")
visible := mustItem(t, srv, ws.ID, coll.ID, "Visible")
hidden := mustItem(t, srv, ws.ID, coll.ID, "Hidden")
guest := mustUser(t, srv, "ack-guest@example.com", "ackguest", "")
if _, err := srv.store.CreateItemGrant(ws.ID, visible.ID, guest.ID, "view", owner.ID); err != nil {
t.Fatal(err)
}
r, err := srv.store.CreateReminder(ws.ID, visible.ID, pastInstant)
if err != nil {
t.Fatal(err)
}
srv.runReminderTick()
tok, err := srv.store.CreateSession(guest.ID, testSessionUA, "192.0.2.1", "go-test", 24*time.Hour)
if err != nil {
t.Fatal(err)
}
base := "/api/v1/workspaces/" + ws.Slug + "/items/"
unknown := reminderWriteAs(srv, "POST", base+"TASK-999999/reminders/ack", nil, tok)
secret := reminderWriteAs(srv, "POST", base+hidden.ID+"/reminders/ack", nil, tok)
if secret.Code != http.StatusNotFound || secret.Code != unknown.Code || secret.Body.String() != unknown.Body.String() {
t.Fatalf("hidden = %d %s, unknown = %d %s", secret.Code, secret.Body.String(), unknown.Code, unknown.Body.String())
}
denied := reminderWriteAs(srv, "POST", base+visible.ID+"/reminders/ack", nil, tok)
if denied.Code != http.StatusForbidden {
t.Fatalf("view grant = %d %s", denied.Code, denied.Body.String())
}
got, err := srv.store.GetReminder(ws.ID, r.ID)
if err != nil {
t.Fatal(err)
}
if got.AckedAt != nil {
t.Fatal("refused ack changed reminder")
}
}
func TestAckItemReminderArchived(t *testing.T) {
t.Parallel()
srv := testServer(t)
slug := createWSWithCollections(t, srv)
item := createItem(t, srv, slug, "tasks", map[string]interface{}{"title": "Archived"})
armViaAPI(t, srv, slug, item, pastInstant)
srv.runReminderTick()
base := "/api/v1/workspaces/" + slug
if rr := doRequest(srv, "DELETE", base+"/items/"+item.Ref, nil); rr.Code != http.StatusNoContent {
t.Fatalf("archive: %d %s", rr.Code, rr.Body.String())
}
byCreate := doRequest(srv, "POST", base+"/items/"+item.Ref+"/reminders", nil)
byRef := doRequest(srv, "POST", base+"/items/"+item.Ref+"/reminders/ack", nil)
if byRef.Code != 409 || byRef.Body.String() != byCreate.Body.String() {
t.Fatalf("ack = %d %s, create = %d %s", byRef.Code, byRef.Body.String(), byCreate.Code, byCreate.Body.String())
}
}
+1
View File
@@ -2466,6 +2466,7 @@ func (s *Server) setupRouter() {
// about the item it names.
r.Get("/reminders", s.handleListItemReminders)
r.Post("/reminders", s.handleCreateItemReminder)
r.Post("/reminders/ack", s.handleAckItemReminder)
// Item schedules (TASK-4102): the time trigger whose
// outstanding occurrence is a managed reminder row.
r.Get("/commitment/links", s.handleListCommitmentLinks)
+2 -2
View File
@@ -134,7 +134,7 @@ Interpret the user's intent and route to the appropriate action. Here are common
**Querying:**
- "what's on my plate?" → role-filtered queue if a role is active, otherwise `pad project next`
- "remind me about this on <date>" / "revisit TASK-5 next Tuesday" → `pad remind` (IDEA-2641). The time is an **instant**, not a date — ask for a time of day rather than picking one, since the server refuses a bare date on purpose. A fired reminder shows up in `pad project next` / `ready` until someone runs `pad item ack <reminder-id>` — `next` prints the exact ack command under the entry, so you never have to go looking for the id; **finishing the item does not acknowledge it**, because a reminder is often armed precisely to fire after the work is done
- "remind me about this on <date>" / "revisit TASK-5 next Tuesday" → `pad remind` (IDEA-2641). The time is an **instant**, not a date — ask for a time of day rather than picking one, since the server refuses a bare date on purpose. A fired reminder shows up in `pad project next` / `ready` until someone runs `pad item ack <reminder-id|ref>` — `next` prints the exact ack command under the entry, so you never have to go looking for the id; **finishing the item does not acknowledge it**, because a reminder is often armed precisely to fire after the work is done
`pad remind forecast set|clear` sets a hand-set milestone estimate; it arms nothing and is never a missed deadline.
- "check this every weekday at 9" / "this is due Friday 5pm" / "what's on my agenda?" → a **schedule**: `pad remind TASK-5 --start 2026-11-09T09:00 --every weekdays` (`--deadline hard|soft` for a due time, `--window 2h` for a span). The start is a wall time in the user's zone (no `Z`, no offset); omit `--tz` unless asked, and the server pins the account zone. Resolve an occurrence with `pad remind done|skip|snooze|move TASK-5`; list with `pad remind agenda`. There is no `pad cal`.
@@ -224,7 +224,7 @@ pad item search "query"
pad item comment TASK-5 "..." [--reply-to <comment-id>] # or --stdin for a multi-line body; an empty one is refused
pad remind TASK-5 --remind-at 2026-08-01T09:00:00Z # arm a one-shot reminder (RFC3339 INSTANT; a bare date is refused)
pad item reminders TASK-5 # armed / fired / acknowledged
pad item ack <reminder-id> # acknowledge a fired reminder
pad item ack <reminder-id|ref> # ref: exactly one fired, unacknowledged unmanaged reminder; multiple require an id
pad item unremind <reminder-id>
pad remind TASK-5 --start 2026-11-09T09:00 --every weekdays # schedule (daily weekdays weekly biweekly monthly monthly-last quarterly yearly, or an RRULE)
pad remind TASK-5 --start 2026-11-14 --deadline hard # a due date (all-day) the item must not miss