Manual
Almnck.
Price: 50ⓐ

Editorial Pipeline Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Build a Django-based publishing pipeline where git is truth, with static site output via django-distill.

Architecture: Django syncs from editorial/ directory, provides admin UI for editing, writes changes back to files. manage.py build-with-distill generates static web/ output.

Tech Stack: Django 5.0, django-distill, Python 3.11, uv, SQLite (dev), Markdown with YAML frontmatter


Task 1: Clean Up Old Structure

Files: - Delete: assets/editorial/ (entire directory) - Delete: src/almnck/__init__.py (will be replaced) - Delete: almnck.egg-info/, dist/ (build artifacts) - Keep: assets/dingbats/, assets/fonts/, assets/pandoc/, assets/vale/

Step 1: Back up the one real article before deletion

mkdir -p /tmp/almnck-backup
cp -r assets/editorial/09final/integrity-new-years-backups /tmp/almnck-backup/
cp assets/editorial/00inbox/beth-slouch-packets-from-davos/brigadoon.md /tmp/almnck-backup/
cp assets/editorial/00inbox/aaron-memorial/aaron.txt /tmp/almnck-backup/

Step 2: Remove old structure

rm -rf assets/editorial/
rm -rf almnck.egg-info/ dist/
rm -f src/almnck/__init__.py

Step 3: Commit the cleanup

git add -A
git commit -m "Remove old editorial structure and build artifacts

Preparing for new Django-based pipeline. Content backed up locally."

Task 2: Create New Directory Structure

Files: - Create: editorial/ (new root for all content) - Create: editorial/articles/ - Create: editorial/pages/ - Create: editorial/inbox/ - Create: src/almnck/ (Django project)

Step 1: Create editorial directory structure

mkdir -p editorial/articles
mkdir -p editorial/pages
mkdir -p editorial/inbox

Step 2: Create placeholder files

Create editorial/.gitkeep:

# This directory contains all publishable content
# See doc/plans/2026-01-02-editorial-pipeline-design.md

Step 3: Commit structure

git add editorial/
git commit -m "Create new editorial directory structure"

Task 3: Migrate Existing Content

Files: - Create: editorial/articles/look-back-up/article.md - Create: editorial/articles/look-back-up/assets/ - Create: editorial/articles/look-back-up/editorial/ - Create: editorial/inbox/aaron-memorial/ - Create: editorial/inbox/packets-from-davos/

Step 1: Create look-back-up article directory

mkdir -p editorial/articles/look-back-up/assets
mkdir -p editorial/articles/look-back-up/editorial

Step 2: Migrate article with updated frontmatter

Create editorial/articles/look-back-up/article.md with this frontmatter:

---
title: "Look Back Up"
author: "Integrity Mather"
author_path: "/~integrity/"
day: jan-01
path: /jan/01/look-back-up/
status: editing
---

Then append the body content from /tmp/almnck-backup/integrity-new-years-backups/new-years-backups.md (everything after the original frontmatter, excluding the ::: {#markdownBody} wrapper).

Step 3: Copy assets

cp /tmp/almnck-backup/integrity-new-years-backups/*.png editorial/articles/look-back-up/assets/

Step 4: Migrate editorial notes

cp /tmp/almnck-backup/integrity-new-years-backups/FACTS.md editorial/articles/look-back-up/editorial/
cp /tmp/almnck-backup/integrity-new-years-backups/0PASS.md editorial/articles/look-back-up/editorial/

Step 5: Create inbox items

mkdir -p editorial/inbox/aaron-memorial
mkdir -p editorial/inbox/packets-from-davos

cp /tmp/almnck-backup/aaron.txt editorial/inbox/aaron-memorial/
cp /tmp/almnck-backup/brigadoon.md editorial/inbox/packets-from-davos/

Step 6: Commit migration

git add editorial/
git commit -m "Migrate existing content to new structure

- look-back-up article with updated frontmatter
- Inbox items preserved for future editing"

Task 4: Initialize Django Project

Files: - Create: src/almnck/__init__.py - Create: src/almnck/settings.py - Create: src/almnck/urls.py - Create: src/almnck/wsgi.py - Create: src/almnck/asgi.py - Create: src/manage.py

Step 1: Create Django project structure

mkdir -p src/almnck
touch src/almnck/__init__.py

Step 2: Create settings.py

"""Django settings for Almanack."""
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
ALMANACK_ROOT = Path(os.environ.get('ALMANACK_ROOT', BASE_DIR.parent))

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'dev-secret-change-in-production')
DEBUG = os.environ.get('DJANGO_DEBUG', 'true').lower() == 'true'
ALLOWED_HOSTS = ['*'] if DEBUG else os.environ.get('ALLOWED_HOSTS', '').split(',')

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_distill',
    'almnck.units',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

ROOT_URLCONF = 'almnck.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'almnck' / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'almnck.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ALMANACK_ROOT / 'db.sqlite3',
    }
}

STATIC_URL = '/static/'
STATIC_ROOT = ALMANACK_ROOT / 'web' / 'static'
STATICFILES_DIRS = [BASE_DIR / 'almnck' / 'static']

# django-distill settings
DISTILL_DIR = ALMANACK_ROOT / 'web'

# Almanack-specific settings
EDITORIAL_DIR = ALMANACK_ROOT / 'editorial'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Step 3: Create urls.py

"""URL configuration for Almanack."""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('almnck.units.urls')),
]

Step 4: Create wsgi.py

"""WSGI config for Almanack."""
import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'almnck.settings')
application = get_wsgi_application()

Step 5: Create asgi.py

"""ASGI config for Almanack."""
import os
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'almnck.settings')
application = get_asgi_application()

Step 6: Create manage.py

#!/usr/bin/env python
"""Django management script for Almanack."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'almnck.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

Step 7: Make manage.py executable and commit

chmod +x src/manage.py
git add src/
git commit -m "Initialize Django project structure"

Task 5: Create Units App

Files: - Create: src/almnck/units/__init__.py - Create: src/almnck/units/models.py - Create: src/almnck/units/admin.py - Create: src/almnck/units/urls.py - Create: src/almnck/units/views.py

Step 1: Create units app directory

mkdir -p src/almnck/units
touch src/almnck/units/__init__.py

Step 2: Create models.py

"""Models for editorial units (articles, pages, banners)."""
from django.db import models


class Unit(models.Model):
    """A single publishable unit (article, page, banner, etc.)."""

    class UnitType(models.TextChoices):
        ARTICLE = 'article', 'Article'
        PAGE = 'page', 'Page'
        BANNER = 'banner', 'Banner'
        INBOX = 'inbox', 'Inbox Item'

    class Status(models.TextChoices):
        DRAFT = 'draft', 'Draft'
        EDITING = 'editing', 'Editing'
        REVIEW = 'review', 'Review'
        PUBLISHED = 'published', 'Published'

    # File system location (relative to editorial/)
    source_path = models.CharField(max_length=500, unique=True)

    # Output location (from frontmatter)
    output_path = models.CharField(max_length=500, blank=True)

    # Metadata
    unit_type = models.CharField(max_length=20, choices=UnitType.choices)
    title = models.CharField(max_length=500)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.DRAFT)

    # Content
    content = models.TextField(blank=True)
    frontmatter = models.JSONField(default=dict)

    # Sync tracking
    file_hash = models.CharField(max_length=64, blank=True)
    last_synced = models.DateTimeField(auto_now=True)

    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-updated_at']

    def __str__(self):
        return f"{self.title} ({self.unit_type})"

    @property
    def day(self):
        """Return the calendar day (e.g., 'jan-01') for articles."""
        return self.frontmatter.get('day', '')

Step 3: Create admin.py

"""Admin interface for editorial units."""
from django.contrib import admin
from .models import Unit


@admin.register(Unit)
class UnitAdmin(admin.ModelAdmin):
    list_display = ['title', 'unit_type', 'status', 'source_path', 'updated_at']
    list_filter = ['unit_type', 'status']
    search_fields = ['title', 'source_path', 'content']
    readonly_fields = ['source_path', 'file_hash', 'last_synced', 'created_at']

    fieldsets = [
        (None, {
            'fields': ['title', 'unit_type', 'status']
        }),
        ('Content', {
            'fields': ['content', 'frontmatter']
        }),
        ('File System', {
            'fields': ['source_path', 'output_path', 'file_hash', 'last_synced'],
            'classes': ['collapse']
        }),
    ]

Step 4: Create urls.py

"""URL patterns for units app."""
from django.urls import path
from . import views

app_name = 'units'

urlpatterns = [
    path('', views.index, name='index'),
]

Step 5: Create views.py

"""Views for units app."""
from django.shortcuts import render
from .models import Unit


def index(request):
    """Home page - list of published articles."""
    articles = Unit.objects.filter(
        unit_type=Unit.UnitType.ARTICLE,
        status=Unit.Status.PUBLISHED
    )
    return render(request, 'units/index.html', {'articles': articles})

Step 6: Commit units app

git add src/almnck/units/
git commit -m "Add units app with Unit model and admin"

Task 6: Create Sync Management Command

Files: - Create: src/almnck/units/management/__init__.py - Create: src/almnck/units/management/commands/__init__.py - Create: src/almnck/units/management/commands/sync_with_repo.py

Step 1: Create management command directories

mkdir -p src/almnck/units/management/commands
touch src/almnck/units/management/__init__.py
touch src/almnck/units/management/commands/__init__.py

Step 2: Create sync_with_repo.py

"""Sync Django database with editorial/ directory."""
import hashlib
import yaml
from pathlib import Path
from django.core.management.base import BaseCommand
from django.conf import settings
from almnck.units.models import Unit


class Command(BaseCommand):
    help = 'Sync database with editorial/ directory'

    def add_arguments(self, parser):
        parser.add_argument(
            '--path',
            type=str,
            help='Sync only a specific subdirectory (e.g., articles/look-back-up)',
        )

    def handle(self, *args, **options):
        editorial_dir = Path(settings.EDITORIAL_DIR)
        if not editorial_dir.exists():
            self.stderr.write(f"Editorial directory not found: {editorial_dir}")
            return

        subpath = options.get('path')
        if subpath:
            scan_dir = editorial_dir / subpath
        else:
            scan_dir = editorial_dir

        self.stdout.write(f"Scanning {scan_dir}...")

        units_found = set()

        for unit_dir in self._find_unit_dirs(scan_dir):
            relative_path = str(unit_dir.relative_to(editorial_dir))
            units_found.add(relative_path)
            self._sync_unit(unit_dir, relative_path)

        # Mark units that no longer exist on disk
        if not subpath:
            missing = Unit.objects.exclude(source_path__in=units_found)
            if missing.exists():
                self.stdout.write(f"Removing {missing.count()} units no longer on disk")
                missing.delete()

        self.stdout.write(self.style.SUCCESS(f"Synced {len(units_found)} units"))

    def _find_unit_dirs(self, base_dir: Path):
        """Find directories that contain a content file."""
        content_patterns = ['article.md', 'page.md', 'banner.md', '*.md', '*.txt']

        for path in base_dir.rglob('*'):
            if path.is_dir():
                # Check if this directory has a content file
                for pattern in ['article.md', 'page.md', 'banner.md']:
                    if (path / pattern).exists():
                        yield path
                        break
                else:
                    # Check for any .md file (inbox items)
                    md_files = list(path.glob('*.md'))
                    txt_files = list(path.glob('*.txt'))
                    if md_files or txt_files:
                        yield path

    def _sync_unit(self, unit_dir: Path, relative_path: str):
        """Sync a single unit directory to database."""
        content_file = self._find_content_file(unit_dir)
        if not content_file:
            return

        content = content_file.read_text()
        file_hash = hashlib.sha256(content.encode()).hexdigest()[:16]

        # Check if already synced with same hash
        try:
            existing = Unit.objects.get(source_path=relative_path)
            if existing.file_hash == file_hash:
                return  # No changes
        except Unit.DoesNotExist:
            existing = None

        # Parse frontmatter
        frontmatter, body = self._parse_frontmatter(content)

        # Determine unit type from path
        unit_type = self._infer_unit_type(relative_path)

        defaults = {
            'title': frontmatter.get('title', unit_dir.name),
            'unit_type': unit_type,
            'status': frontmatter.get('status', 'draft'),
            'output_path': frontmatter.get('path', ''),
            'content': body,
            'frontmatter': frontmatter,
            'file_hash': file_hash,
        }

        unit, created = Unit.objects.update_or_create(
            source_path=relative_path,
            defaults=defaults
        )

        action = "Created" if created else "Updated"
        self.stdout.write(f"  {action}: {unit.title}")

    def _find_content_file(self, unit_dir: Path) -> Path | None:
        """Find the main content file in a unit directory."""
        for name in ['article.md', 'page.md', 'banner.md']:
            path = unit_dir / name
            if path.exists():
                return path

        # Fall back to first .md or .txt file
        for pattern in ['*.md', '*.txt']:
            files = list(unit_dir.glob(pattern))
            if files:
                return files[0]

        return None

    def _parse_frontmatter(self, content: str) -> tuple[dict, str]:
        """Parse YAML frontmatter from content."""
        if not content.startswith('---'):
            return {}, content

        parts = content.split('---', 2)
        if len(parts) < 3:
            return {}, content

        try:
            frontmatter = yaml.safe_load(parts[1]) or {}
        except yaml.YAMLError:
            frontmatter = {}

        body = parts[2].strip()
        return frontmatter, body

    def _infer_unit_type(self, relative_path: str) -> str:
        """Infer unit type from path."""
        if relative_path.startswith('articles/'):
            return Unit.UnitType.ARTICLE
        elif relative_path.startswith('pages/'):
            return Unit.UnitType.PAGE
        elif relative_path.startswith('banners/'):
            return Unit.UnitType.BANNER
        elif relative_path.startswith('inbox/'):
            return Unit.UnitType.INBOX
        return Unit.UnitType.ARTICLE

Step 3: Commit management command

git add src/almnck/units/management/
git commit -m "Add sync-with-repo management command"

Task 7: Create Basic Templates

Files: - Create: src/almnck/templates/base.html - Create: src/almnck/templates/units/index.html - Create: src/almnck/templates/units/article.html

Step 1: Create templates directory

mkdir -p src/almnck/templates/units

Step 2: Create base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Almanack{% endblock %}</title>
    <style>
        body {
            font-family: Georgia, serif;
            max-width: 40em;
            margin: 2em auto;
            padding: 0 1em;
            line-height: 1.6;
        }
        h1, h2, h3 { font-family: sans-serif; }
        a { color: #0066cc; }
        .article-meta { color: #666; font-size: 0.9em; }
    </style>
</head>
<body>
    <header>
        <h1><a href="/">Almanack</a></h1>
    </header>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>
        <p>&copy; Almanack</p>
    </footer>
</body>
</html>

Step 3: Create units/index.html

{% extends "base.html" %}

{% block content %}
<h2>Articles</h2>
{% if articles %}
<ul>
{% for article in articles %}
    <li>
        <a href="{{ article.output_path }}">{{ article.title }}</a>
        {% if article.day %}<span class="article-meta">({{ article.day }})</span>{% endif %}
    </li>
{% endfor %}
</ul>
{% else %}
<p>No published articles yet.</p>
{% endif %}
{% endblock %}

Step 4: Create units/article.html

{% extends "base.html" %}

{% block title %}{{ unit.title }} - Almanack{% endblock %}

{% block content %}
<article>
    <header>
        <h1>{{ unit.title }}</h1>
        <p class="article-meta">
            {% if unit.frontmatter.author %}By {{ unit.frontmatter.author }}{% endif %}
            {% if unit.day %}• {{ unit.day }}{% endif %}
        </p>
    </header>
    <div class="content">
        {{ content|safe }}
    </div>
</article>
{% endblock %}

Step 5: Commit templates

git add src/almnck/templates/
git commit -m "Add base templates for site rendering"

Task 8: Add Distill Integration

Files: - Modify: src/almnck/units/urls.py - Modify: src/almnck/units/views.py - Create: src/almnck/units/management/commands/build_with_distill.py

Step 1: Update urls.py with distill patterns

"""URL patterns for units app with django-distill."""
from django.urls import path
from django_distill import distill_path
from . import views
from .models import Unit

app_name = 'units'


def get_published_articles():
    """Generate URLs for all published articles."""
    for unit in Unit.objects.filter(
        unit_type=Unit.UnitType.ARTICLE,
        status=Unit.Status.PUBLISHED
    ):
        if unit.output_path:
            # Strip leading/trailing slashes and add index.html logic
            path = unit.output_path.strip('/')
            yield {'path': path + '/'}


def get_index():
    """Generate index page."""
    return [{}]


urlpatterns = [
    distill_path(
        '',
        views.index,
        name='index',
        distill_func=get_index,
        distill_file='index.html',
    ),
    distill_path(
        '<path:path>',
        views.article_detail,
        name='article_detail',
        distill_func=get_published_articles,
    ),
]

Step 2: Update views.py with article detail view

"""Views for units app."""
import markdown
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from .models import Unit


def index(request):
    """Home page - list of published articles."""
    articles = Unit.objects.filter(
        unit_type=Unit.UnitType.ARTICLE,
        status=Unit.Status.PUBLISHED
    ).order_by('frontmatter__day')
    return render(request, 'units/index.html', {'articles': articles})


def article_detail(request, path):
    """Render a single article."""
    # Normalize path
    output_path = '/' + path.strip('/') + '/'

    unit = get_object_or_404(
        Unit,
        output_path=output_path,
        status=Unit.Status.PUBLISHED
    )

    # Convert markdown to HTML
    md = markdown.Markdown(extensions=['footnotes', 'tables', 'fenced_code'])
    content = md.convert(unit.content)

    return render(request, 'units/article.html', {
        'unit': unit,
        'content': content,
    })

Step 3: Create build_with_distill.py command

"""Build static site using django-distill."""
from django.core.management.base import BaseCommand
from django.core.management import call_command


class Command(BaseCommand):
    help = 'Build static site to web/ directory'

    def handle(self, *args, **options):
        self.stdout.write("Building static site...")
        call_command('distill-local', '--force')
        self.stdout.write(self.style.SUCCESS("Build complete! Output in web/"))

Step 4: Update pyproject.toml to add markdown dependency

Add markdown to dependencies in pyproject.toml.

Step 5: Commit distill integration

git add src/almnck/units/
git commit -m "Add django-distill integration for static site generation"

Task 9: Update Makefile

Files: - Modify: Makefile

Step 1: Update Makefile with new targets

RED := \033[0;31m
GREEN := \033[0;32m
YELLOW := \033[0;33m
RESET := \033[0m

.PHONY: default
default:
    @echo "$(RED)Please specify a target. See 'make help'$(RESET)"

.PHONY: help
help:
    @echo "$(GREEN)Almanack Makefile$(RESET)"
    @echo ""
    @echo "$(YELLOW)Django:$(RESET)"
    @echo "  sync-django         Sync git repo to Django database"
    @echo "  build-django-site   Generate static site to web/"
    @echo "  serve               Run Django dev server"
    @echo ""
    @echo "$(YELLOW)Editorial:$(RESET)"
    @echo "  editorial-status    Show status of all units"
    @echo "  editorial-doctor    Validate structure and frontmatter"
    @echo "  editorial-commit    Commit editorial changes"
    @echo ""
    @echo "$(YELLOW)Deployment:$(RESET)"
    @echo "  live                Deploy web/ to production"
    @echo ""

.PHONY: check-activated
check-activated:
ifndef ALMANACK_ROOT
    $(error ALMANACK_ROOT is undefined. Run 'source bin/a-activate' first.)
endif

# Django targets
.PHONY: sync-django
sync-django: check-activated
    cd $(ALMANACK_ROOT)/src && python manage.py sync_with_repo

.PHONY: build-django-site
build-django-site: check-activated
    cd $(ALMANACK_ROOT)/src && python manage.py build_with_distill

.PHONY: serve
serve: check-activated
    cd $(ALMANACK_ROOT)/src && python manage.py runserver

.PHONY: migrate
migrate: check-activated
    cd $(ALMANACK_ROOT)/src && python manage.py migrate

# Editorial targets
.PHONY: editorial-status
editorial-status: check-activated
    @$(ALMANACK_ROOT)/bin/editorial-status

.PHONY: editorial-doctor
editorial-doctor: check-activated
    @$(ALMANACK_ROOT)/bin/editorial-doctor

.PHONY: editorial-commit
editorial-commit: check-activated
    git -C $(ALMANACK_ROOT) add editorial/
    git -C $(ALMANACK_ROOT) commit -m "$(MSG)"

# Deployment
RSYNC_OPTS := -avz --delete --delete-after --filter='dir-merge,-n /.gitignore' -e "a-ssh"
DESTINATIONS := boat:/var/local/www/www.almnck.com/ dallas:/var/local/www/www.almnck.com/ sj:/var/local/www/www.almnck.com/

.PHONY: live
live: check-activated
    @test -d "$(ALMANACK_ROOT)/web" || (echo "ERROR: web directory not found" && exit 1)
    @echo "Dry run preview:"
    @$(foreach dest,$(DESTINATIONS),echo "$(YELLOW)To $(dest)$(RESET)"; rsync $(RSYNC_OPTS) --dry-run $(ALMANACK_ROOT)/web/ $(dest);)
    @read -p "Continue with deployment? (y/N): " confirm && [ "$$confirm" = "y" ]
    @$(foreach dest,$(DESTINATIONS),echo "$(YELLOW)To $(dest)$(RESET)"; rsync $(RSYNC_OPTS) $(ALMANACK_ROOT)/web/ $(dest);)

# Testing
.PHONY: test-doc
test-doc: check-activated
    @echo Running doc-check-links
    @sh $(ALMANACK_ROOT)/src/tests/doc-check-links | tapview

Step 2: Commit Makefile

git add Makefile
git commit -m "Update Makefile with new Django and editorial targets"

Task 10: Create Standalone Editorial Scripts

Files: - Create: bin/editorial-status - Create: bin/editorial-doctor

Step 1: Create editorial-status script

#!/usr/bin/env python3
"""Show status of all editorial units."""
import sys
from pathlib import Path
import yaml

def parse_frontmatter(content):
    """Parse YAML frontmatter from content."""
    if not content.startswith('---'):
        return {}
    parts = content.split('---', 2)
    if len(parts) < 3:
        return {}
    try:
        return yaml.safe_load(parts[1]) or {}
    except yaml.YAMLError:
        return {}

def find_content_file(unit_dir):
    """Find main content file in unit directory."""
    for name in ['article.md', 'page.md', 'banner.md']:
        path = unit_dir / name
        if path.exists():
            return path
    for f in unit_dir.glob('*.md'):
        return f
    for f in unit_dir.glob('*.txt'):
        return f
    return None

def main():
    root = Path(__file__).parent.parent
    editorial = root / 'editorial'

    if not editorial.exists():
        print("No editorial/ directory found", file=sys.stderr)
        sys.exit(1)

    print(f"{'TYPE':<10} {'STATUS':<12} {'PATH':<40} {'TITLE'}")
    print("-" * 90)

    for subdir in ['articles', 'pages', 'banners', 'inbox']:
        subpath = editorial / subdir
        if not subpath.exists():
            continue

        for unit_dir in sorted(subpath.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)

            title = fm.get('title', unit_dir.name)[:35]
            status = fm.get('status', 'draft')
            rel_path = str(unit_dir.relative_to(editorial))

            print(f"{subdir:<10} {status:<12} {rel_path:<40} {title}")

if __name__ == '__main__':
    main()

Step 2: Create editorial-doctor script

#!/usr/bin/env python3
"""Validate editorial structure and frontmatter."""
import sys
from pathlib import Path
import yaml

REQUIRED_ARTICLE_FIELDS = ['title', 'path', 'status']
REQUIRED_PAGE_FIELDS = ['title', 'path']

def parse_frontmatter(content):
    if not content.startswith('---'):
        return None
    parts = content.split('---', 2)
    if len(parts) < 3:
        return None
    try:
        return yaml.safe_load(parts[1]) or {}
    except yaml.YAMLError as e:
        return {'_error': str(e)}

def find_content_file(unit_dir):
    for name in ['article.md', 'page.md', 'banner.md']:
        path = unit_dir / name
        if path.exists():
            return path
    for f in unit_dir.glob('*.md'):
        return f
    return None

def check_unit(unit_dir, unit_type):
    """Check a single unit, return list of issues."""
    issues = []

    content_file = find_content_file(unit_dir)
    if not content_file:
        issues.append("No content file found")
        return issues

    content = content_file.read_text()
    fm = parse_frontmatter(content)

    if fm is None:
        issues.append("No YAML frontmatter")
        return issues

    if '_error' in fm:
        issues.append(f"Invalid YAML: {fm['_error']}")
        return issues

    # Check required fields
    required = REQUIRED_ARTICLE_FIELDS if unit_type == 'articles' else REQUIRED_PAGE_FIELDS
    for field in required:
        if field not in fm:
            issues.append(f"Missing required field: {field}")

    # Check path format
    if 'path' in fm:
        path = fm['path']
        if not path.startswith('/'):
            issues.append(f"Path should start with /: {path}")
        if not path.endswith('/'):
            issues.append(f"Path should end with /: {path}")

    return issues

def main():
    root = Path(__file__).parent.parent
    editorial = root / 'editorial'

    if not editorial.exists():
        print("No editorial/ directory found", file=sys.stderr)
        sys.exit(1)

    total_issues = 0

    for subdir in ['articles', 'pages', 'banners']:
        subpath = editorial / subdir
        if not subpath.exists():
            continue

        for unit_dir in sorted(subpath.iterdir()):
            if not unit_dir.is_dir():
                continue

            issues = check_unit(unit_dir, subdir)
            if issues:
                rel_path = unit_dir.relative_to(editorial)
                print(f"\n{rel_path}:")
                for issue in issues:
                    print(f"  - {issue}")
                    total_issues += 1

    if total_issues == 0:
        print("All units OK")
        sys.exit(0)
    else:
        print(f"\n{total_issues} issue(s) found")
        sys.exit(1)

if __name__ == '__main__':
    main()

Step 3: Make scripts executable and commit

chmod +x bin/editorial-status bin/editorial-doctor
git add bin/editorial-status bin/editorial-doctor
git commit -m "Add standalone editorial-status and editorial-doctor scripts"

Task 11: Update pyproject.toml

Files: - Modify: pyproject.toml

Step 1: Update dependencies and package structure

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "almnck"
version = "0.2.0"
description = "Almanack publishing platform"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
    "Django>=5.0",
    "django-distill>=3.1",
    "django-htmx>=1.17",
    "markdown>=3.5",
    "PyYAML>=6.0",
    "beautifulsoup4>=4.12",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-django>=4.5",
]

[tool.hatch.build.targets.wheel]
packages = ["src/almnck"]

Step 2: Commit pyproject.toml

git add pyproject.toml
git commit -m "Update pyproject.toml for new Django structure"

Task 12: Initialize Database and Test

Step 1: Run migrations

cd src && python manage.py migrate

Step 2: Sync content

make sync-django

Step 3: Check status

make editorial-status

Step 4: Run doctor

make editorial-doctor

Step 5: Create superuser for admin

cd src && python manage.py createsuperuser

Step 6: Test dev server

make serve
# Visit http://localhost:8000/admin/

Step 7: Commit database to gitignore

Add db.sqlite3 to .gitignore if not already there.

echo "db.sqlite3" >> .gitignore
git add .gitignore
git commit -m "Ignore SQLite database file"

Task 13: Update CLAUDE.md

Files: - Modify: CLAUDE.md

Update project documentation to reflect new structure. Key changes: - Remove references to old assets/editorial/ structure - Document new editorial/ structure - Update common commands section - Document the sync workflow

Step 1: Update CLAUDE.md content

(Full content to be written based on new structure)

Step 2: Commit

git add CLAUDE.md
git commit -m "Update CLAUDE.md for new editorial pipeline"

Summary

After completing all tasks:

  1. Old assets/editorial/ structure removed
  2. New editorial/ directory with articles/pages/banners/inbox
  3. Django project in src/almnck/ with Unit model
  4. sync_with_repo command syncs git → database
  5. build_with_distill command generates static site
  6. Makefile updated with all new targets
  7. Standalone editorial-status and editorial-doctor scripts
  8. One migrated article (look-back-up) ready for testing

Addendum (2026-01-17): Makefile commands were reorganized. sync-django → sync, build-django-site → build, editorial-status → ed-status, editorial-doctor → ed-doctor.