Index Maker Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Build a CLI tool that uses an LLM to create and maintain a back-of-book index for Almanack articles.
Architecture: Extract citation formatting from Django models into a shared core module. Create a CLI tool that reads the current index + new article content, passes them to the LLM via Simon Willison’s llm library, and merges the results.
Tech Stack: Python 3.11+, llm library (already installed), PyYAML, git (for change detection)
Task 1: Create the Core Citations Module
Extract the almanac-day parsing and citation formatting into a shared module.
Files:
- Create: src/almnck/core/__init__.py
- Create: src/almnck/core/citations.py
- Create: src/tests/test_citations.py
Step 1: Create the core package directory
mkdir -p src/almnck/core
Step 2: Create empty __init__.py
Create src/almnck/core/__init__.py:
"""Core utilities shared across Almanack tools."""
Step 3: Write the failing test
Create src/tests/test_citations.py:
"""Tests for citation formatting."""
import pytest
from almnck.core.citations import format_citation, parse_almanac_day
class TestParseAlmanacDay:
def test_positive_year(self):
year, month, day = parse_almanac_day("2024-01-15")
assert year == 2024
assert month == 1
assert day == 15
def test_negative_year(self):
year, month, day = parse_almanac_day("-4000-01-01")
assert year == -4000
assert month == 1
assert day == 1
def test_invalid_format_raises(self):
with pytest.raises(ValueError):
parse_almanac_day("not-a-date")
class TestFormatCitation:
def test_modern_date(self):
result = format_citation("Look Back Up", "2024-01-01")
assert result == '"Look Back Up" Vol. 6024, i·1'
def test_ancient_date(self):
result = format_citation("The First Assembly", "-4000-01-01")
assert result == '"The First Assembly" Vol. 1, i·1'
def test_month_roman_numerals(self):
# December should be xii
result = format_citation("Test", "2024-12-25")
assert result == '"Test" Vol. 6024, xii·25'
def test_all_months(self):
months = ['i', 'ii', 'iii', 'iv', 'v', 'vi',
'vii', 'viii', 'ix', 'x', 'xi', 'xii']
for i, roman in enumerate(months, 1):
result = format_citation("Test", f"2024-{i:02d}-01")
assert f", {roman}·1" in result
Step 4: Run test to verify it fails
cd src && python -m pytest tests/test_citations.py -v
Expected: FAIL with ModuleNotFoundError: No module named 'almnck.core.citations'
Step 5: Write the implementation
Create src/almnck/core/citations.py:
"""Citation formatting for Almanack articles.
Provides functions to convert almanac-day dates to canonical citation format.
"""
MONTH_ROMAN = ['i', 'ii', 'iii', 'iv', 'v', 'vi',
'vii', 'viii', 'ix', 'x', 'xi', 'xii']
def parse_almanac_day(almanac_day: str) -> tuple[int, int, int]:
"""Parse an almanac-day string into (year, month, day).
Args:
almanac_day: Date string like "2024-01-15" or "-4000-01-01"
Returns:
Tuple of (year, month, day) as integers
Raises:
ValueError: If the format is invalid
"""
try:
if almanac_day.startswith('-'):
# Negative year: -4000-01-01
parts = almanac_day[1:].split('-')
return -int(parts[0]), int(parts[1]), int(parts[2])
else:
parts = almanac_day.split('-')
return int(parts[0]), int(parts[1]), int(parts[2])
except (IndexError, ValueError) as e:
raise ValueError(f"Invalid almanac-day format: {almanac_day}") from e
def almanac_day_to_volume(year: int) -> int:
"""Convert a Gregorian year to Anno Mundi volume number.
Anno Mundi = Gregorian year + 4000, with adjustment for no year 0.
"""
if year <= 0:
return year + 4001 # -4000 -> 1 AM (no year 0)
return year + 4000 # 2024 -> 6024 AM
def format_citation(title: str, almanac_day: str) -> str:
"""Format a citation from title and almanac-day.
Args:
title: Article title
almanac_day: Date string like "2024-01-15"
Returns:
Citation like '"Look Back Up" Vol. 6024, i·1'
"""
year, month, day = parse_almanac_day(almanac_day)
volume = almanac_day_to_volume(year)
month_roman = MONTH_ROMAN[month - 1]
return f'"{title}" Vol. {volume}, {month_roman}·{day}'
Step 6: Run test to verify it passes
cd src && python -m pytest tests/test_citations.py -v
Expected: All tests PASS
Step 7: Commit
git add src/almnck/core/ src/tests/test_citations.py
git commit -m "Add core citations module with format_citation function"
Task 2: Refactor Django Model to Use Shared Citations
Update the Unit model to use the shared citations module.
Files:
- Modify: src/almnck/units/models.py
Step 1: Update the model to import from core
Edit src/almnck/units/models.py, replacing the volume_date_display property:
Replace lines 54-93 (the MONTH_ROMAN and volume_date_display code) with:
@property
def volume_date_display(self):
"""Return 'Vol. YYYY, m·D' computed from almanac-day.
Month is lowercase Roman numeral, separated from day by middot.
"""
from almnck.core.citations import parse_almanac_day, almanac_day_to_volume, MONTH_ROMAN
almanac_day = self.frontmatter.get('almanac-day', '')
if not almanac_day:
return ''
try:
year, month, day = parse_almanac_day(almanac_day)
volume = almanac_day_to_volume(year)
month_roman = MONTH_ROMAN[month - 1]
return f"Vol. {volume}, {month_roman}.{day}"
except (ValueError, IndexError):
return ''
Step 2: Verify Django still works
cd src && python manage.py check
Expected: System check identified no issues.
Step 3: Commit
git add src/almnck/units/models.py
git commit -m "Refactor Unit model to use shared citations module"
Task 3: Verify Index Scaffold Exists
The index page already exists at editorial/pages/index/page.md. Verify it’s present and has the correct structure.
Files:
- Verify: editorial/pages/index/page.md
Step 1: Check the index file exists
cat editorial/pages/index/page.md
Expected: The file should exist with frontmatter including title and status.
Step 2: If needed, update the index file structure
Ensure the file has a marker for where index entries go. If not present, add:
<!-- Index entries begin below. Maintained by bin/update-index -->
Note: The index lives under editorial/pages/ so it gets rendered as a page (at /index/) rather than as an article. This is important for the Django sync workflow.
Task 4: Create the Indexer Prompt
Write the LLM prompt template.
Files:
- Create: assets/prompts/indexer.md
Step 1: Create the prompt file
Create assets/prompts/indexer.md:
You are an indexer for the Almanack, an eclectic publication spanning all of recorded history.
Given the current index and one or more articles to index, output ONLY the new or modified index entries. Do not output the entire index—just the changes.
## Categories to Index
Extract and categorize:
- **People** — named individuals (historical figures, authors, quoted persons)
- **Places** — geographic locations (cities, countries, celestial bodies)
- **Concepts/Topics** — abstract subjects, technical terms, ideas
- **Works** — books, software, artifacts, artworks mentioned
- **Events** — named historical events, incidents
- **Organizations** — groups, institutions, companies, states
## Format Rules
1. Entries are alphabetized under letter headings (## A, ## B, etc.)
2. Sub-entries are indented with two spaces
3. Each entry ends with one or more citations
4. Cross-references use "see also:" format
5. Use the exact citation format provided for each article
Example format:
B
Backup systems — “Look Back Up” Vol. 6024, i·1 borg — “Look Back Up” Vol. 6024, i·1 rsync — “Look Back Up” Vol. 6024, i·1
## Instructions
1. Read the current index to understand existing entries
2. Read the new article(s) carefully
3. Identify all indexable terms from the categories above
4. For each term:
- If it's new, create an entry under the appropriate letter
- If it already exists, add the new citation to it
- If it's a sub-topic of an existing entry, nest it appropriately
5. Output ONLY the letter sections that have changes
6. Maintain alphabetical order within each section
## Current Index
{current_index}
## Article to Index
**Citation:** {citation}
{article_content}
---
Output the new or modified index entries below. Include only changed letter sections.
Step 2: Commit
git add assets/prompts/indexer.md
git commit -m "Add indexer prompt template"
Task 5: Create the Update-Index CLI Tool
Build the main CLI tool.
Files:
- Create: bin/update-index
- Create: src/tests/test_update_index.py
Step 1: Write tests for helper functions
Create src/tests/test_update_index.py:
"""Tests for update-index CLI helpers."""
import pytest
from pathlib import Path
import tempfile
import os
# We'll test the functions once they exist
# For now, just test the module can be imported
def test_placeholder():
"""Placeholder until we have testable functions."""
assert True
Step 2: Create the CLI tool
Create bin/update-index:
#!/usr/bin/env python3
"""Update the Almanack index with new article entries.
Usage:
update-index article-slug [article-slug ...] # index specific articles
update-index --new # index all un-indexed articles
update-index --status # show what needs attention
"""
import argparse
import subprocess
import sys
from pathlib import Path
# Add src to path for imports
ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(ROOT / 'src'))
import yaml
import llm
from almnck.core.citations import format_citation
def get_root() -> Path:
"""Get the Almanack root directory."""
return Path(__file__).parent.parent
def parse_frontmatter(content: str) -> tuple[dict, str]:
"""Parse YAML frontmatter and body from content."""
if not content.startswith('---'):
return {}, content
parts = content.split('---', 2)
if len(parts) < 3:
return {}, content
try:
fm = yaml.safe_load(parts[1]) or {}
return fm, parts[2].strip()
except yaml.YAMLError:
return {}, content
def find_content_file(unit_dir: Path) -> Path | None:
"""Find main content file in unit directory."""
for name in ['article.md', 'page.md', 'banner.md', 'index.md']:
path = unit_dir / name
if path.exists():
return path
for f in unit_dir.glob('*.md'):
return f
return None
def get_published_articles() -> list[tuple[str, Path, dict]]:
"""Get all published articles with their metadata.
Returns list of (slug, path, frontmatter) tuples.
"""
root = get_root()
articles_dir = root / 'editorial' / 'articles'
results = []
for unit_dir in articles_dir.iterdir():
if not unit_dir.is_dir():
continue
content_file = find_content_file(unit_dir)
if not content_file:
continue
content = content_file.read_text()
fm, _ = parse_frontmatter(content)
if fm.get('status') == 'published' and fm.get('almanac-day'):
results.append((unit_dir.name, content_file, fm))
return results
def get_index_content() -> str:
"""Read the current index content."""
root = get_root()
index_file = root / 'editorial' / 'pages' / 'index' / 'page.md'
if not index_file.exists():
return ""
content = index_file.read_text()
_, body = parse_frontmatter(content)
return body
def get_index_last_commit() -> str | None:
"""Get the last commit hash that modified the index."""
root = get_root()
index_file = root / 'editorial' / 'pages' / 'index' / 'page.md'
if not index_file.exists():
return None
try:
result = subprocess.run(
['git', 'log', '-1', '--format=%H', '--', str(index_file)],
capture_output=True, text=True, cwd=root
)
return result.stdout.strip() or None
except subprocess.CalledProcessError:
return None
def get_article_last_commit(article_path: Path) -> str | None:
"""Get the last commit hash that modified an article."""
root = get_root()
try:
result = subprocess.run(
['git', 'log', '-1', '--format=%H', '--', str(article_path)],
capture_output=True, text=True, cwd=root
)
return result.stdout.strip() or None
except subprocess.CalledProcessError:
return None
def is_article_in_index(slug: str, index_content: str) -> bool:
"""Check if an article slug appears in the index."""
# Simple heuristic: check if the slug appears in any citation
return slug.replace('-', ' ').lower() in index_content.lower() or slug in index_content
def is_newer_than(commit_a: str | None, commit_b: str | None) -> bool:
"""Check if commit_a is newer than commit_b."""
if not commit_a or not commit_b:
return False
root = get_root()
try:
# Use git merge-base --is-ancestor
result = subprocess.run(
['git', 'merge-base', '--is-ancestor', commit_b, commit_a],
capture_output=True, cwd=root
)
return result.returncode == 0
except subprocess.CalledProcessError:
return False
def cmd_status():
"""Show status of articles vs index."""
index_content = get_index_content()
index_commit = get_index_last_commit()
articles = get_published_articles()
new_articles = []
changed_articles = []
up_to_date = []
for slug, path, fm in articles:
title = fm.get('title', slug)
article_commit = get_article_last_commit(path)
if not is_article_in_index(title, index_content):
new_articles.append((slug, title))
elif is_newer_than(article_commit, index_commit):
changed_articles.append((slug, title))
else:
up_to_date.append((slug, title))
if new_articles:
print("New (not indexed):")
for slug, title in new_articles:
print(f" {slug}")
if changed_articles:
print("\nChanged since indexed:")
for slug, title in changed_articles:
print(f" ⚠ {slug}")
if up_to_date:
print("\nUp to date:")
for slug, title in up_to_date:
print(f" ✓ {slug}")
if not any([new_articles, changed_articles, up_to_date]):
print("No published articles found.")
def cmd_index(slugs: list[str]):
"""Index specific articles."""
root = get_root()
articles_dir = root / 'editorial' / 'articles'
# Load current index
index_content = get_index_content()
# Load prompt template
prompt_file = root / 'assets' / 'prompts' / 'indexer.md'
if not prompt_file.exists():
print(f"Error: Prompt template not found at {prompt_file}", file=sys.stderr)
sys.exit(1)
prompt_template = prompt_file.read_text()
# Process each article
for slug in slugs:
article_dir = articles_dir / slug
if not article_dir.exists():
print(f"Warning: Article not found: {slug}", file=sys.stderr)
continue
content_file = find_content_file(article_dir)
if not content_file:
print(f"Warning: No content file in {slug}", file=sys.stderr)
continue
content = content_file.read_text()
fm, body = parse_frontmatter(content)
title = fm.get('title', slug)
almanac_day = fm.get('almanac-day')
if not almanac_day:
print(f"Warning: No almanac-day in {slug}", file=sys.stderr)
continue
citation = format_citation(title, almanac_day)
print(f"Indexing: {citation}")
# Build the prompt
prompt = prompt_template.replace('{current_index}', index_content)
prompt = prompt.replace('{citation}', citation)
prompt = prompt.replace('{article_content}', body)
# Call LLM
model = llm.get_model()
response = model.prompt(prompt)
print("\n--- New/Modified Index Entries ---")
print(response.text())
print("-----------------------------------\n")
# TODO: Implement automatic merging
print("(Manual merge required for now. Copy entries above into editorial/pages/index/page.md)")
def cmd_new():
"""Index all un-indexed published articles."""
index_content = get_index_content()
articles = get_published_articles()
new_slugs = []
for slug, path, fm in articles:
title = fm.get('title', slug)
if not is_article_in_index(title, index_content):
new_slugs.append(slug)
if not new_slugs:
print("All published articles are already indexed.")
return
print(f"Found {len(new_slugs)} un-indexed article(s): {', '.join(new_slugs)}")
cmd_index(new_slugs)
def main():
parser = argparse.ArgumentParser(description='Update the Almanack index')
parser.add_argument('slugs', nargs='*', help='Article slugs to index')
parser.add_argument('--status', action='store_true', help='Show index status')
parser.add_argument('--new', action='store_true', help='Index all un-indexed articles')
args = parser.parse_args()
if args.status:
cmd_status()
elif args.new:
cmd_new()
elif args.slugs:
cmd_index(args.slugs)
else:
parser.print_help()
if __name__ == '__main__':
main()
Step 3: Make executable
chmod +x bin/update-index
Step 4: Test the –status command
bin/update-index --status
Expected: Should list published articles and their index status
Step 5: Commit
git add bin/update-index src/tests/test_update_index.py
git commit -m "Add update-index CLI tool"
Task 6: Add Make Targets
Add convenience targets to the Makefile.
Files:
- Modify: Makefile
Step 1: Add index targets to Makefile
Add after line 68 (after the editorial-commit target):
# Index targets
.PHONY: index-status
index-status: check-activated
@$(ALMANACK_ROOT)/bin/update-index --status
.PHONY: index-new
index-new: check-activated
@$(ALMANACK_ROOT)/bin/update-index --new
Step 2: Update help text
Add to the help target (after Editorial section, around line 23):
@echo ""
@echo "$(YELLOW)Index:$(RESET)"
@echo " index-status Show which articles need indexing"
@echo " index-new Index all un-indexed articles"
Step 3: Test the make target
make index-status
Expected: Same output as bin/update-index --status
Step 4: Commit
git add Makefile
git commit -m "Add index make targets"
Task 7: Test End-to-End
Verify the complete workflow works.
Step 1: Check status
make index-status
Step 2: Index one article (dry run)
bin/update-index look-back-up
Review the LLM output for sensible index entries.
Step 3: If output looks good, manually add entries to index
Edit editorial/pages/index/page.md and add the generated entries.
Step 4: Commit the updated index
git add editorial/pages/index/page.md
git commit -m "Index: add entries for look-back-up"
Step 5: Verify status updated
make index-status
Expected: look-back-up should now show as “Up to date” (if the title detection works) or no longer appear in “New”
Future Improvements (Not in this plan)
- Automatic merging of LLM output into the index file
- Better title-to-index matching for status detection
- Style and tone guidance in the prompt
- Index page rendering in Django
Addendum (2026-01-17): Makefile commands were reorganized. index-status → idx-status, index-new → idx-new, index-all → idx-all.