
Repo Docs Align
- 5 installs
- 5 repo stars
- Updated August 5, 2026
- bjornmelin/dev-skills
Repo-docs-align is a Claude Code skill that syncs repo documentation surfaces with code and workflow and turns doc drift into a grounded plan.
About
Repo-docs-align is a Claude Code skill that syncs repository docs such as AGENTS.md, README, ADRs, specs, runbooks, and doc comments with the current code and workflow. It anchors on the current worktree, inventories doc surfaces, and turns drift into a grounded plan or a verified doc-alignment implementation. A developer uses it after a big change, when docs have drifted, or when governance requires an execution plan.
- Syncs repo docs (AGENTS.md, README, ADRs, specs, runbooks) with code and workflow
- Turns doc drift into a grounded, evidence-first execution plan
- Keeps one canonical doc surface per concern and updates it in place
Repo Docs Align by the numbers
- 5 all-time installs (skills.sh)
- Ranked #1,218 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
repo-docs-align capabilities & compatibility
Free; repo-native tooling, any stack.
- Capabilities
- docs alignment · drift detection · repo analysis
- Use cases
- documentation · code review · research
- Pricing
- Free
What repo-docs-align says it does
Use this skill to turn repo-doc drift into a grounded plan; when asked or clearly right, verified doc-align implementation.
One canonical doc surface per concern; update in place; avoid duplicate new docs.
task `plan-only`, `plan-then-execute`, or `audit-only`
npx skills add https://github.com/bjornmelin/dev-skills --skill repo-docs-alignAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 5 |
|---|---|
| repo stars | ★ 5 |
| Last updated | August 5, 2026 |
| Repository | bjornmelin/dev-skills ↗ |
What it does
Detect and fix documentation drift by aligning repo docs with the current code and workflow.
Who is it for?
Fixing documentation drift, planning doc alignment, and keeping AGENTS/README/ADRs/runbooks current with code.
Skip if: Narrow code-only changes with no documentation impact.
When should I use this skill?
After a big change, when docs drift, on docs-align or AGENTS prompts, or when governance needs a plan.
What you get
A grounded doc-alignment plan or verified implementation that brings repo docs back in sync with code.
- drift map
- reviewed-surfaces checklist
- execution plan
By the numbers
- 4 bundled templates (drift-map, reviewed-surfaces, exec-plan, retrospective)
- 3 reference guides
Files
Repo Docs Align
Use this skill to turn repo-doc drift into a grounded plan; when asked or clearly right, verified doc-align implementation.
Read before authority or compression calls:
- references/doc-surfaces-and-authority.md
- references/adaptive-compression.md
- references/subagent-orchestration.md
Bundled resources:
scripts/new_repo_docs_align_artifact.py- scaffold hidden artifacts under.agents/<skill-name>/YYYY-MM/MM-DD/NN/(<skill-name>= installed skill dir name)templates/drift-map.mdtemplates/reviewed-surfaces.mdtemplates/exec-plan.mdtemplates/retrospective.md
Core contract
- Start from current repo reality, not prior assumptions.
- Task incomplete until deliverables produced or marked
[blocked]. - One canonical doc surface per concern; update in place; avoid duplicate new docs.
- Default: repo-wide doc alignment - branch changes affect doc-owned concern anywhere → inspect surface, bring current.
- Hidden working artifacts OK for analysis, planning, tracking, retros; not canonical repo docs. Artifacts support run; canonical docs stay authority.
- Nontrivial runs: explicit checklist of outputs + reviewed areas. Before finalize: every deliverable + related doc surface covered or
[blocked]. - Major-choice scoring (material decisions only):
- No global fixed weight mix - per decision, pick criteria + weights for that focus (placement, supersession, stack/tool, scope, governance, risk, readers, maintenance; use what fits best).
- Name dimensions; weights sum to clear whole (e.g.
100%); score options; record rubric + scores in plan/synthesis. - Target
9.0+on winning path under that rubric when scoring applies. - User input improves major decision → one question at a time.
request_user_inputwhen available: - 2-3 mutually exclusive options
- Rubric for this decision (dimensions + weights) + per-option
0.0-10.0scores (weighted totals OK) - Recommended option first
Tool posture
update_planfor nontrivial runs - workstream explicit + checkable.request_user_inputfor major authority, scope, artifact decisions repo evidence cannot settle. No broad free-form batches.- Parallel read-only retrieval when safe for fast discovery.
- Subagents only when available; bounded exploration, evidence, doc/API verification, grep/path/file audits, focused review, validation triage. Main agent keeps authority, synthesis, default edits local.
- Built-in
web.*or MCP research when repo/docs evidence thin, stale, or task asks external verification. - Tool/plugin discovery only when capability not known this session.
- Image/PDF inspection when source of truth is visual (screenshots, rubrics, scans, PDF-only requirements).
Subagent contract
- Default: exploration + evidence only. No fan-out full doc authorship by default.
- Prefer
1-3focused subagents; no nested subagents unless user asks. - Explorer agents read-heavy, evidence-first. Implementation workers only for narrow follow-on after main agent chose authority path.
- Every
spawn_agentcall: setmodel+reasoning_effort. - Main skill: durable cheap-first — small model for bounded exploration, tighten task before escalate, escalate only underfitting subagent. Model ladder + prompt template in
references/subagent-orchestration.md. - Every delegated task specifies:
- narrow task or question
- allowed scope or surfaces
- read-only vs may edit
- main agent wait now vs local work until synthesis gate
- exact return format
- Default wait: continue local non-overlapping work; wait at synthesis gates before major authority, final recommendations, edits needing delegated evidence.
- Evidence-first returns:
- key finding or result
- files + symbols inspected
- commands or checks run, if any
- recommended next action
- unresolved questions or risks
- Conflicting delegated findings → surface conflict; resolve in main synthesis before act.
Workflow
1. Normalize the job
Extract:
- task
plan-only,plan-then-execute, oraudit-only - user wants durable repo artifact (exec plan/checklist)
- request mentions
AGENTS.md, README, ADRs, specs, runbooks, requirements docs, code comments - whether compression/token optimization is in scope
User asked specific response format → preserve exactly.
Repo dirty or branch-specific → anchor on current worktree:
git status --shortgit diff --name-only- changed code + docs → active functionality + authority surfaces
- from anchor: sweep related docs needing updates, corrections, supersession, rewrites, new coverage
- worktree = start signal for related-doc discovery, not outer boundary of docs review
- OK to inspect/plan/edit docs untouched in worktree if same functionality, workflow, contract, authority chain
- sweep until repo-wide docs for affected functionality current; no stale related guidance
2. Inventory the repo surfaces
Inspect smallest high-signal set first:
- root
AGENTS.md - nearest scoped
AGENTS.md README.md+ docs indexes- repo-local docs hub / status authority:
docs/README.md,requirements.md, release indexes, execution catalogs, machine-readable ledgers when present - ADR/spec/runbook dirs
- requirements, standards, policy docs when present
- recently changed files + nearby comments/docstrings
rg/repo-native search map likely impacted docs before edit. Parallelize independent read-only discovery before synthesis. Delegation: lightweight explorer subagents for repo mapping only after evidence targets known. Many docs → prioritize via docs hubs, status ledgers, execution catalogs, changed functionality; prioritization ≠ coverage limit.
3. Route into the right supporting skills and plugins
Prefer repo-native or user-named skills first. Adapt; don’t assume stack.
Examples:
$agents-md-maintainerbefore finalizing anyAGENTS.mdedit.$technical-writingwhen drafting/rewriting ADRs, specs, runbooks, migration docs, internal guides.$caveman-compressonly when surface fitsreferences/adaptive-compression.md.$hard-cut+$clean-codewhen simplifying stale doc structure or removing superseded guidance.- Stack/platform skills/plugins (
$github,$vercel,$expo,$sentry, Context7, built-in web search) only when repo context or user request makes them relevant.
Named skill/plugin unavailable → note briefly; closest valid fallback.
4. Build a drift map before proposing changes
Compare current docs to:
- implemented behavior
- current scripts/commands
- current architecture + file ownership
- current validation flow
- branch-specific changes that made existing docs stale
- related repo docs describing, constraining, teaching, operating, validating, routing affected functionality
Good delegation:
- one explorer:
AGENTS.md+ scoped guidance drift - one explorer: ADR/spec/runbook/README ownership mapping
- one explorer: external doc/API verification when repo evidence thin; built-in
web.*where search needed
Classify each finding:
update-in-placecreate-canonical-docmark-supersededdelete-stale-guidanceleave-unchanged
No new docs until existing authority doc confirmed not owning concern. Don’t stop at first matching doc. Follow authority chain across README hubs, AGENTS, requirements, ADRs, specs, runbooks, setup, release docs, prompt catalogs, nearby comments/docstrings until related doc set aligned. Map every proposed doc/comment change to exact file, path, or code-comment surface. No named target → not grounded yet.
5. Choose the canonical authority path
Authority matrix in references/doc-surfaces-and-authority.md.
Rules:
- Prefer modifying current canonical doc over creating new.
- New ADR/spec/runbook only when concern materially new + doesn’t fit current authority surface.
- Keep
AGENTS.mddurable repo guidance only — no task logs or branch narration. - Repo already has docs-role map, status ledger, execution catalog → first-class authority input before inventing placement.
- Long-lived execution context needed → create/update one checkable repo-local exec artifact per existing naming conventions.
6. Produce the durable exec artifact when needed
Future-session handoff → create/update one canonical plan/checklist with only fitting sections:
- scope + intent
- summary of completed work
- files + surfaces reviewed
- what is done
- remaining tasks + subtasks
- further improvements worth considering
- required research
- decisions made + open decisions
- validation commands + success criteria
- required skills/plugins/tools
- exact files/dirs to load next session
- enforced rules/invariants next session must preserve
- blockers + assumptions
Execution-oriented, not diary. If the repo already has an execution catalog, prompt ledger, or trigger-prompt system, update that canonical surface, not parallel plan file.
6a. Hidden working artifact policy
Non-canonical artifacts from this skill default:
.agents/<skill-name>/YYYY-MM/MM-DD/NN/
When this skill is installed as repo-docs-align, that resolves to .agents/repo-docs-align/YYYY-MM/MM-DD/NN/.
Use this hidden work area for things like:
drift-map.mdreviewed-surfaces.mdexec-plan.mdretrospective.md- other temporary/session analysis supporting docs alignment
Rules:
- create directory when needed
- fresh numeric run bucket
01,02,03same-day repeats - ensure repo ignores
.agents/or min.agents/<skill-name>/ - canonical docs, ledgers, specs, ADRs, runbooks, active execution catalogs stay true authority surfaces — not
.agents/<skill-name>/ - typed filenames vs one giant note when artifacts differ materially
- only create artifacts useful for run; no empty scaffolding
Deterministic scaffolding for hidden work area:
python3 scripts/new_repo_docs_align_artifact.py \
--dir <repo-root> \
--artifacts drift-map,reviewed-surfaces,exec-plan,retrospectiveRun exact command from installed skill directory. Script resolves bundled templates relative to itself; shorter relative path unambiguous install-wide.
--artifacts = only files needed. --force = only when intentionally refreshing existing artifact file.
7. Implement doc and comment changes when the task calls for execution
After drift map + authority are grounded:
- update canonical docs
- tighten or remove stale guidance
- align nearby code comments/docstrings where useful
- smallest edit set that fully resolves grounded drift; no partially corrected authority chains
- minimal, reviewable diffs
Do not rewrite unrelated docs for imperfection alone.
8. Apply adaptive compression only where it improves the repo
Follow references/adaptive-compression.md.
Default:
- compress internal operational, agent-facing, workflow, repo-maintenance docs when scan speed + token efficiency improve
- richer prose for public, product, marketing, narrative, teaching docs unless user requests compression
When compressing:
- preserve code, commands, paths, URLs, headings, tables, exact technical terms
- keep document navigable
- don’t cavemanify docs whose value is nuanced explanation or polished prose
9. Verify before finalizing
Verify:
- every doc change maps to specific file or confirmed gap
- every unchanged reviewed surface has reason (explicit or implicit) grounded in current repo reality
- authority choices match current repo structure
- requested deliverables complete
- formatting matches surrounding docs
- referenced commands, scripts, paths still exist
- irreversible or external side effects surfaced before execution
Changed AGENTS.md → brief $agents-md-maintainer pass before closeout.
Output shape
Default order unless user asked for a different format:
1. drift summary 2. canonical authority decisions 3. exec artifact path or inline plan 4. implemented doc/comment changes 5. verification commands + residual gaps
Stop rules
- Stop + ask only when major authority decision genuinely ambiguous + repo evidence can’t resolve.
- Missing evidence or uncertain claims →
UNVERIFIED. - Retrieval empty or suspiciously narrow → retry one or two different strategies before conclude.
interface:
display_name: "Repo Docs Align"
short_description: "Align AGENTS, docs, ADRs, specs, and comments with repo reality"
default_prompt: "Use $repo-docs-align to map docs drift, choose canonical authority docs, create or update a durable exec artifact when needed, and execute verified repo-doc alignment end to end."
policy:
allow_implicit_invocation: true
dependencies:
tools:
- type: "mcp"
value: "context7"
description: "Official or primary documentation research when repo evidence is not enough"
Adaptive Compression
Use this file to decide whether caveman-style compression improves a touched document.
Default policy
Prefer selective compression, not blanket compression.
Good compression targets
Compress when the document is mainly:
- internal operational guidance
- agent-facing instructions
- repo-maintenance notes
- execution checklists
- workflow manifests
- compact standards or runbooks where scanning matters more than prose polish
Usually do not compress
Avoid caveman-style compression when the document is mainly:
- product strategy
- marketing or positioning
- public-facing docs
- polished teaching material
- reports where narrative and rhetorical quality matter
- nuanced architecture or design rationale that would lose important precision
Mixed cases
For mixed docs:
- compress operational/checklist sections
- preserve richer prose in narrative, rationale, or externally shared sections
Compression guardrails
When compressing, preserve exactly:
- commands
- code blocks
- file paths
- URLs and links
- headings
- tables
- version numbers and dates
- exact technical terms
Do not compress so far that:
- navigation gets harder
- intent becomes ambiguous
- rationale disappears where future readers need it
- the document stops matching surrounding repo style
Interaction with $caveman-compress
If $caveman-compress is available and the target surface clearly fits this policy, route into it or apply the same rules directly.
If compression would materially harm readability or doc purpose, skip it and say why.
Document Surfaces And Authority
Use this file to choose the smallest correct authority surface for repo-doc alignment work.
Surface selection
AGENTS.md
Use for durable repo guidance that a coding agent must know in a fresh session:
- required verification commands
- architecture invariants
- canonical file ownership
- stable review/release expectations
- recurring failure modes with durable fixes
Do not use for:
- task status
- branch summaries
- step-by-step project plans
- feature-specific narration
README.md
Use for repo entrypoint guidance:
- what the repo is
- how to set up or navigate it
- where core docs live
- top-level workflows users or contributors need first
Do not overload README.md with deep architecture or long task tracking.
ADRs
Use when one material decision needs durable rationale:
- options considered
- chosen path
- consequences
- superseded decisions
Prefer ADRs over broad design docs when one decision is the real unit of change.
Specs / requirements / design docs
Use for implementation-shaping detail:
- goals and non-goals
- constraints
- system design
- rollout and rollback
- validation criteria
Prefer updating an existing canonical spec over creating a sibling spec.
Runbooks / operator guides
Use for operational action:
- detect
- diagnose
- recover
- escalate
Optimize for speed and correctness under pressure.
Exec artifact / checklist / plan file
Use only when the task needs durable future-session execution context.
This file should be:
- checkable
- current
- scoped to one stream of work
- explicit about validation and remaining tasks
Do not duplicate authority already owned by AGENTS.md, ADRs, or stable specs. Link to them instead.
Docs hubs / status ledgers / execution catalogs
Some repos publish an explicit docs-role map or machine-readable execution surface, for example:
docs/README.mdrequirements.mdor status ledgers- release indexes
- prompt catalogs
- machine-readable ledgers or inventories
Treat these as authority-routing inputs. They often answer:
- which doc owns current implementation status
- which docs are active vs superseded
- where execution plans belong
- which filenames or ledgers are contractually stable
If these surfaces exist, read them before creating new docs or relocating work.
Decision rules
1. Update the current authority doc first. 2. Create a new doc only if no existing authority surface fits. 3. Mark stale docs as superseded or delete them when they no longer own the truth. 4. Keep one canonical source per concern. 5. Prefer repo-local conventions for naming and placement.
Mapping hints
If the issue is about:
- repo-wide coding agent behavior ->
AGENTS.md - how to enter or navigate the repo ->
README.md - how docs are partitioned, which docs are active, or where execution work belongs -> docs hub / status ledger / execution catalog
- why a material decision changed -> ADR
- how something should be built or validated -> spec / requirements doc
- how to operate or recover a system -> runbook
- how to continue a bounded workstream next session -> exec artifact
Subagent Orchestration
Use this file when repo-docs-align needs subagents for evidence gathering, repo mapping, or verification.
Purpose
Subagents improve this skill when they stay bounded and evidence-focused. They should reduce search time and surface conflicts, not take over authority decisions or final synthesis.
Default policy
- Main agent owns:
- overall plan quality
- canonical authority decisions
- final synthesis
- default doc edits
- Subagents own:
- exploration
- grep/path/file audits
- doc or API verification
- focused review
- validation triage
- narrowly scoped drafting or implementation only when explicitly needed
Fan-out limits
- Prefer
1-3focused subagents. - Avoid broad fan-out.
- Do not spawn nested subagents unless the user explicitly asks.
Budget-optimized model policy
Default model ladder:
- first choice:
gpt-5.4-mini - larger fallback:
gpt-5.3-codex - near-instant text-only triage:
gpt-5.3-codex-spark
gpt-5.4-mini
- default effort:
medium - use
mediumfor most repo mapping, read-heavy scans, codebase tracing, focused audits, doc/API verification, standard review passes, and normal bounded implementation - use
highfor ambiguous findings, cross-file reasoning, conflicting evidence, tricky debugging, security-sensitive inspection, or critical logic-path review - use
lowonly for simple deterministic tasks such as path lookup, quick grep confirmation, tiny file checks, surface inventory, or basic doc lookup
Prefer medium over low by default. Before moving from medium to high, tighten the task statement, expected output, and verification requirements first.
gpt-5.3-codex
Use only when gpt-5.4-mini is clearly underfitting after one tighter pass, or when the task is cross-cutting, ambiguous, or high-risk.
- use
lowfor straightforward implementation - use
mediumfor normal non-trivial work - use
highonly when genuinely necessary
Do not use xhigh by default.
gpt-5.3-codex-spark
Use only for near-instant, text-only drafting or triage. Do not use Spark for code changes, final decisions, or high-risk reasoning.
Escalation rules
Before raising model or effort, first tighten:
- task statement
- output contract
- verification requirements
Escalate only the specific subagent that is underfitting. Do not escalate the whole session because one worker struggles.
Wait policy
Default posture:
- spawn bounded explorers
- keep the main agent doing non-overlapping local work
- wait at synthesis gates before major authority decisions, final recommendations, or edits that depend on delegated evidence
Only wait immediately when the very next step is blocked on the delegated result.
Mandatory spawn checklist
Every spawn_agent call should include:
- exact task or question
- allowed scope or surfaces
- read-only vs may-edit status
- whether the main agent should wait now or continue until a synthesis gate
- exact return format
- explicit
(model, reasoning_effort) - one-line reason when using a non-default model or effort
Return contract
Require this exact shape or a close equivalent:
Key finding/result:
Files/symbols inspected:
Commands/checks run:
Recommended next action:
Unresolved questions/risks:Reject vague summaries without evidence.
Prompt template
Use a prompt like:
Task: <one narrow question>
Scope: <allowed files, docs, APIs, or repo surfaces only>
Mode: <read-only | may edit>
Wait policy: <main agent waits now | main agent continues until synthesis gate>
Return format:
- Key finding/result
- Files/symbols inspected
- Commands/checks run
- Recommended next action
- Unresolved questions/risks
Model/effort reason: <only when non-default>Good fits for this skill
- explorer 1: map
AGENTS.mdand scoped guidance drift - explorer 2: map README/ADR/spec/runbook ownership and stale surfaces
- explorer 3: verify external docs or APIs when repo evidence is insufficient, using built-in
web.search_query,web.open,web.find,web.click, and relatedweb.*tools as needed
Bad fits for this skill
- broad multi-agent doc rewrites before the authority path is chosen
- nested fan-out
- vague “analyze the repo” prompts
- handing final decisions to a worker when the main agent is not blocked
#!/usr/bin/env python3
"""Create portable repo-docs-align working artifacts under the hidden .agents tree."""
import argparse
import datetime as dt
import re
import subprocess
from pathlib import Path
ARTIFACTS = {
"drift-map": "drift-map.md",
"reviewed-surfaces": "reviewed-surfaces.md",
"exec-plan": "exec-plan.md",
"retrospective": "retrospective.md",
}
def today_parts(date_override: str | None) -> tuple[str, str, str]:
"""Return the month, day, and ISO date used for artifact paths.
Args:
date_override: Optional date string in ``YYYY-MM-DD`` format. If
omitted, the current local date is used.
Returns:
A ``(month_dir, day_dir, iso_date)`` tuple of strings, where
``month_dir`` is ``YYYY-MM``, ``day_dir`` is ``MM-DD``, and
``iso_date`` is ``YYYY-MM-DD``.
Raises:
ValueError: If ``date_override`` is provided but is not valid
``YYYY-MM-DD`` input.
"""
if date_override:
day = dt.datetime.strptime(date_override, "%Y-%m-%d").date()
else:
day = dt.date.today()
return day.strftime("%Y-%m"), day.strftime("%m-%d"), day.isoformat()
def normalize_run_bucket(raw: str) -> str:
"""Normalize a run bucket string to a zero-padded two-digit value.
Args:
raw: Raw bucket input from the CLI. The value must be numeric and at
least 1.
Returns:
A zero-padded two-digit run bucket string such as ``"01"`` or
``"12"``.
Raises:
SystemExit: If ``raw`` is empty, non-numeric, or less than 1.
"""
raw = raw.strip()
if not raw:
raise SystemExit("Run bucket cannot be empty.")
if not raw.isdigit():
raise SystemExit("Run bucket must be numeric, e.g. 01 or 2.")
value = int(raw, 10)
if value < 1:
raise SystemExit("Run bucket must be >= 1.")
return f"{value:02d}"
def next_run_bucket(day_root: Path) -> str:
"""Compute the next available run bucket for a day directory.
Args:
day_root: Root directory for a given day, typically
``.agents/<skill>/<YYYY-MM>/<MM-DD>``.
Returns:
The next available zero-padded run bucket string.
Raises:
OSError: If directory iteration fails while scanning ``day_root``.
"""
max_seen = 0
if day_root.exists():
for child in day_root.iterdir():
if child.is_dir() and child.name.isdigit():
max_seen = max(max_seen, int(child.name, 10))
return f"{max_seen + 1:02d}"
def read_template(skill_root: Path, artifact_key: str) -> str:
"""Read the template text for a named artifact.
Args:
skill_root: Root directory of the installed skill package.
artifact_key: Artifact key from ``ARTIFACTS``.
Returns:
The template file contents as a string.
Raises:
KeyError: If ``artifact_key`` is not a known artifact name.
OSError: If the template file cannot be read.
"""
template_path = (skill_root / "templates" / ARTIFACTS[artifact_key]).resolve()
try:
return template_path.read_text(encoding="utf-8")
except OSError as exc:
raise SystemExit(
"Failed to load template "
f"(artifact_key={artifact_key}, skill_root={skill_root}, template_path={template_path}): "
f"{exc}"
) from exc
def render_template(template: str, iso_date: str, repo_name: str, repo_root: Path) -> str:
"""Substitute repository and date placeholders into a template.
Args:
template: Raw template text containing ``{{DATE}}``, ``{{REPO_NAME}}``,
and ``{{REPO_ROOT}}`` placeholders.
iso_date: Date string in ``YYYY-MM-DD`` format.
repo_name: Repository name used for the rendered artifact.
repo_root: Absolute repository root path inserted into the template.
Returns:
The rendered template text.
Raises:
None: This function performs only string substitution.
"""
return (
template.replace("{{DATE}}", iso_date)
.replace("{{REPO_NAME}}", repo_name)
.replace("{{REPO_ROOT}}", str(repo_root))
)
def has_agents_rule(existing: list[str]) -> bool:
"""Return whether the current .gitignore already mentions the hidden tree."""
pattern = re.compile(r"(?:^|/)\.agents(?:$|/)")
return any(pattern.search(line.lstrip("!/")) for line in existing)
def git_ignores_path(repo_root: Path, relative_path: str) -> bool:
"""Return whether Git currently ignores the given relative path."""
try:
result = subprocess.run(
["git", "check-ignore", "-q", relative_path],
cwd=repo_root,
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except OSError:
return False
return result.returncode == 0
def ensure_gitignore(repo_root: Path, skill_name: str) -> str:
"""Ensure the repository ignores the hidden .agents artifact directory.
Args:
repo_root: Absolute repository root path containing ``.gitignore``.
skill_name: Installed skill directory name used in the hidden path.
Returns:
``"already_ignored"`` if an existing rule already covers the target, or
``"added_agents_rule"`` if ``.agents/`` was appended.
Raises:
OSError: If reading or writing ``.gitignore`` fails.
"""
gitignore_path = repo_root / ".gitignore"
if gitignore_path.exists():
current = gitignore_path.read_text(encoding="utf-8")
else:
current = ""
existing = [
line.strip()
for line in current.splitlines()
if line.strip() and not line.lstrip().startswith("#")
]
probe_path = f".agents/{skill_name}"
if git_ignores_path(repo_root, probe_path) or has_agents_rule(existing):
return "already_ignored"
rule = ".agents/\n"
if current and not current.endswith("\n"):
current += "\n"
gitignore_path.write_text(current + rule, encoding="utf-8")
return "added_agents_rule"
def parse_artifacts(raw: str) -> list[str]:
"""Parse the requested artifact list from CLI input.
Args:
raw: Comma-separated artifact keys or the literal ``all``.
Surrounding whitespace is ignored.
Returns:
A list of validated artifact keys in request order.
Raises:
SystemExit: If an unknown key is provided or no artifacts are requested.
"""
raw = raw.strip().lower()
if raw == "all":
return list(ARTIFACTS.keys())
requested = []
for item in raw.split(","):
key = item.strip()
if not key:
continue
if key not in ARTIFACTS:
valid = ", ".join(sorted(ARTIFACTS))
raise SystemExit(f"Unknown artifact '{key}'. Valid values: {valid}, all")
requested.append(key)
if not requested:
raise SystemExit("No artifacts requested.")
return requested
def main() -> int:
"""Run the CLI to scaffold repo-docs-align working artifacts.
Args:
None: Command-line arguments are parsed from ``sys.argv``.
Returns:
Zero on success.
Raises:
SystemExit: For argument parsing failures, invalid repository paths, or
other user-facing validation errors.
OSError: If filesystem operations fail while creating artifacts.
"""
parser = argparse.ArgumentParser(
description=(
"Create typed working artifacts under "
".agents/<skill-name>/YYYY-MM/MM-DD/NN/ and ensure ignore hygiene."
)
)
parser.add_argument(
"--dir",
default=".",
help="Target repository directory. Defaults to the current directory.",
)
parser.add_argument(
"--artifacts",
default="all",
help=(
"Comma-separated artifact keys to create. "
"Valid: drift-map,reviewed-surfaces,exec-plan,retrospective,all"
),
)
parser.add_argument(
"--date",
default=None,
help="Override date in YYYY-MM-DD format. Defaults to today.",
)
parser.add_argument(
"--run",
default=None,
help="Override numeric run bucket for the day, e.g. 01 or 2. Defaults to the next available bucket.",
)
parser.add_argument(
"--force",
action="store_true",
help="Overwrite artifact files if they already exist.",
)
args = parser.parse_args()
repo_root = Path(args.dir).resolve()
if not repo_root.exists() or not repo_root.is_dir():
raise SystemExit(f"Target directory does not exist: {repo_root}")
requested = parse_artifacts(args.artifacts)
month_dir, day_dir, iso_date = today_parts(args.date)
skill_name = Path(__file__).resolve().parent.parent.name
day_root = repo_root / ".agents" / skill_name / month_dir / day_dir
run_bucket = normalize_run_bucket(args.run) if args.run else next_run_bucket(day_root)
artifact_dir = day_root / run_bucket
artifact_dir.mkdir(parents=True, exist_ok=True)
ignore_status = ensure_gitignore(repo_root, skill_name)
skill_root = Path(__file__).resolve().parent.parent
repo_name = repo_root.name
created_paths: list[Path] = []
for artifact_key in requested:
filename = ARTIFACTS[artifact_key]
target = artifact_dir / filename
if target.exists() and not args.force:
continue
rendered = render_template(
read_template(skill_root, artifact_key),
iso_date=iso_date,
repo_name=repo_name,
repo_root=repo_root,
)
target.write_text(rendered.rstrip() + "\n", encoding="utf-8")
created_paths.append(target)
print(f"artifact_dir={artifact_dir}")
print(f"run_bucket={run_bucket}")
print(f"gitignore={ignore_status}")
for path in created_paths:
print(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Drift Map
Date: {{DATE}} Repo: {{REPO_NAME}} Repo root: {{REPO_ROOT}}
Active functionality
-
Reviewed authority surfaces
- [ ]
AGENTS.md - [ ]
README.md - [ ] docs hub / status authority
- [ ] ADR / spec / runbook chain
- [ ] setup / release / execution surfaces
- [ ] nearby comments / docstrings
Drift findings
| Surface | Status | Issue | Recommended action |
|---|---|---|---|
Missing or new docs needed
-
Blockers / assumptions
-
Exec Plan
Date: {{DATE}} Repo: {{REPO_NAME}} Repo root: {{REPO_ROOT}}
Scope and intent
-
Completed work
-
Reviewed surfaces
-
Remaining tasks
- [ ]
Further improvements
-
Required research
-
Decisions made
-
Open decisions
-
Validation and success criteria
-
Required skills / plugins / tools
-
Exact files or directories to load next
-
Enforced rules / invariants
-
Blockers / assumptions
-
Retrospective
Date: {{DATE}} Repo: {{REPO_NAME}} Repo root: {{REPO_ROOT}}
What worked
-
Friction or missed coverage
-
Skill improvements suggested
-
Repo follow-up opportunities
-
Verification notes
-
Reviewed Surfaces
Date: {{DATE}} Repo: {{REPO_NAME}} Repo root: {{REPO_ROOT}}
Files and surfaces reviewed
-
Related surfaces intentionally unchanged
| Surface | Reason unchanged |
|---|---|
Follow-up review targets
-
Related skills
FAQ
Which doc surfaces does repo-docs-align cover?
AGENTS.md, README, ADRs, specs, runbooks, requirements docs, and code doc comments, with one canonical surface per concern.
Does it plan or also implement?
It supports plan-only, plan-then-execute, and audit-only modes, and can produce a verified doc-alignment implementation when asked.