spec-kit icon indicating copy to clipboard operation
spec-kit copied to clipboard

Add workflow step catalog — community-installable step types

Open Copilot opened this issue 7 months ago • 26 comments

The workflow engine shipped with a dynamic STEP_REGISTRY but no distribution mechanism for community-authored step types. This adds a full catalog system for discovering, installing, and managing custom step types, following the same patterns as the workflow/extension catalogs.

New classes (workflows/catalog.py)

  • StepRegistry — persists installed custom steps in .specify/workflows/steps/step-registry.json; validates JSON shape on load and falls back to a clean default on corruption or unreadable files. save() catches OSError and re-raises StepValidationError so read-only/permission failures surface as a clean CLI error instead of an unhandled exception.
  • StepCatalog — multi-source catalog stack with SHA256-based caching; resolves SPECKIT_STEP_CATALOG_URL env var → .specify/step-catalogs.yml → ~/.specify/step-catalogs.yml → built-in defaults (step-catalog.json + step-catalog.community.json)
  • StepCatalogError / StepValidationError / StepCatalogEntry supporting types

Dynamic step loading (workflows/__init__.py)

load_custom_steps(project_root) scans .specify/workflows/steps/, dynamically imports each package's __init__.py, finds the StepBase subclass matching the declared type_key, and registers it into STEP_REGISTRY. Each step directory is imported as a proper Python package (with submodule_search_locations set and pre-registered in sys.modules) so that relative imports within a step package (e.g. from .helpers import ...) work correctly. type_key values are sanitized to valid Python identifiers and suffixed with an 8-char SHA-256 hash of the original type_key (e.g. test-custom → _speckit_custom_step_test_custom_<hash>) — the hash suffix makes module names collision-resistant when different type_key values produce the same sanitized form (e.g. "a-b" and "a_b"). Broken packages are silently skipped. Dynamic imports are intentionally deferred to workflow execution time — load_custom_steps() is called in the workflow run and workflow resume CLI entrypoints before engine validation/execution so installed step types are usable. CLI metadata commands (list, info) read from StepRegistry and step.yml only and never execute installed step code.

CLI surface (specify workflow step …)

specify workflow step list              # built-in + installed custom types
specify workflow step add <id>          # fetch step.yml + __init__.py (+ extra_files), validate, install
specify workflow step remove <id>       # delete package dir + registry entry
specify workflow step search [query]    # search across all configured catalogs
specify workflow step info <id>         # detail view (built-in or custom)
specify workflow step catalog list      # show active catalog sources
specify workflow step catalog add <url> # add catalog to .specify/step-catalogs.yml
specify workflow step catalog remove <n># remove by index

add validates that the downloaded step.yml's type_key matches the catalog ID and that all fetches use HTTPS before writing anything to disk. Catalog entries may include an optional extra_files dict (relative-path → URL) to install additional package files (e.g. helper modules) alongside step.yml and __init__.py — each extra file is HTTPS-validated, path-traversal-checked against the resolved staging directory, and downloaded before the atomic rename. Downloads happen in a staging directory under steps_base_dir and are moved into place atomically via os.rename() only after all validation passes — a transient failure never corrupts or deletes any pre-existing data, and install is refused if the target directory already exists.

remove allows cleaning up an orphaned step directory (e.g. after a registry reset due to corruption) even when the registry entry is missing — it prints a warning and removes the directory so a fresh install can be attempted. It still errors if neither the directory nor the registry entry exists.

Catalog files

  • workflows/step-catalog.json — official catalog (empty, ready for entries)
  • workflows/step-catalog.community.json — community catalog (empty, ready for entries)

Robustness & security hardening

  • Strict step_id validation: add and remove both call a shared _validate_step_id_or_exit() helper that requires step_id to be a single safe path component — empty strings, path separators (//\), ./.. parts, dotfile prefixes, and reserved names (.cache, step-registry.json) are all rejected before any filesystem operation. After resolve(), an additional defense-in-depth check asserts step_dir.relative_to(steps_base_dir).parts == (step_id,), so tricks like foo/.. (which previously resolved within steps_base_dir and passed relative_to()) cannot target internal directories or cause rmtree to delete the entire steps base.
  • Path traversal guard: extra_files paths are validated by resolving both the destination and the staging base directory before relative_to(), correctly handling symlinks.
  • Collision guard: step add rejects IDs that collide with built-in or already-installed step types.
  • Atomic install: step add downloads and validates in a staging temp dir under steps_base_dir (same filesystem as the destination), then atomically renames into place via os.rename(); install is refused if the target directory already exists.
  • URL validation: All URL validation checks parsed.hostname (not just parsed.netloc or scheme alone) to correctly reject hostless URLs such as https://:80/path — enforced in _validate_catalog_url(), _safe_fetch(), and the fetch-time _validate_url() helpers in both WorkflowCatalog and StepCatalog.
  • Authenticated fetches: _safe_fetch() (used by workflow step add) and StepCatalog._fetch_single_catalog() route through specify_cli.authentication.http.open_url() to support auth.json-based credentials and safe redirect auth stripping, consistent with all other network fetches in the CLI.
  • Cache resilience: catalog cache writes are wrapped in try/except OSError so a read-only filesystem never aborts a successful HTTP fetch.
  • Registry resilience: StepRegistry._load() validates the on-disk JSON shape and catches OSError/UnicodeError, falling back to a clean default on any read failure. StepRegistry.save() translates OSError into StepValidationError so write failures (read-only fs, permission denied) produce a clean CLI error.
  • Catalog config resilience: StepCatalog.add_catalog() and remove_catalog() wrap yaml.safe_load() in try/except (yaml.YAMLError, OSError, UnicodeDecodeError) so a malformed or unreadable .specify/step-catalogs.yml raises a clean StepValidationError instead of an unhandled exception.
  • Empty YAML tolerance: StepCatalog.add_catalog() treats an empty .specify/step-catalogs.yml as an empty mapping rather than a corruption error.
  • Non-dict extra_files tolerance: A warning is printed when a catalog entry's extra_files field is present but not a mapping, and the field is safely ignored.

Tests

35+ tests across TestStepRegistryCustom, TestStepCatalog, TestLoadCustomSteps, and TestWorkflowStepRemoveCLI covering CRUD, catalog resolution (env var / project / user / default), URL validation, search, dynamic loading edge cases, registry shape validation, unreadable-file fallback, empty YAML initialization, module name sanitization and collision-resistance for hyphenated type keys, package-style relative imports within custom step packages, and step remove CLI behavior (registered, orphaned, and fully-missing cases). The chmod-based unreadability test is skipped on Windows.

Copilot avatar Apr 28 '26 17:04 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 06 '26 22:05 mnriem

@copilot apply changes based on the comments in this thread

Applied all changes from the review thread in commits e311afb and df061e0:

  • StepRegistry._load() — now validates the loaded JSON is a dict with a dict steps field (resets malformed steps to {}), and catches OSError/UnicodeError so unreadable files fall back to the default structure instead of crashing CLI commands.
  • StepCatalog.add_catalog() — changed yaml.safe_load(...) to yaml.safe_load(...) or {} so an empty .specify/step-catalogs.yml is treated as an empty mapping and can be initialized by the command.

Three new tests cover these cases: malformed steps key, unreadable registry file (with functional-after-fallback assertion), and empty YAML config file.

Copilot avatar May 06 '26 22:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 06 '26 22:05 mnriem

@copilot apply changes based on the comments in this thread

Applied all changes from the review thread in commits 3e30520 and 1e5f5fd:

  • No dynamic imports in list/info: Removed load_custom_steps() from workflow_step_list() and workflow_step_info(). Both commands now read only from StepRegistry (disk metadata) — no arbitrary step code is executed.
  • Atomic install in step add: Downloads and validation now happen in a tempfile.mkdtemp() temp dir. The temp dir is moved to step_dir only after all validation passes. Pre-existing step_dir is removed before the move (to avoid shutil.move creating a nested subdirectory). finally ensures temp dir cleanup on any failure.
  • _validate_catalog_url(): Changed parsed.netloc → parsed.hostname to correctly reject hostless URLs like https://:80/path.
  • Cache writes: Wrapped cache_dir.mkdir() + file writes in try/except OSError in both WorkflowCatalog and StepCatalog so a read-only filesystem doesn't abort a successful HTTP fetch.
  • test_registry_unreadable_file_resets: Added @pytest.mark.skipif(sys.platform == "win32", ...) to skip the chmod(0o000) test on Windows.

Copilot avatar May 06 '26 23:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 07 '26 13:05 mnriem

@copilot apply changes based on the comments in this thread

Applied all changes from the review thread in commit bf0af27:

  • workflow_run / workflow_resume: Added load_custom_steps(project_root) before WorkflowEngine construction so installed custom step types are registered into STEP_REGISTRY before validation and execution.
  • _safe_fetch(): Added parsed.hostname check for both the initial URL and any redirect, rejecting hostless URLs (e.g. https://:80/path) before urlopen is called.
  • _validate_url() in _fetch_single_catalog(): Added parsed.hostname check in both StepCatalog and WorkflowCatalog fetch helpers, consistent with _validate_catalog_url().

Copilot avatar May 07 '26 13:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 07 '26 17:05 mnriem

@copilot apply changes based on the comments in this thread

Applied both changes from the review thread in commit c310420:

  • add_catalog() / remove_catalog(): Wrapped yaml.safe_load() calls in try/except (yaml.YAMLError, OSError, UnicodeDecodeError) so a malformed or unreadable .specify/step-catalogs.yml raises a clean StepValidationError with a helpful message instead of propagating an unhandled exception.
  • workflow_step_add() — atomic install: Replaced shutil.move() (which could fail non-atomically across filesystems) with:
    • An upfront refusal when step_dir already exists (with a clear error pointing to specify workflow step remove)
    • Staging the temp dir under steps_base_dir (same filesystem as the destination)
    • os.rename() for a truly atomic POSIX rename
    • finally cleans up the temp dir if os.rename() hasn't moved it yet

Copilot avatar May 07 '26 17:05 Copilot

@copilot apply changes based on the comments in this thread and also resolve conflicts

mnriem avatar May 07 '26 18:05 mnriem

@copilot apply changes based on the comments in this thread and also resolve conflicts

Applied all changes from the review thread and resolved the merge conflict in commit b3d0cf6:

  • WorkflowCatalog._validate_catalog_url(): Changed parsed.netloc → parsed.hostname to consistently reject hostless URLs like https://:80/path at config-add time (matching StepCatalog's existing implementation).
  • StepCatalog._load_catalog_config(): Added isinstance(data, dict) check after yaml.safe_load() so a YAML list/string at the root raises StepValidationError instead of crashing with AttributeError.
  • workflow_step_add(): Added isinstance(meta, dict) and isinstance(step_meta, dict) guards after parsing step.yml, giving clear CLI error messages for invalid YAML shapes.
  • Merge conflict resolved: workflow_run/workflow_resume now use _require_specify_project() (introduced in main) followed by load_custom_steps(project_root).

Copilot avatar May 07 '26 18:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 08 '26 19:05 mnriem

@copilot apply changes based on the comments in this thread

Applied both changes in commits b56e6fc and a2a2c70:

  • load_custom_steps() — proper package imports: Moved import re and import sys outside the loop (to the top of the function). The step directory is now imported as a proper Python package: spec_from_file_location(..., submodule_search_locations=[str(step_dir)]), module.__package__ is set, and the module is registered in sys.modules before exec_module so that relative imports (e.g. from .helpers import ...) resolve correctly. The module name is sanitized via re.sub(r"[^A-Za-z0-9_]", "_", type_key) so type_keys like test-custom produce a valid Python identifier (_speckit_custom_step_test_custom). If exec_module raises, the entry is cleaned from sys.modules.
  • workflow_step_add() — reserved ID guard: Added a _RESERVED_STEP_IDS frozenset at module level (.cache, step-registry.json) and reject any step_id that starts with . or is in that set, before creating any staging directory.
  • Added two new tests: test_module_name_sanitized_for_hyphenated_type_key and test_package_relative_import in TestLoadCustomSteps.

Copilot avatar May 08 '26 19:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 11 '26 15:05 mnriem

@copilot apply changes based on the comments in this thread

Applied all three changes from the review thread:

  • Collision-resistant module names (workflows/__init__.py): Synthetic module names now include an 8-char SHA-256 hash of the original type_key (e.g. _speckit_custom_step_a_b_<hash>), so "a-b" and "a_b" produce different module names even though they sanitize to the same form. Updated the two tests that asserted exact module names and added a new test_module_name_collision_resistance test.

  • Multi-file step install (__init__.py): workflow step add now supports an optional extra_files dict in catalog entries (mapping relative path → URL). Each extra file is downloaded via _safe_fetch (HTTPS-validated) and written into the staging directory before the atomic rename. Path traversal is blocked by resolving both the destination and the base directory before calling relative_to() (handles symlinks). A warning is emitted when extra_files is present but is not a mapping.

  • step remove registry fallback (__init__.py): workflow step remove no longer requires a registry entry to proceed. When the step directory exists but the registry entry is missing (e.g. after a corruption-triggered reset), it prints a warning and removes the orphaned directory so a fresh install can be attempted. It still errors if neither the directory nor the registry entry exists. Three new CLI-level tests cover all cases.

Commits: 8d91965, 7432fe5

Copilot avatar May 11 '26 15:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 11 '26 20:05 mnriem

@copilot apply changes based on the comments in this thread

Applied in commit 4e7490e:

  • _safe_fetch() in __init__.py: Replaced from urllib.request import urlopen + urlopen(...) with from specify_cli.authentication.http import open_url as _open_url + _open_url(...). All existing HTTPS/hostname pre- and post-redirect validation is preserved.
  • StepCatalog._fetch_single_catalog() in workflows/catalog.py: Same swap — urlopen → _open_url from the authentication module. The redirect URL check via resp.geturl() is retained.

Copilot avatar May 11 '26 20:05 Copilot

@copilot+claude-opus-4.7 apply changes based on the comments in this thread

mnriem avatar May 12 '26 13:05 mnriem

@copilot+claude-opus-4.7 apply changes based on the comments in this thread

Applied all three changes in commit 4f2d3eb:

  • workflow_step_add — step_id hardening: Added a _validate_step_id_or_exit() helper that rejects empty IDs, path separators (//\), ./.. components, dotfile prefixes (.cache, etc.), and reserved names (step-registry.json). The helper runs before any filesystem operation. After resolve(), an additional defense-in-depth check confirms step_dir.relative_to(steps_base_dir).parts == (step_id,), so tricks like foo/.. (which previously resolved within steps_base_dir and passed relative_to()) are now rejected.
  • workflow_step_remove — step_id hardening: Same _validate_step_id_or_exit() + rel_parts == (step_id,) check, so foo/.. can no longer resolve to steps_base_dir itself and cause shutil.rmtree(step_dir) to delete the entire .specify/workflows/steps directory.
  • StepRegistry.save(): Now wraps mkdir/open/json.dump in try/except OSError and re-raises StepValidationError with a clear message. add()/remove() no longer propagate an unhandled OSError on read-only filesystems or permission errors, so the CLI exits cleanly and users get an actionable message.

All 36 step-related tests pass; ruff and CodeQL are clean.

Copilot avatar May 12 '26 13:05 Copilot

@copilot apply changes based on the comments in this thread

mnriem avatar May 12 '26 15:05 mnriem

@copilot apply changes based on the comments in this thread

Applied all three changes in commit 05771d0:

  • load_custom_steps(): Restructured the per-step logic so that a registered flag tracks successful registration, and a finally block always pops the synthetic module name from sys.modules on any non-success path (failed exec_module, no matching StepBase subclass, or exception during instantiation/registration). Broken/skipped step packages no longer leave lingering import state behind.
  • workflow_step_add(): Wrapped registry.add() in try/except StepValidationError; on failure the just-installed step directory is rolled back via shutil.rmtree(step_dir, ignore_errors=True) and the CLI exits cleanly so the system isn't left with an unregistered package on disk.
  • workflow_step_remove(): Wrapped registry.remove() in try/except StepValidationError so a registry write failure (read-only fs, permission denied) surfaces as a clean CLI error instead of an unhandled exception after the directory has been deleted.

Copilot avatar May 12 '26 15:05 Copilot