Establish Git-first TasksNest documentation and audit baseline
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic documentation preflight; semantic review is a human task."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DOCS = ROOT / "docs"
|
||||
STATE = DOCS / ".audit-state.json"
|
||||
LINK = re.compile(r"(?<!!)\[[^]]+\]\(([^)]+)\)")
|
||||
|
||||
|
||||
def git(*args):
|
||||
result = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True)
|
||||
return result.stdout.strip() if result.returncode == 0 else None
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return parsed.astimezone(timezone.utc) if parsed.tzinfo else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def links():
|
||||
broken = []
|
||||
for source in sorted(DOCS.rglob("*.md")):
|
||||
for target in LINK.findall(source.read_text(encoding="utf-8")):
|
||||
target = target.split()[0].strip("<>")
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme or parsed.netloc or target.startswith("#"):
|
||||
continue
|
||||
path = (source.parent / unquote(parsed.path)).resolve()
|
||||
if not path.is_relative_to(ROOT) or not path.exists():
|
||||
broken.append(f"{source.relative_to(ROOT)} -> {target}")
|
||||
return broken
|
||||
|
||||
|
||||
def preflight(force=False, now=None):
|
||||
now = now or datetime.now(timezone.utc)
|
||||
errors = []
|
||||
try:
|
||||
state = json.loads(STATE.read_text(encoding="utf-8"))
|
||||
if not isinstance(state, dict):
|
||||
raise ValueError("state must be an object")
|
||||
except (OSError, ValueError) as exc:
|
||||
state = {}
|
||||
errors.append(f"audit state unavailable or invalid: {exc}")
|
||||
last = timestamp(state.get("last_successful_audit"))
|
||||
if state.get("last_successful_audit") and last is None:
|
||||
errors.append("invalid last_successful_audit timestamp")
|
||||
if last and last > now:
|
||||
errors.append("last_successful_audit is in the future")
|
||||
last = None
|
||||
commit = state.get("last_audited_commit")
|
||||
head = git("rev-parse", "HEAD")
|
||||
valid = bool(commit and git("cat-file", "-e", f"{commit}^{{commit}}") is not None)
|
||||
reachable = bool(valid and head and git("merge-base", "--is-ancestor", commit, "HEAD") is not None)
|
||||
if commit and not valid:
|
||||
errors.append("last_audited_commit is not a valid local commit")
|
||||
elif commit and not reachable:
|
||||
errors.append("last_audited_commit is not an ancestor of HEAD")
|
||||
# A commit-to-working-tree diff includes committed, staged and unstaged
|
||||
# tracked edits. Untracked files cannot be compared with Git history.
|
||||
changed = git("diff", "--name-only", commit, "--", ".", ":(exclude)docs") if reachable else None
|
||||
return {
|
||||
"now_utc": now.isoformat(), "forced": force,
|
||||
"due": bool(force or last is None or now - last >= timedelta(days=14)),
|
||||
"last_successful_audit": state.get("last_successful_audit"),
|
||||
"last_audited_commit": commit, "head": head,
|
||||
"stored_commit_valid": valid, "stored_commit_reachable": reachable,
|
||||
"changed_tracked_source_files": changed.splitlines() if changed is not None else None,
|
||||
"broken_local_markdown_links": links() if DOCS.exists() else [],
|
||||
"warnings": errors,
|
||||
"semantic_review_performed": False,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--force", action="store_true", help="report audit due regardless of interval")
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(preflight(force=args.force), indent=2))
|
||||
Reference in New Issue
Block a user