Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/manifest-docs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: Manifest documentation sync

on:
pull_request:
paths:
- crewloom-manifest.json
- scripts/sync-docs.py
- scripts/test-sync-docs.py
- .github/workflows/manifest-docs.yml
schedule:
- cron: '43 7 * * *'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: manifest-docs-${{ github.event_name == 'pull_request' && github.ref || 'scheduled' }}
cancel-in-progress: false

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python scripts/test-sync-docs.py -v

sync:
if: github.event_name != 'pull_request'
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Generate preview from public sources
run: python scripts/sync-docs.py
- uses: actions/upload-artifact@v4
with:
name: manifest-docs-preview
path: sync-output/
retention-days: 14
- name: Open review PRs only when owner has configured scoped access
env:
GH_TOKEN: ${{ secrets.CREWLOOM_DOCS_SYNC_TOKEN }}
shell: bash
run: |
set -euo pipefail
if [ -z "$GH_TOKEN" ]; then
echo 'Preview generated. Cross-repository PR writing is not configured.' >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
gh auth setup-git
python scripts/sync-docs.py --publish
15 changes: 15 additions & 0 deletions crewloom-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"schema_version": 1,
"organization": "crewloom",
"projects": [
{"id": "core", "repository": "crewloom", "ref": "main", "version_file": "pyproject.toml", "format": "toml", "output": "documentation/CREWLOOM_FACTS.md", "counts": {"skill_files": {"glob": ".agents/skills/*/SKILL.md"}, "registered_tools": {"json_file": "documentation/TOOLS.json", "key": "tools"}}},
{"id": "bridge", "repository": "bridge", "ref": "main", "version_file": "package.json", "format": "json", "output": "docs/CREWLOOM_FACTS.md", "counts": {}},
{"id": "website", "repository": "crewloom.github.io", "ref": "main", "version_file": "package.json", "format": "json", "output": "docs/CREWLOOM_FACTS.md", "counts": {}}
],
"decisions_required": [
"Bridge canonical product/package naming remains an owner decision. Existing package names are reported verbatim, not endorsed or changed.",
"Domains and support addresses are not inferred or changed.",
"Private repositories are excluded until the owner approves the source fields, public/private destination and scoped access.",
"Website runtime metrics and release/download metadata are not modified by this documentation sync."
]
}
41 changes: 41 additions & 0 deletions docs/MANIFEST_SYNC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Manifest-driven documentation sync

`crewloom-manifest.json` is the reviewed map of source fields and documentation destinations. Source package files stay authoritative for their own versions. The manifest does not invent a unified product version.

## Scope and guardrails

- Public Core, Bridge and website source versions, exact Core `SKILL.md` file count, and exact tool registry entry count.
- Source version and latest stable GitHub release are separate columns. A website repository's GitHub releases can describe Desktop, not the website package. A GitHub release is not proof of an npm/PyPI publication or a deployed version.
- Output is a standalone `CREWLOOM_FACTS.md` in each allowlisted destination. Existing README prose, English/Arabic audit fixes, runtime metrics, download metadata, licenses and package versions are untouched.
- Product code is never imported or executed. No install, build, publish, deployment, merge or auto-merge command exists in this workflow.
- No benchmark, accuracy, latency, safety or compliance claims are generated. Structural counts do not establish quality.
- Private Agent/Pulse/Office repositories are excluded. Adding them needs owner approval for fields, audience and scoped access. Do not copy private source facts into this public repository by default.
- Canonical Bridge naming and domains remain owner decisions. Existing package names are displayed as observed metadata, not renamed.

## What runs automatically after review and merge

Daily at 07:43 UTC, or by manual dispatch, CI tests the generator, reads public default branches and release metadata, and uploads a 14-day preview artifact. Pull requests only run offline fixture tests, with read-only permissions and no sync credential.

Without `CREWLOOM_DOCS_SYNC_TOKEN`, preview mode is the full supported behavior. Nothing is pushed. The workflow says this in its summary rather than claiming cross-repository writes worked.

To enable cross-repository review PRs, the owner must separately configure a fine-grained token or GitHub App token as `CREWLOOM_DOCS_SYNC_TOKEN`, restricted to the three listed public repositories with contents and pull-request write access only. Do not paste credentials into issues or PRs. Organization policy must permit the selected bot identity to create PRs. The ordinary per-repository workflow token does not grant cross-repository write access. No permission or secret is created by this change.

With that credential, the bot creates content-addressed `bot/manifest-docs-sync-*` branches and opens docs-only PRs. It never force pushes or changes an open sync PR. While one is open, that repository is skipped; review or close it first. Retained merged branches do not prevent later, different updates. Repository rules and human merge review still apply. Enable branch protection before relying on this as a control.

The initial PR adds infrastructure only. It does not run a workflow on the default branch or start recurring activity until reviewed and merged. Existing `.github#2` and other consistency-audit PRs remain separate. This is a first rollout, not replacement of every historical hardcoded number. Once approved, the generated document can be linked from audited READMEs without overwriting their narrative changes. Website runtime metrics need a separate reviewed change.

## Local checks

Requires Python 3.11+, git and, for publishing only, authenticated GitHub CLI.

```sh
python scripts/test-sync-docs.py -v
python scripts/sync-docs.py # read public sources, preview only
python scripts/sync-docs.py --checkouts ../ --offline # fixture/local preview
```

The snapshot `facts.json` includes exact source commit IDs. Generated Markdown omits commit IDs so unrelated commits and its own docs-only commits cannot create an endless PR loop. No wall-clock timestamp enters the rendered document. Repeated generation from equal facts is byte-identical.

## Failure handling

Any missing version/registry file, invalid metadata, network or authorization error fails before publishing starts. A 404 on the public latest stable release endpoint is explicitly represented as no stable GitHub release found, not as version zero. A private or moved repository must be removed or re-approved in the manifest rather than silently guessed. PR creation failures remain failed jobs; a branch pushed before a PR error is kept for inspection, never overwritten. Other repositories already processed may have PRs, so inspect the run log before retrying.
178 changes: 178 additions & 0 deletions scripts/sync-docs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Read public source facts, render docs, optionally open PRs. No product imports."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import subprocess
import tempfile
import tomllib
import urllib.error
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
BRANCH = 'bot/manifest-docs-sync'


def run(*args, cwd=None):
return subprocess.check_output(args, cwd=cwd, text=True).strip()


def relative(value):
p = PurePosixPath(value)
if p.is_absolute() or '..' in p.parts or not p.parts:
raise ValueError('Unsafe relative path')
return value


def load_manifest(path):
m = json.loads(path.read_text())
if m['schema_version'] != 1 or m['organization'] != 'crewloom':
raise ValueError('Unsupported manifest')
seen = set()
for p in m['projects']:
if p['repository'] in seen or not re.fullmatch(r'[A-Za-z0-9_.-]+', p['repository']):
raise ValueError('Invalid or duplicate repository')
seen.add(p['repository'])
if p['format'] not in ('json', 'toml') or p['ref'] != 'main':
raise ValueError('Unreviewed source format/ref')
for key in ('version_file', 'output'):
relative(p[key])
if p['output'] not in ('documentation/CREWLOOM_FACTS.md', 'docs/CREWLOOM_FACTS.md'):
raise ValueError('Destination is not allowlisted')
for spec in p['counts'].values():
relative(spec.get('glob', spec.get('json_file', '')))
return m


def release(org, repo):
request = urllib.request.Request(f'https://api.github.com/repos/{org}/{repo}/releases/latest',
headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'crewloom-docs-sync'})
try:
with urllib.request.urlopen(request, timeout=30) as response:
value = json.load(response)
return {'tag': value['tag_name'], 'url': value['html_url'], 'published_at': value['published_at']}
except urllib.error.HTTPError as error:
if error.code == 404:
return None
raise


def collect(project, checkout, latest):
if checkout.is_symlink():
raise ValueError('Symlink checkout')
def read(path):
target = checkout / relative(path)
if not target.resolve().is_relative_to(checkout.resolve()):
raise ValueError('Source escapes checkout')
return target.read_text()
raw = read(project['version_file'])
metadata = json.loads(raw) if project['format'] == 'json' else tomllib.loads(raw)['project']
if not isinstance(metadata['version'], str) or not isinstance(metadata['name'], str):
raise ValueError('Source name/version must be strings')
counts = {}
for name, spec in project['counts'].items():
if 'glob' in spec:
counts[name] = sum(1 for p in checkout.glob(spec['glob']) if p.is_file() and not p.is_symlink())
else:
values = json.loads(read(spec['json_file']))[spec['key']]
if not isinstance(values, (dict, list)):
raise ValueError('Count source must be a registry')
counts[name] = len(values)
return {'id': project['id'], 'repository': project['repository'],
'source_commit': run('git', 'rev-parse', 'HEAD', cwd=checkout),
'source_name': metadata['name'], 'source_version': metadata['version'],
'version_file': project['version_file'], 'counts': counts, 'latest_release': latest}


def safe(value):
return str(value).replace('|', '&#124;').replace('\n', ' ').replace('\r', ' ').replace('<', '&lt;').replace('>', '&gt;').replace('`', '&#96;')


def render(facts):
lines = ['<!-- Generated by crewloom/.github scripts/sync-docs.py. Do not edit. -->',
'# Crewloom source facts', '',
'Source versions are not published versions. Counts describe files/registry entries, not quality, safety, test results or accreditation.', '',
'| Repository | Source package | Source version | Latest stable GitHub release |',
'| :--- | :--- | :--- | :--- |']
for f in facts:
tag = ('Not checked (offline preview)' if f['latest_release'] == 'offline' else
f['latest_release']['tag'] if f['latest_release'] else 'No stable GitHub release found')
lines.append('| ' + ' | '.join(safe(x) for x in (f['repository'], f['source_name'], f['source_version'], tag)) + ' |')
for f in facts:
lines += ['', f"## {safe(f['repository'])}", '',
f"Source: `crewloom/{safe(f['repository'])}`, `{safe(f['version_file'])}` on its manifest ref. Exact inspected commit is recorded in the workflow facts.json artifact."]
for name, count in sorted(f['counts'].items()):
lines.append(f'- {safe(name)}: {count}')
lines += ['', 'Bridge naming, domains and private repository disclosures require owner decisions. No runtime, package version, license, download metadata or benchmark claim is changed by this generator.', '']
return '\n'.join(lines)


def publish(checkout, output, content, repo):
# Only this generated Markdown file may enter a bot commit.
target = checkout / output
if target.exists() and target.read_text() == content:
return 'unchanged'
if not target.resolve().is_relative_to(checkout.resolve()):
raise ValueError('Destination escapes checkout')
# Never rewrite a branch or an in-review PR. A content-addressed branch also
# works when merged branches are retained by repository policy.
pending = json.loads(run('gh', 'pr', 'list', '--repo', repo, '--state', 'open',
'--json', 'headRefName,url', cwd=checkout))
if any(p['headRefName'].startswith(BRANCH + '-') for p in pending):
return 'existing sync PR: skipped; review or close it first'
branch = BRANCH + '-' + hashlib.sha256(content.encode()).hexdigest()[:12]
if run('git', 'ls-remote', '--heads', 'origin', branch, cwd=checkout):
return 'existing bot branch: skipped; inspect previous PR before retrying'
run('git', 'switch', '-c', branch, cwd=checkout)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
run('git', 'add', '--', output, cwd=checkout)
changed = run('git', 'diff', '--cached', '--name-only', cwd=checkout).splitlines()
if changed != [output]:
raise ValueError('Refusing changes outside generated document')
run('git', '-c', 'user.name=crewloom-bot', '-c', 'user.email=41898282+github-actions[bot]@users.noreply.github.com',
'commit', '-m', 'docs: sync source facts from central manifest', cwd=checkout)
run('git', 'push', 'origin', branch, cwd=checkout)
return run('gh', 'pr', 'create', '--repo', repo, '--base', 'main', '--head', branch,
'--title', 'docs: sync source facts from central manifest', '--body',
'Generated documentation only. Source versions and stable GitHub releases remain distinct. Counts are structural, not benchmark claims. Human review and merge required. No runtime, license, publish or deployment changes.', cwd=checkout)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manifest', type=Path, default=ROOT / 'crewloom-manifest.json')
parser.add_argument('--output-dir', type=Path, default=ROOT / 'sync-output')
parser.add_argument('--checkouts', type=Path, help='Use existing read-only checkouts for offline tests')
parser.add_argument('--offline', action='store_true', help='Skip release lookup; never publish offline output')
parser.add_argument('--publish', action='store_true', help='Open docs-only PRs with scoped GH_TOKEN')
args = parser.parse_args()
if args.publish and (args.offline or args.checkouts):
parser.error('Publishing requires fresh checkouts and live release lookup')
m = load_manifest(args.manifest)
args.output_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as temporary:
sources = args.checkouts or Path(temporary)
facts = []
for p in m['projects']:
checkout = sources / p['repository']
if not args.checkouts:
run('git', '-c', 'core.hooksPath=/dev/null', 'clone', '--depth', '1', '--branch', p['ref'],
f"https://github.com/{m['organization']}/{p['repository']}.git", str(checkout))
facts.append(collect(p, checkout, 'offline' if args.offline else release(m['organization'], p['repository'])))
# Collect everything successfully before any writes or disclosures.
content = render(facts)
(args.output_dir / 'facts.json').write_text(json.dumps({'schema_version': 1, 'projects': facts}, indent=2) + '\n')
(args.output_dir / 'CREWLOOM_FACTS.md').write_text(content)
results = []
for p in m['projects']:
repo = f"{m['organization']}/{p['repository']}"
result = publish(sources / p['repository'], p['output'], content, repo) if args.publish else 'preview only'
results.append({'repository': repo, 'result': result})
print(json.dumps(results, indent=2))


if __name__ == '__main__':
main()
Loading
Loading