diff --git a/.changes/external-agents/feat-external-agents-95264810.md b/.changes/external-agents/feat-external-agents-95264810.md new file mode 100644 index 00000000000..402a65afedf --- /dev/null +++ b/.changes/external-agents/feat-external-agents-95264810.md @@ -0,0 +1,7 @@ +--- +bump: minor +--- + +### Added + +- The `external-agents` plugin: hands tasks and reviews to other vendors' official coding-agent CLIs through their documented headless surfaces, Codex first. This release ships the `external-agents` command (`run`, `review`, `status`, `result`, `cancel`, and `update`, which reports a CLI's version, login and latest release, caches its help per version (from stderr when a CLI prints its help there, and reported when a help command prints nothing), and checks its docs index and the config keys the runner passes), the team config schema for `/external-agents.yaml`, and the Codex prerequisite with its daily latest-release check. Every run passes the mode's sandbox and never an approval bypass; a briefed review names its merge base and changed files; a run whose commands the sandbox refused is recorded `blocked-by-mode`, not `ok`; a CLI that is missing, logged out or over its usage limit is refused until its next trial time; `cancel` and the run timeout stop the whole process tree. The `/external-agents:codex` skill drives the command: it runs a Codex task or investigation in the foreground or background, resumes a thread, reviews a branch, and reads back `status`, `result`, `cancel` and `update`, with its first reply line naming the mode the job ran in, model and effort guidance as pointers to the Codex docs, and no model passed unless one is configured. It replaces OpenAI's `codex@openai-codex` plugin. diff --git a/.changes/review/feat-external-agents-council-d5b9c833.md b/.changes/review/feat-external-agents-council-d5b9c833.md new file mode 100644 index 00000000000..565796353a5 --- /dev/null +++ b/.changes/review/feat-external-agents-council-d5b9c833.md @@ -0,0 +1,12 @@ +--- +bump: minor +--- + +### Changed + +- `/review:council` Codex members and `/review:fanout`'s Codex surface now run `external-agents review codex`, the command the `external-agents` plugin puts on the Bash `PATH`, instead of locating the OpenAI Codex plugin's install path. With that plugin not enabled, the member or surface reports `skipped (external-agents not enabled)`. Fanout's adversarial Codex run passes its own bundled brief, `skills/fanout/context/codex-adversarial-brief.md`, through `--brief-file`. +- `council-plan.mjs member` reads a script member's captured output and exit code as its council status (`ran`, `skipped ()` or `failed ()`) and its findings, finding the status line after any notices. + +### Removed + +- `scripts/codex-review.sh` and its test. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index cb25ffd1f78..80193271173 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -972,6 +972,19 @@ ], "defaultEnabled": false }, + { + "name": "external-agents", + "source": "./plugins/external-agents", + "category": "workflow", + "tags": [ + "codex", + "external-agents", + "cross-vendor", + "delegation", + "review", + "cli" + ] + }, { "name": "source-control", "source": "./plugins/source-control", diff --git a/.github/workflows/pr-require-checks.yml b/.github/workflows/pr-require-checks.yml index c57a1697ae9..3aacb797991 100644 --- a/.github/workflows/pr-require-checks.yml +++ b/.github/workflows/pr-require-checks.yml @@ -2512,7 +2512,7 @@ jobs: # cannot see one that is absent, as when a merge silently drops a # plugin.json the catalog still lists (#1547). Repo-wide and static, so # it always runs. - - name: Check every catalog entry resolves to a present, name-matching plugin manifest, and no plugin has a top-level bin/ + - name: Check every catalog entry resolves to a present, name-matching plugin manifest, and no plugin but external-agents has a top-level bin/ id: plugin_manifest_presence continue-on-error: true shell: bash scripts/run-hygiene-gate.sh plugin-manifest-presence {0} diff --git a/docs/adr/0021-reject-the-three-unused-official-plugin-components.md b/docs/adr/0021-reject-the-three-unused-official-plugin-components.md index b52f5177ce7..0e196020f84 100644 --- a/docs/adr/0021-reject-the-three-unused-official-plugin-components.md +++ b/docs/adr/0021-reject-the-three-unused-official-plugin-components.md @@ -1,6 +1,8 @@ # Reject the three unused official plugin components, each with a recheck trigger -- Status: accepted +- Status: accepted; the `bin/` verdict partly superseded by + [ADR 0118](0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md) + for the external-agents plugin - Date: 2026-07-12 ## Decision diff --git a/docs/adr/0117-replace-the-official-codex-plugin-with-one-external-agents-plugin-and-a-skill-per-cli.md b/docs/adr/0117-replace-the-official-codex-plugin-with-one-external-agents-plugin-and-a-skill-per-cli.md new file mode 100644 index 00000000000..1eedebdd4bd --- /dev/null +++ b/docs/adr/0117-replace-the-official-codex-plugin-with-one-external-agents-plugin-and-a-skill-per-cli.md @@ -0,0 +1,65 @@ +# Replace the official Codex plugin with one external-agents plugin and a skill per CLI + +- Status: accepted +- Date: 2026-11-21 +- Refs: [#17954](https://github.com/melodic-software/claude-code-plugins/pull/17954) (the plugin and + the council switch-over), [#17967](https://github.com/melodic-software/claude-code-plugins/pull/17967) + (the Antigravity skill); owner interview of 2026-11-20 and 2026-11-21 (Q4, Q13, Q14, Q16, Q21, + Q28); [ADR 0118](0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md), + [ADR 0119](0119-run-every-external-cli-through-one-runner-over-provider-records-with-per-use-sandbox-ceilings.md) + +## Context + +OpenAI's `codex@openai-codex` plugin ([openai/codex-plugin-cc](https://github.com/openai/codex-plugin-cc)) +was how sessions and the council review lanes reached Codex. It ships legacy `commands/`, a +proactive forwarding agent and hooks that run in every session. It drives `codex app-server`, +which OpenAI documents as experimental, and its prompting guidance names retired models. Upstream's +last push was 2026-07-08, and it had 546 open issues and pull requests when this was recorded. Council +reached into the plugin's private script by install path. The owner also wants the same pattern for +other vendors' CLIs: Gemini/Antigravity now, then Cursor, and maybe Grok's. + +## Decision + +1. **Replace, do not wrap.** The marketplace ships its own plugin, `external-agents`, and dotfiles + turn the official plugin off after it releases. The official plugin is cited as the upstream + source and none of its text or code is copied. +2. **One plugin, one skill per CLI.** `/external-agents:codex` is the first skill and + `/external-agents:antigravity` the second. Every skill shares the plugin's runner, job store, + CLI-facts cache and breaker. Another vendor's CLI is added as a provider record and a skill. +3. **No agent, no hooks, no `commands/`.** Delegation happens only when asked: a skill invocation, + or a council run that names the member. When the plugin is unused, nothing runs. +4. **The name and boundary is non-Anthropic coding-agent CLIs.** Only official vendor CLIs are in + scope: no third-party Claude Code plugin and no Claude provider. `multi-agent` stays Claude-only + and unchanged. +5. **Each skill learns its CLI from the CLI.** Facts come from the CLI's own help, cached per CLI + version, and each skill cites the vendor's docs index without copying from it. + +## Considered options + +- **Keep the official plugin and fix around it.** Rejected (Q4): the hooks cost every session, + the run surface is experimental, and upstream is not taking changes. +- **One plugin per vendor CLI.** Rejected (Q13): each plugin would duplicate the runner, job + store and breaker, so the copies would drift. +- **A forwarding agent, as upstream ships.** Rejected (Q14): a model hop that adds a turn and makes + the output shape depend on the model. Skills and the command reach the CLI directly. +- **Session hooks (a stop-time review gate, session transfer).** Rejected (Q16): they run whether + or not Codex is used, and the owner dropped both features. +- **Drive `codex app-server` or the Codex SDK.** Rejected: OpenAI documents `codex exec` as the + headless surface and calls the app server experimental + ([non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode.md)). + +## Consequences + +- Council's Codex member and `/external-agents:codex` move to the new plugin. Council no longer + looks up another plugin's install path. +- A new CLI costs one provider record, one skill and its tests. Each CLI's permission limits + differ, and ADR 0119 records them. +- Until dotfiles turn the official plugin off, both plugins are installed. Its hooks keep running + until then. + +## Revisit triggers + +- OpenAI resumes maintaining the official plugin and it reaches parity with current Claude Code + plugin guidance. +- A vendor CLI's headless surface cannot be described by a provider record and needs its own code + path. diff --git a/docs/adr/0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md b/docs/adr/0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md new file mode 100644 index 00000000000..2ae637de2f1 --- /dev/null +++ b/docs/adr/0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md @@ -0,0 +1,57 @@ +# Ship the external-agents command in bin/ and exempt it from the no-bin gate + +- Status: accepted +- Date: 2026-11-21 +- Supersedes in part: [ADR 0021](0021-reject-the-three-unused-official-plugin-components.md), its + `bin/` verdict, for the external-agents plugin only +- Refs: [#17954](https://github.com/melodic-software/claude-code-plugins/pull/17954); owner interview + of 2026-11-21 (Q61, Q62: "go w/ recomendations"); + [ADR 0117](0117-replace-the-official-codex-plugin-with-one-external-agents-plugin-and-a-skill-per-cli.md) + +## Context + +Council runs each member from a script, and `review:brief-reviewer` has no Skill tool, so neither +can invoke a skill. Before this change, council reached Codex by locating the official plugin's +install path and running its private script. ADR 0021 rejected `bin/` marketplace-wide. Its recheck +trigger was a script the consumer runs as a bare command. Council, the skills and a person at a +shell now all run `external-agents` that way, so the trigger has fired. +`scripts/check-plugin-manifest-presence.sh` rule 3 fails any plugin with a top-level `bin/`, +because claude.ai organization plugin sync rejects one (#5850). + +## Decision + +1. **`plugins/external-agents/bin/external-agents` is the plugin's one public command**, on the + Bash `PATH` while the plugin is enabled. Council's adapter runs `external-agents review ` + and the skills run the same command. Nothing outside the plugin names its scripts or install path. +2. **The no-bin gate exempts this plugin by name.** Rule 3 skips `external-agents` only. Its test + proves every other plugin's `bin/` still fails. +3. **Organization sync skips external-agents.** The rest of the marketplace still syncs. The + plugin drives local CLIs, so it has nothing to do on claude.ai. +4. **A missing command is a skipped member, never a failure or a fallback answer.** When + `external-agents` is not on `PATH` (plugin disabled, or `PATH` delivery failed), council prints + `skipped (external-agents not enabled)`. + +## Considered options + +- **A council skill member, run from the main thread (design T1 option B).** Rejected by the owner + (Q62): it loads the skill once per member, and the output shape then depends on the model. +- **Invoke the script by `${CLAUDE_PLUGIN_ROOT}` path from council.** Rejected: council would have + to find another plugin's install path, the coupling this change removes. +- **Keep ADR 0021's marketplace-wide rejection.** Rejected: its recheck trigger fired, and no + `scripts/` path lets a script in another plugin call this one without that lookup. + +## Consequences + +- The exemption is one named plugin. Any other plugin that wants `bin/` needs its own record. +- `PATH` delivery is per session and can fail silently + ([anthropics/claude-code#68066](https://github.com/anthropics/claude-code/issues/68066)). When it + fails, council's Codex member reports skipped instead of running. +- The component-stances table in `docs/plugin-philosophy.md` keeps `bin/` at Decline, with this + plugin named as the exception. + +## Revisit triggers + +- claude.ai organization sync accepts a plugin with a top-level `bin/`, so the exemption can become + the rule. +- A script can invoke a skill, or `review:brief-reviewer` gains the Skill tool. +- A second plugin needs a bare command on `PATH`. diff --git a/docs/adr/0119-run-every-external-cli-through-one-runner-over-provider-records-with-per-use-sandbox-ceilings.md b/docs/adr/0119-run-every-external-cli-through-one-runner-over-provider-records-with-per-use-sandbox-ceilings.md new file mode 100644 index 00000000000..8121c42bc3e --- /dev/null +++ b/docs/adr/0119-run-every-external-cli-through-one-runner-over-provider-records-with-per-use-sandbox-ceilings.md @@ -0,0 +1,83 @@ +# Run every external CLI through one runner over provider records, with per-use sandbox ceilings + +- Status: accepted +- Date: 2026-11-21 +- Refs: [#17954](https://github.com/melodic-software/claude-code-plugins/pull/17954) (runner, Codex + record), [#17967](https://github.com/melodic-software/claude-code-plugins/pull/17967) (Antigravity + record and its defaults); owner interview of 2026-11-20 and 2026-11-21 (Q20, Q31, Q42, Q51, Q59, + Q64, and "Opt-in write"); + [ADR 0117](0117-replace-the-official-codex-plugin-with-one-external-agents-plugin-and-a-skill-per-cli.md) + +## Context + +The plugin hands work to CLIs that run in the user's repositories, with the user's credentials, +outside Claude Code's permission system. Each CLI enforces its own limits differently. A Codex run +whose writes were refused still exits 0. A run of agy (the Antigravity CLI) can fall back to +another mode and say so only in a notice. The owner asked for "the safest yet extensible and +configurable method". + +## Decision + +1. **Provider records are data, and one runner is the only code that starts a CLI.** Each CLI's + argv, modes, output shape, resume arguments, review kind and denial rules live in + `providers/.yaml`, checked against one schema that rejects unknown keys. The runner in + `scripts/lib/runner.mjs` reads the record. It records every job in its own file (command, CLI + version, exit, duration, status) and keeps the newest 50 per repository. +2. **Each use runs in a sandbox mode, and the configured mode is both its default and its ceiling.** + Review and investigate are read-only. Task is write for Codex. For agy, task is read-only by + default, and write is one line in a personal or team file (`antigravity.uses.task.mode`, shipped + in #17967). The mode is passed on every run, resume included, with no approval prompt and no + escalation path, and a bypass flag is never passed. A request above the ceiling runs at the + ceiling, and the reply names the config key. Prompts never carry file contents. +3. **Exit 0 is not success.** A run is `ok` only when the CLI exits 0, its output shows a completed + turn and no error, its final message is non-empty, and none of its commands or writes was + denied. Any denial makes the run `blocked-by-mode`, even when the CLI then answers another way. + The answer still prints. +4. **Per-CLI limits are stated, not implied.** + - Codex: the sandbox is the only boundary. MCP servers and hooks configured in the repository + under review run outside it. The runner counts their calls and warns when the branch changes + `.codex/`. + - agy: the boundary is agy's sandbox plus agy's own review of commands. Write mode has no network + isolation. Read-only mode leaves agy only its file-reading tool. No mode restricts web access, + by owner decision. +5. **A repository never chooses what runs.** `.binary_path` is honored only from an + untracked personal file, only as an absolute path, and only when the file name is the CLI's own. +6. **Job and breaker files stay in this plugin's data folder.** That folder is the caller's, + then the installed copy's own, then `CLAUDE_PLUGIN_DATA` only when the name is + `external-agents-*`, because the Bash environment can carry another plugin's value. +7. **Config lives in `external-agents.yaml` on the config-cascade layers.** These are the plugin + default, userConfig, the team file and the personal `.local` file. Nothing is kept under + `~/.claude`, and no model or flag is pinned. With no model configured, the runner passes none, + and the CLI runs on its own default model (agy included, by owner decision of 2026-11-21). + +## Considered options + +- **A runner per CLI.** Rejected: each would carry its own success rule, retention and breaker, and + the safety rules would drift between them. +- **A Bash runner.** Rejected (design T4): the shared libraries are `.mjs`, and one Node file runs + on Windows and POSIX alike. +- **Exit code alone as success.** Rejected: probes showed refused writes exiting 0. +- **Mark an agy run `ok` when it recovers from a denied command.** Rejected: a recovered run read as + blocked still shows its answer, while a blocked run read as done hides lost work. +- **An escalation opt-in (`--approve-for-me` or a config flag).** Rejected (Q31, Q59): no escalation + without a configured ceiling, and none was configured. +- **agy write by default, or agy's hard-wall sandbox setting.** Rejected: write mode has no network + isolation, so the owner made write opt-in. The hard wall hides user-local toolchains such as mise + and nvm (Q64). +- **`binary_path` from any config layer.** Rejected (security gate): a committed file in a reviewed + branch could pick the executable. + +## Consequences + +- An agy investigate run that tries one shell command ends with exit 3 and `blocked-by-mode`, even + when its answer is right. +- Codex flag drift is fixed in a record, not in code. `update` re-reads help when the CLI version + changes. +- A user who wants agy to write sets one config line and accepts that write mode has no network + isolation. + +## Revisit triggers + +- Codex starts exiting non-zero on sandbox denials, so exit code could carry success. +- agy gains network isolation in write mode, or a sandbox that keeps user-local toolchains. +- Codex runs repository MCP servers and hooks inside its sandbox. diff --git a/docs/catalog.md b/docs/catalog.md index 99f5a6fe923..4b49af51dea 100644 --- a/docs/catalog.md +++ b/docs/catalog.md @@ -117,6 +117,7 @@ plugin manifests and kept in sync by CI. Never hand-edit it; the category vocabu - [`session-flow`](../plugins/session-flow): Session lifecycle: workflow (next stage), handoff (save-point, resume prompt), continue-in-background, keep-going (resume after a stall), find-handoff, clean-stop, retro and running-retro, audit-sessions, audit-friction, orient (where the session stands), orchestrate, reanchor (verify assumptions), reconcile (retire finished work), recommend-skills, tidy-work (.work tiers), step-away (run unattended, report on return), go-with-recommendations (accept after an evidence check), check, setup. - [`multi-agent`](../plugins/multi-agent): Workflow and model-routing guidance for multi-agent work: assess (workflow, subagent or single context), route (the role map a workflow script reads from args, keeping fan-out stages off a frontier model), audit-defaults (rechecks bundled defaults against upstream, or sweeps the repo's model and workflow guidance, via a read-only drift-audit workflow), check (whether node resolves and the fetch gate is registered), and setup (writes a user, team or local layer after a preview and a yes). +- [`external-agents`](../plugins/external-agents): Hands tasks and reviews to other vendors' official coding-agent CLIs (Codex first) through their documented headless surfaces: one skill per CLI, one shared runner with per-use sandbox ceilings, job files and a breaker, and the external-agents command that review:council calls. ## Presentation diff --git a/docs/contracts/config-cascade/README.md b/docs/contracts/config-cascade/README.md index 85e2efd3e8d..a53509a3562 100644 --- a/docs/contracts/config-cascade/README.md +++ b/docs/contracts/config-cascade/README.md @@ -131,7 +131,6 @@ with nothing configured. `userConfig` carries a per-person value across repos, w structurally cannot, because a per-user setting cannot decide the location or content of a team-shared artifact. The team layer is the only layer teammates receive. The personal override is the only place a personal deviation can live without either editing the shared file or going uncommitted and lost. -Dropping any one of them reintroduces a problem the other three cannot solve. ## Merge semantics @@ -262,8 +261,8 @@ content *is*, never by the author's preference: and bound by the pointer region below. Its personal channel is the prose personal override `/.local.md`, which replaces whole team sections by heading. A migrated plugin's setup `check` WARNs on any pre-existing personal override file at a retired path rather than silently - ignoring it. The personal override no longer has an effect there, and silence would let a personal - deviation look live. + ignoring it. The personal override no longer has an effect there, and silence would leave the + owner believing the override still applies. - **Structured data where YAML/JSON is the right tool** (`routing.yaml`, `binding.json`, `testing.yaml`) stays a keyed config file under the layers above. Its team layer is `/.yaml`, validated by a JSON Schema @@ -602,6 +601,7 @@ conformance. | `overengineering` | team on conflict for protected keys | per-key | | `multi-agent` | later layer | per-key | | `multi-agent` (`verification`) | the team file at the default branch; a skill entry over the plugin value; an invalid value resolves `standard`, no value `light` | per-key | +| `external-agents` | later layer | per-key | | `review-digest` | later layer; `--policy` over every layer | per-key (lists replace) | | `reviewer-media` | later layer; `--policy` over every layer | per-key (lists replace) | | `playbooks` | later layer | per-key | @@ -721,6 +721,7 @@ its conformance cell. | `overengineering` | team-only | `.claude/overengineering.md` | all three | team on conflict for protected keys | per-key | conforms; per-key override, plus policy-floor inversion on two key groups: the protected-categories set and the suppression entries (which merge per `finding_id`). On both, the team layer wins a direct conflict, personal layers may extend or tighten only, and a personal contribution is named in the report: a gitignored personal override emptying the protected set would defeat the plugin's FLAG-FOR-HUMAN cap on security-class artifacts, and a personal-only suppression is the same weakening `audit-pass` prevents above. Narrowing or emptying the protected set stays available on the tracked layer, spelled one category at a time so the diff names each protection dropped. The threshold and observation-window keys take ordinary refinement. Keys owned by the plugin's `reference/consumer-config.md`; suppression-entry keys by [`finding-suppression`](../finding-suppression/README.md) | | `multi-agent` | no-floor | team: `/multi-agent.yaml`, `` being the bound convention home, else `docs/conventions`; user-global `~/.claude/multi-agent.yaml`; personal override `.claude/multi-agent.local.yaml` | all three | later layer | per-key | the team file is validated by `plugins/multi-agent/schemas/multi-agent.schema.json`. The old team locations, the config block in `docs/conventions/multi-agent.md` and `.claude/multi-agent.yaml`, are not read; `/multi-agent:setup check` names each one it finds, and while the YAML is absent the first `/multi-agent:setup apply --layer team` write copies one old file's keys into it, leaving that file in place. Rule 5 holds: a layer that does not parse or names another schema is skipped and named, and an unknown key or a value outside its allowed set is reported and inert. No policy-floor class: every key is a routing dial, and turning the fan-out guard off is a documented opt-in on whichever layer sets it. Keys owned by [`plugins/multi-agent/reference/config.md`](../../../plugins/multi-agent/reference/config.md); resolved by `plugins/multi-agent/scripts/resolve-roles.sh`, read by `/multi-agent:route`, `/multi-agent:audit-defaults` and `/multi-agent:setup check`; written by `/multi-agent:setup apply` (any of the three layers, after a preview and an explicit yes) | | `multi-agent` (`verification`) | team-only | team: `/multi-agent.yaml`, the role map's team file (`` from the convention-home pointer line at the default branch, default `docs/conventions`; schema `plugins/multi-agent/schemas/multi-agent.schema.json`) | team only | the team file at the default branch; a skill entry over the plugin value; an invalid value resolves `standard`, no value `light` | per-key | conforms to the [location axis](#location-of-the-team-layer-a-docs-convention-file-or-claudename) ([ADR 0064](../../adr/0064-home-plugin-customization-in-docs-conventions-yaml.md)); no `userConfig` option, and the user-global and personal files do not set it: `scripts/resolve-roles.sh` passes over the keys in every layer, and `/multi-agent:setup apply` writes them to the team layer only. `verification_skills.` beats `verification`. `lib/read-verification.sh` (the plugin's copy) reads the file at `origin/` after a fetch, never the working tree, so a branch cannot lower its own level, and names a working-tree copy that gives another level. An invalid value or a file that does not parse is named and resolves `standard`; no value resolves `light`. Levels owned by [`docs/contracts/verification-level/README.md`](../verification-level/README.md); read by `/multi-agent:audit-defaults`. This row covers `verification` and `verification_skills` | +| `external-agents` | no-floor | team: `/external-agents.yaml` (schema `plugins/external-agents/schemas/external-agents.schema.json`), `` being the bound convention home, else `docs/conventions`; personal override `/external-agents.local.yaml` | plugin default, team and personal override; no `userConfig` option yet | later layer | per-key | conforms: read through `resolve` by `plugins/external-agents/scripts/lib/config.mjs` over the bundled `defaults.json`; no `~/.claude` file and no `.claude/*.local` file. Declared exception: `.binary_path` is honored only from the personal override and only when absolute, since it picks the executable that runs; a team value is reported and ignored | | `review-digest` | no-floor | team: `docs/conventions/review-digest.yaml`; user-global `~/.claude/review-digest.json`; personal override `.claude/review-digest.local.json` | all three | later layer; `--policy` over every layer | per-key (lists replace) | conforms to the [location axis](#location-of-the-team-layer-a-docs-convention-file-or-claudename): the team layer is the YAML file alone, the [ADR 0064](../../adr/0064-home-plugin-customization-in-docs-conventions-yaml.md) team file. Rule 5 holds: a layer that does not parse is named and skipped, an invalid value is reported and ignored, and an unknown key is inert. Declared deviation from the per-layer verdicts: an untracked team layer is reported and resolved as absent rather than stopping, and a personal override that is not gitignored is reported and still applied, since every key only decides when a reader is offered a view. No policy-floor class. Keys owned by [`review-digest`](../../conventions/review-digest.md); resolved by `plugins/review/lib/review-digest.mjs` for `/review:explain-change` (whose `digest-policy.mjs` also reads the `rendered-views` `medium` key) and `/review:reviewer-media` | | `reviewer-media` | team-only for `voice_command` and `allow_unattended_paid_voice`, no-floor otherwise | team: `docs/conventions/reviewer-media.yaml` read at the pull request's `baseRefOid`; personal override `docs/conventions/reviewer-media.local.yaml`, applied only when untracked | team and personal override; no user-global file | later layer; `--policy` over every layer | per-key (lists replace) | conforms: read through `readLayers` with the base-commit team text; an invalid team value falls to the default, an invalid personal value leaves the team value, and a team-only key in the personal override is refused. Keys owned by [`reviewer-media`](../../conventions/reviewer-media.md); resolved by `plugins/review/skills/reviewer-media/scripts/decide.mjs` | | `playbooks` | no-floor | team: `docs/conventions/playbooks.yaml` (schema `plugins/playbooks/schemas/playbooks.schema.json`); per user: the plugin's `userConfig` | `userConfig` + team | later layer | per-key | declared deviation: a [ADR 0064](../../adr/0064-home-plugin-customization-in-docs-conventions-yaml.md) team file with no `~/.claude/` file and no personal override. An unexpanded `${user_config.}` reads as unset, and a value outside a key's list is named and resolves the default. Keys owned by the plugin's `reference/config.md`; read in the skill text of `/playbooks:fable-5` (`described_problem`), which reports the supplying layer | diff --git a/docs/plugin-philosophy.md b/docs/plugin-philosophy.md index 09ceb490d22..faab1916d19 100644 --- a/docs/plugin-philosophy.md +++ b/docs/plugin-philosophy.md @@ -226,7 +226,7 @@ describes the person's workflow around the skill rather than what the skill does names no second step keeps the name: `in` before a place (`continue-in-background`), or `or` between alternatives the skill itself weighs (`reuse-or-replace`). -`/name:name` doubling is a naming defect, not an idiom: one of the two names is failing at its job, +`/name:name` doubling is a naming defect, not an idiom, because one of the two names is failing at its job, the namespace not naming the domain or the skill not naming its action. Fix it by, in preference order: rename the skill to its real action verb; rename the plugin to its domain noun; decompose, when the single skill hides distinct discovery intents (the split rule in the migration playbook's @@ -406,7 +406,7 @@ results, not omissions; the trigger, never the date, is what obliges re-deriving | [MCP servers](https://code.claude.com/docs/en/mcp) | Adopt on need | Clears the plugin-acceptance security review for egress and trust delegation. Also the only component type that can cost a consumer their prompt cache: every other kind only appends to the request, while enabling or disabling a plugin that provides an MCP server forces a full re-read whenever the server's tools load into the prefix instead of being deferred by tool search (pointer: [actions that invalidate the cache](https://code.claude.com/docs/en/prompt-caching#actions-that-invalidate-the-cache)). | 2026-08-10 | | [LSP servers](https://code.claude.com/docs/en/plugins/components#lsp-servers) | Adopt on need | Consumer must have the language-server binary; declare the prerequisite per the failure-behavior rules. | 2026-07-17 | | [Output styles](https://code.claude.com/docs/en/plugins/components#themes-and-output-styles) | Adopt on need | No additional constraints. | 2026-07-17 | -| [`bin/`](https://code.claude.com/docs/en/plugins/components#executables) | Decline | claude.ai organization plugin sync rejects a plugin with a top-level `bin/` (#5850), and `scripts/check-plugin-manifest-presence.sh` fails any plugin that adds one. Put executables under `scripts/` and invoke them via `${CLAUDE_PLUGIN_ROOT}/scripts/`. Bare-name invocation was never dependable either: `PATH` delivery is per-session and can silently fail ([anthropics/claude-code#68066](https://github.com/anthropics/claude-code/issues/68066)), and a `bash "…/x"` invocation does not match a `Bash(x:*)` allow rule. | 2026-07-17 | +| [`bin/`](https://code.claude.com/docs/en/plugins/components#executables) | Decline | claude.ai organization plugin sync rejects a plugin with a top-level `bin/` (#5850), and `scripts/check-plugin-manifest-presence.sh` fails any plugin that adds one. Put executables under `scripts/` and invoke them via `${CLAUDE_PLUGIN_ROOT}/scripts/`. Bare-name invocation was never dependable either: `PATH` delivery is per-session and can silently fail ([anthropics/claude-code#68066](https://github.com/anthropics/claude-code/issues/68066)), and a `bash "…/x"` invocation does not match a `Bash(x:*)` allow rule. One exception: `external-agents` ships its public command in `bin/`, the gate exempts it by name, and organization sync skips that plugin ([ADR 0118](adr/0118-ship-the-external-agents-command-in-bin-and-exempt-it-from-the-no-bin-gate.md)). | 2026-11-21 | | Plugin `settings.json` ([changelog 2.1.323](https://code.claude.com/docs/en/changelog#2-1-323)) | `agent` prohibited by default | `agent` takes over the main thread, a consumer-hostile default for a marketplace plugin; any exception requires documented justification in the plugin README. | 2026-11-17 | | [Monitors](https://code.claude.com/docs/en/plugins/components#monitors) | Wait | Experimental (`experimental.monitors`); interactive-CLI-only, unsandboxed at hook trust level, no `${user_config.*}` and no `CLAUDE_PLUGIN_OPTION_*` in monitor processes; keep running after mid-session disable. Re-verify before each audit. | 2026-07-17 | | [Themes](https://code.claude.com/docs/en/plugins/components#themes-and-output-styles) | Wait | Experimental (`experimental.themes`); schema may change between releases. Re-verify before each audit. | 2026-07-17 | @@ -861,8 +861,8 @@ subaction and carries no `install-` prefix: guardrails `identity-domains` and `r **Refusal template.** A setup whose hook only calls a tool on the consumer's files, and which has no install path recorded in the consumer's repo, declines to install. It uses this shape, not a -plugin-specific rationale: print the consumer-run command; do not invent `apply install-` to -paper over the gap; name every reason that applies; at least one always does. +plugin-specific rationale: print the consumer-run command; do not add an `apply install-` +subaction that cannot install; name every reason that applies; at least one always does. 1. The hook resolves the tool on `PATH`, so the install it can use is machine-level (a global bin directory such as `$GOPATH/bin`, cargo, Homebrew, a pre-built binary); a dependency recorded @@ -1167,7 +1167,7 @@ Three bias classes name the trigger: The delegation target has an independence ladder: a same-vendor fresh context removes the session's reasoning but can still share the model's blind spots; a different-vendor advisor removes both. Where the verdict is high-stakes and correlated blind spots are the risk, a checkpoint site prefers a -cross-vendor advisor **when one is enabled and set up**, for example the OpenAI Codex plugin, when its documented surface can take this artifact, invoked per its own docs, with the fresh-context same-vendor subagent as the +cross-vendor advisor **when one is enabled and set up**, for example the `external-agents` plugin's Codex skill, when its documented surface can take this artifact, invoked per its own docs, with the fresh-context same-vendor subagent as the stated fallback, never a route to a command that may not resolve. That reference is optional collaboration, so it carries the presence-gate-plus-fallback shape ([seam phrasing](contracts/seam-phrasing/README.md)) at each site that instructs it; an advisor diff --git a/docs/skill-cheat-sheet.md b/docs/skill-cheat-sheet.md index 60258dd14a3..da4df6f3c6a 100644 --- a/docs/skill-cheat-sheet.md +++ b/docs/skill-cheat-sheet.md @@ -142,6 +142,7 @@ From the stage definitions: A conditional stage runs only when its trigger holds | [`/debugging:debug`](../plugins/debugging/skills/debug/SKILL.md) | `debugging` | Debug broken behavior. Reproduce, hypothesize, instrument, fix with regression test | | `[diagnose] [--unattended] [bug description or observation]` | [pstack `tdd`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-attack-the-premise`](upstream/cursor-pstack.md#attribution-table), [pstack `feature`](upstream/cursor-pstack.md#attribution-table), [pstack `runtime-forensics`](upstream/cursor-pstack.md#attribution-table), [Pocock `diagnosing-bugs`](upstream/mattpocock-skills.md#attribution-table) | `/verification:confirm`, `/review:quality-gate`, `/implementation:implement`, `/debugging:analyze-profile`, `/planning:interview`, `/bugs:write`, `/session-flow:workflow` | | [`/developer-experience:build-cli`](../plugins/developer-experience/skills/build-cli/SKILL.md) | `developer-experience` | Build, extend, port or review a team's command-line tools against the CLI contract | | `[review] [what to build or review]` | | `/developer-experience:audit-tools`, `/review:quality-gate` | | [`/explainer-video:produce`](../plugins/explainer-video/skills/produce/SKILL.md) | `explainer-video` | Script, narrate, render and check a ManimCE explainer video, frames judged in a fresh context | | ` [output dir]` | | `/harness-ops:prerequisites`, `/source-control:pull-request` | +| [`/external-agents:codex`](../plugins/external-agents/skills/codex/SKILL.md) | `external-agents` | Hand tasks, investigations and reviews to the Codex CLI and read back its jobs | `run`, `review`, `status`, `result`, `cancel`, `update` | `[run \|review --base \|status []\|result \|cancel \|update]` | | `/review:council` | | [`/implementation:implement`](../plugins/implementation/skills/implement/SKILL.md) | `implementation` | Execute approved plans with TDD, incremental validation, and green commits | `feature`, `fix`, `refactor`, `replace`, `config` | `[feature\|fix\|refactor\|replace\|config] [task]` | [pstack `tdd`](upstream/cursor-pstack.md#attribution-table), [pstack `autonomous-run`](upstream/cursor-pstack.md#attribution-table), [pstack `architect`](upstream/cursor-pstack.md#attribution-table), [pstack `figure-it-out`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-boundary-discipline`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-exhaust-the-design-space`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-laziness-protocol`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-never-block-on-the-human`](upstream/cursor-pstack.md#attribution-table), [pstack `feature`](upstream/cursor-pstack.md#attribution-table), [pstack `visual-parity`](upstream/cursor-pstack.md#attribution-table) | `/testing:plan`, `/testing:audit`, `/testing:run-e2e`, `/review:quality-gate` | | [`/implementation:implement-dispatch`](../plugins/implementation/skills/implement-dispatch/SKILL.md) | `implementation` | Orchestrate worker subagents to execute an approved plan | | `[phase] [--unattended] [--items ] [--base ] [--wave-cap ]` | [pstack `autopilot-full`](upstream/cursor-pstack.md#attribution-table), [pstack `figure-it-out`](upstream/cursor-pstack.md#attribution-table), [pstack `principle-build-the-lever`](upstream/cursor-pstack.md#attribution-table), [pstack `orchestrate`](upstream/cursor-pstack.md#attribution-table), [pstack `feature`](upstream/cursor-pstack.md#attribution-table), [Pocock `implement-spec`](upstream/mattpocock-skills.md#attribution-table) | `/testing:plan`, `/testing:audit`, `/testing:run-e2e`, `/review:quality-gate` | | [`/instruction-placement:establish-hub`](../plugins/instruction-placement/skills/establish-hub/SKILL.md) | `instruction-placement` | Set up or check the hub repository where cross-repository sessions start | `plan`, `apply` | `[plan\|apply]` | | `/source-control:pull-request` | diff --git a/docs/upstream/t3dotgg-tstack.md b/docs/upstream/t3dotgg-tstack.md index d6010edb352..56d48444159 100644 --- a/docs/upstream/t3dotgg-tstack.md +++ b/docs/upstream/t3dotgg-tstack.md @@ -34,13 +34,13 @@ reason. | Idea (link at the pin) | What it does | Upstream problem, motivation, goal | Our problem | Disposition | |---|---|---|---|---| -| [`council`: panel across vendors](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md) | Sends one request to read-only reviewers on three vendors' flagship models and refuses a stand-in when one is missing. | One vendor's models share blind spots, so a second opinion needs another vendor. **Inference** | Correlated reviewer blind spots: `plugins/review/skills/fanout/context/run-everything-mode.md` step 3 runs Codex for this reason, and `fanout_diversity` picks `lens`, `model` or `codex`. | **adapt:** a council skill in the `review` plugin whose members come from a `council_members` key in the review plugin's config cascade, Claude-only by default, with the members for a run chosen per change from its paths, size or risk. Each provider is an adapter (`codex-review.sh` is the first to add), and a member that cannot run is reported, never replaced. It stays opt-in: lens and model tiers tied on recall, and Codex alone raised 0 of 152 and 1 of 123 important findings in the evals linked above. | +| [`council`: panel across vendors](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md) | Sends one request to read-only reviewers on three vendors' flagship models and refuses a stand-in when one is missing. | One vendor's models share blind spots, so a second opinion needs another vendor. **Inference** | Correlated reviewer blind spots: `plugins/review/skills/fanout/context/run-everything-mode.md` step 3 runs Codex for this reason, and `fanout_diversity` picks `lens`, `model` or `codex`. | **adapt:** a council skill in the `review` plugin whose members come from a `council_members` key in the review plugin's config cascade, Claude-only by default, with the members for a run chosen per change from its paths, size or risk. Each provider is an adapter (`external-agents review codex` is the first), and a member that cannot run is reported, never replaced. It stays opt-in: lens and model tiers tied on recall, and Codex alone raised 0 of 152 and 1 of 123 important findings in the evals linked above. | | [`council`: score per round in the PR body](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md) | Asks each reviewer for a mark out of ten and writes a table of marks by round into the description. | A reader wants a quick signal of how a review converged. **Inference** | A view of whether repeated rounds converge, once a council can repeat. | **adapt:** a `council_scores` key, off by default, because a mark has no anchor a gate acts on. Findings stay ranked by severity and confidence (`plugins/review/reference/findings-normalization.md`). | | [`council`: repeat until every reviewer is satisfied](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md) | Applies agreed fixes and starts a fresh full review, with no round limit. | Convergence across reviewers is the exit test. **Inference** | Fixes need a check by someone who did not write them: `plugins/review/skills/fanout/context/fix-pass-mode.md`, "Follow-up". | **adapt:** a `council_max_rounds` key replaces the open-ended loop, with a default of one so the post-fix re-review keeps running once over the changed hunks, as the `fix-rereview-stops-after-one-round` eval holds. A higher value is an explicit opt-in. | | [`council`: hold scope across rounds](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md#L61) | Makes the orchestrator responsible for refusing additions that repeated review proposes. | Each extra pass invites more change. **Stated** ([source](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md#L61)) | Review fixes that widen a change: `plugins/source-control/reference/review-discipline.md` D4.6. | **already have:** the D4.6 scope test and `fanout_act_on_cap` in `/review:fanout`. | | [`council`: act on each result as it lands](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md#L28) | Compares a member's findings with the code as soon as that member returns and settles fixes before the others finish, but holds every file edit until no member is still reviewing the checkout. | Time lost waiting on the slowest reviewer. **Inference** | Round wall time, and edits made while a member still reviews: council Step 5 waits for every member before Step 6 normalizes the round. | **already have** the edit hold: `plugins/review/skills/council/SKILL.md` Step 7 starts `/review:fanout fix` only after round N's file is written, and that file needs every member's status. **reject** the early check: here `/review:fanout fix` chooses the fixes from the written round file, which ranks each row by how many members raised it (`plugins/review/reference/findings-normalization.md` Stage 4), so a fix chosen from one member's output would come before that count exists. The one row check Step 6 makes, reading a CRITICAL row's cited line, could start as a member returns, but the round still waits for its slowest member. | -| [`council`: members the run does not wait for](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md#L30) | Lets the user exempt a member from the wait; output that comes in after the rest is read as advice, and its mark stays out of the table. | One slow reviewer holds up the round. **Inference** | A slow member delays its round: every member must end `ran`, `skipped` or `failed` before Step 6, and `plugins/review/scripts/codex-review.sh` sets no time limit of its own. | **reject:** Step 5 of `plugins/review/skills/council/SKILL.md` waits until every member it sent ends with a status, and taking this needs a new member status or config key. Output that lands after the round file is written would still reach no fix, since Step 6 never edits a written round file and fix admits one only by name and digest. | -| [`sol-loop`: one outside reviewer on a round budget](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md) | Runs a single OpenAI reviewer for three rounds, five for risky areas, later rounds limited to new edits and unresolved items. | Correctness of a change before it is filed. **Stated** ([source](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md#L8)) | The vendor-diverse pass: `plugins/review/scripts/codex-review.sh`. | **adapt:** a Codex entry in `council_members` covers the outside reviewer, and rounds after the first are limited the same way under `council_max_rounds`. `/review:fanout` stays one pass. | +| [`council`: members the run does not wait for](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/council/SKILL.md#L30) | Lets the user exempt a member from the wait; output that comes in after the rest is read as advice, and its mark stays out of the table. | One slow reviewer holds up the round. **Inference** | A slow member delays its round: every member must end `ran`, `skipped` or `failed` before Step 6, and `external-agents review codex` waits up to `codex.timeout_seconds` (1800 s by default). | **reject:** Step 5 of `plugins/review/skills/council/SKILL.md` waits until every member it sent ends with a status, and taking this needs a new member status or config key. Output that lands after the round file is written would still reach no fix, since Step 6 never edits a written round file and fix admits one only by name and digest. | +| [`sol-loop`: one outside reviewer on a round budget](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md) | Runs a single OpenAI reviewer for three rounds, five for risky areas, later rounds limited to new edits and unresolved items. | Correctness of a change before it is filed. **Stated** ([source](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md#L8)) | The vendor-diverse pass: `external-agents review codex` (`plugins/external-agents`). | **adapt:** a Codex entry in `council_members` covers the outside reviewer, and rounds after the first are limited the same way under `council_max_rounds`. `/review:fanout` stays one pass. | | [`sol-loop`: severity tied to intent](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md) | Grades a finding by whether the intended case breaks, and calls anything off that path a nit. | Rare paths inflate reviews. **Inference** | Findings outside the change's purpose: fan-out's `spec` and `standards` axis and its intent paragraph in `plugins/review/skills/fanout/SKILL.md`. | **already have:** our reviewers report everything and the normalization stage ranks it against intent, so a reviewer never withholds a finding. | | [`sol-loop`: finding ledger and diff-size check](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md) | Tracks each finding's id, severity and outcome, and cuts code when fixes enlarged the change. | Review fixes creep. **Stated** ([source](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/sol-loop/SKILL.md#L13)) | Per-finding tracking: `plugins/source-control/reference/review-discipline.md` sections 2 and 3, and `manage_feedback_ledger.py`. | **already have:** the ledger, with scope held per finding by D4.6. No total-size comparison exists in the fix flows searched (`review-discipline.md`, `fix-pass-mode.md`, babysit `feedback.md`), and no recurrence of the problem has been recorded to justify one. | | [`babysit-pr`: wait through one watcher](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/babysit-pr/SKILL.md#L15) | Allows one watcher per PR, because polling draws on an account-wide quota. | Quota exhaustion from duplicate pollers. **Stated** ([source](https://github.com/t3dotgg/tstack/blob/11e37a74d0a6868c121cd0910ab2b3bd9873b92a/skills/babysit-pr/SKILL.md#L15)) | The same quota: `plugins/source-control/skills/pull-request/reference/monitor.md` section 3.0.1. | **already have:** the session's own arming record, and the babysit lease for the fleet loop. | diff --git a/plugins/external-agents/.claude-plugin/plugin.json b/plugins/external-agents/.claude-plugin/plugin.json new file mode 100644 index 00000000000..272f02ad921 --- /dev/null +++ b/plugins/external-agents/.claude-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "name": "external-agents", + "description": "Hands tasks and reviews to other vendors' official coding-agent CLIs (Codex first) through their documented headless surfaces: one skill per CLI, one shared runner with per-use sandbox ceilings, job files and a breaker, and the external-agents command that review:council calls.", + "author": { + "name": "Melodic Software", + "email": "info@melodicsoftware.com" + }, + "version": "0.0.0", + "license": "MIT", + "keywords": [ + "codex", + "external-agents", + "cross-vendor", + "delegation", + "review", + "cli" + ], + "metadata": { + "category": "workflow" + } +} diff --git a/plugins/external-agents/CHANGELOG.md b/plugins/external-agents/CHANGELOG.md new file mode 100644 index 00000000000..9514c930fff --- /dev/null +++ b/plugins/external-agents/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +All notable changes to the `external-agents` plugin are documented here. Format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this plugin uses semantic versioning. diff --git a/plugins/external-agents/README.md b/plugins/external-agents/README.md new file mode 100644 index 00000000000..e348c070ffa --- /dev/null +++ b/plugins/external-agents/README.md @@ -0,0 +1,58 @@ +# external-agents + +A Claude Code plugin that hands tasks and reviews to other vendors' official coding-agent CLIs +through their documented headless surfaces. Codex is the first CLI. Each CLI gets one skill; one +shared runner is the only code that calls a CLI. + +It replaces OpenAI's `codex@openai-codex` plugin +([openai/codex-plugin-cc](https://github.com/openai/codex-plugin-cc), read as the upstream source; +none of its text or code is copied). + +## Status + +In progress: `run`, `review`, `status`, `result`, `cancel` and `update` work, and +`/external-agents:codex` drives them. + +## Surface + +- **`external-agents`**, on the Bash `PATH` while the plugin is enabled: `run`, `review`, `status`, + `result`, `cancel` and `update`. `review:council` calls `external-agents review `; nothing + outside this plugin reads its install path or its scripts. +- **`/external-agents:codex`**: hands a task, an investigation or a review to Codex, in the + foreground or background, and reads back, resumes or cancels its jobs. +- No hooks, no agents and no `commands/` folder: nothing runs until you or a council run asks. + +claude.ai organization plugin sync skips this plugin, because it ships a top-level `bin/` +([org sync](https://claude.com/docs/plugins/org-sync)). It needs a local CLI, so it cannot run there +anyway. + +## Requirements + +- `node`. +- Each CLI you want to reach, installed and logged in. The plugin never installs one. + +## Configuration + +`/external-agents.yaml` (team, tracked) and `/external-agents.local.yaml` (personal, +gitignored), `` being the repository's convention home, by default `docs/conventions`. Keys +are in [`schemas/external-agents.schema.json`](schemas/external-agents.schema.json); layers and +precedence are in the +[config-cascade contract](../../docs/contracts/config-cascade/README.md). An unset model, effort or +profile leaves the CLI's own configuration in charge. + +## Job files + +Job files, logs, the breaker state and the CLI-facts cache (`cli-facts///`, the +CLI's own help captured by `update`) live in the plugin's data directory. An installed copy works +the directory out from its own install path, using the directory name the +[plugin reference](https://code.claude.com/docs/en/plugins-reference#environment-variables) +documents, because a command run through the Bash tool can carry another plugin's +`CLAUDE_PLUGIN_DATA`. A copy that is not installed, such as a checkout, needs `CLAUDE_PLUGIN_DATA` +set to a directory whose name starts with `external-agents-`; any other value is not used. + +## Install + +```shell +/plugin marketplace add melodic-software/claude-code-plugins +/plugin install external-agents@melodic-software +``` diff --git a/plugins/external-agents/bin/external-agents b/plugins/external-agents/bin/external-agents new file mode 100755 index 00000000000..46759f028f9 --- /dev/null +++ b/plugins/external-agents/bin/external-agents @@ -0,0 +1,18 @@ +#!/usr/bin/env node +const { join } = require("node:path"); +const { pathToFileURL } = require("node:url"); + +const argv = process.argv.slice(2); + +import(pathToFileURL(join(__dirname, "..", "scripts", "external-agents.mjs")).href) + .then(({ main }) => main(argv)) + .then((code) => { process.exitCode = code; }) + .catch((error) => { + if (argv[0] === "review") { + const product = /^[a-z][a-z0-9-]*$/.test(argv[1] || "") ? argv[1] : "external-agents"; + const reason = String((error && error.message) || error).replace(/\s+/g, " ").trim(); + process.stdout.write(`${product}: failed (${reason})\n`); + } + process.stderr.write(`${(error && error.stack) || error}\n`); + process.exitCode = 1; + }); diff --git a/plugins/external-agents/defaults.json b/plugins/external-agents/defaults.json new file mode 100644 index 00000000000..e717330823e --- /dev/null +++ b/plugins/external-agents/defaults.json @@ -0,0 +1,14 @@ +{ + "schema": 1, + "codex": { + "timeout_seconds": 1800, + "uses": { + "task": { "mode": "write" }, + "investigate": { "mode": "read-only" }, + "review": { "mode": "read-only" } + }, + "council": { "enabled": true } + }, + "breaker": { "cooldown_hours": 24 }, + "jobs": { "keep": 50 } +} diff --git a/plugins/external-agents/lib/cli-version-check.mjs b/plugins/external-agents/lib/cli-version-check.mjs new file mode 100644 index 00000000000..2863e96e9c9 --- /dev/null +++ b/plugins/external-agents/lib/cli-version-check.mjs @@ -0,0 +1,143 @@ +// GENERATED from lib/cli-version-check.mjs by scripts/sync-shared-copies.sh. Do not edit this copy: +// edit the canonical source, then rerun the script. +import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +export const DAY_MS = 24 * 60 * 60 * 1000; +const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const NPM = /^npm:((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)$/; +const GITHUB = /^github:([A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*)$/; + +const USAGE = `usage: + node cli-version-check.mjs check --state-dir DIR --cli NAME --installed TEXT --source npm:|github:/ [--hint TEXT] [--json] + node cli-version-check.mjs claim --state-dir DIR --name NAME (exit 0 when due, 1 when already run today)`; + +function machineStateFile(stateDir, name) { + if (!stateDir) throw new Error("stateDir is required"); + if (typeof name !== "string" || !NAME.test(name)) throw new Error(`invalid name: ${name}`); + return join(stateDir, "cli-version-check", `${name}.json`); +} + +function lastClaim(file) { + try { + return Date.parse(JSON.parse(readFileSync(file, "utf8")).checked_at); + } catch { + return NaN; + } +} + +export const STALE_LOCK_MS = 30_000; + +function exclusively(file, claim) { + const lock = `${file}.lock`; + mkdirSync(dirname(file), { recursive: true }); + for (const mayBreakStaleLock of [true, false]) { + try { + closeSync(openSync(lock, "wx")); + } catch (err) { + if (err.code !== "EEXIST") throw err; + const heldSince = statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0; + if (mayBreakStaleLock && Date.now() - heldSince > STALE_LOCK_MS) { + rmSync(lock, { force: true }); + continue; + } + return false; + } + try { + return claim(); + } finally { + rmSync(lock, { force: true }); + } + } + return false; +} + +export function claimDaily({ stateDir, name, now = Date.now() }) { + const file = machineStateFile(stateDir, name); + return exclusively(file, () => { + const last = lastClaim(file); + if (last <= now && now - last < DAY_MS) return false; + const tmp = `${file}.${process.pid}.tmp`; + writeFileSync(tmp, `${JSON.stringify({ checked_at: new Date(now).toISOString() })}\n`); + renameSync(tmp, file); + return true; + }); +} + +export function parseVersion(text) { + return /\d+(?:\.\d+)+/.exec(String(text ?? ""))?.[0] ?? null; +} + +export function compareVersions(a, b) { + const x = a.split(".").map(Number); + const y = b.split(".").map(Number); + for (let i = 0; i < Math.max(x.length, y.length); i++) { + const d = (x[i] ?? 0) - (y[i] ?? 0); + if (d) return Math.sign(d); + } + return 0; +} + +function release(source) { + let m = NPM.exec(source); + if (m) return { url: `https://registry.npmjs.org/${m[1]}/latest`, field: "version" }; + m = GITHUB.exec(source); + if (m) return { url: `https://api.github.com/repos/${m[1]}/releases/latest`, field: "tag_name" }; + throw new Error(`invalid source: ${source} (expected npm: or github:/)`); +} + +export async function checkVersion({ stateDir, cli, installed, source, hint = "", now = Date.now(), fetch = globalThis.fetch, timeoutMs = 3000 }) { + const { url, field } = release(source); + // Claimed before the lookup so a failed one also waits a day: unauthenticated api.github.com allows 60 requests an hour per IP, https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api + if (!claimDaily({ stateDir, name: cli, now })) return { status: "skipped" }; + const tail = String(hint).replace(/\s+/g, " ").trim(); + const withHint = (text) => (tail ? `${text} ${tail}` : text); + const have = parseVersion(installed); + if (!have) return { status: "not-installed", message: withHint(`${cli} is not installed or printed no version.`) }; + let latest = null; + let reason = "no version in the response"; + try { + const res = await fetch(url, { headers: { accept: "application/json", "user-agent": "cli-version-check" }, signal: AbortSignal.timeout(timeoutMs) }); + if (res.ok) latest = parseVersion((await res.json())?.[field]); + else reason = `HTTP ${res.status}`; + } catch (err) { + reason = err?.name === "TimeoutError" ? `no answer in ${timeoutMs} ms` : String(err?.message ?? err); + } + if (!latest) return { status: "unverified", installed: have, message: `${cli}: could not read the latest release from ${url} (${reason}); next check in 24 hours.` }; + if (compareVersions(have, latest) < 0) return { status: "behind", installed: have, latest, message: withHint(`${cli} ${have} is behind ${latest}.`) }; + return { status: "current", installed: have, latest }; +} + +async function main(argv) { + const [command, ...rest] = argv; + const { values } = parseArgs({ + args: rest, + options: { + "state-dir": { type: "string" }, + cli: { type: "string" }, + name: { type: "string" }, + installed: { type: "string", default: "" }, + source: { type: "string" }, + hint: { type: "string", default: "" }, + json: { type: "boolean", default: false }, + }, + }); + if (command === "claim") return claimDaily({ stateDir: values["state-dir"], name: values.name }) ? 0 : 1; + if (command !== "check") throw new Error(`unknown command: ${command ?? "(none)"}\n${USAGE}`); + const result = await checkVersion({ stateDir: values["state-dir"], cli: values.cli, installed: values.installed, source: values.source, hint: values.hint }); + if (values.json) process.stdout.write(`${JSON.stringify(result)}\n`); + else if (result.message) process.stdout.write(`${result.message}\n`); + return 0; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main(process.argv.slice(2)).then( + (code) => process.exit(code), + (err) => { + process.stderr.write(`cli-version-check: ${err.message}\n`); + process.exit(2); + }, + ); +} diff --git a/plugins/external-agents/lib/config-cascade.mjs b/plugins/external-agents/lib/config-cascade.mjs new file mode 100644 index 00000000000..4cca08955c5 --- /dev/null +++ b/plugins/external-agents/lib/config-cascade.mjs @@ -0,0 +1,581 @@ +// GENERATED from lib/config-cascade.mjs by scripts/sync-shared-copies.sh. Do not edit this copy: +// edit the canonical source, then rerun the script. +// The four-layer plugin config cascade (docs/adr/0075): later layers win per key. +// +// resolve({plugin, projectRoot, home, schema, defaults, userConfig, teamOnly, floors, userHome}) +// -> {values, provenance: {"a.b": layer | [layers]}, prose: [paths], sections: [{heading, text, layer}], +// layers: [{name, path, state: "loaded" | "absent" | "invalid", errors, error_keys}], legacy: [{path, kind}]} +// +// readLayers({...}) -> each layer's own accepted values, unmerged (see its comment below) +// +// fileState(path) -> {ok} | {refused: why} | {}, and escapes(dir, root) -> boolean: the path +// guards the file layers use, for a caller that reads other repository files the same way +// +// `error_keys[i]` tags `errors[i]`: the dotted key the error names (key-level), or null when it is +// about the layer as a whole (file-level: a file refused or unparsable, a value that is not a mapping). +// +// Layers, in order: "defaults" (the `defaults` object, already parsed by the caller), "userConfig" +// (the plugin's userConfig values, flattened names), "team" (/) and "local", the +// personal override (/.local). A file layer reads .yaml for config and .md +// for prose; it is absent when neither file exists. `home` is the convention home the caller +// resolved, relative to projectRoot unless absolute (default docs/conventions). There is no +// user-global file layer: a file under /docs/conventions is never read, and `userHome` +// (default os.homedir()) only locates the legacy files reported in `legacy`. `schema` is a JSON +// Schema object; the subset honored is type (object, string, array, null, integer, number, boolean), +// enum, properties, additionalProperties (false or a schema), items, minimum, maximum, minItems and +// maxItems. +// +// A key is a schema leaf: any node that is not an object with `properties`, or a path named in +// `teamOnly`. The setup writer's top-level `written_against` and `provenance` records are not keys, +// declared or not: every layer skips them, so they reach neither `values` nor a userConfig name. +// Each layer's leaves are checked one by one; a leaf whose value fails the schema is +// dropped from that layer with an error naming layer, file and key, and a lower layer's value is +// then never used (ADR 0075, the invalid-value rule): a valid higher layer still wins, otherwise the +// key takes its default. The personal override is the one exception, because it refines the team +// file: an invalid personal value leaves the team value standing. A key containing `.` is +// rejected the same way, since keys are joined with `.` into paths, and so are `__proto__`, +// `constructor` and `prototype`, at any depth inside a value too, which a caller's merge would treat +// as more than data. A refused file makes its layer invalid; the layer's other file still applies. The team and +// local layers come from the repository: each reads only regular files, never a symlink, and is +// invalid when a relative `home` resolves outside projectRoot. A team-only key is +// accepted in "defaults" and "team" and rejected elsewhere. A YAML file that does not parse, or +// whose top level is not a mapping, makes its layer invalid and contributes no values; its .md +// file still supplies prose. A leaf whose last segment is `disable` and whose value is a list is the +// union of every layer's list, and its provenance is an array of the layer names that set it, in +// layer order; every other key's provenance is a single layer-name string. +// +// Policy floors. `floors` maps a key path to a `Floor direction` value (the Implementers table of +// docs/contracts/config-cascade/README.md; the closed set is no-floor, team-only, lowest-value, +// any-layer-wins and stricter-value), or to {direction, scale} where stricter-value takes a scale +// from loosest to strictest (default: the leaf's schema `enum` order). When the team layer set a +// floor key, a personal value is accepted only if it is no looser in that direction: team-only takes +// an equal value (a list must keep every team item); lowest-value a number no higher; any-layer-wins +// a tightening value (`true` or "report") whenever the team value is one; stricter-value a value at +// or beyond the team value on the scale. A looser value is dropped with an error naming the layer, +// file and key, and the team value stands. Floors bind the personal override; a `*.disable` union key +// is not compared. +// +// userConfig maps each schema leaf path to its name joined with `_` (widget.limit is widget_limit); +// two leaves with one name throw. An empty string or an unrendered `${user_config.` placeholder is +// unset, names outside the schema are ignored, and a list, mapping or team-only key is rejected. +// A string value takes the leaf's integer, number or boolean type when the leaf does not accept +// strings. Legacy locations (.claude/.* under userHome and projectRoot, and a fenced +// `yaml config` block in the team .md) are reported in `legacy`, never read for values. +// +// Prose. A `.local.md` H2 section (a `## ` heading outside a code fence) replaces the team `.md` +// section with the same heading; every other team section is kept, a local section with a new +// heading follows them, and the team text before the first H2 is kept. `sections` lists the result in +// order, each with the layer it came from (`heading` is null for text before the first H2). +// This module reads files only. File contents are data; error messages quote them as JSON strings. +import { lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path"; +import { parse } from "./yaml-subset.mjs"; + +const PLUGIN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const SCALARS = ["string", "integer", "number", "boolean", "null"]; +const DIRECTIONS = ["no-floor", "team-only", "lowest-value", "any-layer-wins", "stricter-value"]; +const clip = (text) => (text.length > 60 ? `${text.slice(0, 60)}...` : text); +const quote = (text) => JSON.stringify(clip(text)); +const show = (value) => clip(JSON.stringify(value) ?? String(value)); +const put = (object, key, value) => Object.defineProperty(object, key, { value, enumerable: true, writable: true, configurable: true }); +const isMapping = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const RESERVED = new Set(["__proto__", "constructor", "prototype"]); +const WRITER_KEYS = new Set(["written_against", "provenance"]); +const isWriterKey = (parts, key) => !parts.length && WRITER_KEYS.has(key); +const newLayer = (name, path, state, errors = [], error_keys = errors.map(() => null)) => ({ name, path, state, errors, error_keys }); +/** Records an error on `layer`, tagged with the dotted key it names, or null for a file-level one. */ +const record = (layer, message, key = null) => { + layer.errors.push(message); + layer.error_keys.push(key); +}; +/** Records `message` on `layer`, prefixed with the layer's name and path. */ +const recordOn = (layer, message, key) => record(layer, `${layer.name}${layer.path ? ` (${layer.path})` : ""}: ${message}`, key); + +function checkPlugin(plugin) { + if (typeof plugin !== "string" || !PLUGIN.test(plugin)) throw new Error(`config-cascade: plugin name ${JSON.stringify(plugin)} is not a plain name`); +} + +/** The convention home, whether a relative one escapes projectRoot, and the [name, stem] of each file layer. */ +function fileLayersOf(plugin, projectRoot, home) { + const homeDir = resolvePath(projectRoot, home); + // A relative home is inside the checkout by intent; a committed symlink must not carry it out. + const homeEscapes = !isAbsolute(home) && escapes(homeDir, projectRoot); + const stems = [ + ["team", join(homeDir, plugin)], + ["local", join(homeDir, `${plugin}.local`)], + ]; + return { homeDir, homeEscapes, stems }; +} + +const escapedLayer = (name, stem, homeDir) => + newLayer(name, `${stem}.yaml`, "invalid", [`${name} (${homeDir}): the convention home resolves outside the project; a repository layer stays inside it`]); + +/** {ok} for a readable repository layer file, {refused: why} for one that must not be read, {} when + * absent. A symlink is refused, since it could reach a file outside the checkout, and so is anything + * but a regular file, since a device or FIFO never finishes reading. */ +export function fileState(path) { + let st; + try { + st = lstatSync(path); + } catch { + return {}; + } + if (st.isSymbolicLink()) return { refused: "is a symlink; a repository layer reads only regular files" }; + return st.isFile() ? { ok: true } : { refused: "is not a regular file" }; +} + +/** True when `dir` exists and its real path lies outside the real path of `root`. */ +export function escapes(dir, root) { + try { + const rel = relative(realpathSync(root), realpathSync(dir)); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + } catch { + return false; + } +} +const typesOf = (node) => (node.type === undefined ? null : [node.type].flat()); + +const fits = { + object: isMapping, + array: Array.isArray, + string: (v) => typeof v === "string", + integer: Number.isInteger, + number: (v) => typeof v === "number" && Number.isFinite(v), + boolean: (v) => typeof v === "boolean", + null: (v) => v === null, +}; + +/** The schema for `key` under `node`: a schema, null when anything goes, false when it is unknown. */ +function child(node, key) { + if (isMapping(node.properties) && Object.hasOwn(node.properties, key)) return node.properties[key]; + if (node.additionalProperties === false) return false; + return isMapping(node.additionalProperties) ? node.additionalProperties : null; +} + +const isBranch = (node, path, teamOnly) => + isMapping(node) && isMapping(node.properties) && !teamOnly.has(path) && (typesOf(node)?.includes("object") ?? true); + +/** Why `value` does not fit `node`, as messages relative to the key; empty when it fits. */ +function check(value, node, at = "") { + const prefix = at ? `${at}: ` : ""; + const types = typesOf(node); + if (types && !types.some((t) => fits[t]?.(value))) return [`${prefix}expected ${types.join(" or ")}, got ${show(value)}`]; + if (Array.isArray(node.enum) && !node.enum.includes(value)) return [`${prefix}${show(value)} is not one of ${node.enum.map(show).join(", ")}`]; + if (typeof value === "number" && typeof node.minimum === "number" && value < node.minimum) return [`${prefix}${show(value)} must be at least ${node.minimum}`]; + if (typeof value === "number" && typeof node.maximum === "number" && value > node.maximum) return [`${prefix}${show(value)} must be at most ${node.maximum}`]; + if (Array.isArray(value) && typeof node.minItems === "number" && value.length < node.minItems) return [`${prefix}needs at least ${node.minItems} items, got ${value.length}`]; + if (Array.isArray(value) && typeof node.maxItems === "number" && value.length > node.maxItems) return [`${prefix}allows at most ${node.maxItems} items, got ${value.length}`]; + // An open node ({}) checks nothing but reserved names, which are refused at every depth. + if (Array.isArray(value)) return value.flatMap((item, i) => check(item, isMapping(node.items) ? node.items : {}, `${at}[${i}]`)); + if (!isMapping(value)) return []; + return Object.keys(value).flatMap((key) => { + const where = `${at}.${quote(key)}`; + if (RESERVED.has(key)) return [`${where}: a reserved name, never a config key`]; + const sub = child(node, key); + if (sub === false) return [`${where}: unknown key`]; + return check(value[key], sub ?? {}, where); + }); +} + +/** The accepted leaves of one layer's mapping, as [parts, value] pairs; rejections go to `fail` + * with the dotted key, and `true` third when the value itself was the problem. */ +function leaves(data, schema, { teamOnly, allowTeamOnly, fail }) { + const out = []; + const walk = (object, node, parts) => { + for (const key of Object.keys(object)) { + if (isWriterKey(parts, key)) continue; + const path = [...parts, key]; + const dotted = path.join("."); + const sub = child(node, key); + const value = object[key]; + if (RESERVED.has(key)) fail(`${quote(dotted)}: a reserved name, never a config key`, dotted); + else if (key.includes(".")) fail(`${quote(dotted)}: a key may not contain "."; nest it instead`, dotted); + else if (sub === false) fail(`${quote(dotted)}: unknown key`, dotted); + else if (teamOnly.has(dotted) && !allowTeamOnly) fail(`${quote(dotted)}: accepted only in the team layer`, dotted); + else if (sub && isBranch(sub, dotted, teamOnly)) { + if (isMapping(value)) walk(value, sub, path); + else if (value !== null) fail(`${quote(dotted)}: expected a mapping, got ${show(value)}`, dotted, true); + } else { + const problems = check(value, sub ?? {}); + if (problems.length) fail(`${quote(dotted)}: ${problems.join("; ")}`, dotted, true); + else out.push([path, value]); + } + } + }; + walk(data, schema, []); + return out; +} + +/** Flattened userConfig name to {path, node} for every schema leaf. */ +function flatNames(schema, teamOnly) { + const names = new Map(); + const walk = (node, parts) => { + for (const key of Object.keys(isMapping(node.properties) ? node.properties : {})) { + if (isWriterKey(parts, key)) continue; + const path = [...parts, key]; + const dotted = path.join("."); + const sub = node.properties[key]; + if (isBranch(sub, dotted, teamOnly)) { + walk(sub, path); + continue; + } + const name = path.join("_"); + if (names.has(name)) throw new Error(`config-cascade: schema keys ${names.get(name).dotted} and ${dotted} both flatten to userConfig name ${name}`); + names.set(name, { path, dotted, node: sub }); + } + }; + walk(schema, []); + return names; +} + +function coerce(raw, node) { + const types = typesOf(node) ?? []; + if (typeof raw !== "string" || types.includes("string")) return raw; + if ((types.includes("integer") || types.includes("number")) && /^[-+]?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (types.includes("boolean") && (raw === "true" || raw === "false")) return raw === "true"; + return raw; +} + +function userConfigLeaves(userConfig, names, teamOnly, fail) { + const out = []; + for (const [name, raw] of Object.entries(userConfig)) { + if (raw === undefined || raw === null || raw === "" || (typeof raw === "string" && raw.startsWith("${user_config."))) continue; + const leaf = names.get(name); + if (!leaf) continue; + const types = typesOf(leaf.node); + if (teamOnly.has(leaf.dotted)) fail(`${quote(leaf.dotted)}: accepted only in the team layer`, leaf.dotted); + else if (types && !types.every((t) => SCALARS.includes(t))) fail(`${quote(leaf.dotted)}: lists and mappings are set only in files`, leaf.dotted); + else { + const value = coerce(raw, leaf.node); + const problems = check(value, leaf.node); + if (problems.length) fail(`${quote(leaf.dotted)}: ${problems.join("; ")}`, leaf.dotted, true); + else out.push([leaf.path, value]); + } + } + return out; +} + +/** One file layer: its report entry, its parsed mapping (or null), and its prose path (or null). */ +function readLayer(name, stem) { + const path = `${stem}.yaml`; + const md = `${stem}.md`; + const layer = newLayer(name, path, "absent"); + const mdFile = fileState(md); + if (mdFile.refused) { + layer.state = "invalid"; + record(layer, `${name} (${md}): ${mdFile.refused}`); + } + const prose = mdFile.ok ? md : null; + if (prose) layer.state = "loaded"; + const yamlFile = fileState(path); + if (yamlFile.refused) { + layer.state = "invalid"; + record(layer, `${name} (${path}): ${yamlFile.refused}`); + } + if (!yamlFile.ok) return { layer, data: null, prose }; + return { layer, data: parseInto(layer, () => readFileSync(path, "utf8")), prose }; +} + +/** The mapping `text()` parses to, loading `layer`; null, with the layer invalid, when it does not parse or is not a mapping. */ +function parseInto(layer, text) { + try { + const doc = parse(text()) ?? {}; + if (!isMapping(doc)) throw new Error("the top level must be a mapping"); + if (layer.state !== "invalid") layer.state = "loaded"; + return doc; + } catch (e) { + layer.state = "invalid"; + record(layer, `${layer.name} (${layer.path}): ${e.message}`); + return null; + } +} + +/** The body of the first ``` config block outside any other fence in a Markdown text, running to + * the end when unclosed; null when there is none. */ +export function configBlockBody(text) { + let fence = null; // the open fence's marker run, backticks or tildes + let body = null; + for (const line of text.split(/\r\n|\r|\n/)) { + const run = line.match(/^(`{3,}|~{3,})/)?.[0]; + if (fence) { + if (run?.[0] === fence[0] && run.length >= fence.length && line.trimEnd().length === run.length) { + if (body) return body.join("\n"); + fence = null; + } else body?.push(line); + } else if (/^```[A-Za-z0-9_-]+ config\s*$/.test(line)) [fence, body] = ["```", []]; + else if (run) fence = run; + } + return body?.join("\n") ?? null; +} + +/** True when the Markdown file holds a ``` config block outside any other fence. */ +function hasConfigBlock(path) { + const text = fileState(path).ok ? readText(path) : null; + return text !== null && configBlockBody(text) !== null; +} + +/** A Markdown text as [{heading, text}], split at each H2 outside a code fence; the first entry holds + * the text before the first H2 (heading null) and is dropped when empty. */ +function splitSections(text) { + const out = [{ heading: null, lines: [] }]; + let fence = null; + for (const line of text.split(/(?<=\n)/)) { + const run = line.match(/^ {0,3}(`{3,}|~{3,})/)?.[1]; + if (fence) { + if (run?.[0] === fence[0] && run.length >= fence.length && line.trim().length === run.length) fence = null; + } else if (run) fence = run; + else { + const h = line.match(/^## +(.*?)(?: +#+)?\s*$/); + if (h) { + out.push({ heading: h[1].replace(/\s+/g, " ").trim(), lines: [line] }); + continue; + } + } + out.at(-1).lines.push(line); + } + return out.map(({ heading, lines }) => ({ heading, text: lines.join("") })).filter((s) => s.heading !== null || s.text.trim() !== ""); +} + +function readText(path) { + try { + return readFileSync(path, "utf8"); + } catch { + return null; + } +} + +/** The team sections with each same-heading local section in its place, then the local sections the + * team lacks. The first team section with a heading is replaced; a later team repeat of it is dropped. */ +function mergeSections(teamText, localText) { + const team = teamText === null ? [] : splitSections(teamText).map((s) => ({ ...s, layer: "team" })); + const local = localText === null ? [] : splitSections(localText).map((s) => ({ ...s, layer: "local" })); + const replacement = new Map(local.filter((s) => s.heading !== null).map((s) => [s.heading, s])); + const used = new Set(); + const out = []; + for (const s of team) { + if (s.heading === null || !replacement.has(s.heading)) out.push(s); + else if (!used.has(s.heading)) { + used.add(s.heading); + out.push(replacement.get(s.heading)); + } + } + const teamHeadings = new Set(team.map((s) => s.heading)); + for (const s of local) { + // Text before the first H2 follows the team's own only when the team has no file; a repeated heading keeps its last section. + const fresh = s.heading === null ? team.length === 0 : !teamHeadings.has(s.heading) && replacement.get(s.heading) === s; + if (fresh) out.push(s); + } + return out; +} + +function legacyFiles(dir, plugin, kind) { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + return []; + } + return entries.filter((e) => e.isFile() && e.name.startsWith(`${plugin}.`)).map((e) => ({ path: join(dir, e.name), kind: kind(e.name) })); +} + +function setPath(object, parts, value) { + let at = object; + for (const part of parts.slice(0, -1)) { + if (!Object.hasOwn(at, part) || !isMapping(at[part])) put(at, part, {}); + at = at[part]; + } + put(at, parts.at(-1), value); +} + +/** Validated floors: dotted key to {direction, scale}. */ +function normalizeFloors(floors) { + if (!isMapping(floors)) throw new Error("config-cascade: floors must be a mapping of key path to Floor direction"); + const out = new Map(); + for (const [key, raw] of Object.entries(floors)) { + const direction = typeof raw === "string" ? raw : raw?.direction; + if (!DIRECTIONS.includes(direction)) throw new Error(`config-cascade: floor ${JSON.stringify(key)} has direction ${show(direction)}, not one of ${DIRECTIONS.join(", ")}`); + out.set(key, { direction, scale: isMapping(raw) && Array.isArray(raw.scale) ? raw.scale : null }); + } + return out; +} + +function nodeAt(schema, parts) { + let node = schema; + for (const part of parts) { + node = node && child(node, part); + if (!node) return null; + } + return node; +} + +const tightening = (v) => v === true || v === "report"; + +/** Why `personal` loosens `team` in the floor's direction, or null when it does not. */ +function looser(floor, personal, team, node) { + if (JSON.stringify(personal) === JSON.stringify(team)) return null; + switch (floor.direction) { + case "team-only": + if (Array.isArray(personal) && Array.isArray(team) && team.every((t) => personal.some((p) => JSON.stringify(p) === JSON.stringify(t)))) return null; + return `${show(personal)} differs from the team value ${show(team)}, and the team value wins`; + case "lowest-value": + if (typeof personal === "number" && typeof team === "number" && personal <= team) return null; + return `${show(personal)} is not lower than or equal to the team value ${show(team)}`; + case "any-layer-wins": + if (!tightening(team) || tightening(personal)) return null; + return `${show(personal)} drops the team value ${show(team)}, which is the tightening one`; + case "stricter-value": { + const scale = floor.scale ?? node?.enum ?? []; + const a = scale.findIndex((v) => JSON.stringify(v) === JSON.stringify(personal)); + const b = scale.findIndex((v) => JSON.stringify(v) === JSON.stringify(team)); + if (a >= 0 && b >= 0 && a >= b) return null; + return `${show(personal)} is not as strict as the team value ${show(team)} on the scale ${show(scale)}`; + } + default: + return null; + } +} + +export function resolve({ plugin, projectRoot, home = "docs/conventions", schema, defaults, userConfig, teamOnly = [], floors = {}, userHome = homedir() }) { + checkPlugin(plugin); + const only = new Set(teamOnly); + const floorMap = normalizeFloors(floors); + const names = flatNames(schema, only); + const { homeDir, homeEscapes, stems } = fileLayersOf(plugin, projectRoot, home); + const layers = []; + const contributions = []; // [layer name, [[parts, value]], dotted keys whose value was invalid] + const prose = []; + const proseText = {}; + + // pairsOf(fail) returns the layer's accepted [parts, value] pairs; falsy when it contributes none. + const take = (layer, pairsOf) => { + const invalid = new Set(); + const fail = (message, key, valueFailed = false) => { + recordOn(layer, message, key); + if (valueFailed) invalid.add(key); + }; + if (pairsOf) contributions.push([layer.name, pairsOf(fail), invalid]); + layers.push(layer); + }; + const fileLeaves = (data, allowTeamOnly) => data && ((fail) => leaves(data, schema, { teamOnly: only, allowTeamOnly, fail })); + + const shaped = (name, given) => { + if (given === undefined || given === null) return { layer: newLayer(name, null, "absent"), ok: false }; + if (isMapping(given)) return { layer: newLayer(name, null, "loaded"), ok: true }; + return { layer: newLayer(name, null, "invalid", [`${name}: expected a mapping, got ${show(given)}`]), ok: false }; + }; + const d = shaped("defaults", defaults); + take(d.layer, d.ok && fileLeaves(defaults, true)); + const u = shaped("userConfig", userConfig); + take(u.layer, u.ok && ((fail) => userConfigLeaves(userConfig, names, only, fail))); + for (const [name, stem] of stems) { + if (homeEscapes) { + take(escapedLayer(name, stem, homeDir)); + continue; + } + const read = readLayer(name, stem); + take(read.layer, fileLeaves(read.data, name === "team")); + if (read.prose) { + prose.push(read.prose); + proseText[name] = readText(read.prose); + } + } + + const merged = new Map(); // dotted -> {parts, value, from} + let base = new Map(); // the defaults layer's entries, where an invalid higher value falls back to + const within = (dotted, key) => dotted === key || dotted.startsWith(`${key}.`); + for (const [name, pairs, invalid] of contributions) { + // A lower layer's value is never used for an invalid one; the personal override refines the team file, so its keys fall to team. + if (name !== "local") { + for (const key of invalid) { + for (const dotted of [...merged.keys()]) if (within(dotted, key)) merged.delete(dotted); + for (const [dotted, entry] of base) if (within(dotted, key)) merged.set(dotted, entry); + } + } + const layer = layers.find((l) => l.name === name); + for (const [parts, value] of pairs) { + const dotted = parts.join("."); + const prior = merged.get(dotted); + const floor = floorMap.get(dotted); + const union = parts.at(-1) === "disable" && Array.isArray(value); + if (name === "local" && floor && floor.direction !== "no-floor" && !union && prior && [prior.from].flat().includes("team")) { + const why = looser(floor, value, prior.value, nodeAt(schema, parts)); + if (why) { + record(layer, `local (${layer.path}): ${quote(dotted)}: loosens the ${floor.direction} policy floor: ${why}`, dotted); + continue; + } + } + if (union) { + const items = Array.isArray(prior?.value) ? [...prior.value] : []; + const seen = new Set(items.map((i) => JSON.stringify(i))); + for (const item of value) { + const key = JSON.stringify(item); + if (!seen.has(key)) items.push(item); + seen.add(key); + } + // An empty list adds nothing, so its layer is credited only when no layer set the key before. + const from = Array.isArray(prior?.from) ? prior.from : []; + merged.set(dotted, { parts, value: items, from: value.length > 0 || !prior ? [...from, name] : from }); + } else merged.set(dotted, { parts, value, from: name }); + } + if (name === "defaults") base = new Map(merged); + } + const values = {}; + const provenance = {}; + for (const [dotted, { parts, value, from }] of merged) { + setPath(values, parts, value); + put(provenance, dotted, from); + } + + const legacy = legacyOf(plugin, userHome, projectRoot, !homeEscapes && `${join(homeDir, plugin)}.md`); + const sections = mergeSections(proseText.team ?? null, proseText.local ?? null).map(({ heading, text, layer }) => ({ heading, text, layer })); + return { values, provenance, prose, sections, layers, legacy }; +} + +/** The legacy locations that exist; `teamMd` (or false) is the team .md checked for a fenced config block. */ +function legacyOf(plugin, userHome, projectRoot, teamMd) { + const found = [ + ...legacyFiles(join(userHome, ".claude"), plugin, () => "claude-user"), + ...(projectRoot ? legacyFiles(join(projectRoot, ".claude"), plugin, (n) => (n.startsWith(`${plugin}.local.`) ? "claude-local" : "claude-project")) : []), + ...(teamMd && hasConfigBlock(teamMd) ? [{ path: teamMd, kind: "fenced-block" }] : []), + ]; + // The project root may be the user home, so a file is reported under its first kind only. + return found.filter((entry, i) => found.findIndex((e) => e.path === entry.path) === i); +} + +/** + * Each layer's own accepted values, unmerged, for a caller that weighs the layers itself (the + * rendered-views publish rule reads every layer separately: lib/view-settings.mjs). The same reader, + * refusals and schema check as resolve(), with no precedence, floors or invalid-value fallback: an + * invalid value leaves only its own layer. Layers: "userConfig", then "team" and "local" when + * projectRoot is set. `team`, as {path, text}, replaces the working-tree team file (text null: + * absent), for a caller reading it from a git ref. + * readLayers({plugin, projectRoot, home, schema, userConfig, teamOnly, team, userHome}) + * -> {layers: [{name, path, state, errors, error_keys, values: {"a.b": value}}], legacy} + */ +export function readLayers({ plugin, projectRoot = null, home = "docs/conventions", schema, userConfig, teamOnly = [], team, userHome = homedir() }) { + checkPlugin(plugin); + const only = new Set(teamOnly); + const layers = []; + const add = (layer, pairsOf) => { + const values = {}; + for (const [parts, value] of pairsOf ? pairsOf((message, key) => recordOn(layer, message, key)) : []) put(values, parts.join("."), value); + layers.push({ ...layer, values }); + }; + if (isMapping(userConfig)) add(newLayer("userConfig", null, "loaded"), (fail) => userConfigLeaves(userConfig, flatNames(schema, only), only, fail)); + if (!projectRoot) return { layers, legacy: legacyOf(plugin, userHome, null, false) }; + const { homeDir, homeEscapes, stems } = fileLayersOf(plugin, projectRoot, home); + for (const [name, stem] of stems) { + const fileLeaves = (data) => data && ((fail) => leaves(data, schema, { teamOnly: only, allowTeamOnly: name === "team", fail })); + if (name === "team" && team) { + const layer = newLayer(name, team.path, "absent"); + add(layer, typeof team.text === "string" && fileLeaves(parseInto(layer, () => team.text))); + } else if (homeEscapes) { + add(escapedLayer(name, stem, homeDir)); + } else { + const read = readLayer(name, stem); + add(read.layer, fileLeaves(read.data)); + } + } + return { layers, legacy: legacyOf(plugin, userHome, projectRoot, !homeEscapes && `${join(homeDir, plugin)}.md`) }; +} diff --git a/plugins/external-agents/lib/prerequisites.mjs b/plugins/external-agents/lib/prerequisites.mjs new file mode 100755 index 00000000000..2956c9bbfe5 --- /dev/null +++ b/plugins/external-agents/lib/prerequisites.mjs @@ -0,0 +1,899 @@ +#!/usr/bin/env node +// GENERATED from lib/prerequisites.mjs by scripts/sync-shared-copies.sh. Do not edit this copy: +// edit the canonical source, then rerun the script. +// Read a plugin's prerequisites.json and report which declared dependencies resolve. +// The contract is docs/contracts/prerequisites/README.md; the schema sits beside it. +// +// prerequisites.mjs report --plugin-root [--plugin-root ...] +// prerequisites.mjs check [--for ] [--data-dir ] +// prerequisites.mjs probe [--run-if-unset-or-true