Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

ci: add docs-quality gates and stricter PR template (#173)

TamL.848e90a818cc
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 1946890..f161653 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -12,6 +12,18 @@ Thanks for contributing to img2threejs. Keep the pull request focused and remove
-
+## Description matches the diff
+
+- [ ] The title and summary describe exactly what the diff changes (no unrelated files, no commits inherited from another PR). `docs:` PRs touch only docs; CI enforces this.
+
+## Verified
+
+<!-- REQUIRED. Commands you actually ran and their key output (paste the relevant lines). "N/A" only for pure typo fixes. -->
+
+## Unverified claims
+
+<!-- REQUIRED. Anything stated in docs or code comments that you did NOT execute or confirm (install steps, versions, performance, behavior on other hosts). Write "None" or list each item; do not state unverified items as fact in the docs. -->
+
## Validation
<!-- Record the checks you ran and their results. Include render/comparison-sheet evidence for changes that affect reconstruction quality. -->
diff --git a/.github/workflows/docs-quality.yml b/.github/workflows/docs-quality.yml
new file mode 100644
index 0000000..679cc55
--- /dev/null
+++ b/.github/workflows/docs-quality.yml
@@ -0,0 +1,60 @@
+name: Docs quality
+
+# Deterministic, stdlib-only gates (scripts/ci/*.py, Python 3.10). No third-party actions.
+on:
+ pull_request:
+
+permissions:
+ contents: read
+ pull-requests: read
+
+jobs:
+ scripts-selftest:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+ - run: python3 -m unittest discover -s scripts/ci/tests
+
+ markdown:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+ - name: GFM table lint (changed *.md)
+ run: python3 scripts/ci/md_tables.py --base "origin/${{ github.base_ref }}"
+ - name: Relative links and anchors (changed *.md)
+ run: python3 scripts/ci/md_links.py --baseline scripts/ci/link-baseline.txt --base "origin/${{ github.base_ref }}"
+
+ skill-budget:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+ - run: python3 scripts/ci/skill_budget.py
+
+ pr-scope:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.10"
+ - name: Title type vs diff, stacked-PR warning
+ env:
+ PR_TITLE: ${{ github.event.pull_request.title }} # via env: never interpolate titles into shell
+ GH_TOKEN: ${{ github.token }}
+ run: >
+ python3 scripts/ci/pr_scope.py --gha 1
+ --title "$PR_TITLE" --base "origin/${{ github.base_ref }}"
+ --repo "${{ github.repository }}" --pr "${{ github.event.pull_request.number }}"
diff --git a/scripts/ci/link-baseline.txt b/scripts/ci/link-baseline.txt
new file mode 100644
index 0000000..77a5105
--- /dev/null
+++ b/scripts/ci/link-baseline.txt
@@ -0,0 +1,2 @@
+# Known-broken relative links tolerated by the gate ("path: target" per line).
+# Empty on purpose: main currently has none. Fix links instead of adding here.
diff --git a/scripts/ci/md_links.py b/scripts/ci/md_links.py
new file mode 100644
index 0000000..1a16576
--- /dev/null
+++ b/scripts/ci/md_links.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""Check relative links and #anchors in Markdown files (GitHub slug rules).
+
+Usage: md_links.py [--baseline FILE] --base <ref> | --all | FILE...
+A baseline file lists known-broken links ("path: target" per line, '#' comments)
+that are tolerated so the gate passes on main; remove lines as they get fixed.
+Stale baseline entries are reported (not failed) so they get cleaned up.
+"""
+import os
+import re
+import sys
+import unicodedata
+from urllib.parse import unquote
+
+sys.path.insert(0, os.path.dirname(__file__))
+from mdcommon import files_from_args, iter_lines, report # noqa: E402
+
+LINK_RE = re.compile(r"(?<!!)\[(?:[^\]\\]|\\.)*\]\(\s*<?([^)\s>]+)>?(?:\s+\"[^\"]*\")?\s*\)|!\[[^\]]*\]\(\s*<?([^)\s>]+)>?[^)]*\)")
+HEADING_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
+HTML_ID_RE = re.compile(r"""<a\s+[^>]*(?:name|id)=["']([^"']+)["']""", re.I)
+CODE_SPAN_RE = re.compile(r"`[^`]*`")
+
+
+def slugify(heading):
+ """GitHub heading slug: strip md formatting, lowercase, drop punctuation, spaces->'-'."""
+ t = re.sub(r"!?\[([^\]]*)\]\([^)]*\)", r"\1", heading)
+ t = t.replace("`", "")
+ t = re.sub(r"<[^>]+>", "", t)
+ t = t.strip().lower()
+ out = []
+ for ch in t:
+ if ch.isalnum() or ch in "-_":
+ out.append(ch)
+ elif ch == " ":
+ out.append("-")
+ elif unicodedata.category(ch)[0] in "LNM":
+ out.append(ch)
+ return "".join(out)
+
+
+_anchor_cache = {}
+
+
+def anchors_of(path):
+ if path in _anchor_cache:
+ return _anchor_cache[path]
+ seen, anchors = {}, set()
+ try:
+ with open(path, encoding="utf-8") as fh:
+ text = fh.read()
+ except OSError:
+ text = ""
+ for _, line, fenced in iter_lines(text):
+ if fenced:
+ continue
+ m = HEADING_RE.match(line)
+ if m:
+ s = slugify(m.group(2))
+ k = seen.get(s, 0)
+ seen[s] = k + 1
+ anchors.add(s if k == 0 else f"{s}-{k}")
+ for h in HTML_ID_RE.findall(line):
+ anchors.add(h)
+ _anchor_cache[path] = anchors
+ return anchors
+
+
+def check_text(text, path, root="."):
+ problems = []
+ for n, line, fenced in iter_lines(text):
+ if fenced:
+ continue
+ line = CODE_SPAN_RE.sub("", line)
+ for m in LINK_RE.finditer(line):
+ target = m.group(1) or m.group(2)
+ if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", target) or target.startswith("//"):
+ continue
+ file_part, _, frag = target.partition("#")
+ file_part = unquote(file_part.split("?")[0])
+ if file_part:
+ dest = os.path.normpath(os.path.join(os.path.dirname(path), file_part))
+ if file_part.startswith("/"):
+ dest = os.path.normpath(os.path.join(root, file_part.lstrip("/")))
+ if not os.path.exists(dest):
+ problems.append((path, n, target, f"file not found: {dest}"))
+ continue
+ else:
+ dest = path
+ if frag and dest.endswith(".md") and os.path.isfile(dest):
+ if unquote(frag).lower() not in {a.lower() for a in anchors_of(dest)}:
+ problems.append((path, n, target, f"anchor '#{frag}' not found in {dest}"))
+ return problems
+
+
+def load_baseline(path):
+ entries = set()
+ if path and os.path.isfile(path):
+ for l in open(path, encoding="utf-8"):
+ l = l.strip()
+ if l and not l.startswith("#"):
+ entries.add(l)
+ return entries
+
+
+def main(argv):
+ baseline = None
+ if argv[:1] == ["--baseline"]:
+ baseline, argv = argv[1], argv[2:]
+ base = load_baseline(baseline)
+ used, out = set(), []
+ for f in files_from_args(argv):
+ if not os.path.isfile(f):
+ continue
+ with open(f, encoding="utf-8") as fh:
+ for path, n, target, why in check_text(fh.read(), f):
+ key = f"{path}: {target}"
+ if key in base:
+ used.add(key)
+ else:
+ out.append(f"{path}:{n}: broken link '{target}' ({why})")
+ for stale in sorted(base - used):
+ print(f"note: baseline entry no longer needed or file not checked: {stale}")
+ return report(out)
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci/md_tables.py b/scripts/ci/md_tables.py
new file mode 100644
index 0000000..ece7401
--- /dev/null
+++ b/scripts/ci/md_tables.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""Detect GFM tables that will not render.
+
+Usage: md_tables.py --base <ref> | --all | FILE...
+Checks: rows starting with '||', empty/invalid delimiter cells, header vs
+delimiter column-count mismatch.
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(__file__))
+from mdcommon import files_from_args, iter_lines, report # noqa: E402
+
+DELIM_CELL = re.compile(r"^\s*:?-+:?\s*$")
+
+
+def split_row(line):
+ s = line.strip()
+ if s.startswith("|"):
+ s = s[1:]
+ if s.endswith("|") and not s.endswith("\\|"):
+ s = s[:-1]
+ return [c for c in re.split(r"(?<!\\)\|", s)]
+
+
+def looks_like_delim(line):
+ s = line.strip()
+ return "|" in s and re.fullmatch(r"[\s|:\-]+", s) is not None and "-" in s
+
+
+def check_text(text, name="<text>"):
+ problems = []
+ lines = list(iter_lines(text))
+ for idx, (n, line, fenced) in enumerate(lines):
+ if fenced:
+ continue
+ if line.lstrip().startswith("||"):
+ problems.append(f"{name}:{n}: table row starts with '||' (renders as broken table); use a single '|'")
+ continue
+ if looks_like_delim(line) and idx > 0:
+ pn, prev, pf = lines[idx - 1]
+ if pf or "|" not in prev:
+ continue
+ cells = split_row(line)
+ bad = [c for c in cells if not DELIM_CELL.match(c)]
+ if bad:
+ problems.append(f"{name}:{n}: delimiter row has empty/invalid cell(s) {bad!r}")
+ continue
+ if len(split_row(prev)) != len(cells):
+ problems.append(f"{name}:{n}: header has {len(split_row(prev))} columns but delimiter row has {len(cells)}")
+ return problems
+
+
+def main(argv):
+ problems = []
+ for f in files_from_args(argv):
+ if os.path.isfile(f):
+ with open(f, encoding="utf-8") as fh:
+ problems += check_text(fh.read(), f)
+ return report(problems)
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci/mdcommon.py b/scripts/ci/mdcommon.py
new file mode 100644
index 0000000..c497681
--- /dev/null
+++ b/scripts/ci/mdcommon.py
@@ -0,0 +1,59 @@
+"""Shared helpers for the docs-quality gates (stdlib only)."""
+import re
+import subprocess
+import sys
+
+FENCE_RE = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
+
+
+def iter_lines(text):
+ """Yield (lineno, line, in_fence). Fence markers themselves count as in_fence."""
+ fence = None
+ for n, line in enumerate(text.splitlines(), 1):
+ m = FENCE_RE.match(line)
+ if fence is None:
+ if m:
+ fence = m.group(1)[0]
+ yield n, line, True
+ continue
+ yield n, line, False
+ else:
+ yield n, line, True
+ if m and m.group(1)[0] == fence and not line.strip().strip(fence):
+ fence = None
+
+
+def strip_frontmatter_lines(text):
+ """Return text with a leading YAML front matter block blanked (line numbers kept)."""
+ lines = text.splitlines()
+ if lines and lines[0].strip() == "---":
+ for i in range(1, len(lines)):
+ if lines[i].strip() == "---":
+ return "\n".join([""] * (i + 1) + lines[i + 1:])
+ return text
+
+
+def changed_files(base, pattern_suffix=".md"):
+ out = subprocess.run(
+ ["git", "diff", "--name-only", "--diff-filter=ACMR", f"{base}...HEAD"],
+ capture_output=True, text=True, check=True).stdout
+ return [f for f in out.splitlines() if f.endswith(pattern_suffix)]
+
+
+def files_from_args(argv):
+ """argv: either explicit files, or `--base <ref>` to use the git diff."""
+ if len(argv) >= 2 and argv[0] == "--base":
+ return changed_files(argv[1])
+ if argv == ["--all"]:
+ out = subprocess.run(["git", "ls-files", "*.md"], capture_output=True,
+ text=True, check=True).stdout
+ return out.splitlines()
+ return argv
+
+
+def report(problems):
+ for p in problems:
+ print(p)
+ if problems:
+ print(f"\n{len(problems)} problem(s) found.", file=sys.stderr)
+ return 1 if problems else 0
diff --git a/scripts/ci/pr_scope.py b/scripts/ci/pr_scope.py
new file mode 100644
index 0000000..6857cf1
--- /dev/null
+++ b/scripts/ci/pr_scope.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""PR scope gate: the conventional-commit type in the PR title must match the diff.
+
+Usage: pr_scope.py --title TITLE --base REF [--repo OWNER/NAME --pr N]
+- `docs:` / `docs(scope):` PRs may only touch docs-like paths; otherwise FAIL.
+- Stacked-PR warning (never fails): commits of this PR that also sit in another
+ open PR's head. Uses `gh` read-only; skipped silently if unavailable.
+"""
+import fnmatch
+import json
+import re
+import subprocess
+import sys
+
+TYPE_RE = re.compile(r"^\s*([a-zA-Z]+)(\([^)]*\))?(!)?:\s")
+DOCS_PATTERNS = ["*.md", "docs/*", "assets/*", ".github/pull_request_template.md",
+ ".github/ISSUE_TEMPLATE/*", ".github/PULL_REQUEST_TEMPLATE/*"]
+
+
+def commit_type(title):
+ m = TYPE_RE.match(title or "")
+ return m.group(1).lower() if m else None
+
+
+def is_docs_path(path):
+ return any(fnmatch.fnmatch(path, p) for p in DOCS_PATTERNS)
+
+
+def scope_problems(title, files):
+ if commit_type(title) != "docs":
+ return []
+ bad = [f for f in files if not is_docs_path(f)]
+ if not bad:
+ return []
+ shown = "\n".join(f" - {f}" for f in bad[:20])
+ more = f"\n ... and {len(bad) - 20} more" if len(bad) > 20 else ""
+ return [f"PR title says 'docs' but the diff touches {len(bad)} non-docs file(s) "
+ f"(of {len(files)} changed):\n{shown}{more}\n"
+ "Allowed for docs PRs: *.md, docs/, assets/, PR/issue templates. "
+ "Retitle (feat:/fix:/chore:) or split the non-docs changes into their own PR."]
+
+
+def git(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True, check=True).stdout.splitlines()
+
+
+def stacked_overlap(own_commits, others):
+ """others: list of {number, commits:[oid]}; returns {number: [shared oids]}."""
+ own = set(own_commits)
+ res = {}
+ for o in others:
+ shared = sorted(own & set(o.get("commits", [])))
+ if shared:
+ res[o["number"]] = shared
+ return res
+
+
+def stacked_warnings(base, repo, pr):
+ try:
+ own = git("rev-list", f"{base}..HEAD")
+ raw = subprocess.run(
+ ["gh", "pr", "list", "--repo", repo, "--state", "open", "--limit", "100",
+ "--json", "number,commits"],
+ capture_output=True, text=True, check=True, timeout=60).stdout
+ others = [{"number": p["number"], "commits": [c["oid"] for c in p["commits"]]}
+ for p in json.loads(raw) if str(p["number"]) != str(pr)]
+ except Exception as e: # gh missing, no token, API error: skip gracefully
+ print(f"note: stacked-PR check skipped ({type(e).__name__})")
+ return []
+ return [f"::warning::possible stacked PR: {len(c)} commit(s) of this PR are also in open PR #{n} "
+ f"(e.g. {c[0][:10]}). Target main with only your own commits, or wait for #{n} to merge."
+ for n, c in stacked_overlap(own, others).items()]
+
+
+def main(argv):
+ a = dict(zip(argv[::2], argv[1::2]))
+ title, base = a.get("--title", ""), a.get("--base", "origin/main")
+ files = [f for f in git("diff", "--name-only", f"{base}...HEAD")]
+ probs = scope_problems(title, files)
+ if a.get("--repo") and a.get("--pr"):
+ for w in stacked_warnings(base, a["--repo"], a["--pr"]):
+ print(w)
+ for p in probs:
+ print(f"::error::{p}" if a.get("--gha") else p)
+ print(f"type={commit_type(title)!r} files={len(files)} -> {'FAIL' if probs else 'ok'}")
+ return 1 if probs else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci/skill-budget.json b/scripts/ci/skill-budget.json
new file mode 100644
index 0000000..2490911
--- /dev/null
+++ b/scripts/ci/skill-budget.json
@@ -0,0 +1,6 @@
+{
+ "file": "SKILL.md",
+ "max_words": 4300,
+ "baseline_words": 4102,
+ "note": "main count + ~5%. Raise max_words only deliberately, with justification in the PR."
+}
diff --git a/scripts/ci/skill_budget.py b/scripts/ci/skill_budget.py
new file mode 100644
index 0000000..03291ea
--- /dev/null
+++ b/scripts/ci/skill_budget.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Fail if SKILL.md (always-loaded agent router) exceeds its word budget.
+
+Budget lives in scripts/ci/skill-budget.json. To raise it intentionally, edit
+"max_words" in that file in the same PR and justify the growth in the PR
+description (SKILL.md is loaded into every agent context).
+Usage: skill_budget.py [CONFIG]
+"""
+import json
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def word_count(path):
+ with open(path, encoding="utf-8") as fh:
+ return len(fh.read().split()) # same as `wc -w`
+
+
+def check(config_path):
+ cfg = json.load(open(config_path, encoding="utf-8"))
+ path = cfg["file"] # relative to the repo root (cwd)
+ n = word_count(path)
+ if n > cfg["max_words"]:
+ return [f"{cfg['file']} has {n} words, over the budget of {cfg['max_words']} "
+ f"(+{n - cfg['max_words']}). It is loaded into every agent context: trim it, move detail "
+ f"to docs/, or raise max_words in {os.path.relpath(config_path)} deliberately and justify it in the PR."]
+ print(f"{cfg['file']}: {n} words (budget {cfg['max_words']})")
+ return []
+
+
+if __name__ == "__main__":
+ probs = check(sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "skill-budget.json"))
+ for p in probs:
+ print(p)
+ sys.exit(1 if probs else 0)
diff --git a/scripts/ci/tests/test_ci_scripts.py b/scripts/ci/tests/test_ci_scripts.py
new file mode 100644
index 0000000..71b2dc1
--- /dev/null
+++ b/scripts/ci/tests/test_ci_scripts.py
@@ -0,0 +1,99 @@
+import json
+import os
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+import md_links # noqa: E402
+import md_tables # noqa: E402
+import pr_scope # noqa: E402
+import skill_budget # noqa: E402
+
+GOOD = "| a | b |\n|---|:-:|\n| 1 | 2 |\n"
+
+
+class TableTests(unittest.TestCase):
+ def test_good_table(self):
+ self.assertEqual(md_tables.check_text(GOOD), [])
+
+ def test_double_pipe_row(self):
+ self.assertTrue(md_tables.check_text("| a | b |\n|---|---|\n|| 1 | 2 |\n"))
+
+ def test_column_mismatch(self):
+ self.assertTrue(md_tables.check_text("| a | b | c |\n|---|---|\n| 1 | 2 | 3 |\n"))
+
+ def test_empty_delimiter_cell(self):
+ self.assertTrue(md_tables.check_text("| a | b |\n|---| |\n| 1 | 2 |\n"))
+
+ def test_fenced_ignored(self):
+ self.assertEqual(md_tables.check_text("```\n|| x\n```\n"), [])
+
+
+class LinkTests(unittest.TestCase):
+ def setUp(self):
+ md_links._anchor_cache.clear()
+ self.d = tempfile.TemporaryDirectory()
+ self.addCleanup(self.d.cleanup)
+
+ def write(self, name, text):
+ p = os.path.join(self.d.name, name)
+ open(p, "w").write(text)
+ return p
+
+ def test_slug(self):
+ self.assertEqual(md_links.slugify("Hello, World! `x` (v2)"), "hello-world-x-v2")
+
+ def test_ok_and_duplicate_heading(self):
+ p = self.write("a.md", "# A\n## Same\n## Same\n[x](#a) [y](#same-1) [z](b.md)\n")
+ self.write("b.md", "x")
+ self.assertEqual(md_links.check_text(open(p).read(), p), [])
+
+ def test_broken(self):
+ p = self.write("a.md", "# A\n[x](#nope) [y](missing.md) [z](https://e.com/x) `[c](zzz.md)`\n")
+ self.assertEqual(len(md_links.check_text(open(p).read(), p)), 2)
+
+ def test_cross_file_anchor(self):
+ self.write("b.md", "# Bee\n")
+ p = self.write("a.md", "[ok](b.md#bee) [bad](b.md#ant)\n")
+ self.assertEqual(len(md_links.check_text(open(p).read(), p)), 1)
+
+
+class BudgetTests(unittest.TestCase):
+ def test_over_and_under(self):
+ with tempfile.TemporaryDirectory() as d:
+ cwd = os.getcwd()
+ os.chdir(d)
+ try:
+ open("S.md", "w").write("one two three")
+ cfg = os.path.join(d, "c.json")
+ json.dump({"file": "S.md", "max_words": 3}, open(cfg, "w"))
+ self.assertEqual(skill_budget.check(cfg), [])
+ json.dump({"file": "S.md", "max_words": 2}, open(cfg, "w"))
+ self.assertEqual(len(skill_budget.check(cfg)), 1)
+ finally:
+ os.chdir(cwd)
+
+
+class ScopeTests(unittest.TestCase):
+ def test_type(self):
+ self.assertEqual(pr_scope.commit_type("docs(readme): x"), "docs")
+ self.assertEqual(pr_scope.commit_type("feat!: x"), "feat")
+ self.assertIsNone(pr_scope.commit_type("Update stuff"))
+
+ def test_docs_pr_with_code_fails(self):
+ self.assertTrue(pr_scope.scope_problems("docs: add sponsor", ["README.md", "forge/x.py"]))
+
+ def test_docs_pr_clean(self):
+ self.assertEqual(pr_scope.scope_problems("docs(x): y", ["README.md", "docs/a/b.md", "assets/i.png"]), [])
+
+ def test_non_docs_title_unrestricted(self):
+ self.assertEqual(pr_scope.scope_problems("feat: y", ["forge/x.py"]), [])
+
+ def test_stacked_overlap(self):
+ r = pr_scope.stacked_overlap(["a", "b"], [{"number": 5, "commits": ["b", "z"]}, {"number": 6, "commits": ["q"]}])
+ self.assertEqual(r, {5: ["b"]})
+
+
+if __name__ == "__main__":
+ unittest.main()