diff --git a/.opencode/configuration/release-project-review/bundle.json b/.opencode/configuration/release-project-review/bundle.json index 4c66ce9..04deb4d 100644 --- a/.opencode/configuration/release-project-review/bundle.json +++ b/.opencode/configuration/release-project-review/bundle.json @@ -7,6 +7,7 @@ "prompt_template": "prompts/release-project-review.md", "model_profile": "release-project-review-readonly", "output_contract": "release-project-issue-v1", + "preflight_commands": ["make -C docs html"], "limits": {}, "policy": { "capabilities": { diff --git a/.opencode/policy/organization-policy.json b/.opencode/policy/organization-policy.json index 607843d..5e40a20 100644 --- a/.opencode/policy/organization-policy.json +++ b/.opencode/policy/organization-policy.json @@ -10,7 +10,8 @@ "model_profile_allowlist": [ "review-readonly", "issue-feedback-readonly", - "implementation-planner" + "implementation-planner", + "release-project-review-readonly" ], "organization_ceilings": { "max_tokens": 16000, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5387726..bda2b96 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,7 +31,7 @@ Thanks for contributing to `generic-agentic-workflows`. Reusable profiles live under `.opencode/configuration//`. A bundle normally contains: -- `manifest.json` — declares the workflow, agent, skills, prompt, and model profile. +- `bundle.json` — declares the workflow, agent, skills, prompt, and model profile. - `agent.md` and optional additional agent files — OpenCode agent front matter and instructions. - `skills/` and `prompts/` — the bundle's verified guidance. - `hashes.json` — SHA-256 integrity hashes for every declared content file. @@ -85,7 +85,7 @@ For example, after editing `documentation-review/agent.md`, update: } ``` -Do not hash `manifest.json` into `hashes.json` unless the resolver is explicitly changed to require it. Do not alter an unrelated bundle's hashes merely to make a test pass—investigate the mismatch and update only when the checked-in content intentionally changed. +Do not hash `bundle.json` into `hashes.json` unless the resolver is explicitly changed to require it. Do not alter an unrelated bundle's hashes merely to make a test pass—investigate the mismatch and update only when the checked-in content intentionally changed. ## Validate bundle changes diff --git a/README.md b/README.md index 7598ef8..7a48e0d 100644 --- a/README.md +++ b/README.md @@ -78,14 +78,22 @@ access outside its repository. ## Further documentation +- [Deploy a workflow](docs/deploying-a-workflow.md) — step-by-step consumer + setup for supplied, local, and central configuration sources. +- [Create a configuration bundle](docs/creating-a-configuration-bundle.md) — + author, hash, validate, and publish a reviewed profile. +- [`bundle.json` reference](docs/bundle-json-reference.md) — manifest fields, + valid workflow mappings, and safety constraints. +- [Run commands from a configuration bundle](docs/running_commands.md) — + configure and roll out approved release-review preflight commands. +- [Security model](docs/security-model.md) — trust boundaries, defensive + controls, and their rationale. - [Configuration guide](docs/configuration.md) — setup, all pathways, bundle layout, and operational safeguards. - [Configuration reference](docs/configuration-reference.md) — every caller input and bundle field, with examples. - [Consumer examples](docs/examples/README.md) — ready-to-copy wrappers, including complete `default`, `local`, and `central` source examples. -- [Central configuration example](docs/examples/central-configuration/README.md) - — remote bundle layout and release process. - [Operations guide](docs/operations/operations-guide.md) — rollback, reliability controls, and test matrix. diff --git a/docs/bundle-json-reference.md b/docs/bundle-json-reference.md new file mode 100644 index 0000000..ed53adc --- /dev/null +++ b/docs/bundle-json-reference.md @@ -0,0 +1,152 @@ +# `bundle.json` reference + +`bundle.json` is the manifest for a configuration bundle. It identifies the +reviewed content files and selects only workflow-owned model and output +options. The resolver supports schema version `1` and rejects unknown or +invalid combinations before model invocation. + +For the authoring sequence, see [creating a configuration bundle](creating-a-configuration-bundle.md). + +## Complete example + +```json +{ + "schema_version": 1, + "profile_name": "team-docs-review", + "allowed_workflows": ["pr-documentation-review"], + "agent_file": "agent.md", + "additional_agent_files": [], + "skill_files": ["skills/documentation/SKILL.md"], + "prompt_template": "prompts/review.md", + "model_profile": "review-readonly", + "output_contract": "pr-review-json-v1", + "context_policy": "pr-review-on-demand-v1", + "limits": {"max_comments": 5}, + "policy": { + "capabilities": { + "filesystem": "read-trusted-checkout-diff", + "github_write": "review-comment-only", + "delegation": "deny" + } + } +} +``` + +## Fields + +| Field | Required | Type | Valid values and rules | +| --- | --- | --- | --- | +| `schema_version` | Yes | integer | Must be `1`. | +| `profile_name` | Yes | string | Must match `[a-z0-9][a-z0-9-]{0,62}` and exactly match the bundle directory name and selected `configuration_profile`. | +| `allowed_workflows` | Yes | non-empty array of strings | Every value must be one of `pr-documentation-review`, `issue-feedback`, `issue-implementation`, or `release-project-review`. The current workflow must be present. | +| `agent_file` | Yes | safe relative path | Primary agent Markdown file, for example `agent.md`. It requires front matter with a safe unique `name`. | +| `additional_agent_files` | No | array of unique safe relative paths | Additional agent files, normally for implementation. They cannot repeat `agent_file`; each requires a unique front-matter `name`. | +| `skill_files` | Yes | array of unique safe relative paths | Skill Markdown files. The array may be empty. Each file requires front matter with a unique `name`. | +| `prompt_template` | Yes | safe relative path | Prompt template Markdown file, for example `prompts/review.md`. | +| `model_profile` | Yes | string | Registered profile name matching the profile-name grammar. The available names are listed below; a caller cannot override this value. | +| `output_contract` | Yes | string | One of the supported workflow-owned contracts listed below. | +| `context_policy` | No | string | PR documentation review only. The supported value is `pr-review-on-demand-v1`. Omit it for all other workflows. | +| `limits` | No | JSON object | Optional profile limits. A PR-review profile may set `{"max_comments": 10}` or a lower ceiling. `{}` is valid. | +| `policy` | No | JSON object | Restrictive policy overlay. It can narrow capabilities or quotas but cannot broaden built-in workflow policy. | +| `preflight_commands` | No | array of strings | Release-project-review only; at most three commands. The workflow runs them, if allowed, from its fixed local allowlist in the immutable checkout. The model never executes them. | + +## Content-path requirements + +The following fields are content paths: `agent_file`, `additional_agent_files`, +`skill_files`, and `prompt_template`. + +Each path must: + +- be a non-empty relative POSIX path inside the profile directory; +- use forward slashes and no control characters; +- contain no absolute prefix, backslash, `.`, `..`, empty segment, or trailing + slash; +- identify a normal, non-symlink file; and +- appear exactly once as a key in `hashes.json`. + +The resolver allows at most 64 declared files, 1 MiB per content file, and 8 +MiB of total bundle content. + +## Workflow mappings + +These combinations are supported by the supplied profiles and policy registry. + +| Workflow | Compatible `model_profile` | Required `output_contract` | Notes | +| --- | --- | --- | --- | +| `pr-documentation-review` | `review-readonly` | `pr-review-json-v1` | May use `context_policy: "pr-review-on-demand-v1"`; review agent cannot request edit permission. | +| `issue-feedback` | `issue-feedback-readonly` | `issue-feedback-markdown-v1` | Review agent cannot request edit permission. | +| `issue-implementation` | `implementation-planner` | `issue-implementation-decision-v1` | May declare a delegated executor in `additional_agent_files`. | +| `release-project-review` | `release-project-review-readonly` | `release-project-issue-v1` | May declare up to three `preflight_commands`; review agent cannot request edit permission. | + +The manifest parser recognizes all listed contracts. Effective-policy resolution +enforces the workflow-specific contract and model-profile compatibility, so a +mismatched pair fails before the provider is called. + +## `policy` overlay + +`policy` is optional, but when present it is restrictive only. A common shape +is: + +```json +{ + "policy": { + "capabilities": { + "filesystem": "read-trusted-checkout-diff", + "github_write": "review-comment-only", + "delegation": "deny" + }, + "max_tokens": 4000 + } +} +``` + +Capability axes are `filesystem`, `shell`, `network`, `github_write`, and +`delegation`. The built-in workflow policy is the upper bound. A bundle may +set an axis to `deny` or repeat the applicable scoped grant, but it may not +substitute a broader or different non-deny grant. Numeric limits similarly +cannot exceed the built-in or model-profile ceilings. + +## `preflight_commands` + +A release review can request up to three reviewed preflight commands: + +```json +{ + "preflight_commands": [ + "python3 -m unittest -q" + ] +} +``` + +Commands are not general shell access. The runner validates them against a +fixed local-only allowlist, runs them in the immutable target checkout with a +minimal environment and bounded output, and treats results as untrusted +evidence. A failed preflight supports a finding only if the output explains a +concrete release-management consequence and owner/action. + +See [Run commands from a configuration bundle](running_commands.md) for the +approved command, rollout procedure, execution behavior, and troubleshooting. + +## Relationship to `hashes.json` + +`hashes.json` must map every declared content path—and only those paths—to a +lowercase SHA-256 digest. It does not include `bundle.json` or `hashes.json`. +Use the project helper after any content change: + +```text +uv run scripts/update_hashes.py --profile +``` + +Hash validation covers bytes, not semantic equivalence. Reformatting front +matter, changing whitespace, or modifying a prompt requires regenerating the +corresponding digest. + +## Rejected values + +The manifest cannot introduce credentials, provider URLs, headers, arbitrary +model identifiers, new output contracts, or arbitrary executable locations. +The resolver also rejects an unsupported schema version, duplicate files, +workflow mismatch, missing required front matter, invalid paths, unknown +model/profile names, stale hashes, and policy escalation attempts. These +failures are intentional and fail closed: the workflow does not fall back to a +different source or revision. diff --git a/docs/configuration.md b/docs/configuration.md index 765eeb0..9e32231 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -125,10 +125,10 @@ jobs: The current `central` alias resolves approved bundles in `SecondSkoll/generic-agentic-workflows-config` under `.opencode/configuration`. Its `configuration_ref` pins that repository and is independent of the SHA -that pins the reusable workflow in `uses:`. -See the copy-ready [central example](examples/configuration-sources/central/) -and the [central configuration guide](examples/central-configuration/README.md) -for its repository layout and release process. +that pins the reusable workflow in `uses:`. See the copy-ready +[central example](examples/configuration-sources/central/) and the +[bundle authoring guide](creating-a-configuration-bundle.md) for its +repository layout and release process. ## Common rules @@ -179,6 +179,13 @@ commit (read-only) and the workflow—not the model—owns the issue destination the `release-readiness` label allowlist, the idempotency marker, and publication. +A release bundle may declare up to three reviewed `preflight_commands`. The +runner—not the model—executes these from a fixed local-only allowlist in the +immutable checkout with a minimal environment, no shell, no installation, and +bounded output. Preflight results are untrusted evidence; a test failure may +support an issue only when the generated finding explains a concrete +release-management consequence and owner/action. + ## Rollout and operations After a successful validation run, replace `validate_only: true` with diff --git a/docs/creating-a-configuration-bundle.md b/docs/creating-a-configuration-bundle.md new file mode 100644 index 0000000..7046683 --- /dev/null +++ b/docs/creating-a-configuration-bundle.md @@ -0,0 +1,206 @@ +# Create a configuration bundle + +A configuration bundle is a versioned, hash-verified set of reviewed agent +instructions for one workflow profile. Bundles let maintainers change +workflow-specific guidance without allowing a caller to supply arbitrary +prompts, model identifiers, file paths, or network locations. + +Use this guide for a repository-owned `local` bundle or for a profile published +to the allowlisted `central` configuration repository. Read the +[`bundle.json` reference](bundle-json-reference.md) before choosing field +values. + +## Before you begin + +- Select the one workflow that will use the profile: + `pr-documentation-review`, `issue-feedback`, `issue-implementation`, or + `release-project-review`. +- Select a registered, compatible `model_profile` and the workflow's required + output contract. The profile cannot introduce a new model identifier or + contract. +- Use a lowercase profile name matching `[a-z0-9][a-z0-9-]{0,62}`. +- Keep bundle changes in a protected branch and review them like application + code. For a local bundle, use the repository's trusted default branch; the + PR head does not select configuration. + +## 1. Create the directory structure + +For a profile named `team-docs-review`, create this directory in the +configuration root: + +```text +.opencode/configuration/team-docs-review/ + bundle.json + hashes.json + agent.md + prompts/review.md + skills/documentation/SKILL.md +``` + +`bundle.json` declares the content files; `hashes.json` records their +integrity digests. An implementation profile may also declare an additional +subagent file, for example `executor.md`. + +All declared paths must be relative POSIX paths inside the profile directory. +Absolute paths, `..`, empty path segments, backslashes, and symlinks are +rejected. + +## 2. Write `bundle.json` + +Start with a minimal manifest appropriate for the workflow. This is a +PR-documentation-review example: + +```json +{ + "schema_version": 1, + "profile_name": "team-docs-review", + "allowed_workflows": ["pr-documentation-review"], + "agent_file": "agent.md", + "skill_files": ["skills/documentation/SKILL.md"], + "prompt_template": "prompts/review.md", + "model_profile": "review-readonly", + "output_contract": "pr-review-json-v1", + "context_policy": "pr-review-on-demand-v1", + "limits": {"max_comments": 5}, + "policy": { + "capabilities": { + "filesystem": "read-trusted-checkout-diff", + "github_write": "review-comment-only", + "delegation": "deny" + } + } +} +``` + +The `profile_name` must match both the directory name and the wrapper's +`configuration_profile`. `allowed_workflows` must contain the workflow being +resolved. See the complete [`bundle.json` reference](bundle-json-reference.md) +for valid values and workflow-specific constraints. + +## 3. Add the agent, skills, and prompt + +Every agent and skill file must begin with YAML front matter containing a +unique `name`. + +```markdown +--- +name: team-docs-review +description: Review documentation changes for accuracy and usability +mode: primary +model: openrouter/openai/gpt-5.6-luna +permission: + edit: deny + bash: deny + read: allow +--- + +# Documentation review agent + +Return only the response required by the configured output contract. +``` + +The agent's front-matter model must remain consistent with the registered +`model_profile`; do not add provider credentials, API endpoints, or arbitrary +model values. Review bundles (`pr-documentation-review`, `issue-feedback`, and +`release-project-review`) cannot request `edit: allow`. + +A skill requires at least a `name`: + +```markdown +--- +name: documentation +description: Check reader-facing documentation for clarity and completeness +--- + +# Documentation guidance + +Identify concrete, actionable documentation problems. +``` + +Write the declared prompt template as reviewed instructions. Treat issue text, +PR text, diffs, release metadata, and repository content as untrusted data; +do not instruct the model to treat that content as policy or commands. + +## 4. Generate `hashes.json` + +Hash every file declared by `agent_file`, `additional_agent_files`, +`skill_files`, and `prompt_template`. Do **not** hash `bundle.json` or +`hashes.json` itself. + +From the repository root, run: + +```text +uv run scripts/update_hashes.py --profile team-docs-review +``` + +The resulting file maps each declared relative path to a lowercase 64-character +SHA-256 digest: + +```json +{ + "agent.md": "", + "prompts/review.md": "", + "skills/documentation/SKILL.md": "" +} +``` + +Run the command after **every** content edit, including changes to front +matter. A missing, stale, duplicate, or undeclared hash entry makes resolution +fail closed. + +## 5. Validate the bundle locally + +Resolve the profile directly before committing it. For the example above: + +```text +uv run python scripts/agentic_configuration.py \ + --workflow pr-documentation-review \ + --bundle-root .opencode/configuration \ + --configuration-profile team-docs-review \ + --result /tmp/team-docs-review.json +``` + +Use the matching workflow identifier for every other profile. The resolver +checks schema version, profile/workflow compatibility, path safety, required +front matter, known output contract, and each declared content hash. + +Then run the relevant project tests and inspect the generated resolution JSON. +Do not work around a failure by weakening hashes or policy restrictions; fix +the manifest or file content that caused it. + +## 6. Publish the bundle through the intended source + +### Local source + +1. Commit the bundle under `.opencode/configuration//` on the + protected default branch of the consumer repository. +2. Set the wrapper inputs to `configuration_source: local` and + `configuration_profile: `. +3. Omit `configuration_ref`. + +### Central source + +1. Commit the bundle under `.opencode/configuration//` in the + approved central configuration repository. +2. Review and record the resulting full commit SHA. +3. Set `configuration_source: central`, `configuration_ref` to that SHA, and + `configuration_profile` to the profile name in each consumer wrapper. +4. If the central repository is private, forward the read-only + `central_config_token` secret. + +### Supplied default source + +Do not copy a supplied profile merely to use it unchanged. Select +`configuration_source: default`, provide the reviewed SHA of this workflow +repository as `configuration_ref`, and select the supplied profile name. + +## 7. Roll out and maintain it + +Deploy a changed bundle with `validate_only`, then `dry_run`, and finally +normal publication. For remote profiles, promote the new commit SHA explicitly +in each wrapper. For local profiles, merge only to the trusted default branch. + +When changing a bundle, update hashes, rerun resolution and tests, and review +the provenance artifact after deployment. OpenCode loads `.opencode/` +configuration at startup; restart it after configuration changes when using it +interactively. diff --git a/docs/deploying-a-workflow.md b/docs/deploying-a-workflow.md new file mode 100644 index 0000000..c24da4f --- /dev/null +++ b/docs/deploying-a-workflow.md @@ -0,0 +1,172 @@ +# Deploy an agentic workflow + +This guide deploys one of the reusable workflows in a repository that consumes +this project. It covers all supported configuration sources: the supplied +`default` profiles, repository-owned `local` bundles, and organization-managed +`central` bundles. + +For the individual input definitions, see the [configuration reference](configuration-reference.md). +For authoring a local or central profile, see [creating a configuration bundle](creating-a-configuration-bundle.md). + +## 1. Choose the workflow + +| Workflow | Reusable workflow | Typical trigger | Required caller permissions | +| --- | --- | --- | --- | +| Documentation review | `opencode-documentation-review.yml` | `pull_request` | `contents: read`, `pull-requests: write` | +| Issue feedback | `opencode-issue-feedback.yml` | `issues` | `contents: read`, `issues: write` | +| Release project review | `opencode-release-project-review.yml` | `workflow_dispatch`, schedule, or a release wrapper | `contents: read`, `issues: write` | + +The issue-implementation workflow is manual-dispatch only. It is not available +as a remote reusable call. + +Use the copy-ready wrappers under [configuration-source examples](examples/configuration-sources/README.md) +when one matches the intended deployment. + +## 2. Prepare credentials and permissions + +1. Add `OPENROUTER_API_KEY` as an Actions secret in the consumer repository. + Restrict its scope, credit limit, and lifetime. +2. Grant the calling job only the permissions in the table above. The caller, + not the reusable workflow, owns its `permissions:` declaration. +3. If using a private central configuration repository, add a + `CENTRAL_CONFIG_TOKEN` secret with read-only `contents: read` access to that + repository. +4. For a cross-repository release review, provide a separate + `release_target_token` scoped only to the reviewed target with + `contents: read` and `issues: write`. Do not rely on the caller's + `GITHUB_TOKEN` for another repository. + +## 3. Select a configuration source + +Choose exactly one source for a workflow invocation. + +| Source | Use it when | `configuration_ref` | Bundle location | +| --- | --- | --- | --- | +| `default` | A supplied profile is sufficient | Required: reviewed lowercase 40-character commit SHA | This workflow repository | +| `local` | The consuming repository owns its instructions | Omit it | Consumer repository's trusted default-branch checkout | +| `central` | An organization shares approved profiles | Required: reviewed lowercase 40-character commit SHA | Allowlisted central repository | + +A profile name must match `[a-z0-9][a-z0-9-]{0,62}`. Remote references are +immutable commit SHAs: branches, tags, URLs, and partial SHAs are rejected. +The remote bundle pin is independent of the commit SHA used to pin the +reusable workflow in `uses:`. + +### Option A: supplied `default` profile + +Choose `default` to use a supplied profile unchanged. Pin both the reusable +workflow and the supplied bundle revision to a reviewed commit SHA. The +profiles currently supplied are `documentation-review`, `issue-feedback`, +`default-implementation`, and `release-project-review`. + +```yaml +jobs: + review: + uses: SecondSkoll/generic-agentic-workflows/.github/workflows/opencode-documentation-review.yml@ + permissions: + contents: read + pull-requests: write + with: + configuration_source: default + configuration_ref: + configuration_profile: documentation-review + focus: documentation + max_comments: 10 + validate_only: true + secrets: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} +``` + +### Option B: repository-owned `local` bundle + +Choose `local` when the repository needs its own reviewed instructions. Put +the bundle in `.opencode/configuration//` on the protected default +branch. No `configuration_ref` is accepted or needed: the workflow reads the +trusted caller checkout rather than pull-request content. + +```yaml +jobs: + review: + uses: SecondSkoll/generic-agentic-workflows/.github/workflows/opencode-documentation-review.yml@ + permissions: + contents: read + pull-requests: write + with: + configuration_source: local + configuration_profile: team-docs-review + focus: documentation + max_comments: 5 + validate_only: true + secrets: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} +``` + +Create and validate the bundle before enabling the wrapper. The [bundle +authoring guide](creating-a-configuration-bundle.md) shows the required +layout and maintenance process. + +### Option C: organization-managed `central` bundle + +Choose `central` for a profile reviewed once and used by multiple repositories. +The source is an alias to the fixed allowlisted repository +`SecondSkoll/generic-agentic-workflows-config`; callers cannot provide a +repository name or URL. Pin its bundle commit independently. + +```yaml +jobs: + review: + uses: SecondSkoll/generic-agentic-workflows/.github/workflows/opencode-documentation-review.yml@ + permissions: + contents: read + pull-requests: write + with: + configuration_source: central + configuration_ref: + configuration_profile: documentation-review + focus: documentation + max_comments: 10 + validate_only: true + secrets: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + central_config_token: ${{ secrets.CENTRAL_CONFIG_TOKEN }} # Required only if central is private +``` + +## 4. Add a wrapper workflow + +Create a workflow under `.github/workflows/` in the consumer repository. The +wrapper owns event filtering, concurrency, permissions, and secret forwarding; +the reusable workflow owns configuration validation, model execution, output +validation, publication, and provenance artifacts. + +For example, a documentation-review wrapper can use `pull_request` and call +the `default` example above. For an issue-feedback wrapper, replace the +reusable workflow path with `opencode-issue-feedback.yml`, grant +`issues: write`, and use `max_issues` instead of `max_comments`. + +Do not expose prompt text, agent or skill paths, model IDs, URLs, repository +names, branches, tags, or mutable references as wrapper inputs. The reusable +interface intentionally accepts only typed, bounded selectors. + +## 5. Roll out safely + +Promote the wrapper through these stages: + +1. Commit it with `validate_only: true`. This validates the invocation and + its typed configuration selection without calling a model, resolving bundle + content, or writing to GitHub. +2. Review the run summary and redacted configuration/provenance artifacts. +3. Replace `validate_only: true` with `dry_run: true`. This can invoke the + model and validate its output, but it does not publish feedback. +4. Inspect the generated result and artifacts. +5. Remove `dry_run` to allow publication. + +`validate_only` and `dry_run` are mutually exclusive. At any stage, return to +a known-good workflow or remote-bundle SHA to roll back explicitly. + +## 6. Verify ongoing operation + +Each run uploads short-retention (14-day) redacted artifacts, including the +resolved configuration, effective policy, and provenance record. Use them to +confirm the selected profile, remote SHA, output contract, model profile, and +result without exposing credentials, full prompts, raw model output, or full +untrusted content. See the [operations guide](operations/operations-guide.md) +for rollback, incident response, and reliability limits. diff --git a/docs/plans/agentic-interaction.md b/docs/plans/agentic-interaction.md new file mode 100644 index 0000000..afa34cc --- /dev/null +++ b/docs/plans/agentic-interaction.md @@ -0,0 +1 @@ +With preflight commands, a command is used before an agent runs. We would like to have the agent run with a specific prompt, have an action run in the workflow, then have an agent assess the output of the action and reflect on its actions. \ No newline at end of file diff --git a/docs/running_commands.md b/docs/running_commands.md new file mode 100644 index 0000000..3d5ba9b --- /dev/null +++ b/docs/running_commands.md @@ -0,0 +1,180 @@ +# Run commands from a configuration bundle + +Configuration bundles can request a small set of workflow-owned commands by +using `preflight_commands`. This is intended for release-readiness evidence, +not general shell access. + +Command execution is currently supported only by the +`release-project-review` workflow. The workflow runner—not the model—executes +each approved command in the immutable target release checkout. Agent +configuration should continue to deny Bash access. + +## Prerequisites and limits + +A command must satisfy all of these requirements: + +- The bundle's `allowed_workflows` must contain `release-project-review`. +- `preflight_commands` must be a JSON array containing at most three strings. +- Every string must exactly match a command in the workflow's fixed allowlist. +- The required top-level executable must already be available on the + GitHub-hosted runner. An approved project command may perform its normal, + reviewed setup—for example, the Sphinx Stack Makefile creates a virtual + environment and installs `docs/requirements.txt`—but a bundle cannot add a + separate installation command. + +The currently approved commands are: + +```text +python3 -m pytest +make -C docs html +``` + +Arguments, paths, environment assignments, pipes, redirects, command chaining, +and alternate spellings are not accepted. The Sphinx command is specifically +approved for a release checkout that uses the Sphinx Stack's `docs/Makefile`; +after it runs, the workflow also requires a non-empty +`docs/_build/index.html`. The Makefile may create its documented virtual +environment and install its pinned Python requirements. For example, +`python3 -m pytest tests/` is a different command and is rejected. + +## Configure a bundle + +Add `preflight_commands` to the release-review profile's `bundle.json`: + +```json +{ + "schema_version": 1, + "profile_name": "release-readiness", + "allowed_workflows": ["release-project-review"], + "agent_file": "agent.md", + "skill_files": ["skills/release-management/SKILL.md"], + "prompt_template": "prompts/release-project-review.md", + "model_profile": "release-project-review-readonly", + "output_contract": "release-project-issue-v1", + "limits": {}, + "preflight_commands": [ + "python3 -m pytest" + ], + "policy": { + "capabilities": { + "filesystem": "read-release-context-only", + "github_write": "issue-create-only", + "delegation": "deny" + } + } +} +``` + +Do not grant the agent shell access. A release-review agent should retain +read-only permissions such as: + +```yaml +permission: + edit: deny + bash: deny + read: allow +``` + +`preflight_commands` is manifest configuration, not a declared content file, +so it is not added to `hashes.json`. If agent, skill, or prompt content is also +changed, regenerate the content hashes as usual: + +```text +uv run scripts/update_hashes.py --profile release-readiness +``` + +## Validate the configuration + +Resolve the bundle before deploying it: + +```text +uv run python scripts/agentic_configuration.py \ + --workflow release-project-review \ + --bundle-root .opencode/configuration \ + --configuration-profile release-readiness \ + --result /tmp/release-readiness.json +``` + +Resolution verifies the field type, workflow compatibility, and three-command +limit. The command allowlist is enforced by the release runner before model +invocation. An unsupported command fails closed rather than being passed to a +shell or ignored. + +## Enable the workflow + +Select the configured profile from a release-project-review wrapper. For a +bundle stored in the consuming repository's trusted default branch: + +```yaml +jobs: + release-review: + uses: organization/generic-agentic-workflows/.github/workflows/opencode-release-project-review.yml@ + permissions: + contents: read + issues: write + with: + target_repository: ${{ github.repository }} + release_id: ${{ github.event.release.id }} + configuration_source: local + configuration_profile: release-readiness + dry_run: true + secrets: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} +``` + +For a supplied or central bundle, use `configuration_source: default` or +`configuration_source: central` and provide the reviewed full commit SHA as +`configuration_ref`. See [Deploy a workflow](deploying-a-workflow.md) for the +complete source-specific setup and token requirements. + +There is no separate caller input that enables commands. Selecting a valid +release-review bundle containing `preflight_commands` enables execution during +the review phase. + +`validate_only: true` resolves configuration but deliberately skips release +fetching, checkout, command execution, model invocation, and publication. Use +`dry_run: true` for the first execution test: it runs the preflight and model +but suppresses issue publication. After inspecting the run and its provenance, +remove `dry_run` to enable normal publication. + +## Execution behavior + +For each configured command, the runner: + +1. maps the exact configured string to fixed argument-vector entries; +2. starts the process directly without a shell; +3. runs it from the immutable target release checkout; +4. supplies a minimal environment and no standard input; +5. limits execution to 300 seconds; and +6. captures at most 16 KiB of combined standard output and standard error; and +7. for `make -C docs html`, verifies that `docs/_build/index.html` is a + non-empty regular file. + +A nonzero exit or timeout is recorded as preflight evidence and does not by +itself fail the workflow. The result is supplied to the model as untrusted +data. It may support a release-readiness issue only when the finding explains +a concrete release-management consequence and identifies an owner or action. + +Invalid configuration, an unapproved command, a missing target checkout, or a +missing required executable fails the review before model invocation. The +model cannot alter a command, request another command, install software, or +execute the preflight itself. + +## Troubleshooting + +- **No command ran:** Confirm the selected profile contains + `preflight_commands` and the run is not using `validate_only: true`. +- **Unapproved release preflight command:** Use the exact approved string; + arbitrary flags and commands are intentionally unsupported. +- **`python3` is required:** Ensure the runner provides Python 3. The reusable + workflow sets up Python for non-validation runs. +- **Pytest cannot be imported:** The target project must make pytest available + without a preflight installation step. Command execution does not grant + dependency-installation capability. +- **The Sphinx build passed but the output check failed:** Confirm that the + release's `docs/Makefile` writes its dirhtml output to + `docs/_build/index.html`; missing, empty, and symbolic-link entry points are + rejected. +- **Tests failed but the workflow continued:** This is expected. A test failure + is evidence for the release review, while configuration or execution-safety + failures stop the workflow. diff --git a/docs/security-model.md b/docs/security-model.md new file mode 100644 index 0000000..22e8c98 --- /dev/null +++ b/docs/security-model.md @@ -0,0 +1,157 @@ +# Security model + +These reusable workflows automate feedback and narrowly bounded implementation +using a model, but they do not treat the model, pull requests, issues, release +metadata, or caller inputs as trusted control planes. This document explains +the controls that establish the trust boundary and why they exist. + +## Security principles + +1. **Configuration is reviewed, immutable, and verified.** A caller selects a + profile; it does not supply instructions, paths, or model settings. +2. **Untrusted repository data remains data.** Issue text, PR text, diffs, + release notes, and checked-out context are explicitly delimited and cannot + change policy or publication targets. +3. **Every layer can only narrow authority.** Workflow policy, organization + policy, bundle policy, local overlay, and typed invocation inputs are + intersected rather than overridden. +4. **The workflow, not the model, performs privileged actions.** Parsing, + validation, destination selection, idempotency, and GitHub publication are + deterministic runner responsibilities. +5. **Failures stop safely.** Invalid configuration or policy does not trigger + a fallback to a branch, tag, local profile, or stale remote content. + +## Control summary + +| Control | Threat addressed | Why it is needed | +| --- | --- | --- | +| Immutable workflow and remote-bundle SHA pins | Mutable branch/tag substitution | A reviewed commit is stable; a branch or tag can later point to different workflow code or instructions. | +| Fixed source aliases | Caller-controlled URLs or repositories | An alias maps to a known repository and root, preventing configuration exfiltration or unreviewed code sources. | +| Hash-verified bundle files | Tampered, incomplete, or substituted agent content | The manifest's declared content must match `hashes.json` byte-for-byte before use. | +| Path and symlink validation | Traversal and filesystem escape | Bundles cannot read a runner path outside their profile through `..`, absolute paths, or symlinks. | +| Trusted base checkout for PR review | Pull-request code execution/configuration takeover | `pull_request_target` uses the trusted base and does not check out or execute the untrusted PR head. | +| Typed invocation inputs | Prompt injection through wrapper inputs | Callers may choose bounded selectors, not raw prompt text, paths, model IDs, URLs, or mutable refs. | +| Restrictive policy merge | Lower layers broadening privilege | Every policy layer intersects capabilities and takes lower quotas; attempted escalation fails. | +| Least-privilege permissions and tokens | Excessive GitHub access | Each wrapper declares only the GitHub permissions it needs, and external releases use a target-scoped token. | +| Contract-validated model output | Model-directed API calls or malformed publication | The runner accepts only versioned output shapes before it posts comments, reviews, or issues. | +| Redacted provenance | Secret or sensitive-content leakage in diagnostics | Artifacts aid investigation without recording tokens, raw prompts, raw model output, full diffs, or release bodies. | + +## Configuration trust boundary + +A configuration bundle combines `bundle.json`, declared agent/skill/prompt +files, and `hashes.json`. The resolver enforces the supported schema, known +workflow and output contract, a registered model-profile name, safe relative +paths, required agent/skill front matter, file-count and size bounds, and +SHA-256 integrity for every declared content file. + +There are three source choices: + +- **`local`** reads the profile from the consuming repository's trusted + default-branch checkout. Pull-request content is not used to select it. +- **`default`** resolves a supplied profile from this repository at a full + pinned SHA. +- **`central`** resolves an organization profile from the fixed allowlisted + central repository at a separately pinned full SHA. + +Remote resolution is bounded by request timeouts, retry count, response size, +bundle file count, and total content size. A missing file, bad hash, unknown +source, invalid SHA, or resolution failure stops the run with no fallback. + +These checks prevent a caller or a PR author from redirecting the workflow to +an arbitrary repository, replacing a reviewed instruction with a different +file, or exploiting filesystem path traversal. + +## Input and prompt-injection defenses + +Model-facing workflows process adversarial text by design. An issue author, +PR author, release author, or contributor can write text that looks like an +instruction. The workflows therefore: + +- delimit untrusted source material and identify it as data; +- use a reviewed prompt template selected through the bundle instead of + caller-supplied prompt text; +- bound the amount and type of context collected; +- restrict PR inline comments to added diff lines, converting invalid + locations to summary feedback; and +- require a versioned output contract before publication. + +This does not claim that a model cannot be influenced by input. It ensures +that influence cannot alter the model's configured capabilities, select +credentials or destinations, execute arbitrary commands, or bypass the +workflow's deterministic validation and publication logic. + +## Policy and capability boundaries + +The effective policy has five ordered layers: built-in workflow policy, +organization policy/model profile, bundle policy, optional consumer overlay, +and typed invocation inputs. The merge is restrictive only: + +- capability allowlists are intersected; +- quotas use the lower value; +- permissions combine with logical AND; and +- conflicting required values are rejected. + +For example, documentation review is limited to a trusted checkout diff, +provider-only network access, review-comment publication, and no delegation. +A bundle can deny an already permitted operation or lower a quota, but it +cannot exchange that scope for a broader one. Review agent front matter that +requests edit permission is rejected. + +The issue-implementation path has a different, deliberately narrow policy: +its model may plan and use an executor only within the repository workspace +allowlist and validation-command allowlist. Before push or PR creation, the +workflow blocks edits to workflow files, automation, dependencies, and agent, +skill, configuration, or policy files. This protects the automation from +self-modification and dependency-based escalation. + +## GitHub access and publication + +Reusable callers own triggers, concurrency, permission declarations, and +secret forwarding. They should grant only the selected workflow's required +permissions. The model never receives a general GitHub write capability or +selects an API endpoint. + +For release project review, the workflow validates a canonical `owner/repo`, +accepts exactly one release ID or conservatively validated tag, resolves the +release through the GitHub API, and checks out the exact immutable target +commit read-only. Cross-repository review requires an explicitly forwarded, +target-scoped token with `contents: read` and `issues: write`; the caller's +`GITHUB_TOKEN` is not assumed to work outside its repository. + +The release output contract allows either `NO_ISSUE` or a constrained +`CREATE_ISSUE` record. The runner owns the destination repository, +`release-readiness` label allowlist, idempotency marker, and final issue +creation. It rejects output fields that attempt to specify a repository, +endpoint, URL, assignee, or milestone. + +## Idempotency and abuse resistance + +Feedback markers include a deterministic configuration digest. PR feedback is +suppressed for the same digest and PR head SHA; issue feedback is suppressed +for the same digest. Release-review idempotency includes the canonical target, +release ID, immutable target commit, configuration digest, and workflow +version. As a result, retried events do not create duplicate feedback, while a +reviewed configuration change intentionally produces a new identity. + +Output contracts reject malformed JSON, unknown fields or labels, empty or +oversize content, and unsupported findings. The runner creates at most one +release-readiness issue for a matching release-review identity. + +## Logging, provenance, and incident response + +Every execution path emits redacted provenance, including validation-only and +configuration failures. Artifacts retain enough information to investigate: +workflow version, target metadata, selected source/profile/SHA, manifest and +prompt hashes, output contract, model profile, effective-policy hash, mode, +and result. + +They deliberately exclude credentials, token values, complete prompts, raw +model responses, full issue text, unredacted diffs, and release bodies. Keep +artifact retention short (currently 14 days), restrict access to Actions logs +and artifacts, and never add secrets to bundle files or prompts. + +If a workflow behaves unexpectedly, set `validate_only: true` or disable its +wrapper trigger, preserve the redacted artifacts, identify the failing layer, +and explicitly pin a known-good workflow or bundle SHA. Do not automate +rollback to an unreviewed revision. The [operations guide](operations/operations-guide.md) +contains the detailed incident-response and rollback procedure. diff --git a/scripts/agentic_configuration.py b/scripts/agentic_configuration.py index a964478..b665a85 100644 --- a/scripts/agentic_configuration.py +++ b/scripts/agentic_configuration.py @@ -326,6 +326,7 @@ class BundleManifest: additional_agent_files: tuple[str, ...] = () bundle_policy: dict[str, Any] = field(default_factory=dict) context_policy: str | None = None + preflight_commands: tuple[str, ...] = () def parse_manifest(payload: Any, *, workflow: str) -> BundleManifest: @@ -396,6 +397,17 @@ def parse_manifest(payload: Any, *, workflow: str) -> BundleManifest: raise ConfigurationError("context_policy is only supported for pull-request reviews") if context_policy not in SUPPORTED_CONTEXT_POLICIES: raise ConfigurationError(f"unknown context_policy: {context_policy!r}") + raw_preflight_commands = payload.get("preflight_commands", []) + if not isinstance(raw_preflight_commands, list) or not all( + isinstance(command, str) for command in raw_preflight_commands + ): + raise ConfigurationError("preflight_commands must be a list of strings") + if raw_preflight_commands and workflow != "release-project-review": + raise ConfigurationError( + "preflight_commands are only supported for release-project-review" + ) + if len(raw_preflight_commands) > 3: + raise ConfigurationError("preflight_commands may contain at most 3 commands") manifest_sha256 = sha256_json(payload) return BundleManifest( schema_version=schema_version, @@ -411,6 +423,7 @@ def parse_manifest(payload: Any, *, workflow: str) -> BundleManifest: additional_agent_files=additional_agent_files, bundle_policy=dict(bundle_policy), context_policy=context_policy, + preflight_commands=tuple(raw_preflight_commands), ) @@ -464,6 +477,7 @@ def to_dict(self) -> dict[str, Any]: "limits": dict(self.manifest.limits), "bundle_policy": dict(self.manifest.bundle_policy), "context_policy": self.manifest.context_policy, + "preflight_commands": list(self.manifest.preflight_commands), } def to_json(self) -> str: diff --git a/scripts/run_agentic_release_project_review.py b/scripts/run_agentic_release_project_review.py index dcd0bef..7ad175d 100644 --- a/scripts/run_agentic_release_project_review.py +++ b/scripts/run_agentic_release_project_review.py @@ -31,6 +31,7 @@ import json import os import re +import shutil import subprocess import sys import tempfile @@ -94,6 +95,21 @@ def _load_sibling(name: str): MAX_RELEASE_CONTEXT_TOTAL_BYTES = 256 * 1024 MAX_RELEASE_CONTEXT_FILES = 8 +# Commands are selected by a reviewed, hash-verified bundle but are executed +# by this runner, never by the model. Keep this intentionally small and use +# argv execution (not a shell) so a profile cannot append flags, redirects, or +# another command. The test process receives a minimal environment and runs +# only in the immutable release checkout. +ALLOWED_RELEASE_PREFLIGHT_COMMANDS: dict[str, tuple[str, ...]] = { + "python3 -m pytest": ("python3", "-m", "pytest"), + "make -C docs html": ("make", "-C", "docs", "html"), +} +PREFLIGHT_OUTPUT_ARTIFACTS: dict[str, tuple[str, ...]] = { + "make -C docs html": ("docs/_build/index.html",), +} +MAX_PREFLIGHT_OUTPUT_BYTES = 16 * 1024 +PREFLIGHT_TIMEOUT_SECONDS = 300 + #: Per-release-fetch bounds. RELEASE_FETCH_TIMEOUT = 30 RELEASE_FETCH_RETRIES = 3 @@ -108,6 +124,81 @@ class ReleaseReviewError(ValueError): """Raised when release resolution, review, or publication fails.""" +def run_release_preflight( + commands: object, repo_root: Path +) -> str: + """Run a bounded allowlisted local validation suite and summarize it. + + Failure is evidence for the release review rather than a workflow failure: + the model must decide whether it creates a release-management issue from + that evidence. Invalid configuration fails closed before model execution. + """ + if not isinstance(commands, list) or not all(isinstance(item, str) for item in commands): + raise ReleaseReviewError("resolved preflight_commands must be a list of strings") + if not commands: + return "No local preflight commands were configured." + if not repo_root.is_dir(): + raise ReleaseReviewError(f"release checkout is unavailable: {repo_root}") + + python = shutil.which("python3") + path_entries = [os.path.dirname(python)] if python else [] + path_entries.append(os.defpath) + safe_environment = { + "HOME": tempfile.gettempdir(), + "PATH": os.pathsep.join(path_entries), + "PYTHONNOUSERSITE": "1", + "PYTHONDONTWRITEBYTECODE": "1", + } + summaries: list[str] = [] + for command in commands: + argv = ALLOWED_RELEASE_PREFLIGHT_COMMANDS.get(command) + if argv is None: + raise ReleaseReviewError(f"unapproved release preflight command: {command!r}") + executable_path = shutil.which(argv[0], path=safe_environment["PATH"]) + if executable_path is None: + raise ReleaseReviewError( + f"{argv[0]} is required for approved release preflight" + ) + executable = (executable_path, *argv[1:]) + try: + completed = subprocess.run( + executable, + cwd=repo_root, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + errors="replace", + timeout=PREFLIGHT_TIMEOUT_SECONDS, + env=safe_environment, + check=False, + ) + output = (completed.stdout + completed.stderr).strip() + output = output[:MAX_PREFLIGHT_OUTPUT_BYTES] + status = "passed" if completed.returncode == 0 else f"failed (exit {completed.returncode})" + except subprocess.TimeoutExpired as error: + output = ((error.stdout or "") + (error.stderr or "")).strip() + output = output[:MAX_PREFLIGHT_OUTPUT_BYTES] + status = f"timed out after {PREFLIGHT_TIMEOUT_SECONDS}s" + artifact_lines: list[str] = [] + for relative_path in PREFLIGHT_OUTPUT_ARTIFACTS.get(command, ()): + artifact = repo_root / relative_path + if artifact.is_file() and not artifact.is_symlink() and artifact.stat().st_size > 0: + artifact_lines.append( + f"Output check: passed ({relative_path}, {artifact.stat().st_size} bytes)" + ) + else: + artifact_lines.append( + f"Output check: failed ({relative_path} is missing, empty, or not a regular file)" + ) + if status == "passed": + status = "failed (expected output missing)" + details = f"Command: {command}\nResult: {status}\nOutput:\n{output or '(no output)'}" + if artifact_lines: + details += "\n" + "\n".join(artifact_lines) + summaries.append(details) + return "\n\n".join(summaries) + + # --------------------------------------------------------------------------- # GitHub REST API (target-scoped token) # --------------------------------------------------------------------------- @@ -912,6 +1003,28 @@ def _cmd_review(args: argparse.Namespace) -> int: ) if release_context: untrusted += "\n\nRelease/operational documents at the target commit (untrusted):\n" + release_context + try: + preflight = run_release_preflight( + resolved_bundle.get("preflight_commands", []), args.repo_root + ) + except ReleaseReviewError as error: + print(f"::error::Release preflight failed: {error}", file=sys.stderr) + _write_provenance( + path=provenance_path, + resolved_bundle=resolved_bundle, + effective_policy=effective_policy, + target_repository=target_repository, + release_id=release_id, + target_commit_sha=target_commit_sha, + release_tag=release_tag, + mode=mode, + result="failed", + workflow_version=workflow_version, + caller_repository=caller_repository, + error=error, + ) + return 1 + untrusted += "\n\nLocal release preflight results (untrusted evidence):\n" + preflight agent_name = resolved_bundle.get("agent_name") or "release-project-review" output_contract = resolved_bundle.get("output_contract") or OUTPUT_CONTRACT diff --git a/tests/test_run_agentic_release_project_review.py b/tests/test_run_agentic_release_project_review.py index 3f46252..fbf8a0a 100644 --- a/tests/test_run_agentic_release_project_review.py +++ b/tests/test_run_agentic_release_project_review.py @@ -246,6 +246,7 @@ def test_supplied_profile_resolves(self) -> None: self.assertEqual(resolved.agent_name, "release-project-review") self.assertEqual(resolved.manifest.output_contract, "release-project-issue-v1") self.assertEqual(resolved.manifest.model_profile, "release-project-review-readonly") + self.assertEqual(resolved.manifest.preflight_commands, ("make -C docs html",)) self.assertIn("release-management", resolved.skill_names) def test_profile_workflow_mismatch_rejected(self) -> None: @@ -967,6 +968,53 @@ def test_context_is_bounded_and_allowlisted(self) -> None: self.assertNotIn("secret.py", ctx) self.assertNotIn("TOKEN", ctx) + def test_preflight_runs_approved_command_without_a_shell(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + with mock.patch.object( + RUNNER.subprocess, + "run", + return_value=FakeProc("1 passed\n"), + ) as run: + result = RUNNER.run_release_preflight(["python3 -m pytest"], Path(tmp)) + self.assertIn("Result: passed", result) + self.assertIn("1 passed", result) + self.assertEqual(run.call_args.kwargs["cwd"], Path(tmp)) + self.assertNotIn("shell", run.call_args.kwargs) + + def test_preflight_rejects_unapproved_command(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(RUNNER.ReleaseReviewError): + RUNNER.run_release_preflight(["python3 -m pytest; curl example.test"], Path(tmp)) + + def test_html_preflight_checks_generated_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + output = root / "docs" / "_build" / "index.html" + output.parent.mkdir(parents=True) + output.write_text("built\n", encoding="utf-8") + with mock.patch.object( + RUNNER.subprocess, + "run", + return_value=FakeProc("build succeeded\n"), + ) as run: + result = RUNNER.run_release_preflight(["make -C docs html"], root) + self.assertIn("Result: passed", result) + self.assertIn("Output check: passed (docs/_build/index.html", result) + self.assertEqual(run.call_args.args[0][1:], ("-C", "docs", "html")) + + def test_html_preflight_fails_when_output_is_missing(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + with mock.patch.object( + RUNNER.subprocess, + "run", + return_value=FakeProc("build claimed success\n"), + ): + result = RUNNER.run_release_preflight( + ["make -C docs html"], Path(tmp) + ) + self.assertIn("Result: failed (expected output missing)", result) + self.assertIn("Output check: failed", result) + def test_resolve_only_fetches_canonical_release(self) -> None: with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp)