From 838f5bf3d09b2e78f5bc9e200a9135fa06022eca Mon Sep 17 00:00:00 2001 From: Kevin Burchell Date: Tue, 6 Oct 2026 12:37:58 -0700 Subject: [PATCH] Hermes 1.4 + API v6: list_tags, check_items, notes inside notes, archived search filter, error codes in helper output Co-Authored-By: Claude Opus 5.5 --- hermes/README.md | 20 ++- hermes/brainfeed/SKILL.md | 29 +++- hermes/brainfeed/scripts/brainfeed.py | 17 ++- hermes/tests/test_api.py | 83 +++++++++++ supabase/functions/brainfeed-api/index.ts | 135 ++++++++++++++++-- .../20261006200000_hermes_14_tags.sql | 10 ++ 6 files changed, 265 insertions(+), 29 deletions(-) create mode 100644 supabase/migrations/20261006200000_hermes_14_tags.sql diff --git a/hermes/README.md b/hermes/README.md index c9c8f13..a374816 100644 --- a/hermes/README.md +++ b/hermes/README.md @@ -85,6 +85,8 @@ rebuild and re-import. |---|---| | `notes`, `reminders`, `settings` | RLS: `auth.uid() = user_id` for the web app. The API uses the service role but filters **every** query by the token's `user_id`; clients cannot send `user_id` (unknown fields → 400). | | `api_tokens` | `user_id, name, token_hash (sha256:<64 hex>, unique), created_at, last_used_at, revoked_at`. RLS: owners can see and add their own rows, and may update only `name` / `revoked_at` (column-level grant). They can never change a hash or the owner. | +| `bf_tag_counts(user)` | Tag → note count for non-archived notes, most-used first (same as the web app's tag list). `service_role` only. | +| trigger `notes_check_parent` | Nesting rules for every path: one level only, same owner, never itself. Its messages are passed through to the agent as 400s. | | `bf_claim_reminders(user, limit, lease)` | Atomic `UPDATE … FOR UPDATE SKIP LOCKED`: picks due, not-done, unclaimed reminders and stamps a `claim_id` plus a lease (default 5 min). `EXECUTE` is granted to `service_role` only. | | `bf_ack_reminders(user, claim_id)` | Marks a claim delivered. One-time → `done = true`. Repeating → `due_at` moves to the next future occurrence. Sets `last_sent_at`. `service_role` only. | | `private.next_occurrence(due, repeat, tz)` | Computed in the user's IANA zone and always offset from the original date, so 9:00 stays 9:00 across DST and the 31st stays the 31st (clamped in short months). | @@ -94,15 +96,18 @@ rebuild and re-import. ## API (base `https://bzvibdjrknqvmurwjroq.supabase.co/functions/v1/brainfeed-api`) All requests need the `X-BrainFeed-Token` header. Bodies are JSON objects, and unknown fields -are rejected. Errors come back as `{"error": code, "message": text}` with 400 / 401 / 404 / 413 / 500 / 503. +are rejected. Errors come back as `{"error": code, "message": text}` with 400 / 401 / 404 / 409 / 413 / 500 / 503. +The helper prints them as `BrainFeed API error (): `. | Method & path | Body | Returns | |---|---|---| | `GET /v1/status` | – | `ok, token, account (masked), timezone, now_local, notes, open_reminders` | -| `POST /v1/notes` | `body` (≤20k), `tags?[]`, `source?` (hermes / telegram / discord / sms) | `note` | -| `POST /v1/notes/search` | `q?` (words AND-ed, `#tag` filters), `tags?[]`, `pinned?`, `limit?` ≤50, `before?` ISO | `notes[]` newest first | -| `POST /v1/notes/get` | `id` | `note` | -| `POST /v1/notes/update` | `id`, `body?`, `add_tags?[]`, `remove_tags?[]`, `pinned?`, `archived?` (true hides from the feed, false restores) | `note` (hashtags re-derived from a new body; manual tags kept) | +| `POST /v1/notes` | `body` (≤20k), `tags?[]`, `source?` (hermes / telegram / discord / sms), `parent_id?` (save inside that note) | `note` | +| `POST /v1/notes/search` | `q?` (words AND-ed, `#tag` filters), `tags?[]`, `pinned?`, `limit?` ≤50, `before?` ISO, `archived?` (true = only archived, false = none; omitted = both), `parent_id?` (notes inside that note) | `notes[]` newest first | +| `POST /v1/notes/get` | `id` | `note`, `parent` (`id`, `first_line`) or null, `children[]` (`id`, `first_line`, `archived`), `checklist[]` (`n`, `done`, `text`) | +| `POST /v1/notes/update` | `id`, `body?`, `add_tags?[]`, `remove_tags?[]`, `pinned?`, `archived?` (true hides from the feed, false restores), `parent_id?` (note id = move inside, null = take out) | `note` (hashtags re-derived from a new body; manual tags kept) | +| `POST /v1/notes/check` | `id`, `check?[]` / `uncheck?[]` (item numbers, or item text: an exact case-insensitive match, else text found in exactly one item), `add?[]` (new items, after the last item, or a new list at the end) | `note`, `checked`, `unchecked`, `added`, `checklist[]`, `message` ("3/5 done"). Errors `no_match` / `ambiguous` (400). Written only if the note is unchanged since it was read (retried, then 409), so concurrent ticks never overwrite each other | +| `POST /v1/tags` | `limit?` ≤500 | `tags[]` (`tag`, `count`), non-archived notes, most-used first | | `POST /v1/notes/append` | `id`, `body` | `note` with `\n\n— Oct 4, 8:30 PM\n` added (stamp in the user's zone, built server-side). A single database UPDATE (`bf_append_note`), so concurrent appends never overwrite each other | | `POST /v1/calendar` | `from_local?` (`YYYY-MM-DD`, default today), `days?` 1–31 (default 7) | `overdue_before[]` (open reminders due before the range) and `days[]`: `date`, `weekday`, `reminders[]` (`time_local`, `repeat`, `status`: scheduled / overdue / repeat / done) and `notes[]` (non-archived, `first_line`). Repeats expanded with the same wall-clock, anchored, month-end-clamped rules as delivery | | `POST /v1/reminders` | `body` (≤2k), `due_at` (ISO **with** offset) **or** `due_local` (`YYYY-MM-DDTHH:MM` in the user's zone) **or** `dates_local` (list of 1–100 local times, at least one in the future; stored as repeat `dates`), `repeat?`, `source?` | `reminder` with `due_local` | @@ -182,7 +187,10 @@ or reminders. Without a terminal and without flags, it keeps the token and confi It covers: auth failures and refusal of the `Authorization` header; the token never appearing in output; cross-account isolation and `user_id` injection; note add/search/edit/tag rules; DST conversion; exclusive claims, lease expiry and retry, ack for one-time and repeating reminders, -late labels, reactivation rules; photos (caption + photo, photo-only, attach more, fake +late labels, reactivation rules; tag counts (archived excluded); checklist ticks by text and +number, exact-vs-partial matching, ambiguous/no-match errors, starting a new list, concurrent ticks +all landing; nesting (add inside, move in/out, children/parent, one-level and cross-account +refusals); the archived search filter; photos (caption + photo, photo-only, attach more, fake images rejected before anything is created, bad names, links, size, other users' notes, Shortcut-style raw upload, non-image/unknown-parameter/10-per-note limits); request files (shell metacharacters and heredoc delimiters stored verbatim, bad names, links, oversized and non-JSON files, disallowed ops, file deleted after use); diff --git a/hermes/brainfeed/SKILL.md b/hermes/brainfeed/SKILL.md index a7b23a5..761bb74 100644 --- a/hermes/brainfeed/SKILL.md +++ b/hermes/brainfeed/SKILL.md @@ -1,7 +1,7 @@ --- name: brainfeed description: Save, search and edit Kevin's BrainFeed notes and reminders (a private "feed for your brain"). Use when Kevin says chuck/save/note/jot this, asks what was saved about something, or asks for a reminder. -version: 1.3.1 +version: 1.4.0 platforms: [linux, macos] metadata: hermes: @@ -28,6 +28,9 @@ INBOX = ~/.config/brainfeed/inbox/ (absolute path: see `status` output) - "what did I save about…", "find my note on…", "anything tagged #x?" → `search_notes` - "change/fix/retag that note", "pin it", "archive it" → `edit_note` - "add to my X note: …", "update my shiny hunt log" → `append_note` +- "check off milk", "untick eggs", "add bread to my grocery list" → `check_items` +- "put this inside my X note", "move that into…", "take it out of…" → `add_note` / `edit_note` with `parent_id` +- "what tags do I use?" → `list_tags` (also use it yourself before tagging, see **Tags**) - "what's on my calendar / this week / Friday?" → `calendar` - "remind me to… at/on/every…" → `add_reminder` - "what reminders do I have?", "move/cancel my reminder…" → `list_reminders` / `edit_reminder` @@ -49,10 +52,12 @@ file name. | op | fields | |---|---| -| `add_note` | `body` (Kevin's words, verbatim), `tags` (optional list), `source`: `"telegram"` or `"discord"` | -| `search_notes` | `q` (words AND-ed; `#tag` filters), `tags`, `pinned`, `limit` (≤50) | -| `get_note` | `id` | -| `edit_note` | `id`, and any of `body`, `add_tags`, `remove_tags`, `pinned`, `archived` (true hides it from the feed and calendar; false brings it back). Archived notes still appear in `search_notes` results, with `archived_at` set | +| `add_note` | `body` (Kevin's words, verbatim), `tags` (optional list), `source`: `"telegram"` or `"discord"`, `parent_id` (optional: save it **inside** that note) | +| `search_notes` | `q` (words AND-ed; `#tag` filters), `tags`, `pinned`, `limit` (≤50), `archived` (`false` = leave archived out, `true` = only archived; omit for both), `parent_id` (list the notes inside that note) | +| `get_note` | `id`. Also returns `parent` (the note it sits in), `children` (notes inside it) and `checklist` (numbered items with `done`) | +| `edit_note` | `id`, and any of `body`, `add_tags`, `remove_tags`, `pinned`, `archived` (true hides it from the feed and calendar; false brings it back), `parent_id` (a note id moves it inside that note; `null` takes it back out). Archived notes still appear in `search_notes` results, with `archived_at` set | +| `check_items` | `id`, and any of `check` / `uncheck` (lists of item numbers from `get_note`'s `checklist`, or item text), `add` (list of new item texts, added after the last item). Returns the updated `checklist` and a `message` like "3/5 done" | +| `list_tags` | `limit` (optional): Kevin's tags with how many notes use each, most-used first | | `append_note` | `id`, `body`: adds a time-stamped entry ("— Oct 4, 8:30 PM") to the end of an existing note | | `calendar` | `from_local` (`"YYYY-MM-DD"`, default today), `days` (1–31, default 7): each day's reminders (with repeats worked out, `status` scheduled/overdue/repeat/done) and non-archived notes created that day, plus `overdue_before`: open reminders that were due before `from_local` | | `add_note` + photos | as `add_note`, plus `photos`: list of image file names in `INBOX` (`body` optional: defaults to "📷 Photo") | @@ -67,6 +72,8 @@ Examples of file contents: {"op": "add_note", "body": "Stream overlay idea: live dex counter #twitch", "source": "telegram"} {"op": "search_notes", "q": "overlay", "limit": 10} {"op": "add_reminder", "body": "Call the vet", "due_local": "2026-10-02T09:00", "source": "telegram"} +{"op": "check_items", "id": "", "check": ["milk"], "add": ["bread"]} +{"op": "add_note", "body": "Lure + Shiny Charm combo", "parent_id": "", "source": "telegram"} ``` **Photos.** When Kevin sends an image to save: @@ -92,6 +99,18 @@ Only JPEG, PNG, GIF and WebP are accepted (max 10 MB, up to 10 per note). For ot item's wording exactly as Kevin gave it; only the `- [ ] ` prefix is added. - Headings: `# Title` or `## Section` at the start of a line (a space after the #). - To add to an existing log-style note, use `append_note` rather than editing the whole body. +- To tick, untick or add checklist items, use `check_items`, never `edit_note` with a rewritten + body. If it answers `ambiguous` (the text matches several items), `get_note` and ask Kevin which + one, or use the item number. On `no_match`, show him the items instead of guessing. + +**Tags.** Before tagging a note yourself (Kevin didn't type a `#tag`), run `list_tags` and reuse +an existing tag when one fits (`#groceries`, not a new `#grocery`). Make a new tag only when +nothing fits, and say so ("new tag #recipes"). Never change tags Kevin typed. + +**Notes inside notes.** BrainFeed nests one level deep: a note can hold other notes, but a note +that's inside another can't hold any, and a note that holds others can't be moved inside one. +The API explains the reason if Kevin asks for something that breaks this; pass it on in plain words. +Search first to find the outer note's `id`, and confirm if more than one note matches. **Notes.** Keep Kevin's wording and any `#tags`. Reply briefly, e.g. "Saved to BrainFeed ✓ (#twitch)". diff --git a/hermes/brainfeed/scripts/brainfeed.py b/hermes/brainfeed/scripts/brainfeed.py index 74314fd..33f8903 100644 --- a/hermes/brainfeed/scripts/brainfeed.py +++ b/hermes/brainfeed/scripts/brainfeed.py @@ -15,8 +15,8 @@ inbox/NAME.json with its file-writing tool, so user text never passes through a shell. The shell command contains only fixed, safe tokens. call NAME.json ops: add_note, search_notes, get_note, edit_note, append_note, - attach_photos, add_reminder, list_reminders, edit_reminder, - calendar + check_items, list_tags, attach_photos, add_reminder, + list_reminders, edit_reminder, calendar add_note / attach_photos take "photos": [image files that are also in inbox/]; each is uploaded, then deleted. @@ -47,7 +47,7 @@ import urllib.error import urllib.request from datetime import datetime, timezone -VERSION = "1.3.1" +VERSION = "1.4.0" CONFIG_DIR = os.path.expanduser(os.environ.get("BRAINFEED_CONFIG_DIR", "~/.config/brainfeed")) CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json") TOKEN_FILE = os.path.join(CONFIG_DIR, "token") @@ -66,6 +66,8 @@ CALL_OPS = { "get_note": ("POST", "/v1/notes/get"), "edit_note": ("POST", "/v1/notes/update"), "append_note": ("POST", "/v1/notes/append"), + "check_items": ("POST", "/v1/notes/check"), + "list_tags": ("POST", "/v1/tags"), "calendar": ("POST", "/v1/calendar"), "attach_photos": None, # handled locally: uploads inbox photos to a note "add_reminder": ("POST", "/v1/reminders"), @@ -150,10 +152,13 @@ def api(method, path, body=None, token=None, raw=None): except urllib.error.HTTPError as e: # Report only status + the server's message; never request headers. try: - msg = json.loads(e.read().decode()).get("message", "") + payload = json.loads(e.read().decode()) + msg, code = payload.get("message", ""), payload.get("error", "") except Exception: - msg = "" - err = HelperError(f"BrainFeed API error {e.code}: {msg or e.reason}") + msg, code = "", "" + # The short error code (e.g. "ambiguous", "no_match") tells the agent what to do next. + tag = f" ({code})" if isinstance(code, str) and code and len(code) <= 32 and code.replace("_", "").isalpha() else "" + err = HelperError(f"BrainFeed API error {e.code}{tag}: {msg or e.reason}") err.status = e.code raise err from None except urllib.error.URLError as e: diff --git a/hermes/tests/test_api.py b/hermes/tests/test_api.py index 8836d05..2a4290b 100644 --- a/hermes/tests/test_api.py +++ b/hermes/tests/test_api.py @@ -529,6 +529,89 @@ class Review131(unittest.TestCase): run("deliver") # tidy: deliver it so it doesn't linger as overdue +class Skill14(unittest.TestCase): + """Skill 1.4: list_tags, check_items, notes inside notes, archived filter.""" + + def call(self, obj, name="s14.json", check=True): + inbox = os.path.join(DIR_A, "inbox") + os.makedirs(inbox, mode=0o700, exist_ok=True) + with open(os.path.join(inbox, name), "w") as f: + json.dump(obj, f) + p = run("call", name, check=check) + return json.loads(p.stdout) if p.returncode == 0 else p + + def test_list_tags_counts_and_skips_archived(self): + t = "tg" + os.urandom(3).hex() + j("add", f"one #{t}"); j("add", f"two #{t}") + gone = j("add", f"three #{t}")["note"] + self.call({"op": "edit_note", "id": gone["id"], "archived": True}) + tags = {x["tag"]: x["count"] for x in self.call({"op": "list_tags"})["tags"]} + self.assertEqual(tags[t], 2) + self.assertIn("400", self.call({"op": "list_tags", "user_id": "x"}, check=False).stderr) + + def test_check_items(self): + n = j("add", "# Groceries\n- [ ] Milk\n- [ ] eggs\n- [x] Bread\n- [ ] oat milk\nnotes after")["note"] + out = self.call({"op": "check_items", "id": n["id"], "check": ["eggs"], "uncheck": [3], "add": ["Coffee"]}) + self.assertEqual([(x["text"], x["done"]) for x in out["checklist"]], + [("Milk", False), ("eggs", True), ("Bread", False), ("oat milk", False), ("Coffee", False)]) + self.assertTrue(out["note"]["body"].endswith("- [ ] Coffee\nnotes after")) + self.assertEqual(out["message"], "1/5 done") + # "milk" is exactly item 1 (exact match beats "oat milk"); "mil" is ambiguous + self.assertEqual(self.call({"op": "check_items", "id": n["id"], "check": ["milk"]})["checked"], ["Milk"]) + self.assertIn("ambiguous", self.call({"op": "check_items", "id": n["id"], "check": ["mil"]}, check=False).stderr) + self.assertIn("no_match", self.call({"op": "check_items", "id": n["id"], "check": ["kale"]}, check=False).stderr) + self.assertIn("no item 9", self.call({"op": "check_items", "id": n["id"], "check": [9]}, check=False).stderr) + got = self.call({"op": "get_note", "id": n["id"]}) + self.assertEqual([x["n"] for x in got["checklist"]], [1, 2, 3, 4, 5]) + self.assertIn("404", self.call({"op": "check_items", "id": NOTE_B, "add": ["x"]}, check=False).stderr) + + def test_check_items_starts_a_list(self): + n = j("add", "Packing for the trip")["note"] + out = self.call({"op": "check_items", "id": n["id"], "add": ["charger", "socks"]}) + self.assertEqual(out["note"]["body"], "Packing for the trip\n\n- [ ] charger\n- [ ] socks") + + def test_concurrent_checks_all_land(self): + import concurrent.futures + n = j("add", "\n".join(f"- [ ] item{i}" for i in range(4)))["note"] + def one(i): + inbox = os.path.join(DIR_A, "inbox") + with open(os.path.join(inbox, f"ck{i}.json"), "w") as f: + json.dump({"op": "check_items", "id": n["id"], "check": [f"item{i}"]}, f) + return run("call", f"ck{i}.json", check=False).returncode + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex: + self.assertEqual(list(ex.map(one, range(4))), [0] * 4) + self.assertTrue(all(x["done"] for x in self.call({"op": "get_note", "id": n["id"]})["checklist"])) + + def test_notes_inside_notes(self): + outer = j("add", "Shiny hunts " + os.urandom(3).hex())["note"] + kid = self.call({"op": "add_note", "body": "Charmander: 1,204 eggs", "parent_id": outer["id"]})["note"] + self.assertEqual(kid["parent_id"], outer["id"]) + loose = j("add", "Pikachu hunt")["note"] + self.call({"op": "edit_note", "id": loose["id"], "parent_id": outer["id"]}) + got = self.call({"op": "get_note", "id": outer["id"]}) + self.assertEqual([c["id"] for c in got["children"]], [kid["id"], loose["id"]]) + self.assertEqual(self.call({"op": "get_note", "id": kid["id"]})["parent"]["id"], outer["id"]) + inside = self.call({"op": "search_notes", "parent_id": outer["id"]})["notes"] + self.assertEqual({x["id"] for x in inside}, {kid["id"], loose["id"]}) + # one level only, and never into someone else's note (same answer, nothing leaked) + self.assertIn("cannot hold other notes", self.call({"op": "add_note", "body": "x", "parent_id": kid["id"]}, check=False).stderr) + other = j("add", "standalone")["note"] + self.assertIn("cannot be moved inside", self.call({"op": "edit_note", "id": outer["id"], "parent_id": other["id"]}, check=False).stderr) + self.assertIn("cannot hold other notes", self.call({"op": "add_note", "body": "x", "parent_id": NOTE_B}, check=False).stderr) + out = self.call({"op": "edit_note", "id": loose["id"], "parent_id": None})["note"] + self.assertIsNone(out["parent_id"]) + + def test_search_archived_filter(self): + w = "arch" + os.urandom(3).hex() + keep = j("add", f"{w} keep")["note"] + gone = j("add", f"{w} gone")["note"] + self.call({"op": "edit_note", "id": gone["id"], "archived": True}) + ids = lambda **kw: {x["id"] for x in self.call({"op": "search_notes", "q": w, **kw})["notes"]} + self.assertEqual(ids(), {keep["id"], gone["id"]}) + self.assertEqual(ids(archived=False), {keep["id"]}) + self.assertEqual(ids(archived=True), {gone["id"]}) + + class Outage(unittest.TestCase): """Delivery failures are silent at first, alert once, then recover once.""" diff --git a/supabase/functions/brainfeed-api/index.ts b/supabase/functions/brainfeed-api/index.ts index 31bf813..594d6fb 100644 --- a/supabase/functions/brainfeed-api/index.ts +++ b/supabase/functions/brainfeed-api/index.ts @@ -1,8 +1,9 @@ -// BrainFeed agent API (v1). +// BrainFeed agent API (v1, revision 6). // // A deliberately small, fixed set of operations for an agent like Hermes -// or an iPhone Shortcut: add / search / edit notes, attach photos, add / -// search / edit reminders, and claim/ack due reminders for delivery. +// or an iPhone Shortcut: add / search / edit notes (incl. nesting and +// checklist ticks), list tags, attach photos, add / search / edit +// reminders, and claim/ack due reminders for delivery. // No deletes, no arbitrary queries. // // Auth: "X-BrainFeed-Token: <64 hex chars>" (a bearer token in a custom @@ -118,6 +119,43 @@ function source(v: unknown) { return v; } +// Database rule violations worth showing the agent as-is (nesting trigger). +function dbError(error: { message?: string } | null, fallback: string) { + const m = error?.message || ''; + if (/cannot contain itself|cannot hold other notes|cannot be moved inside another/.test(m)) return bad(m); + return new ApiError(500, 'db_error', fallback); +} +function optUuid(v: unknown, field: string) { + if (v === undefined) return undefined; + if (v === null) return null; + return uuid(v, field); +} +const firstLine = (body: string) => (body.split('\n').find((l) => l.trim()) || '').replace(/^#{1,3} |^\s*[-*] \[[ xX]\] /, '').slice(0, 80); + +// Checklists are plain-text lines: "- [ ] milk" / "- [x] eggs" (same rule as the web app). +const CHECK_RE = /^(\s*[-*] \[)([ xX])(\] ?)(.*)$/; +function checklist(body: string) { + return body.split('\n').flatMap((l, i) => { const m = l.match(CHECK_RE); return m ? [{ line: i, done: m[2] !== ' ', text: m[4] }] : []; }); +} +type Item = ReturnType[number]; +// An item is picked by its number (1 = first checklist item) or by its text: +// an exact (case-insensitive) match wins, otherwise the text must be in exactly one item. +function pickItem(items: Item[], sel: unknown, field: string): Item { + if (Number.isInteger(sel)) { + const it = items[(sel as number) - 1]; + if (!it) throw bad(`${field}: there is no item ${sel} (the note has ${items.length})`); + return it; + } + if (typeof sel !== 'string' || !sel.trim() || sel.length > 500) throw bad(`${field} entries must be item numbers or item text`); + const q = sel.trim().toLowerCase(); + const exact = items.filter((x) => x.text.trim().toLowerCase() === q); + if (exact.length === 1) return exact[0]; + const part = exact.length ? exact : items.filter((x) => x.text.toLowerCase().includes(q)); + if (part.length === 1) return part[0]; + if (!part.length) throw new ApiError(400, 'no_match', `${field}: no checklist item matches "${sel}"`); + throw new ApiError(400, 'ambiguous', `${field}: "${sel}" matches ${part.length} items (${part.map((x) => x.text).join(' | ')}); use the item number`); +} + // --------------------------------------------------------- time zones async function userTz(userId: string) { const { data } = await db.from('settings').select('timezone').eq('user_id', userId).maybeSingle(); @@ -301,23 +339,29 @@ const routes: Record = { }, 'POST /v1/notes': async (c, b) => { - only(b, ['body', 'tags', 'source']); + only(b, ['body', 'tags', 'source', 'parent_id']); const text = str(b.body, 'body', { required: true })!; + const parent = optUuid(b.parent_id, 'parent_id') ?? null; const { data, error } = await db.from('notes') - .insert({ user_id: c.userId, body: text, tags: tags(b.tags, 'tags'), source: source(b.source) }) + .insert({ user_id: c.userId, body: text, tags: tags(b.tags, 'tags'), source: source(b.source), parent_id: parent }) .select(NOTE_COLS).single(); - if (error) throw new ApiError(500, 'db_error', 'Could not save note'); + if (error) throw dbError(error, 'Could not save note'); return { note: data, message: 'Saved to BrainFeed ✓' }; }, 'POST /v1/notes/search': async (c, b) => { - only(b, ['q', 'tags', 'pinned', 'limit', 'before']); + only(b, ['q', 'tags', 'pinned', 'limit', 'before', 'archived', 'parent_id']); const q = str(b.q, 'q', { max: 200 }) || ''; const tagList = tags(b.tags, 'tags'); let query = db.from('notes').select(NOTE_COLS).eq('user_id', c.userId) .order('created_at', { ascending: false }).limit(int(b.limit, 'limit', 20, 1, 50)); if (tagList.length) query = query.contains('tags', tagList); if (bool(b.pinned, 'pinned') !== undefined) query = query.eq('pinned', b.pinned as boolean); + // archived: true = only archived, false = leave them out; omitted = both. + const arch = bool(b.archived, 'archived'); + if (arch === true) query = query.not('archived_at', 'is', null); + if (arch === false) query = query.is('archived_at', null); + if (b.parent_id !== undefined) query = query.eq('parent_id', uuid(b.parent_id, 'parent_id')); if (b.before !== undefined) { const d = new Date(String(b.before)); if (isNaN(d.getTime())) throw bad('before must be an ISO date'); @@ -336,11 +380,20 @@ const routes: Record = { only(b, ['id']); const { data } = await db.from('notes').select(NOTE_COLS).eq('user_id', c.userId).eq('id', uuid(b.id)).maybeSingle(); if (!data) throw new ApiError(404, 'not_found', 'Note not found'); - return { note: data }; + const [{ data: kids }, { data: parent }] = await Promise.all([ + db.from('notes').select('id,body,archived_at').eq('user_id', c.userId).eq('parent_id', data.id).order('created_at').limit(100), + data.parent_id ? db.from('notes').select('id,body').eq('user_id', c.userId).eq('id', data.parent_id).maybeSingle() : Promise.resolve({ data: null }), + ]); + return { + note: data, + parent: parent ? { id: parent.id, first_line: firstLine(parent.body as string) } : null, + children: (kids || []).map((k) => ({ id: k.id, first_line: firstLine(k.body as string), archived: !!k.archived_at })), + checklist: checklist(data.body as string).map((x, i) => ({ n: i + 1, done: x.done, text: x.text })), + }; }, 'POST /v1/notes/update': async (c, b) => { - only(b, ['id', 'body', 'add_tags', 'remove_tags', 'pinned', 'archived']); + only(b, ['id', 'body', 'add_tags', 'remove_tags', 'pinned', 'archived', 'parent_id']); const id = uuid(b.id); const { data: cur } = await db.from('notes').select('id,tags').eq('user_id', c.userId).eq('id', id).maybeSingle(); if (!cur) throw new ApiError(404, 'not_found', 'Note not found'); @@ -349,15 +402,18 @@ const routes: Record = { const add = tags(b.add_tags, 'add_tags'), remove = tags(b.remove_tags, 'remove_tags'); const pinned = bool(b.pinned, 'pinned'); const archived = bool(b.archived, 'archived'); - if (text === undefined && !add.length && !remove.length && pinned === undefined && archived === undefined) throw bad('Nothing to update'); + // parent_id: a note id moves this note inside it; null takes it out. + const parent = optUuid(b.parent_id, 'parent_id'); + if (text === undefined && !add.length && !remove.length && pinned === undefined && archived === undefined && parent === undefined) throw bad('Nothing to update'); // Body first: the database re-derives #hashtags from the new text. - if (text !== undefined || pinned !== undefined || archived !== undefined) { + if (text !== undefined || pinned !== undefined || archived !== undefined || parent !== undefined) { const patch: Record = {}; if (text !== undefined) patch.body = text; if (pinned !== undefined) patch.pinned = pinned; if (archived !== undefined) patch.archived_at = archived ? new Date().toISOString() : null; + if (parent !== undefined) patch.parent_id = parent; const { error } = await db.from('notes').update(patch).eq('user_id', c.userId).eq('id', id); - if (error) throw new ApiError(500, 'db_error', 'Could not update note'); + if (error) throw dbError(error, 'Could not update note'); } if (add.length || remove.length) { const { data: now } = await db.from('notes').select('tags').eq('user_id', c.userId).eq('id', id).single(); @@ -386,6 +442,61 @@ const routes: Record = { return { note: data, message: 'Added to the note ✓' }; }, + 'POST /v1/notes/check': async (c, b) => { + only(b, ['id', 'check', 'uncheck', 'add']); + const id = uuid(b.id); + const list = (v: unknown, field: string) => { + if (v === undefined) return []; + if (!Array.isArray(v) || !v.length || v.length > 50) throw bad(`${field} must be a list of 1-50 entries`); + return v; + }; + const check = list(b.check, 'check'), uncheck = list(b.uncheck, 'uncheck'); + const add = list(b.add, 'add').map((t) => str(t, 'add item', { required: true, max: 500 })!.replace(/\s*\n\s*/g, ' ')); + if (!check.length && !uncheck.length && !add.length) throw bad('Send check, uncheck or add'); + // Optimistic write: only lands if nobody changed the note since we read it. + for (let attempt = 0; attempt < 4; attempt++) { + const { data: cur } = await db.from('notes').select('body,updated_at').eq('user_id', c.userId).eq('id', id).maybeSingle(); + if (!cur) throw new ApiError(404, 'not_found', 'Note not found'); + const lines = (cur.body as string).split('\n'); + const items = checklist(cur.body as string); + const set = (sel: unknown, field: string, done: boolean) => { + const it = pickItem(items, sel, field); + lines[it.line] = lines[it.line].replace(CHECK_RE, (_m, a, _x, z, t) => a + (done ? 'x' : ' ') + z + t); + return it.text; + }; + const checked = check.map((x) => set(x, 'check', true)); + const unchecked = uncheck.map((x) => set(x, 'uncheck', false)); + if (add.length) { + const at = items.length ? items[items.length - 1].line + 1 : lines.length; + const fresh = add.map((t) => '- [ ] ' + t); + if (!items.length && lines.length && lines[lines.length - 1].trim()) fresh.unshift(''); + lines.splice(at, 0, ...fresh); + } + const body = lines.join('\n'); + if (body.length > MAX_BODY) throw bad('Note would be too long'); + const { data: rows, error } = await db.from('notes').update({ body }).eq('user_id', c.userId).eq('id', id) + .eq('updated_at', cur.updated_at).select(NOTE_COLS); + if (error) throw new ApiError(500, 'db_error', 'Could not update note'); + if (rows?.length) { + const now = checklist(rows[0].body as string); + return { + note: rows[0], checked, unchecked, added: add, + checklist: now.map((x, i) => ({ n: i + 1, done: x.done, text: x.text })), + message: `${now.filter((x) => x.done).length}/${now.length} done`, + }; + } + } + throw new ApiError(409, 'conflict', 'The note kept changing; try again'); + }, + + 'POST /v1/tags': async (c, b) => { + only(b, ['limit']); + const { data, error } = await db.rpc('bf_tag_counts', { p_user: c.userId }); + if (error) throw new ApiError(500, 'db_error', 'Tag lookup failed'); + const limit = int(b.limit, 'limit', 200, 1, 500); + return { tags: (data || []).slice(0, limit).map((t: { tag: string; count: number }) => ({ tag: t.tag, count: Number(t.count) })) }; + }, + 'POST /v1/calendar': async (c, b) => { only(b, ['from_local', 'days']); const tz = await userTz(c.userId); diff --git a/supabase/migrations/20261006200000_hermes_14_tags.sql b/supabase/migrations/20261006200000_hermes_14_tags.sql new file mode 100644 index 0000000..9a11f9b --- /dev/null +++ b/supabase/migrations/20261006200000_hermes_14_tags.sql @@ -0,0 +1,10 @@ +-- Tag counts for the agent API (service role only; the API passes the +-- token's user, never a client-supplied one). Mirrors public.tag_counts(). +create or replace function public.bf_tag_counts(p_user uuid) +returns table (tag text, count bigint) language sql stable security definer set search_path = '' as $$ + select t, count(*) from public.notes n, unnest(n.tags) t + where n.user_id = p_user and n.archived_at is null + group by t order by count(*) desc, t; +$$; +revoke all on function public.bf_tag_counts(uuid) from public, anon, authenticated; +grant execute on function public.bf_tag_counts(uuid) to service_role;