From 1dce3433b137a3548c8177e4370b4258a2cf1bbd Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:44:26 -0500 Subject: [PATCH 01/25] feat(external-agents): scaffold the plugin and exempt its bin/ from the no-bin gate New plugin external-agents: manifest, README, catalog entry, team config schema, the Codex prerequisite with its github latest-release source, shared copies of config-cascade, yaml-subset, cli-version-check and the prerequisites checker, and the bin/external-agents shim (usage only). scripts/check-plugin-manifest-presence.sh rule 3 now skips plugins/external-agents/bin, because review:council needs its command on PATH; any other plugin's bin/ still fails, with a test case for each. The plugin is left out of claude.ai organization sync (owner decision). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015XWwmfSVU9f2by5nqbM3Ak --- .../feat-external-agents-95264810.md | 7 + .claude-plugin/marketplace.json | 13 + .github/workflows/pr-require-checks.yml | 2 +- docs/catalog.md | 1 + docs/contracts/config-cascade/README.md | 2 + .../.claude-plugin/plugin.json | 21 + plugins/external-agents/CHANGELOG.md | 4 + plugins/external-agents/README.md | 46 + plugins/external-agents/bin/external-agents | 7 + .../external-agents/lib/cli-version-check.mjs | 143 +++ .../external-agents/lib/config-cascade.mjs | 581 +++++++++++ plugins/external-agents/lib/prerequisites.mjs | 899 ++++++++++++++++++ plugins/external-agents/lib/prerequisites.ps1 | 58 ++ plugins/external-agents/lib/prerequisites.sh | 73 ++ plugins/external-agents/lib/yaml-subset.mjs | 313 ++++++ plugins/external-agents/prerequisites.json | 46 + .../schemas/external-agents.schema.json | 69 ++ .../scripts/external-agents.mjs | 19 + scripts/check-plugin-manifest-presence.sh | 5 +- .../check-plugin-manifest-presence.test.sh | 23 + scripts/fragment-plugins.txt | 1 + scripts/shared-copies.txt | 6 + 22 files changed, 2336 insertions(+), 3 deletions(-) create mode 100644 .changes/external-agents/feat-external-agents-95264810.md create mode 100644 plugins/external-agents/.claude-plugin/plugin.json create mode 100644 plugins/external-agents/CHANGELOG.md create mode 100644 plugins/external-agents/README.md create mode 100755 plugins/external-agents/bin/external-agents create mode 100644 plugins/external-agents/lib/cli-version-check.mjs create mode 100644 plugins/external-agents/lib/config-cascade.mjs create mode 100644 plugins/external-agents/lib/prerequisites.mjs create mode 100644 plugins/external-agents/lib/prerequisites.ps1 create mode 100644 plugins/external-agents/lib/prerequisites.sh create mode 100644 plugins/external-agents/lib/yaml-subset.mjs create mode 100644 plugins/external-agents/prerequisites.json create mode 100644 plugins/external-agents/schemas/external-agents.schema.json create mode 100644 plugins/external-agents/scripts/external-agents.mjs 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..f9f902baad4 --- /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 scaffold: the `external-agents` command (usage only for now), the team config schema for `/external-agents.yaml`, and the Codex prerequisite with its daily latest-release check. It replaces OpenAI's `codex@openai-codex` plugin once the runner and the Codex skill land. 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/catalog.md b/docs/catalog.md index 6bba436659b..27bb69a4123 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 dc7c5fdd422..bd74051e089 100644 --- a/docs/contracts/config-cascade/README.md +++ b/docs/contracts/config-cascade/README.md @@ -600,6 +600,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 | @@ -719,6 +720,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 by design: no `~/.claude` file and no `.claude/*.local` file. The resolver is not built yet, so nothing on `main` reads these layers | | `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/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..1df3b41cae9 --- /dev/null +++ b/plugins/external-agents/README.md @@ -0,0 +1,46 @@ +# 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 + +Scaffold only: the `external-agents` command prints its usage. The runner, the Codex skill and +council's switch-over follow in later changes. + +## 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. +- 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. + +## 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..94c0e753767 --- /dev/null +++ b/plugins/external-agents/bin/external-agents @@ -0,0 +1,7 @@ +#!/usr/bin/env node +const { join } = require("node:path"); +const { pathToFileURL } = require("node:url"); + +import(pathToFileURL(join(__dirname, "..", "scripts", "external-agents.mjs")).href) + .then(({ main }) => main(process.argv.slice(2))) + .then((code) => { process.exitCode = code; }); 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 100644 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