diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3603554743..9d9d340a06 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -9,6 +9,7 @@ on: - 'docs/**' - 'presets/catalog.community.json' - 'bundles/catalog.community.json' + - 'workflows/catalog.community.json' - '.github/workflows/docs.yml' # Allows you to run this workflow manually from the Actions tab @@ -58,6 +59,11 @@ jobs: env: GH_TOKEN: ${{ github.token }} + - name: Generate community workflow documentation + run: python3 docs/generate_workflows.py --fetch-stars + env: + GH_TOKEN: ${{ github.token }} + - name: Build with DocFX run: | cd docs diff --git a/docs/.gitignore b/docs/.gitignore index 36f571cdfc..20c42faf2b 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -5,6 +5,7 @@ obj/ _generated/ community/presets/ community/bundles/ +community/workflows/ # Temporary files *.tmp diff --git a/docs/README.md b/docs/README.md index 78523ecbe8..bf29c514fb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,11 +12,12 @@ To build the documentation locally: dotnet tool install -g docfx ``` -2. Generate the community preset and bundle directories from the local catalogs: +2. Generate the community preset, bundle, and workflow directories from the local catalogs: ```bash python3 docs/generate_presets.py --fetch-stars python3 docs/generate_bundles.py --fetch-stars + python3 docs/generate_workflows.py --fetch-stars ``` 3. Build the documentation: @@ -28,19 +29,20 @@ To build the documentation locally: 4. Open your browser to `http://localhost:8080` to view the documentation. -Run the corresponding generator again after editing `presets/catalog.community.json` -or `bundles/catalog.community.json`. They create the ignored -`_generated/preset-directory.md` and `_generated/bundle-directory.md` includes and -`community/presets/*.md` and `community/bundles/*.md` detail pages, removing pages for deleted entries. +Run the corresponding generator again after editing `presets/catalog.community.json`, +`bundles/catalog.community.json`, or `workflows/catalog.community.json`. They create +the ignored `_generated/preset-directory.md`, `_generated/bundle-directory.md`, +and `_generated/workflow-directory.md` includes and `community/presets/*.md`, +`community/bundles/*.md`, and `community/workflows/*.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 or bundle content. With +building it does not fetch or execute third-party preset, bundle, or workflow 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. Search, tag, role/team (bundles), -and sort controls enhance complete static listings, which remain readable +declared integration (workflows), and sort controls enhance complete static listings, which remain readable without JavaScript. ## Structure @@ -128,9 +130,9 @@ the site homepage. Process command references and authentication remain under ## Deployment -Documentation, community preset or bundle catalog, and docs workflow changes on the +Documentation, community preset, bundle, or workflow catalog, and docs workflow changes on the upstream `main` branch trigger the normal GitHub Pages deployment. Each build -generates the preset and bundle directories and detail pages and refreshes repository star +generates the preset, bundle, and workflow directories and detail pages and refreshes repository star counts before running DocFX. A weekly run on Mondays at 04:17 UTC refreshes the site and its build-time star counts, using the same path as manual runs. It does not write star counts back to the catalogs. diff --git a/docs/assets/workflow-catalog.css b/docs/assets/workflow-catalog.css new file mode 100644 index 0000000000..d4424eb966 --- /dev/null +++ b/docs/assets/workflow-catalog.css @@ -0,0 +1,175 @@ +.workflow-catalog, +.workflow-detail { + --workflow-muted: var(--bs-secondary-color, #59636e); + --workflow-border: var(--bs-border-color, #d1d9e0); +} + +.workflow-controls { + display: grid; + grid-template-columns: repeat(2, minmax(8rem, 1fr)) minmax(9rem, 1fr) auto; + align-items: end; + gap: 1rem; + margin: 2rem 0 1rem; +} + +.workflow-catalog [hidden] { + display: none !important; +} + +.workflow-search { + grid-column: 1 / -1; +} + +.workflow-controls label { + display: block; + margin-bottom: 0.4rem; + font-weight: 600; +} + +.workflow-controls input, +.workflow-controls select, +.workflow-reset { + min-height: 2.75rem; + width: 100%; + padding: 0.5rem 0.75rem; + border: 1px solid var(--workflow-border); + border-radius: 0.375rem; + color: var(--bs-body-color, #1f2328); + background: var(--bs-body-bg, #fff); + font: inherit; +} + +.workflow-controls input::placeholder { + color: var(--workflow-muted); + opacity: 1; +} + +.workflow-reset:hover { + background: var(--bs-tertiary-bg, #f6f8fa); +} + +.workflow-controls :focus-visible, +.workflow-catalog a:focus-visible, +.workflow-detail a:focus-visible { + outline: 2px solid var(--bs-link-color, #0969da); + outline-offset: 3px; +} + +.workflow-result-count, +.workflow-entry-meta { + color: var(--workflow-muted); + font-size: 0.9rem; +} + +.workflow-results { + list-style: none; + padding: 0; + margin: 0 0 2rem; +} + +.workflow-entry { + padding: 1.5rem 0; + border-top: 1px solid var(--workflow-border); +} + +.workflow-entry-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 1rem; +} + +.workflow-entry-heading h2 { + margin: 0 0 0.5rem; + border: 0; + font-size: 1.2rem; +} + +.workflow-entry p { + margin: 0 0 0.75rem; +} + +.workflow-version { + color: var(--workflow-muted); + font-size: 0.85rem; + white-space: nowrap; +} + +.workflow-entry-stats { + display: flex; + align-items: baseline; + flex-shrink: 0; + gap: 1rem; +} + +.workflow-stars { + font-size: 0.85rem; + white-space: nowrap; +} + +.workflow-entry-stats span.workflow-stars { + color: var(--workflow-muted); +} + +.workflow-tags { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.workflow-tag { + padding: 0.15rem 0.55rem; + border: 1px solid var(--workflow-border); + border-radius: 1rem; + font-size: 0.8rem; +} + +.workflow-metadata { + display: grid; + grid-template-columns: minmax(9rem, 1fr) minmax(0, 3fr); + gap: 0.75rem 1.5rem; + margin: 1.5rem 0 2rem; +} + +.workflow-metadata dt, +.workflow-metadata dd { + margin: 0; +} + +.workflow-detail, +.workflow-entry { + overflow-wrap: anywhere; +} + +.workflow-source-links { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.5rem; +} + +@media (max-width: 900px) { + .workflow-controls { + grid-template-columns: 1fr 1fr; + } +} + +@media (max-width: 480px) { + .workflow-controls, + .workflow-metadata { + grid-template-columns: 1fr; + } + + .workflow-metadata { + gap: 0.25rem; + } + + .workflow-metadata dd { + margin-bottom: 0.75rem; + } + + .workflow-entry-heading { + flex-direction: column; + gap: 0; + margin-bottom: 0.5rem; + } +} diff --git a/docs/assets/workflow-catalog.js b/docs/assets/workflow-catalog.js new file mode 100644 index 0000000000..c8cfaac8f5 --- /dev/null +++ b/docs/assets/workflow-catalog.js @@ -0,0 +1,66 @@ +(() => { + const catalog = document.querySelector("[data-workflow-catalog]"); + if (!catalog) return; + + const form = catalog.querySelector("[data-workflow-controls]"); + const query = form.elements.namedItem("q"); + const tag = form.elements.namedItem("tag"); + const integration = form.elements.namedItem("integration"); + const sort = form.elements.namedItem("sort"); + const list = catalog.querySelector(".workflow-results"); + const entries = Array.from(list.children); + const status = catalog.querySelector("[data-workflow-status]"); + const empty = catalog.querySelector("[data-workflow-empty]"); + const searchable = entries.map((entry) => ({ + entry, + text: entry.dataset.workflowSearch.toLocaleLowerCase(), + tags: JSON.parse(entry.dataset.workflowTags), + integrations: JSON.parse(entry.dataset.workflowIntegrations), + })); + const params = new URLSearchParams(window.location.search); + query.value = params.get("q") || ""; + tag.value = params.get("tag") || ""; + if (!tag.value) tag.value = ""; + integration.value = params.get("integration") || ""; + if (!integration.value) integration.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)) + && (!integration.value || item.integrations.includes(integration.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} workflows`; + empty.hidden = visible !== 0; + + const next = new URL(window.location.href); + for (const [key, value] of [["q", query.value], ["tag", tag.value], ["integration", integration.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 = ""; + integration.value = ""; + sort.value = "az"; + update(); + }); + update(); + form.hidden = false; +})(); diff --git a/docs/community/workflows.md b/docs/community/workflows.md index 8fa898e164..d310ed8b71 100644 --- a/docs/community/workflows.md +++ b/docs/community/workflows.md @@ -11,15 +11,15 @@ repeatable processes. ## Available workflows -Entries in the [community workflow catalog](https://github.com/github/spec-kit/blob/main/workflows/catalog.community.json): - -| Workflow | Version | Description | -| --- | --- | --- | -| [ADO story lifecycle](https://github.com/praveenlavu/spec-kit-ado/tree/v0.4.0/workflows/ado-lifecycle) (`ado-lifecycle`) | 0.4.0 | Takes an Azure DevOps story to an open pull request with a preview, a human gate and an apply for every Azure Boards or PR change | -| [GitHub issue lifecycle](https://github.com/praveenlavu/spec-kit-ghp/tree/v0.1.2/workflows/ghp-lifecycle) (`ghp-lifecycle`) | 0.1.2 | Takes a GitHub story issue to an open pull request with a preview, a human gate and an apply for every GitHub issue, Project or PR change | -| [Spec Kit lifecycle for Jira](https://github.com/praveenlavu/spec-kit-jira/tree/v0.1.0/workflows/jira-lifecycle) (`jira-lifecycle`) | 0.1.0 | Takes a Jira Cloud story to an open pull request with a preview, a human gate and an apply for every Jira or PR change | -| [Guided SDD Pipeline](https://github.com/domattioli/spec-kit-workflow-pipeline) (`pipeline`) | 1.1.0 | Chains specify, clarify, plan, tasks, analyze, implement, and converge, with a clarify gate and post-implementation convergence loop | -| [Full SDD Cycle - no gates](https://github.com/clintcparker/speckit-addons/tree/yolo-v0.1.0/workflows/yolo) (`yolo`) | 0.1.0 | Runs specify, plan, tasks, and implement without review gates | +This directory is generated from the +[community workflow catalog](https://github.com/github/spec-kit/blob/main/workflows/catalog.community.json), +alphabetically by name. Detail pages show release links, declared requirements, +and source-review guidance. Integration filters reflect author-declared +alternatives, not verified compatibility; missing declarations do not imply +support for every integration. Repository stars are captured at documentation +build time and are not an endorsement. + +[!INCLUDE [Community workflow directory](../_generated/workflow-directory.md)] These are community definitions, distinct from the workflows bundled with Spec Kit. Inspect active sources and advertised releases: diff --git a/docs/docfx.json b/docs/docfx.json index 8eb15f90da..c874496f93 100644 --- a/docs/docfx.json +++ b/docs/docfx.json @@ -8,6 +8,7 @@ "community/*.md", "community/presets/*.md", "community/bundles/*.md", + "community/workflows/*.md", "bundles/*.md", "extensions/*.md", "guides/*.md", diff --git a/docs/generate_workflows.py b/docs/generate_workflows.py new file mode 100644 index 0000000000..1f09bb3a72 --- /dev/null +++ b/docs/generate_workflows.py @@ -0,0 +1,329 @@ +"""Generate the community workflow directory and DocFX detail pages from the catalog.""" + +import argparse +import html +import json +import os +import re +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 integrations(entry: dict) -> list[str]: + declared = entry.get("requires", {}).get("integrations", {}) + if not isinstance(declared, dict) or set(declared) - {"any"}: + raise ValueError(f"{entry['id']}.requires.integrations must contain an any list") + values = declared.get("any", []) + if not isinstance(values, list): + raise ValueError(f"{entry['id']}.requires.integrations.any must be a list") + return [text(value, f"{entry['id']}.requires.integrations.any") for value in values] + + +def load_workflows(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("workflow catalog must be an object with schema_version 1.0") + entries = catalog.get("workflows") + if not isinstance(entries, dict): + raise ValueError("workflow catalog must contain a workflows object") + for workflow_id, entry in entries.items(): + if not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", workflow_id): + raise ValueError(f"invalid workflow ID: {workflow_id}") + if not isinstance(entry, dict) or entry.get("id") != workflow_id: + raise ValueError(f"{workflow_id}: entry ID must match its catalog key") + for field in ("name", "description", "author", "version"): + text(entry.get(field), f"{workflow_id}.{field}") + url(entry.get("url"), f"{workflow_id}.url") + for field in ("repository", "documentation", "changelog"): + if field in entry: + url(entry[field], f"{workflow_id}.{field}") + requires = entry.get("requires", {}) + if not isinstance(requires, dict): + raise ValueError(f"{workflow_id}.requires must be an object") + if "speckit_version" in requires: + text(requires["speckit_version"], f"{workflow_id}.requires.speckit_version") + integrations(entry) + tags = entry.get("tags", []) + if not isinstance(tags, list): + raise ValueError(f"{workflow_id}.tags must be a list") + for tag in tags: + text(tag, f"{workflow_id}.tags") + for field in ("license", "created_at", "updated_at"): + if field in entry: + text(entry[field], f"{workflow_id}.{field}") + if "sha256" in entry and ( + not isinstance(entry["sha256"], str) + or not re.fullmatch(r"[0-9a-fA-F]{64}", entry["sha256"]) + ): + raise ValueError(f"{workflow_id}.sha256 must contain 64 hexadecimal digits") + return sorted(entries.values(), key=lambda entry: (entry["name"].casefold(), entry["id"])) + + +def repository_stars(workflows: 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-workflow-documentation", + "X-GitHub-Api-Version": "2022-11-28", + } + if token: + headers["Authorization"] = f"Bearer {token}" + repositories = {} + for entry in workflows: + repository = entry.get("repository") + if repository is None: + continue + 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(workflows: list[dict], stars: dict[str, int | None]) -> str: + escape = escape_metadata + tags = sorted( + {tag for entry in workflows for tag in entry.get("tags", [])}, + key=lambda tag: (tag.casefold(), tag), + ) + declared = sorted( + {name for entry in workflows for name in integrations(entry)}, + key=lambda name: (name.casefold(), name), + ) + options = "".join(f'' for tag in tags) + integration_options = "".join(f'' for name in declared) + rows = [] + for entry in workflows: + names = integrations(entry) + requirement = "Any of: " + ", ".join(names) if names else "No integrations declared" + search = " ".join( + [entry[field] for field in ("id", "name", "description", "author")] + + entry.get("tags", []) + names + ) + badges = "".join(f'{escape(tag)}' for tag in entry.get("tags", [])) + rows.append( + f'
  • ' + f'

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

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

    {escape(entry["description"])}

    ' + f'

    By {escape(entry["author"])}' + f' {escape(requirement)}

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

    {len(workflows)} workflows

    + + +
    +""" + + +def detail(entry: dict, stars: int | None) -> str: + escape = escape_metadata + names = integrations(entry) + metadata = { + "Workflow ID": entry["id"], + "Catalog version": entry["version"], + "Author": entry["author"], + "Repository stars": f"{stars:,}" if stars is not None else "Unavailable", + "License": entry.get("license", "Not provided"), + "Requires Spec Kit": entry.get("requires", {}).get("speckit_version", "Not specified"), + "Declared integrations": "Any of: " + ", ".join(names) if names else "Not specified", + "Tags": ", ".join(entry.get("tags", [])) or "None listed", + "Created": entry.get("created_at", "Not provided"), + "Updated": entry.get("updated_at", "Not provided"), + } + definitions = "".join( + f"
    {escape(label)}
    {escape(value)}
    " for label, value in metadata.items() + ) + links = " ".join( + f'{label}' + for field, label in ( + ("repository", "View source and README"), + ("documentation", "Author documentation"), + ("changelog", "Changelog"), + ) + if field in entry + ) or "No source repository or documentation links listed; inspect the release before installation." + checksum = ( + "

    Before installation, compute the downloaded artifact's SHA-256 and " + "compare it with the catalog SHA-256 below. If they do not match, " + "stop and do not install the artifact.

    " + f'

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

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

    No SHA-256 digest is listed in this catalog entry. Obtain and verify " + "an integrity digest from a source you trust before installation.

    " + ) + return f""" + + +
    +

    Back to community workflows

    +

    {escape(entry["name"])}

    +

    {escape(entry["description"])}

    + +

    Workflow details

    +
    {definitions}
    +

    Requirements are author-declared expectations, not enforced permissions or +a sandbox. Missing integration metadata does not imply support for every integration. +Repository stars reflect the last documentation build, not a safety assessment.

    +

    Review before installing or running

    +

    This workflow is independently maintained. Maintainers check catalog metadata only; +they do not review, audit, endorse, or support workflow code, scripts, or dependencies. +You must vet the exact release, required integrations, custom steps, shell commands +and environment values, side effects, credentials, and review gates before installation and use.

    +

    The community catalog is discovery-only. A listing does not make +specify workflow add {escape(entry["id"])} installable through that source. +Inspect active workflow and step catalogs; project configuration may select sources +you did not choose. Use only separately vetted, install-allowed catalogs or an explicit +release source after review.

    +

    After vetting, download and inspect the catalog-listed +artifact for version {escape(entry["version"])}. It may be raw YAML or a complete +package; raw YAML does not include adjacent scripts or resources.

    +{checksum} +

    A digest checks artifact integrity; it is not evidence of code review or safety. +Direct-URL installation selects the source explicitly and does not use catalog digest +verification. Verify the downloaded bytes before installing a local definition or package; +see the workflow installation options.

    +

    Installing a workflow does not run it. Running a workflow executes its steps; +it is not a dry run. Test unfamiliar workflows in a disposable project and review +applicable gate, rejection, failure, and resume behavior.

    +

    See also

    + +
    +""" + + +def generate(catalog_path: Path, docs_path: Path, *, fetch_stars: bool = False) -> int: + workflows = load_workflows(catalog_path) + stars = repository_stars(workflows) if fetch_stars else {} + pages = {f"{entry['id']}.md": detail(entry, stars.get(entry.get("repository"))) for entry in workflows} + listing = directory(workflows, stars) + details_path = docs_path / "community" / "workflows" + 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 / "workflow-directory.md").write_text(listing, encoding="utf-8") + return len(workflows) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--catalog", type=Path, default=ROOT / "workflows/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"Workflow documentation generation failed: {exc}\n") + print(f"Generated directory and detail pages for {count} community workflows.") + + +if __name__ == "__main__": + main() diff --git a/docs/workflows/publishing.md b/docs/workflows/publishing.md index 050988f2cf..6229f1e57a 100644 --- a/docs/workflows/publishing.md +++ b/docs/workflows/publishing.md @@ -115,6 +115,12 @@ the release's real values. Keep `requires` consistent with the definition. The current release stays at the top level; use `releases` for historical versions as described in the catalog reference. +The [community workflow directory](../community/workflows.md) and its detail +pages are generated from this catalog during documentation builds. Do not +maintain a separate Markdown listing or edit generated pages. To preview a +catalog change locally, run `python3 docs/generate_workflows.py` before DocFX; +add `--fetch-stars` to refresh build-time repository stars. + Submit a focused catalog PR with: - Workflow ID, name, version, repository, and license. diff --git a/tests/test_workflow_documentation.py b/tests/test_workflow_documentation.py new file mode 100644 index 0000000000..12c0d29916 --- /dev/null +++ b/tests/test_workflow_documentation.py @@ -0,0 +1,449 @@ +"""Catalog-derived workflow documentation, controls, failures, and build wiring.""" + +import copy +import importlib.util +import io +import json +import os +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_workflows.py" +spec = importlib.util.spec_from_file_location("generate_workflows", 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") == "workflow-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 Workflow", + "description": "Review a specification", + "author": "Contributor", + "version": "1.2.3", + "license": "MIT", + "repository": "https://github.com/example/workflows", + "documentation": "https://github.com/example/workflows/blob/v1.2.3/README.md", + "changelog": "https://github.com/example/workflows/blob/v1.2.3/CHANGELOG.md", + "url": "https://example.com/v1.2.3/workflow.yml", + "requires": {"speckit_version": ">=1.0.0", "integrations": {"any": ["copilot", "claude"]}}, + "tags": ["review", "planning"], + } + data = {"schema_version": "1.0", "workflows": {"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_complete_static_directory_and_detail_per_entry(tmp_path): + path = ROOT / "workflows/catalog.community.json" + original = path.read_bytes() + entries = json.loads(original)["workflows"] + assert generator.generate(path, tmp_path) == len(entries) + parsed = DirectoryParser() + parsed.feed((tmp_path / "_generated/workflow-directory.md").read_text(encoding="utf-8")) + assert len(parsed.entries) == len(entries) + assert set(parsed.links) == {f"workflows/{workflow_id}.md" for workflow_id in entries} + assert all("hidden" not in entry for entry in parsed.entries) + assert {page.stem for page in (tmp_path / "community/workflows").glob("*.md")} == set(entries) + for workflow_id, entry in entries.items(): + detail = (tmp_path / f"community/workflows/{workflow_id}.md").read_text(encoding="utf-8") + assert generator.escape_metadata(entry["name"]) in detail + assert generator.escape_metadata(entry["url"]) in detail + assert "discovery-only" in detail + assert "do not review, audit, endorse, or support" in detail + assert "shell commands" in detail and "environment values" in detail + assert "not a dry run" in detail + assert "--install-allowed" not in detail + assert path.read_bytes() == original + + +def test_generation_is_deterministic_and_removes_deleted_pages(catalog): + data, path, docs = catalog + other = copy.deepcopy(data["workflows"]["sample"]) + other.update(id="other", name="Another Workflow") + data["workflows"]["other"] = other + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + first = (docs / "_generated/workflow-directory.md").read_bytes() + assert first.index(b"Another Workflow") < first.index(b"Sample Workflow") + generator.generate(path, docs) + assert (docs / "_generated/workflow-directory.md").read_bytes() == first + del data["workflows"]["other"] + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + assert not (docs / "community/workflows/other.md").exists() + assert (docs / "community/workflows/sample.md").is_file() + + +def test_casefold_tied_filters_and_names_have_deterministic_tie_breakers(catalog): + data, path, docs = catalog + data["workflows"]["sample"].update(name="Same", tags=["Review"]) + data["workflows"]["sample"]["requires"]["integrations"]["any"] = ["Copilot"] + other = copy.deepcopy(data["workflows"]["sample"]) + other.update(id="other", name="same", tags=["review"]) + other["requires"]["integrations"]["any"] = ["copilot"] + data["workflows"]["other"] = other + path.write_text(json.dumps(data), encoding="utf-8") + listings = [] + for seed in ("1", "2", "3", "4"): + output = docs / seed + result = subprocess.run( + [sys.executable, str(GENERATOR), "--catalog", str(path), "--docs", str(output)], + env={**os.environ, "PYTHONHASHSEED": seed}, + capture_output=True, text=True, timeout=30, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + listings.append((output / "_generated/workflow-directory.md").read_bytes()) + assert len(set(listings)) == 1 + assert listings[0].index(b"workflows/other.md") < listings[0].index(b"workflows/sample.md") + + +def test_optional_fields_are_not_invented_and_empty_catalog_is_readable(catalog, monkeypatch): + data, path, docs = catalog + entry = data["workflows"]["sample"] + for field in ("repository", "documentation", "changelog", "requires", "tags", "license"): + del entry[field] + path.write_text(json.dumps(data), encoding="utf-8") + monkeypatch.setattr(generator, "urlopen", lambda *args, **kwargs: pytest.fail("No repository to fetch")) + generator.generate(path, docs, fetch_stars=True) + detail = (docs / "community/workflows/sample.md").read_text(encoding="utf-8") + assert "
    Declared integrations
    Not specified
    " in detail + assert "
    Requires Spec Kit
    Not specified
    " in detail + assert "No source repository or documentation links listed" in detail + assert "No SHA-256 digest is listed" in detail + assert "Obtain and verify an integrity digest" in detail + assert "Unavailable" in detail + data["workflows"] = {} + path.write_text(json.dumps(data), encoding="utf-8") + assert generator.generate(path, docs) == 0 + assert "0 workflows" in (docs / "_generated/workflow-directory.md").read_text(encoding="utf-8") + assert not (docs / "community/workflows/sample.md").exists() + + +@pytest.mark.parametrize("has_digest", [True, False]) +def test_workflow_artifact_vetting_and_digest_guidance(catalog, has_digest): + data, path, docs = catalog + if has_digest: + data["workflows"]["sample"]["sha256"] = "a" * 64 + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + detail = (docs / "community/workflows/sample.md").read_text(encoding="utf-8") + assert ("compute the downloaded artifact's SHA-256" in detail) is has_digest + assert ("No SHA-256 digest is listed" in detail) is not has_digest + if has_digest: + assert "compare it with the catalog SHA-256 below" in detail + assert "stop and do not install the artifact" in detail + assert f"{'a' * 64}" in detail + assert "does not use catalog digest\nverification" in detail + assert "raw YAML does not include adjacent scripts or resources" in detail + assert "
    Declared integrations
    Any of: copilot, claude
    " in detail + assert 'href="https://github.com/example/workflows/blob/v1.2.3/CHANGELOG.md"' in detail + assert "not enforced permissions" in detail + + +@pytest.mark.parametrize(("field", "value"), [ + ("id", "../escape"), ("name", None), ("author", ""), ("version", 1), + ("url", "javascript:alert(1)"), ("repository", "https://user:secret@example.com/repo"), + ("documentation", "https://example.com/\nreadme"), ("changelog", "http://example.com/log"), + ("tags", "review"), ("tags", [None]), ("requires", []), + ("requires", {"speckit_version": None}), + ("requires", {"integrations": "copilot"}), + ("requires", {"integrations": {"any": "copilot"}}), + ("requires", {"integrations": {"any": [None]}}), + ("requires", {"integrations": {"unknown": ["copilot"]}}), + ("sha256", "{line_break}{line_break}[injected](javascript:alert%281%29) & |' + entry = data["workflows"]["sample"] + entry.update(name=payload, description=payload, author=payload, version=payload, + license=payload, tags=[payload], created_at=payload, updated_at=payload) + entry["requires"] = {"speckit_version": payload, "integrations": {"any": [payload]}} + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + for generated in (docs / "_generated/workflow-directory.md", docs / "community/workflows/sample.md"): + source = generated.read_text(encoding="utf-8") + assert payload not in source + assert generator.escape_metadata(payload) in source + parsed = DirectoryParser() + parsed.feed((docs / "_generated/workflow-directory.md").read_text(encoding="utf-8")) + assert parsed.scripts == ["../assets/workflow-catalog.js"] + assert json.loads(parsed.entries[0]["data-workflow-tags"]) == [payload] + assert json.loads(parsed.entries[0]["data-workflow-integrations"]) == [payload] + if shutil.which("docfx") is None: + pytest.skip("DocFX is required to verify rendered Markdown") + (docs / "community/workflows.md").write_text( + "# Community Workflows\n\n[!INCLUDE [Directory](../_generated/workflow-directory.md)]\n", + encoding="utf-8", + ) + config = {"build": {"content": [{"files": ["community/**.md"]}], + "dest": "_site", "template": ["default", "modern"]}} + (docs / "docfx.json").write_text(json.dumps(config), encoding="utf-8") + result = subprocess.run( + [shutil.which("docfx"), "docfx.json", "--logLevel", "Error"], + cwd=docs, capture_output=True, text=True, timeout=120, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + for page in ("community/workflows.html", "community/workflows/sample.html"): + rendered = (docs / "_site" / page).read_text(encoding="utf-8") + parsed = DirectoryParser() + parsed.feed(rendered) + assert not any(link.startswith("javascript:") for link in parsed.links) + assert "[injected](javascript:alert%281%29)" in rendered + + +def test_stars_are_build_only_deduplicated_and_include_true_zero(catalog, monkeypatch): + data, path, docs = catalog + other = copy.deepcopy(data["workflows"]["sample"]) + other.update(id="other", repository="https://github.com/EXAMPLE/workflows.git") + data["workflows"]["other"] = other + path.write_text(json.dumps(data), encoding="utf-8") + original = path.read_bytes() + calls = [] + + def fetch(request, timeout): + calls.append(request) + assert timeout == 10 + return io.BytesIO(b'{"stargazers_count":0}') + + monkeypatch.setattr(generator, "urlopen", fetch) + monkeypatch.setenv("GH_TOKEN", "test-token") + generator.generate(path, docs, fetch_stars=True) + assert len(calls) == 1 + assert calls[0].full_url == "https://api.github.com/repos/example/workflows" + assert calls[0].get_header("Authorization") == "Bearer test-token" + listing = (docs / "_generated/workflow-directory.md").read_text(encoding="utf-8") + assert listing.count('aria-label="0 GitHub repository stars"') == 2 + assert ".git/stargazers" not in listing + for workflow_id in data["workflows"]: + assert "
    Repository stars
    0
    " in ( + docs / f"community/workflows/{workflow_id}.md" + ).read_text(encoding="utf-8") + assert path.read_bytes() == original + + +@pytest.mark.parametrize("response", [ + b"invalid JSON", b"[]", b"{}", b'{"stargazers_count":true}', + b'{"stargazers_count":-1}', b'{"stargazers_count":"12"}', + TimeoutError("GitHub timed out"), IncompleteRead(b'{"stargazers_count":', 10), +]) +def test_star_failures_warn_and_render_unavailable(catalog, monkeypatch, capsys, response): + _, path, docs = catalog + + def fetch(*args, **kwargs): + if isinstance(response, Exception): + raise response + return io.BytesIO(response) + + monkeypatch.setattr(generator, "urlopen", fetch) + assert generator.generate(path, docs, fetch_stars=True) == 1 + assert "Warning: stars unavailable for example/workflows:" in capsys.readouterr().err + assert "Stars unavailable" in (docs / "_generated/workflow-directory.md").read_text(encoding="utf-8") + assert "
    Repository stars
    Unavailable
    " in ( + docs / "community/workflows/sample.md" + ).read_text(encoding="utf-8") + + +def test_only_github_receives_token_and_offline_generation_makes_no_requests(catalog, monkeypatch, capsys): + data, path, docs = catalog + monkeypatch.setenv("GH_TOKEN", "test-token") + monkeypatch.setattr(generator, "urlopen", lambda *args, **kwargs: pytest.fail("Unexpected API request")) + generator.generate(path, docs) + data["workflows"]["sample"]["repository"] = "https://example.com/workflows" + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs, fetch_stars=True) + assert "not a GitHub repository URL" in capsys.readouterr().err + + +def test_stars_without_token_are_available(catalog, monkeypatch): + _, path, docs = catalog + monkeypatch.delenv("GH_TOKEN", raising=False) + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + + def fetch(request, timeout): + assert request.get_header("Authorization") is None + return io.BytesIO(b'{"stargazers_count":1234}') + + monkeypatch.setattr(generator, "urlopen", fetch) + generator.generate(path, docs, fetch_stars=True) + assert 'aria-label="1,234 GitHub repository stars"' in ( + docs / "_generated/workflow-directory.md" + ).read_text(encoding="utf-8") + + +@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is required to exercise directory controls") +def test_search_integration_tag_sort_empty_state_url_and_reset(catalog): + data, path, docs = catalog + other = copy.deepcopy(data["workflows"]["sample"]) + other.update(id="other", name="Another Workflow", tags=["design"]) + other["requires"]["integrations"]["any"] = ["gemini"] + data["workflows"]["other"] = other + path.write_text(json.dumps(data), encoding="utf-8") + generator.generate(path, docs) + parsed = DirectoryParser() + parsed.feed((docs / "_generated/workflow-directory.md").read_text(encoding="utf-8")) + result = subprocess.run( + [shutil.which("node"), "-e", r""" +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const vm = require("node:vm"); +const input = JSON.parse(fs.readFileSync(0, "utf8")); +const entries = input.entries.map((attrs) => ({ + hidden: false, + dataset: { + workflowSearch: attrs["data-workflow-search"], + workflowIntegrations: attrs["data-workflow-integrations"], + workflowTags: attrs["data-workflow-tags"], + }, +})); +const fields = Object.fromEntries(["q", "tag", "integration", "sort"].map((key) => [key, {value: ""}])); +const handlers = {}; +const form = { + hidden: true, + elements: {namedItem: (name) => fields[name]}, + addEventListener: (event, handler) => { handlers[event] = handler; }, +}; +const list = { + children: [...entries], + append: (entry) => { + list.children.splice(list.children.indexOf(entry), 1); + list.children.push(entry); + }, +}; +const status = {}; +const empty = {}; +const elements = { + "[data-workflow-controls]": form, ".workflow-results": list, + "[data-workflow-status]": status, "[data-workflow-empty]": empty, +}; +let current = new URL("https://example.com/community/workflows.html?q=REVIEW&integration=claude&tag=planning&sort=za&keep=1"); +vm.runInNewContext(input.script, { + document: {querySelector: () => ({querySelector: (key) => elements[key]})}, + window: { + location: current, + history: {replaceState: (_state, _title, url) => { current = url; }}, + }, + URL, URLSearchParams, +}); +const visible = () => list.children.filter((entry) => !entry.hidden); +assert.equal(form.hidden, false); +assert.equal(visible().length, 1); +assert.equal(status.textContent, "1 of 2 workflows"); +fields.q.value = "missing"; +handlers.input(); +assert.equal(visible().length, 0); +assert.equal(empty.hidden, false); +handlers.reset(); +assert.equal(visible().length, 2); +assert.equal(empty.hidden, true); +assert.equal(list.children[0].dataset.workflowIntegrations, '["gemini"]'); +assert.equal(current.search, "?keep=1"); +fields.sort.value = "za"; +handlers.change(); +assert.equal(list.children[0].dataset.workflowIntegrations, '["copilot", "claude"]'); +fields.integration.value = "gemini"; +handlers.change(); +assert.equal(visible().length, 1); +fields.tag.value = "planning"; +handlers.change(); +assert.equal(visible().length, 0); +handlers.reset(); +fields.q.value = "Sample Contributor"; +let prevented = false; +handlers.submit({preventDefault: () => { prevented = true; }}); +assert.equal(prevented, true); +assert.equal(visible().length, 1); +"""], + input=json.dumps({ + "entries": parsed.entries, + "script": (ROOT / "docs/assets/workflow-catalog.js").read_text(encoding="utf-8"), + }), + capture_output=True, text=True, timeout=30, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_catalog_updates_trigger_generation_in_existing_normal_and_weekly_deployment(): + workflow = yaml.safe_load((ROOT / ".github/workflows/docs.yml").read_text(encoding="utf-8")) + assert "workflows/catalog.community.json" in workflow[True]["push"]["paths"] + assert workflow[True]["schedule"] == [{"cron": "17 4 * * 1"}] + assert workflow["permissions"] == {"contents": "read", "pages": "write", "id-token": "write"} + assert workflow["jobs"]["build"]["if"] == "github.repository == 'github/spec-kit'" + steps = workflow["jobs"]["build"]["steps"] + generation = next(index for index, step in enumerate(steps) + if step.get("run") == "python3 docs/generate_workflows.py --fetch-stars") + assert steps[generation]["env"] == {"GH_TOKEN": "${{ github.token }}"} + build = next(index for index, step in enumerate(steps) if "docfx docfx.json" in step.get("run", "")) + assert generation < build + assert all("if" not in step for step in steps) + config = json.loads((ROOT / "docs/docfx.json").read_text(encoding="utf-8")) + assert "community/workflows/*.md" in config["build"]["content"][0]["files"] + assert "assets/**" in config["build"]["resource"][0]["files"] + page = (ROOT / "docs/community/workflows.md").read_text(encoding="utf-8") + assert "[!INCLUDE [Community workflow directory](../_generated/workflow-directory.md)]" in page + assert "| Workflow |" not in page + publishing = (ROOT / "docs/workflows/publishing.md").read_text(encoding="utf-8") + assert "Do not\nmaintain a separate Markdown listing" in publishing + assert "There is no workflow-definition submission issue form" in publishing