# Mirror a playbook to files

> Keep a folder of Markdown files in step with your playbooks, fetching only what changed, for tools and pipelines that read files.

Some tools only read files: a coding agent without MCP, a CI job, a static site, your own search index. This recipe keeps a folder of Markdown in step with one or more playbooks. People keep editing in PlaybookOps, and the folder follows.

Each run asks [what changed](https://developers.playbookops.ai/guides/knowledge#keep-up-with-changes) since the last one, including deleted documents, so it's cheap to run every few minutes. Listing and reading are free; they only count toward the [rate limit](https://developers.playbookops.ai/limits-and-credits).

## The script

You need a Read-only key, or a Custom key that can read **Playbooks and documents**, and `pip install httpx`. Save this as `sync_playbooks.py`, fill in `PLAYBOOKS`, and run `python sync_playbooks.py context/`.

```python
"""Mirror PlaybookOps playbooks into a folder of Markdown files.

    python sync_playbooks.py context/          # what changed since the last run
    python sync_playbooks.py context/ --full   # rewrite everything, like after renaming folders
"""
import json
import os
import re
import sys
import time
from pathlib import Path

import httpx

# Playbook id -> folder name
PLAYBOOKS = {
    "PLAYBOOK_ID": "engineering",
    "ANOTHER_PLAYBOOK_ID": "runbooks",
}
BEGINNING = "2000-01-01T00:00:00Z"
SKIP_STATUSES = {"archived"}

api = httpx.Client(
    base_url="https://developers.playbookops.ai/v1",
    headers={"Authorization": f"Bearer {os.environ['PLAYBOOKOPS_API_KEY']}"},
    timeout=60,
)

def get(path: str, **params) -> dict:
    while True:
        res = api.get(path, params=params)
        if res.status_code == 429:
            time.sleep(int(res.headers.get("Retry-After", "5")))
            continue
        res.raise_for_status()
        return res.json()

def safe(name: str) -> str:
    return re.sub(r"[^\w .-]+", "-", name).strip(" .") or "untitled"

def folder_paths(playbook_id: str) -> dict:
    """Folder id -> its path on disk, like "Runbooks/Database"."""
    folders = get(f"/playbooks/{playbook_id}/folders")["data"]
    return {f["id"]: "/".join(safe(part) for part in f["path"].split(" / ")) for f in folders}

def render(doc: dict) -> str:
    """The document as Markdown, with its details as front matter."""
    details = {k: doc[k] for k in ("id", "title", "version", "status", "tags", "updated_at", "url")}
    front = "\n".join(f"{k}: {json.dumps(v)}" for k, v in details.items())
    return f"---\n{front}\n---\n\n# {doc['title']}\n\n{doc['content']}\n"

def file_name(doc: dict) -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", doc["title"].lower()).strip("-")[:60] or "untitled"
    return f"{slug}-{doc['id'][:8]}.md"

def remove(root: Path, state: dict, doc_id: str) -> None:
    path = state["files"].pop(doc_id, None)
    if path:
        (root / path).unlink(missing_ok=True)
        print(f"removed  {path}")

def write(root: Path, state: dict, doc: dict, folders: dict) -> None:
    sub = folders.get(doc["folder_id"])
    path = "/".join(p for p in (PLAYBOOKS[doc["playbook_id"]], sub, file_name(doc)) if p)
    old = state["files"].get(doc["id"])
    if old and old != path:
        (root / old).unlink(missing_ok=True)  # renamed or moved
    (root / path).parent.mkdir(parents=True, exist_ok=True)
    (root / path).write_text(render(doc), encoding="utf-8")
    state["files"][doc["id"]] = path
    print(f"wrote    {path}")

def sync(root: Path, full: bool) -> None:
    state_file = root / ".playbookops-sync.json"
    state = json.loads(state_file.read_text()) if state_file.exists() else {"since": None, "files": {}}
    since = BEGINNING if full or not state["since"] else state["since"]
    folders = {}
    while True:
        page = get("/document-changes", since=since, limit=200)
        for change in page["changed"]:
            playbook_id = change["playbook_id"]
            if playbook_id not in PLAYBOOKS or change["status"] in SKIP_STATUSES:
                remove(root, state, change["id"])  # moved elsewhere, or archived
                continue
            if playbook_id not in folders:
                folders[playbook_id] = folder_paths(playbook_id)
            try:
                doc = get(f"/documents/{change['id']}", full="true")
            except httpx.HTTPStatusError as error:
                if error.response.status_code != 404:
                    raise
                remove(root, state, change["id"])  # deleted since
                continue
            write(root, state, doc, folders[playbook_id])
        for gone in page["removed"]:
            remove(root, state, gone["id"])
        since = state["since"] = page["next_since"]
        state_file.write_text(json.dumps(state, indent=2))
        if not page["has_more"]:
            return

if __name__ == "__main__":
    sync(Path(sys.argv[1]), full="--full" in sys.argv)
```

Each file starts with the document's details, so tools and people can get back to the source:

```markdown
---
id: "6f1d2c1e-…"
title: "How we deploy the backend"
version: 7
status: "published"
tags: ["deploys"]
updated_at: "2026-11-21T15:04:05Z"
url: "https://app.playbookops.ai/playbooks/…"
---

# How we deploy the backend

Deploys go out from main through the Deploy workflow…
```

## Deleted, moved and archived documents

The change feed reports documents that were deleted or moved to another playbook, and the script removes their files. Archived documents come through as changes with `status: "archived"`; the script removes those too, so take `archived` out of `SKIP_STATUSES` to keep them.

Documents land in subfolders that match their folders in the playbook. Renaming a folder doesn't change its documents, so after reorganizing a playbook, run once with `--full` to rewrite every file in its new place. Removals are kept for 90 days, so if the sync hasn't run in that long, run `--full` too.

## Keep a repo in step

To keep a mirror in a Git repository, for agents that read the repo or as a plain-text backup, run the sync from CI and commit what changed. With GitHub Actions:

```yaml
name: Sync playbooks
on:
  schedule:
    - cron: "*/30 * * * *"
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install httpx
      - run: python scripts/sync_playbooks.py context/
        env:
          PLAYBOOKOPS_API_KEY: ${{ secrets.PLAYBOOKOPS_API_KEY }}
      - run: |
          git config user.name "playbookops-sync"
          git config user.email "playbookops-sync@users.noreply.github.com"
          git add context
          git diff --cached --quiet || git commit -m "Sync playbooks" && git push
```

Treat the folder as read-only: edits made there are overwritten on the next sync. Add a `context/README.md` that says so and links to the playbooks.

## Load documents into a prompt

When an agent must always follow a few documents, like coding conventions or a support tone guide, read them when the agent starts instead of syncing files. This is the PlaybookOps version of an `AGENTS.md`:

```python
PINNED = ["DOCUMENT_ID", "ANOTHER_DOCUMENT_ID"]

def pinned_context() -> str:
    docs = [get(f"/documents/{doc_id}", full="true") for doc_id in PINNED]
    return "\n\n".join(f"# {d['title']}\n\n{d['content']}" for d in docs)

system_prompt = BASE_INSTRUCTIONS + "\n\n" + pinned_context()
```

Reads are free, but cache the result for a few minutes if the agent starts often. Keep it to a handful of short documents, and let the agent [look up](https://developers.playbookops.ai/cookbooks/grounded-answers) the rest.

## Next

- [Move a docs repo into PlaybookOps](https://developers.playbookops.ai/cookbooks/import-a-docs-repo) goes the other way, from files into playbooks.
- [Keeping up with changes](https://developers.playbookops.ai/guides/knowledge#keep-up-with-changes) explains `since`, `next_since` and removals.
