bowerbird-bookmarks 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ # Personal data — must never be committed or packaged
2
+ bower.db*
3
+ bowerbird.db*
4
+ backups/
5
+ exports/
6
+ reports/
7
+
8
+ # Build / env
9
+ dist/
10
+ .venv/
11
+ __pycache__/
12
+ *.pyc
13
+ *.egg-info/
14
+
15
+ # macOS / exFAT junk
16
+ .DS_Store
17
+ ._*
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Borck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: bowerbird-bookmarks
3
+ Version: 0.6.0
4
+ Summary: Audit, clean, categorise and explore your browser bookmarks — link validation, LLM thematic analysis, Wayback recovery, and safe write-back
5
+ Project-URL: Homepage, https://github.com/michael-borck/bowerbird
6
+ Author-email: Michael Borck <michael.borck@curtin.edu.au>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Michael Borck
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ License-File: LICENSE
29
+ Keywords: bookmarks,brave,browser,chrome,claude,curation,firefox,link-rot,obsidian,wayback
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: Environment :: Console
32
+ Classifier: Environment :: Web Environment
33
+ Classifier: Intended Audience :: End Users/Desktop
34
+ Classifier: Operating System :: MacOS
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
38
+ Classifier: Topic :: Utilities
39
+ Requires-Python: >=3.12
40
+ Requires-Dist: anthropic>=0.90
41
+ Requires-Dist: fastapi>=0.115
42
+ Requires-Dist: httpx>=0.27
43
+ Requires-Dist: uvicorn>=0.30
44
+ Description-Content-Type: text/markdown
45
+
46
+ # Bowerbird
47
+
48
+ Like its namesake bowerbird, it collects — then, unlike you, it curates.
49
+ Bowerbird audits, cleans, categorises and helps you rediscover your browser
50
+ bookmarks, entirely on your own machine.
51
+
52
+ ```
53
+ pip install bowerbird-bookmarks
54
+ bowerbird ingest # read your browsers' bookmarks (read-only)
55
+ bowerbird check # validate every link
56
+ bowerbird serve # dashboard at http://127.0.0.1:8420
57
+ ```
58
+
59
+ ## What it does
60
+
61
+ - **Multi-browser ingest** — Chrome, Brave, Edge, Vivaldi (one Chromium parser),
62
+ Firefox (`places.sqlite`) and Safari (read-only). Sources are facets, not
63
+ silos: the same link saved in two browsers is one URL, tracked once.
64
+ - **Link validation** that doesn't lie: only 404/410 (or a confirmed soft-404)
65
+ counts as *dead*; a bot-wall 403 is *blocked, not dead*; reaching a login page
66
+ counts as *alive*; YouTube videos are checked via oEmbed because deleted
67
+ videos still return 200.
68
+ - **Canonicalisation and duplicate detection** (tracking params stripped,
69
+ youtu.be unified, per-source dupe groups with a keeper heuristic).
70
+ - **LLM thematic analysis** (Claude, two-pass): a taxonomy is derived from your
71
+ collection first, then bookmarks are assigned 1–3 categories with confidence.
72
+ Categories are tags — one bookmark can live in many.
73
+ - **Full-text search** (SQLite FTS5) over titles, URLs, topics, and the visible
74
+ text of every reachable page.
75
+ - **Ask your bookmarks** — ask a question, get *links from your own collection*
76
+ grouped by theme with a line on why each is relevant. Never answers from the
77
+ open web.
78
+ - **Graveyard & Wayback** — dead links get Internet Archive snapshot lookup,
79
+ per-row or bulk replace, and bulk retire for the unrecoverable.
80
+ - **Domain triage** — review a whole domain in one decision.
81
+ - **Obsidian export** — topic notes plus per-bookmark stubs with frontmatter
82
+ and wikilinks; drop the folder into your vault.
83
+ - **Topic map** — a force-directed graph of your collection's themes.
84
+ - **Safe write-back** — regenerate the browser's bookmarks file: duplicates
85
+ collapsed, dead links moved to a `_Graveyard` folder (never silently
86
+ deleted), Wayback replacements applied. Dry-run by default, timestamped
87
+ backup always, refuses to run while the browser is open.
88
+
89
+ ## Requirements
90
+
91
+ - macOS (browser profile discovery is macOS-path based for now)
92
+ - Python 3.12+
93
+ - An Anthropic API key (`ANTHROPIC_API_KEY`) for the categorisation and Ask
94
+ features — everything else works without one.
95
+
96
+ ## Data location
97
+
98
+ Everything lives in `$BOWERBIRD_HOME` (default `~/.bowerbird`): the SQLite database,
99
+ write-back backups, reports and exports. A `bowerbird.db` in the current directory is respected. Your browsers' own files are only ever
100
+ written by the explicit `bowerbird writeback --apply`, and backed up first.
101
+
102
+ ## Commands
103
+
104
+ | Command | What it does |
105
+ |---|---|
106
+ | `bowerbird sources` | detect and register installed browsers |
107
+ | `bowerbird ingest` | import bookmarks + history (read-only, reconciling) |
108
+ | `bowerbird check` | validate links (`--recheck` to re-probe) |
109
+ | `bowerbird enrich` | fetch page titles/descriptions/text for search |
110
+ | `bowerbird categorize --taxonomy` / `--assign` | two-pass LLM categorisation |
111
+ | `bowerbird index` | rebuild the full-text search index |
112
+ | `bowerbird wayback` | look up Internet Archive snapshots for dead links |
113
+ | `bowerbird report` | write a Markdown audit report |
114
+ | `bowerbird obsidian` | export an Obsidian-ready folder |
115
+ | `bowerbird writeback --source-id N [--apply]` | write the cleaned tree back |
116
+ | `bowerbird serve` | the dashboard (Library, Ask, Graveyard, Duplicates, Domains, Topic map) |
117
+
118
+ ## Notes
119
+
120
+ The CLI is also installed under the short alias `bower`, and the Python module
121
+ is `import bowerbird`.
122
+
123
+ ## Status
124
+
125
+ Beta. Built and used in anger on a 9,600-bookmark collection; APIs and schema
126
+ may still change. Issues and ideas welcome.
@@ -0,0 +1,81 @@
1
+ # Bowerbird
2
+
3
+ Like its namesake bowerbird, it collects — then, unlike you, it curates.
4
+ Bowerbird audits, cleans, categorises and helps you rediscover your browser
5
+ bookmarks, entirely on your own machine.
6
+
7
+ ```
8
+ pip install bowerbird-bookmarks
9
+ bowerbird ingest # read your browsers' bookmarks (read-only)
10
+ bowerbird check # validate every link
11
+ bowerbird serve # dashboard at http://127.0.0.1:8420
12
+ ```
13
+
14
+ ## What it does
15
+
16
+ - **Multi-browser ingest** — Chrome, Brave, Edge, Vivaldi (one Chromium parser),
17
+ Firefox (`places.sqlite`) and Safari (read-only). Sources are facets, not
18
+ silos: the same link saved in two browsers is one URL, tracked once.
19
+ - **Link validation** that doesn't lie: only 404/410 (or a confirmed soft-404)
20
+ counts as *dead*; a bot-wall 403 is *blocked, not dead*; reaching a login page
21
+ counts as *alive*; YouTube videos are checked via oEmbed because deleted
22
+ videos still return 200.
23
+ - **Canonicalisation and duplicate detection** (tracking params stripped,
24
+ youtu.be unified, per-source dupe groups with a keeper heuristic).
25
+ - **LLM thematic analysis** (Claude, two-pass): a taxonomy is derived from your
26
+ collection first, then bookmarks are assigned 1–3 categories with confidence.
27
+ Categories are tags — one bookmark can live in many.
28
+ - **Full-text search** (SQLite FTS5) over titles, URLs, topics, and the visible
29
+ text of every reachable page.
30
+ - **Ask your bookmarks** — ask a question, get *links from your own collection*
31
+ grouped by theme with a line on why each is relevant. Never answers from the
32
+ open web.
33
+ - **Graveyard & Wayback** — dead links get Internet Archive snapshot lookup,
34
+ per-row or bulk replace, and bulk retire for the unrecoverable.
35
+ - **Domain triage** — review a whole domain in one decision.
36
+ - **Obsidian export** — topic notes plus per-bookmark stubs with frontmatter
37
+ and wikilinks; drop the folder into your vault.
38
+ - **Topic map** — a force-directed graph of your collection's themes.
39
+ - **Safe write-back** — regenerate the browser's bookmarks file: duplicates
40
+ collapsed, dead links moved to a `_Graveyard` folder (never silently
41
+ deleted), Wayback replacements applied. Dry-run by default, timestamped
42
+ backup always, refuses to run while the browser is open.
43
+
44
+ ## Requirements
45
+
46
+ - macOS (browser profile discovery is macOS-path based for now)
47
+ - Python 3.12+
48
+ - An Anthropic API key (`ANTHROPIC_API_KEY`) for the categorisation and Ask
49
+ features — everything else works without one.
50
+
51
+ ## Data location
52
+
53
+ Everything lives in `$BOWERBIRD_HOME` (default `~/.bowerbird`): the SQLite database,
54
+ write-back backups, reports and exports. A `bowerbird.db` in the current directory is respected. Your browsers' own files are only ever
55
+ written by the explicit `bowerbird writeback --apply`, and backed up first.
56
+
57
+ ## Commands
58
+
59
+ | Command | What it does |
60
+ |---|---|
61
+ | `bowerbird sources` | detect and register installed browsers |
62
+ | `bowerbird ingest` | import bookmarks + history (read-only, reconciling) |
63
+ | `bowerbird check` | validate links (`--recheck` to re-probe) |
64
+ | `bowerbird enrich` | fetch page titles/descriptions/text for search |
65
+ | `bowerbird categorize --taxonomy` / `--assign` | two-pass LLM categorisation |
66
+ | `bowerbird index` | rebuild the full-text search index |
67
+ | `bowerbird wayback` | look up Internet Archive snapshots for dead links |
68
+ | `bowerbird report` | write a Markdown audit report |
69
+ | `bowerbird obsidian` | export an Obsidian-ready folder |
70
+ | `bowerbird writeback --source-id N [--apply]` | write the cleaned tree back |
71
+ | `bowerbird serve` | the dashboard (Library, Ask, Graveyard, Duplicates, Domains, Topic map) |
72
+
73
+ ## Notes
74
+
75
+ The CLI is also installed under the short alias `bower`, and the Python module
76
+ is `import bowerbird`.
77
+
78
+ ## Status
79
+
80
+ Beta. Built and used in anger on a 9,600-bookmark collection; APIs and schema
81
+ may still change. Issues and ideas welcome.
@@ -0,0 +1,3 @@
1
+ """Bower — Brave bookmark audit, validation and discovery."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,73 @@
1
+ """URL canonicalisation — produces a dedupe key, not a replacement URL.
2
+
3
+ The canonical form unifies scheme to https, strips www./m., drops fragments,
4
+ tracking parameters and trailing slashes, sorts the query, and folds YouTube's
5
+ many URL shapes onto youtube.com/watch?v=ID.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
12
+
13
+ TRACKING_PARAMS = {
14
+ "fbclid", "gclid", "gclsrc", "dclid", "msclkid", "yclid", "twclid",
15
+ "igshid", "mc_cid", "mc_eid", "mkt_tok", "spm", "si", "_hsenc", "_hsmi",
16
+ "vero_id", "cmpid", "ncid", "sr_share", "ref_src", "ref_url", "share_id",
17
+ }
18
+
19
+ YOUTUBE_HOSTS = {"youtube.com", "m.youtube.com", "www.youtube.com", "music.youtube.com"}
20
+ # Params that don't change which video you land on.
21
+ YOUTUBE_DROP = {"feature", "ab_channel", "pp", "index", "app", "sns", "annotation_id", "src_vid"}
22
+
23
+
24
+ def is_checkable(url: str) -> bool:
25
+ """http(s) URLs pointing at a public host."""
26
+ try:
27
+ parts = urlsplit(url)
28
+ except ValueError:
29
+ return False
30
+ if parts.scheme not in ("http", "https"):
31
+ return False
32
+ host = (parts.hostname or "").lower()
33
+ if not host or host == "localhost" or host.endswith(".local"):
34
+ return False
35
+ try:
36
+ if ipaddress.ip_address(host).is_private or ipaddress.ip_address(host).is_loopback:
37
+ return False
38
+ except ValueError:
39
+ pass # not an IP literal — a normal hostname
40
+ return True
41
+
42
+
43
+ def canonicalize(url: str) -> str:
44
+ try:
45
+ parts = urlsplit(url.strip())
46
+ except ValueError:
47
+ return url.strip()
48
+ if parts.scheme not in ("http", "https"):
49
+ return url.strip()
50
+
51
+ host = (parts.hostname or "").lower()
52
+ path = parts.path or "/"
53
+ query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
54
+ if not k.startswith("utm_") and k not in TRACKING_PARAMS]
55
+
56
+ if host == "youtu.be":
57
+ video_id = path.strip("/").split("/")[0]
58
+ host, path = "youtube.com", "/watch"
59
+ query = [("v", video_id)] + [(k, v) for k, v in query if k != "v"]
60
+ if host in YOUTUBE_HOSTS:
61
+ host = "youtube.com"
62
+ query = [(k, v) for k, v in query if k not in YOUTUBE_DROP]
63
+
64
+ if host.startswith("www."):
65
+ host = host[4:]
66
+
67
+ port = parts.port
68
+ netloc = host if port in (None, 80, 443) else f"{host}:{port}"
69
+
70
+ if path != "/" and path.endswith("/"):
71
+ path = path.rstrip("/")
72
+
73
+ return urlunsplit(("https", netloc, path, urlencode(sorted(query)), ""))
@@ -0,0 +1,255 @@
1
+ """Two-pass LLM categorisation (cabinet's design, with its roadmap lesson applied).
2
+
3
+ Pass A (`derive_taxonomy`): one Claude Opus call looks at the existing folder
4
+ structure plus a sample of the corpus and produces a clean, fixed taxonomy —
5
+ deriving the taxonomy *before* assigning anything prevents the synonym-sprawl
6
+ failure mode ("Finance" vs "Finances") that grows batch by batch.
7
+
8
+ Pass B (`assign`): batches of bookmarks are matched against that fixed taxonomy
9
+ with structured outputs. Assignments record their source and model so a better
10
+ model can later redo only machine-made labels. Manual assignments are never
11
+ overwritten.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import random
18
+ import sqlite3
19
+ from collections import Counter
20
+ from datetime import datetime, timezone
21
+ from urllib.parse import urlsplit
22
+
23
+ import anthropic
24
+
25
+ TAXONOMY_MODEL = "claude-opus-5"
26
+ ASSIGN_MODEL = "claude-haiku-4-5"
27
+ BATCH_SIZE = 25
28
+
29
+ TAXONOMY_SCHEMA = {
30
+ "type": "object",
31
+ "properties": {
32
+ "categories": {
33
+ "type": "array",
34
+ "items": {
35
+ "type": "object",
36
+ "properties": {
37
+ "name": {"type": "string"},
38
+ "children": {"type": "array", "items": {"type": "string"}},
39
+ },
40
+ "required": ["name", "children"],
41
+ "additionalProperties": False,
42
+ },
43
+ }
44
+ },
45
+ "required": ["categories"],
46
+ "additionalProperties": False,
47
+ }
48
+
49
+ ASSIGN_SCHEMA = {
50
+ "type": "object",
51
+ "properties": {
52
+ "items": {
53
+ "type": "array",
54
+ "items": {
55
+ "type": "object",
56
+ "properties": {
57
+ "index": {"type": "integer"},
58
+ "categories": {
59
+ "type": "array",
60
+ "items": {
61
+ "type": "object",
62
+ "properties": {
63
+ "path": {"type": "string"},
64
+ "confidence": {"type": "number"},
65
+ },
66
+ "required": ["path", "confidence"],
67
+ "additionalProperties": False,
68
+ },
69
+ },
70
+ },
71
+ "required": ["index", "categories"],
72
+ "additionalProperties": False,
73
+ },
74
+ }
75
+ },
76
+ "required": ["items"],
77
+ "additionalProperties": False,
78
+ }
79
+
80
+
81
+ def _folder_counts(conn: sqlite3.Connection) -> Counter:
82
+ counts: Counter = Counter()
83
+ for row in conn.execute("SELECT folder_path FROM bookmarks WHERE removed=0"):
84
+ for part in row["folder_path"].split("/"):
85
+ if part and part not in ("Bookmarks bar", "Other bookmarks", "Imported From Firefox",
86
+ "unfiled", "menu", "toolbar", "Imported"):
87
+ counts[part] += 1
88
+ return counts
89
+
90
+
91
+ def _sample_items(conn: sqlite3.Connection, n: int = 300) -> list[str]:
92
+ rows = conn.execute(
93
+ """SELECT b.title, b.url, b.folder_path FROM bookmarks b
94
+ WHERE b.removed=0 GROUP BY b.canonical_url ORDER BY RANDOM() LIMIT ?""", (n,)
95
+ ).fetchall()
96
+ return [f"{r['title'][:80]} | {(urlsplit(r['url']).hostname or '')} | {r['folder_path'][:60]}"
97
+ for r in rows]
98
+
99
+
100
+ def derive_taxonomy(conn: sqlite3.Connection, model: str = TAXONOMY_MODEL) -> dict:
101
+ client = anthropic.Anthropic()
102
+ folders = "\n".join(f"{name}: {count}" for name, count in _folder_counts(conn).most_common(80))
103
+ sample = "\n".join(_sample_items(conn))
104
+
105
+ response = client.messages.create(
106
+ model=model,
107
+ max_tokens=8000,
108
+ output_config={"effort": "medium",
109
+ "format": {"type": "json_schema", "schema": TAXONOMY_SCHEMA}},
110
+ messages=[{
111
+ "role": "user",
112
+ "content": (
113
+ "Design a category taxonomy for a personal bookmark collection of ~8,500 links "
114
+ "belonging to an academic who teaches computing, does research, 3D prints, and has "
115
+ "many hobbies. Requirements:\n"
116
+ "- 12-20 top-level categories, each with 0-8 children (two levels max).\n"
117
+ "- Merge synonyms and near-duplicates into one canonical name.\n"
118
+ "- Names are short (1-3 words). No 'Miscellaneous'/'Other' categories.\n"
119
+ "- The taxonomy must cover the whole collection; prefer broad, durable categories "
120
+ "over one-off niches.\n\n"
121
+ f"Existing folder names with bookmark counts:\n{folders}\n\n"
122
+ f"Random sample of bookmarks (title | domain | folder):\n{sample}"
123
+ ),
124
+ }],
125
+ )
126
+ if response.stop_reason == "refusal":
127
+ raise RuntimeError("taxonomy request was refused")
128
+ data = json.loads(next(b.text for b in response.content if b.type == "text"))
129
+
130
+ paths = []
131
+ for cat in data["categories"]:
132
+ paths.append(cat["name"])
133
+ paths.extend(f"{cat['name']} / {child}" for child in cat["children"])
134
+ for path in paths:
135
+ conn.execute("INSERT OR IGNORE INTO categories(path, source) VALUES(?, 'llm')", (path,))
136
+ conn.commit()
137
+ return {"top_level": len(data["categories"]), "total_paths": len(paths)}
138
+
139
+
140
+ def _system_prompt(conn: sqlite3.Connection) -> list[dict]:
141
+ taxonomy = "\n".join(r["path"] for r in conn.execute("SELECT path FROM categories ORDER BY path"))
142
+ return [{
143
+ "type": "text",
144
+ "text": (
145
+ "You categorise bookmarks from a personal collection into a fixed taxonomy.\n\n"
146
+ "Rules:\n"
147
+ "- Assign 1 to 3 categories per bookmark, most relevant first, each with a "
148
+ "confidence between 0 and 1.\n"
149
+ "- Use ONLY paths from the taxonomy below, exactly as written. Never invent new ones.\n"
150
+ "- Prefer the most specific applicable path (a child over its parent).\n"
151
+ "- The bookmark's original folder is a hint about the owner's intent, not ground truth.\n"
152
+ "- If genuinely nothing fits, return an empty categories array for that item.\n\n"
153
+ f"Taxonomy:\n{taxonomy}"
154
+ ),
155
+ "cache_control": {"type": "ephemeral"},
156
+ }]
157
+
158
+
159
+ def assign(conn: sqlite3.Connection, model: str = ASSIGN_MODEL,
160
+ limit: int | None = None, progress_every: int = 10) -> dict:
161
+ client = anthropic.Anthropic()
162
+ valid_paths = {r["path"] for r in conn.execute("SELECT path FROM categories")}
163
+ if not valid_paths:
164
+ raise RuntimeError("no taxonomy — run `bower categorize --taxonomy` first")
165
+ system = _system_prompt(conn)
166
+
167
+ rows = conn.execute(
168
+ """SELECT u.id, u.check_url, u.page_title, u.page_description,
169
+ (SELECT title FROM bookmarks b WHERE b.canonical_url=u.canonical_url
170
+ AND b.removed=0 LIMIT 1) AS title,
171
+ (SELECT folder_path FROM bookmarks b WHERE b.canonical_url=u.canonical_url
172
+ AND b.removed=0 LIMIT 1) AS folder_path
173
+ FROM urls u
174
+ WHERE u.status NOT IN ('skipped')
175
+ AND NOT EXISTS (SELECT 1 FROM url_categories c WHERE c.url_id=u.id)
176
+ ORDER BY u.id"""
177
+ + (f" LIMIT {int(limit)}" if limit else "")
178
+ ).fetchall()
179
+ if not rows:
180
+ return {"assigned": 0}
181
+
182
+ now = datetime.now(timezone.utc).isoformat()
183
+ cat_ids = {r["path"]: r["id"] for r in conn.execute("SELECT id, path FROM categories")}
184
+ assigned = skipped = batches = 0
185
+
186
+ for start in range(0, len(rows), BATCH_SIZE):
187
+ batch = rows[start:start + BATCH_SIZE]
188
+ lines = []
189
+ for i, r in enumerate(batch):
190
+ desc = (r["page_description"] or "")[:200]
191
+ lines.append(
192
+ f"[{i}] title: {(r['title'] or r['page_title'] or '')[:110]}\n"
193
+ f" url: {r['check_url'][:120]}\n"
194
+ f" folder: {(r['folder_path'] or '')[:80]}"
195
+ + (f"\n description: {desc}" if desc else "")
196
+ )
197
+ try:
198
+ response = client.messages.create(
199
+ model=model,
200
+ max_tokens=8000,
201
+ system=system,
202
+ output_config={"format": {"type": "json_schema", "schema": ASSIGN_SCHEMA}},
203
+ messages=[{"role": "user", "content": "Categorise these bookmarks:\n\n" + "\n".join(lines)}],
204
+ )
205
+ except anthropic.APIStatusError as exc:
206
+ print(f" batch at {start} failed: {exc.status_code} {exc.message}", flush=True)
207
+ skipped += len(batch)
208
+ continue
209
+ if response.stop_reason == "refusal":
210
+ skipped += len(batch)
211
+ continue
212
+
213
+ data = json.loads(next(b.text for b in response.content if b.type == "text"))
214
+ for item in data.get("items", []):
215
+ idx = item.get("index")
216
+ if not isinstance(idx, int) or not 0 <= idx < len(batch):
217
+ continue
218
+ url_id = batch[idx]["id"]
219
+ for cat in item.get("categories", [])[:3]:
220
+ cat_id = cat_ids.get(cat.get("path"))
221
+ if cat_id is None:
222
+ continue # hallucinated path — drop, never create
223
+ conn.execute(
224
+ """INSERT OR IGNORE INTO url_categories
225
+ (url_id, category_id, confidence, source, model, assigned_at)
226
+ VALUES(?,?,?,'llm',?,?)""",
227
+ (url_id, cat_id, float(cat.get("confidence", 0)), model, now))
228
+ assigned += 1
229
+ conn.commit()
230
+ batches += 1
231
+ if batches % progress_every == 0:
232
+ print(f" {min(start + BATCH_SIZE, len(rows))}/{len(rows)} processed", flush=True)
233
+
234
+ return {"assigned": assigned, "skipped": skipped, "batches": batches}
235
+
236
+
237
+ def rebuild_index(conn: sqlite3.Connection) -> dict:
238
+ """Rebuild the FTS5 search index from bookmarks + enrichment + categories."""
239
+ conn.execute("DELETE FROM search")
240
+ rows = conn.execute(
241
+ """SELECT u.id, u.check_url, u.page_title, u.page_description, u.page_text,
242
+ (SELECT GROUP_CONCAT(b.title, ' ') FROM bookmarks b
243
+ WHERE b.canonical_url=u.canonical_url AND b.removed=0) AS titles,
244
+ (SELECT GROUP_CONCAT(c.path, ' ; ') FROM url_categories uc
245
+ JOIN categories c ON c.id=uc.category_id WHERE uc.url_id=u.id) AS topics
246
+ FROM urls u"""
247
+ ).fetchall()
248
+ for r in rows:
249
+ conn.execute(
250
+ "INSERT INTO search(url_id, title, url, page, topics) VALUES(?,?,?,?,?)",
251
+ (r["id"], r["titles"] or "", r["check_url"],
252
+ " ".join(filter(None, [r["page_title"], r["page_description"], r["page_text"]])),
253
+ r["topics"] or ""))
254
+ conn.commit()
255
+ return {"indexed": len(rows)}