🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
docs(adr): ADR-503..510 — mods integration follow-ups (#4581) (#4585)
rUv9ec771996a26
diff --git a/v3/docs/adr/ADR-503-learning-loop-gaming-defences.md b/v3/docs/adr/ADR-503-learning-loop-gaming-defences.mdnew file mode 100644index 0000000000..fcbe797998--- /dev/null+++ b/v3/docs/adr/ADR-503-learning-loop-gaming-defences.md@@ -0,0 +1,91 @@+# ADR 503: hardening the verified-outcome learning loop against gamed signals++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 6. Builds on: ADR-502 (the loop, on by default since 3.64.0).++## 1. Context++ADR-502 trains SONA from turns whose outcome was decided by the exit status of a recognised test, build, typecheck or lint command.++The exit-status rules already cover two things:+- They refuse masked statuses: `|| true`, pipes, `;`, background jobs, command substitution, and segments that are not verifiers.+- They require at least one edit in the turn.++Four gaps remain.++- **The model controls what the verifier checks.** All of the following exit 0 honestly:+ - deleting or weakening a failing test;+ - marking a test `.skip`;+ - adding `--passWithNoTests`;+ - narrowing the command (`vitest run one-file.test.ts`);+ - editing the `test` script in `package.json` so `npm test` runs nothing.+- **The session reports its own results.** `verified-trajectories.jsonl` is a project file. Anything that can write to the project can append `verified-success` lines.+- **A single fixed check loses value over time.** Research on reward hacking (Anthropic, arXiv 2511.18397) finds that any fixed proxy is eventually gamed. That study trains model weights and ruflo's loop does not, so this is a design caution, not measured evidence about ruflo.+- **There is no baseline yet.** The §7 evaluation has not been run, so drift cannot be detected against anything.++## 2. Decision++Four layers, cheapest first. A layer can only downgrade a record (`verified-success` → `unknown`). No layer can upgrade one.++### 2.1 Mod: tamper signals within the turn++This layer needs no extra process. The mod already sees every finished tool call, so it can record which files were edited in each trajectory. At the end of the turn it adds taints to a `verified-success` record:++| Taint | Set when |+|---|---|+| `edited-tests` | An edited path is a test file: `*.test.*`, `*.spec.*`, anything under `__tests__/` or `tests/`, `test_*.py`, `*_test.go`, `*_test.rs`. |+| `edited-verifier-config` | An edited file can change what a verifier checks: `package.json`, `vitest.config.*`, `jest.config.*`, `pytest.ini`, `pyproject.toml`, `setup.cfg`, `tox.ini`, `Cargo.toml`, `go.mod`, `tsconfig*.json`, `.eslintrc*`, `eslint.config.*`, `Makefile`. |+| `narrowed-verifier` | The deciding command weakens or narrows the check: `--passWithNoTests`, `-t`/`--testNamePattern`/`-k`, `--skip`, `--exclude`, `--testPathIgnorePatterns`, or a test runner given one test-file argument. |++The record keeps its outcome word. The taints travel with it as `taint: [...]`.++### 2.2 CLI: tainted records do not train++`ingestVerifiedOutcomes` treats any tainted record as `unknown` for training:+- It is counted under a new `tainted` total.+- It is never sent to SONA.++A project can opt individual taint classes back in by setting `learningLoop.allowTaint` in `.claude-flow/config.json` (for example `["edited-verifier-config"]`). By default no class is allowed.++### 2.3 CLI: re-verify before training (opt-in, rotating)++This layer is controlled by `learningLoop.reverify` in `.claude-flow/config.json`. It is **off by default**, because it runs project code. When it is on, ingest re-runs a verifier before it trains a `verified-success` record:++- **Where it runs:** in a temporary detached `git worktree` at the current `HEAD`. The record stores which commit was used.+- **How long it may take:** a hard timeout, 300 s by default. On timeout, on any error, or on a non-zero exit, the record is downgraded to `unknown`.+- **Which check runs:** the checks rotate. When the project has more than one recognised verifier script (`test`, `typecheck`, `build`, `lint` in `package.json`, or `cargo test`/`cargo check`), ingest runs one the record did **not** use, round-robin across ingests. This way the model cannot learn which single check counts.+- **What it may run:** only commands from a fixed allowlist built from the project's own manifest. Text from the record is never executed.++### 2.4 CLI: anomaly gate on lessons++Before `buildLessons` turns a pattern into a prompt lesson, it holds the pattern back if any of these is true:++1. Its success rate is 100% over 8 or more records, and half or more of them carried an allowed taint.+2. Every success came from a narrowed (single-file) command.+3. All its successes arrived within one session, so there has been no independent repetition.++A held pattern stays in SONA, where routing still sees it only through SONA's own 0.6 gate. It never becomes a prompt lesson. `ruflo hooks verified-ingest` lists each one as `held: <id> (<reason>)`.++## 3. The evaluation that is still owed++A new script, `scripts/eval-learning-loop.mjs`, will:++- run a fixed set of 30 tasks with `claude -p`, once with `learningLoop` off and once with it on, using lessons pre-trained on a separate training split;+- report verified success rate, cost per verified success, and lesson hit rate.++The script is manual and costs money, so it is not part of CI. ADR-502 §6 still applies: if the evaluation shows no gain, or shows a cost regression, the default goes back to off.++## 4. Consequences++- **Fewer records train.** Genuine work that touches tests, such as a fix that adds a test, is held back by default. This trade is intended: a missed lesson costs little, while a learned hack degrades routing.+- **Re-verification is expensive.** It costs CPU and runs project code, which is why it is opt-in and off by default.++## 5. Verification++- **Mods harness:** each taint class is set by the right edits and commands and never on clean turns, and a taint never changes the outcome word.+- **CLI tests:**+ - tainted records are counted and never sent to SONA;+ - `allowTaint` lets exactly the listed class through;+ - the anomaly gate holds each of its three cases;+ - re-verification downgrades on failure, timeout and error, and is never called when it is off.diff --git a/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md b/v3/docs/adr/ADR-504-mods-real-binary-test-tier.mdnew file mode 100644index 0000000000..0f6b8a0c80--- /dev/null+++ b/v3/docs/adr/ADR-504-mods-real-binary-test-tier.md@@ -0,0 +1,76 @@+# ADR 504: a real-binary test tier for ruflo mods and hooks++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 5. Builds on: ADR-404 and the mods harness (`v3/@claude-flow/cli/__tests__/mods/harness.ts`).++## 1. Context++ruflo tests its mods in a single tier: a TypeScript harness that imitates the engine's contract. It catches most regressions but missed #4485. ruflo-mods 0.7.0 shipped with two `session.start` registrations that had no matcher. The real loader refuses that, so none of the mod's hooks ran.++The harness has learned that rule since, but it can only check rules someone already knows. The ADR-502 canary turned up two more facts the harness had only assumed, and both came from running the real binary:+- a non-zero Bash exit sets `isError`;+- `$.fs.write` into `.claude-flow/data/` succeeds.++vigiles (zernie/vigiles) tests hooks in three tiers:+- **unit:** pure hook logic;+- **deterministic:** the real `claude` binary talking to a scripted model;+- **eval:** a paid model.++Only the eval tier needs an API key.++## 2. Decision++Add the middle, deterministic tier.++### 2.1 Scripted model++A new file, `v3/@claude-flow/cli/__tests__/real-binary/mock-model.mjs`, runs a local HTTP server that speaks the Anthropic Messages API, both streaming and non-streaming.++- It replays a scripted conversation from a fixture: assistant turns, `tool_use` blocks with fixed inputs, and the final text.+- Claude Code reaches it through `ANTHROPIC_BASE_URL=http://127.0.0.1:<port>` with a dummy `ANTHROPIC_API_KEY`.+- It logs every request it receives, so a test can check what context reached the model, such as the `[RUFLO_LESSONS]` block or the route block.+- Requests it does not recognise get a minimal valid answer, so an engine-internal call (title or summary generation) cannot hang the run.++### 2.2 Runner++`__tests__/real-binary/run.ts` launches:++```+claude -p "<prompt>" --plugin-dir plugins/ruflo-mods --settings <fixture> --output-format stream-json+```++The run happens in a temporary project, with:+- `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`;+- an isolated `HOME` and `CLAUDE_CONFIG_DIR`;+- the mock model.++The runner returns the exit code, the stream-json events, the mock's request log, and the temporary project's files.++### 2.3 First contracts++1. **Loads.** With every boolean option on, ruflo-mods loads with no module error. This checks the #4485 class against the real loader.+2. **Learning loop.** A scripted turn edits a file and runs `npm test` (`node --test`), first failing and then passing. `verified-trajectories.jsonl` gets one `verified-success` record.+3. **Lessons reach the model.** With a lessons file present, the mock's next request contains the `[RUFLO_LESSONS]` block.+4. **Guard tightens.** A scripted Bash call that deletes the filesystem root is denied before it runs.+5. **Route context.** The route block reaches the request.++### 2.4 Where it runs++A new CI job, `mods-real-binary`, in `.github/workflows/mod-guidance.yml`:++- It installs a pinned Claude Code version (`npm i -g @anthropic-ai/claude-code@<pin>`) and runs the tier. It needs no secret.+- The pin is moved only by PR. An engine change that breaks a contract is then caught on the version bump, not in users' sessions.+- If the binary cannot be installed or started, the job fails and names the step. It never skips silently.++The tier also runs locally with `npm run test:real-binary` from `v3/@claude-flow/cli`.++## 3. Limits++- **The mock is not a model.** It cannot show whether a lesson changes behaviour; that belongs to the paid eval tier (ADR-503 §3).+- **Request shapes may change between Claude Code versions.** The mock accepts unknown fields and asserts only on message content.+- **Some features may refuse a non-Anthropic base URL.** If one does, its contract moves to the eval tier and is never faked.++## 4. Verification++The tier must be able to catch #4485. Adding a second `session.start` registration without a matcher to a scratch copy of ruflo-mods must make contract 1 fail.diff --git a/v3/docs/adr/ADR-505-compaction-snapshot-and-reload.md b/v3/docs/adr/ADR-505-compaction-snapshot-and-reload.mdnew file mode 100644index 0000000000..a1b6cd45f0--- /dev/null+++ b/v3/docs/adr/ADR-505-compaction-snapshot-and-reload.md@@ -0,0 +1,79 @@+# ADR 505: pre-compaction snapshot and post-compaction reload++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 3. Builds on: ADR-451 item 7 (`compactCarry`), ADR-502 (lessons), ADR-404.++## 1. Context++When Claude Code compacts a conversation, only the summary survives.++What ruflo does today:+- `compactCarry` adds at most 600 characters of ids and status words to the summarizer's instructions.+- Nothing keeps the transcript itself.+- Nothing puts ruflo's memory back after compaction.++How claude-mem and Nowledge Mem handle it, with classic hooks:+- They save the session before compaction, in PreCompact.+- After compaction, a SessionStart `compact` hook re-injects a bounded summary.+- They fall back through several sources when one is empty.++The mod engine offers more than classic hooks for this:+- `session.compact` carries `e.messages`, the transcript about to be compacted, and `e.agentId`.+- The next main-loop `prompt.submit` can carry context that the model reads and the person does not see.++## 2. Decision++Add a new ruflo-mods option, `compactSnapshot`, **on by default**. It only writes a local file and adds a bounded block after a compaction that has already lost information.++### 2.1 Before: snapshot++This runs on `session.compact` for the main loop (`agentId` absent), before `next(e)`.++**What is written:** a new `.claude-flow/sessions/compactions/<iso-time>.jsonl` with one line per message:+- the role;+- the text content, cut to 2,000 characters;+- the names and ids of any tool calls.++Tool inputs and outputs are never written. Each line passes through the shared secret and injection screen, and a line with a finding is stored as `[redacted]`.++**Limits:**+- 400 messages per snapshot;+- 2 MiB per snapshot;+- the newest 10 snapshots are kept and older ones are deleted.++**Failure handling:** the compaction is never blocked, delayed or rewritten. A failed write is logged to debug and dropped.++### 2.2 After: reload once++The mod sets `state.compacted = true`. On the next main-loop `prompt.submit`, it adds one `[RUFLO_AFTER_COMPACT]` context block of at most 2,000 characters, built from these sources in order:++1. up to 3 lessons from this session that matched a prompt (ADR-502);+2. the last 5 loop outcomes recorded this session: the task cut to 80 characters, the outcome word, and the verifier command;+3. open swarm and claim ids, as `compactCarry` gathers them;+4. the project-relative path of the snapshot just written, so the model can `Read` it if it needs a detail back.++The flag is then cleared:+- A source that fails or is empty is skipped.+- If every source is empty, no block is added.+- The whole block is screened, and a block that fails the screen is dropped.++### 2.3 Relation to `compactCarry`++`compactCarry` shapes the summary itself. `compactSnapshot` keeps the transcript and restores ruflo's state afterwards. They are independent and can both be on.++## 3. Security and privacy++- **Snapshots are local.** They hold conversation text in `.claude-flow/`, which `ruflo init` adds to `.gitignore`. When snapshots exist, `ruflo doctor` warns if `.claude-flow/` is not ignored by git.+- **The reload block contains only ruflo's own validated data.** It is built from in-memory state and validated files, never from snapshot content.+- **Turning it off:** `compactSnapshot: false`.++## 4. Verification++Harness tests:+- A snapshot is written only on a main-loop compaction, and it is bounded, rotated and screened.+- The compaction proceeds even when the write fails.+- The reload block is added exactly once and stays within bounds.+- No block is added when no source has anything to give.++Real-binary tier (ADR-504): `/compact` in a scripted session produces a snapshot.diff --git a/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md b/v3/docs/adr/ADR-506-plugin-userconfig-secrets.mdnew file mode 100644index 0000000000..252f7cd76f--- /dev/null+++ b/v3/docs/adr/ADR-506-plugin-userconfig-secrets.md@@ -0,0 +1,71 @@+# ADR 506: plugin secrets through `userConfig` with `sensitive: true`++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 1.++## 1. Context++Today ruflo plugins read their credentials from the process environment, and therefore from shell profiles or `.env` files. The main ones:++| Variable | Used by |+|---|---|+| `OPENROUTER_API_KEY` | ruflo-cost-tracker, metaharness redblue, bench solvers |+| `PINATA_API_KEY` / `PINATA_API_SECRET` / `PINATA_API_JWT` | plugin registry publishing |+| `RUFLO_ADMIN_TOKEN` | ruflo-x-gateway |+| `CGF_CALLER_TOKEN` | x-gateway federation |+| `SERAPHINA_METALLM_KEY` | meta-llm gateway calls |+| `OLLAMA_API_KEY` | local model endpoints |++No ruflo plugin declares a `userConfig` option with `sensitive: true` (none of 40+ plugin manifests).++The Claude Code plugin reference describes what `userConfig` with `sensitive: true` does:+- The value is masked as it is entered.+- It is stored in the platform's secure credential store; non-sensitive values go under `pluginConfigs` in settings.+- Hooks receive it as the environment variable `CLAUDE_PLUGIN_OPTION_<KEY>`.+- MCP and exec-form hook `args` can use `${user_config.KEY}`.+- Shell-form hook commands, monitor commands and MCP `headersHelper` refuse `${user_config.*}` substitution.+- Monitor processes do not receive the `CLAUDE_PLUGIN_OPTION_*` variables.++## 2. Decision++### 2.1 Declare the keys++Each plugin that needs a credential declares it as a `userConfig` option with `"sensitive": true` and `"required": false`:++- ruflo-cost-tracker: `openrouterApiKey`;+- ruflo-x-gateway: `adminToken`;+- ruflo-metaharness: `openrouterApiKey`.++The description says what the key is for and that it is stored in the credential store.++### 2.2 Read it through one helper++A shared helper, `readSecret(name, envFallbacks)`, is copied into each plugin's scripts folder; plugins may not import across folders. It reads, in order:++1. `CLAUDE_PLUGIN_OPTION_<NAME>`, which is set when the plugin runs under Claude Code with the option filled in;+2. the existing environment variables, kept for backward compatibility and for standalone CLI use.++It never logs or echoes the value. Its error text names the option and the variable, never the value.++### 2.3 Never put a secret in a command line++Plugin hooks and MCP entries that need a secret take it from the environment variable. They never use `${user_config.KEY}` substitution into argv: the value would be visible in `ps`, and the shell forms refuse it anyway.++### 2.4 Guard against regressions++A new audit, `scripts/audit-plugin-secrets.mjs`, runs in the existing `plugin-package-audit` CI job:++- It fails when a plugin declares a `userConfig` key whose name matches `/(key|token|secret|password|jwt)/i` without `sensitive: true`.+- It fails when a `.claude-plugin/plugin.json` or `hooks.json` carries a literal value that matches a secret shape. It uses the same patterns as the mods' secret screen.++## 3. What does not change++- The npm publish token and the helpers signing key stay in GCP Secret Manager. They belong to maintainer tooling, not to plugins.+- Environment variables keep working, so no user is broken.++## 4. Verification++- The audit is unit-tested with three fixtures: a key declared without `sensitive`, a literal secret, and a clean manifest.+- The helper is unit-tested: option over environment, fallback order, and no value in error text.+- Live: with `openrouterApiKey` set through `/plugin` configuration, a cost-tracker script receives it as `CLAUDE_PLUGIN_OPTION_OPENROUTERAPIKEY` and nothing else in the process sees it.diff --git a/v3/docs/adr/ADR-507-plugin-footprint-skills-commands.md b/v3/docs/adr/ADR-507-plugin-footprint-skills-commands.mdnew file mode 100644index 0000000000..5efd41f668--- /dev/null+++ b/v3/docs/adr/ADR-507-plugin-footprint-skills-commands.md@@ -0,0 +1,60 @@+# ADR 507: cutting the plugin suite's per-turn footprint++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 4. Builds on: ADR-451 (`agentTrim`).++## 1. Context++Claude Code keeps the name and description of every skill, agent and command the model can invoke in context on every turn, whether it is used or not. MCP servers start, and hooks fire, in every session where their plugin is enabled.++ruflo's marketplace currently ships 167 skills across its plugins. The largest are ruflo-cost-tracker (24), ruflo-metaharness (13), ruflo-ai-team (12) and ruflo-browser (10). No skill sets `disable-model-invocation`.++`agentTrim` already hides unused agent types and measured about 4,000 tokens saved per request. Skills and commands have no equivalent.++## 2. Decision++### 2.1 Measure first++A new script, `scripts/measure-plugin-footprint.mjs`, reports per plugin:+- skills, commands and agents;+- the characters each contributes to the per-turn listing (name plus description);+- an estimated token count (characters ÷ 4).++It writes `v3/docs/validation/plugin-footprint-<date>.md` and is the before/after evidence for this ADR.++### 2.2 User-invoked by default for operational skills++A skill whose job is something a person asks for explicitly, rather than something the model should pick on its own, gets `disable-model-invocation: true` in its frontmatter. It stays available as `/<skill>` but leaves the model's listing.++The first pass covers:+- release and publish skills;+- dashboards and reports;+- benchmark runners;+- one-shot setup and install skills;+- cost-tracker sub-reports, all of which are reached through `/cost`.++The rule for choosing is written into `plugins/README.md`. A skill the model needs to discover by itself, such as memory search or swarm init guidance, stays model-invoked.++### 2.3 Shorter descriptions++A skill or command description longer than 300 characters is cut to one sentence of what it does and when to use it, keeping the "Use when" phrasing ADR-112 requires. The audit enforces a 300-character ceiling on new skills, and the baseline cannot grow.++### 2.4 Optional mod trim for skills++ruflo-mods gains `skillTrim`, **default off**. It works like `agentTrim`, using the engine's skill-listing hook where one exists:+- It hides model-invoked skills that have not been used in the last 30 days and are not named in the prompt.+- `skillTrimKeep` lists skills that must always stay visible.++If the engine exposes no such hook, `skillTrim` is not built and this section is closed in the PR.++## 3. Consequences++- A person who relied on the model discovering an operational skill must now type `/<skill>`. The plugin README tables say which skills are user-invoked.+- No skill is removed or renamed (ADR-406).++## 4. Verification++- Footprint report before and after, committed.+- Each changed SKILL.md still passes the plugin smoke contracts and the ADR-112 audit.+- A smoke check confirms that every `disable-model-invocation: true` skill is still listed in its plugin README.diff --git a/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md b/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.mdnew file mode 100644index 0000000000..0a601be90c--- /dev/null+++ b/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md@@ -0,0 +1,60 @@+# ADR 508: the cost ladder feeds gateway budgets++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 2. Builds on: ADR-404 (the mod's cost ladder), the ruflo-cost-tracker plugin, the meta-llm gateway.++## 1. Context++ruflo-mods' cost ladder (`costBudgetUsd`, `costHardStop`) watches the session's live cost through `session.measure`. It announces the 50, 75, 90 and 100% rungs once each. At 100%, it can refuse new subagent spawns. It cannot stop the model call that pushes spend past the line, and it knows nothing about other sessions or other machines.++Gateways can enforce budgets for real. LiteLLM, for example, can be put in front of Claude Code through `ANTHROPIC_BASE_URL` and then:+- enforce `max_budget` over a rolling `budget_duration` (24h, 7d or 30d);+- stack several windows through `budget_limits`;+- fall back to a cheaper model when a per-model budget runs out (`model_max_budget` plus `budget_fallbacks`, on virtual keys, from v1.92).++The meta-llm gateway that ruflo users run behind `cognitum-*` models has its own allowance tiers. A gateway sees every request. It cannot see which tool or subagent caused the spend.++## 2. Decision++Keep attribution in the mod. Put enforcement in the gateway, and connect the two with a file.++### 2.1 One budget file, read by both++`.claude-flow/cost/budget.json` (version 1) holds the budget:++```json+{ "version": 1, "windows": [ { "usd": 10, "period": "24h" }, { "usd": 100, "period": "30d" } ], "hardStop": true, "fallbackModel": "haiku" }+```++- The mod reads it when `costBudgetUsd` is 0. It uses the smallest window's `usd` for the per-session ladder, and announces which window is closest to its limit.+- `ruflo cost budget set --daily 10 --monthly 100` writes the file.++### 2.2 Export to a gateway++`ruflo cost budget export --gateway litellm` prints the LiteLLM key settings for the current budget (`budget_limits`, `model_max_budget`, `budget_fallbacks`) as YAML or as a `/key/generate` JSON body. `--apply --url <proxy> --key-env LITELLM_MASTER_KEY` posts it.++- The master key is read from the environment variable named by `--key-env` (or from a `userConfig` sensitive option, ADR-506). It is never taken from argv.+- `--gateway meta-llm` is accepted only once meta-llm documents a budget API. Until then it fails with a pointer to this ADR. ruflo never guesses an endpoint.++### 2.3 Attribution stays in the mod++The mod keeps a per-session breakdown of `session.measure` cost deltas, by subagent type (from `agent.spawn`) and by the tool that ran just before each delta. At session end it writes the breakdown to the cost-tracker's ledger, so `ruflo cost report` can say which agents and tools spent the money. This is the part the gateway cannot see.++### 2.4 When the gateway refuses++When a model call fails with a budget error, ruflo-mods toasts once: `budget: the gateway refused the request (<window> spent)`. It records the event. It does not retry or change models itself; that is the gateway's fallback configuration.++## 3. Security++- No gateway credential is stored in the budget file.+- `--apply` sends only the budget fields, to the URL given, over HTTPS unless the host is loopback.++## 4. Verification++- Unit tests:+ - budget file validation, including hostile files: negative values, unknown periods, oversized arrays;+ - the ladder reads the file;+ - the LiteLLM export output matches LiteLLM's documented schema field by field;+ - `--apply` refuses plain HTTP to a non-loopback host.+- Attribution is tested in the mods harness with scripted `session.measure` and `agent.spawn` events.diff --git a/v3/docs/adr/ADR-509-plugin-trust-signing-and-scan.md b/v3/docs/adr/ADR-509-plugin-trust-signing-and-scan.mdnew file mode 100644index 0000000000..04f0674c8d--- /dev/null+++ b/v3/docs/adr/ADR-509-plugin-trust-signing-and-scan.md@@ -0,0 +1,73 @@+# ADR 509: trust for the ruflo plugin marketplace — signing, scan before install, refusing project auto-approve keys++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 7. Builds on: the `modTrust` gate (ADR-404), `settings-risk-scanner.ts`, the helpers signing key (`ruflo-helpers-signing-key`), and `metaharness mcp-scan`.++## 1. Context++ruflo's marketplace (`ruvnet/ruflo`) is third-party. Claude Code reserves the official and community tier names for marketplaces sourced from `github.com/anthropics/`. Every plugin or mod installed from ruflo's marketplace runs with the user's privileges.++Three gaps remain.++1. **Nothing proves a plugin's files are the ones the maintainers reviewed.** The marketplace clone follows the default branch. A compromised branch, a malicious PR that slipped through, or a tampered local clone all load the same way. The ruflo CLI's helpers are already signed with Ed25519 (`helpers.manifest.json`, `scripts/sign-helpers.mjs`); plugins are not.+2. **No scan runs before install.** `ruflo mods install` and `ruflo init` call `claude plugin install` without checking what the plugin's MCP servers and hooks will run. `metaharness mcp-scan` exists, but nothing calls it on that path.+3. **Project settings can pre-approve things.** CVE-2025-59536 showed that a repository's `.claude/settings.json` with `enableAllProjectMcpServers: true` started an MCP server before the user could read the trust dialog. `settings-risk-scanner.ts` already flags hook payloads and `permissions.allow` entries that `ruflo init` carries forward, but it is advisory only, and it does not cover the auto-approve keys.++## 2. Decision++### 2.1 Signed plugin manifests++At release, a new script, `scripts/sign-plugins.mjs`, writes `plugins/<name>/.claude-plugin/signature.json` for every plugin in `.claude-plugin/marketplace.json`:+- a SHA-256 of every file in the plugin, as a sorted list of path and digest;+- the plugin's version;+- an Ed25519 signature over that canonical JSON.++The signing uses the **existing** helpers signing key pair, so no new secret is created. The public key is already pinned in the CLI.++`ruflo mods doctor` and a new `ruflo plugins verify [name]` check the marketplace clone (and the install cache) against the signatures:++| Result | When |+|---|---|+| `verified` | Every file matches and the signature is valid. |+| `modified` | Lists the files that differ. |+| `unsigned` | No signature file. |+| `bad-signature` | The signature does not verify. |++With `modTrust: refuse-risky`, ruflo-mods refuses to trust a ruflo plugin whose clone is `modified` or `bad-signature`. Its `plugin.register` gate already sees the plugin id; it gains the verify result through a status file that `ruflo mods doctor` writes at install time. Without that setting the result is reported, not enforced, because a contributor running from a local checkout is always `modified`.++### 2.2 Scan before install++`ruflo mods install`, `ruflo init` (mods path) and `ruflo plugins install` run a static scan of each plugin's `.mcp.json`, `hooks/hooks.json` and hook modules before `claude plugin install`. It reuses `metaharness mcp-scan` rules when that package is present, and the mods trust classifier (`hooks/trust.ts` capability list) otherwise.++- A `high` finding stops the install and names the plugin, file and rule. `--accept-risk <plugin>` overrides it for that one plugin and records the override in `.claude-flow/mods/install.json`.+- `medium` findings are printed and the install continues.++### 2.3 Refuse project-level auto-approve keys++`settings-risk-scanner.ts` gains these keys when they appear in **project** settings (`.claude/settings.json`, `.claude/settings.local.json`):+- `enableAllProjectMcpServers: true`;+- non-empty `enabledMcpjsonServers`;+- `permissions.defaultMode: "bypassPermissions"`;+- `permissions.allow` entries with a bare `Bash` or a `*` wildcard;+- `hooks` entries whose command is not a ruflo helper.++When `ruflo init` or `init --upgrade` would carry such a key forward, it now **stops** and prints the key and the reason. Two flags continue past it:+- `--keep-risky-settings` keeps the key;+- `--drop-risky-settings` writes the merged file without it.++`ruflo doctor` reports these keys as a warning in any project.++## 3. Limits++- Signing proves the files match a release. It does not prove the release is safe; review still does that.+- A user who points the marketplace at a fork gets `unsigned` or `modified`, by design.+- The scan is static. A hook that downloads code at run time is caught only by the rules that flag network and process use, which the trust classifier already names.++## 4. Verification++- `sign-plugins` and `verify` round-trip, including tamper, missing-file, extra-file and bad-signature cases.+- The install path stops on a `high` finding and records `--accept-risk`.+- The risk scanner covers each new key.+- `init` stops and `--drop-risky-settings` removes the key.+- Live: `ruflo plugins verify ruflo-mods` reports `verified` on a published release clone.diff --git a/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.md b/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.mdnew file mode 100644index 0000000000..521ea76b91--- /dev/null+++ b/v3/docs/adr/ADR-510-headless-and-sdk-plugin-staging.md@@ -0,0 +1,67 @@+# ADR 510: loading ruflo plugins in headless and Agent SDK workers++Status: Proposed (2026-10-29)++Issue: #4581 follow-up 8. Builds on: ADR-404 (mods), the headless worker daemon, and the ADR-502 canary (mods ran under `claude -p --plugin-dir`).++## 1. Context++ruflo starts headless Claude Code workers in three places:+- the background worker daemon;+- `/federation dispatch`;+- metaharness and Darwin runners using `claude -p`.++None of these uses the Claude Agent SDK library. ruflo has no `@anthropic-ai/claude-agent-sdk` dependency. Third parties do embed ruflo's plugins in SDK sessions.++What is known:+- **`claude -p` on a fresh config loads no marketplace plugins.** The marketplace is cloned only by an interactive, trusted start (ruflo-mods README). A headless worker therefore runs without ruflo-mods' guard, routing and learning loop unless something loads them.+- **`claude -p --plugin-dir <path>` loads a plugin from a local folder**, function-hook mods included, when `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`. The ADR-502 canary confirmed this on 2.1.289.+- **The Agent SDK accepts plugins only as `{ type: "local", path }`** (Agent SDK plugins docs). A plugin path that does not exist is skipped without an error; the session's init message reports `plugins` and `plugin_errors`. Whether function-hook mods run under the SDK is not documented. The deep-research run could not establish it.++## 2. Decision++### 2.1 One resolver++A new module, `v3/@claude-flow/cli/src/mods/plugin-paths.ts`, provides `resolvePluginPaths(names)`. It returns an absolute folder per plugin, trying in order:++1. a `--source local` marketplace directory (the checkout);+2. the marketplace clone (`$CLAUDE_CONFIG_DIR|~/.claude/plugins/marketplaces/ruflo/plugins/<name>`);+3. the install cache (`.../plugins/cache/ruflo/<name>/<version>`).++A plugin whose folder lacks `.claude-plugin/plugin.json` is reported as missing. It is never returned.++### 2.2 Headless workers pass `--plugin-dir`++Every place where ruflo builds a `claude -p` command line adds `--plugin-dir <path>` for each resolved plugin in its worker profile. The default profile is ruflo-mods only. It also sets `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1` unless the caller set it.++If a plugin cannot be resolved, the worker:+- starts anyway;+- logs `plugin <name> not found; worker runs without it` once per process;+- records the missing plugin in the worker's status.++It does not fail silently, and it does not refuse to run.++### 2.3 SDK users get the same resolver++`ruflo plugins paths [--json]` prints the resolved paths and any missing plugins. An SDK caller can then build `plugins: [{ type: "local", path }]`. The README section "Using ruflo plugins from the Agent SDK" shows this, and it shows checking the init message's `plugin_errors`.++### 2.4 Verify, do not assume++`ruflo doctor --component headless-plugins` runs `claude -p --plugin-dir <ruflo-mods> --output-format stream-json "reply ok"` with a 60-second timeout. Without a model key it uses ADR-504's mock model. It reports:+- whether the init event lists ruflo-mods;+- whether `plugin_errors` is empty;+- whether the mod's session heartbeat (`.claude-flow/mods/session.json`) was written.++This answers "do mods run headless here" per machine instead of from documentation. Running the same check through the Agent SDK stays a documented manual step until ruflo takes an SDK dependency.++## 3. Limits++- Function hooks under the SDK are unverified. The README says so.+- `--plugin-dir` loads the plugin from disk as-is. Combined with ADR-509, a worker can check the plugin's signature first; the default worker profile does so when `modTrust` is `refuse-risky`.++## 4. Verification++- `resolvePluginPaths`: tested for each source in order, a missing manifest, and a `CLAUDE_CONFIG_DIR` override.+- The worker command builder adds `--plugin-dir` and the environment variable, and does not duplicate a caller's own flag.+- The doctor check is covered by a test using the ADR-504 mock model.+- Live: a daemon worker run shows the ruflo-mods heartbeat.