-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverge-tags.py
More file actions
887 lines (698 loc) · 29.2 KB
/
Copy pathconverge-tags.py
File metadata and controls
887 lines (698 loc) · 29.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
#!/usr/bin/env python3
"""
converge-tags.py — Reduce tag sprawl in GoodLinks by merging redundant tags.
Identifies semantically similar tag pairs and low-count tags that can be
absorbed into broader categories, presents suggestions interactively, and
applies approved merges via the GoodLinks API.
Environment:
GOODLINKS_TOKEN — GoodLinks API token.
ANTHROPIC_API_KEY — Anthropic API key.
"""
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from pathlib import Path
import anthropic
# ── Configuration ──────────────────────────────────────────────────────────────
GOODLINKS_BASE = "http://localhost:9428/api/v1"
PROPOSALS_FILE = Path("./proposals.json")
FETCH_TIMEOUT = 15
PAGE_LIMIT = 100
LLM_MODEL = "claude-haiku-4-5-20251001"
MAX_RETRIES = 3
# ── Data Models ────────────────────────────────────────────────────────────────
@dataclass
class TagCount:
"""A tag name paired with its article count.
Attributes:
name: kebab-case tag name.
count: Number of links with this tag.
"""
name: str
count: int
@dataclass
class MergeSuggestion:
"""A proposed merge operation (covers both similar-pair and absorption).
Attributes:
source_tags: Tags to be removed (1 for absorption, 2 for similar-pair).
target_tag: Tag to receive the articles.
source_counts: Article counts for source tags (parallel with source_tags).
target_count: Article count for the target tag.
merge_type: Either "similar-pair" or "absorption".
"""
source_tags: list[str]
target_tag: str
source_counts: list[int]
target_count: int
merge_type: str
@dataclass
class MergeResult:
"""Outcome of applying a single merge.
Attributes:
suggestion: The merge suggestion that was applied.
links_retagged: Number of links successfully re-tagged.
failures: Number of link updates that failed.
"""
suggestion: MergeSuggestion
links_retagged: int
failures: int
# ── Private Helpers ────────────────────────────────────────────────────────────
def _gl_request(method: str, path: str, body=None):
"""Send an authenticated request to the GoodLinks API.
Constructs a JSON request against ``GOODLINKS_BASE`` using the bearer
token stored in the ``GOODLINKS_TOKEN`` environment variable.
Args:
method: HTTP method (e.g. ``"GET"``, ``"PATCH"``).
path: API path appended to ``GOODLINKS_BASE`` (e.g. ``"/tags"``).
body: Optional Python object serialised as JSON for the request body.
Defaults to ``None``.
Returns:
The parsed JSON response body.
Raises:
KeyError: If the ``GOODLINKS_TOKEN`` environment variable is not set.
urllib.error.URLError: If the network request fails or times out
(15-second timeout).
"""
print("Calling the GoodLinks API...", file=sys.stderr)
url = f"{GOODLINKS_BASE}{path}"
data = json.dumps(body).encode() if body else None
req = urllib.request.Request(
url,
data=data,
method=method,
headers={
"Authorization": f"Bearer {os.environ['GOODLINKS_TOKEN']}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp:
return json.load(resp)
def _call_claude(prompt: str, max_tokens: int) -> str:
"""Call the Claude API with exponential backoff retry.
Sends a single-message conversation to Claude and returns the text
response. Retries up to ``MAX_RETRIES`` times on
``anthropic.RateLimitError`` with exponential backoff (60s on first
retry, then 2 ** attempt seconds).
Args:
prompt: The user message to send to Claude.
max_tokens: Maximum tokens in Claude's response.
Returns:
The text content of Claude's response.
Raises:
RuntimeError: If all retry attempts are exhausted or a
non-rate-limit error occurs.
"""
client = anthropic.Anthropic()
last_err: Exception | None = None
for attempt in range(MAX_RETRIES):
try:
print("Calling Claude...", prompt, file=sys.stderr)
msg = client.messages.create(
model=LLM_MODEL,
max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
)
return msg.content[0].text.strip()
except anthropic.RateLimitError as e:
wait = 60 if attempt == 0 else 2 ** attempt
print(
f" [rate-limit] attempt {attempt + 1}/{MAX_RETRIES}, "
f"sleeping {wait}s…",
file=sys.stderr,
flush=True,
)
time.sleep(wait)
last_err = e
except Exception as e:
last_err = e
break
raise RuntimeError(
f"Claude API failed after {MAX_RETRIES} attempts: {last_err}"
)
def _compute_merged_tags(
existing_tags: set[str], source_tag: str, target_tag: str
) -> set[str]:
"""Compute the resulting tag set after a merge operation.
Applies the merge logic: remove the source tag and add the target tag.
The target tag appears exactly once regardless of whether it was already
present, the source tag is removed, and all other tags are preserved
unchanged.
Args:
existing_tags: The current set of tags on a link.
source_tag: The tag to be removed.
target_tag: The tag to be added.
Returns:
The new tag set: ``(existing_tags - {source_tag}) | {target_tag}``.
"""
print("Computing merged tags...", file=sys.stderr)
return (existing_tags - {source_tag}) | {target_tag}
def _classify_input(text: str) -> str | None:
"""Classify interactive approval prompt input.
Determines whether a user's input to the approval prompt represents
approval, rejection, or an unrecognized response requiring re-prompt.
Args:
text: Raw user input string from the approval prompt.
Returns:
``"approve"`` if the stripped, lowercased input is ``"y"`` or
``"yes"``; ``"reject"`` if it is ``"n"`` or ``"no"``; ``None``
for all other strings (indicating re-prompt needed).
"""
normalized = text.strip().lower()
if normalized in ("y", "yes"):
return "approve"
if normalized in ("n", "no"):
return "reject"
return None
def _parse_claude_json(raw: str):
"""Strip markdown fences and extract JSON from Claude's response.
Handles both fenced (```json ... ```) and unfenced JSON responses.
Uses ``json.JSONDecoder.raw_decode`` to extract the first complete
JSON value, avoiding issues with trailing text or greedy regex matching.
Args:
raw: The raw text response from Claude.
Returns:
The parsed JSON value (typically a list or dict).
Raises:
ValueError: If no valid JSON structure is found in the response.
"""
print("Parsing Claude response...", file=sys.stderr)
# Strip markdown fences
cleaned = re.sub(
r"^```(?:json)?\s*|\s*```$", "", raw, flags=re.MULTILINE
).strip()
# Find the first [ or { character
decoder = json.JSONDecoder()
for i, ch in enumerate(cleaned):
if ch in ("[", "{"):
try:
obj, _ = decoder.raw_decode(cleaned, i)
return obj
except json.JSONDecodeError:
continue
raise ValueError(f"No JSON structure found in response: {raw!r}")
# ── Phase 1: Fetch Tags with Counts ────────────────────────────────────────────
def _fetch_all_links_for_tag(tag: str) -> list[dict]:
"""Fetch all links tagged with a given tag, paginating until exhausted.
Queries ``GET /links`` with the ``tag`` filter and paginates using
``offset`` and ``limit`` parameters until the API reports
``hasMore: false``.
Args:
tag: The tag name to filter links by.
Returns:
A list of link dicts returned by the GoodLinks API.
Raises:
urllib.error.URLError: If a network or timeout error occurs.
urllib.error.HTTPError: If the API returns a non-2xx status.
"""
print("Fetch all links for tag...", file=sys.stderr)
all_links: list[dict] = []
offset = 0
while True:
params = urllib.parse.urlencode({
"tag": tag,
"offset": offset,
"limit": PAGE_LIMIT,
})
path = f"/links?{params}"
resp = _gl_request("GET", path)
links = resp.get("data", [])
all_links.extend(links)
if not resp.get("hasMore", False):
break
offset += PAGE_LIMIT
return all_links
def _fetch_tags_with_counts() -> list[TagCount]:
"""Retrieve all tags and their article counts from the GoodLinks API.
Calls ``GET /tags`` for the full tag list, then for each tag queries
``GET /links?tag={tag}`` with pagination to determine the total
link count. Prints the tag-count summary to stdout as a JSON array
sorted alphabetically by tag name.
Returns:
A list of ``TagCount`` objects sorted alphabetically by name.
Side Effects:
Prints a JSON array of ``{"name": ..., "count": ...}`` objects to
stdout.
Raises:
SystemExit: With exit code 2 if the GoodLinks API is unreachable,
returns an HTTP error, or times out.
"""
print("Fetch tags with counts...", file=sys.stderr)
try:
tags_response = _gl_request("GET", "/tags")
except urllib.error.HTTPError as e:
url = f"{GOODLINKS_BASE}/tags"
print(
f"Error: HTTP {e.code} from {url}: {e.reason}",
file=sys.stderr,
)
sys.exit(2)
except urllib.error.URLError as e:
url = f"{GOODLINKS_BASE}/tags"
print(
f"Error: cannot reach {url}: {e.reason}",
file=sys.stderr,
)
sys.exit(2)
tag_names: list[str] = tags_response if isinstance(
tags_response, list
) else tags_response.get("tags", [])
results: list[TagCount] = []
for tag_name in tag_names:
try:
links = _fetch_all_links_for_tag(tag_name)
except urllib.error.HTTPError as e:
url = (
f"{GOODLINKS_BASE}/links?tag={tag_name}"
f"&offset=0&limit={PAGE_LIMIT}"
)
print(
f"Error: HTTP {e.code} from {url}: {e.reason}",
file=sys.stderr,
)
sys.exit(2)
except urllib.error.URLError as e:
url = (
f"{GOODLINKS_BASE}/links?tag={tag_name}"
f"&offset=0&limit={PAGE_LIMIT}"
)
print(
f"Error: cannot reach {url}: {e.reason}",
file=sys.stderr,
)
sys.exit(2)
results.append(TagCount(name=tag_name, count=len(links)))
results.sort(key=lambda tc: tc.name)
# Print tag-count summary to stdout as JSON array.
summary = [{"name": tc.name, "count": tc.count} for tc in results]
print(json.dumps(summary, indent=2))
return results
# ── Phase 2: Analyze Tags ──────────────────────────────────────────────────────
def _passes_threshold(count_a: int, count_b: int) -> bool:
"""Check whether two tag counts are within the 33% similarity threshold.
The pair passes if the smaller count is at least 67% of the larger count:
``min(count_a, count_b) / max(count_a, count_b) >= 0.67``.
Args:
count_a: Article count for the first tag (must be positive).
count_b: Article count for the second tag (must be positive).
Returns:
``True`` if the pair passes the threshold, ``False`` otherwise.
"""
print("Checking thresholds...", file=sys.stderr)
return min(count_a, count_b) / max(count_a, count_b) >= 0.67
def _find_similar_pairs(tags_with_counts: list[TagCount]) -> list[MergeSuggestion]:
"""Identify semantically similar tag pairs via Claude and filter by count.
Sends all tag names (without counts) to Claude requesting pairs of
semantically equivalent tags. Filters the returned pairs by the 33%
count-similarity threshold and constructs ``MergeSuggestion`` objects
for qualifying pairs.
Args:
tags_with_counts: The complete list of tags with their article counts.
Returns:
A list of ``MergeSuggestion`` objects with ``merge_type="similar-pair"``
for each pair that passes the threshold filter.
Raises:
SystemExit: With exit code 3 if the Claude API call fails after retries.
"""
print("Finding similar pairings...", file=sys.stderr)
tag_names = [tc.name for tc in tags_with_counts]
counts_by_name = {tc.name: tc.count for tc in tags_with_counts}
prompt = (
"You are analyzing a tag taxonomy for a bookmarks manager.\n"
"Below is the complete list of tags. Identify pairs of tags that are\n"
"semantically equivalent or overlapping (synonyms, abbreviations,\n"
"spelling variants, or near-duplicates that refer to the same "
"concept).\n\n"
"Do NOT pair tags that are merely related or in the same category.\n"
"Only pair tags where one could fully replace the other without loss "
"of meaning.\n\n"
f"Tags:\n{json.dumps(tag_names)}\n\n"
"For each pair, suggest a single unified tag name in kebab-case "
"lowercase.\n"
"Respond with JSON only (no markdown fences):\n"
"[\n"
' {"tag_a": "...", "tag_b": "...", "suggested_name": "..."},\n'
" ...\n"
"]\n"
"If no pairs are found, respond with an empty array: []"
)
try:
raw = _call_claude(prompt, max_tokens=4096)
except RuntimeError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(3)
parsed = _parse_claude_json(raw)
# If Claude returned a dict instead of a list, try to extract a list.
if isinstance(parsed, dict):
# Look for the first value that is a list.
extracted = None
for v in parsed.values():
if isinstance(v, list):
extracted = v
break
# If no list found but the dict looks like a single pair, wrap it.
if extracted is None and "tag_a" in parsed:
extracted = [parsed]
parsed = extracted if extracted is not None else []
suggestions: list[MergeSuggestion] = []
for pair in parsed:
if not isinstance(pair, dict):
continue
tag_a = pair.get("tag_a", "")
tag_b = pair.get("tag_b", "")
suggested_name = pair.get("suggested_name", "")
# Skip pairs referencing tags not in the original list.
if tag_a not in counts_by_name or tag_b not in counts_by_name:
continue
count_a = counts_by_name[tag_a]
count_b = counts_by_name[tag_b]
if not _passes_threshold(count_a, count_b):
continue
# Determine source_tags and target_count.
source_tags = [tag_a, tag_b]
source_counts = [count_a, count_b]
# target_count is the count of whichever source equals the target,
# or the max if the target is a new name.
if suggested_name == tag_a:
target_count = count_a
elif suggested_name == tag_b:
target_count = count_b
else:
target_count = max(count_a, count_b)
suggestions.append(
MergeSuggestion(
source_tags=source_tags,
target_tag=suggested_name,
source_counts=source_counts,
target_count=target_count,
merge_type="similar-pair",
)
)
return suggestions
def _find_absorption_targets(
tags_with_counts: list[TagCount],
) -> list[MergeSuggestion]:
"""Identify low-count tags that can be absorbed into broader high-count tags.
For each tag with an article count between 1 and 9 inclusive, sends a
targeted prompt to Claude asking it to select the single most semantically
similar tag from among all tags with count > 9. Tags where Claude cannot
find a suitable match are skipped.
Args:
tags_with_counts: Complete list of ``TagCount`` objects representing
all tags and their article counts.
Returns:
A list of ``MergeSuggestion`` objects with ``merge_type="absorption"``,
one per low-count tag that Claude matched to a higher-count target.
Side Effects:
Prints rate-limit retry messages to stderr during Claude API calls.
Raises:
SystemExit: With exit code 3 if a Claude API call fails after all
retry attempts.
"""
print("Finding absorbtion targets...", file=sys.stderr)
low_count_tags = [tc for tc in tags_with_counts if 1 <= tc.count <= 9]
high_count_tags = [tc for tc in tags_with_counts if tc.count > 9]
if not low_count_tags or not high_count_tags:
return []
candidate_names = [tc.name for tc in high_count_tags]
high_count_map = {tc.name: tc.count for tc in high_count_tags}
suggestions: list[MergeSuggestion] = []
for tag in low_count_tags:
prompt = (
"You are analyzing a tag taxonomy for a bookmarks manager.\n"
f'A tag "{tag.name}" has very few articles ({tag.count}).\n'
"\n"
"Below are existing tags with more than 9 articles that could "
"potentially\n"
"absorb this tag. Select the single most semantically similar tag "
"that\n"
"could serve as a broader category encompassing "
f'"{tag.name}".\n'
"\n"
"Candidate targets:\n"
f"{json.dumps(candidate_names)}\n"
"\n"
"If none of the candidates are semantically similar enough to "
f'absorb\n"{tag.name}", respond with: {{"target": null}}\n'
"\n"
"Otherwise respond with JSON only (no markdown fences):\n"
'{"target": "chosen-tag-name"}'
)
try:
raw = _call_claude(prompt, max_tokens=100)
except RuntimeError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(3)
try:
parsed = _parse_claude_json(raw)
except ValueError:
# Could not parse response — skip this tag.
continue
target = parsed.get("target") if isinstance(parsed, dict) else None
if target is None:
continue
# Validate the target actually exists in the high-count list.
if target not in high_count_map:
continue
suggestions.append(
MergeSuggestion(
source_tags=[tag.name],
target_tag=target,
source_counts=[tag.count],
target_count=high_count_map[target],
merge_type="absorption",
)
)
return suggestions
def _write_proposals(suggestions: list[MergeSuggestion]) -> None:
"""Serialize merge suggestions to JSON and write to the proposals file.
Converts each ``MergeSuggestion`` to a dict matching the JSON output
schema (``merge_type``, ``source_tags``, ``source_counts``,
``target_tag``, ``target_count``) and writes them as a pretty-printed
JSON array to ``PROPOSALS_FILE``.
Args:
suggestions: The list of merge suggestions to serialize.
Side Effects:
Writes a JSON file to ``PROPOSALS_FILE``.
Prints a confirmation message to stdout on success.
Raises:
SystemExit: With exit code 4 if the file write fails due to
permissions, disk space, or other I/O errors.
"""
print("Write proposals...", file=sys.stderr)
records = [
{
"merge_type": s.merge_type,
"source_tags": s.source_tags,
"source_counts": s.source_counts,
"target_tag": s.target_tag,
"target_count": s.target_count,
} for s in suggestions
]
try:
PROPOSALS_FILE.write_text(json.dumps(records, indent=2))
except (IOError, OSError) as e:
print(
f"Error: failed to write {PROPOSALS_FILE}: {e}",
file=sys.stderr,
)
sys.exit(4)
print(f"Wrote {len(suggestions)} proposals to {PROPOSALS_FILE}")
# ── Phase 3: Present Suggestions ───────────────────────────────────────────────
def _present_suggestions(
suggestions: list[MergeSuggestion],
) -> list[MergeSuggestion]:
"""Display merge suggestions interactively and collect user approvals.
Presents each suggestion to the user showing source tag(s), target tag,
article counts, and merge type. Prompts for approval (y/yes) or
rejection (n/no), re-prompting on unrecognized input. If the suggestions
list is empty, prints an informational message and exits.
Args:
suggestions: The list of merge suggestions to present. May be empty.
Returns:
A list of ``MergeSuggestion`` objects that the user approved.
Side Effects:
Prints each suggestion and prompt to stdout.
Reads interactive input from stdin via ``input()``.
Raises:
SystemExit: With exit code 0 if no suggestions are provided.
"""
print("Print suggestions...", file=sys.stderr)
if not suggestions:
print("No convergence opportunities found.")
sys.exit(0)
total = len(suggestions)
approved: list[MergeSuggestion] = []
for idx, suggestion in enumerate(suggestions, start=1):
# Format source tags with counts.
source_parts = " + ".join(
f'"{tag}" ({count})'
for tag, count in zip(
suggestion.source_tags, suggestion.source_counts
)
)
label = (
f"[{idx}/{total}] {suggestion.merge_type}: "
f'{source_parts} \u2192 "{suggestion.target_tag}" '
f"({suggestion.target_count})"
)
print(label)
# Prompt until valid input received.
while True:
response = input("Approve? [y/n]: ")
classification = _classify_input(response)
if classification == "approve":
approved.append(suggestion)
break
elif classification == "reject":
break
else:
print("Please enter 'y' or 'n'.")
return approved
# ── Phase 4: Apply Merges ──────────────────────────────────────────────────────
def _apply_merges(approved: list[MergeSuggestion]) -> list[MergeResult]:
"""Execute approved merges by re-tagging links via the GoodLinks API.
For each approved merge suggestion, iterates over its source tags,
fetches all links with that source tag, and PATCHes each link to add
the target tag and remove the source tag. Tracks successes and failures
per merge, printing progress to stdout and errors to stderr.
Args:
approved: List of user-approved ``MergeSuggestion`` objects to apply.
Returns:
A list of ``MergeResult`` objects, one per approved merge, reporting
the number of links successfully re-tagged and the number of failures.
Side Effects:
Prints per-merge confirmation or skip messages to stdout.
Prints per-link error messages to stderr on PATCH failure.
"""
print("Apply merges...", file=sys.stderr)
results: list[MergeResult] = []
for suggestion in approved:
links_retagged = 0
failures = 0
for source_tag in suggestion.source_tags:
try:
links = _fetch_all_links_for_tag(source_tag)
except (urllib.error.URLError, urllib.error.HTTPError) as e:
print(
f' Error fetching links for "{source_tag}": {e}',
file=sys.stderr,
)
links = []
if not links:
print(
f'Skipped "{source_tag}" \u2192 '
f'"{suggestion.target_tag}": no links found'
)
continue
for link in links:
link_id = link.get("id", "unknown")
url = link.get("url", "unknown")
body = {
"addedTags": [suggestion.target_tag],
"removedTags": [source_tag],
}
try:
_gl_request("PATCH", f"/links/{link_id}", body)
links_retagged += 1
except Exception as e:
failures += 1
print(
f" Error updating link {link_id} ({url}): {e}",
file=sys.stderr,
)
print(
f'Merged "{source_tag}" \u2192 '
f'"{suggestion.target_tag}": {len(links)} links re-tagged'
)
results.append(
MergeResult(
suggestion=suggestion,
links_retagged=links_retagged,
failures=failures,
)
)
return results
def _print_summary(results: list[MergeResult]) -> None:
"""Print a formatted summary of all merge operations to stdout.
Aggregates statistics from the list of merge results and prints a
human-readable summary showing total merges attempted, fully successful
merges, total links re-tagged, and total link update failures.
Args:
results: List of ``MergeResult`` objects from ``_apply_merges()``.
Side Effects:
Prints the summary block to stdout.
"""
print("Print a summary...", file=sys.stderr)
merges_attempted = len(results)
merges_successful = sum(1 for r in results if r.failures == 0)
total_links_retagged = sum(r.links_retagged for r in results)
total_failures = sum(r.failures for r in results)
print("\n── Summary ──")
print(f"Merges attempted : {merges_attempted}")
print(f"Merges successful : {merges_successful}")
print(f"Links re-tagged : {total_links_retagged}")
print(f"Failures : {total_failures}")
# ── Entry Point ────────────────────────────────────────────────────────────────
def _validate_env() -> list[str]:
"""Check that all required environment variables are set and non-empty.
Returns:
A list of variable names that are missing or empty. An empty list
means all required variables are present.
"""
print("Validating the environment...", file=sys.stderr)
required_vars = ("GOODLINKS_TOKEN", "ANTHROPIC_API_KEY")
return [var for var in required_vars if not os.environ.get(var)]
def main():
"""Entry point: converge redundant tags in a GoodLinks library.
Orchestrates the full pipeline:
1. Validate required environment variables.
2. Phase 1 — Fetch all tags with article counts from the GoodLinks API.
3. Phase 2 — Analyze tags via Claude AI (similar pairs + absorption).
4. Phase 3 — Present suggestions interactively and collect approvals.
5. Phase 4 — Apply approved merges via the GoodLinks API.
Exit Codes:
0: Success (including "no suggestions" or "no approved" paths).
1: Missing environment variables.
2: GoodLinks API unreachable or HTTP error during fetch phase.
3: Claude API failure after retries.
4: File I/O error writing proposals JSON.
Side Effects:
Prints tag-count summary, merge proposals, per-merge confirmations,
and a final summary to stdout. Prints error messages to stderr.
Raises:
SystemExit: On any fatal error condition (see exit codes above).
"""
# 1. Validate environment
missing = _validate_env()
if missing:
print(
f"Error: missing environment variable(s): {', '.join(missing)}",
file=sys.stderr,
)
sys.exit(1)
# 2. Phase 1: Fetch tags with counts
tags_with_counts = _fetch_tags_with_counts()
# 3. Phase 2: Analyze via Claude
similar_pairs = _find_similar_pairs(tags_with_counts)
absorption_targets = _find_absorption_targets(tags_with_counts)
all_suggestions = similar_pairs + absorption_targets
_write_proposals(all_suggestions)
# 4. Phase 3: Present suggestions interactively
approved = _present_suggestions(all_suggestions)
# 5. Handle "no approved" early exit
if not approved:
print("No merges approved.")
_print_summary([])
sys.exit(0)
# 6. Phase 4: Apply approved merges
results = _apply_merges(approved)
# 7. Print summary
_print_summary(results)
if __name__ == "__main__":
main()