diff --git a/.github/scripts/validate_community_preset.py b/.github/scripts/validate_community_preset.py index ebc64a6cfd..b5ce4344e4 100644 --- a/.github/scripts/validate_community_preset.py +++ b/.github/scripts/validate_community_preset.py @@ -335,23 +335,10 @@ def submission(args: argparse.Namespace) -> None: raise Blocked("original catalog entry is not an object") if previous is not None and not isinstance(previous.get("created_at"), str): raise Blocked("original catalog entry has no created_at to preserve") - original_rows = documentation_rows( - read_text(args.docs, "original documentation", Blocked), Blocked - ) - expected_row = documentation_row(expected) - previous_row = None - if previous is not None: - previous_row = existing_documentation_row(original_rows, previous) snapshot = { "expected": expected, "created_at": previous.get("created_at") if previous else None, "expected_timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT00:00:00Z"), - "documentation": { - "expected_row_count": original_rows.count(expected_row), - "previous_row": previous_row, - "previous_row_count": original_rows.count(previous_row) - if previous_row is not None else 0, - }, } try: args.snapshot.write_text(json.dumps(snapshot), encoding="utf-8") @@ -360,85 +347,6 @@ def submission(args: argparse.Namespace) -> None: print("PASSED: published preset.yml, release tag, README, and issue fields agree") -def documentation_row(entry: dict) -> str: - def cell(value: str) -> str: - return value.replace("\\", r"\\").replace("|", r"\|").replace("\n", " ") - - provided = entry["provides"] - quantities = [ - f"{count} {name[:-1] if count == 1 else name}" - for name, count in provided.items() if count - ] - dependencies = entry["requires"].get("extensions", []) - requires = ", ".join(f"{name} extension" for name in dependencies) or "—" - repo = entry["repository"].rstrip("/").rsplit("/", 1)[-1] - return ( - f"| {cell(entry['name'])} | {cell(entry['description'])} | " - f"{', '.join(quantities)} | {requires} | " - f"[{repo}]({entry['repository']}) |" - ) - - -def markdown_table_cells(row: str) -> list[str]: - cells = [] - cell = [] - escaped = False - for character in row: - if escaped: - if character in ("\\", "|"): - cell.append(character) - else: - cell.extend(("\\", character)) - escaped = False - elif character == "\\": - escaped = True - elif character == "|": - cells.append("".join(cell).strip()) - cell = [] - else: - cell.append(character) - if escaped: - cell.append("\\") - cells.append("".join(cell).strip()) - return cells - - -def documentation_rows(text: str, error_type: type[Exception]) -> list[str]: - lines = text.splitlines() - try: - start = next(i for i, line in enumerate(lines) if line.startswith("| Preset |")) - except StopIteration as exc: - raise error_type("documentation has no Community Presets table") from exc - rows = [] - for line in lines[start + 2:]: - if not line.startswith("|"): - break - rows.append(line.strip()) - return rows - - -def existing_documentation_row(rows: list[str], entry: dict) -> str: - name = entry.get("name") - repository = entry.get("repository") - if not isinstance(name, str) or not isinstance(repository, str): - raise Blocked("original catalog entry lacks documentation row identity") - matches = [] - for row in rows: - cells = markdown_table_cells(row) - if len(cells) < 3 or cells[1] != name: - continue - url_cell = cells[-2] if cells[-1] == "" else cells[-1] - link = re.fullmatch(r"\[[^\]]*\]\(([^)]+)\)", url_cell) - if link and link[1].rstrip("/") == repository.rstrip("/"): - matches.append(row) - if len(matches) != 1: - raise Blocked( - "original documentation must contain exactly one row matching the " - f"catalog name and repository for {name!r}; found {len(matches)}" - ) - return matches[0] - - def generated(args: argparse.Namespace) -> None: snapshot = read_json(args.snapshot, "verifier snapshot", Blocked) expected = snapshot.get("expected") @@ -469,46 +377,13 @@ def generated(args: argparse.Namespace) -> None: raise GeneratedError("catalog entry updated_at does not match the expected UTC date") if catalog.get("updated_at") != expected_timestamp: raise GeneratedError("catalog top-level updated_at does not match the expected UTC date") - documentation = snapshot.get("documentation") - if not isinstance(documentation, dict): - raise Blocked("verifier snapshot lacks original documentation state") - expected_row_count = documentation.get("expected_row_count") - previous_row = documentation.get("previous_row") - previous_row_count = documentation.get("previous_row_count") - if ( - not isinstance(expected_row_count, int) - or isinstance(expected_row_count, bool) - or expected_row_count < 0 - or previous_row is not None and not isinstance(previous_row, str) - or not isinstance(previous_row_count, int) - or isinstance(previous_row_count, bool) - or previous_row_count < 0 - ): - raise Blocked("verifier snapshot has invalid original documentation state") - rows = documentation_rows( - read_text(args.docs, "generated documentation", GeneratedError), - GeneratedError, - ) - names = [markdown_table_cells(row)[1] for row in rows] - if names != sorted(names, key=str.casefold): - raise GeneratedError("documentation preset names are not in alphabetical order") - expected_row = documentation_row(expected) - expected_generated_count = expected_row_count + ( - 0 if previous_row == expected_row else 1 - ) - if rows.count(expected_row) != expected_generated_count: - raise GeneratedError(f"documentation row does not match validated values: {expected_row}") - if previous_row is not None and previous_row != expected_row: - expected_previous_count = max(0, previous_row_count - 1) - if rows.count(previous_row) != expected_previous_count: - raise GeneratedError("previous documentation row was not replaced") - print("PASSED: generated catalog and documentation match validated submission") + print("PASSED: generated catalog matches validated submission") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("phase", choices=("submission", "generated")) - for name in ("issue", "archive", "readme", "catalog", "docs", "snapshot"): + for name in ("issue", "archive", "readme", "catalog", "snapshot"): parser.add_argument(f"--{name}", required=True, type=Path) args = parser.parse_args() try: diff --git a/.github/workflows/add-community-preset.lock.yml b/.github/workflows/add-community-preset.lock.yml index f86ecda27e..9953691852 100644 --- a/.github/workflows/add-community-preset.lock.yml +++ b/.github/workflows/add-community-preset.lock.yml @@ -1,4 +1,4 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"b4af3f68becf88fb1763c4da846706cbedde768068083c3ad5b8dc5b7b1d0958","body_hash":"3b13d3a5ecb2aa18e12166d1d774ca39cd35e39ea24d65fa735afbf3430f5670","compiler_version":"v0.88.7","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.80"}} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"564efd2f35a62e6eefd16aa78978c1c65f7a5d503d98412f61789a19138d65c9","body_hash":"853306b78d6cb2990eb3645fbfc04aa5eef71e54fb1514dcac2cb42d7cab36f8","compiler_version":"v0.88.7","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.80"}} # gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"820762786026740c76f36085b0efc47a31fe5020","version":"v7.0.0"},{"repo":"actions/setup-python","sha":"5fda3b95a4ea91299a34e894583c3862153e4b97","version":"v7.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"5e508589e03a7757a7e05b26e834292f5445bfb6","version":"v0.88.7"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.14","digest":"sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.14@sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.14","digest":"sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.14@sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.14","digest":"sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.14@sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.18","digest":"sha256:85b940556a8faa4e1fdbef124bfd75f2c4ebd855a10b88a1c3b6f3e97f6f1a53","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.18@sha256:85b940556a8faa4e1fdbef124bfd75f2c4ebd855a10b88a1c3b6f3e97f6f1a53"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:0daa8971fa4732b647150cb6524a6b0804b68d5d24f6f58b5dd1af23bd63fb23","pinned_image":"ghcr.io/github/gh-aw-node@sha256:0daa8971fa4732b647150cb6524a6b0804b68d5d24f6f58b5dd1af23bd63fb23"},{"image":"ghcr.io/github/github-mcp-server:v1.11.0","digest":"sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699","pinned_image":"ghcr.io/github/github-mcp-server:v1.11.0@sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699"}],"mcp_servers":[{"name":"github","tools":["get_commit","get_file_contents","get_latest_release","get_release_by_tag","get_tag","issue_read","list_branches","list_commits","list_issue_types","list_issues","list_releases","list_starred_repositories","list_tags","search_code","search_issues","search_repositories"]},{"name":"safeoutputs","tools":["add_comment","add_labels","create_pull_request","missing_data","missing_tool","noop","remove_labels"]}]} # This file was automatically generated by gh-aw (v0.88.7). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # @@ -583,7 +583,7 @@ jobs: env: GH_AW_FILE_ROOT: "${{ runner.temp }}/gh-aw" GH_AW_FILE_CONFIG: "{\"files\":[{\"path\":\"safeoutputs/config.json\",\"content_env\":\"GH_AW_SAFE_OUTPUTS_CONFIG\"}]}" - GH_AW_SAFE_OUTPUTS_CONFIG: "{\"add_comment\":{\"max\":2},\"add_labels\":{\"allowed\":[\"preset-submission\",\"validation-passed\",\"validation-failed\",\"needs-info\"],\"issue_intent\":false,\"max\":3},\"create_pull_request\":{\"allowed_files\":[\"presets/catalog.community.json\",\"docs/community/presets.md\"],\"draft\":true,\"labels\":[\"preset-submission\",\"automated\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"CONTRIBUTING.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\"],\"protected_files_policy\":\"blocked\",\"title_prefix\":\"[preset] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"remove_labels\":{\"allowed\":[\"validation-passed\",\"validation-failed\"]},\"report_incomplete\":{}}" + GH_AW_SAFE_OUTPUTS_CONFIG: "{\"add_comment\":{\"max\":2},\"add_labels\":{\"allowed\":[\"preset-submission\",\"validation-passed\",\"validation-failed\",\"needs-info\"],\"issue_intent\":false,\"max\":3},\"create_pull_request\":{\"allowed_files\":[\"presets/catalog.community.json\"],\"draft\":true,\"labels\":[\"preset-submission\",\"automated\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"CONTRIBUTING.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\"],\"protected_files_policy\":\"blocked\",\"title_prefix\":\"[preset] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"remove_labels\":{\"allowed\":[\"validation-passed\",\"validation-failed\"]},\"report_incomplete\":{}}" with: script: | const path = require('path'); @@ -2004,7 +2004,7 @@ jobs: GH_AW_ALLOWED_DOMAINS: "api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,github.com,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,ppa.launchpad.net,raw.githubusercontent.com,release-assets.githubusercontent.com,s.symcb.com,s.symcd.com,security.ubuntu.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":2},\"add_labels\":{\"allowed\":[\"preset-submission\",\"validation-passed\",\"validation-failed\",\"needs-info\"],\"issue_intent\":false,\"max\":3},\"create_pull_request\":{\"allowed_files\":[\"presets/catalog.community.json\",\"docs/community/presets.md\"],\"draft\":true,\"labels\":[\"preset-submission\",\"automated\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"CONTRIBUTING.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\"],\"protected_files_policy\":\"blocked\",\"title_prefix\":\"[preset] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"remove_labels\":{\"allowed\":[\"validation-passed\",\"validation-failed\"]},\"report_incomplete\":{}}" + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":2},\"add_labels\":{\"allowed\":[\"preset-submission\",\"validation-passed\",\"validation-failed\",\"needs-info\"],\"issue_intent\":false,\"max\":3},\"create_pull_request\":{\"allowed_files\":[\"presets/catalog.community.json\"],\"draft\":true,\"labels\":[\"preset-submission\",\"automated\"],\"max\":1,\"max_patch_files\":100,\"max_patch_size\":4096,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"CONTRIBUTING.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\"],\"protected_files_policy\":\"blocked\",\"title_prefix\":\"[preset] \"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"remove_labels\":{\"allowed\":[\"validation-passed\",\"validation-failed\"]},\"report_incomplete\":{}}" GH_AW_CI_TRIGGER_TOKEN: ${{ secrets.GH_AW_CI_TRIGGER_TOKEN }} with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/add-community-preset.md b/.github/workflows/add-community-preset.md index d6bdd63c1f..4762c630bc 100644 --- a/.github/workflows/add-community-preset.md +++ b/.github/workflows/add-community-preset.md @@ -61,7 +61,6 @@ safe-outputs: max: 1 allowed-files: - presets/catalog.community.json - - docs/community/presets.md protected-files: policy: blocked exclude: @@ -307,7 +306,7 @@ Retain multiline list values as strings. Do not interpolate issue or README text into shell commands. Run this fixed command unchanged: ```bash -python3 .github/scripts/validate_community_preset.py submission --issue /tmp/gh-aw/preset-submission.json --archive /tmp/gh-aw/community-archive.zip --readme /tmp/gh-aw/preset-readme.md --catalog presets/catalog.community.json --docs docs/community/presets.md --snapshot /tmp/gh-aw/preset-validation.json +python3 .github/scripts/validate_community_preset.py submission --issue /tmp/gh-aw/preset-submission.json --archive /tmp/gh-aw/community-archive.zip --readme /tmp/gh-aw/preset-readme.md --catalog presets/catalog.community.json --snapshot /tmp/gh-aw/preset-validation.json ``` The verifier reads `preset.yml` from the downloaded ZIP, including preset-scoped @@ -357,7 +356,7 @@ If there are no environment blockers and every required check completed and pass 1. Remove any stale `validation-passed` and `validation-failed` labels from earlier runs. 2. Continue to Step 3. **Do not add `validation-passed` yet**: the generated - catalog and documentation must pass Step 5's verifier before success is recorded. + catalog must pass Step 5's verifier before success is recorded. ## Step 3 — Determine Add vs Update @@ -445,46 +444,25 @@ verifier snapshot's UTC date in ISO 8601 format. The generated-file verifier in Step 5 parses and checks the JSON. Fix any catalog error it reports and rerun it before continuing. -## Step 5 — Update `docs/community/presets.md` +## Step 5 — Verify the generated catalog -Edit `docs/community/presets.md` to add or update a row in the Community -Presets table. - -### For a new preset - -Insert a new row in **alphabetical order by preset name**: - -``` -| | | templates, commands | | []() | -``` - -For the Requires column: -- Use `—` if no extensions are required -- List required extension IDs if any (e.g., `aide extension`), comma-separated -- Omit zero-count kinds from Provides and use singular nouns for counts of one - -If the preset provides scripts, include them: ` templates, commands, scripts` - -### For an update - -Find the existing row and update any changed fields in-place. - -### Verify the generated files +The documentation build generates the alphabetical preset directory and detail +pages directly from the catalog. Do not edit `docs/community/presets.md` or +generated documentation as part of a submission. Before labeling success or requesting a PR, run this fixed command unchanged: ```bash -python3 .github/scripts/validate_community_preset.py generated --issue /tmp/gh-aw/preset-submission.json --archive /tmp/gh-aw/community-archive.zip --readme /tmp/gh-aw/preset-readme.md --catalog presets/catalog.community.json --docs docs/community/presets.md --snapshot /tmp/gh-aw/preset-validation.json +python3 .github/scripts/validate_community_preset.py generated --issue /tmp/gh-aw/preset-submission.json --archive /tmp/gh-aw/community-archive.zip --readme /tmp/gh-aw/preset-readme.md --catalog presets/catalog.community.json --snapshot /tmp/gh-aw/preset-validation.json ``` The verifier checks JSON parsing, the validated catalog metadata (including `homepage` set to the submitted repository URL) and digest, the top-level and entry `updated_at` timestamps against the recorded UTC date (and `created_at` for new entries), -alphabetical ID order, the documentation row's name, purpose, counts, extension -requirements and repository link, alphabetical name order, and preservation of -`created_at` on updates. Exit 3 (`REPAIR`) is an agent-generated catalog or -documentation error, **not** a submitter defect: fix the files and re-run this +alphabetical ID order, and preservation of `created_at` on updates. +Exit 3 (`REPAIR`) is an agent-generated catalog error, **not** a submitter +defect: fix the catalog and re-run this command until it exits 0. Do not label `validation-failed` for an error in generated files. Exit 2 (`BLOCKED`) means an input or tool is unavailable: report the exact error and workflow run link to the maintainer, remove @@ -500,7 +478,7 @@ branch naming convention: This repository-owned gh-aw maintenance workflow does not perform the contributor open-PR count check or request confirmation. After successful validation and -allowed catalog/docs file updates, emit the configured draft `create_pull_request` +allowed catalog updates, emit the configured draft `create_pull_request` safe output regardless of the submitter's or filing account's open PR count. - **New preset:** `add--preset` @@ -514,7 +492,6 @@ Add preset to community catalog Add preset submitted by @ to: - presets/catalog.community.json (alphabetical order) -- docs/community/presets.md community presets table Closes # ``` @@ -525,7 +502,6 @@ Update preset to v Update preset submitted by @: - presets/catalog.community.json (version, download_url, etc.) -- docs/community/presets.md community presets table Closes # ``` @@ -540,8 +516,8 @@ Include: ## Important Rules -- **Alphabetical order matters** — entries must be sorted by ID in the JSON and - by name in the docs table +- **Alphabetical order matters** — entries must be sorted by ID in the JSON; + documentation display order is generated automatically - **Always validate JSON** after editing — a trailing comma or missing brace will break the catalog - **Use `Closes` not `Fixes`** — `Closes #N` is the correct keyword for @@ -549,4 +525,3 @@ Include: - **Preserve `created_at` on updates** — keep the original value; only update `updated_at` - **Do not modify any other files** — only `presets/catalog.community.json` - and `docs/community/presets.md` diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e03f6443ec..de3025a3e7 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -7,6 +7,8 @@ on: branches: ["main"] paths: - 'docs/**' + - 'presets/catalog.community.json' + - '.github/workflows/docs.yml' # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -42,6 +44,11 @@ jobs: - name: Setup DocFX run: dotnet tool install -g docfx + - name: Generate community preset documentation + run: python3 docs/generate_presets.py --fetch-stars + env: + GH_TOKEN: ${{ github.token }} + - name: Build with DocFX run: | cd docs diff --git a/docs/.gitignore b/docs/.gitignore index 614670d9f1..c5abf40617 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -2,6 +2,8 @@ _site/ obj/ .docfx/ +_generated/ +community/presets/ # Temporary files *.tmp diff --git a/docs/README.md b/docs/README.md index 055c5e284b..467783a2a7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,14 +12,34 @@ To build the documentation locally: dotnet tool install -g docfx ``` -2. Build the documentation: +2. Generate the community preset directory from the local catalog: + + ```bash + python3 docs/generate_presets.py --fetch-stars + ``` + +3. Build the documentation: ```bash cd docs docfx docfx.json --serve ``` -3. Open your browser to `http://localhost:8080` to view the documentation. +4. Open your browser to `http://localhost:8080` to view the documentation. + +Run the generator again after editing `presets/catalog.community.json`. +It creates the ignored `_generated/preset-directory.md` include and +`community/presets/*.md` detail pages, removing pages for deleted entries. +Do not edit these generated files. The directory uses only catalog metadata: +building it does not fetch or execute third-party preset content. With +`--fetch-stars`, it reads star counts from the GitHub API once per repository. +Set `GH_TOKEN` or `GITHUB_TOKEN` for authenticated API limits; the deployment +workflow uses its repository token. Counts reflect the last build, +and shared repositories have the same count. Failed lookups produce warnings +and show "Stars unavailable", never an invented zero. Omit `--fetch-stars` +for an offline build with unavailable counts. Its search, tag, +and sort controls enhance a complete static listing, which remains readable +without JavaScript. ## Structure @@ -106,4 +126,9 @@ the site homepage. Process command references and authentication remain under ## Deployment -Documentation is automatically built and deployed to GitHub Pages when changes are pushed to the `main` branch. The workflow is defined in `.github/workflows/docs.yml`. +Documentation, community preset catalog, and docs workflow changes on the +upstream `main` branch trigger the normal GitHub Pages deployment. Each build +generates the preset directory and detail pages and refreshes repository star +counts before running DocFX. Manual runs use the same path; there is no separate +weekly schedule. The workflow is defined in `.github/workflows/docs.yml` and +runs only in the upstream repository. diff --git a/docs/assets/preset-catalog.css b/docs/assets/preset-catalog.css new file mode 100644 index 0000000000..b2e54f26f0 --- /dev/null +++ b/docs/assets/preset-catalog.css @@ -0,0 +1,175 @@ +.preset-catalog, +.preset-detail { + --preset-muted: var(--bs-secondary-color, #59636e); + --preset-border: var(--bs-border-color, #d1d9e0); +} + +.preset-controls { + display: grid; + grid-template-columns: minmax(12rem, 2fr) minmax(8rem, 1fr) minmax(9rem, 1fr) auto; + align-items: end; + gap: 1rem; + margin: 2rem 0 1rem; +} + +.preset-catalog [hidden] { + display: none !important; +} + +.preset-controls label { + display: block; + margin-bottom: 0.4rem; + font-weight: 600; +} + +.preset-controls input, +.preset-controls select, +.preset-reset { + min-height: 2.75rem; + width: 100%; + padding: 0.5rem 0.75rem; + border: 1px solid var(--preset-border); + border-radius: 0.375rem; + color: var(--bs-body-color, #1f2328); + background: var(--bs-body-bg, #fff); + font: inherit; +} + +.preset-controls input::placeholder { + color: var(--preset-muted); + opacity: 1; +} + +.preset-reset:hover { + background: var(--bs-tertiary-bg, #f6f8fa); +} + +.preset-controls :focus-visible, +.preset-catalog a:focus-visible, +.preset-detail a:focus-visible { + outline: 2px solid var(--bs-link-color, #0969da); + outline-offset: 3px; +} + +.preset-result-count, +.preset-entry-meta { + color: var(--preset-muted); + font-size: 0.9rem; +} + +.preset-results { + list-style: none; + padding: 0; + margin: 0 0 2rem; +} + +.preset-entry { + padding: 1.5rem 0; + border-top: 1px solid var(--preset-border); +} + +.preset-entry-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 1rem; +} + +.preset-entry-heading h2 { + margin: 0 0 0.5rem; + border: 0; + font-size: 1.2rem; +} + +.preset-entry p { + margin: 0 0 0.75rem; +} + +.preset-version { + color: var(--preset-muted); + font-size: 0.85rem; + white-space: nowrap; +} + +.preset-entry-stats { + display: flex; + align-items: baseline; + flex-shrink: 0; + gap: 1rem; +} + +.preset-stars { + font-size: 0.85rem; + white-space: nowrap; +} + +.preset-entry-stats span.preset-stars { + color: var(--preset-muted); +} + +.preset-tags { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.preset-tag { + padding: 0.15rem 0.55rem; + border: 1px solid var(--preset-border); + border-radius: 1rem; + font-size: 0.8rem; +} + +.preset-metadata { + display: grid; + grid-template-columns: minmax(9rem, 1fr) minmax(0, 3fr); + gap: 0.75rem 1.5rem; + margin: 1.5rem 0 2rem; +} + +.preset-metadata dt, +.preset-metadata dd { + margin: 0; +} + +.preset-detail, +.preset-entry { + overflow-wrap: anywhere; +} + +.preset-source-links { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.5rem; +} + +@media (max-width: 900px) { + .preset-controls { + grid-template-columns: 1fr 1fr; + } + + .preset-search { + grid-column: 1 / -1; + } +} + +@media (max-width: 480px) { + .preset-controls, + .preset-metadata { + grid-template-columns: 1fr; + } + + .preset-metadata { + gap: 0.25rem; + } + + .preset-metadata dd { + margin-bottom: 0.75rem; + } + + .preset-entry-heading { + flex-direction: column; + gap: 0; + margin-bottom: 0.5rem; + } +} diff --git a/docs/assets/preset-catalog.js b/docs/assets/preset-catalog.js new file mode 100644 index 0000000000..855ff8e9e6 --- /dev/null +++ b/docs/assets/preset-catalog.js @@ -0,0 +1,60 @@ +(() => { + const catalog = document.querySelector("[data-preset-catalog]"); + if (!catalog) return; + + const form = catalog.querySelector("[data-preset-controls]"); + const query = form.elements.namedItem("q"); + const tag = form.elements.namedItem("tag"); + const sort = form.elements.namedItem("sort"); + const list = catalog.querySelector(".preset-results"); + const entries = Array.from(list.children); + const status = catalog.querySelector("[data-preset-status]"); + const empty = catalog.querySelector("[data-preset-empty]"); + const searchable = entries.map((entry) => ({ + entry, + text: entry.dataset.presetSearch.toLocaleLowerCase(), + tags: JSON.parse(entry.dataset.presetTags), + })); + const params = new URLSearchParams(window.location.search); + query.value = params.get("q") || ""; + tag.value = params.get("tag") || ""; + if (!tag.value) tag.value = ""; + sort.value = params.get("sort") === "za" ? "za" : "az"; + + function update() { + const words = query.value.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean); + let visible = 0; + for (const item of searchable) { + const matches = words.every((word) => item.text.includes(word)) + && (!tag.value || item.tags.includes(tag.value)); + item.entry.hidden = !matches; + if (matches) visible += 1; + } + const ordered = sort.value === "za" ? [...entries].reverse() : entries; + for (const entry of ordered) list.append(entry); + status.textContent = `${visible} of ${entries.length} presets`; + empty.hidden = visible !== 0; + + const next = new URL(window.location.href); + for (const [key, value] of [["q", query.value], ["tag", tag.value], ["sort", sort.value === "za" ? "za" : ""]]) { + if (value) next.searchParams.set(key, value); + else next.searchParams.delete(key); + } + window.history.replaceState(null, "", next); + } + + form.addEventListener("input", update); + form.addEventListener("change", update); + form.addEventListener("submit", (event) => { + event.preventDefault(); + update(); + }); + form.addEventListener("reset", () => { + query.value = ""; + tag.value = ""; + sort.value = "az"; + update(); + }); + update(); + form.hidden = false; +})(); diff --git a/docs/community/presets.md b/docs/community/presets.md index 099094f38f..8214375b27 100644 --- a/docs/community/presets.md +++ b/docs/community/presets.md @@ -1,54 +1,22 @@ +--- +_disableAffix: true +--- + # Community Presets +Find presets that adapt Spec Kit's templates, commands, and terminology to your process. Search by purpose, author, or tag, then open a preset to explore its requirements and release details. + > [!NOTE] > Community presets are independently created and maintained by their respective authors. Maintainers only verify that catalog entries are complete and correctly formatted — they do **not review, audit, endorse, or support the preset code itself**. Review preset source code before installation and use at your own discretion. -The following community-contributed presets customize how Spec Kit behaves — overriding templates, commands, and terminology without changing any tooling. Presets are available in [`catalog.community.json`](https://github.com/github/spec-kit/blob/main/presets/catalog.community.json): - -| Preset | Purpose | Provides | Requires | URL | -|--------|---------|----------|----------|-----| -| A11Y Governance | Adds accessibility (WCAG 2.2 AA), accessible text and JSON status parity, bilingual DE/EN delivery, CEFR-B2 readability, inclusive-content governance, didactic inline-code-comment review, and audit-ready Spec-Kit run evidence to Spec Kit. | 11 templates, 3 commands | — | [spec-kit-preset-a11y-governance](https://github.com/hindermath/spec-kit-preset-a11y-governance) | -| Agent Parity Governance | Adds shared-guidance and generated-command parity, fleet-completion evidence, secret-free runner metadata, and traceable Spec Kit evidence across declared AI-agent surfaces. | 7 templates, 3 commands | — | [spec-kit-preset-agent-parity-governance](https://github.com/hindermath/spec-kit-preset-agent-parity-governance) | -| Agentstandards Task Gate | Hard-blocks Spec Kit task generation until the persisted multi-vendor architecture gate is READY. | 1 command | agentstandards extension | [agentstandards](https://github.com/bbjwz/agentstandards) | -| AIDE In-Place Migration | Adapts the AIDE extension workflow for in-place technology migrations (X → Y pattern) — adds migration objectives, verification gates, knowledge documents, and behavioral equivalence criteria | 2 templates, 8 commands | AIDE extension | [spec-kit-presets](https://github.com/mnriem/spec-kit-presets) | -| Architecture Governance | Adds secure architecture, STRIDE/CAPEC threat models, arc42, S-ADRs, Zero Trust, SAMM, C3A/C5 cloud assurance, and audit-ready evidence to Spec Kit. | 15 templates, 3 commands | — | [spec-kit-preset-architecture-governance](https://github.com/hindermath/spec-kit-preset-architecture-governance) | -| Autonomous Run Governance | Adds permission-bounded autonomous delivery and an optional policy-driven intake-review gate before feature creation. | 16 templates, 5 commands, 11 scripts | — | [spec-kit-preset-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-autonomous-run-governance) | -| Canon Core | Adapts original Spec Kit workflow to work together with Canon extension | 2 templates, 8 commands | — | [spec-kit-canon](https://github.com/maximiliamus/spec-kit-canon) | -| Claude AskUserQuestion | Upgrades `/speckit.clarify` and `/speckit.checklist` on Claude Code from Markdown-table prompts to the native AskUserQuestion picker, with a recommended option and reasoning on every question | 2 commands | — | [spec-kit-preset-claude-ask-questions](https://github.com/0xrafasec/spec-kit-preset-claude-ask-questions) | -| Closed Vocabulary Check | Adds a pass to /speckit.analyze that flags closed sets of values enumerated more than once with different members, and reports its own coverage. | 1 command | — | [spec-kit-preset-closed-vocabulary](https://github.com/yunusdim/spec-kit-preset-closed-vocabulary) | -| Command Density | Compacts the nine core Spec Kit command prompts while preserving scripts, handoffs, placeholders, hook output blocks, and rule structure | 9 commands | — | [spec-kit-preset-command-density](https://github.com/Xopoko/spec-kit-preset-command-density) | -| Cross-Platform Governance | Adds Bash/PowerShell parity, read-only checks, scoped native-override review, Unix man-pages, bilingual help, Verb-Noun discipline, and traceable Spec Kit evidence to scripting projects. | 9 templates, 3 commands | — | [spec-kit-preset-cross-platform-governance](https://github.com/hindermath/spec-kit-preset-cross-platform-governance) | -| Database Standards | Database conventions for spec-driven work: naming, data-model design, constraints, data protection, performance, query safety, a schema-review checklist, and engine-specific references. ORM-agnostic. | 4 templates, 1 command | — | [spec-kit-preset-db-standards](https://github.com/gdakuzak/spec-kit-preset-db-standards) | -| Explicit Task Dependencies | Adds explicit `(depends on T###)` dependency declarations and an Execution Wave DAG to tasks.md for parallel scheduling | 1 template, 1 command | — | [spec-kit-preset-explicit-task-dependencies](https://github.com/Quratulain-bilal/spec-kit-preset-explicit-task-dependencies) | -| Fiction Book Writing | It adapts the Spec-Driven Development workflow for storytelling to create books or audiobooks (with annotations) in 12 languages: features become story elements, specs become story briefs, plans become story structures, and tasks become scene-by-scene writing tasks. Supports single and multi-POV, all major plot structure frameworks, and two style modes: an author voice sample or humanized AI prose principles. Supports interactive elements like brainstorming, interview, roleplay, and extras like statistics, cover builder, illustration builder, and bio command. Export with templates for KDP, D2D, etc. | 26 templates, 34 commands, 2 scripts | — | [speckit-preset-fiction-book-writing](https://github.com/adaumann/speckit-preset-fiction-book-writing) | -| Game Narrative Writing | Preset for game narrative design and interactive storytelling. It adapts the Spec-Driven Development workflow for game narratives: features become story mechanics, specs become narrative briefs, plans become story maps, and tasks become dialogue and scene-writing tasks. Supports branching narratives, player agency systems, state machines, and interactive dialogue trees. | 37 templates, 34 commands, 5 scripts | — | [speckit-preset-game-narrative-writing](https://github.com/adaumann/speckit-preset-game-narrative-writing) | -| Intake Authoring Governance | Governs traceable intake CRUD, language-aware requirements collections, bounded public HTTPS sources, and explicitly approved single or series authoring. | 13 templates, 5 commands, 9 scripts | — | [spec-kit-preset-intake-authoring-governance](https://github.com/hindermath/spec-kit-preset-intake-authoring-governance) | -| Intake Review Governance | Reviews single, series, campaign, and language-aware requirements collections before Spec Kit execution. | 9 templates, 3 commands, 5 scripts | — | [spec-kit-preset-intake-review-governance](https://github.com/hindermath/spec-kit-preset-intake-review-governance) | -| Intake Sequencing Governance | Manages language-aware intake-series order, typed dependencies, lifecycle, and authority-neutral next-candidate selection. | 12 templates, 6 commands, 8 scripts | — | [spec-kit-preset-intake-sequencing-governance](https://github.com/hindermath/spec-kit-preset-intake-sequencing-governance) | -| Inventory Alignment | Classifies each requirement against a read-only inventory of live IDs before writing, so reworded requirements are updated instead of duplicated. | 1 template, 2 commands | speckit-inventory extension | [spec-kit-inventory-alignment](https://github.com/Yash-Chindam/spec-kit-inventory-alignment) | -| iSAQB Architecture Governance | Adds iSAQB/CPSA-F and arc42 architecture governance with Spec-Kit evidence for goals, views, quality scenarios, ADRs, risks, and technical debt. | 14 templates, 3 commands | — | [spec-kit-preset-isaqb-architecture-governance](https://github.com/hindermath/spec-kit-preset-isaqb-architecture-governance) | -| Jira Issue Tracking | Overrides `speckit.taskstoissues` to create Jira epics, stories, and tasks instead of GitHub Issues via Atlassian MCP tools | 1 command | — | [spec-kit-preset-jira](https://github.com/luno/spec-kit-preset-jira) | -| Model Driven Engineering | Focuses on streamlined commands, app repository support, cross-spec support, and capability-aware project memory for model-driven engineering workflows | 6 templates, 11 commands | MDE extension | [spec-kit-preset-mde](https://github.com/AI-MDE/spec-kit-preset-mde) | -| Model Routing Governance | Discovers harness-local models and maps provider-neutral Spec Kit roles to validated local runner profiles without storing credentials or machine-specific availability in Git. | 4 templates, 2 commands, 6 scripts | — | [spec-kit-preset-model-routing-governance](https://github.com/hindermath/spec-kit-preset-model-routing-governance) | -| Multi-Repo Branching | Coordinates feature branch creation across multiple git repositories (independent repos and submodules) during plan and tasks phases | 2 commands | — | [spec-kit-preset-multi-repo-branching](https://github.com/sakitA/spec-kit-preset-multi-repo-branching) | -| NIEM Information Exchanges | Adds evidence-based NIEM exchange modeling to the core, assess, and bugfix processes while preserving their commands, artifacts, and scope. | 7 templates, 18 commands | assess extension, bug extension | [spec-kit-presets](https://github.com/mnriem/spec-kit-presets) | -| OKR Bet Spec Section | Adds a Hypothesis & Bet section (with the bet's verification contract) to every spec and teaches /speckit.specify to fill it from an okr:/H-n bet. Companion of the okr extension. | 1 template, 1 command | — | [spec-kit-okr](https://github.com/juanl/spec-kit-okr) | -| OpenProject Work Packages | Overrides speckit.taskstoissues to create OpenProject work packages (phases, tasks, sub-tasks, relations) via an OpenProject MCP server instead of GitHub Issues | 1 command | — | [speckit-openproject](https://github.com/Nachklang-io/speckit-openproject) | -| OpenUP Governance | Composes OpenUP lifecycle governance into Spec Kit's own constitution, spec, plan and tasks templates, and wraps /tasks and /implement with the governed execution contract. | 4 templates, 2 commands | openup extension | [specup](https://github.com/anvigo12/specup) | -| Parallel Autonomous Run Governance | Coordinates isolated autonomous campaigns and optionally gates worker scheduling on a current campaign intake review. | 10 templates, 5 commands, 2 scripts | autonomous-run-governance >=0.2.2; optional: intake-review-governance >=0.1.0 | [spec-kit-preset-parallel-autonomous-run-governance](https://github.com/hindermath/spec-kit-preset-parallel-autonomous-run-governance) | -| Pirate Speak (Full) | Transforms all Spec Kit output into pirate speak — specs become "Voyage Manifests", plans become "Battle Plans", tasks become "Crew Assignments" | 6 templates, 9 commands | — | [spec-kit-presets](https://github.com/mnriem/spec-kit-presets) | -| Project Statistics Governance | Reproducible Git-bound project transparency with offline measurements, explicit write authority and opt-in reference estimates; no AI productivity claims. | 4 templates, 3 commands, 2 scripts | — | [spec-kit-preset-project-statistics-governance](https://github.com/hindermath/spec-kit-preset-project-statistics-governance) | -| Screenwriting | Spec-Driven Development for screenwriting/scriptwriting/tutorials: feature films, television (pilot, episode, limited series), and stage plays. Adapts the Spec Kit workflow to screenplay craft — slug lines, action lines, act breaks, beat sheets, and industry-standard pitch documents. Supports three-act, Save the Cat, TV pilot, network episode, cable/streaming episode, and stage-play structural frameworks. Export to Fountain, FTX, PDF | 26 templates, 32 commands, 1 script | — | [speckit-preset-screenwriting](https://github.com/adaumann/speckit-preset-screenwriting) | -| Secure Development Assurance Governance | Validates project-owned secure-development manifest, version, normalized hash, checklist, review, risk, closure, and image-impact evidence without granting human approvals or certifications. | 2 templates, 2 commands, 2 scripts | — | [spec-kit-preset-secure-development-assurance-governance](https://github.com/hindermath/spec-kit-preset-secure-development-assurance-governance) | -| Security Governance | Adds secure coding, memory-safe-language guidance, security-gate and supply-chain evidence, and scoped GDPR, NIS2, CRA, EU AI Act, and DORA screening to Spec Kit. | 19 templates, 3 commands | — | [spec-kit-preset-security-governance](https://github.com/hindermath/spec-kit-preset-security-governance) | -| SicarioSpec Core | Baseline secure-by-default Spec Kit governance profile. | 5 templates | — | [sicario-spec](https://github.com/dfirs1car1o/sicario-spec) | -| Software Humano | Compiles the requirements of the Software Humano manifesto into the eight core Spec Kit commands and into the spec, plan and tasks templates, quoting the manifesto's literal text rather than rephrasing it. | 4 templates, 8 commands | — | [software-humano-speckit](https://github.com/dacunao/software-humano-speckit) | -| Spec2Cloud | Spec-driven workflow tuned for shipping to Azure: spec → plan → tasks → implement → deploy | 5 templates, 8 commands | — | [spec2cloud](https://github.com/Azure-Samples/Spec2Cloud) | -| SpecAssay | Appends durable-ID, Carries, and SpecAssay vocabulary onto Spec Kit spec, tasks, and constitution templates. | 3 templates | specassay-check extension | [specassay](https://github.com/rdryfoos/specassay) | -| Table of Contents Navigation | Adds a navigable Table of Contents to generated spec.md, plan.md, and tasks.md documents | 3 templates, 3 commands | — | [spec-kit-preset-toc-navigation](https://github.com/Quratulain-bilal/spec-kit-preset-toc-navigation) | -| Test-First Governance | Governs TDD with coverage-complete BDD/ATDD Gherkin scenarios, explicit suite ownership, professional test reports, traceability, and risk-based quality gates. | 10 templates, 8 commands | — | [spec-kit-preset-test-first-governance](https://github.com/ka-zo/spec-kit-preset-test-first-governance) | -| Verified Codebase Context | Generate evidence-qualified repository context and use it across planning, tasks, analysis, and implementation | 1 template, 5 commands | — | [spec-kit-preset-codebase-memory-context](https://github.com/philo-x/spec-kit-preset-codebase-memory-context) | -| VS Code Ask Questions | Enhances the clarify command to use `vscode/askQuestions` for batched interactive questioning. | 1 command | — | [spec-kit-presets](https://github.com/fdcastel/spec-kit-presets) | -| Workflow Preset | Behavior-first specification, design artifacts, and agent-native handoff orchestration — adds requirement-phase behavior drafts, formal BDD/UIF/behavior contracts, optional design artifacts, and scoped implementation handoffs with Core Agent, Vertical Planner Agent, and Worker Agent modes | 22 templates, 8 commands | — | [spec-kit-workflow-preset](https://github.com/bigsmartben/spec-kit-workflow-preset) | - -To build and publish your own preset, see the [Presets Publishing Guide](../presets/publishing.md). +This directory is generated from the [community preset catalog](https://github.com/github/spec-kit/blob/main/presets/catalog.community.json). Versions shown are catalog-listed releases, not live repository releases. The community catalog is discovery-only. + +Star counts are GitHub repository totals captured at the last documentation build. Presets in the same repository share a count; stars are not a safety endorsement. + +[!INCLUDE [Community preset directory](../_generated/preset-directory.md)] + +## See also + +- [Preset overview](../presets/overview.md) +- [Catalogs and trust](../presets/catalogs.md) +- [Publish a preset](../presets/publishing.md) diff --git a/docs/docfx.json b/docs/docfx.json index e9b3bd3a48..43b2eecb07 100644 --- a/docs/docfx.json +++ b/docs/docfx.json @@ -6,6 +6,7 @@ "*.md", "toc.yml", "community/*.md", + "community/presets/*.md", "bundles/*.md", "extensions/*.md", "guides/*.md", @@ -33,7 +34,8 @@ "resource": [ { "files": [ - "images/**" + "images/**", + "assets/**" ] }, { diff --git a/docs/generate_presets.py b/docs/generate_presets.py new file mode 100644 index 0000000000..38db689bd2 --- /dev/null +++ b/docs/generate_presets.py @@ -0,0 +1,305 @@ +"""Generate the community preset directory and DocFX detail pages from the catalog.""" + +import argparse +import html +import json +import os +import re +import shlex +import sys +from concurrent.futures import ThreadPoolExecutor +from http.client import HTTPException +from pathlib import Path +from urllib.parse import urlsplit +from urllib.request import Request, urlopen + + +ROOT = Path(__file__).resolve().parent.parent + + +def text(value: object, context: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{context} must be a non-empty string") + return value + + +def escape_metadata(value: str) -> str: + # Literal blank lines end raw HTML blocks in DocFX's Markdown parser. + return html.escape(value).replace("\r", " ").replace("\n", " ") + + +def url(value: object, context: str) -> str: + value = text(value, context) + parsed = urlsplit(value) + if ( + parsed.scheme != "https" + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or any(character.isspace() or ord(character) < 32 for character in value) + ): + raise ValueError(f"{context} must be an HTTPS URL without credentials or whitespace") + return value + + +def unique_keys(pairs: list[tuple]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate catalog key: {key}") + result[key] = value + return result + + +def load_presets(catalog_path: Path) -> list[dict]: + catalog = json.loads(catalog_path.read_text(encoding="utf-8"), object_pairs_hook=unique_keys) + if not isinstance(catalog, dict) or catalog.get("schema_version") != "1.0": + raise ValueError("preset catalog must be an object with schema_version 1.0") + entries = catalog.get("presets") + if not isinstance(entries, dict): + raise ValueError("preset catalog must contain a presets object") + for preset_id, entry in entries.items(): + if not re.fullmatch(r"[a-z][a-z0-9-]*", preset_id): + raise ValueError(f"invalid preset ID: {preset_id}") + if not isinstance(entry, dict) or entry.get("id") != preset_id: + raise ValueError(f"{preset_id}: entry ID must match its catalog key") + for field in ("name", "description", "author", "version", "license"): + text(entry.get(field), f"{preset_id}.{field}") + for field in ("repository", "documentation", "download_url"): + url(entry.get(field), f"{preset_id}.{field}") + requires = entry.get("requires") + if not isinstance(requires, dict): + raise ValueError(f"{preset_id}.requires must be an object") + text(requires.get("speckit_version"), f"{preset_id}.requires.speckit_version") + dependencies(requires.get("extensions", [])) + provided = entry.get("provides") + if not isinstance(provided, dict): + raise ValueError(f"{preset_id}.provides must be an object") + for kind in ("templates", "commands", "scripts"): + count = provided.get(kind, 0) + if not isinstance(count, int) or isinstance(count, bool) or count < 0: + raise ValueError(f"{preset_id}.provides.{kind} must be a non-negative integer") + tags = entry.get("tags") + if not isinstance(tags, list): + raise ValueError(f"{preset_id}.tags must be a list") + for tag in tags: + text(tag, f"{preset_id}.tags") + for field in ("updated_at", "sha256"): + if field in entry: + text(entry[field], f"{preset_id}.{field}") + return sorted(entries.values(), key=lambda entry: (entry["name"].casefold(), entry["id"])) + + +def dependencies(values: object) -> list[str]: + if not isinstance(values, list): + raise ValueError("requires.extensions must be a list") + result = [] + for value in values: + if isinstance(value, str): + result.append(text(value, "extension dependency")) + elif isinstance(value, dict): + name = text(value.get("id"), "extension dependency ID") + if "version" in value: + name += f" {text(value['version'], 'extension dependency version')}" + if "required" in value and not isinstance(value["required"], bool): + raise ValueError("extension dependency required must be a boolean") + if value.get("required", True) is False: + name += " (optional)" + result.append(name) + else: + raise ValueError("extension dependency must be a string or object") + return result + + +def contributions(entry: dict) -> str: + return ", ".join( + f"{count} {kind[:-1] if count == 1 else kind}" + for kind in ("templates", "commands", "scripts") + if (count := entry["provides"].get(kind, 0)) + ) or "No contributions listed" + + +def repository_stars(presets: list[dict]) -> dict[str, int | None]: + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "spec-kit-preset-documentation", + "X-GitHub-Api-Version": "2022-11-28", + } + if token: + headers["Authorization"] = f"Bearer {token}" + + repositories = {} + for entry in presets: + repository = entry["repository"] + parsed = urlsplit(repository) + path = parsed.path.strip("/").removesuffix(".git") + if ( + parsed.netloc.lower() != "github.com" + or parsed.query + or parsed.fragment + or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", path) + ): + print(f"Warning: stars unavailable for {repository}: not a GitHub repository URL", file=sys.stderr) + repositories[repository] = None + else: + repositories[repository] = path.casefold() + + def fetch(repository: str) -> int | None: + request = Request(f"https://api.github.com/repos/{repository}", headers=headers) + try: + with urlopen(request, timeout=10) as response: + data = json.load(response) + count = data.get("stargazers_count") if isinstance(data, dict) else None + if not isinstance(count, int) or isinstance(count, bool) or count < 0: + raise ValueError("GitHub response has no valid stargazers_count") + return count + except (OSError, ValueError, HTTPException) as exc: + print(f"Warning: stars unavailable for {repository}: {exc}", file=sys.stderr) + return None + + unique = sorted({repository for repository in repositories.values() if repository is not None}) + with ThreadPoolExecutor(max_workers=6) as pool: + counts = dict(zip(unique, pool.map(fetch, unique))) + return { + repository: counts.get(key) if key is not None else None + for repository, key in repositories.items() + } + + +def star_badge(entry: dict, count: int | None) -> str: + if count is None: + return 'Stars unavailable' + repository = entry["repository"].rstrip("/").removesuffix(".git") + return ( + f'' + f' {count:,}' + ) + + +def directory(presets: list[dict], stars: dict[str, int | None]) -> str: + escape = escape_metadata + tags = sorted({tag for entry in presets for tag in entry["tags"]}, key=str.casefold) + options = "".join(f'' for tag in tags) + rows = [] + for entry in presets: + search = " ".join( + [entry[field] for field in ("id", "name", "description", "author")] + + entry["tags"] + dependencies(entry["requires"].get("extensions", [])) + ) + badges = "".join(f'{escape(tag)}' for tag in entry["tags"]) + rows.append( + f'
  • ' + f'

    ' + f'{escape(entry["name"])}

    ' + f'{escape(entry["version"])}{star_badge(entry, stars.get(entry["repository"]))}
    ' + f'

    {escape(entry["description"])}

    ' + f'' + f'
    {badges}
  • ' + ) + return f""" + + +
    + +

    {len(presets)} presets

    + +
      {"".join(rows)}
    +
    +""" + + +def detail(entry: dict, stars: int | None) -> str: + escape = escape_metadata + metadata = { + "Preset ID": entry["id"], + "Catalog version": entry["version"], + "Author": entry["author"], + "Repository stars": f"{stars:,}" if stars is not None else "Unavailable", + "License": entry["license"], + "Requires Spec Kit": entry["requires"]["speckit_version"], + "Extension dependencies": ", ".join(dependencies(entry["requires"].get("extensions", []))) or "None listed", + "Provides": contributions(entry), + "Tags": ", ".join(entry["tags"]) or "None listed", + "Updated": entry.get("updated_at", "Not provided"), + } + definitions = "".join( + f"
    {escape(label)}
    {escape(value)}
    " for label, value in metadata.items() + ) + checksum = ( + f'

    Catalog SHA-256: {escape(entry["sha256"])}

    ' + if entry.get("sha256") else "

    No SHA-256 digest is listed in this catalog entry.

    " + ) + command = escape(f"specify preset add --from {shlex.quote(entry['download_url'])}") + return f""" + + +
    +

    Back to community presets

    +

    {escape(entry["name"])}

    +

    {escape(entry["description"])}

    + +

    Preset details

    + +

    Review before installing

    +

    This preset is independently maintained. Maintainers check catalog metadata only; +they do not review, audit, endorse, or support the preset code. +You must vet the preset source and the exact release before installation.

    +

    The community catalog is discovery-only. After vetting, this command explicitly +installs the archive listed for version {escape(entry["version"])}:

    +
    {command}
    +{checksum} +

    A digest checks archive integrity; it is not evidence of code review or safety.

    +

    See also

    + +
    +""" + + +def generate(catalog_path: Path, docs_path: Path, *, fetch_stars: bool = False) -> int: + presets = load_presets(catalog_path) + stars = repository_stars(presets) if fetch_stars else {} + pages = {f"{entry['id']}.md": detail(entry, stars.get(entry["repository"])) for entry in presets} + listing = directory(presets, stars) + details_path = docs_path / "community" / "presets" + details_path.mkdir(parents=True, exist_ok=True) + for stale in details_path.glob("*.md"): + if stale.name not in pages: + stale.unlink() + for name, content in pages.items(): + (details_path / name).write_text(content, encoding="utf-8") + include_path = docs_path / "_generated" + include_path.mkdir(parents=True, exist_ok=True) + (include_path / "preset-directory.md").write_text(listing, encoding="utf-8") + return len(presets) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--catalog", type=Path, default=ROOT / "presets/catalog.community.json") + parser.add_argument("--docs", type=Path, default=ROOT / "docs") + parser.add_argument("--fetch-stars", action="store_true", help="Fetch GitHub repository star counts at build time") + args = parser.parse_args() + try: + count = generate(args.catalog, args.docs, fetch_stars=args.fetch_stars) + except (ValueError, OSError) as exc: + parser.exit(1, f"Preset documentation generation failed: {exc}\n") + print(f"Generated directory and detail pages for {count} community presets.") + + +if __name__ == "__main__": + main() diff --git a/docs/presets/publishing.md b/docs/presets/publishing.md index 7d04b5d1ca..490b78c1c0 100644 --- a/docs/presets/publishing.md +++ b/docs/presets/publishing.md @@ -127,9 +127,9 @@ dedicated checksum field in the form. If supplied, it must match the fetched archive; a mismatch is a validation failure, not a value the automation silently replaces. -Do not edit `presets/catalog.community.json` or -`docs/community/presets.md` yourself as a substitute for submission. -Automation prepares those changes after validation. +Do not edit `presets/catalog.community.json` yourself as a substitute for +submission. Automation prepares catalog changes after validation; the +documentation site generates its preset directory from that catalog. ## What happens after submission @@ -144,10 +144,11 @@ Automation prepares those changes after validation. The verifier parses the published manifest without executing archive content, comparing its ID, version, Spec Kit requirement, and required extensions to the issue. -4. On success, automation proposes a draft pull request updating the catalog - and community table. It records the actual archive digest, preserves - `created_at` on updates, sorts catalog IDs and display names appropriately, - and verifies the generated files before marking validation passed. +4. On success, automation proposes a draft pull request updating the catalog. + It records the actual archive digest, preserves `created_at` on updates, + sorts catalog IDs, and verifies the generated catalog before marking + validation passed. The docs build generates the alphabetical directory + and individual preset pages; there is no separate table to maintain. 5. A maintainer reviews the generated catalog changes and merges them when approved. The preset becomes discoverable; the community catalog remains discovery-only. diff --git a/tests/test_community_preset_validation.py b/tests/test_community_preset_validation.py index bda9052604..8fba4fc247 100644 --- a/tests/test_community_preset_validation.py +++ b/tests/test_community_preset_validation.py @@ -36,7 +36,7 @@ def submission(tmp_path): "tags": "sample, example", } paths = {name: tmp_path / name for name in ( - "issue.json", "archive.zip", "README.md", "catalog.json", "presets.md", + "issue.json", "archive.zip", "README.md", "catalog.json", "snapshot.json", )} paths["README.md"].write_text( @@ -57,11 +57,6 @@ def submission(tmp_path): paths["catalog.json"].write_text( json.dumps({"presets": {}}), encoding="utf-8" ) - paths["presets.md"].write_text( - "| Preset | Purpose | Provides | Requires | URL |\n" - "|--------|---------|----------|----------|-----|\n", - encoding="utf-8", - ) return issue, manifest, paths @@ -73,7 +68,6 @@ def run_verifier(paths, phase="submission"): "--archive", str(paths["archive.zip"]), "--readme", str(paths["README.md"]), "--catalog", str(paths["catalog.json"]), - "--docs", str(paths["presets.md"]), "--snapshot", str(paths["snapshot.json"]), ], capture_output=True, text=True, check=False, @@ -108,16 +102,6 @@ def write_generated(issue, paths, *, created_at=None): paths["catalog.json"].write_text(json.dumps({ "updated_at": entry["updated_at"], "presets": {"sample": entry}, }), encoding="utf-8") - preset_name = issue["preset_name"].replace("\\", r"\\").replace("|", r"\|") - description = issue["description"].replace("\\", r"\\").replace("|", r"\|") - paths["presets.md"].write_text( - "| Preset | Purpose | Provides | Requires | URL |\n" - "|--------|---------|----------|----------|-----|\n" - f"| {preset_name} | {description} | 1 template, 1 command | " - "aide extension, canon extension | " - "[presets](https://github.com/example/presets) |\n", - encoding="utf-8", - ) return entry @@ -468,11 +452,11 @@ def test_missing_archive_is_blocked_not_failed(submission): assert "BLOCKED" in result.stdout -def test_missing_generated_documentation_is_repairable(submission): +def test_missing_generated_catalog_is_repairable(submission): issue, _, paths = submission assert run_verifier(paths).returncode == 0 write_generated(issue, paths) - paths["presets.md"].unlink() + paths["catalog.json"].unlink() result = run_verifier(paths, "generated") assert result.returncode == 3 assert "REPAIR" in result.stdout @@ -535,7 +519,7 @@ def test_generated_update_rejects_stale_homepage(submission): assert "homepage" in result.stdout -def test_generated_documentation_accepts_escaped_pipe_in_preset_name(submission): +def test_generated_catalog_accepts_pipe_in_preset_name(submission): issue, _, paths = submission issue["preset_name"] = "Data | Governance" paths["issue.json"].write_text(json.dumps(issue), encoding="utf-8") @@ -545,7 +529,7 @@ def test_generated_documentation_accepts_escaped_pipe_in_preset_name(submission) assert result.returncode == 0, result.stdout + result.stderr -def test_generated_documentation_accepts_backslash_before_pipe(submission): +def test_generated_catalog_accepts_backslash_before_pipe(submission): issue, _, paths = submission issue["preset_name"] = r"Data \| Governance" paths["issue.json"].write_text(json.dumps(issue), encoding="utf-8") @@ -555,21 +539,11 @@ def test_generated_documentation_accepts_backslash_before_pipe(submission): assert result.returncode == 0, result.stdout + result.stderr -def test_generated_documentation_allows_duplicate_display_names(submission): +def test_generated_catalog_allows_duplicate_display_names(submission): issue, _, paths = submission - other_row = ( - "| Sample Preset | Other usage | 1 command | — | " - "[other](https://github.com/example/other) |" - ) paths["catalog.json"].write_text(json.dumps({ "presets": {"other": {"name": issue["preset_name"]}}, }), encoding="utf-8") - paths["presets.md"].write_text( - "| Preset | Purpose | Provides | Requires | URL |\n" - "|--------|---------|----------|----------|-----|\n" - f"{other_row}\n", - encoding="utf-8", - ) assert run_verifier(paths).returncode == 0 entry = write_generated(issue, paths) catalog = json.loads(paths["catalog.json"].read_text(encoding="utf-8")) @@ -578,28 +552,13 @@ def test_generated_documentation_allows_duplicate_display_names(submission): "sample": entry, } paths["catalog.json"].write_text(json.dumps(catalog), encoding="utf-8") - paths["presets.md"].write_text( - "| Preset | Purpose | Provides | Requires | URL |\n" - "|--------|---------|----------|----------|-----|\n" - f"{other_row}\n" - "| Sample Preset | Sample usage | 1 template, 1 command | " - "aide extension, canon extension | " - "[presets](https://github.com/example/presets) |\n", - encoding="utf-8", - ) result = run_verifier(paths, "generated") assert result.returncode == 0, result.stdout + result.stderr -def test_generated_documentation_accepts_replaced_renamed_row(submission): +def test_generated_catalog_accepts_renamed_preset(submission): issue, _, paths = submission original = write_generated(issue, paths, created_at="2024-12-01T00:00:00Z") - paths["presets.md"].write_text( - paths["presets.md"].read_text(encoding="utf-8").replace( - "Sample usage", "Legacy documentation wording" - ), - encoding="utf-8", - ) paths["catalog.json"].write_text(json.dumps({ "updated_at": original["updated_at"], "presets": {"sample": original}, }), encoding="utf-8") @@ -611,30 +570,23 @@ def test_generated_documentation_accepts_replaced_renamed_row(submission): assert result.returncode == 0, result.stdout + result.stderr -def test_generated_documentation_rejects_stale_row_after_rename(submission): +def test_generated_catalog_rejects_stale_name_after_rename(submission): issue, _, paths = submission original = write_generated(issue, paths, created_at="2024-12-01T00:00:00Z") - paths["presets.md"].write_text( - paths["presets.md"].read_text(encoding="utf-8").replace( - "Sample usage", "Legacy documentation wording" - ), - encoding="utf-8", - ) - previous_row = paths["presets.md"].read_text(encoding="utf-8").splitlines()[2] paths["catalog.json"].write_text(json.dumps({ "updated_at": original["updated_at"], "presets": {"sample": original}, }), encoding="utf-8") issue["preset_name"] = "Renamed Preset" paths["issue.json"].write_text(json.dumps(issue), encoding="utf-8") assert run_verifier(paths).returncode == 0 - write_generated(issue, paths, created_at="2024-12-01T00:00:00Z") - paths["presets.md"].write_text( - paths["presets.md"].read_text(encoding="utf-8") + previous_row + "\n", - encoding="utf-8", - ) + entry = write_generated(issue, paths, created_at="2024-12-01T00:00:00Z") + entry["name"] = original["name"] + paths["catalog.json"].write_text(json.dumps({ + "updated_at": entry["updated_at"], "presets": {"sample": entry}, + }), encoding="utf-8") result = run_verifier(paths, "generated") assert result.returncode == 3 - assert "previous documentation row" in result.stdout + assert "name" in result.stdout @pytest.mark.parametrize(("damage", "message"), [ @@ -644,8 +596,8 @@ def test_generated_documentation_rejects_stale_row_after_rename(submission): ("homepage-missing", "homepage"), ("homepage-stale", "homepage"), ("catalog-timestamp", "top-level updated_at"), - ("docs-order", "alphabetical"), - ("docs-row", "documentation row"), + ("catalog-dependencies", "requires"), + ("catalog-digest", "sha256"), ("created-at", "created_at"), ]) def test_generated_defects_are_fixable_not_submission_failures(submission, damage, message): @@ -689,18 +641,14 @@ def test_generated_defects_are_fixable_not_submission_failures(submission, damag "sample": entry, }}), encoding="utf-8" ) - elif damage == "docs-order": - paths["presets.md"].write_text( - paths["presets.md"].read_text(encoding="utf-8") - + "| AAA | x | 1 command | — | [aaa](https://github.com/aaa/aaa) |\n", - encoding="utf-8", - ) - elif damage == "docs-row": - paths["presets.md"].write_text( - paths["presets.md"].read_text(encoding="utf-8").replace( - "Sample usage", "Wrong purpose" - ), encoding="utf-8", - ) + elif damage in ("catalog-dependencies", "catalog-digest"): + if damage == "catalog-dependencies": + entry["requires"]["extensions"] = [] + else: + entry["sha256"] = "0" * 64 + paths["catalog.json"].write_text(json.dumps({ + "updated_at": entry["updated_at"], "presets": {"sample": entry}, + }), encoding="utf-8") elif damage == "created-at": entry["created_at"] = "2000-01-01T00:00:00Z" paths["catalog.json"].write_text( diff --git a/tests/test_github_workflows.py b/tests/test_github_workflows.py index 0eb2a7cbae..0078d900f1 100644 --- a/tests/test_github_workflows.py +++ b/tests/test_github_workflows.py @@ -61,7 +61,7 @@ "preset", "preset-submission", "presets/catalog.community.json", - "docs/community/presets.md", + None, "Do not modify any other files", ), ) @@ -788,15 +788,14 @@ def test_community_submission_automation_is_wired_to_allowed_files(): assert f"names: [{label}]" in source_text assert catalog_file in source_text - assert docs_file in source_text + if docs_file is not None: + assert docs_file in source_text assert instruction in source_text - assert _create_pull_request_allowed_files(source_text) == [ - catalog_file, - docs_file, - ] + allowed_files = [catalog_file] + ([docs_file] if docs_file is not None else []) + assert _create_pull_request_allowed_files(source_text) == allowed_files assert _safe_output_config(yaml.safe_load(compiled_text))[ "create_pull_request" - ]["allowed_files"] == [catalog_file, docs_file] + ]["allowed_files"] == allowed_files assert label in assignment_text @@ -1117,7 +1116,10 @@ def test_community_upgrade_preserves_scoped_draft_pr_contract( f"add-community-{kind}" ) assert instruction in source_text - assert REPOSITORY_OWNED_DRAFT_PR_EXEMPTION in " ".join(source_text.split()) + exemption = REPOSITORY_OWNED_DRAFT_PR_EXEMPTION + if docs_file is None: + exemption = exemption.replace("catalog/docs file updates", "catalog updates") + assert exemption in " ".join(source_text.split()) assert ( f"{{{{#runtime-import .github/workflows/add-community-{kind}.md}}}}" in compiled_text @@ -1156,18 +1158,19 @@ def test_community_upgrade_preserves_scoped_draft_pr_contract( } assert source["safe-outputs"]["noop"] == {"report-as-issue": False} assert outputs["noop"] == {"max": 1, "report-as-issue": "false"} + allowed_files = [catalog_file] + ([docs_file] if docs_file is not None else []) assert source["safe-outputs"]["create-pull-request"] == { "title-prefix": f"[{kind}] ", "labels": [label, "automated"], "draft": True, "max": 1, - "allowed-files": [catalog_file, docs_file], + "allowed-files": allowed_files, "protected-files": { "policy": "blocked", "exclude": ["README.md", "CHANGELOG.md"] }, } create_pr = outputs["create_pull_request"] - assert create_pr["allowed_files"] == [catalog_file, docs_file] + assert create_pr["allowed_files"] == allowed_files assert create_pr["draft"] is True assert create_pr["title_prefix"] == f"[{kind}] " assert create_pr["labels"] == [label, "automated"] @@ -1380,7 +1383,7 @@ def test_community_archive_permission_failures_are_not_submission_failures(kind) if kind == "preset": assert "Remove any stale `validation-passed` and `validation-failed`" in passed assert "Do not add `validation-passed` yet" in passed - generated = source_text.split("### Verify the generated files", 1)[1].split( + generated = source_text.split("## Step 5", 1)[1].split( "\n## Step 6", 1 )[0] assert "validate_community_preset.py generated" in generated diff --git a/tests/test_preset_documentation.py b/tests/test_preset_documentation.py new file mode 100644 index 0000000000..baafa165ad --- /dev/null +++ b/tests/test_preset_documentation.py @@ -0,0 +1,351 @@ +"""Catalog-derived documentation, invalid inputs, and docs deployment wiring.""" + +import copy +import importlib.util +import io +import json +import shutil +import subprocess +import sys +from html.parser import HTMLParser +from http.client import IncompleteRead +from pathlib import Path + +import pytest +import yaml + + +ROOT = Path(__file__).resolve().parent.parent +GENERATOR = ROOT / "docs/generate_presets.py" +spec = importlib.util.spec_from_file_location("generate_presets", GENERATOR) +generator = importlib.util.module_from_spec(spec) +spec.loader.exec_module(generator) + + +class DirectoryParser(HTMLParser): + def __init__(self): + super().__init__() + self.entries = [] + self.links = [] + self.scripts = [] + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + if tag == "li" and attrs.get("class") == "preset-entry": + self.entries.append(attrs) + if tag == "a": + self.links.append(attrs["href"]) + if tag == "script": + self.scripts.append(attrs.get("src")) + + +@pytest.fixture +def catalog(tmp_path): + entry = { + "id": "sample", + "name": "Sample Preset", + "description": "Adds useful context", + "author": "Contributor", + "version": "1.2.3", + "license": "MIT", + "repository": "https://github.com/example/presets", + "documentation": "https://github.com/example/presets/blob/v1.2.3/sample/README.md", + "download_url": "https://github.com/example/presets/releases/download/sample-v1.2.3/sample.zip", + "requires": { + "speckit_version": ">=1.0.0", + "extensions": [{"id": "aide", "version": ">=2.0", "required": False}], + }, + "provides": {"templates": 1, "commands": 2}, + "tags": ["context", "planning"], + } + data = {"schema_version": "1.0", "presets": {"sample": entry}} + path = tmp_path / "catalog.json" + path.write_text(json.dumps(data), encoding="utf-8") + return data, path, tmp_path / "docs" + + +def test_real_catalog_has_one_page_and_static_link_per_entry(tmp_path): + catalog_path = ROOT / "presets/catalog.community.json" + entries = json.loads(catalog_path.read_text(encoding="utf-8"))["presets"] + assert generator.generate(catalog_path, tmp_path) == len(entries) + listing = (tmp_path / "_generated/preset-directory.md").read_text(encoding="utf-8") + parsed = DirectoryParser() + parsed.feed(listing) + assert len(parsed.entries) == len(entries) + assert set(parsed.links) == {f"presets/{preset_id}.md" for preset_id in entries} + assert all("hidden" not in entry for entry in parsed.entries) + assert {page.stem for page in (tmp_path / "community/presets").glob("*.md")} == set(entries) + for preset_id, entry in entries.items(): + detail = (tmp_path / f"community/presets/{preset_id}.md").read_text(encoding="utf-8") + assert generator.html.escape(entry["name"]) in detail + assert generator.html.escape(entry["download_url"]) in detail + assert "do not review, audit, endorse, or support" in detail + assert "after vetting" in detail.lower() + assert "--install-allowed" not in detail + + +def test_generation_is_deterministic_and_removes_deleted_pages(catalog): + data, path, docs = catalog + other = copy.deepcopy(data["presets"]["sample"]) + other.update(id="other", name="Another Preset") + data["presets"]["other"] = other + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + first = (docs / "_generated/preset-directory.md").read_bytes() + assert first.index(b"Another Preset") < first.index(b"Sample Preset") + generator.generate(path, docs) + assert (docs / "_generated/preset-directory.md").read_bytes() == first + del data["presets"]["other"] + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + assert not (docs / "community/presets/other.md").exists() + assert (docs / "community/presets/sample.md").is_file() + + +def test_untrusted_metadata_is_text_not_markup_or_markdown(catalog): + data, path, docs = catalog + entry = data["presets"]["sample"] + payload = '\n\n\r\n![x](javascript:alert(1)) & |' + entry.update(name=payload, description=payload, author=payload, tags=[payload]) + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + for generated in ( + docs / "_generated/preset-directory.md", + docs / "community/presets/sample.md", + ): + source = generated.read_text(encoding="utf-8") + assert payload not in source + assert generator.escape_metadata(payload) in source + listing = (docs / "_generated/preset-directory.md").read_text(encoding="utf-8") + detail = (docs / "community/presets/sample.md").read_text(encoding="utf-8") + parsed = DirectoryParser() + parsed.feed(listing) + assert parsed.scripts == ["../assets/preset-catalog.js"] + assert json.loads(parsed.entries[0]["data-preset-tags"]) == [payload] + assert generator.escape_metadata(payload) in detail + assert "