🌊 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
feat: managed workflows, unified console runs and verified advisory learning (#4471)
rUvdb141ba70ed5
diff --git a/.github/workflows/managed-dynamic-workflows.yml b/.github/workflows/managed-dynamic-workflows.ymlnew file mode 100644index 0000000000..67435f1f51--- /dev/null+++ b/.github/workflows/managed-dynamic-workflows.yml@@ -0,0 +1,49 @@+name: Managed dynamic workflows contract+on:+ pull_request:+ paths:+ - 'v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts'+ - 'v3/@claude-flow/cli/src/services/managed*.ts'+ - 'plugins/ruflo-console/**'+ - 'v3/@claude-flow/cli/__tests__/managed*.test.ts'+ - 'plugins/ruflo-agent/**'+ - 'plugins/ruflo-workflows/**'+ - 'scripts/managed-outcome-verifier.mts'+ - 'scripts/e2e-managed-*.mts'+ - '.github/workflows/managed-dynamic-workflows.yml'+ workflow_dispatch:+permissions:+ contents: read+jobs:+ contract:+ runs-on: ubuntu-latest+ strategy:+ matrix:+ node: ['20', '22']+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}+ - name: Install isolated test tooling without lifecycle scripts+ run: |+ npm install --prefix "$RUNNER_TEMP/managed-tools" --ignore-scripts --no-audit --no-fund [email protected] [email protected] @types/node@22 @claude-flow/[email protected]+ ln -s "$RUNNER_TEMP/managed-tools/node_modules" node_modules+ - name: Type check the adapter boundary+ run: node node_modules/typescript/lib/tsc.js --target es2022 --module nodenext --moduleResolution nodenext --strict --skipLibCheck --types node --noEmit v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts+ - name: Offline provider and adjacent workflow regressions+ working-directory: v3/@claude-flow/cli+ run: node ../../../node_modules/vitest/vitest.mjs run --maxWorkers=2 --config vitest.config.ts __tests__/managed-agent-tools.test.ts __tests__/managed-workflows.test.ts __tests__/managed-mod-integration.test.ts __tests__/managed-learning.test.ts __tests__/managed-learning-loop.test.ts __tests__/managed-memory-isolation.test.ts __tests__/managed-run-collector.test.ts __tests__/managed-run-store.test.ts __tests__/workflow-validation-runtime.test.ts __tests__/workflow-resume-dispatch-r50.test.ts __tests__/workflow-progress-ownership-r50.test.ts+ - name: Executable independent verifier and feedback cycle+ run: |+ node node_modules/typescript/lib/tsc.js --target es2022 --module nodenext --moduleResolution nodenext --strict --skipLibCheck --types node --outDir "$RUNNER_TEMP/managed-e2e" scripts/e2e-managed-loop.mts scripts/managed-outcome-verifier.mts v3/@claude-flow/cli/src/services/managed-memory-worker.ts+ node "$RUNNER_TEMP/managed-e2e/scripts/e2e-managed-loop.mjs"+ - name: Plugin and registration contracts+ run: |+ bash plugins/ruflo-agent/scripts/smoke.sh+ bash plugins/ruflo-workflows/scripts/smoke.sh+ node scripts/audit-cli-mcp-tools.mjs++ - name: Focused console managed integration and rendering+ run: node node_modules/vitest/vitest.mjs run --maxWorkers=2 plugins/ruflo-console/tests/managed.spec.ts plugins/ruflo-console/tests/managed-palette.spec.ts plugins/ruflo-console/tests/model-tools.spec.ts plugins/ruflo-console/tests/palette-view.spec.ts plugins/ruflo-console/tests/workflows.spec.ts plugins/ruflo-console/tests/mods-section.spec.ts plugins/ruflo-console/tests/render-smoke.spec.ts plugins/ruflo-console/tests/tui-actions.spec.tsdiff --git a/README.md b/README.mdindex d7a5c4a679..baf2b2b17e 100644--- a/README.md+++ b/README.md@@ -275,7 +275,7 @@ This adds slash commands and agent definitions. `ruflo-core` (installed above) d| Plugin | What it does ||--------|-------------|-| [**ruflo-agent**](plugins/ruflo-agent/README.md) | Run agents — local WASM sandbox (rvagent) + Anthropic Claude Managed Agents (cloud) |+| [**ruflo-agent**](plugins/ruflo-agent/README.md) | Run agents — local WASM sandbox (rvagent) + Anthropic Claude Managed Agents (cloud), with opt-in bounded dynamic workflows, gated session controls and verified advisory learning || [**ruflo-plugin-creator**](plugins/ruflo-plugin-creator/README.md) | Scaffold, validate, and publish your own plugins |#### Domain-Specificdiff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.mdindex df1e6cabfd..07a091b74a 100644--- a/docs/USERGUIDE.md+++ b/docs/USERGUIDE.md@@ -647,6 +647,24 @@ y sends it · n cancels · it expires in 59 s**In Claude Code**, the same console has an optional Orbital look and a Theme Studio: run `/ruflo themes`. See the [console README](../plugins/ruflo-console/README.md#orbital-theme).+### Managed cloud agents (optional, opt-in)++Besides local WASM agents (`wasm_agent_*`), `ruflo-agent` can run an agent in Anthropic's cloud through the Claude Managed Agents beta (`managed_agent_*`). It needs `ANTHROPIC_API_KEY` (or `CLAUDE_API_KEY`) and Managed Agents beta access; without a key every tool says so and nothing is called. Local WASM agents need neither.++**Dynamic workflows.** A cloud agent can start a workflow of parallel workers. You opt in per agent with `dynamicWorkflows: true` and a mandatory `budgetCents` (an integer US-cents string; requests already in flight can overshoot). Networking is limited, and `predefinedAgents` restricts which workers may run. Provider completion is **not** correctness: results come back as `verification: "unverified"`, so inspect worker threads and run your own tests before keeping anything.++**In the console.** Managed sessions appear on the Workflows page with their reported budget, blockers and worker counts (Learning shows advisory evidence). Showing them makes no provider calls. A session that is running or rescheduling reads as running; one stopped at its budget or waiting for an action reads as active, not finished. Inspect, interrupt and terminate are palette entries bound to one session and use the same confirm card as every other change.++**Host settings (all off by default).**++| Setting | What it turns on |+|---|---|+| `RUFLO_MANAGED_CONTROL=1` + `RUFLO_MANAGED_CONTROL_SESSIONS=sesn_a,sesn_b` | `managed_agent_control` and `managed_agent_interrupt` act only on the listed sessions, after a fresh read of the provider's state. Once set, `managed_agent_terminate` obeys the same list and deletes only that session's own environment. |+| `RUFLO_MANAGED_LEARNING=1` + `RUFLO_MANAGED_VERIFIER_PUBLIC_KEY` | Verified advisory learning: signed outcomes are checked against your public key, unsigned ones stay quarantined, and a bounded feedback cycle can recommend a strategy. Nothing changes routing by itself. |+| `RUFLO_MANAGED_AGENTS_BASE_URL` | Operator-only override of the API origin (an HTTPS origin, no credentials, path or redirects). It is never a tool argument, so a prompt cannot point your API key somewhere else. |++**Limits worth knowing.** The verifier signs observations with a key that sits in the same user account as the checks it runs, so only run checks that **you** wrote, never ones an agent produced. After a crash a lock file can be left behind; remove it by hand once no ruflo process is running. Live execution against the provider has not been exercised in this release. The full list is in [ADR 0004](../plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.md#amendment-independent-review-and-known-limits-2026-10-25); the plugin's tools are in the [ruflo-agent README](../plugins/ruflo-agent/README.md).+<details><summary>🤖 <strong>OpenAI Codex CLI Support</strong> — Full Codex integration with self-learning</summary>diff --git a/docs/benchmarks/managed-cycle-admission.json b/docs/benchmarks/managed-cycle-admission.jsonnew file mode 100644index 0000000000..d3a4c5d4ed--- /dev/null+++ b/docs/benchmarks/managed-cycle-admission.json@@ -0,0 +1,18 @@+{+ "kind": "local durable-admission CPU benchmark",+ "node": "v24.22.1",+ "rounds": 7,+ "signedRows": 18,+ "baseline": "18 recordLearning transactions",+ "candidate": "one recordLearningBatch transaction",+ "equivalentEvidence": true,+ "sequentialMedianMs": 185.276346,+ "atomicMedianMs": 25.40276300000005,+ "speedup": 7.293550941682983,+ "admissionTransactions": {+ "baseline": 18,+ "candidate": 1+ },+ "sourceSha256": "53ec943484530e9c8c44ead4f8b7f8088b54548d9f262ef4fa041413b8d860a6",+ "limitations": "Synthetic metadata, same-machine temporary filesystem and seven runs. No provider task quality, native backend speed, billing savings or deployment promotion is inferred."+}diff --git a/docs/benchmarks/managed-dynamic-workflows.json b/docs/benchmarks/managed-dynamic-workflows.jsonnew file mode 100644index 0000000000..91e02addff--- /dev/null+++ b/docs/benchmarks/managed-dynamic-workflows.json@@ -0,0 +1,17 @@+{+ "kind": "synthetic event processing only",+ "node": "v24.22.1",+ "baselineCommit": "973d0ab497c9138d7bee1dc3c7a4d3985e37bf9e",+ "baselineSha256": "261e5a46ea94bf9dc79b9907f68f7768df15ae156fc0033cd18a2c8155fa287f",+ "candidateSha256": "513ecb0b0d6fcb7d1504c3c81e78356372066564986234aa18bc157e102e5959",+ "events": 5001,+ "polls": 51,+ "repeats": 9,+ "baselineMedianMs": 10.286731000000032,+ "candidateMedianMs": 6.096832000000006,+ "latencyRatio": 1.6872255951943602,+ "baselineEventVisits": 132501,+ "incrementalEventVisits": 5001,+ "eventVisitReduction": 0.9622568886272557,+ "limitations": "No provider latency, token savings, dollar savings or bug-finding improvement measured. Snapshot output assembly is included in both timings."+}diff --git a/docs/benchmarks/managed-learning-console.json b/docs/benchmarks/managed-learning-console.jsonnew file mode 100644index 0000000000..69db16e39e--- /dev/null+++ b/docs/benchmarks/managed-learning-console.json@@ -0,0 +1,23 @@+{+ "kind": "synthetic CPU and contract benchmark",+ "node": "v24.22.1",+ "sourceHashes": {+ "managed-run-collector.ts": "9ea9862916b43766f93cb4886999457858364101cc36abbfdbecab24badc1257",+ "managed-learning.ts": "beb451f5b58d2afb39749e2730c811c6b3b7dc04aa3e636201eb307834abfcae",+ "managed-run-store.ts": "e75c5f25d9f0537a9560d8f120fe7915aea287d3f01bf2b430a4394608504c02",+ "managed-learning-store.ts": "16d044cbd5818f36c9ad4d6539534ca0af8e597e0460933ee725795a43476ea3"+ },+ "workers": 1000,+ "replayedEvents": 6006,+ "uniqueEvents": 3003,+ "eventReads": 1,+ "sessionReads": 1,+ "inactiveReads": 0,+ "collectionMs": 51.251221000000015,+ "workerPageMedianMs": 0.052930000000003474,+ "signedTrainingRows": 60,+ "signatureVerificationMs": 15.94511,+ "recommendationMedianMs": 0.8973909999999705,+ "syntheticSelected": "candidate",+ "limitations": "Fixture costs and outcomes are synthetic. No live provider quality, dollar savings, native vector backend or GPU/UI performance is measured. Warm console rendering is separately covered by view tests."+}diff --git a/docs/validation/managed-dynamic-workflows.md b/docs/validation/managed-dynamic-workflows.mdnew file mode 100644index 0000000000..fdf36d1620--- /dev/null+++ b/docs/validation/managed-dynamic-workflows.md@@ -0,0 +1,131 @@+# Managed dynamic workflows validation++This records the initial adapter stage. See the [console and verified learning validation](managed-learning-console.md) for the latest expanded integration results.++Date: 2026-10-24. Baseline: `973d0ab497c9138d7bee1dc3c7a4d3985e37bf9e`.+Scope: existing Managed Agents REST adapter, incremental event reducer,+plugin guidance, and isolated CI contract. No dependency or lockfile changes.++## Results++| Check | Result |+| --- | --- |+| Provider fixtures and existing no-key tool contract | 87 tests passed |+| Adjacent persisted workflow validation/resume/ownership | 21 tests passed |+| Strict TypeScript check of adapter and imported service | Passed |+| ruflo-agent plugin smoke | 16 passed |+| ruflo-workflows plugin smoke | 18 passed |+| CLI/MCP registration audit | 413 registered, zero dangling references |+| Tool discoverability audit | 411 scanned, zero missing guidance/short/duplicate descriptions |+| Ruflo 3.25.6 deep code security scan, adapter and seven hook files | Zero scanner findings |+| Independent source review | Six confirmed defects corrected and covered by fixtures |+| Whitespace/diff integrity | Passed |++Scanner coverage is heuristic and scoped. It is not a dependency advisory audit+or proof of security. No dependency changes were introduced. Existing whole+repository dependency exposure is outside this patch's assessment. Advisory+feeds were not queried. The threat model and specific attack regressions are+in [ADR 0003](../../plugins/ruflo-agent/docs/adrs/0003-managed-dynamic-workflows.md).++The independent reviewer identified stale final-idle completion, interruption+completion, valid confirmation result unions, historical-run contamination,+missing run IDs and nested usage accounting. All six have regression fixtures.++## Reproduction++With repository development dependencies installed, from `v3/@claude-flow/cli`:++```sh+npx vitest run --config vitest.config.ts \+ __tests__/managed-agent-tools.test.ts \+ __tests__/managed-workflows.test.ts \+ __tests__/managed-mod-integration.test.ts \+ __tests__/workflow-validation-runtime.test.ts \+ __tests__/workflow-resume-dispatch-r50.test.ts \+ __tests__/workflow-progress-ownership-r50.test.ts+```++From the repository root:++```sh+npx tsc --target es2022 --module nodenext --moduleResolution nodenext \+ --strict --skipLibCheck --types node --noEmit \+ v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts+bash plugins/ruflo-agent/scripts/smoke.sh+bash plugins/ruflo-workflows/scripts/smoke.sh+node scripts/audit-cli-mcp-tools.mjs+node scripts/audit-tool-descriptions.mjs+git diff --check+```++Actual local tooling: Node 24.22.1, Vitest 3.2.6, TypeScript 5.9.3, and the+Ruflo security scanner pinned to 3.25.6. The GitHub workflow installs isolated+Vitest 3.2.6, TypeScript 5.9.3, Node 22 types and cli-core 3.7.5 with lifecycle+scripts disabled. No provider key is needed by CI.++The scanner was run read-only against copies of+`managed-agent-tools.ts`, `managed-workflows.ts`, and the seven changed hook+files in the agent and workflow mods, using:++```sh+npx -y @claude-flow/[email protected] security scan \+ --target /tmp/ruflo-managed-audit --depth deep --type code+```++## Measured optimization++Run on Node >=22.18, with the baseline commit available locally:++```sh+node scripts/bench-managed-workflows.mjs+```++The benchmark executes the exact original summarizer extracted from the frozen+baseline source, compares incremental reduction with repeated full-history+summarization, verifies equal assistant text and alternates timing order after+warmup. Both timings include output assembly. Nine measured repetitions, 5,001+events, 51 observations. The source hashes are in the+[JSON receipt](../benchmarks/managed-dynamic-workflows.json).++| Metric | Baseline | Candidate |+| --- | ---: | ---: |+| Median local processing | 10.287 ms | 6.097 ms |+| Events visited | 132,501 | 5,001 |++This sample is 1.69 times faster with 96.2% fewer event visits. It does not+measure provider latency, tokens, billing, model quality or bug-finding recall.+Inclusive watermarks can replay multiple events sharing a timestamp; those+events are deduplicated rather than counted twice.++## Limits and next adoption gate++The live Anthropic API was not invoked. All provider tests use deterministic+HTTP fixtures. The full monorepo suite was not run; the focused boundary and+adjacent workflows were tested. Hosted GitHub CI is a separate observation.++Before broad adoption, the maintainer should validate one live session with a+small cents budget, minimal network access and a non-sensitive fixture, inspect+every worker transcript, independently reproduce results, and explicitly delete+the session and owned resources. Then compare single agent, current Ruflo swarm+and managed workflows on the same frozen corpus at equal dollar budgets over+three runs. Suggested adoption gate: at least 10% more reproducible findings per+dollar, no higher false-positive rate, and verified interruption/deletion.++No claim of improved model quality or production readiness follows from the+synthetic optimization. Keep the PR in draft until live validation is recorded.++## Mod and plugin refinement++The follow-up adds 27 tests exercising real registered hook functions, policy+settings, local capability discovery, no-network runtime introspection, workflow+mod routing and compatibility with the existing console parser. Combined focused+and adjacent suite: 108 passing tests. The original hosted Managed dynamic workflows+contract passed before this refinement; new hosted checks must run on the updated+commit. Plugin versions are raised to agent 0.4.0 and workflows 0.7.0 so installed+copies receive the shipped behavior.++The native Claude plugin test runner was not invoked. Hook execution is covered+by a deterministic test harness using the existing hook call pattern; the real+host remains a separate compatibility check. Console parser integration is tested+without changing the console plugin. The mod is a local admission constraint, not+an organization-wide spend controller.diff --git a/docs/validation/managed-learning-console.md b/docs/validation/managed-learning-console.mdnew file mode 100644index 0000000000..4805c147de--- /dev/null+++ b/docs/validation/managed-learning-console.md@@ -0,0 +1,85 @@+# Managed learning and console validation++Date: 2026-10-25. Extends the initial managed adapter on PR #4471.+Follow-up: [actual ruOS integration checks and recall fix](managed-ruos-e2e.md).+Decision: [ADR 0004](../../plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.md).+No runtime dependencies or lockfiles changed.++## Results++| Check | Observed result |+| --- | --- |+| Backend adapter, collector, controls, learning and adjacent workflow regressions | 167 tests passed across nine files |+| Focused console managed/workflow/mod/render/action regressions | 101 tests passed across five files |+| Strict adapter TypeScript boundary | Passed, TypeScript 5.9.3 |+| Agent / workflows plugin smoke | 16 / 18 checks passed |+| CLI/MCP registration | 415 tools, zero dangling references |+| Tool discoverability | 413 scanned, zero missing guidance, short or duplicate descriptions |+| Ruflo 3.25.6 deep code scan of changed integration sources | Zero scanner findings |+| Independent source review | No remaining blockers in the reviewed paths |+| Warm console view rendering | Median below 16 ms in the bounded fixture test |++The console checks use the actual view functions with a fixture rendering kit.+They do not measure native terminal/GPU rendering. The full console smoke suite+is not a clean validation result: an earlier concurrent run encountered timing+and temporary-file races and was stopped. The focused action suite passed in+isolation and again within the five-file run. The full monorepo suite was not run.+The scanner is scoped heuristic evidence, not a proof of security or a dependency+advisory audit. No live provider or native memory backend was exercised.++## Acceptance coverage++Collector tests replay 1,000 workers with duplicates, reordered reconnects,+budget and permission pauses, failures and conflicting event IDs. They check+aggregate counts, bounded pages, one in-process collection and an exclusive+cross-process OS lease. Snapshot reads have no provider transport and no timers.+Provider completion never sets worker inspection or acceptance verification.++Controls reject unknown fields and caller approval flags, check current host+policy and exact session allowlists, fetch provider state, and recheck policy+before dispatch. Tests cover changed policy, unknown provider state, failed+deletion and credential rotation during observation. Per-session timestamps+prevent one refresh from freshening another session.++Learning tests cover Ed25519 receipts, strict metadata, unsigned quarantine+poisoning, mutable input isolation, verifier rotation, forged cached advice,+training/holdout leakage, complete paired trials, equal admitted budgets,+source identity, safety/quality/latency regression, replay/adversarial gates,+failed native insertion and forged semantic recall. Recommendations remain+advisory; defaults and capability grants never change. The native memory API+contract is mocked; actual embedding/index performance remains unmeasured.++Durable ledger writes preflight directory fsync before mutation, then use an+exclusive lock, bounded reads, atomic replacement and file/directory fsync.+Linux behavior was tested; Windows durability was not. Unsupported directory+durability must fail instead of claiming a durable write. Same-user adversarial+filesystem races remain outside the directory-check guarantee.++## Reproducible synthetic benchmark++Receipt: [managed-learning-console.json](../benchmarks/managed-learning-console.json).+It includes source hashes and Node version. Compile the three service entry+points, then run:++```sh+node node_modules/typescript/lib/tsc.js --target es2022 --module nodenext \+ --moduleResolution nodenext --strict --skipLibCheck --types node \+ --outDir /tmp/managed-integration-build \+ v3/@claude-flow/cli/src/services/managed-learning.ts \+ v3/@claude-flow/cli/src/services/managed-run-collector.ts \+ v3/@claude-flow/cli/src/services/managed-run-store.ts+node scripts/bench-managed-integration.mjs /tmp/managed-integration-build+```++The recorded run retained 3,003 unique events from 6,006 supplied events for+1,000 workers, with one event read, one session read and zero inactive reads.+Collection took 51.25 ms; cached worker page median was 0.053 ms. Verifying 60+signed training receipts took 15.95 ms; recommendation median was 0.897 ms.+These single-machine fixture measurements are not a before/after performance+claim. Fixture cost and success outcomes cannot establish real model quality,+dollar savings, statistical significance or production routing improvement.++The dedicated CI workflow repeats the nine backend files, five console files,+strict type check, plugin smoke and registration audit using isolated pinned+test tooling. A live bounded provider run, trusted verifier deployment and an+actual native memory index/recall round trip remain release validation gates.diff --git a/docs/validation/managed-loop-e2e.json b/docs/validation/managed-loop-e2e.jsonnew file mode 100644index 0000000000..8e8c9bade1--- /dev/null+++ b/docs/validation/managed-loop-e2e.json@@ -0,0 +1,33 @@+{+ "schema": "ruflo.managed-verifier-e2e/v1",+ "assertions": 86,+ "verifiedSubprocessReceipts": 18,+ "cyclePhases": [+ "admitted",+ "recorded",+ "recommended",+ "evaluated"+ ],+ "replayedDuplicates": 18,+ "deniedCycleWrites": 0,+ "training": 6,+ "pairedHoldout": 6,+ "advisoryEligible": true,+ "measuredBaselineP95Ms": 1249,+ "measuredCandidateP95Ms": 267,+ "defaultsChanged": false,+ "costOrigin": "synthetic-fixture",+ "limitations": "Real verifier subprocesses, signatures, file persistence, feedback cycle and heldout gates; synthetic workload and cost fixture only. No live provider quality, billing savings, universal safety or native vector backend is claimed.",+ "sourceHashes": {+ "v3/@claude-flow/cli/src/services/managed-learning.ts": "beb451f5b58d2afb39749e2730c811c6b3b7dc04aa3e636201eb307834abfcae",+ "v3/@claude-flow/cli/src/services/managed-learning-loop.ts": "0802c5b54cba703187a47bede6db51db24d16dff964677713f9c20a0e0eea501",+ "v3/@claude-flow/cli/src/services/managed-memory-client.ts": "7a47f099f128eedd4b9a55bf18462eae0a6756c2ee5267732dddea73e2d4fa7e",+ "v3/@claude-flow/cli/src/services/managed-learning-store.ts": "53ec943484530e9c8c44ead4f8b7f8088b54548d9f262ef4fa041413b8d860a6",+ "v3/@claude-flow/cli/src/services/managed-workflows.ts": "513ecb0b0d6fcb7d1504c3c81e78356372066564986234aa18bc157e102e5959",+ "v3/@claude-flow/cli/src/services/managed-run-collector.ts": "9ea9862916b43766f93cb4886999457858364101cc36abbfdbecab24badc1257",+ "v3/@claude-flow/cli/src/services/managed-run-store.ts": "e75c5f25d9f0537a9560d8f120fe7915aea287d3f01bf2b430a4394608504c02",+ "v3/@claude-flow/cli/src/services/managed-memory-worker.ts": "542c929ec1482562964169d3ae083612e1f52fbd4685834c246c07870748d54c",+ "scripts/managed-outcome-verifier.mts": "a49cdc043cbbd9733875d07c00200ec24dfc2352258ce6b6310d5581f0382a10",+ "scripts/e2e-managed-loop.mts": "6a500b113df5cf4b36f1f0d7f1689a5716e6fdd84b5cb790ff388e43cba4082f"+ }+}diff --git a/docs/validation/managed-loop-e2e.md b/docs/validation/managed-loop-e2e.mdnew file mode 100644index 0000000000..84063a8de8--- /dev/null+++ b/docs/validation/managed-loop-e2e.md@@ -0,0 +1,103 @@+# Managed feedback cycle validation++Date: 2026-10-25. Extends [ADR 0004](../../plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.md)+and the [previous native ruOS checks](managed-ruos-e2e.md).++## Local evidence++| Check | Result |+| --- | --- |+| Backend provider, learning, cycle, worker and adjacent regressions | 199 tests passed across 11 files |+| Console managed palette, permissions, rendering and actions | 150 passed across eight files |+| Executable verifier and feedback E2E | 86 assertions passed; 18 signed outcomes from real verifier subprocesses |+| Replay and revoked admission | 18 duplicate outcomes, no added rows; denied cycle made zero ledger writes |+| Paired holdout | Six complete pairs eligible on explicitly synthetic costs; no promotion |+| Actual child process lifecycle | Exit 134, SIGKILL, timeout, malformed responses, capacity, warm reuse and grant revocation covered |+| Strict TypeScript boundaries | Adapter, worker and executable scripts passed |+| Agent/workflows smoke | 16/18 checks passed |+| Registration/discoverability | 415 tools, zero dangling; 413 descriptions, all gates pass |+| Pinned Ruflo 3.25.6 scoped deep code scan | Zero heuristic findings |++The verifier runs separate acceptance, safety, replay and adversarial commands,+then measured metric checks, rehashes source/artifact/spec/cost inputs and signs+the closed observation. Tests include failed checks, timeouts, mutated source,+cost mismatch, unsafe paths/key modes, signatures and key rotation. Check programs+are host-reviewed trusted code, not sandboxed arbitrary agent instructions.++One atomic batch replaces repeated ledger transactions in a cycle. At most 24+outcomes are admitted; an indexing cycle accepts at most six training outcomes+and rejects a larger training batch before writes. Later native failure leaves+the signed batch durable and resumable. Native replay authenticates the exact+existing row instead of overwriting immutable evidence. Empty cycles can read+existing evidence and return advisory recommendations.++Fresh host callbacks guard import boundaries, native readiness and the append+grant. Revocation after a granted append may arrive too late to undo that write;+the result reports ambiguity rather than success. A single reusable child has+a 15 second operation timeout and five second idle expiry. Its environment+excludes provider credentials and startup hooks; model download is disabled.+Native/system OOM still needs host memory controls; a process boundary is not+an OS sandbox. Windows/macOS durability and POSIX verifier behavior remain+unqualified.++## ruOS runtime evidence++[Source-bound ruOS receipt](managed-loop-ruos.json) records Node 20.20.2 with+native memory 3.0.9: 199 backend tests and 150 console tests passed. The compiled+verifier loop passed all 86 assertions. Source and emitted JavaScript workers+each durably indexed three rows, replayed all three without replacement and+recalled all three from another process. The real MCP cycle indexed and recalled+three outcomes and replayed them without changing defaults.++The first Node 20 test run exposed a harness assumption about Node 24 TypeScript+support. The test now emits the fixed worker as JavaScript before forking and+rejects early process exit. CI covers Node 20 and 22. The verifier E2E stages an owner-only copy of the+fixture Node executable so tool-cache permissions cannot weaken or invalidate+the production executable policy. A group-writable copy is explicitly rejected.+The deliberately slower synthetic baseline waits one second to keep scheduling+noise from determining fixture eligibility; these timings do not measure model+performance.++Offline hardening configures the exact Transformers.js module identities loaded+by AgentDB before registry initialization; Python-style offline environment flags+alone do not enforce that setting. A fresh native source write/replay and compiled+restart recall passed with this configuration. This verifies the exercised Linux+runtime and emitted entry, not a full monorepo build or OS network sandbox.++## Measured optimization++[Benchmark receipt](../benchmarks/managed-cycle-admission.json) compares identical+18 signed rows with seven rounds, verifying identical persisted evidence:++| Admission | Median local time | Transactions |+| --- | --- | --- |+| Existing individual record calls | 185.28 ms | 18 |+| Atomic batch | 25.40 ms | 1 |++The measured speedup was 7.29 times. This is temporary-filesystem CPU/durability+overhead on one machine, not task intelligence, native indexing performance,+provider savings or statistical evidence of a better model strategy.++## Reproduction++With the pinned test tooling installed as in the dedicated CI workflow:++```sh+node node_modules/typescript/lib/tsc.js --target es2022 --module nodenext \+ --moduleResolution nodenext --strict --skipLibCheck --types node \+ --outDir /tmp/managed-e2e scripts/e2e-managed-loop.mts \+ scripts/managed-outcome-verifier.mts scripts/bench-managed-cycle.mts \+ v3/@claude-flow/cli/src/services/managed-memory-worker.ts+node /tmp/managed-e2e/scripts/e2e-managed-loop.mjs+node /tmp/managed-e2e/scripts/bench-managed-cycle.mjs+```++The live provider runner is separate: it exits 3 with a blocked JSON result and+zero provider calls without explicit opt-in, an executor key and one or two+predefined worker IDs. It never infers entitlement from a Claude subscription.+Unknown creation outcomes require inspection; dependent cleanup stops if session+deletion is unconfirmed. Confirmed completion remains unverified correctness.++Keep PR #4471 draft pending actual provider canary, production verifier operation,+platform qualification and the relevant CI results. The JSON receipts bind the exercised source and+ruOS native child measurements; provider quality and spend remain unmeasured.diff --git a/docs/validation/managed-loop-ruos.json b/docs/validation/managed-loop-ruos.jsonnew file mode 100644index 0000000000..b2510e9b8f--- /dev/null+++ b/docs/validation/managed-loop-ruos.json@@ -0,0 +1,128 @@+{+ "sourceCommit": "0677967f4b30cdaa2946efeb43d0e729a8244bd8",+ "node": "20.20.2",+ "memory": "3.0.9",+ "backendTests": {+ "passed": 199,+ "files": 11,+ "seconds": 6.77,+ "testHarnessCorrection": "Emit worker JavaScript instead of relying on Node24 source TypeScript support"+ },+ "sourceNativeWrite": {+ "mode": "write",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "indexMs": [+ 3716.9965199999997,+ 312.9204900000004,+ 168.51188000000002+ ],+ "nativeReplayRows": 3,+ "workers": 1,+ "advisoryStrategy": "fixture",+ "passed": true,+ "indexedRows": 3,+ "allDurableWithEmbedding": true+ },+ "sourceNativeRestartRecall": {+ "mode": "recall",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "recalled": 3,+ "backend": "ruflo-memory-child",+ "similarityIsVerification": false,+ "advisoryStrategy": "fixture",+ "passed": true+ },+ "compiledNativeWrite": {+ "mode": "write",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "indexMs": [+ 1630.54065,+ 394.0604199999998,+ 249.2598399999997+ ],+ "nativeReplayRows": 3,+ "workers": 1,+ "advisoryStrategy": "fixture",+ "passed": true,+ "indexedRows": 3,+ "allDurableWithEmbedding": true+ },+ "compiledNativeRestartRecall": {+ "mode": "recall",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "recalled": 3,+ "backend": "ruflo-memory-child",+ "similarityIsVerification": false,+ "advisoryStrategy": "fixture",+ "passed": true+ },+ "nativeMcpCycle": {+ "passed": true,+ "phase": "actual MCP native feedback cycle",+ "phases": [+ "admitted",+ "recorded",+ "indexed",+ "recalled",+ "recommended"+ ],+ "duplicates": 3,+ "indexed": 3,+ "recalled": 3,+ "defaultsChanged": false+ },+ "verifierLoop": {+ "schema": "ruflo.managed-verifier-e2e/v1",+ "assertions": 86,+ "verifiedSubprocessReceipts": 18,+ "cyclePhases": [+ "admitted",+ "recorded",+ "recommended",+ "evaluated"+ ],+ "replayedDuplicates": 18,+ "deniedCycleWrites": 0,+ "training": 6,+ "pairedHoldout": 6,+ "advisoryEligible": true,+ "measuredBaselineP95Ms": 1258,+ "measuredCandidateP95Ms": 242,+ "defaultsChanged": false,+ "costOrigin": "synthetic-fixture",+ "limitations": "Real verifier subprocesses, signatures, file persistence, feedback cycle and heldout gates; synthetic workload and cost fixture only. No live provider quality, billing savings, universal safety or native vector backend is claimed."+ },+ "sourceQualification": "Base feature commit plus the Node20 worker test harness correction and offline Transformers.js configuration; exact final worker hash below.",+ "consoleTests": {+ "passed": 150,+ "files": 8,+ "seconds": 17.51+ },+ "offlineNativeValidation": {+ "workerSha256": "542c929ec1482562964169d3ae083612e1f52fbd4685834c246c07870748d54c",+ "sourceWriteRows": 3,+ "sourceReplayRows": 3,+ "workers": 1,+ "sourceIndexMs": [+ 3030.97137,+ 469.28666,+ 482.79537+ ],+ "compiledRestartRecallRows": 3,+ "passed": true,+ "configuration": "Resolve AgentDB transformer module identities and disable allowRemoteModels before native registry initialization",+ "boundary": "Linux source and emitted JavaScript native runtime exercised; no full monorepo build or operating system network sandbox claim"+ }+}diff --git a/docs/validation/managed-ruos-e2e.json b/docs/validation/managed-ruos-e2e.jsonnew file mode 100644index 0000000000..d35500a939--- /dev/null+++ b/docs/validation/managed-ruos-e2e.json@@ -0,0 +1,107 @@+{+ "sourceBase": "8e08b5fbe48b9c7a55e4224cd1f5c15bf9095554",+ "consolePureSpecs": { "passed": 3516, "skipped": 35, "filesPassed": 236, "filesSkipped": 5, "durationSeconds": 214.74, "maxWorkers": 1, "exitCode": 0 },+ "learningStoreSha256": "34b4d08ae338edf40711ebc0a2fbc560aff8234c6edb5a43650a6be87865d9e3",+ "node": "20.20.2",+ "memory": "3.0.9",+ "sqlite": "12.11.1",+ "write": {+ "mode": "write",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "indexed": [+ {+ "indexed": true,+ "durable": true,+ "namespace": "managed-workflow-evidence",+ "id": "10654aef6e93d97a2d250ec7052326a6e8230fce42ad806cdaf8ff0229b43982",+ "hasEmbedding": true,+ "advisory": true+ },+ {+ "indexed": true,+ "durable": true,+ "namespace": "managed-workflow-evidence",+ "id": "1f6a6b39cabd277d258b4c3504a13900ed5c6d30510a68ac964f1d6681de4fd7",+ "hasEmbedding": true,+ "advisory": true+ },+ {+ "indexed": true,+ "durable": true,+ "namespace": "managed-workflow-evidence",+ "id": "1923ca387495897e3632d36f17a7405d038a487a62e8d52d23f0d1060d414afd",+ "hasEmbedding": true,+ "advisory": true+ }+ ],+ "advisoryStrategy": "fixture",+ "passed": true+ },+ "restartRecall": {+ "mode": "recall",+ "syntheticFixtures": true,+ "modelCalls": 0,+ "defaultsChanged": false,+ "verifiedRows": 3,+ "recalled": 3,+ "backend": "ruflo-memory",+ "similarityIsVerification": false,+ "advisoryStrategy": "fixture",+ "passed": true+ },+ "terminalChecks": {+ "managedRun": true,+ "providerUnverified": true,+ "workersUnverified": true,+ "acceptanceUnverified": true,+ "budget": true+ },+ "liveClaude": {+ "passed": false,+ "error": "OAuth session expired and could not be refreshed",+ "toolCalls": 0,+ "reportedCostUsd": 0+ },+ "authenticatedConsoleRetry": {+ "loginVerified": true,+ "modelTurnSucceeded": true,+ "pluginListed": true,+ "pluginVersion": "0.49.0",+ "hostVersion": "2.1.283",+ "consoleToolsAvailable": false,+ "consoleToolCalls": 0,+ "reportedCostUsd": 0.0183653,+ "driverExitCode": 1,+ "passed": false+ },+ "compatibleHostVerification": {+ "hostVersion": "2.1.287",+ "installedConsoleVersion": "0.48.0",+ "candidateConsoleVersion": "0.49.0",+ "modVersion": "0.7.0",+ "swarmVersion": "0.3.7",+ "installedPluginsEnabled": true,+ "stableDriverExitCode": 0,+ "candidateDriverExitCode": 0,+ "candidateToolCalls": 2,+ "candidateReportedCostUsd": 0.0389625,+ "interactivePaneVisuallyConfirmed": true,+ "syntheticManagedSnapshot": true,+ "managedProviderCalls": 0,+ "checks": {+ "managedRun": true,+ "providerUnverified": true,+ "workersUnverified": true,+ "acceptanceUnverified": true,+ "budget": true+ },+ "passed": true+ },+ "directProvider": {+ "tested": false,+ "reason": "No API key delivered to executor"+ }+}diff --git a/docs/validation/managed-ruos-e2e.md b/docs/validation/managed-ruos-e2e.mdnew file mode 100644index 0000000000..e73e3b5d69--- /dev/null+++ b/docs/validation/managed-ruos-e2e.md@@ -0,0 +1,147 @@+# Managed workflows ruOS integration validation++Date: 2026-10-25. Machine: Work Desktop, Fly ID `85050dc77130e8`.+Source: PR #4471 commit `8e08b5fbe48b9c7a55e4224cd1f5c15bf9095554`, followed by+the recall hydration fix in this commit. Node 20.20.2; Claude Code 2.1.283;+installed Ruflo 3.47.1 was left unchanged. The candidate was checked out into+`/home/ruv/work/ruflo-managed-e2e-4471`; tests and terminal bundle use that source.+Initial isolated tests did not change tenant routes, capability grants or global+runtimes. Subsequent user-authorized login and installation are recorded below.++## Verified results++| Boundary | Result |+| --- | --- |+| Candidate backend contracts on ruOS | 167 tests passed before the recall fix |+| Candidate focused console regressions on ruOS | 101 tests passed |+| Complete pure console spec suite on ruOS, one worker | 3,516 passed, 35 skipped; 236 files passed, five skipped; 214.74 seconds; exit 0 |+| Backend regressions after recall fix, local workspace | 168 passed; strict adapter types passed locally and on ruOS |+| Standalone console build | Actual candidate terminal bundle built successfully |+| Disk snapshot to terminal host to Workflows view | Passed five assertions: managed run, provider unverified, workers unverified, acceptance unverified, reported budget |+| Signed local ledger to new process | Three fixture receipts survived and were reverified |+| Native indexing with declared memory 3.0.9 | Three records durably indexed with embeddings |+| Native search after process restart, before fix | Failed: zero of three receipts recalled |+| Native search after process restart, after fix | Passed: three of three receipts authenticated; advisory strategy returned; defaults unchanged |+| Claude login and authenticated retry | Login verified; model turn succeeded; console driver failed because console tools were absent |+| Installed stable plugins with Claude Code 2.1.287 | Console tools registered; Workflows driver exited 0 |+| Candidate managed view with Claude Code 2.1.287 | Two actual console tool calls, all five display assertions passed; reported cost $0.0389625 |++The terminal check injected workersInspected=true, acceptancePassed=true and+verification=verified into a snapshot. The real Node filesystem reader and+bundled terminal host still displayed all three verification boundaries as+unverified. This was a local fixture integration test, not provider execution or+validation of the Claude Code function-hook host. Its snapshot was read without+a CLI entry or model transport.++Native tests used `scripts/e2e-managed-native.mts` in separate write and recall+processes. The fixture signing key was generated in memory and never persisted;+only its public key and signed synthetic metadata were stored. The observations+are explicitly synthetic plumbing evidence, not model-quality measurements or+production evaluation receipts. There were zero model calls and no automatic+promotion. The test used the real memory initializer, native SQLite writer and+embedding backend, rather than mocked memory APIs.++The complete pure spec command used `--maxWorkers=1 --testTimeout=30000` and+excluded `**/*.test.ts` as the plugin smoke does for host-kit tests. This resolves+the earlier incomplete pure suite result under contention; it does not claim+that the authenticated host-kit tests or full monorepo suite passed.+Machine-readable native and terminal evidence: [receipt](managed-ruos-e2e.json).++## Defect found and corrected++`searchEntries` returns 60-character content previews plus an ellipsis. The+initial implementation tried to parse those previews as complete signed JSON,+so actual authenticated recall returned no evidence even though native rows and+embeddings were present. Mocked contracts had supplied full JSON and missed it.++Recall now hydrates each eligible hit using the existing `getEntry` operation+with the exact project database, fixed namespace and admitted digest key. It+then rechecks row key, namespace, size, schema, signature, content digest and+local training-cohort membership. Search rank never establishes verification.+A regression covers truncated previews and mismatched hydrated namespaces.+Recommendations still use the complete eligible training cohort.++## Host incompatibility and unresolved live gate++The desktop's installed `@claude-flow/memory` was 3.0.0-alpha.26. A diagnostic+initialization with that older package aborted its process (exit 134) with+`memory allocation of 4158883080 bytes failed`. This is not evidence that the+candidate's pinned dependency has the same failure. The isolated probe was+aligned to the candidate manifest's memory 3.0.9 without changing global+packages; write and restart recall then passed after the hydration fix.++The isolated dependency install disabled lifecycle scripts and reused the+desktop's already working better-sqlite3 12.11.1 native binding of the same+installed package version. Initial old-backend versions were AgentDB+3.0.0-alpha.20 and RuVector core 0.1.32. No claim of arbitrary historical backend+compatibility follows from the successful current-dependency run.++The first real headless Claude console driver failed before any tool call:+`Failed to authenticate: OAuth session expired and could not be refreshed`.+It reported cost $0 and zero calls. ANTHROPIC_API_KEY and CLAUDE_API_KEY were+absent from the executor environment and Claude settings. The ruOS vault lists+an Anthropic slot, but the exposed tools do not supply a verified key-delivery+path for this running executor. Secret values were never requested or printed.++The user subsequently completed authentication. `claude auth status` confirmed+a logged-in Claude subscription, and the repeated driver made a successful model+turn with reported cost $0.0183653. Its system initialization listed+ruflo-console 0.49.0 from the candidate path, but no console tools were registered.+The model reported console_state, console_open, console_set and console_run+unavailable. The driver exited 1 with zero console calls. This establishes an+actual host registration blocker on Claude Code 2.1.283; it does not isolate+whether the cause is host feature support, configuration or module loading.+No authorization code or token is included in these artifacts.++### Installation and compatible host resolved console registration++At the user's request, the official ruflo marketplace was refreshed and+ruflo-mods 0.7.0, ruflo-swarm 0.3.7 and ruflo-console 0.48.0 were installed and+enabled at user scope. Existing settings were backed up privately, then the+documented CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 setting was enabled. Even with+that flag, the 2.1.283 isolated driver made no console calls.++Claude Code 2.1.287 was installed in an isolated prefix from its pinned official+npm package. Its native Linux binary passed console hook validation and the+stable Workflows driver (console_open and console_state, exit 0). A user-local+claude-ruflo launcher and Ruflo Console desktop entry select that tested host;+the system claude binary was not replaced. The real interactive /ruflo pane+was opened and visually confirmed on the desktop with the installed console.++The candidate console 0.49.0 was then loaded with --plugin-dir using 2.1.287,+alongside the installed mods and swarm. The actual Claude console driver made+two tool calls and exited 0; a separate assertion over its full tool-result+stream confirmed the managed session, reported budget and all three unverified+correctness boundaries. The seed intentionally claimed verified=true. The test+cost reported $0.0389625. Stable 0.48.0 remains the installed console; the draft+candidate was tested without publishing or replacing that installed version.++This supersedes the console registration blocker for the tested 2.1.287 host.+The version comparison is an observed compatibility matrix, not a diagnosis of+every internal host rollout condition. The managed source was based on+8e08b5fbe48b9c7a55e4224cd1f5c15bf9095554; its console files were unchanged by+the later recall and documentation commits. No remote provider was contacted+by the managed view itself.++Direct Anthropic Managed Agents execution, live budget pauses and fresh remote+controls remain unvalidated. A Claude subscription login does not establish+Managed Agents API credentials or beta entitlement. Securely deliver an+authorized API key with beta access before rerunning the bounded provider test.++## Reproduction and acceptance++With the candidate's declared native dependencies and tsx available:++```sh+node node_modules/tsx/dist/cli.mjs scripts/e2e-managed-native.mts write /tmp/managed-native-probe+node node_modules/tsx/dist/cli.mjs scripts/e2e-managed-native.mts recall /tmp/managed-native-probe+```++Use a new isolated directory for each write. The second command must run in a+new process, recall all three signed rows and leave defaults unchanged. Native+abort diagnostics must run in an isolated process; JavaScript cannot catch a+native process abort. Do not substitute a sql.js fallback for the native gate.++Release acceptance additionally requires one bounded live workflow visible in+the actual console host, a policy denial at execution, verified remote cleanup,+and independent task acceptance evidence. Until then PR #4471 remains draft.diff --git a/plugins/ruflo-agent/.claude-plugin/plugin.json b/plugins/ruflo-agent/.claude-plugin/plugin.jsonindex b5a740956b..5e7cf1660b 100644--- a/plugins/ruflo-agent/.claude-plugin/plugin.json+++ b/plugins/ruflo-agent/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-agent",- "description": "Agent runtimes for ruflo — local WASM-sandboxed agents (rvagent: 10 wasm_agent_*/wasm_gallery_* MCP tools, built on @ruvector/rvagent-wasm + @ruvector/ruvllm-wasm per ADR-070) plus Anthropic Claude Managed Agents as a cloud backend (managed_agent_* MCP tools per ADR-115). One interface, local-vs-cloud runtimes.",- "version": "0.3.4",+ "description": "Local WASM and managed cloud runtimes with bounded dynamic workflows, live capability discovery and session-local mod policy.",+ "version": "0.4.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -22,7 +22,9 @@"mcp","gallery","mod",- "function-hooks"+ "function-hooks",+ "dynamic-workflows",+ "capability-discovery"],"userConfig": {"guard": {@@ -35,6 +37,35 @@"on","off"]+ },+ "managedWorkflows": {+ "type": "string",+ "title": "Managed dynamic workflows",+ "description": "Allow dynamic cloud workflow creation through this host session. Independent of secret guard.",+ "required": false,+ "default": "off",+ "options": [+ "on",+ "off"+ ]+ },+ "maxBudgetCents": {+ "type": "string",+ "title": "Maximum managed workflow budget",+ "description": "Canonical positive integer US cents. Default 2500 ($25). Invalid configured values deny dynamic creation.",+ "required": false,+ "default": "2500"+ },+ "allowInlineAgents": {+ "type": "string",+ "title": "Allow inline workflow agents",+ "description": "Allow dynamic inline agents; off requires predefined agents with separately reviewed tools.",+ "required": false,+ "default": "off",+ "options": [+ "on",+ "off"+ ]}}}diff --git a/plugins/ruflo-agent/CHANGELOG.md b/plugins/ruflo-agent/CHANGELOG.mdindex a57f95b39a..6f07357315 100644--- a/plugins/ruflo-agent/CHANGELOG.md+++ b/plugins/ruflo-agent/CHANGELOG.md@@ -2,6 +2,18 @@Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history.+## 0.4.0 — 2026-10-24+- feat: verified feedback cycles, independent host verification, atomic admission and isolated native memory with replay and policy checks+- fix: `managed_agent_prompt` could report the previous turn's answer as finished on a later poll while the new turn was still running; only events from the acknowledged message onward are tracked+- fix: `managed_agent_interrupt` now goes through the same host policy, session allowlist and fresh provider-state check as `managed_agent_control` (it had no gate); `managed_agent_terminate` obeys the allowlist, and deletes only the session's own environment, once `RUFLO_MANAGED_CONTROL=1` (default behaviour unchanged)+- fix: verifier receipts must use the canonical base64 spelling of the signature; other spellings of the same bytes verified yet were stored as separate records, which could fill the 500-record ledger+- fix: a failed local snapshot write no longer fails a successful provider read or a completed session deletion, and a prompt that fails after it was sent now reports its `messageId` so a retry does not send it twice+- chore: the API-key scope marker is a keyed digest under a per-process random key, never a bare hash of the key+- fix: hydrate native memory search previews before authenticating recalled managed workflow receipts; verified through ruOS process restart+- feat: shared managed run collection, policy checked controls and verified advisory learning with native evidence memory bridge+- feat: managed workflow capability discovery, bounded local mod policy and console policy metadata+- fix: ship the managed workflow integration through a versioned plugin update+## 0.3.4 — 2026-10-12- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)diff --git a/plugins/ruflo-agent/README.md b/plugins/ruflo-agent/README.mdindex 7390ac42c0..c7b8491e4e 100644--- a/plugins/ruflo-agent/README.md+++ b/plugins/ruflo-agent/README.md@@ -33,7 +33,7 @@ Design: [ADR-115](../../v3/docs/adr/ADR-115-managed-agents-rvagent-backend.md) (- `managed-agent` — run an Anthropic Claude Managed Agent (cloud) — create / prompt / status / events / list / terminate- `nested-subagents` — spawn nested sub-agent trees (depth ≤ 5) via Claude Code's native `Task` tool for context-managed deep delegation-## MCP surface (33 tools: 14 `wasm_agent_*`, 13 `wasm_gallery_*`, 6 `managed_agent_*`)+## MCP surface (37 tools: 14 `wasm_agent_*`, 13 `wasm_gallery_*`, 10 `managed_agent_*`)### WASM runtime — `v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts` (27 in total; the main ones)@@ -50,16 +50,20 @@ Design: [ADR-115](../../v3/docs/adr/ADR-115-managed-agents-rvagent-backend.md) (| `wasm_gallery_search` | Search the gallery || `wasm_gallery_create` | Publish a WASM agent to the gallery |-### Managed (cloud) runtime — `v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts` (6, ADR-115)+### Managed (cloud) runtime — `v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts` (10, ADR-115, ADR-0003, ADR-0004)| Tool | Purpose | WASM counterpart ||------|---------|------------------|+| `managed_agent_control` | Inspect, interrupt or terminate through fresh host allowlist and provider checks | Console confirm card |+| `managed_agent_learning` | Quarantine outcomes, verify host receipts, recommend, compare, index and recall evidence | Learning page |+| `managed_agent_capabilities` | Local adapter requirements and integration boundaries; no key or network needed | `/agent-mod capabilities` || `managed_agent_create` | Provision Agent + Environment + Session (`POST /v1/agents`, `/v1/environments`, `/v1/sessions`). Accepts `model` / `system` / `name` / `networking` / `packages` / `initScript` / `mcpServers` / `skills`. | `wasm_agent_create` || `managed_agent_prompt` | Send a user turn (`POST /v1/sessions/{id}/events`), poll until the session goes idle (default 180 s, cap 600 s) → `{finished, status, stopReason, assistantText, toolUses[], eventCount}` | `wasm_agent_prompt` || `managed_agent_status` | Session lifecycle state (idle/running/error, title, last error) | — || `managed_agent_events` | Full server-persisted event log + a summary (the transcript/artifact view) | `wasm_agent_files` || `managed_agent_list` | List Managed Agent sessions on the org (id, status, title) — see which are still billing | `wasm_agent_list` |-| `managed_agent_terminate` | `DELETE /v1/sessions/{id}` (± the environment) — **always call when done**; a cloud session bills container time + tokens until deleted | `wasm_agent_terminate` |+| `managed_agent_interrupt` | Queue a pause request; never confirms workflow cancellation | `wasm_agent_terminate` |+| `managed_agent_terminate` | `DELETE /v1/sessions/{id}` (± the environment) — **always call when done**; running sessions consume runtime and tokens | `wasm_agent_terminate` |> Beta API (`anthropic-beta: managed-agents-2026-04-01`); `multiagent` / `define-outcomes` on the agent config are research preview. `mcpServers` for a cloud agent must point at a **publicly reachable** URL — a local `ruflo mcp start` is not reachable from Anthropic's cloud (deploy/tunnel an HTTP ruflo MCP server first). Managed sessions cost LM tokens + container time and are rate-limited per org.@@ -68,7 +72,7 @@ Design: [ADR-115](../../v3/docs/adr/ADR-115-managed-agents-rvagent-backend.md) (- **CLI:** pinned to `@claude-flow/cli` v3.6 major+minor.- **WASM runtime:** built on `@ruvector/rvagent-wasm` + `@ruvector/ruvllm-wasm` (declared in `@claude-flow/cli`'s `optionalDependencies` per [ADR-070](../../v3/implementation/adrs/ADR-070-rvagent-wasm-completion.md)). Without those packages, the `wasm_agent_*` tools fall through to graceful-degradation no-ops.- **Managed runtime:** plain `fetch` against the Managed Agents REST API — no extra SDK dependency. Without `ANTHROPIC_API_KEY` / `CLAUDE_API_KEY`, every `managed_agent_*` tool returns a structured error pointing at the `wasm_agent_*` fallback (the CLI/MCP server stays up).-- **Verification:** `bash plugins/ruflo-agent/scripts/smoke.sh` is the contract (12 structural checks). CI: `.github/workflows/ruflo-agent-smoke.yml`. Behavioral guard for the cloud tools: `v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts` (no-network).+- **Verification:** `bash plugins/ruflo-agent/scripts/smoke.sh` is the contract (16 structural checks). CI: `.github/workflows/ruflo-agent-smoke.yml`. Behavioral guard for the cloud tools: `v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts` (no-network).## Sandbox / trust@@ -84,7 +88,7 @@ This plugin owns the `wasm-gallery` AgentDB namespace (kebab-case, per [ruflo-ag```bashbash plugins/ruflo-agent/scripts/smoke.sh-# Expected: "12 passed, 0 failed"+# Expected: "16 passed, 0 failed"```## Architecture Decisions@@ -109,3 +113,142 @@ Agent also ships as a function-hook mod (ADR-445 pattern; hooks in `hooks/`, loa- **Options** (`userConfig`): `guard` (`on` by default).Test: `claude plugin validate plugins/ruflo-agent`, `claude plugin test plugins/ruflo-agent`, and `bash plugins/ruflo-agent/scripts/smoke.sh`.++## Dynamic workflows++The existing cloud adapter accepts `dynamicWorkflows: true` and requires+`budgetCents` before provisioning any resources. Example:++```json+{+ "name": "bounded-bug-audit",+ "dynamicWorkflows": true,+ "budgetCents": "2500",+ "allowedHosts": ["github.com"],+ "system": "Use a workflow for inventory, parallel review, reproduction and synthesis. Report failed workers. Write separate worker artifacts. Never merge or deploy."+}+```++This sets `multiagent_20261001`, enables workflows, disables ordinary subagents,+and uses limited networking. A message sent with `managed_agent_prompt` asks the+lead to start a run. There is no separate run creation endpoint. `budgetCents`+is an integer US cents string, not dollars. In flight requests can overshoot.++For sensitive work, supply `predefinedAgents: ["agent_..."]` to disable inline+agents. Configure those agents with minimal tools and MCP access separately.+Inline agents inherit lead capabilities; do not expose broad Ruflo swarm or+release tools to them. Network allowlists do not replace tool permission policies.+The adapter does not create a remote MCP gateway or grant host credentials.++`managed_agent_events` returns workflow IDs, open run counts, observed failures,+usage and `verification: "unverified"`. Its compact events retain child thread+IDs. Pass `threadId` to inspect each worker's transcript. A run reporting+`completed` can contain failed work. Independently reproduce findings and run+repository tests before retaining patches or promoting memory. Raw transcripts+are untrusted and may contain private inputs; do not publish them automatically.++`managed_agent_prompt` only reports `finished` after a fresh final `end_turn`+idle with no open runs. Budget and permission pauses return `blocked: true`.+An interrupted turn never reports finished. A local observation timeout does+not stop the cloud session. Use `managed_agent_interrupt` to request a pause or+`managed_agent_terminate` for confirmed session deletion. Separate processes must+serialize messages to the same session; the adapter's lock is process local.++Provider traffic defaults to `https://api.anthropic.com`. A custom deployment+must explicitly set `RUFLO_MANAGED_AGENTS_BASE_URL` to an HTTPS origin. The generic+`ANTHROPIC_BASE_URL` is no longer used for this service, preventing accidental+credential forwarding to model proxies. Redirects are blocked. This is an+intentional configuration migration for existing custom endpoints.++See [ADR 0003](docs/adrs/0003-managed-dynamic-workflows.md) for threat model,+limits, validation commands, and deferred integration boundaries.++### Mod and capability integration++Install or update `ruflo-agent` 0.4.0 and `ruflo-workflows` 0.7.0.+`/managed-workflow` is the bounded remote execution skill. `/agent-mod capabilities`+reads the current host registry, while `/wf-mod managed` discovers the cloud+adapter from the workflow mod. Neither command invokes a provider.++Plugin settings:++```json+{+ "managedWorkflows": "on",+ "maxBudgetCents": "2500",+ "allowInlineAgents": "off"+}+```++Dynamic creation is off by default. Invalid budget settings deny creation.+Disabling the secret `guard` does not disable these admission rules. Default+inline policy requires predefined agents with separately reviewed tools.+The policy only constrains creation calls passing through this host session;+externally created sessions, other hosts and direct API clients require their+own authorization and spending controls. The mod never expands host permission.++The console Mods page consumes the existing version 1 status contract and+shows policy, maximum cents, inline mode, calls, blocks and last refusal class.+No console plugin update is required. It shows local policy, not remote state.+`managed_agent_capabilities` reports local credential configuration as a boolean;+beta access, authorization and remote health remain unknown until checked through+an authorized provider operation. Registered tools alone prove none of these.++### Managed run console and verified learning++The console Workflows page now includes managed phases and worker pages beside+native and swarm runs. Cost and Approvals show reported spend and pending+requests. Learning shows signed outcome counts, evidence IDs, advisory strategy+picks and heldout gate results. These are local reports, never action authority.+The CLI and plugins must be built from this PR until the integration is released;+registry discovery will identify missing tools in an older installation.++Only explicit prompt/inspection requests collect provider state. Panels read+cached local projections, with no provider traffic while inactive. One collector+shares reads per session; an OS lease blocks concurrent collectors in another+process. A crashed lease must be inspected before manual recovery. Sessions have+separate freshness timestamps and partial worker pages retain aggregate counts.++Host controls:++```text+RUFLO_MANAGED_CONTROL=1+RUFLO_MANAGED_CONTROL_SESSIONS=sesn_example+RUFLO_MANAGED_LEARNING=1+RUFLO_MANAGED_VERIFIER_PUBLIC_KEY=<trusted Ed25519 public PEM from host configuration>+```++These settings are off or absent by default. A console confirmation cannot+supply them. Control dispatch rechecks both host policy and fresh provider state.+Learning accepts only closed metadata; raw transcripts, arbitrary commands and+caller trust labels are rejected. Unsigned observations remain quarantined.+The independent host verifier signs source/artifact/policy/corpus/evaluator+identities, measured cost/latency and actual test results. The private key never+belongs in an agent prompt or MCP argument.++`managed_agent_learning` actions: `status`, `record`, `recommend`, `evaluate`,+`index`, `recall`. Recommendations use training receipts only. Heldout results+cannot teach the recommender or enter the memory index. Evaluation requires a+complete paired frozen corpus, at least three trials, equal admitted budgets,+at least 10% better successes per dollar, and safety/quality/latency gates plus+the existing MetaHarness conjunction. It never changes routing defaults.+Native append-only memory indexing and semantic recall are optional; absent+embeddings or backends are reported instead of being called a successful vector+integration. See [ADR 0004](docs/adrs/0004-verified-learning-and-console.md).++### Executable outcome verification and feedback cycles++The host runs `scripts/managed-outcome-verifier.mts` with a reviewed, owned+manifest and private signing key held outside test environments. Separate+acceptance, safety, replay and adversarial checks measure actual exits; source,+artifact and cost bindings are checked before signing. This trusted host utility+is not an arbitrary command tool for agents.++`managed_agent_learning` action `cycle` admits up to 24 signed measured outcomes,+records one atomic batch, optionally indexes six training outcomes, recalls,+recommends and evaluates a complete paired holdout. Its result is advisory; it+never starts model work or promotes defaults. `scripts/e2e-managed-loop.mts`+exercises the verifier and feedback path. `scripts/e2e-managed-provider.mts` is a+separate opt-in live canary and exits blocked without provider credentials and+predefined worker IDs. The native memory worker isolates crashes and timeouts;+it does not provide an operating-system memory sandbox. See ADR 0004.diff --git a/plugins/ruflo-agent/commands/managed-agent.md b/plugins/ruflo-agent/commands/managed-agent.mdindex 2bb77899ae..d0a5fb8f12 100644--- a/plugins/ruflo-agent/commands/managed-agent.md+++ b/plugins/ruflo-agent/commands/managed-agent.md@@ -8,6 +8,17 @@ Manage Claude Managed Agent sessions (the cloud agent runtime; the local WASM ru1. Call `mcp__plugin_ruflo-core_ruflo__managed_agent_list` to show every Managed Agent session on this org (id, status, title) — note which are still `running` (i.e. still billing).2. For a specific session: `mcp__plugin_ruflo-core_ruflo__managed_agent_status` `{ sessionId }` (idle/running/error) and `mcp__plugin_ruflo-core_ruflo__managed_agent_events` `{ sessionId }` (full transcript + a summary: assistantText, toolUses).3. To run new work: `mcp__plugin_ruflo-core_ruflo__managed_agent_create` then `mcp__plugin_ruflo-core_ruflo__managed_agent_prompt` (see the `managed-agent` skill for the full flow + the cost/cleanup notes).-4. Clean up stale sessions: `mcp__plugin_ruflo-core_ruflo__managed_agent_terminate` `{ sessionId, environmentId? }` — a cloud session bills until deleted.+4. Clean up stale sessions: `mcp__plugin_ruflo-core_ruflo__managed_agent_terminate` `{ sessionId, environmentId? }` — running sessions consume runtime and tokens.If `managed_agent_*` returns "needs ANTHROPIC_API_KEY" → no key/beta access; use the local `/wasm` runtime instead.++For dynamic workflows create with `dynamicWorkflows: true`, integer+`budgetCents` ("2500" = $25), and an exact `allowedHosts` list. Follow open runs+and worker transcripts before independently validating results. A completed run+is unverified. `managed_agent_interrupt` requests a pause; it never confirms+cancellation. A polling timeout does not stop cloud work. See the managed-agent+skill for the bounded workflow procedure.++For local discovery first inspect `managed_agent_capabilities`, which needs no+key and makes no network call. `/agent-mod capabilities` shows actual registry+names and plugin settings. `/managed-workflow` provides the bounded procedure.diff --git a/plugins/ruflo-agent/docs/adrs/0003-managed-dynamic-workflows.md b/plugins/ruflo-agent/docs/adrs/0003-managed-dynamic-workflows.mdnew file mode 100644index 0000000000..ed3ce883cd--- /dev/null+++ b/plugins/ruflo-agent/docs/adrs/0003-managed-dynamic-workflows.md@@ -0,0 +1,187 @@+---+id: ADR-0003+title: Bounded Managed Agents dynamic workflows+status: Proposed+date: 2026-10-24+---++## Outcome and scope++Extend ADR-115's existing cloud executor rather than create another provider+stack. Users can opt into Anthropic dynamic workflows, observe runs and worker+failures, interrupt work and preserve evidence without treating generated claims+as verified results. The existing six tools remain; interrupt and local capabilities are additive.+The native `workflow_*` scheduler and WASM runtime are unchanged.++Inputs: task text, an API credential held by the host, optional model, exact+network hosts, a mandatory dynamic-session budget, optional predefined agents.+Outputs: provider resource IDs, acknowledged message ID, run states, usage,+thread references, explicit blocked/interrupted/finished observations, unverified+assistant text. Assumption: the caller is authorized to use the configured+Anthropic organization. These tools are not a tenant authorization gateway.++## Primary source research++Reviewed 2026-10-24. The beta header stays `managed-agents-2026-04-01` and the+existing API version stays pinned to `2023-06-01`; no unrelated API migration.++1. [Multiagent configuration](https://platform.claude.com/docs/en/managed-agents/multiagent-orchestration):+ `multiagent_20261001`; workflows are agent generated and start from a user+ message. Disable ordinary subagents explicitly. Restrict inline capability+ inheritance with predefined agents when required.+2. [Workflow runs](https://platform.claude.com/docs/en/managed-agents/workflow-runs):+ run events occur on the primary session history. Runs remain open until+ status_ended. Provider completed does not imply successful worker execution.+ Current limits list 1,000 agents per run, 64 concurrently working threads+ without a concurrency guarantee, and a default 24 hour lifetime. The adapter+ does not advertise unenforceable per-run concurrency controls.+3. [Budgets](https://platform.claude.com/docs/en/managed-agents/budgets):+ attach at session creation; amount is canonical integer US cents, not dollars.+ Budget stops new model requests. In flight requests and tools can overshoot.+4. [Event API](https://platform.claude.com/docs/en/api/beta/sessions/events/list):+ chronological order, opaque next_page/page cursor; processed_at can be null+ while a submitted user event is queued. The send acknowledgement supplies+ the new user event ID.+5. [Events and interruption](https://platform.claude.com/docs/en/managed-agents/events-and-streaming):+ interrupts are asynchronous and do not end workflow runs. Permission pauses+ and budget pauses must not be called completion.+6. [Thread events](https://platform.claude.com/docs/en/api/beta/sessions/threads/events/list):+ inspect worker-specific events through the existing events tool's threadId.++## Decision and alternatives++| Alternative | Delivery and latency | Cost and risk | Decision |+| --- | --- | --- | --- |+| Extend existing REST adapter | No new runtime dependency; existing registration | One provider boundary to harden | Selected |+| Add a separate SDK/provider stack | More packaging and duplicate credential handling | Additional dependency and lifecycle drift | Rejected for this increment |+| Replace Ruflo orchestration with managed workflows | Requires migration; provider controls execution | Provider coupling; weakens portability | Rejected |++The adapter remains optional and performs no model call unless a user invokes+the managed tools. Dynamic creation requires budgetCents and limited networking;+legacy creation keeps its old networking default for compatibility. Generic+ANTHROPIC_BASE_URL is intentionally replaced by a dedicated HTTPS-origin+RUFLO_MANAGED_AGENTS_BASE_URL override to avoid sending organization credentials+to an unrelated model proxy. Redirects are refused.++## Control flow and invariants++1. Validate dynamic config before network activity. Construct a supported+ multiagent block; do not forward arbitrary multiagent JSON. Provision agent,+ environment and budgeted session. Return IDs for all known resources.+2. On a definite creation rejection, delete known resources created by that+ call, in reverse order. On ambiguous network/5xx failure preserve resources+ and return cleanupRequired. The server may have created a session before+ losing the response. Never blindly retry mutating requests.+3. Prompt: acquire a process-local session lock, send once, obtain message ID.+ Poll complete chronological history until that exact message has processed.+ Carry prior still-open runs but exclude old ended-run failures.+4. Reduce only current-turn processed events. Subsequently query with inclusive+ processed_at watermark and deduplicate IDs, including equal timestamps.+ Follow every next_page. Do not use a timestamp from the client clock.+5. Return blocked for budget/permission pause. Completion requires all runs to+ end and a subsequent final end_turn idle. An interrupt never counts as+ completion. A run's completed result never sets verification to passed.+6. A local timeout does not stop the remote session. Interrupt only requests a+ pause. Deletion confirms session termination; environment deletion only+ follows successful session deletion and contributes to cleanup success.++Success walkthrough: create budgeted session, acknowledge message, observe+run creation, worker output, run end, lead final idle. Report finished and+unverified; caller inspects workers and independently tests artifacts.++Failure walkthrough: provider handles a failed worker and ends a run completed.+The primary transcript may not include that error. Return unverified and+needsThreadInspection regardless. If the inspected worker reports session.error,+surface observedFailures. Never promote memory or merge a patch automatically.++## Security model and operational bounds++| Threat | Control | Residual risk |+| --- | --- | --- |+| Token amplification or recursive delegation | Mandatory cents budget; ordinary subagents disabled; document narrow MCP grants | In flight overshoot; inline workers inherit capabilities |+| Credential forwarding | Dedicated endpoint override, HTTPS origin only, redirects blocked | Operator can deliberately choose a custom HTTPS service |+| Secret leakage in exception output | Generic transport errors; discard upstream error bodies | Task transcripts can legitimately contain private content; caller must protect them |+| Stale or malformed lifecycle evidence | Message-ID boundary, validated pages, open-run tracking, independent verification required | Provider beta semantics can change |+| Memory/response exhaustion | 8 MB response, 16 MB transcript, 10,000 events, 100 pages; repeated cursor rejection | Large valid runs require external inspection; no silent truncation |+| Shared sandbox file races | Separate worker outputs; serialize patch application | Policy belongs to configured agents and caller, not prose alone |+| Duplicate writes/retries | Local prompt lock; no automatic POST retries | Multiple Ruflo processes require an external session ownership lock |+| Destructive cleanup after uncertain POST | Retain resources and disclose cleanupRequired | Manual resource reconciliation can be required |++Each HTTP call is bounded to 30 seconds. Prompt event reads share the remaining+observation deadline; sleep never extends it. Event inspection has a 30 second+deadline. The prompt wait setting bounds observation only, not remote lifetime.++Do not expose these organization-scoped tools directly to an untrusted remote+agent. A future deployed MCP gateway must independently enforce tenant identity,+tool allowlists, expiry, recursion depth and action capabilities. Network policy+is not a substitute for agent tool permission policies.++## Implementation loop and acceptance++Implement a narrow increment, run regression fixtures, inspect the diff with an+independent reviewer, fix confirmed issues, rerun tests, then benchmark against+the frozen source. Retain performance changes only when outputs and security+invariants match. No automatic release, merge, budget increase or capability+expansion is part of this loop.++| Requirement | Executable evidence |+| --- | --- |+| Budget and network admission before side effects | managed-workflows.test.ts dynamic admission cases |+| Current-turn lifecycle and final-idle semantics | historical idle, open runs, interruption and old failed run regressions |+| Failure transparency | API failure, malformed event and worker error fixtures |+| Bounded observation | page cycle/shape, transcript and deadline guards |+| Cleanup integrity | definite rejection, ambiguous failure and deletion failure fixtures |+| Optional offline runtime | managed-agent-tools.test.ts no-key fallback for all seven tools |+| Existing workflows unchanged | workflow validation, resume and ownership regression suites |+| Measured optimization | scripts/bench-managed-workflows.mjs, exact frozen source summarizer |++See [validation receipt](../../../../docs/validation/managed-dynamic-workflows.md)+for commands, measured results and limitations. Live provider validation and+equal-dollar model quality comparison remain separate release/adoption gates.++## Deferred boundaries and rollback++No remote MCP deployment, no task_assign/federation integration, no replacement+of workflow_run, no automatic artifact execution, no memory promotion and no+signed RVF export. Existing memory/RVF services can consume independently+verified artifacts later; a transcript is not a signed cognitive artifact.++Rollback: stop using dynamicWorkflows on new sessions, explicitly terminate+existing sessions and owned environments, or revert this PR. Removing the local+adapter does not stop remote sessions. No new production state schema or npm+dependency requires migration.++## Plugin and mod integration refinement++`ruflo-agent` 0.4.0 adds an independent creation admission hook. The optional+secret guard never disables dynamic policy. Settings default to cloud fanout+off, inline agents off, maximum 2500 US cents. A malformed configured cap becomes+zero and denies dynamic creation. Flat and wrapped tool input shapes are supported;+ambiguous mixed shapes are refused. The hook can deny or forward unchanged,+never grant permission over a downstream host denial.++`/agent-mod capabilities` refreshes the live tool registry locally, displays full+names and missing tools, and marks duplicate suffixes ambiguous. A failed registry+read is unknown, not missing. `managed_agent_capabilities` exposes local runtime+facts without network activity. Credential presence is a boolean; provider health,+beta access and authorization remain unknown. The descriptor names memory/RVF+boundaries without granting those capabilities.++`ruflo-workflows` 0.7.0 adds `/wf-mod managed` to discover that descriptor and route+to the new `managed-workflow` skill. The generic console already consumes modVersion,+summary and refusal class through version 1 status files, so the agent mod supplies+bounded static policy metadata without raw prompts, credentials or session IDs.++Admission is host-session-local. It does not govern externally created sessions,+other Ruflo processes or direct provider clients. Existing provider budgets and+host action capabilities remain independent. No new remote execution or provider+readiness is implied by plugin installation or registry discovery.++## Superseding integration detail++[ADR 0004](0004-verified-learning-and-console.md) extends this decision with all+five console/learning priorities: unified managed runs, shared collectors,+budget/blocker panels, fresh-policy controls and host-authenticated advisory+learning. It preserves the original unverified provider-completion boundary and+adds no automatic default/promotion authority. The optional memory bridge stores+verified training evidence rather than promoting a model or policy.diff --git a/plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.md b/plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.mdnew file mode 100644index 0000000000..12735da602--- /dev/null+++ b/plugins/ruflo-agent/docs/adrs/0004-verified-learning-and-console.md@@ -0,0 +1,345 @@+---+id: ADR-0004+title: First class managed console runs and verified advisory learning+status: Proposed+date: 2026-10-25+---++## Outcome++Extend [ADR 0003](0003-managed-dynamic-workflows.md) across all five requested+integration priorities: unified run model, one collector per session, budgets+and blockers, policy checked actions, and verified outcome feedback. Reuse+the console's workflow navigation, bounded readers, action confirmation and+Learning page; do not add a second dashboard or a provider client in hooks.++The resulting loop observes execution, records an outcome, authenticates a host+verifier's evidence, recalls training patterns, recommends a strategy and checks+it on a frozen holdout. No step silently promotes or deploys a default policy.++## Architecture and ownership++| Component | Input | Output and authority |+| --- | --- | --- |+| ManagedRunCollector | Explicit primary event/session reads | Incremental run, phase, worker and blocker facts; no correctness claim |+| Project collector lease | Project/session and host credential scope | One active collection; concurrent same-scope callers share it |+| Managed snapshot projection | Sanitized collected metadata | Six sessions, 60 worker rows/page, full aggregate counts, 128 KB maximum |+| Console | Local cached snapshots and learning summary | First class managed workflow rows, budgets, blockers and evidence; no provider traffic |+| managed_agent_control | Session/action, optional inspection offset | Fresh host policy and provider checks before dispatch; input cannot grant approval |+| Learning ledger | Closed metadata and optional Ed25519 receipt | Quarantine or authenticated measured outcome; 500 rows, 2 MB maximum |+| RuVector/AgentDB bridge | Authenticated training evidence | Native append-only index; independently revalidated recall hits |+| Advisory evaluator | Complete paired signed heldout results | Existing MetaHarness accept conjunction plus efficiency/safety gates; never a default write |++Production sources: `managed-run-collector.ts`, `managed-run-store.ts`,+`managed-learning.ts`, `managed-learning-store.ts` in the CLI services directory.+The two new MCP operations are `managed_agent_control` and+`managed_agent_learning`; the existing tool names remain available.++## 1. Unified console run model++`WfRun.kind` adds `managed`. Native, swarm and managed execution share workflow+navigation, but native controls are never offered for managed rows. Provider+phases and worker phase IDs are used when present; absent facts remain unknown.++The UI distinguishes provider completion, worker inspection and acceptance.+The collector always writes workersInspected=false, acceptancePassed=false and+verification=unverified. A completed provider run cannot produce a verified+badge. Signed learning receipts attest measured outcomes separately; they do+not make an unchecked snapshot an authorization token.++Each session carries its own observation timestamp. Refreshing one session+cannot make another session fresh. Observations older than 30 seconds or from+an implausible future timestamp are marked stale. Unknown cost is n/a, not zero.+Provider list cost is not mixed into unrelated local model budget totals.+Pending event IDs are shown for inspection; there is no blanket approval action.++## 2. Shared collector and bounded observation++Prompt polling and primary event inspection use one process-local singleflight+collector, with inclusive processed_at watermark, event-ID deduplication and+semantic replay equality. A 1 second cache prevents immediate duplicate reads.+Only explicit requests cause reads; snapshots, pagination and panel refreshes+never invoke a provider. There are no background collection timers.++A project/session OS lease prevents another process from collecting concurrently.+The lease is exclusive, never automatically stolen, and released on completion.+A crashed process may leave a lease requiring operator inspection. Singleflight+sharing never crosses host credential scopes. Session/action authorization is+not inferred from either the lease or cached data.++The collector caps six sessions, 10,000 events and 16 MB. It retains worker+aggregates while publishing 60 workers at a time. The console bounds file reads+and reuses parsed objects when text is unchanged. A collector cache is not a+restart journal; after restart it reloads provider history within the same caps.++## 3. Budget and approval visibility++Budget and reported list cost are integer US cents. Remaining budget and any+overshoot are displayed as observations. Provider budgets stop new requests,+so in flight work can exceed the cap. The console does not extrapolate unknown+cost or treat a budget pause as completion.++Permission requests, custom tool calls and requires_action event IDs populate+the blocker view. Confirmation/result events remove resolved IDs. Correctness+and host permissions are never inferred from a provider's completion label.++## 4. Controls recheck policy at execution++Console buttons use the existing confirmed, fixed CLI action:++```text+mcp exec -t managed_agent_control -p {sessionId,action,threadOffset?}+```++The handler accepts only inspect, interrupt and terminate. It requires+RUFLO_MANAGED_CONTROL=1 and an exact comma-separated session allowlist in+RUFLO_MANAGED_CONTROL_SESSIONS. It reads current provider state, then reads host+policy again immediately before dispatch. Unknown state, a changed policy,+unknown input fields, or a caller supplied approval flag fails closed.++Interrupt requests a pause and never confirms cancellation. Successful deletion+updates the observed session termination, without claiming acceptance or worker+inspection. Unexpected asynchronous deletion responses are not treated as+confirmed termination. Other direct managed tools retain their existing host+permission boundary; this control policy is not organization-wide authorization.++## 5. Verified learning and optimization++Learning writes require host RUFLO_MANAGED_LEARNING=1. The host configures the+trusted Ed25519 public key in RUFLO_MANAGED_VERIFIER_PUBLIC_KEY; an MCP caller+cannot supply a public key, declare itself verified, or request shell execution+through the learning API. The verifier's private key stays outside this service.++Version 1 observation metadata contains task/attempt/source/artifact/policy/+corpus/evaluator hashes, coarse task type, strategy ID/model/worker count/template,+split/trial, admitted budget, measured cost/duration, acceptance and safety+results, replay/adversarial verdicts, drift and rollback measurements. No raw+prompt, transcript, arbitrary command or credential field is accepted.++The trusted verifier must independently check the source and artifact and sign+the complete canonical observation after measuring the outcome. Cryptography+authenticates that verifier's statement; it does not replace the verifier's+tests or prove its operational independence. Unknown cost/duration cannot be+used for recommendations. Cumulative session list cost must not be mislabeled+as one task's measured cost.++Unsigned observations stay quarantined and cannot reserve a trusted attempt ID.+Quarantine has a separate 100-row ceiling, leaving capacity for authenticated+results. A matching valid attestation can attach to an unsigned observation;+two conflicting valid outcomes for one attempt are refused. Every reload and+memory recall rechecks signatures. Recommendations/evaluations are rederived+from currently valid receipts; old JSON advice cannot survive verifier rotation+or tampered evidence as supported advice.++Recommendations use only authenticated training observations in the exact task,+policy and evaluator cohort, require three distinct training tasks per strategy,+include failures in cost/quality denominators and enforce a latency constraint.+They return model, worker count, template, sample count, observed success rate,+successes per dollar, p95 latency and evidence IDs. Sample size is evidence,+not a calibrated probability. All-failed or unsupported cohorts abstain.++The optional memory index uses namespace managed-workflow-evidence, native+append-only writes and strict insertion. Uncertain persistence is an error;+missing embeddings are reported explicitly. Heldout and unsigned records are+never indexed. Semantic recall checks namespace, receipt signature, content+digest and local cohort membership. Similarity is not verification, and recall+does not select a favorable subset for efficiency scoring. The full eligible+training cohort determines the advisory recommendation.++Actual native integration showed that search results contain display previews,+not complete receipts. Recall hydrates the exact scoped row via getEntry before+checking its size, identity and signature. ruOS write/restart/recall validates+three embedded fixture receipts with the declared memory 3.0.9 dependency;+older desktop memory alpha.26 aborts during native initialization and is not+qualified. See the [ruOS validation](../../../../docs/validation/managed-ruos-e2e.md).++The actual console host path is qualified on Claude Code 2.1.287: installed+mods/swarm/console load and candidate managed views pass real console tool+assertions. The tested 2.1.283 host exposed no console tools even with the+function-hook flag; plugin installation alone is not proof of registration.++### Frozen evaluation gate++The heldout manifest declares 2 to 100 unique task hashes and 3 to 10 trials;+its canonical hash must match all paired receipts. Both strategies must have+exactly one result per task/trial, matching source identity and admitted budget.+Training/holdout task overlap is rejected. A project ledger binds a corpus to+one confirmation comparison, preventing candidate switching on that holdout.++Numeric domains are validated before the existing MetaHarness accept() function.+The gate requires at least 10% more verified successes per actual dollar, no+per-task acceptance regression, no safety failure, no p95 latency regression,+and the existing adversarial, replay, drift, receipt and rollback conjunction.+Fitness passed to MetaHarness is normalized cost efficiency, not raw pass rate.+Eligibility is advisory. No router champion, configuration, signing authority,+capability envelope or deployment state is modified. Statistical significance+and real model superiority require separately designed live experiments.++## Acceptance and measured limits++Required regressions include 1,000 workers with duplicate/reordered reconnects,+budget/permission pauses and failures; one collector and OS lease; no inactive+provider traffic; safe worker paging; stale policy denial; forged receipts;+quarantine poisoning; key rotation; heldout leakage; incomplete/mismatched trials;+failed persistence; and native tool/console compatibility.++The local bounded rendering target is under 16 ms. Validation measures warm+rendering with the actual view functions and fixture kit, not native GPU/UI+latency. CPU benchmarks and synthetic learning gate results cannot establish+live provider performance, dollar savings or model-quality improvements.++## Failure and rollback boundaries++Local files are advisory projections, not an action authority. Same-user+adversarial filesystem races are outside the directory-check guarantee. Atomic+file replacement and directory fsync are used; platforms without those semantics+must fail rather than claim durable writes. Ledger and summary are separate+atomic writes, so a crash can leave an older display summary.++Disable learning/control environment flags to stop those effects. Stop using+dynamicWorkflows for new sessions and explicitly terminate owned remote sessions+before removing the adapter. No existing default model, native workflow schema,+router state or memory row is migrated or overwritten by this integration.++Validation receipt: [managed learning and console](../../../../docs/validation/managed-learning-console.md).++## Amendment: executable verification and bounded feedback cycles++The next delivery closes four gaps exposed by native integration: managed+buttons were not callable through the model palette; signed observations had+no executable independent host verifier; native memory could abort the MCP+process; and individual learning operations required manual sequencing.++### Specification and invariants++1. Exact session-bound palette entries reuse the confirmed action runner and+ its existing permission classes. Text and selection changes cannot retarget+ an admitted action. The remote handler still rechecks provider and host policy.+2. A host-owned verifier manifest names explicit tests and source/artifact files.+ The verifier executes bounded argv checks without a shell, verifies measured+ cost bindings, rehashes files and signs the complete outcome. Failed tests+ remain failed observations, not discarded evidence. Neither MCP input nor a+ provider transcript supplies commands, signing keys or acceptance verdicts.+3. Native memory initialization and operations run in a fixed worker process.+ A timeout, native abort, malformed response or missing backend cannot become+ successful indexing and cannot take down the parent through a native abort.+ Process isolation is not an OS memory sandbox and does not prevent host OOM.+4. One cycle admits at most 24 measured signed outcomes in an exact cohort,+ persists one atomic batch, optionally indexes at most six training outcomes,+ recalls authenticated evidence, recommends and optionally evaluates paired+ holdouts. Every asynchronous phase rechecks the current host authorization.+5. A cycle never runs model tasks, starts a background timer, promotes policy,+ changes routing defaults or broadens an execution envelope. A scheduler or+ workflow invokes it explicitly after independent verification.++### Control flow and restart behavior++```text+verify host manifest and measurements+→ admit every signed outcome before mutation+→ persist atomic batch+→ optional bounded native index and authenticated recall+→ recommend from all eligible training evidence+→ optional complete paired holdout evaluation+→ return advisory result and phase evidence+```++The existing managed_agent_learning operation gains action=cycle with one+closed cycle object. The host flag and configured verifier key are checked+again across phase boundaries; a caller approval or promotion flag is rejected.+Indexing cycles with more than six training outcomes are rejected before any+write; the 24 outcome admission bound still applies to non-indexing cycles.+The worker permits one active operation with no queue, a 15 second operation+timeout and five second idle expiry. Host authorization is rechecked after native+initialization and immediately before an append grant. Revocation after a granted+write can report an admitted-write ambiguity; it cannot promise to undo that write.+The child strips provider credentials and configures the actual AgentDB+Transformers.js module to disable remote model loading before native startup.+These controls do not constitute an OS memory or network sandbox.++Per-attempt immutability makes replay safe. A failure after batch persistence+leaves durable evidence that can be retried, not a false claim that later phases+completed. Native insertion replay must verify the existing exact scoped row+instead of overwriting it or trusting a local index-complete marker.++The host verifier is trusted executable code, not a sandbox for arbitrary test+programs. Its private key is loaded outside child test environments. Host-owned+commands still require ordinary repository review and OS controls. Synthetic+fixture prices exercise the gate but cannot demonstrate economic improvement.++### Alternatives and operational tradeoffs++| Choice | Decision and rationale |+| --- | --- |+| Native imports in MCP process | Rejected: a native abort bypasses JavaScript error handling |+| Unbounded process per receipt | Rejected: repeated model/backend initialization and concurrency pressure |+| Bounded native worker lifecycle | Selected: isolates aborts and permits bounded warm reuse; native RSS still needs host limits |+| One fsync transaction per outcome | Retained for legacy record; cycles use one batch transaction to reduce durable-write overhead |+| Automatic promotion after the cost gate | Rejected: measured eligibility does not grant deployment authority |+| Model-submitted test command | Rejected: acceptance commands belong to the trusted host manifest |++### Acceptance and release gates++Run executable verifier success, failure, timeout, source mutation and cost+binding cases. Replay an authenticated cycle and confirm zero duplicate rows.+Revoke authorization between phases and confirm no later effects. Crash and+hang the native worker and confirm the parent remains available. Exercise+console_run with exact session IDs, confirmation and permission downgrades.+Measure atomic batching against the same sequential durable record baseline.++The live provider canary is separately opt-in, requires an executor API key and+one or two existing predefined agent IDs, uses the official origin and a fixed+small task with a $1 provider budget. In-flight requests may overshoot. Unknown+creation outcomes require inspection rather than blind retry or cascading+cleanup. Missing credentials produce a blocked result with zero provider calls.+Passing fixture E2E is not a live budget-pause or production-quality claim.++Linux ruOS, local CPU fixtures and CI have separate receipts. Windows/macOS+durability, production verifier operation and a live provider canary remain+explicit release gates until actual results exist. Disable learning/control+flags to stop effects; no automatic policy or memory migration is introduced.++Validation update, 2026-10-25: [feedback cycle report](../../../../docs/validation/managed-loop-e2e.md)+and [ruOS receipt](../../../../docs/validation/managed-loop-ruos.json) record 199+backend tests, 150 console tests, 86 verifier-loop assertions, source and emitted+JavaScript native persistence/restart recall, and the real MCP learning cycle.+The fixed-fixture batch benchmark reduced 18 transactions to one, with 7.29 times+lower median admission time. This measures ledger overhead, not provider quality+or cost savings. No routing default was promoted. Live provider, production+verifier and cross-platform release gates remain open.++## Amendment: independent review and known limits, 2026-10-25++An independent security and correctness review of this change found the defects below. They were fixed with a test that fails+without the fix: a stale previous-turn completion on later polls of `managed_agent_prompt`; `managed_agent_interrupt` having no+host policy gate (it now uses the `managed_agent_control` path; `managed_agent_terminate` obeys the same allowlist, and deletes only+the session's own environment, once `RUFLO_MANAGED_CONTROL=1`); non-canonical base64 spellings of one verifier signature being+stored as separate ledger records; a failed local snapshot write failing a successful provider read or deletion; a failed prompt not+reporting its `messageId`; and the console showing rescheduling, budget-stopped and action-blocked sessions as finished.++The following are **known limits that this change does not remove**. They are why learning and the control plane stay opt-in+(`RUFLO_MANAGED_LEARNING=1`, `RUFLO_MANAGED_CONTROL=1`) and why the evidence is advisory:++1. **The verifier runs its checks in the same trust domain as its signing key.** Checks run as the same user as the signer. A 0600+ key file is readable by any same-user process, so a check that executes agent-produced code can read the key and sign a false+ observation. The host-owned cost receipt and specs must live under the verified root, and the owner and group/world-write checks+ cannot tell the host's file from one the agent wrote as the same user. The command denylist does not stop `python3 -c`, `node -e`+ or `find -exec`. **Only run the verifier where its manifests and checks are authored by the host, never by the agent under test,+ and ideally sign from a separate user or container.** A cost receipt is not authenticated: `successesPerDollar` is only as honest+ as that file.+2. **Evidence is only partly bound to what ran.** `treeHash` covers the listed files; `evaluatorHash` hashes the command line, not+ the contents of the scripts or dependencies the check read. Receipts carry no ledger or project binding, key id or expiry, and+ a synthetic-fixture receipt signed by the production key looks the same as a live one in the ledger.+3. **A crashed process can leave a lock that nothing reclaims.** `*.collector.lock`, `snapshot.lock` and the learning `writer.lock`+ carry no pid or time. Remove the file by hand after confirming no ruflo process is running; concurrent writers fail instead of+ waiting.+4. **Some sessions cannot be controlled or can wedge.** A session in an `error` state is not accepted by the control allowlist. A+ conflicting replay of a processed event, or more than 10,000 events, makes refresh throw on every read until the process restarts.+5. **Observation cost.** Each poll deep-copies up to 16 MB of events two or three times, including on a cache hit.+6. **The learning summary is written after the ledger commit.** If it fails or exceeds 64 KB the caller sees an error although the+ record is committed.+7. **Unconfirmed against the live provider:** whether a `created_at[gte]` filter with a `processed_at` watermark can skip a message+ queued while the session was busy, and whether `max_list_cost.amount` is in cents. Both need the live-provider canary that is+ still an open release gate.++A native-memory child process is a process boundary, not an OS memory or network sandbox.diff --git a/plugins/ruflo-agent/hooks/command.ts b/plugins/ruflo-agent/hooks/command.tsindex e5c0eb85e6..041586ecab 100644--- a/plugins/ruflo-agent/hooks/command.ts+++ b/plugins/ruflo-agent/hooks/command.ts@@ -5,7 +5,7 @@ import type { Stats } from './status'/** `/agent-mod` is answered locally and takes no model turn. */export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats }-const HELP = ['/agent-mod status', '/agent-mod scan <text>', '/agent-mod guarded'].join('\n')+const HELP = ['/agent-mod status', '/agent-mod scan <text>', '/agent-mod guarded', '/agent-mod capabilities'].join('\n')export function answer(args: string, deps: CommandDeps): string {const [verb = '', ...rest] = args.trim().split(/\s+/)@@ -15,7 +15,7 @@ export function answer(args: string, deps: CommandDeps): string {if (verb === '' || verb === 'help') return HELPif (verb === 'status') {- return `guard ${opts.guard ? 'on' : 'off'} · calls guarded ${stats.calls} · blocked ${stats.blocked}`+ return `guard ${opts.guard ? 'on' : 'off'} · calls guarded ${stats.calls} · blocked ${stats.blocked}\nManaged workflow policy ${opts.managedWorkflows ? 'on' : 'off'}; maximum ${opts.maxBudgetCents} US cents; inline ${opts.allowInlineAgents ? 'on' : 'off'}`}if (verb === 'scan') {diff --git a/plugins/ruflo-agent/hooks/guard.ts b/plugins/ruflo-agent/hooks/guard.tsindex c42718c0cf..7f9adff9a5 100644--- a/plugins/ruflo-agent/hooks/guard.ts+++ b/plugins/ruflo-agent/hooks/guard.ts@@ -13,7 +13,7 @@ export function splitName(name: string): { server: string; tool: string } | undeexport function owns(tool: string, input: unknown): boolean {const parts = splitName(tool)const name = parts?.tool ?? tool- return ['wasm_agent_prompt', 'wasm_agent_tool', 'wasm_agent_create', 'wasm_gallery_create', 'managed_agent_create', 'managed_agent_prompt'].includes(name)+ return ['wasm_agent_prompt', 'wasm_agent_tool', 'wasm_agent_create', 'wasm_gallery_create', 'managed_agent_create', 'managed_agent_prompt', 'managed_agent_learning'].includes(name)}/** The reason a call is refused, or undefined when it may go. Never names or echoes the secret. */diff --git a/plugins/ruflo-agent/hooks/managed.ts b/plugins/ruflo-agent/hooks/managed.tsnew file mode 100644index 0000000000..c7d50d03a5--- /dev/null+++ b/plugins/ruflo-agent/hooks/managed.ts@@ -0,0 +1,50 @@+import type { ModOptions } from './options'+import { splitName } from './guard'++export const MANAGED_TOOLS = ['managed_agent_capabilities', 'managed_agent_learning', 'managed_agent_control', 'managed_agent_create', 'managed_agent_prompt', 'managed_agent_status', 'managed_agent_events', 'managed_agent_list', 'managed_agent_interrupt', 'managed_agent_terminate'] as const++const record = (v: unknown): Record<string, unknown> | undefined => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined++/** Host tool envelopes may be flat or hold arguments in input/arguments. Never scan arbitrary descendants as policy. */+export function managedInput(event: unknown): Record<string, unknown> | undefined {+ const e = record(event)+ if (!e) return undefined+ if ('input' in e) return e.dynamicWorkflows !== undefined || 'arguments' in e ? undefined : record(e.input)+ if ('arguments' in e) return e.dynamicWorkflows !== undefined ? undefined : record(e.arguments)+ return e+}++export function managedName(tool: string): string | undefined {+ const name = splitName(tool)?.tool ?? tool+ return (MANAGED_TOOLS as readonly string[]).includes(name) ? name : undefined+}++/** Tightens dynamic creation only; ordinary managed sessions retain their existing behavior. */+export function managedVerdict(tool: string, event: unknown, opts: ModOptions): string | undefined {+ if (managedName(tool) !== 'managed_agent_create') return undefined+ const input = managedInput(event)+ if (!input) return 'ruflo-agent: malformed managed tool input'+ if (input.dynamicWorkflows === undefined || input.dynamicWorkflows === false) return undefined+ if (input.dynamicWorkflows !== true) return 'ruflo-agent: dynamicWorkflows must be boolean'+ if (!opts.managedWorkflows) return 'ruflo-agent: dynamic workflow policy is off; enable managedWorkflows in plugin settings'+ if (typeof input.budgetCents !== 'string' || !/^[1-9][0-9]{0,8}$/.test(input.budgetCents) || Number(input.budgetCents) > opts.maxBudgetCents) return 'ruflo-agent: dynamic workflow budget exceeds plugin policy or is invalid'+ if (input.networking !== undefined && input.networking !== 'limited') return 'ruflo-agent: dynamic workflow network policy requires limited networking'+ if (!opts.allowInlineAgents && (!Array.isArray(input.predefinedAgents) || input.predefinedAgents.length === 0)) return 'ruflo-agent: plugin policy requires predefined agents; inline agents are off'+ return undefined+}++/** Registration is observable; beta access, authorization and remote health are not inferred. */+export function managedCapabilities(tools: readonly string[], opts: ModOptions): string {+ const available = new Set(tools.map(t => splitName(t)?.tool ?? t))+ const present = MANAGED_TOOLS.filter(t => available.has(t))+ const missing = MANAGED_TOOLS.filter(t => !available.has(t))+ return [+ `Managed workflow policy: ${opts.managedWorkflows ? 'on' : 'off'}; maximum ${opts.maxBudgetCents} US cents; inline agents ${opts.allowInlineAgents ? 'on' : 'off'}.`,+ `Registered managed tools (${present.length}/${MANAGED_TOOLS.length}): ${present.join(', ') || 'none'}.`,+ `Registry names: ${tools.filter(t => MANAGED_TOOLS.includes((splitName(t)?.tool ?? t) as typeof MANAGED_TOOLS[number])).slice(0, 32).map(t => t.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 160)).join(', ') || 'none'}.`,+ 'Duplicate tool suffixes across servers are ambiguous; select the trusted Ruflo server explicitly.',+ ...(missing.length ? [`Missing: ${missing.join(', ')}. Install or update ruflo-core and ruflo-agent.`] : []),+ 'Local registration is not authorization, beta access, credential readiness or remote health.',+ 'Use managed_agent_capabilities for runtime configuration facts. Use ruflo-workflows for persisted pipelines, wasm_agent_* for local sandboxing, memory_* only for independently verified evidence.',+ ].join('\n')+}diff --git a/plugins/ruflo-agent/hooks/options.ts b/plugins/ruflo-agent/hooks/options.tsindex 30d36f3420..eaac04f1c6 100644--- a/plugins/ruflo-agent/hooks/options.ts+++ b/plugins/ruflo-agent/hooks/options.ts@@ -3,6 +3,9 @@ import type { PluginOptions } from 'claude-code'/** The plugin's `userConfig`, validated: a bad value is the default (guard on). */export type ModOptions = {readonly guard: boolean+ readonly managedWorkflows: boolean+ readonly maxBudgetCents: number+ readonly allowInlineAgents: boolean}// BEGIN SHARED FLAG (generated by scripts/sync-mod-screen.mjs; edit plugins/ruflo-agentdb/hooks/options.ts)@@ -14,5 +17,8 @@ export function readOptions(options: PluginOptions | undefined): ModOptions {const o = options ?? {}return {guard: flag(o.guard, true),+ managedWorkflows: flag(o.managedWorkflows, false),+ maxBudgetCents: typeof o.maxBudgetCents === 'string' && /^[1-9][0-9]{0,8}$/.test(o.maxBudgetCents) ? Number(o.maxBudgetCents) : o.maxBudgetCents === undefined ? 2500 : 0,+ allowInlineAgents: flag(o.allowInlineAgents, false),}}diff --git a/plugins/ruflo-agent/hooks/register.ts b/plugins/ruflo-agent/hooks/register.tsindex 5682983e12..e414be5004 100644--- a/plugins/ruflo-agent/hooks/register.ts+++ b/plugins/ruflo-agent/hooks/register.ts@@ -2,6 +2,7 @@ import type { Hook, Register } from 'claude-code'import { answer } from './command'import { owns, verdict } from './guard'+import { managedCapabilities, managedName, managedVerdict } from './managed'import { readOptions } from './options'import { newStats, STATUS_PATH, statusText, type Stats } from './status'import type { ModOptions } from './options'@@ -32,7 +33,7 @@ export const register: Register = (on, options) => {s.root = (await $.session.root()) as string | undefineds.stats.startedMs = await $.clock.now()try {- await $.command.register({ name: 'agent-mod', description: 'Agent mod: status, scan <text>, guarded' })+ await $.command.register({ name: 'agent-mod', description: 'Agent mod: status, scan <text>, guarded, capabilities' })} catch {/* a name taken by another plugin must not stop the mod */}@@ -40,18 +41,25 @@ export const register: Register = (on, options) => {return result})- if (s.opts.guard) {+ {on('tool.call', async ($, e, next) => {- if (!owns(e.tool, e)) return next(e)+ if (!owns(e.tool, e) && !managedName(e.tool)) return next(e)s.stats.calls++- const reason = verdict(e.tool, e)- if (reason === undefined) return next(e)- s.stats.blocked+++ const policyReason = managedVerdict(e.tool, e, s.opts)+ const reason = policyReason ?? (s.opts.guard ? verdict(e.tool, e) : undefined)+ if (reason !== undefined) { s.stats.blocked++; s.stats.lastDenied = policyReason ? 'policy' : 'secret' }await flush($, s)- return { deny: reason }+ return reason === undefined ? next(e) : { deny: reason }})}/** `/agent-mod` (a markdown command of the plugin cannot be answered by a hook, so the mod owns this name). */- on('command.run', { command: 'agent-mod' }, async (_$, e) => ({ text: answer(typeof e.args === 'string' ? e.args : '', { opts: s.opts, stats: s.stats }) }))+ on('command.run', { command: 'agent-mod' }, async ($, e) => {+ const args = typeof e.args === 'string' ? e.args : ''+ if (args.trim() === 'capabilities') {+ try { return { text: managedCapabilities((await $.tool.list()).map(t => t.name), s.opts) } }+ catch { return { text: 'Tool discovery unavailable; managed runtime readiness is unknown.' } }+ }+ return { text: answer(args, { opts: s.opts, stats: s.stats }) }+ })}diff --git a/plugins/ruflo-agent/hooks/status.ts b/plugins/ruflo-agent/hooks/status.tsindex e0e535c1e3..cca205799d 100644--- a/plugins/ruflo-agent/hooks/status.ts+++ b/plugins/ruflo-agent/hooks/status.ts@@ -1,11 +1,11 @@/** Counters the mod keeps for the session and writes to `.claude-flow/agent-mod/status.json` for the console. */-export type Stats = { calls: number; blocked: number; startedMs: number }+export type Stats = { calls: number; blocked: number; startedMs: number; lastDenied?: string }export const newStats = (): Stats => ({ calls: 0, blocked: 0, startedMs: 0 })export const STATUS_PATH = '.claude-flow/agent-mod/status.json'/** The file's text; `version` lets the console refuse a shape it does not know. */-export function statusText(stats: Stats, mode: { guard: boolean }, nowMs: number): string {- return `${JSON.stringify({ version: 1, updatedMs: nowMs, mod: 'agent', guard: mode.guard, ...stats }, null, 2)}\n`+export function statusText(stats: Stats, mode: { guard: boolean; managedWorkflows?: boolean; maxBudgetCents?: number; allowInlineAgents?: boolean }, nowMs: number): string {+ return `${JSON.stringify({ version: 1, updatedMs: nowMs, mod: 'agent', modVersion: '0.4.0', guard: mode.guard, summary: `Managed workflows ${mode.managedWorkflows ? 'on' : 'off'}; budget ${mode.maxBudgetCents ?? 2500} cents; inline ${mode.allowInlineAgents ? 'on' : 'off'}; secrets ${mode.guard ? 'on' : 'off'}`, ...stats }, null, 2)}\n`}diff --git a/plugins/ruflo-agent/scripts/smoke.sh b/plugins/ruflo-agent/scripts/smoke.shindex 9398462472..3834748ccb 100755--- a/plugins/ruflo-agent/scripts/smoke.sh+++ b/plugins/ruflo-agent/scripts/smoke.sh@@ -7,11 +7,11 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json is ruflo-agent 0.3.4 with both-runtime keywords"+step "1. plugin.json is ruflo-agent 0.4.0 with both-runtime keywords"P="$ROOT/.claude-plugin/plugin.json"v=$(grep -E '"version"' "$P" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)n=$(grep -E '"name"' "$P" | grep -oE 'ruflo-agent' | head -1)-if [[ "$v" != "0.3.4" ]]; then bad "expected version 0.3.4, got '$v'";+if [[ "$v" != "0.4.0" ]]; then bad "expected version 0.4.0, got '$v'";elif [[ "$n" != "ruflo-agent" ]]; then bad "expected name ruflo-agent";elsemiss=""@@ -88,11 +88,11 @@ for f in "$ROOT"/skills/*/SKILL.md; dodone[[ -z "$bad_skills" ]] && ok || bad "wildcard:$bad_skills"-step "12. managed-agent (cloud runtime) skill + command + all 6 managed_agent_* tools referenced (ADR-115)"+step "12. managed-agent (cloud runtime) skill + command + all 10 managed_agent_* tools referenced (ADR-115)"miss=""[[ -f "$ROOT/skills/managed-agent/SKILL.md" ]] || miss="$miss missing-skill"[[ -f "$ROOT/commands/managed-agent.md" ]] || miss="$miss missing-command"-for t in managed_agent_create managed_agent_prompt managed_agent_status managed_agent_events managed_agent_list managed_agent_terminate; do+for t in managed_agent_control managed_agent_learning managed_agent_capabilities managed_agent_create managed_agent_prompt managed_agent_status managed_agent_events managed_agent_list managed_agent_terminate managed_agent_interrupt; dogrep -rq "$t" "$ROOT/skills" "$ROOT/commands" || miss="$miss no-ref-$t"done# the cloud-runtime skill must keep an explicit allowed-tools list (no wildcard) and offer the wasm fallback@@ -104,16 +104,16 @@ grep -q 'wasm_agent_create' "$ROOT/skills/managed-agent/SKILL.md" 2>/dev/null ||step "M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines"mod_ok=1grep -q '"./register.ts"' "$ROOT/hooks/hooks.json" || mod_ok=0-for f in options screen guard command status register; do+for f in options screen guard command status managed register; do[[ -f "$ROOT/hooks/$f.ts" ]] || mod_ok=0[[ $(wc -l < "$ROOT/hooks/$f.ts" 2>/dev/null || echo 9999) -le 500 ]] || mod_ok=0done[[ $mod_ok -eq 1 ]] && ok || bad "mod hooks incomplete or too long"-step "M2. mod: userConfig defaults are safe (guard on)"+step "M2. mod: userConfig defaults are safe (guard on, dynamic and inline off)"node -e 'const c = require(process.argv[1]).userConfig || {}-process.exit(c.guard && c.guard.default === "on" ? 0 : 1)+process.exit(c.guard?.default === "on" && c.managedWorkflows?.default === "off" && c.allowInlineAgents?.default === "off" && c.maxBudgetCents?.default === "2500" ? 0 : 1)' "$ROOT/.claude-plugin/plugin.json" && ok || bad "userConfig defaults wrong"step "M3. mod: hooks never touch the network or spawn a process"diff --git a/plugins/ruflo-agent/skills/managed-agent/SKILL.md b/plugins/ruflo-agent/skills/managed-agent/SKILL.mdindex 4087ef0575..b301cfe78d 100644--- a/plugins/ruflo-agent/skills/managed-agent/SKILL.md+++ b/plugins/ruflo-agent/skills/managed-agent/SKILL.md@@ -2,7 +2,7 @@name: managed-agentdescription: Run an Anthropic Claude Managed Agent — a cloud agent harness (container + filesystem + tools), the cloud counterpart of the local wasm-agent runtimeargument-hint: "<create|prompt|status|events|list|terminate> [options]"-allowed-tools: mcp__plugin_ruflo-core_ruflo__managed_agent_create mcp__plugin_ruflo-core_ruflo__managed_agent_prompt mcp__plugin_ruflo-core_ruflo__managed_agent_status mcp__plugin_ruflo-core_ruflo__managed_agent_events mcp__plugin_ruflo-core_ruflo__managed_agent_list mcp__plugin_ruflo-core_ruflo__managed_agent_terminate mcp__plugin_ruflo-core_ruflo__wasm_agent_create Bash+allowed-tools: mcp__plugin_ruflo-core_ruflo__managed_agent_control mcp__plugin_ruflo-core_ruflo__managed_agent_learning mcp__plugin_ruflo-core_ruflo__managed_agent_capabilities mcp__plugin_ruflo-core_ruflo__managed_agent_create mcp__plugin_ruflo-core_ruflo__managed_agent_prompt mcp__plugin_ruflo-core_ruflo__managed_agent_status mcp__plugin_ruflo-core_ruflo__managed_agent_events mcp__plugin_ruflo-core_ruflo__managed_agent_list mcp__plugin_ruflo-core_ruflo__managed_agent_terminate mcp__plugin_ruflo-core_ruflo__managed_agent_interrupt mcp__plugin_ruflo-core_ruflo__wasm_agent_create Bash---# Managed Agent (Anthropic cloud runtime)@@ -36,13 +36,13 @@ This skill drives the **managed** runtime — Anthropic's [Claude Managed Agents4. **List** — `mcp__plugin_ruflo-core_ruflo__managed_agent_list` `{ limit? }` — every session on the org (so you can see which are still running / billing).-5. **Terminate** — `mcp__plugin_ruflo-core_ruflo__managed_agent_terminate` `{ sessionId, environmentId? }` — **always do this when done**: a cloud session keeps billing container time + tokens until deleted. Pass `environmentId` to also delete the environment ruflo created.+5. **Terminate** — `mcp__plugin_ruflo-core_ruflo__managed_agent_terminate` `{ sessionId, environmentId? }` — **always do this when done**: running sessions consume runtime and tokens. Pass `environmentId` to also delete the environment ruflo created.## Cost & safety- Managed Agents bill per session (LM tokens + container time) and are rate-limited per org. Estimate before a long run; record completed sessions to the `cost-tracking` namespace.- Treat orphaned sessions like leaked resources — `managed_agent_list` then `managed_agent_terminate` anything stale.-- Beta API (`managed-agents-2026-04-01`); `multiagent` / `define-outcomes` on the agent config are research preview.+- Beta API (`managed-agents-2026-04-01`); dynamic workflows are opt-in beta; outcomes remain outside this adapter.## Quick example@@ -54,3 +54,47 @@ managed_agent_prompt { "sessionId": "sesn_…", "message": "echo hello > /tmp/xmanaged_agent_terminate { "sessionId": "sesn_…", "environmentId": "env_…" }→ { sessionDeleted: true, environmentDeleted: true }```++## Dynamic workflow procedure++1. Create with `dynamicWorkflows: true`, `budgetCents: "2500"` ($25), and exact+ `allowedHosts`. Networking is limited. Use `predefinedAgents` for restricted+ workers; otherwise inline agents inherit lead tools. Never expose recursive+ swarm launch or release tools to remote workers.+2. Prompt the lead to run inventory, review, reproduction and synthesis phases.+ Use separate worker output paths because the cloud sandbox is shared.+3. Follow `workflowRuns`, `openRuns`, `blocked`, `observedFailures` and+ `verification`. Budget/permission pauses are not completion. `finished`+ requires a new final idle after all runs end, and does not prove correctness.+4. Read child thread IDs in `managed_agent_events`; pass `threadId` to read each+ worker. Independently validate artifacts before merging or promoting memory.+5. `managed_agent_interrupt` queues a pause, never confirms cancellation.+ Observation timeouts leave remote work running. Delete the session explicitly+ when finished; delete only environments you own. Preserve IDs returned on+ failed creation and inspect ambiguous failures before retrying.++The six original tools remain available, plus `managed_agent_interrupt`, `managed_agent_control` (host-policy gated inspect, interrupt and terminate), `managed_agent_learning` and local `managed_agent_capabilities`. `managed_agent_interrupt` is gated like `managed_agent_control`; `managed_agent_terminate` is gated the same way once the host sets `RUFLO_MANAGED_CONTROL=1`.+No automatic gateway deployment, recursive delegation, budget escalation,+artifact execution, repository merge, memory promotion or RVF signing occurs.++Use `/managed-workflow` for the full dynamic workflow procedure and+`managed_agent_capabilities`, `/agent-mod capabilities` or `/wf-mod managed` to+discover the adapter. Default mod policy disables dynamic creation and inline+agents; enable only the settings needed for an already authorized task.++## Verified learning and console use++Use the console Workflows, Cost, Approvals and Learning pages to inspect managed+runs. Snapshots are staleable local observations and never authorize actions.+Use `managed_agent_control` for fresh policy checked inspect/interrupt/terminate;+the host must separately allow the exact session. Never pass an approval flag.++Before a repeated task, ask `managed_agent_learning` for a recommendation in the+exact task/policy/evaluator scope. It is advisory and cannot expand budget,+worker permissions, network access or default models. After independent host+verification, record the closed outcome and host Ed25519 signature. Unknown or+unsigned observations stay quarantined. Never request the verifier private key.+Use `index`/`recall` only for authenticated training evidence; preserve reported+backend/embedding failures. Use `evaluate` on a frozen, disjoint heldout manifest+with three or more trials before treating a strategy as eligible. Eligibility+never grants promotion, deployment or configuration writes.diff --git a/plugins/ruflo-agent/skills/managed-workflow/SKILL.md b/plugins/ruflo-agent/skills/managed-workflow/SKILL.mdnew file mode 100644index 0000000000..ef88e9524e--- /dev/null+++ b/plugins/ruflo-agent/skills/managed-workflow/SKILL.md@@ -0,0 +1,74 @@+---+name: managed-workflow+description: Discover and run bounded remote dynamic workflows with Ruflo mod policy, worker inspection and independent acceptance gates+argument-hint: "<task and acceptance test>"+allowed-tools: mcp__plugin_ruflo-core_ruflo__managed_agent_control mcp__plugin_ruflo-core_ruflo__managed_agent_learning mcp__plugin_ruflo-core_ruflo__managed_agent_capabilities mcp__plugin_ruflo-core_ruflo__managed_agent_create mcp__plugin_ruflo-core_ruflo__managed_agent_prompt mcp__plugin_ruflo-core_ruflo__managed_agent_status mcp__plugin_ruflo-core_ruflo__managed_agent_events mcp__plugin_ruflo-core_ruflo__managed_agent_list mcp__plugin_ruflo-core_ruflo__managed_agent_interrupt mcp__plugin_ruflo-core_ruflo__managed_agent_terminate+---++# Bounded managed workflows++Use this for remote Claude tasks with independent pieces and explicit acceptance+tests. Use `wasm-agent` for local isolated work, and `ruflo-workflows` for+persisted approval gates or native workflow scripts. Do not turn a simple task+into remote fanout just because tools are registered.++1. Inspect `managed_agent_capabilities`. Registration, configured credentials,+ provider beta access, tool authorization and remote health are separate facts.+ A configured credential is not proof of access. Never infer remote readiness.+2. The agent mod provides `/agent-mod capabilities` and the workflow mod provides+ `/wf-mod managed`. These commands list tools without making provider calls.+ Dynamic creation through the agent mod is off by default. Existing user+ authorization takes precedence; do not introduce another confirmation when+ the task already authorizes bounded execution.+3. Respect the host's `managedWorkflows`, `maxBudgetCents` and+ `allowInlineAgents` settings. Do not disable policy to bypass a refusal.+ Default maximum is 2500 US cents. Inline agents are off by default, requiring+ predefined agents whose tools were reviewed separately. In flight work can+ exceed a provider budget. This is local creation admission, not a global+ organization spending ceiling or a policy for externally created sessions.+4. Record task scope, source commit, output contract, deadline, budget, allowed+ network hosts and independent acceptance test before creation. Do not put+ keys or MCP tokens in prompts. Never give remote workers recursive Ruflo+ swarm launch, release or broad secret access.+5. Create with `dynamicWorkflows: true`, `budgetCents`, exact `allowedHosts`,+ and appropriate `predefinedAgents`. Save resource IDs. Send one scoped task+ asking for inventory, parallel work, independent reproduction and synthesis.+ Workers share files; require separate worker outputs and serialize patches.+6. Inspect open runs, pauses, failures and every worker thread with+ `managed_agent_events`. A run ending completed never proves correctness.+ Observation timeout does not stop remote work. Interrupt requests a pause;+ terminate confirms session deletion. Clean up only owned resources.+7. Independently test artifacts against the original source and acceptance+ contract. Persist only verified evidence through the repository's memory/RVF+ integration, binding source identity, reproduction commands and real usage.+ Never store credentials or promote an unverified transcript as learned truth.++The console's Mods page shows the agent mod's creation policy, cap, inline+setting and counters. It does not establish cloud run state. This skill grants+no additional tool, network, credential, memory or release authority.++## Verified learning and console use++Use the console Workflows, Cost, Approvals and Learning pages to inspect managed+runs. Snapshots are staleable local observations and never authorize actions.+Use `managed_agent_control` for fresh policy checked inspect/interrupt/terminate;+the host must separately allow the exact session. Never pass an approval flag.++Before a repeated task, ask `managed_agent_learning` for a recommendation in the+exact task/policy/evaluator scope. It is advisory and cannot expand budget,+worker permissions, network access or default models. After independent host+verification, record the closed outcome and host Ed25519 signature. Unknown or+unsigned observations stay quarantined. Never request the verifier private key.+Use `index`/`recall` only for authenticated training evidence; preserve reported+backend/embedding failures. Use `evaluate` on a frozen, disjoint heldout manifest+with three or more trials before treating a strategy as eligible. Eligibility+never grants promotion, deployment or configuration writes.++After the host verifier has tested and signed outcomes, use managed_agent_learning+action=cycle with a closed cycle object: scope, at most 24 evidence records,+optional index, maxP95Ms and evaluation (manifest, baselineId, candidateId).+One atomic batch precedes bounded native indexing and advisory evaluation.+Replays preserve attempt identity. Never place commands, keys, approval or+promotion flags in a cycle. A failed later phase can leave the signed batch+persisted; inspect status and retry the same evidence rather than inventing+new attempts. This is an explicit feedback step, not automatic task execution.diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.jsonindex e0759059ba..6fbb54d67a 100644--- a/plugins/ruflo-console/.claude-plugin/plugin.json+++ b/plugins/ruflo-console/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-console",- "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",- "version": "0.48.0",+ "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings \u2192 Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",+ "version": "0.49.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -85,7 +85,7 @@"look": {"type": "string","title": "Look",- "description": "bbs is the neon BBS look: an ASCII-art banner, ▓▒░ section headers and a cyberpunk palette. plain uses your terminal theme colours and plain rules (better on light backgrounds). orbital uses black telemetry panels, square red borders, muted values and green health indicators; best with a dark terminal.",+ "description": "bbs is the neon BBS look: an ASCII-art banner, \u2593\u2592\u2591 section headers and a cyberpunk palette. plain uses your terminal theme colours and plain rules (better on light backgrounds). orbital uses black telemetry panels, square red borders, muted values and green health indicators; best with a dark terminal.","default": "bbs","options": ["bbs",diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.mdindex 2aa2160327..3e29d84d05 100644--- a/plugins/ruflo-console/CHANGELOG.md+++ b/plugins/ruflo-console/CHANGELOG.md@@ -2,6 +2,13 @@Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`.+## 0.49.0 — 2026-10-24+- feat: exact managed session controls in the model palette with existing confirmation and permission gates+- fix: a rescheduling session shows as running, and a session stopped at its budget, waiting on a required action or holding an open tool request shows as active instead of finished+- feat: first class managed sessions in Workflows with reported budgets, remote blockers and host checked controls+- feat: advisory managed learning evidence and recommendations in Learning+- fix: provider completion never becomes a verified correctness badge; local snapshot flags are not authority+## 0.48.0 — 2026-10-24- feat: ruRE can read a folder outside the project that you allow (ADR-499). New option `rureFolders` (`name=/absolute/folder; name2=…`); a ruRE sample then names it as `@name/sub/file`. Changing the option is an install-class change that always waits for your Yes (Claude's console tools can only propose it at the full control level), so Claude can reach an outside folder only through a name you defined. A folder that is a link, a link anywhere below it, `..`, an absolute path typed as a sample, an unknown name, and a filesystem root are all refused; ruRE still only parses.- chore: the preflight of a ruRE row now receives the console's options (same line count in the runner).diff --git a/plugins/ruflo-console/README.md b/plugins/ruflo-console/README.mdindex c89b30074b..5c56c167f9 100644--- a/plugins/ruflo-console/README.md+++ b/plugins/ruflo-console/README.md@@ -14,6 +14,8 @@ RUFLO_E2E_LIVE=1 bash plugins/ruflo-console/scripts/drive.sh \Output is one `CALL <tool> <input>` and one `RESULT <tool> <text>` line per console call (each result cut at 4000 characters), then `COST <usd> CALLS <n>`, then one `EXPECT ok|FAIL /regex/` line per `--expect`.+For managed sessions, `console_state` with `filter: "managed"` lists exact session-bound palette ids such as `managed-inspect-sesn_abc`, `managed-interrupt-sesn_abc` and `managed-terminate-sesn_abc`. Pass a listed id to `console_run`; text arguments cannot select another session. The selected Workflows run is listed first. Inspect requires the `manage` control level; interrupt and terminate require `full` under the existing conservative action classifier. All use the console confirmation gate, and destructive actions still await the person in auto mode. At execution the managed control backend checks current provider state and host policy; displayed progress or verification claims grant no permission. `console_state` reports the current page as bounded text, so open Workflows, Cost or Learning before reading its managed facts.+| Exit | Meaning ||------|---------|| 0 | a console call ran and every `--expect` matched (or the run was skipped, see below) |@@ -154,3 +156,38 @@ The terminal color picker provides swatches and exact `#RRGGBB` entry for headinImports are limited to 4096 characters and a strict version 1 data schema. Status labels and actual check results remain unchanged. Saving requires at least 3:1 foreground/background contrast; the generator aims for 4.5:1.Theme Studio uses focused Colors, Motion and AI tabs. At 100 content columns it places the editor beside a persistent globe and routing preview; narrower panes stack both panels with a compact routing strip. A single color role picker replaces the repeated swatch lists. Minimum contrast is shown before saving, and Discard draft changes restores the active palette without deleting saved themes.+++## Managed workflow execution and learning++The Workflows page includes managed sessions alongside native workflows and+Ruflo swarms. It reads bounded local observations from+`.claude-flow/managed-workflows/snapshot.json`; it never starts a provider poll.+A session's phases/workers, provider state, observed failures, budget and list+cost are displayed with stale and partial markers. At most six managed sessions+and 60 workers per session are retained in the visible model. Larger totals+remain explicit. Unknown cost is n/a, never zero.++Provider finished, worker inspection and independent acceptance are separate+states. A local file claiming `verified: true` or acceptance success cannot+produce a green correctness badge. Inspect every worker through the runtime and+independently test artifacts before using learning evidence.++Inspect, Interrupt and Terminate buttons use the existing confirmation runner+with fixed argv to `managed_agent_control`. They pass only session ID and action.+The control handler must fetch fresh provider state and recheck current host+policy when it executes. A snapshot, even a fresh one, never grants authority.+No blanket remote approval button is exposed. An interrupt only requests a pause;+termination is only confirmed by the runtime's fresh result.++Cost shows managed session budgets separately from local session totals.+Approvals shows remote budget and permission blockers with an explicit Inspect+control. Learning reads the advisory summary at+`.claude-flow/managed-learning/summary.json`, up to 64 KB, and shows reported+quarantine/training/heldout counts, the recommended strategy, measured efficiency,+latency and evidence hashes. It does not revalidate signatures or promote defaults.+The runtime must revalidate evidence for routing; console summaries are untrusted+display evidence only.++Warm snapshots reuse both the existing file cache and parsed facts. View renders+are bounded to visible rows and make zero provider requests while inactive.diff --git a/plugins/ruflo-console/hooks/data/managed.ts b/plugins/ruflo-console/hooks/data/managed.tsnew file mode 100644index 0000000000..fe0c44fa36--- /dev/null+++ b/plugins/ruflo-console/hooks/data/managed.ts@@ -0,0 +1,126 @@+/** Local managed execution snapshots. Display evidence only, never action authority. */+import { cleanText } from './wf-clean'+import { jsonObject, recordOf } from './parse'+import { readBounded, under, type ReadCache, type ReaderFs } from './files'+import type { WfRun, WfAgent } from './workflows'++export const MANAGED_PATH = '.claude-flow/managed-workflows/snapshot.json'+export const LEARNING_PATH = '.claude-flow/managed-learning/summary.json'+export const MANAGED_MAX_BYTES = 128_000+export const LEARNING_MAX_BYTES = 64_000+export const MANAGED_STALE_MS = 30_000+export const MANAGED_SESSION_CAP = 6+export const MANAGED_THREAD_CAP = 60+const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/+const whole = (v: unknown, max = 1_000_000_000): number | null => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= max ? v : null+const label = (v: unknown, max = 80): string => typeof v === 'string' ? cleanText(v).slice(0, max) : ''+const id = (v: unknown): string | null => typeof v === 'string' && ID.test(v) ? v : null++export type ManagedThread = { id: string; runId: string | null; phaseId: string | null; status: string }+export type ManagedSession = {+ sessionId: string; updatedMs: number; status: string; stopReason: string | null; budgetCents: number | null; listCostCents: number | null;+ providerFinished: boolean; workersInspected: boolean; acceptancePassed: boolean; verification: 'unverified';+ runs: { id: string; status: string; result?: string; phases: { id: string; name: string; status: string }[] }[]; threads: ManagedThread[]; threadCount: number; threadOffset: number; partial: boolean;+ blockedEventIds: string[]; observedFailures: number;+ threadCounts: { running: number; ended: number; failed: number; idle: number };+}+export type ManagedFacts = { updatedMs: number; sessions: ManagedSession[]; omittedSessions: number }+export type ManagedLearning = {+ updatedMs: number; observations: number; verified: number; quarantined: number; training: number; holdout: number;+ selected: { id: string; samples: number; successesPerDollar: number | null; p95Ms: number | null; evidenceIds: string[] } | null;+ evaluation: { eligible: boolean; delta: number | null; pairedResults: number; noRegression: boolean } | null;+}++/** Known states stay literal; unknown strings cannot inject labels or status semantics. */+const state = (v: unknown): string => typeof v === 'string' && ['running', 'rescheduling', 'idle', 'terminated', 'ended', 'completed', 'failed', 'error', 'stopped', 'unknown'].includes(v) ? v : 'unknown'++export function parseManaged(text: string | null): ManagedFacts | null {+ if (text === null || text.length > MANAGED_MAX_BYTES) return null+ const value = jsonObject(text)+ if (value?.version !== 1 || whole(value.updatedMs, Number.MAX_SAFE_INTEGER) === null || !Array.isArray(value.sessions) || value.sessions.length > 100) return null+ const sessions: ManagedSession[] = []+ const seen = new Set<string>()+ for (const raw of value.sessions.slice(0, MANAGED_SESSION_CAP)) {+ const s = recordOf(raw), sessionId = id(s?.sessionId)+ if (s === null || sessionId === null || !sessionId.startsWith('sesn_') || seen.has(sessionId) || !Array.isArray(s.runs) || !Array.isArray(s.threads) || s.threads.length > 2000 || s.runs.length > 100 || whole(s.observedFailures, 100_000) === null || !Array.isArray(s.blockedEventIds)) return null+ seen.add(sessionId)+ const threads = new Map<string, ManagedThread>()+ for (const rawThread of s.threads) {+ const t = recordOf(rawThread), threadId = id(t?.id)+ if (t === null || threadId === null) return null+ threads.set(threadId, { id: threadId, runId: id(t.runId), phaseId: id(t.phaseId), status: state(t.status) })+ }+ const visible = [...threads.values()]+ const count = whole(s.threadCount, 100_000) ?? visible.length+ const offset = s.threadOffset === undefined ? 0 : whole(s.threadOffset, 9999)+ if (offset === null) return null+ const c = recordOf(s.threadCounts)+ const measured = c !== null && ['running', 'ended', 'failed', 'idle'].every(k => whole(c[k], 100_000) !== null)+ const threadCounts = measured ? { running: c!.running as number, ended: c!.ended as number, failed: c!.failed as number, idle: c!.idle as number } : {+ running: visible.filter(t => t.status === 'running').length,+ ended: visible.filter(t => ['ended', 'completed', 'terminated', 'stopped'].includes(t.status)).length,+ failed: visible.filter(t => ['failed', 'error'].includes(t.status)).length,+ idle: visible.filter(t => t.status === 'idle').length,+ }+ if (count < offset + visible.length || Object.values(threadCounts).reduce((a, b) => a + b, 0) > count) return null+ const runs = s.runs.map(r => {+ const v = recordOf(r), runId = id(v?.id)+ if (v === null || runId === null || (v.phases !== undefined && (!Array.isArray(v.phases) || v.phases.length > 100))) return null+ const phases = (Array.isArray(v.phases) ? v.phases : []).map(p => { const phase = recordOf(p), phaseId = id(phase?.id); return phase === null || phaseId === null ? null : { id: phaseId, name: label(phase.name) || phaseId, status: state(phase.status) } })+ if (phases.some(p => p === null)) return null+ return { id: runId, status: state(v.status), ...(typeof v.result === 'string' && { result: state(v.result) }), phases }+ })+ if (runs.some(r => r === null)) return null+ sessions.push({+ sessionId, updatedMs: s.updatedMs === undefined ? value.updatedMs as number : whole(s.updatedMs, Number.MAX_SAFE_INTEGER) ?? 0, status: state(s.status), stopReason: ['end_turn', 'budget_reached', 'requires_action'].includes(s.stopReason as string) ? s.stopReason as string : null,+ budgetCents: whole(s.budgetCents), listCostCents: whole(s.listCostCents), providerFinished: s.providerFinished === true,+ // Files are not verifier authority; even a forged true never becomes a verified badge.+ workersInspected: false, acceptancePassed: false, verification: 'unverified', runs: runs as ManagedSession['runs'],+ threads: visible.slice(0, MANAGED_THREAD_CAP), threadCount: count, threadOffset: offset, partial: count > Math.min(visible.length, MANAGED_THREAD_CAP),+ blockedEventIds: Array.isArray(s.blockedEventIds) ? [...new Set(s.blockedEventIds.filter(v => id(v) !== null) as string[])].slice(0, 100) : [],+ observedFailures: whole(s.observedFailures, 100_000) ?? 0, threadCounts,+ })+ }+ return { updatedMs: value.updatedMs as number, sessions, omittedSessions: Math.max(0, value.sessions.length - MANAGED_SESSION_CAP) }+}++export function parseManagedLearning(text: string | null): ManagedLearning | null {+ if (text === null || text.length > LEARNING_MAX_BYTES) return null+ const v = jsonObject(text)+ if (v?.version !== 1 || v.advisory !== true || v.defaultsChanged !== false || whole(v.updatedMs, Number.MAX_SAFE_INTEGER) === null) return null+ if (['observations', 'verified', 'quarantined', 'training', 'holdout'].some(k => whole(v[k], 100_000) === null)) return null+ if ((v.verified as number) + (v.quarantined as number) !== v.observations || (v.training as number) + (v.holdout as number) !== v.verified) return null+ const r = recordOf(v.lastRecommendation), selected = recordOf(r?.selected), strategy = recordOf(selected?.strategy)+ const e = recordOf(v.lastEvaluation)+ const finite = (n: unknown): number | null => typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : null+ return {+ updatedMs: v.updatedMs as number, observations: v.observations as number, verified: v.verified as number, quarantined: v.quarantined as number, training: v.training as number, holdout: v.holdout as number,+ selected: selected === null || strategy === null || id(strategy.id) === null ? null : { id: label(strategy.id), samples: whole(selected.samples, 100_000) ?? 0, successesPerDollar: finite(selected.successesPerDollar), p95Ms: finite(selected.p95Ms), evidenceIds: Array.isArray(selected.evidenceIds) ? selected.evidenceIds.filter(h => typeof h === 'string' && /^[a-f0-9]{64}$/.test(h)).slice(0, 6) : [] },+ evaluation: e === null ? null : { eligible: e.eligible === true, delta: typeof e.delta === 'number' && Number.isFinite(e.delta) ? e.delta : null, pairedResults: whole(e.pairedResults, 100_000) ?? 0, noRegression: e.noRegression === true },+ }+}++const parsed = new WeakMap<ReadCache, { managedText: string | null; managed: ManagedFacts | null; learningText: string | null; learning: ManagedLearning | null }>()+export async function readManaged(fs: ReaderFs, cache: ReadCache, cwd: string): Promise<{ managed: ManagedFacts | null; learning: ManagedLearning | null }> {+ const [m, l] = await Promise.all([readBounded(fs, cache, under(cwd, MANAGED_PATH), MANAGED_MAX_BYTES, true), readBounded(fs, cache, under(cwd, LEARNING_PATH), LEARNING_MAX_BYTES, true)])+ const mt = m.text, lt = l.text, held = parsed.get(cache)+ const managed = held?.managedText === mt ? held.managed : parseManaged(mt)+ const learning = held?.learningText === lt ? held.learning : parseManagedLearning(lt)+ parsed.set(cache, { managedText: mt, managed, learningText: lt, learning })+ return { managed, learning }+}++/** Managed sessions participate in the same bounded workflow navigation model. */+export function managedRuns(facts: ManagedFacts | null | undefined, nowMs: number): WfRun[] {+ if (!facts) return []+ return facts.sessions.map(s => {+ const stale = nowMs - s.updatedMs > MANAGED_STALE_MS || s.updatedMs > nowMs + 5000+ const phaseNames = new Map(s.runs.flatMap(r => r.phases.map(p => [`${r.id}:${p.id}`, `${r.id} / ${p.name}`] as const)))+ const agents: WfAgent[] = s.threads.map(t => ({ id: t.id, label: t.id, phase: t.runId && t.phaseId ? phaseNames.get(`${t.runId}:${t.phaseId}`) ?? `${t.runId} / ${t.phaseId}` : t.runId ?? 'Primary', state: stale ? 'stale' : t.status === 'running' ? 'running' : ['failed', 'error'].includes(t.status) ? 'failed' : ['ended', 'completed', 'terminated', 'stopped'].includes(t.status) ? 'done' : 'idle', hasWorktree: false, isUnverified: true }))+ const titles = [...new Set([...s.runs.flatMap(r => r.phases.length ? r.phases.map(p => `${r.id} / ${p.name}`) : [r.id]), ...agents.map(a => a.phase)])]+ const phases = titles.map(title => { const list = agents.filter(a => a.phase === title); return { title, detail: 'provider observation; correctness unverified', agents: list, done: list.filter(a => a.state === 'done').length, total: list.length, running: list.filter(a => a.state === 'running').length, failed: list.filter(a => a.state === 'failed').length } })+ return { id: s.sessionId, name: `Managed ${s.sessionId}`, kind: 'managed', state: stale ? 'stalled' : s.observedFailures > 0 ? 'failed' : s.status === 'running' || s.status === 'rescheduling' ? 'running' : s.stopReason === 'budget_reached' || s.stopReason === 'requires_action' || s.blockedEventIds.length > 0 ? 'active' : 'finished', phases,+ running: s.threadCounts.running, done: s.threadCounts.ended, failed: Math.max(s.observedFailures, s.threadCounts.failed), idle: s.threadCounts.idle, total: s.threadCount,+ totalTokens: null, isTokensPartial: true, hasRecord: true, updatedMs: s.updatedMs, isStale: stale, managed: s }+ })+}diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.tsindex f0034055b6..79d0a82653 100644--- a/plugins/ruflo-console/hooks/data/snapshot.ts+++ b/plugins/ruflo-console/hooks/data/snapshot.ts@@ -29,6 +29,7 @@ import { parseMissions, type MissionObservation } from './missions'import { readBounded, readDisk, textOf, type ProjectKey, type Read, type ReadCache, type ReaderFs } from './files'import { parseAgentdbMod, type AgentdbMod } from './agentdb-mod'import { readMods, type ModsFacts } from './mods'+import { readManaged, type ManagedFacts, type ManagedLearning } from './managed'import {parseAgents,parseClaims,@@ -92,6 +93,8 @@ export type Snapshot = {recall?: RecallFacts/** Every `.claude-flow/<short>-mod/status.json` the per-plugin mods wrote (ADR-446), bounded and shape-checked. */mods: ModsFacts+ managed?: ManagedFacts | null+ managedLearning?: ManagedLearning | nullchanged: numberreadAtMs: number}@@ -113,8 +116,12 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,const offered = location === undefined ? null : parseMarketplaceManifest(textOf(await readBounded(fs, cache, `${location}/.claude-plugin/marketplace.json`)))const reads = Object.fromEntries((Object.keys(disk.project) as ProjectKey[]).map(key => [key, statusOf(disk.project[key])])) as Snapshot['reads']+ const managed = await readManaged(fs, cache, cwd)+return {reads,+ managed: managed.managed,+ managedLearning: managed.learning,swarm,agents: parseAgents(text('agents')),tasks: parseTasks(text('tasks')),diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.tsindex db092efd0b..3e3d19fe6d 100644--- a/plugins/ruflo-console/hooks/data/workflows.ts+++ b/plugins/ruflo-console/hooks/data/workflows.ts@@ -11,6 +11,7 @@* Unknown event types and keys are ignored, a half-written last line is dropped, and a missing source is a missing fact:* nothing here is estimated.*/+import type { ManagedSession } from './managed'import { ESCAPES, HIDDEN, INVISIBLE, shortId, type AgentRecord } from './parse'export type AgentState = 'running' | 'done' | 'failed' | 'stale' | 'idle' | 'queued'@@ -36,6 +37,8 @@ export type WfAgent = {lastTool?: string/** Set for a ruflo agent: what the confirm-gated verbs act on. */ruflo?: AgentRecord+ /** Provider completion is never a correctness badge. */+ isUnverified?: boolean}export type WfPhase = { title: string; detail?: string; agents: WfAgent[]; done: number; total: number; running: number; failed: number }@@ -45,7 +48,7 @@ export type RunState = 'running' | 'completed' | 'failed' | 'stalled' | 'finisheexport type WfRun = {id: stringname: string- kind: 'workflow' | 'ruflo-swarm'+ kind: 'workflow' | 'ruflo-swarm' | 'managed'state: RunStatephases: WfPhase[]running: number@@ -65,6 +68,7 @@ export type WfRun = {updatedMs?: numberisStale?: booleanlisted?: number+ managed?: ManagedSession}const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)diff --git a/plugins/ruflo-console/hooks/managed-actions.ts b/plugins/ruflo-console/hooks/managed-actions.tsnew file mode 100644index 0000000000..002ed13b6b--- /dev/null+++ b/plugins/ruflo-console/hooks/managed-actions.ts@@ -0,0 +1,21 @@+/** Fixed, confirm-gated remote controls. The MCP handler rechecks provider and host policy at execution. */+import type { ActionSpec } from './actions'++export function managedAction(sessionId: string, action: 'inspect' | 'interrupt' | 'terminate', threadOffset?: number): ActionSpec | null {+ if (!/^sesn_[A-Za-z0-9_-]{1,95}$/.test(sessionId)) return null+ if (threadOffset !== undefined && (action !== 'inspect' || !Number.isSafeInteger(threadOffset) || threadOffset < 0 || threadOffset > 9999)) return null+ return {+ label: `${action} managed session ${sessionId}`,+ args: ['mcp', 'exec', '-t', 'managed_agent_control', '-p', JSON.stringify({ sessionId, action, ...(threadOffset === undefined ? {} : { threadOffset }) })],+ declared: action === 'terminate' ? 'delete' : action === 'inspect' ? 'network' : 'write',+ expect: 'a fresh provider result after current host policy is checked; a local snapshot never grants this action',+ note: action === 'interrupt' ? 'Requests a pause only; it does not confirm cancellation.' : action === 'terminate' ? 'Deletes the remote session after a fresh policy check; no environment is deleted by this button.' : 'Reads current remote status through the managed control tool; no background provider request.',+ timeoutMs: 60_000,+ lines: stdout => {+ try {+ const value = JSON.parse(stdout) as Record<string, unknown>+ return [`Remote ${action}: ${value.success === true ? 'reported success' : 'not confirmed'}.`, 'Provider completion is separate from acceptance and learning verification.']+ } catch { return ['Remote response could not be interpreted; inspect through the managed control tool.', 'No successful cancellation or verification is inferred.'] }+ },+ }+}diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.tsindex 089d88bedb..fc23c6a3dd 100644--- a/plugins/ruflo-console/hooks/palette.ts+++ b/plugins/ruflo-console/hooks/palette.ts@@ -29,6 +29,9 @@ import { XRUV } from './xruv'import { VEC, vecSpec, vecWhy } from './vector'import { selection } from './views/select'import { plain } from './data/parse'+import { managedAction } from './managed-actions'+import { pick } from './data/workflows-nav'+import { workflowsModelOf } from './wf-live'export type PaletteRun =| { kind: 'spec'; spec: ActionSpec | null; why: string }@@ -85,6 +88,22 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {const out: PaletteEntry[] = []const add = (id: string, group: string, label: string, run: PaletteRun) => out.push({ id, group, label, run })+ // Exact session-bound ids, never a text-taking command or a selected-run alias: changing the cursor cannot retarget a call.+ // These local facts admit a target only. The MCP control handler checks fresh provider state and host policy on execution.+ const managedSessions = state.snapshot?.managed?.sessions ?? []+ if (managedSessions.length) {+ const model = workflowsModelOf(state, nowMs)+ const selected = model === null ? null : pick(state.wf.ui, model.runs).run+ const sessions = [...managedSessions].sort((a, b) => Number(b.sessionId === selected?.id) - Number(a.sessionId === selected?.id))+ for (const session of sessions) {+ for (const action of ['inspect', 'interrupt', 'terminate'] as const) {+ const spec = managedAction(session.sessionId, action)+ if (spec === null) continue+ add(`managed-${action}-${session.sessionId}`, 'managed', `${action} managed session ${session.sessionId}${session.sessionId === selected?.id ? ' (selected)' : ''}`, { kind: 'spec', spec, why: 'managed controls require a valid session id and fresh host policy' })+ }+ }+ }+for (const amount of BUDGET_PRESETS) add(`cost-budget-${amount}`, 'cost', `set ruflo-mods budget to $${amount}`, { kind: 'spec', spec: setBudget(state, String(amount)), why: budgetWhy(state, String(amount)) })add('cost-budget', 'cost', 'cost-budget <amount>: set ruflo-mods costBudgetUsd (0.01–10000)', { kind: 'text', keyword: 'cost-budget', make: text => setBudget(state, text), why: text => budgetWhy(state, text) })add('cost-model-stats', 'cost', 'inspect local model routing counts (spend n/a)', { kind: 'spec', spec: inspectModels(state), why: '' })diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.tsindex 1bf1407aa9..abcb2125ea 100644--- a/plugins/ruflo-console/hooks/version.ts+++ b/plugins/ruflo-console/hooks/version.ts@@ -2,4 +2,4 @@* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.*/-export const CONSOLE_VERSION = '0.48.0'+export const CONSOLE_VERSION = '0.49.0'diff --git a/plugins/ruflo-console/hooks/views/cost.ts b/plugins/ruflo-console/hooks/views/cost.tsindex 5e5e6057a1..1238ce13d5 100644--- a/plugins/ruflo-console/hooks/views/cost.ts+++ b/plugins/ruflo-console/hooks/views/cost.ts@@ -1,4 +1,5 @@import type { RenderElement } from 'claude-code'+import { managedBudgetRows } from './managed'import { BUDGET_HELP, BUDGET_PRESETS, canSetBudget, ladderDollars, projectSpend } from '../cost'import type { ModelStats } from '../data/cli'@@ -71,6 +72,7 @@ export function costView(ctx: Ctx): RenderElement {rows.push(kv(ctx, 'budget', `${budget.level} · ${used === undefined ? 'n/a' : `$${used.toFixed(2)}`} of $${budget.limit.toFixed(2)} (${used === undefined ? 'n/a' : pct(used / budget.limit)})`, color))if (used !== undefined) rows.push(text(ctx, `${' '.repeat(17)}${ladder(used, budget.limit, Math.min(40, ctx.columns - 20))} 50·75·90·100%`, { color }))}+ rows.push(...managedBudgetRows(ctx))rows.push(...breakdownRows(ctx))rows.push(...providerRows(ctx))rows.push(rule(ctx, 'Alert thresholds', 'OK below 50%'))diff --git a/plugins/ruflo-console/hooks/views/learning.ts b/plugins/ruflo-console/hooks/views/learning.tsindex 398c889cb9..82d12ea38c 100644--- a/plugins/ruflo-console/hooks/views/learning.ts+++ b/plugins/ruflo-console/hooks/views/learning.ts@@ -1,4 +1,5 @@import type { RenderElement } from 'claude-code'+import { managedLearningRows } from './managed'import type { Intelligence } from '../data/cli'import { ago, art, col, count, kv, live, pct, picture, row, section, sourceLine, starts, text, THEME, type Ctx } from './common'@@ -138,6 +139,7 @@ export function learningView(ctx: Ctx): RenderElement {text(ctx, 'live engine: hooks_intelligence_stats in a fresh CLI process, so in-memory counters start at zero there', { dimColor: true }),]const rows: RenderElement[] = [+ ...managedLearningRows(ctx),...section(ctx, 'learn-router', 'Router', 'ruflo-mods · routing-outcomes.json', routerRows, true),...section(ctx, 'learn-pipeline', 'Pipeline', 'RETRIEVE → JUDGE → DISTILL → CONSOLIDATE', pipelineRows, true),...section(ctx, 'learn-sona', 'SONA · ReasoningBank', 'neural/stats.json', sonaRows, false),diff --git a/plugins/ruflo-console/hooks/views/manage.ts b/plugins/ruflo-console/hooks/views/manage.tsindex 7f933a5995..9ae254777a 100644--- a/plugins/ruflo-console/hooks/views/manage.ts+++ b/plugins/ruflo-console/hooks/views/manage.ts@@ -3,6 +3,7 @@* entries (by id), so a button here runs exactly what the palette or `/ruflo run <id>` would.*/import type { RenderElement } from 'claude-code'+import { managedApprovalRows } from './managed'import { approvalsOf, waitingApprovalsOf } from '../data/alerts'import type { Lane } from '../gfx/maps'@@ -23,6 +24,7 @@ export function approvalsView(ctx: Ctx): RenderElement {const items = approvalsOf(ctx.state)const picked = items.length === 0 ? -1 : ((ctx.state.select.item % items.length) + items.length) % items.lengthconst rows: RenderElement[] = [rule(ctx, 'Approvals', items.length === 0 ? 'nothing waiting' : headline(items.length, waitingApprovalsOf(ctx.state).length))]+ rows.push(...managedApprovalRows(ctx))if (items.length === 0) {rows.push(...paragraph(ctx, 'No hive-mind proposals, stealable claims, refused mods, permission denies or budget alerts waiting.', { dimColor: true }))diff --git a/plugins/ruflo-console/hooks/views/managed.ts b/plugins/ruflo-console/hooks/views/managed.tsnew file mode 100644index 0000000000..319967011c--- /dev/null+++ b/plugins/ruflo-console/hooks/views/managed.ts@@ -0,0 +1,70 @@+/** Managed runtime facts on existing pages. Local snapshots never authorize remote actions. */+import type { RenderElement } from 'claude-code'+import type { ActionSpec } from '../actions'+import type { WfRun } from '../data/workflows'+import { managedAction } from '../managed-actions'+import { MANAGED_STALE_MS, type ManagedSession } from '../data/managed'+import { ago, kv, text, rule, THEME, type Ctx } from './common'+import { flow } from './wf-layout'++const dollars = (cents: number | null): string => cents === null ? 'n/a' : `$${(cents / 100).toFixed(2)}`+const budget = (s: ManagedSession): string => `${dollars(s.listCostCents)} reported / ${dollars(s.budgetCents)} budget · remaining ${s.listCostCents === null || s.budgetCents === null ? 'n/a' : dollars(Math.max(0, s.budgetCents - s.listCostCents))}${s.listCostCents !== null && s.budgetCents !== null && s.listCostCents > s.budgetCents ? ` · overshoot ${dollars(s.listCostCents - s.budgetCents)}` : ''}`++export function managedRunRows(ctx: Ctx, run: WfRun, ask: (spec: ActionSpec) => void): RenderElement[] {+ const s = run.managed+ if (!s) return []+ const rows: RenderElement[] = [+ kv(ctx, 'runtime', `managed · ${s.status} · snapshot ${ago(run.updatedMs, ctx.nowMs)}${run.isStale ? ' · stale' : ''}`),+ kv(ctx, 'provider', s.providerFinished ? 'finished reported; correctness remains unverified' : `not finished${s.stopReason ? ` · ${s.stopReason}` : ''}`, THEME.info),+ kv(ctx, 'workers', 'inspection not independently verified by this console', THEME.warn),+ kv(ctx, 'acceptance', 'not independently verified; no green correctness badge', THEME.warn),+ kv(ctx, 'budget', budget(s)),+ kv(ctx, 'blockers', `${s.blockedEventIds.length} pending decisions · ${s.observedFailures} observed failures`),+ ]+ if (s.partial) rows.push(text(ctx, ` Showing workers ${s.threads.length ? s.threadOffset + 1 : 0}..${s.threadOffset + s.threads.length}/${s.threadCount}; totals may exceed this bounded page.`, { dimColor: true }))+ if (s.partial) {+ const pages = []+ if (s.threadOffset > 0) pages.push({ key: `managed-prev-${s.sessionId}`, label: 'Previous workers', onPress: () => { const spec = managedAction(s.sessionId, 'inspect', Math.max(0, s.threadOffset - 60)); if (spec) ask(spec) } })+ if (s.threadOffset + s.threads.length < s.threadCount && s.threadOffset + 60 <= 9999) pages.push({ key: `managed-next-${s.sessionId}`, label: 'Next workers', onPress: () => { const spec = managedAction(s.sessionId, 'inspect', s.threadOffset + 60); if (spec) ask(spec) } })+ rows.push(...flow(ctx, pages, `managed-pages-${s.sessionId}`))+ }+ if (s.blockedEventIds.length) rows.push(text(ctx, ` Pending decision IDs: ${s.blockedEventIds.slice(0, 4).join(', ')}. Inspect the current request before responding; no blanket approval control is offered.`, { color: THEME.warn }))+ rows.push(...flow(ctx, ['inspect', 'interrupt', 'terminate'].map(action => ({ key: `managed-${action}-${s.sessionId}`, label: `${action[0]!.toUpperCase()}${action.slice(1)}`, onPress: () => { const spec = managedAction(s.sessionId, action as 'inspect' | 'interrupt' | 'terminate'); if (spec) ask(spec) } })), 'managed-controls'))+ rows.push(text(ctx, ' Each action asks first and rechecks provider state and host policy at execution. Snapshot age never grants permission.', { dimColor: true }))+ return rows+}++export function managedBudgetRows(ctx: Ctx): RenderElement[] {+ const facts = ctx.state.snapshot?.managed+ if (!facts || facts.sessions.length === 0) return []+ return [rule(ctx, 'Managed cloud budgets', 'reported list cost; separate scope'),+ ...facts.sessions.map(s => kv(ctx, s.sessionId.slice(0, 16), `${budget(s)} · ${s.stopReason ?? s.status}`)),+ text(ctx, ' In-flight work can overshoot a cap. Unknown values are not zero; these sessions are not added to the local budget total.', { dimColor: true })]+}++export function managedApprovalRows(ctx: Ctx): RenderElement[] {+ const facts = ctx.state.snapshot?.managed+ if (!facts) return []+ const blocked = facts.sessions.filter(s => s.blockedEventIds.length > 0 || ['requires_action', 'budget_reached'].includes(s.stopReason ?? ''))+ if (!blocked.length) return []+ return [rule(ctx, 'Managed blockers', 'remote decisions require fresh inspection'), ...blocked.flatMap(s => [+ kv(ctx, s.sessionId.slice(0, 16), `${s.stopReason ?? 'pending decision'} · ${s.blockedEventIds.length} decision IDs${ctx.nowMs - s.updatedMs > MANAGED_STALE_MS || s.updatedMs > ctx.nowMs + 5000 ? ' · stale snapshot' : ''}`, THEME.warn),+ ...flow(ctx, [{ key: `managed-blocker-${s.sessionId}`, label: 'Inspect current request', onPress: () => { const spec = managedAction(s.sessionId, 'inspect'); if (spec) ctx.act.workflows.ask(spec) } }], `managed-blocker-row-${s.sessionId}`),+ ])]+}++export function managedLearningRows(ctx: Ctx): RenderElement[] {+ const facts = ctx.state.snapshot?.managedLearning+ if (!facts) return []+ const selected = facts.selected, evaluation = facts.evaluation+ return [rule(ctx, 'Managed workflow learning', 'advisory host reports; no automatic promotion'),+ kv(ctx, 'evidence', `${facts.verified} host-verified reported / ${facts.observations} observations · ${facts.quarantined} quarantined`),+ kv(ctx, 'separation', `${facts.training} training · ${facts.holdout} heldout; heldout outcomes do not train recommendations`),+ kv(ctx, 'suggestion', selected === null ? 'abstained or no recommendation recorded' : `${selected.id} · N=${selected.samples} · ${selected.successesPerDollar === null ? 'n/a' : selected.successesPerDollar.toFixed(2)} successes/$ · p95 ${selected.p95Ms === null ? 'n/a' : `${selected.p95Ms} ms`}`),+ ...(selected?.evidenceIds.length ? [kv(ctx, 'receipt IDs', selected.evidenceIds.map(h => h.slice(0, 12)).join(', '))] : []),+ kv(ctx, 'comparison', evaluation === null ? 'no heldout evaluation recorded' : `${evaluation.eligible ? 'eligible advisory result' : 'not eligible'} · ${evaluation.pairedResults} pairs · ${evaluation.delta === null ? 'n/a' : `${(evaluation.delta * 100).toFixed(1)}%`} efficiency change · no regression ${evaluation.noRegression ? 'reported' : 'not established'}`, THEME.info),+ text(ctx, ' Defaults remain unchanged. Summary files are display evidence, not verification authority.', { dimColor: true }),+ text(ctx, ' The runtime must revalidate signed receipts before routing.', { dimColor: true }),+ kv(ctx, 'updated', ago(facts.updatedMs, ctx.nowMs)),+ ]+}diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.tsindex 03f1396ab3..d764625c2e 100644--- a/plugins/ruflo-console/hooks/views/workflows.ts+++ b/plugins/ruflo-console/hooks/views/workflows.ts@@ -8,6 +8,7 @@ import { spawnAgent, stopAgent } from '../ops'import { ago, clip, col, kv, row, rule, text, THEME, type Ctx } from './common'import { flow, runTag } from './wf-layout'import { slotsFor } from './wf-slots'+import { managedRunRows } from './managed'/** What the workflows view asks of the controller: a confirm-gated ruflo verb, or to name a transcript's path. */export type WorkflowsHooks = { ask: (spec: ActionSpec) => void; show: (path: string) => void }@@ -56,7 +57,7 @@ function header(ctx: Ctx, run: WfRun, runs: readonly WfRun[], at: number): Rende/** Left cell: `❯ ✔ Build 4/4`, the cursor row bold, the run's current phase marked ❯. */function phaseCell(ctx: Ctx, phase: WfPhase, index: number, flags: { isHere: boolean; isCurrent: boolean; width: number }): RenderElement {- const { mark, color } = phaseMark(phase, ctx.nowMs)+ const { mark, color } = phase.agents.some(a => a.isUnverified) ? { mark: '○', color: THEME.info } : phaseMark(phase, ctx.nowMs)const count = `${phase.done}/${phase.total}`const title = clip(`${index + 1} ${phase.title}`, Math.max(4, flags.width - count.length - 6))@@ -78,7 +79,7 @@ function agentCell(ctx: Ctx, agent: WfAgent, isHere: boolean, width: number): Reconst label = clip(agent.label, Math.max(6, width - fixed - 1))return row(ctx, [- ctx.kit.Text({ ...(COLOR(agent.state) !== undefined && { color: COLOR(agent.state) as string }), children: `${isHere ? '▸' : ' '}${MARK(agent.state, ctx.nowMs)} ` }),+ ctx.kit.Text({ ...((agent.isUnverified ? THEME.info : COLOR(agent.state)) !== undefined && { color: agent.isUnverified ? THEME.info : COLOR(agent.state) as string }), children: `${isHere ? '▸' : ' '}${agent.isUnverified && agent.state === 'done' ? '○' : MARK(agent.state, ctx.nowMs)} ` }),ctx.kit.Text({ wrap: 'truncate-end', ...(isHere && { bold: true }), children: `${label.padEnd(Math.max(6, width - fixed))}` }),...(width >= 62 && model !== '' ? [ctx.kit.Text({ dimColor: true, children: model })] : []),...(width >= 74 && badge !== '' ? [ctx.kit.Text({ color: THEME.info, children: badge })] : []),@@ -140,13 +141,14 @@ export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi,const here = pick(ui, model.runs)if (here.run === null) {- rows.push(text(ctx, model.root === null ? 'No Claude Code config directory is known here, so no workflow runs can be read.' : `No workflow runs for this project under ${clip(model.root, Math.max(20, ctx.columns - 30))}, and no ruflo swarm yet.`, { color: THEME.warn }))+ rows.push(text(ctx, model.root === null ? 'No Claude Code config directory is known here, so no workflow runs can be read.' : `No workflow runs for this project under ${clip(model.root, Math.max(20, ctx.columns - 30))}, and no ruflo swarm or managed session yet.`, { color: THEME.warn }))rows.push(text(ctx, 'Claude Code writes a run folder when a Workflow script starts; ruflo agents appear once a swarm exists.', { dimColor: true }))return col(ctx, rows, 'workflows')}rows.push(...header(ctx, here.run, model.runs, here.ui.run))+ if (here.run.managed) rows.push(...managedRunRows(ctx, here.run, hooks.ask))const run = here.runconst wide = ctx.columns >= 56diff --git a/plugins/ruflo-console/hooks/wf-live.ts b/plugins/ruflo-console/hooks/wf-live.tsindex bf70ac7740..eb369ba5eb 100644--- a/plugins/ruflo-console/hooks/wf-live.ts+++ b/plugins/ruflo-console/hooks/wf-live.ts@@ -8,6 +8,7 @@import { cleanRun, cleanText } from './data/wf-clean'import { readWorkflowRuns, type WorkflowFs } from './data/workflows-read'import { allRuns, startOn } from './data/workflows-nav'+import { managedRuns } from './data/managed'import type { WfRun } from './data/workflows'import { plain } from './data/parse'import type { Host } from './host'@@ -41,9 +42,10 @@ export function runNotices(prev: ReadonlyMap<string, string> | null, next: readoexport function workflowsModelOf(state: State, nowMs: number): WorkflowsModel | null {const read = state.wf.read- if (read === null) return null+ if (read === null && !state.snapshot?.managed) return null+ if (read === null) return { runs: managedRuns(state.snapshot?.managed, nowMs), root: null, capBytes: 128000, skipped: 0, more: 0 }- return { runs: allRuns(read.runs, state.snapshot?.swarm ?? null, state.snapshot?.agents ?? [], nowMs), root: read.root, capBytes: read.capBytes, skipped: read.skipped, more: read.more }+ return { runs: allRuns([...read.runs, ...managedRuns(state.snapshot?.managed, nowMs)], state.snapshot?.swarm ?? null, state.snapshot?.agents ?? [], nowMs), root: read.root, capBytes: read.capBytes, skipped: read.skipped, more: read.more }}/**diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.shindex 9873fb7ad2..2871b7b5b6 100755--- a/plugins/ruflo-console/scripts/smoke.sh+++ b/plugins/ruflo-console/scripts/smoke.sh@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares ruflo-console 0.48.0"+step "1. plugin.json declares ruflo-console 0.49.0"grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \- && grep -q '"version": "0.48.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"+ && grep -q '"version": "0.49.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"step "2. hooks.json names exactly one module and no classic hook commands"grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \diff --git a/plugins/ruflo-console/tests/managed-palette.spec.ts b/plugins/ruflo-console/tests/managed-palette.spec.tsnew file mode 100644index 0000000000..ee0098fdd9--- /dev/null+++ b/plugins/ruflo-console/tests/managed-palette.spec.ts@@ -0,0 +1,95 @@+import { describe, expect, it, vi } from 'vitest'+import { parseManaged } from '../hooks/data/managed'+import type { Host } from '../hooks/host'+import { callTool, classOf, landingRefusal, type ModelToolDeps } from '../hooks/model-tools'+import { paletteEntries } from '../hooks/palette'+import { createRunner } from '../hooks/runner'+import { settingsOf } from '../hooks/settings'+import { newState } from '../hooks/state'++function setup(level: 'read' | 'write' | 'manage' | 'full' = 'full', confirm: 'ask' | 'auto' = 'ask') {+ const state = newState({})+ state.view = 'workflows'+ state.options.cli = 'ruflo'+ Object.assign(settingsOf(state).ai, { modelControl: level, modelConfirm: confirm })+ state.snapshot = { managed: parseManaged(JSON.stringify({ version: 1, updatedMs: Date.now(), sessions: ['sesn_a', 'sesn_b'].map(sessionId => ({+ sessionId, status: 'running', providerFinished: false, workersInspected: true, acceptancePassed: true, verification: 'verified',+ runs: [], threads: [], blockedEventIds: [], observedFailures: 0,+ })) })) } as any+ const run = vi.fn(async (_argv: readonly string[]) => ({ exitCode: 0, stdout: '{"success":true}', stderr: '' }))+ const host = { run, invalidate: () => undefined, after: () => ({ cancel: () => undefined }) } as unknown as Host+ const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined, landingRefusal: pending => landingRefusal(state, pending) })+ const deps = { state, control: { host, runner, actions: { workflows: { ask: () => undefined, show: () => undefined } } } } as unknown as ModelToolDeps+ const entries = () => paletteEntries(state, Date.now()).filter(entry => entry.group === 'managed')+ return { state, run, runner, deps, entries }+}++describe('managed session palette actions', () => {+ it('lists bounded exact session ids, with the selected run first, through console_state', async () => {+ const ctx = setup()+ ctx.state.wf.ui.run = 1+ expect(ctx.entries().map(entry => entry.id)).toEqual(['managed-inspect-sesn_b', 'managed-interrupt-sesn_b', 'managed-terminate-sesn_b', 'managed-inspect-sesn_a', 'managed-interrupt-sesn_a', 'managed-terminate-sesn_a'])+ expect(ctx.entries()[0]!.label).toContain('(selected)')+ const answer = JSON.parse(await callTool('console_state', { filter: 'managed' }, ctx.deps))+ expect(answer.entries.map((entry: { id: string }) => entry.id).filter((id: string) => id.startsWith('managed-'))).toEqual(ctx.entries().map(entry => entry.id))+ expect(ctx.run).not.toHaveBeenCalled()+ })++ it('never offers arbitrary or missing sessions and removes vanished targets', async () => {+ const ctx = setup()+ for (const id of ['managed-inspect', 'managed-inspect-sesn_c', 'managed-inspect-sesn_a;echo', 'managed-inspect-sesn_../../etc']) {+ expect(await callTool('console_run', { id, text: 'sesn_b' }, ctx.deps)).toContain('no palette entry')+ }+ ctx.state.snapshot!.managed!.sessions = []+ expect(ctx.entries()).toEqual([])+ expect(await callTool('console_run', { id: 'managed-inspect-sesn_a' }, ctx.deps)).toContain('no palette entry')+ expect(ctx.run).not.toHaveBeenCalled()+ })++ it.each(['inspect', 'interrupt', 'terminate'] as const)('queues %s through console_run and executes only its fixed confirmed target', async action => {+ const ctx = setup()+ expect(await callTool('console_run', { id: `managed-${action}-sesn_a`, text: 'sesn_b --approved' }, ctx.deps)).toContain('Waiting for the person')+ expect(ctx.run).not.toHaveBeenCalled()+ ctx.state.wf.ui.run = 1+ await ctx.runner.confirm(ctx.state.pending!.id)+ expect(ctx.run).toHaveBeenCalledTimes(1)+ const argv = ctx.run.mock.calls[0]![0]+ expect(argv.slice(0, 6)).toEqual(['ruflo', 'mcp', 'exec', '-t', 'managed_agent_control', '-p'])+ expect(JSON.parse(argv[6]!)).toEqual({ sessionId: 'sesn_a', action })+ })++ it.each([['inspect', 'write', 'network'], ['interrupt', 'manage', 'delete'], ['terminate', 'manage', 'delete']] as const)('denies %s below its existing permission class', async (action, level, kind) => {+ const ctx = setup(level)+ const entry = ctx.entries().find(entry => entry.id === `managed-${action}-sesn_a`)!+ expect(entry.run.kind).toBe('spec')+ if (entry.run.kind === 'spec') expect(classOf(entry.run.spec!)).toBe(kind)+ expect(await callTool('console_run', { id: entry.id }, ctx.deps)).toContain(`is a ${kind} action`)+ expect(ctx.state.pending).toBeNull()+ expect(ctx.run).not.toHaveBeenCalled()+ })++ it('rechecks current console permission at confirmation after a level change', async () => {+ const ctx = setup()+ await callTool('console_run', { id: 'managed-inspect-sesn_a' }, ctx.deps)+ Object.assign(settingsOf(ctx.state).ai, { modelControl: 'read' })+ await ctx.runner.confirm(ctx.state.pending!.id)+ expect(ctx.run).not.toHaveBeenCalled()+ expect(ctx.state.outcome?.detail).toContain('not run')+ })++ it('keeps destructive controls awaiting a person in auto mode', async () => {+ const ctx = setup('full', 'auto')+ expect(await callTool('console_run', { id: 'managed-terminate-sesn_a' }, ctx.deps)).toContain('Waiting for the person')+ expect(ctx.run).not.toHaveBeenCalled()+ })++ it('surfaces fresh backend policy refusal despite optimistic snapshot facts', async () => {+ const ctx = setup()+ ctx.run.mockResolvedValue({ exitCode: 0, stdout: '{"isError":true,"error":"fresh host policy denied"}', stderr: '' })+ await callTool('console_run', { id: 'managed-inspect-sesn_a' }, ctx.deps)+ await ctx.runner.confirm(ctx.state.pending!.id)+ expect(ctx.state.outcome?.ok).toBe(false)+ expect(ctx.run).toHaveBeenCalledTimes(1)+ expect(JSON.parse(ctx.run.mock.calls[0]![0][6]!)).toEqual({ sessionId: 'sesn_a', action: 'inspect' })+ })+})diff --git a/plugins/ruflo-console/tests/managed.spec.ts b/plugins/ruflo-console/tests/managed.spec.tsnew file mode 100644index 0000000000..09397187a9--- /dev/null+++ b/plugins/ruflo-console/tests/managed.spec.ts@@ -0,0 +1,150 @@+import { describe, expect, it, vi } from 'vitest'+import { performance } from 'node:perf_hooks'+import { MANAGED_PATH, LEARNING_PATH, managedRuns, parseManaged, parseManagedLearning, readManaged } from '../hooks/data/managed'+import { managedAction } from '../hooks/managed-actions'+import { workflowsModelOf } from '../hooks/wf-live'+import { workflowsView } from '../hooks/views/workflows'+import { managedApprovalRows, managedBudgetRows, managedLearningRows } from '../hooks/views/managed'+import { newState } from '../hooks/state'+import { newWfUi } from '../hooks/data/workflows-nav'+import { THEME, type Ctx, type Kit } from '../hooks/views/common'++const NOW = 1_000_000+const session = (extra = {}) => ({ sessionId: 'sesn_a', status: 'idle', stopReason: 'end_turn', budgetCents: 2500, listCostCents: 100,+ providerFinished: true, workersInspected: true, acceptancePassed: true, verification: 'verified',+ runs: [{ id: 'wrun_a', status: 'ended', result: 'completed' }], threads: [{ id: 'thread_a', runId: 'wrun_a', status: 'completed' }],+ blockedEventIds: [], observedFailures: 0, ...extra })+const snapshot = (sessions: unknown[] = [session()], extra = {}) => JSON.stringify({ version: 1, updatedMs: NOW, sessions, ...extra })+const tree = (node: unknown, out: any[] = []): any[] => {+ if (Array.isArray(node)) node.forEach(n => tree(n, out))+ else if (node && typeof node === 'object') { out.push(node); tree((node as any).props?.children, out) }+ return out+}+const textOf = (node: unknown) => tree(node).filter(n => n.kind === 'Text').map(n => n.props.children).join('\n')+const kit = Object.fromEntries(['Text', 'Box', 'Button'].map(kind => [kind, (props: any) => ({ kind, props })])) as unknown as Kit+function context(facts = parseManaged(snapshot())): Ctx {+ const state = newState({})+ state.snapshot = { managed: facts } as any+ return { kit, state, nowMs: NOW, columns: 100, pictures: new Map(), act: { workflows: { ask: vi.fn() } } as any }+}++describe('managed run state shown in the console', () => {+ // The console used to show anything that was not literally `running` as `finished`.+ it.each([+ ['rescheduling is still running', { status: 'rescheduling', stopReason: null, providerFinished: false }, 'running'],+ ['a budget stop is not finished', { status: 'idle', stopReason: 'budget_reached', providerFinished: false }, 'active'],+ ['waiting on a required action is not finished', { status: 'idle', stopReason: 'requires_action', providerFinished: false }, 'active'],+ ['an open tool request is not finished', { blockedEventIds: ['evt_a'] }, 'active'],+ ['a completed turn is finished', {}, 'finished'],+ ])('%s', (_name, extra, state) => {+ const facts = parseManaged(snapshot([session(extra)]))!+ expect(managedRuns(facts, NOW)[0]!.state).toBe(state)+ })+})++describe('managed local snapshot contract', () => {+ it('never treats snapshot verification booleans as authority', () => {+ const facts = parseManaged(snapshot())!+ expect(facts.sessions[0]).toMatchObject({ providerFinished: true, workersInspected: false, acceptancePassed: false, verification: 'unverified' })+ })+ it.each([null, '{}', snapshot([], { version: 2 }), snapshot([session({ sessionId: '../secret' })]), snapshot([session(), session()])])('refuses malformed input %s', value => {+ expect(parseManaged(value)).toBeNull()+ })+ it('deduplicates 1000 workers and keeps a bounded visible page', () => {+ const threads = Array.from({ length: 1000 }, (_, i) => ({ id: `t_${i}`, runId: 'wrun_a', status: i % 2 ? 'running' : 'completed' }))+ const facts = parseManaged(snapshot([session({ status: 'running', threads: [...threads, ...threads.slice(0, 10)], threadCount: 1000 })]))!+ expect(facts.sessions[0]).toMatchObject({ threadCount: 1000, partial: true, threadCounts: { running: 500, ended: 500 } })+ expect(facts.sessions[0]!.threads).toHaveLength(60)+ expect(managedRuns(facts, NOW)[0]).toMatchObject({ kind: 'managed', total: 1000, running: 500, done: 500 })+ })+ it('preserves provider phase names and worker association', () => {+ const facts = parseManaged(snapshot([session({ runs: [{ id: 'wrun_a', status: 'running', phases: [{ id: 'phase_a', name: 'Independent reproduction', status: 'running' }] }], threads: [{ id: 'thread_a', runId: 'wrun_a', phaseId: 'phase_a', status: 'running' }] })]))!+ const run = managedRuns(facts, NOW)[0]!+ expect(run.phases[0]!.title).toContain('Independent reproduction')+ expect(run.phases[0]!.agents[0]!.id).toBe('thread_a')+ })+ it('marks stale snapshots without manufacturing completion', () => {+ const run = managedRuns(parseManaged(snapshot()), NOW + 31_000)[0]!+ expect(run).toMatchObject({ state: 'stalled', isStale: true })+ })+ it('does not freshen another session when the snapshot is refreshed', () => {+ const facts = parseManaged(snapshot([session({ sessionId: 'sesn_old', updatedMs: NOW - 31_000 }), session({ sessionId: 'sesn_new', updatedMs: NOW })]))!+ const runs = managedRuns(facts, NOW)+ expect(runs[0]).toMatchObject({ id: 'sesn_old', isStale: true, state: 'stalled', updatedMs: NOW - 31_000 })+ expect(runs[1]).toMatchObject({ id: 'sesn_new', isStale: false, updatedMs: NOW })+ })+ it('preserves unknown cost instead of turning it into zero', () => {+ expect(parseManaged(snapshot([session({ listCostCents: undefined })]))!.sessions[0]!.listCostCents).toBeNull()+ })+ it('rejects negative and impossible aggregate counts', () => {+ expect(parseManaged(snapshot([session({ threadCount: 1, threadCounts: { running: 2, ended: 0, failed: 0, idle: 0 } })]))).toBeNull()+ })+ it('reuses unchanged parsed snapshot and summary without rereading file contents', async () => {+ const files = new Map([[`/work/${MANAGED_PATH}`, snapshot()], [`/work/${LEARNING_PATH}`, '{}']])+ const read = vi.fn(async (p: string) => files.get(p)!)+ const fs = { read, stat: async (p: string) => ({ kind: 'file', size: files.get(p)!.length, mtimeMs: 1 }), list: async () => [] }+ const cache = new Map()+ const a = await readManaged(fs, cache, '/work'), b = await readManaged(fs, cache, '/work')+ expect(read).toHaveBeenCalledTimes(2)+ expect(a.managed).toBe(b.managed)+ })+})++describe('first class managed views and safe controls', () => {+ it('renders managed runs before native workflow discovery and never gives a green correctness badge', () => {+ const ctx = context(), model = workflowsModelOf(ctx.state, NOW)!+ expect(model.runs[0]!.kind).toBe('managed')+ const result = workflowsView(ctx, model, newWfUi(), { ask: vi.fn(), show: vi.fn() })+ expect(textOf(result)).toContain('correctness remains unverified')+ expect(textOf(result)).toContain('workers')+ expect(tree(result).filter(n => n.kind === 'Text' && n.props.color === THEME.ok)).toHaveLength(0)+ expect(tree(result).filter(n => n.kind === 'Button').map(n => n.props.label)).toEqual(expect.arrayContaining(['Inspect', 'Interrupt', 'Terminate']))+ })+ it('renders measured budgets, pending decisions and advisory evidence separately', () => {+ const ctx = context(parseManaged(snapshot([session({ stopReason: 'requires_action', blockedEventIds: ['sevt_a'] })])))+ expect(textOf(managedBudgetRows(ctx))).toContain('$1.00 reported / $25.00 budget')+ expect(textOf(managedApprovalRows(ctx))).toContain('requires_action')+ ctx.state.snapshot!.managedLearning = parseManagedLearning(JSON.stringify({ version: 1, updatedMs: NOW, advisory: true, defaultsChanged: false, observations: 8, verified: 6, quarantined: 2, training: 3, holdout: 3, lastRecommendation: { selected: { strategy: { id: 'small' }, samples: 3, successesPerDollar: 2, p95Ms: 10, evidenceIds: ['a'.repeat(64)] } } }))+ const lines = textOf(managedLearningRows(ctx))+ expect(lines).toContain('small')+ expect(lines).toContain('Defaults remain unchanged')+ expect(lines).toContain('aaaaaaaaaaaa')+ })+ it('builds fixed argv, asks first and never passes snapshot approval fields', () => {+ for (const action of ['inspect', 'interrupt', 'terminate'] as const) {+ const spec = managedAction('sesn_a', action)!+ expect(spec.isReadOnly).not.toBe(true)+ expect(spec.args.slice(0, 5)).toEqual(['mcp', 'exec', '-t', 'managed_agent_control', '-p'])+ expect(JSON.parse(spec.args[5]!)).toEqual({ sessionId: 'sesn_a', action })+ expect(spec.expect).toContain('fresh provider')+ }+ expect(managedAction('sesn_a;rm', 'terminate')).toBeNull()+ })+ it('pages worker inspection through fixed confirm-gated controls', () => {+ const ctx = context(parseManaged(snapshot([session({ threads: Array.from({ length: 60 }, (_, i) => ({ id: `t_${i}`, runId: 'wrun_a', status: 'running' })), threadCount: 1000, threadOffset: 60 })])))+ const ask = vi.fn(), model = workflowsModelOf(ctx.state, NOW)!+ const view = workflowsView(ctx, model, newWfUi(), { ask, show: vi.fn() })+ const next = tree(view).find(n => n.kind === 'Button' && n.props.label === 'Next workers')+ next.props.onPress()+ expect(JSON.parse(ask.mock.calls[0][0].args[5])).toEqual({ sessionId: 'sesn_a', action: 'inspect', threadOffset: 120 })+ expect(managedAction('sesn_a', 'terminate', 60)).toBeNull()+ expect(managedAction('sesn_a', 'inspect', -1)).toBeNull()+ })+ it('does not call a provider while rendering a hidden or inactive snapshot', () => {+ const ctx = context(), ask = vi.fn()+ workflowsView(ctx, workflowsModelOf(ctx.state, NOW), newWfUi(), { ask, show: vi.fn() })+ managedBudgetRows(ctx); managedApprovalRows(ctx); managedLearningRows(ctx)+ expect(ask).not.toHaveBeenCalled()+ })+ it('keeps warm bounded managed render below 16ms median on the local fixture', () => {+ const threads = Array.from({ length: 1000 }, (_, i) => ({ id: `t_${i}`, runId: 'wrun_a', status: 'running' }))+ const ctx = context(parseManaged(snapshot([session({ threads, threadCount: 1000, status: 'running' })])))+ const model = workflowsModelOf(ctx.state, NOW)!, samples: number[] = []+ for (let i = 0; i < 30; i++) {+ const start = performance.now()+ workflowsView(ctx, model, newWfUi(), { ask: () => {}, show: () => {} })+ samples.push(performance.now() - start)+ }+ expect(samples.sort((a, b) => a - b)[15]).toBeLessThan(16)+ })+})diff --git a/plugins/ruflo-workflows/.claude-plugin/plugin.json b/plugins/ruflo-workflows/.claude-plugin/plugin.jsonindex 24e338e60c..4c357ad54c 100644--- a/plugins/ruflo-workflows/.claude-plugin/plugin.json+++ b/plugins/ruflo-workflows/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-workflows",- "description": "Workflow automation across two surfaces: the 10 workflow_* MCP tools (create/run/execute/status/list/pause/resume/cancel/delete/template) with full state-machine lifecycle (created → running ↔ paused → completed/cancelled), and native Claude Code Workflow JS orchestration (.claude/workflows/*.js — agent/parallel/pipeline/phase fan-out). Includes GAIA benchmark component for Princeton HAL leaderboard submissions.",- "version": "0.6.7",+ "description": "Persisted workflows, native orchestration and discovery of the optional managed cloud runtime.",+ "version": "0.7.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"diff --git a/plugins/ruflo-workflows/CHANGELOG.md b/plugins/ruflo-workflows/CHANGELOG.mdindex 98f8bab3a4..63732f4c8e 100644--- a/plugins/ruflo-workflows/CHANGELOG.md+++ b/plugins/ruflo-workflows/CHANGELOG.md@@ -2,6 +2,10 @@Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-workflows`.+## 0.7.0 — 2026-10-24+- feat: managed workflow capability discovery, bounded local mod policy and console policy metadata+- fix: ship the managed workflow integration through a versioned plugin update+## 0.6.7 — 2026-10-12- fix: the shared text screen now catches `.env` and e-mailed credentials, no longer flags a model's token talk (`--max-tokens`, `/oauth/token`, "token usage"), and no longer flags values that only name where a secret lives (`./service-account.json`, `--set-secrets=NAME=NAME:latest`); every rule stays linear (#4094, thanks @proffesor-for-testing)diff --git a/plugins/ruflo-workflows/README.md b/plugins/ruflo-workflows/README.mdindex f6d8732a63..18a35888c9 100644--- a/plugins/ruflo-workflows/README.md+++ b/plugins/ruflo-workflows/README.md@@ -157,3 +157,17 @@ This plugin also loads as a function-hook mod (ADR-445 pattern, `hooks/hooks.jso- **Option.** `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.Test it: `claude plugin validate plugins/ruflo-workflows`, `claude plugin test plugins/ruflo-workflows`, `bash plugins/ruflo-workflows/scripts/smoke.sh`.++## Optional cloud execution++For Anthropic hosted dynamic workflows, use the existing `ruflo-agent`+`managed_agent_*` adapter. Its opt-in configuration and safety contract are+[documented here](../ruflo-agent/README.md#dynamic-workflows). This is a third+execution surface alongside persisted MCP workflows and local Claude Code JS+workflows. It does not change `workflow_run` scheduling or turn a native+workflow script into a Managed Agents workflow program.++`/wf-mod managed` now discovers the installed cloud capability tool from the+current registry. Missing tools and failed discovery are reported separately.+Use `/managed-workflow` from ruflo-agent to execute bounded remote work. These+local commands do not establish provider access or grant execution permission.diff --git a/plugins/ruflo-workflows/hooks/command.ts b/plugins/ruflo-workflows/hooks/command.tsindex 6aeffe6844..65e1cff705 100644--- a/plugins/ruflo-workflows/hooks/command.ts+++ b/plugins/ruflo-workflows/hooks/command.ts@@ -5,7 +5,7 @@ import type { Stats } from './status'/** `/wf-mod` is answered locally and takes no model turn. */export type CommandDeps = { readonly opts: ModOptions; readonly stats: Stats; readonly tools: () => Promise<readonly string[]> }-const HELP = ['/wf-mod status', '/wf-mod scan <text>', '/wf-mod lifecycle'].join('\n')+const HELP = ['/wf-mod status', '/wf-mod scan <text>', '/wf-mod lifecycle', '/wf-mod managed'].join('\n')export async function answer(args: string, deps: CommandDeps): Promise<string> {const [verb = '', ...rest] = args.trim().split(/\s+/)@@ -19,6 +19,13 @@ export async function answer(args: string, deps: CommandDeps): Promise<string> {return [`guard ${opts.guard ? 'on' : 'off'} · checked ${stats.checked} · blocked ${stats.blocked}`, seen === '' ? 'no workflow calls this session' : seen].join('\n')}+ if (verb === 'managed') {+ try {+ const names = (await deps.tools()).filter(t => t === 'managed_agent_capabilities' || t.endsWith('__managed_agent_capabilities'))+ return names.length ? `Managed adapter registered: ${names.map(n => n.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 160)).slice(0, 8).join(', ')}. Inspect that tool and /agent-mod capabilities before creation. Use persisted workflow_* for approval gates; managed workflows are remote execution with independently verified outputs. Registration does not establish authorization or beta access.` : 'Managed adapter not registered. Install or update ruflo-core and ruflo-agent. Use local workflow_* or native Workflow for current work.'+ } catch { return 'Managed tool discovery unavailable; registration and readiness are unknown.' }+ }+if (verb === 'scan') {if (arg === '') return 'usage: /wf-mod scan <text>'const found = secretsIn(arg)diff --git a/plugins/ruflo-workflows/hooks/register.ts b/plugins/ruflo-workflows/hooks/register.tsindex d165680fb8..ed48e59d20 100644--- a/plugins/ruflo-workflows/hooks/register.ts+++ b/plugins/ruflo-workflows/hooks/register.ts@@ -29,7 +29,7 @@ export const register: Register = (on, options) => {const result = await next(e)s.root = (await $.session.root()) as string | undefinedtry {- await $.command.register({ name: 'wf-mod', description: 'Workflows mod: status, scan <text>, lifecycle' })+ await $.command.register({ name: 'wf-mod', description: 'Workflows mod: status, scan <text>, lifecycle, managed' })} catch {/* a name taken by another plugin must not stop the mod */}diff --git a/plugins/ruflo-workflows/scripts/smoke.sh b/plugins/ruflo-workflows/scripts/smoke.shindex 6408e3b88b..9d9e1f0d71 100755--- a/plugins/ruflo-workflows/scripts/smoke.sh+++ b/plugins/ruflo-workflows/scripts/smoke.sh@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares 0.6.7 with lifecycle keywords"+step "1. plugin.json declares 0.7.0 with lifecycle keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.6.7" ]]; then bad "expected 0.6.7, got '$v'"; else+if [[ "$v" != "0.7.0" ]]; then bad "expected 0.7.0, got '$v'"; elsemiss=""for k in mcp workflow-templates pause-resume lifecycle; dogrep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjsindex 93b9198be9..ceda074879 100644--- a/scripts/audit-env-var-precedence.mjs+++ b/scripts/audit-env-var-precedence.mjs@@ -57,6 +57,7 @@ const KNOWN_ESCAPE_HATCHES = new Set(['RUFLO_ADMIN_TOKEN', // credential: the x.ruv.io gateway's OWN admin token, read by plugins/ruflo-x-gateway. Env-only by design — a secret must never be a CLI flag (shell history / process lists), and the gateway is a service with no typed command surface at all.'RUFLO_SERAPHINA_DAILY_CAP', // gateway spend guard (#3275): shared daily Seraphina budget. Read by a long-running service, not a typed command — there is no invocation to attach a flag to.'RUFLO_SERAPHINA_IP_HOURLY_CAP',// gateway spend guard (#3275): per-client hourly Seraphina budget. Same service-only reasoning.+ 'RUFLO_MANAGED_AGENTS_BASE_URL',// Trust boundary: the Managed Agents adapter sends the API key to this origin, so it is operator config only. MCP/CLI arguments cannot select another host; apiBase() accepts a bare HTTPS origin (no credentials, path, query or fragment) and every request uses redirect:'error'.'RUFLO_X_GATEWAY_URL', // Trust boundary: gateway reads/admin writes pin destinations to server config; MCP/CLI arguments cannot select another host.'SERAPHINA_METALLM_URL', // Trust boundary: credential-bearing Meta-LLM requests pin destinations to server config.'RUFLO_X_ADMIN_TOKEN', // credential: gateway admin token for x.ruv.io gateway-identity writes (x_federation_publish/invite_mint/admit). Env-only by design — a secret must never be a CLI flag (shell history / process lists). Gateway destination is trusted server config; --gateway/tool arguments must match it.diff --git a/scripts/bench-managed-cycle.mts b/scripts/bench-managed-cycle.mtsnew file mode 100644index 0000000000..78d342973b--- /dev/null+++ b/scripts/bench-managed-cycle.mts@@ -0,0 +1,36 @@+/** Same signed rows and durable semantics: legacy individual writes versus atomic cycle admission. */+import assert from 'node:assert/strict';+import { generateKeyPairSync, sign, createHash } from 'node:crypto';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { canonical, digest, observationOf } from '../v3/@claude-flow/cli/src/services/managed-learning.js';+import { learningStatus, recordLearning, recordLearningBatch } from '../v3/@claude-flow/cli/src/services/managed-learning-store.js';++const pair = generateKeyPairSync('ed25519'), key = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const rows = Array.from({ length: 18 }, (_, i) => {+ const observation = observationOf({ v: 1, attemptId: digest(`attempt-${i}`), taskHash: digest(`task-${i}`), sourceHash: digest('source'), artifactHash: digest('artifact'), policyHash: digest('policy'), corpusHash: digest('train'), evaluatorHash: digest('evaluator'), taskType: 'implementation', split: 'train', trial: 0,+ strategy: { id: 'fixture', model: 'no-model', workers: 1, template: 'bench' }, budgetCents: 100, costCents: 1, durationMs: 1,+ checks: { acceptance: true, safety: true, replay: true, adversarial: true, drift: 0, driftThreshold: .05, rollbackRate: 0 } });+ return { observation, signature: sign(null, Buffer.from(canonical(observation)), pair.privateKey).toString('base64') };+});+const sequential: number[] = [], atomic: number[] = [];+for (let round = 0; round < 7; round++) {+ const root = mkdtempSync(join(tmpdir(), 'managed-cycle-bench-'));+ try {+ const a = join(root, 'sequential'), b = join(root, 'atomic');+ const { mkdirSync } = await import('node:fs'); mkdirSync(a); mkdirSync(b);+ let at = performance.now(); for (const e of rows) recordLearning(a, e, key); sequential.push(performance.now() - at);+ at = performance.now(); recordLearningBatch(b, rows, key); atomic.push(performance.now() - at);+ assert.equal(learningStatus(a, key).verified, 18); assert.equal(learningStatus(b, key).verified, 18);+ const records = (path: string) => JSON.parse(readFileSync(join(path, '.claude-flow/managed-learning/state.json'), 'utf8')).records;+ assert.equal(digest(records(a)), digest(records(b)), 'Both paths must persist identical evidence');+ } finally { rmSync(root, { recursive: true, force: true }); }+}+const median = (v: number[]) => [...v].sort((a, b) => a - b)[Math.floor(v.length / 2)]!;+const source = 'v3/@claude-flow/cli/src/services/managed-learning-store.ts';+console.log(JSON.stringify({ kind: 'local durable-admission CPU benchmark', node: process.version, rounds: 7, signedRows: 18,+ baseline: '18 recordLearning transactions', candidate: 'one recordLearningBatch transaction', equivalentEvidence: true,+ sequentialMedianMs: median(sequential), atomicMedianMs: median(atomic), speedup: median(sequential) / median(atomic),+ admissionTransactions: { baseline: 18, candidate: 1 }, sourceSha256: createHash('sha256').update(readFileSync(source)).digest('hex'),+ limitations: 'Synthetic metadata, same-machine temporary filesystem and seven runs. No provider task quality, native backend speed, billing savings or deployment promotion is inferred.' }, null, 2));diff --git a/scripts/bench-managed-integration.mjs b/scripts/bench-managed-integration.mjsnew file mode 100644index 0000000000..3004595bc3--- /dev/null+++ b/scripts/bench-managed-integration.mjs@@ -0,0 +1,43 @@+/** CPU-only collector/learning benchmark. Pass the directory compiled by tsc. */+import { pathToFileURL } from 'node:url';+import { resolve, join } from 'node:path';+import { performance } from 'node:perf_hooks';+import { createHash, generateKeyPairSync, sign } from 'node:crypto';+import { readFileSync } from 'node:fs';+const build = resolve(process.argv[2] ?? '/tmp/managed-integration-build');+const { ManagedRunCollector } = await import(pathToFileURL(join(build, 'managed-run-collector.js')));+const { canonical, digest, observationOf, recommend, trustedEvidence } = await import(pathToFileURL(join(build, 'managed-learning.js')));+const event = (id, type, rest = {}) => ({ id, type, processed_at: '2026-10-24T12:00:00Z', ...rest });+const events = [event('run', 'workflow_run.created', { workflow_run_id: 'wrun_a', phases: [] })];+for (let i = 0; i < 1000; i++) {+ const s = { workflow_run_id: 'wrun_a', session_thread_id: `thread_${i}` };+ events.push(event(`c${i}`, 'session.thread_created', s), event(`r${i}`, 'session.thread_status_running', s), event(`e${i}`, 'session.thread_status_terminated', s));+}+events.push(event('end', 'workflow_run.status_ended', { workflow_run_id: 'wrun_a', result: { type: 'completed' } }), event('idle', 'session.status_idle', { stop_reason: { type: 'end_turn' } }));+let reads = 0;+const collector = new ManagedRunCollector();+const transport = { readEvents: async () => { reads++; return [...events, ...events]; }, readSession: async () => { reads++; return { status: 'idle' }; } };+const start = performance.now();+const [one, two] = await Promise.all([collector.refresh('sesn_bench', transport), collector.refresh('sesn_bench', transport)]);+const collectionMs = performance.now() - start;+if (reads !== 2 || one.snapshot.threadCount !== 1000 || two.snapshot.verification !== 'unverified') throw Error('Collector invariant failed');+const pages = [];+for (let i = 0; i < 100; i++) { const at = performance.now(); collector.page('sesn_bench', (i % 16) * 60); pages.push(performance.now() - at); }+const before = reads;+for (let i = 0; i < 1000; i++) collector.snapshots();+if (reads !== before) throw Error('Inactive traffic');+const pair = generateKeyPairSync('ed25519'), key = pair.publicKey.export({ format: 'pem', type: 'spki' }).toString();+const scope = { taskType: 'code-review', policyHash: digest('policy'), evaluatorHash: digest('evaluator') };+const rows = [];+for (const id of ['baseline', 'candidate']) for (let i = 0; i < 30; i++) {+ const o = observationOf({ v: 1, attemptId: digest(`${id}-${i}`), taskHash: digest(`train-${i}`), sourceHash: digest('source'), artifactHash: digest('artifact'), corpusHash: digest('train'), ...scope, split: 'train', trial: 0,+ strategy: { id, model: 'claude-fixture', workers: 1, template: 'review' }, budgetCents: 250, costCents: id === 'candidate' ? 50 : 100, durationMs: 100,+ checks: { acceptance: true, safety: true, replay: true, adversarial: true, drift: 0, driftThreshold: .05, rollbackRate: 0 } });+ rows.push({ observation: o, signature: sign(null, Buffer.from(canonical(o)), pair.privateKey).toString('base64') });+}+const attestStart = performance.now(), trusted = trustedEvidence(rows, key), signatureVerificationMs = performance.now() - attestStart;+const samples = [];+for (let i = 0; i < 100; i++) { const at = performance.now(); const result = recommend(trusted, scope); if (result.selected?.strategy.id !== 'candidate') throw Error('Recommendation invariant'); samples.push(performance.now() - at); }+const median = xs => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];+const sourceHashes = Object.fromEntries(['managed-run-collector.ts', 'managed-learning.ts', 'managed-run-store.ts', 'managed-learning-store.ts'].map(f => [f, createHash('sha256').update(readFileSync(`v3/@claude-flow/cli/src/services/${f}`)).digest('hex')]));+console.log(JSON.stringify({ kind: 'synthetic CPU and contract benchmark', node: process.version, sourceHashes, workers: 1000, replayedEvents: events.length * 2, uniqueEvents: one.events.length, eventReads: 1, sessionReads: 1, inactiveReads: reads - before, collectionMs, workerPageMedianMs: median(pages), signedTrainingRows: trusted.length, signatureVerificationMs, recommendationMedianMs: median(samples), syntheticSelected: 'candidate', limitations: 'Fixture costs and outcomes are synthetic. No live provider quality, dollar savings, native vector backend or GPU/UI performance is measured. Warm console rendering is separately covered by view tests.' }, null, 2));diff --git a/scripts/bench-managed-workflows.mjs b/scripts/bench-managed-workflows.mjsnew file mode 100644index 0000000000..b3f0a9ec03--- /dev/null+++ b/scripts/bench-managed-workflows.mjs@@ -0,0 +1,56 @@+/** Deterministic event-processing benchmark, not a model-quality benchmark.+ * Node >=22.18: node scripts/bench-managed-workflows.mjs+ */+import { performance } from 'node:perf_hooks';+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { ManagedProgress } from '../v3/@claude-flow/cli/src/services/managed-workflows.ts';++const baselineCommit = '973d0ab497c9138d7bee1dc3c7a4d3985e37bf9e';+const baselinePath = 'v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts';+const baselineSource = execFileSync('git', ['show', `${baselineCommit}:${baselinePath}`], { encoding: 'utf8' });+// Exercise the exact original summarizer from the frozen source, compiled by+// Node's strip-types, rather than substituting a slower baseline algorithm.+const { stripTypeScriptTypes } = await import('node:module');+const original = baselineSource.slice(baselineSource.indexOf('function summarizeEvents('), baselineSource.indexOf('async function fetchSessionEvents('));+const summarize = new Function(`${stripTypeScriptTypes(original)}; return summarizeEvents;`)();+const hash = value => createHash('sha256').update(value).digest('hex');+const candidateSource = readFileSync('v3/@claude-flow/cli/src/services/managed-workflows.ts');+const events = Array.from({ length: 5000 }, (_, i) => ({+ id: `e${i}`, type: 'agent.message', processed_at: new Date(1792843200000 + i).toISOString(),+ content: [{ type: 'text', text: 'bounded result\n' }],+}));+events.push({ id: 'idle', type: 'session.status_idle', processed_at: '2026-10-24T13:00:00Z', stop_reason: { type: 'end_turn' } });++function run(mode) {+ const p = new ManagedProgress(); let result;+ const start = performance.now();+ for (let n = 100; n < events.length + 100; n += 100) {+ result = mode === 'baseline' ? summarize(events.slice(0, n)) : (p.accept(events.slice(n - 100, n)), p.snapshot());+ }+ return { ms: performance.now() - start, result };+}+for (let i = 0; i < 3; i++) { run('baseline'); run('incremental'); }+const baseline = [], candidate = [];+for (let i = 0; i < 9; i++) {+ // Alternate order to reduce systematic warmup bias.+ const order = i % 2 ? ['baseline', 'incremental'] : ['incremental', 'baseline'];+ for (const mode of order) {+ const r = run(mode); (mode === 'baseline' ? baseline : candidate).push(r.ms);+ if (r.result.assistantText !== events.slice(0, -1).map(e => e.content[0].text).join('')) throw new Error('Output mismatch');+ }+}+const median = xs => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];+const polls = Math.ceil(events.length / 100);+const baselineVisits = Array.from({ length: polls }, (_, i) => Math.min(events.length, (i + 1) * 100)).reduce((a, b) => a + b, 0);+console.log(JSON.stringify({+ kind: 'synthetic event processing only', node: process.version, baselineCommit,+ baselineSha256: hash(baselineSource), candidateSha256: hash(candidateSource),+ events: events.length, polls, repeats: 9,+ baselineMedianMs: median(baseline), candidateMedianMs: median(candidate),+ latencyRatio: median(baseline) / median(candidate),+ baselineEventVisits: baselineVisits, incrementalEventVisits: events.length,+ eventVisitReduction: 1 - events.length / baselineVisits,+ limitations: 'No provider latency, token savings, dollar savings or bug-finding improvement measured. Snapshot output assembly is included in both timings.',+}, null, 2));diff --git a/scripts/e2e-managed-loop.mts b/scripts/e2e-managed-loop.mtsnew file mode 100644index 0000000000..1106aa7f75--- /dev/null+++ b/scripts/e2e-managed-loop.mts@@ -0,0 +1,135 @@+/** Real verifier subprocess + real ledger services; costs/workloads are synthetic fixtures. */+import assert from 'node:assert/strict';+import { generateKeyPairSync } from 'node:crypto';+import { chmodSync, copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawnSync } from 'node:child_process';+import { digest, isVerified, manifestOf } from '../v3/@claude-flow/cli/src/services/managed-learning.js';+import { evaluateLearning, learningStatus, recordLearning, recommendLearning } from '../v3/@claude-flow/cli/src/services/managed-learning-store.js';+import { cycleLearning } from '../v3/@claude-flow/cli/src/services/managed-learning-loop.js';+import { treeHash, type HostManifest } from './managed-outcome-verifier.mjs';++const root = mkdtempSync(join(tmpdir(), 'managed-verifier-e2e-'));+const keys = mkdtempSync(join(tmpdir(), 'managed-verifier-keys-'));+const cycleRoot = mkdtempSync(join(tmpdir(), 'managed-verifier-cycle-'));+const deniedRoot = mkdtempSync(join(tmpdir(), 'managed-verifier-denied-'));+chmodSync(root, 0o700); chmodSync(keys, 0o700);+const pair = generateKeyPairSync('ed25519');+const publicKey = pair.publicKey.export({ format: 'pem', type: 'spki' }).toString();+const privatePath = join(keys, 'verifier.pem');+writeFileSync(privatePath, pair.privateKey.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 });+// Hosted tool-cache executables can be group-writable. Keep the verifier's+// executable policy intact by staging an owner-only fixture binary.+const fixtureNode = join(keys, 'node-fixture');+copyFileSync(process.execPath, fixtureNode); chmodSync(fixtureNode, 0o700);+const verifier = join(dirname(fileURLToPath(import.meta.url)), 'managed-outcome-verifier.mjs');+let assertions = 0;+const check = (condition: unknown, message: string) => { assert.ok(condition, message); assertions++; };+const json = (path: string, value: unknown) => writeFileSync(path, JSON.stringify(value), { mode: 0o600 });+const fixtureSource = `const fs = require('node:fs'), assert = require('node:assert/strict');+const artifact = JSON.parse(fs.readFileSync('artifact.json', 'utf8'));+const task = JSON.parse(fs.readFileSync('task.json', 'utf8'));+const solve = x => { if (!Number.isInteger(x) || x < 0 || x > 100) throw Error('invalid'); return x * 2; };+const kind = process.argv[2];+if (kind === 'acceptance') { if (artifact.strategy === 'baseline') Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000); assert.equal(artifact.output, task.expected); }+else if (kind === 'safety') { assert.deepEqual(Object.keys(artifact).sort(), ['output','strategy','x']); assert.ok(Number.isSafeInteger(artifact.output)); assert.equal(process.env.RUFLO_MANAGED_VERIFIER_PRIVATE_KEY_FILE, undefined); }+else if (kind === 'replay') { assert.equal(solve(artifact.x), solve(artifact.x)); assert.equal(solve(artifact.x), artifact.output); }+else if (kind === 'adversarial') { for (const x of ['injection', -1, 101, null]) assert.throws(() => solve(x)); }+else if (kind === 'metrics') { const samples = [1,2,3], failed = samples.filter(x => solve(x) !== x*2).length; console.log(JSON.stringify({ drift: failed/samples.length, driftThreshold: .05, rollbackRate: failed/samples.length })); }+else if (kind === 'slow') setTimeout(() => {}, 10000);+else if (kind === 'mutate') fs.appendFileSync('check.cjs', '\\n// changed');+else if (kind === 'private-failure') { console.error('private-child-diagnostic-marker'); process.exitCode = 1; }+else throw Error('unknown check');+`;+writeFileSync(join(root, 'check.cjs'), fixtureSource, { mode: 0o600 });+json(join(root, 'policy.json'), { v: 1, policy: 'bounded-fixture-tests', release: false });+json(join(root, 'evaluator.json'), { v: 1, measures: 'functional fixture checks, not universal safety or live provider performance' });+const heldTasks = [{ id: 'held-one', x: 5, expected: 10 }, { id: 'held-two', x: 7, expected: 14 }];+const manifest = manifestOf({ taskHashes: heldTasks.map(digest), trials: [0, 1, 2] });+json(join(root, 'corpus.json'), manifest);+const command = (kind: string) => ({ argv: [fixtureNode, join(root, 'check.cjs'), kind], cwd: '.', timeoutMs: 3000 });+let lastManifest: HostManifest;+function prepare(task: { id: string; x: number; expected: number }, strategyId: string, split: 'train' | 'holdout', trial: number): HostManifest {+ json(join(root, 'task.json'), task);+ json(join(root, 'artifact.json'), { strategy: strategyId, x: task.x, output: task.expected });+ const strategy = { id: strategyId, model: 'fixture-no-provider', workers: strategyId === 'baseline' ? 1 : 2, template: 'functional-fixture' };+ const sourceHash = treeHash(root, ['check.cjs']), artifactHash = treeHash(root, ['artifact.json']);+ json(join(root, 'cost.json'), { v: 1, origin: 'synthetic-fixture', amountCents: strategyId === 'baseline' ? 100 : 50, taskHash: digest(task), sourceHash, artifactHash, strategyHash: digest(strategy), receiptId: digest({ task, strategyId, split, trial }) });+ lastManifest = { v: 1, root, sourceFiles: ['check.cjs'], artifactFiles: ['artifact.json'], taskSpec: 'task.json', policySpec: 'policy.json', corpusSpec: 'corpus.json', evaluatorSpec: 'evaluator.json', costReceipt: 'cost.json', taskType: 'code-review', split, trial, strategy, budgetCents: 250,+ checks: { acceptance: [command('acceptance')], safety: [command('safety')], replay: [command('replay')], adversarial: [command('adversarial')] }, metrics: command('metrics') };+ json(join(root, 'host-manifest.json'), lastManifest);+ return lastManifest;+}+function invoke(expectSuccess = true) {+ const result = spawnSync(process.execPath, [verifier, join(root, 'host-manifest.json')], { encoding: 'utf8', timeout: 125_000, maxBuffer: 1_000_000, env: { PATH: '/usr/bin:/bin', RUFLO_MANAGED_VERIFIER_PRIVATE_KEY_FILE: privatePath, RUFLO_MANAGED_VERIFIER_ALLOW_SYNTHETIC: '1' } });+ check(expectSuccess ? result.status === 0 : result.status !== 0, `Verifier unexpected exit ${result.status}`);+ check(!result.stdout.includes('PRIVATE KEY') && !result.stdout.includes('private-child-diagnostic-marker') && !result.stderr.includes('private-child-diagnostic-marker'), 'Private check output must not escape');+ return expectSuccess ? JSON.parse(result.stdout) : null;+}++try {+ const evidence = [];+ for (const strategyId of ['baseline', 'candidate']) {+ for (let trial = 0; trial < 3; trial++) {+ prepare({ id: `training-${trial}`, x: trial + 1, expected: (trial + 1) * 2 }, strategyId, 'train', trial);+ const result = invoke(); evidence.push(result.evidence);+ check(isVerified(result.evidence, publicKey), 'Verifier receipt must authenticate');+ check(result.report.costOrigin === 'synthetic-fixture' && result.report.checks.length === 5, 'Every declared independent check must execute');+ check(result.evidence.observation.durationMs > 0 && result.evidence.observation.checks.safety, 'Metrics are from actual subprocess checks');+ if (strategyId === 'baseline' && trial === 0) {+ recordLearning(root, { observation: result.evidence.observation }, publicKey);+ check(learningStatus(root, publicKey).verified === 0, 'Unsigned outcome must remain quarantined');+ }+ recordLearning(root, result.evidence, publicKey);+ }+ for (const task of heldTasks) for (const trial of manifest.trials) {+ prepare(task, strategyId, 'holdout', trial);+ const result = invoke(); evidence.push(result.evidence); recordLearning(root, result.evidence, publicKey);+ }+ }+ const scope = { taskType: 'code-review' as const, policyHash: evidence[0].observation.policyHash, evaluatorHash: evidence[0].observation.evaluatorHash };+ const recommendation = recommendLearning(root, scope, publicKey);+ check(recommendation.selected?.strategy.id === 'candidate' && recommendation.defaultsChanged === false, 'Real ledger must recommend from full trusted training cohort');+ const evaluation = evaluateLearning(root, { scope, manifest, baselineId: 'baseline', candidateId: 'candidate' }, publicKey);+ check(evaluation.pairedResults === 6 && evaluation.delta === 1 && evaluation.defaultsChanged === false, 'Real paired holdout must retain immutable evaluation boundaries');+ check(evaluation.eligible, 'Bounded fixture should satisfy independent gate under measured latency');+ check(learningStatus(root, publicKey).verified === 18, 'All verifier subprocess receipts must reload and authenticate');+ const cycleInput = { scope, evidence, evaluation: { manifest, baselineId: 'baseline', candidateId: 'candidate' }, index: false };+ const cycle = await cycleLearning(cycleRoot, cycleInput, publicKey, () => true);+ check(cycle.recorded.length === 18 && cycle.evaluation?.eligible && cycle.phases.join(',') === 'admitted,recorded,recommended,evaluated', 'Real feedback cycle must admit, record, recommend and evaluate');+ const replay = await cycleLearning(cycleRoot, cycleInput, publicKey, () => true);+ check(replay.cycleId === cycle.cycleId && replay.recorded.length === 0 && replay.duplicates.length === 18, 'Actual cycle replay must be idempotent');+ await assert.rejects(cycleLearning(deniedRoot, cycleInput, publicKey, () => false)); assertions++;+ check(!existsSync(join(deniedRoot, '.claude-flow')), 'Denied cycle must have no ledger side effects');+ const copied = JSON.parse(JSON.stringify(evidence[0])); copied.observation.costCents = 1;+ check(!isVerified(copied, publicKey), 'Post-verification cost mutation must invalidate signature');+ assert.throws(() => recordLearning(root, copied, publicKey)); assertions++;+ const wrongKey = generateKeyPairSync('ed25519').publicKey.export({ format: 'pem', type: 'spki' }).toString();+ check(learningStatus(root, wrongKey).lastEvaluation === null, 'Key rotation must invalidate old eligible advice');++ prepare({ id: 'failure', x: 2, expected: 4 }, 'candidate', 'train', 9);+ lastManifest!.checks.acceptance = [command('private-failure')]; json(join(root, 'host-manifest.json'), lastManifest!);+ const failure = invoke();+ check(failure.evidence.observation.checks.acceptance === false && isVerified(failure.evidence, publicKey), 'Actual failed checks must remain signed failures');+ prepare({ id: 'timeout', x: 2, expected: 4 }, 'candidate', 'train', 10);+ lastManifest!.checks.acceptance = [{ ...command('slow'), timeoutMs: 30 }]; json(join(root, 'host-manifest.json'), lastManifest!);+ const timeout = invoke();+ check(timeout.evidence.observation.checks.acceptance === false && timeout.report.checks[0].timedOut, 'Timeout must never become a passing check');+ prepare({ id: 'bad-cost', x: 2, expected: 4 }, 'candidate', 'train', 11);+ const cost = JSON.parse(readFileSync(join(root, 'cost.json'), 'utf8')); cost.taskHash = digest('wrong-task'); json(join(root, 'cost.json'), cost); invoke(false);+ prepare({ id: 'bad-command', x: 2, expected: 4 }, 'candidate', 'train', 12);+ lastManifest!.checks.acceptance[0]!.argv[0] = 'node'; json(join(root, 'host-manifest.json'), lastManifest!); invoke(false);+ prepare({ id: 'unsafe-executable', x: 2, expected: 4 }, 'candidate', 'train', 12);+ chmodSync(fixtureNode, 0o770); invoke(false); chmodSync(fixtureNode, 0o700);+ prepare({ id: 'shell-command', x: 2, expected: 4 }, 'candidate', 'train', 12);+ lastManifest!.checks.acceptance[0]!.argv = ['/bin/sh', '-c', 'exit 0']; json(join(root, 'host-manifest.json'), lastManifest!); invoke(false);+ prepare({ id: 'bad-cwd', x: 2, expected: 4 }, 'candidate', 'train', 13);+ lastManifest!.checks.acceptance[0]!.cwd = '../'; json(join(root, 'host-manifest.json'), lastManifest!); invoke(false);+ prepare({ id: 'key-mode', x: 2, expected: 4 }, 'candidate', 'train', 14);+ chmodSync(privatePath, 0o644); invoke(false); chmodSync(privatePath, 0o600);+ prepare({ id: 'mutated-source', x: 2, expected: 4 }, 'candidate', 'train', 15);+ lastManifest!.checks.acceptance = [command('mutate')]; json(join(root, 'host-manifest.json'), lastManifest!); invoke(false);+ console.log(JSON.stringify({ schema: 'ruflo.managed-verifier-e2e/v1', assertions, verifiedSubprocessReceipts: 18, cyclePhases: cycle.phases, replayedDuplicates: replay.duplicates.length, deniedCycleWrites: 0, training: 6, pairedHoldout: evaluation.pairedResults, advisoryEligible: evaluation.eligible, measuredBaselineP95Ms: evaluation.baselineP95Ms, measuredCandidateP95Ms: evaluation.candidateP95Ms, defaultsChanged: false, costOrigin: 'synthetic-fixture', limitations: 'Real verifier subprocesses, signatures, file persistence, feedback cycle and heldout gates; synthetic workload and cost fixture only. No live provider quality, billing savings, universal safety or native vector backend is claimed.' }, null, 2));+} finally { for (const path of [root, keys, cycleRoot, deniedRoot]) rmSync(path, { recursive: true, force: true }); }diff --git a/scripts/e2e-managed-native.mts b/scripts/e2e-managed-native.mtsnew file mode 100644index 0000000000..2ebd3264e9--- /dev/null+++ b/scripts/e2e-managed-native.mts@@ -0,0 +1,72 @@+/** Real disk/native-memory probe. Run write, then recall in a NEW process with tsx.+ * Synthetic signed fixtures test plumbing only; they are not measured model outcomes.+ * Usage: tsx scripts/e2e-managed-native.mts write|status|recall /absolute/isolated/state+ * Does not install dependencies, call a model, persist a private key or change defaults.+ */+import assert from 'node:assert/strict';+import { generateKeyPairSync, sign } from 'node:crypto';+import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';+import { resolve, join, isAbsolute } from 'node:path';+import { canonical, digest, observationOf } from '../v3/@claude-flow/cli/src/services/managed-learning.js';+import { indexLearning, learningStatus, recallLearning, recordLearning, recommendLearning } from '../v3/@claude-flow/cli/src/services/managed-learning-store.js';+import { managedMemoryClient } from '../v3/@claude-flow/cli/src/services/managed-memory-client.js';++const [mode, inputRoot] = process.argv.slice(2);+assert(['write', 'status', 'recall'].includes(mode));+assert(inputRoot && isAbsolute(inputRoot), 'Use an explicit isolated absolute state directory');+const root = resolve(inputRoot), metadata = join(root, 'probe.json');+const scope = { taskType: 'code-review', policyHash: digest('native-probe-policy'), evaluatorHash: digest('synthetic-plumbing-only') };+let output: Record<string, unknown> = { mode, syntheticFixtures: true, modelCalls: 0, defaultsChanged: false };+try {+ mkdirSync(root, { recursive: true, mode: 0o700 });+ process.chdir(root); // Native memory paths are scoped to the process project root.+ if (mode === 'write') {+ assert(!existsSync(metadata), 'Refusing to overwrite an existing probe');+ mkdirSync(root, { recursive: true, mode: 0o700 });+ const pair = generateKeyPairSync('ed25519');+ const publicKey = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString();+ const ids: string[] = [];+ for (let trial = 0; trial < 3; trial++) {+ const observation = observationOf({ v: 1, attemptId: digest(`native-attempt-${trial}`), taskHash: digest(`native-task-${trial}`),+ sourceHash: digest('synthetic-source'), artifactHash: digest('synthetic-artifact'), corpusHash: digest('native-train'), ...scope,+ split: 'train', trial, strategy: { id: 'fixture', model: 'synthetic-no-model', workers: 1, template: 'plumbing' }, budgetCents: 100,+ costCents: 1, durationMs: 1, checks: { acceptance: true, safety: true, replay: true, adversarial: true, drift: 0, driftThreshold: .05, rollbackRate: 0 } });+ const evidence = { observation, signature: sign(null, Buffer.from(canonical(observation)), pair.privateKey).toString('base64') };+ const stored = recordLearning(root, evidence, publicKey);+ assert(stored.verified);+ ids.push(stored.id);+ }+ writeFileSync(metadata, JSON.stringify({ publicKey, ids }), { mode: 0o600 });+ const recommendation = recommendLearning(root, scope, publicKey);+ assert.equal(recommendation.selected?.samples, 3);+ assert.equal(learningStatus(root, publicKey).verified, 3);+ const indexed = [], indexMs = [];+ for (const id of ids) { const started = performance.now(); indexed.push(await indexLearning(root, id, publicKey)); indexMs.push(performance.now() - started); }+ assert(indexed.every(row => row.durable));+ // Replay the same immutable native rows instead of attempting overwrite.+ for (const id of ids) assert.equal((await indexLearning(root, id, publicKey)).durable, true);+ output = { ...output, verifiedRows: 3, indexed, indexMs, nativeReplayRows: ids.length, workers: managedMemoryClient.stats().workers, advisoryStrategy: recommendation.selected?.strategy.id };+ } else {+ const { publicKey, ids } = JSON.parse(readFileSync(metadata, 'utf8'));+ assert.equal(learningStatus(root, publicKey).verified, 3);+ if (mode === 'status') {+ output = { ...output, verifiedRows: 3, ledgerReloaded: true, nativeBackendExercised: false };+ } else {+ const recalled = await recallLearning(root, scope, publicKey);+ assert(recalled.available, 'Memory backend unavailable after restart');+ assert.equal(recalled.evidence.length, ids.length, 'Every indexed fixture must survive restart and signature validation');+ assert(recalled.evidence.every(row => ids.includes(row.id)));+ assert.equal(recalled.recommendation.selected?.samples, 3);+ output = { ...output, verifiedRows: 3, recalled: recalled.evidence.length, backend: recalled.backend,+ similarityIsVerification: recalled.similarityIsVerification, advisoryStrategy: recalled.recommendation.selected?.strategy.id };+ }+ }+ output.passed = true;+} catch (error) {+ output = { ...output, passed: false, error: (error as Error).message };+ process.exitCode = 1;+} finally {+ managedMemoryClient.close();+ writeFileSync(join(root, `native-${mode}.json`), JSON.stringify(output, null, 2));+ console.log(JSON.stringify(output));+}diff --git a/scripts/e2e-managed-provider.mts b/scripts/e2e-managed-provider.mtsnew file mode 100644index 0000000000..76d7e98421--- /dev/null+++ b/scripts/e2e-managed-provider.mts@@ -0,0 +1,85 @@+/** Opt-in real provider canary. No key or entitlement is inferred from a Claude login.+ * RUFLO_MANAGED_E2E_LIVE=1 RUFLO_MANAGED_E2E_AGENT_IDS=agent_... tsx scripts/e2e-managed-provider.mts+ * Uses a $1 provider budget (in-flight overshoot remains possible), limited networking,+ * fixed harmless work, existing predefined workers and cleanup of only new owned resources.+ */+import { managedAgentTools } from '../v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.js';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import assert from 'node:assert/strict';++const agents = (process.env.RUFLO_MANAGED_E2E_AGENT_IDS ?? '').split(',').filter(Boolean);+const key = process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY;+const blockers = [process.env.RUFLO_MANAGED_E2E_LIVE !== '1' && 'explicit live opt-in', !key && 'executor API key',+ (!agents.length || agents.length > 2 || agents.some(id => !/^agent_[A-Za-z0-9]+$/.test(id))) && 'one or two predefined agent IDs',+ process.env.RUFLO_MANAGED_AGENTS_BASE_URL && process.env.RUFLO_MANAGED_AGENTS_BASE_URL !== 'https://api.anthropic.com' && 'official provider origin'].filter(Boolean);+if (blockers.length) {+ console.log(JSON.stringify({ passed: false, blocked: true, blockers, providerCalls: 0 }));+ process.exit(3);+}+const previous = { cwd: process.env.CLAUDE_FLOW_CWD, control: process.env.RUFLO_MANAGED_CONTROL, sessions: process.env.RUFLO_MANAGED_CONTROL_SESSIONS };+const root = mkdtempSync(join(tmpdir(), 'managed-provider-canary-'));+process.env.CLAUDE_FLOW_CWD = root;+const call = async (name: string, input: Record<string, unknown>) => {+ const result = await managedAgentTools.find(t => t.name === name)!.handler(input);+ return result as Record<string, any>;+};+const report: Record<string, unknown> = { passed: false, liveProvider: true, budgetCents: 100, maxWaitMs: 45_000, verification: 'unverified', acceptancePassed: false, root };+let owned: Record<string, any> = {};+try {+ owned = await call('managed_agent_create', { name: 'ruflo-e2e-canary', title: 'Bounded managed workflow canary', dynamicWorkflows: true, budgetCents: '100', predefinedAgents: agents, allowedHosts: [], networking: 'limited',+ system: 'Run only this harmless arithmetic workflow. Use at most two predefined workers. Do not use network or modify external data.' });+ assert.equal(owned.success, true, 'Provider creation did not succeed; inspect owned IDs and cleanup report');+ report.sessionId = owned.sessionId;+ process.env.RUFLO_MANAGED_CONTROL = '1'; process.env.RUFLO_MANAGED_CONTROL_SESSIONS = owned.sessionId;+ const prompt = await call('managed_agent_prompt', { sessionId: owned.sessionId, message: 'Run a small workflow with at most two predefined workers to independently calculate 2+2, combine the results, and return RUFLO_E2E_OK=4. No other work.', maxWaitMs: 45_000 });+ report.observedStatus = prompt.status ?? 'unknown';+ const inspected = await call('managed_agent_control', { sessionId: owned.sessionId, action: 'inspect', threadOffset: 0 });+ assert.equal(inspected.success, true, 'Fresh worker inspection failed');+ assert.equal(inspected.snapshot?.verification, 'unverified');+ report.workerCount = inspected.snapshot?.threadCount ?? null;+ report.providerFinished = inspected.snapshot?.providerFinished ?? false;+ report.listCostCents = inspected.snapshot?.listCostCents ?? null;+ report.budgetPauseObserved = inspected.snapshot?.stopReason === 'budget_reached';+ assert.equal(prompt.success, true, 'Prompt failed');+ assert.equal(typeof prompt.messageId, 'string', 'Prompt was not acknowledged');+ assert.equal(inspected.snapshot?.providerFinished, true, 'Provider has not finished; this canary is incomplete');+ assert(inspected.snapshot?.runs?.length > 0 && inspected.snapshot?.threadCount > 0, 'No dynamic workflow and child worker were observed');+ assert(typeof prompt.assistantText === 'string' && prompt.assistantText.includes('RUFLO_E2E_OK=4'), 'Expected response marker was not observed');+ process.env.RUFLO_MANAGED_CONTROL = '0';+ const refused = await call('managed_agent_control', { sessionId: owned.sessionId, action: 'interrupt' });+ assert.equal(refused.success, false, 'Revoked host policy authorized an action');+ report.revokedPolicyDenied = true;+ process.env.RUFLO_MANAGED_CONTROL = '1';+ const ended = await call('managed_agent_control', { sessionId: owned.sessionId, action: 'terminate' });+ assert.equal(ended.cancellationConfirmed, true, 'Remote termination not confirmed');+ report.remoteTerminationConfirmed = true;+ report.passed = true;+} catch { report.error = 'Live canary failed; inspect provider status and resource cleanup before retrying'; process.exitCode = 1; }+finally {+ const cleanup: Record<string, unknown> = {};+ report.ownedResourceIds = { sessionId: owned.sessionId, environmentId: owned.environmentId, agentId: owned.agentId };+ report.creationCleanupRequired = owned.cleanupRequired ?? false;+ if (!owned.cleanupRequired) {+ for (const [kind, id, pattern] of [+ ['sessions', owned.sessionId, /^sesn_[A-Za-z0-9]+$/],+ ['environments', owned.environmentId, /^env_[A-Za-z0-9]+$/],+ ['agents', owned.agentId, /^agent_[A-Za-z0-9]+$/],+ ] as const) {+ if (!pattern.test(id ?? '')) continue;+ if (kind === 'sessions' && report.remoteTerminationConfirmed) { cleanup[kind] = true; continue; }+ try {+ const result = await fetch(`https://api.anthropic.com/v1/${kind}/${encodeURIComponent(id)}`, { method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(15_000), headers: { 'x-api-key': key!, 'anthropic-version': '2023-06-01', 'anthropic-beta': 'managed-agents-2026-04-01' } });+ cleanup[kind] = [200, 204, 404].includes(result.status); await result.body?.cancel();+ } catch { cleanup[kind] = false; }+ if (kind === 'sessions' && cleanup[kind] !== true) { report.creationCleanupRequired = true; break; }+ }+ }+ report.cleanup = cleanup;+ if (Object.values(cleanup).some(v => v === false) || report.creationCleanupRequired) { report.passed = false; process.exitCode = 1; }+ for (const [name, value] of Object.entries({ CLAUDE_FLOW_CWD: previous.cwd, RUFLO_MANAGED_CONTROL: previous.control, RUFLO_MANAGED_CONTROL_SESSIONS: previous.sessions })) {+ if (value === undefined) delete process.env[name]; else process.env[name] = value;+ }+ console.log(JSON.stringify(report));+}diff --git a/scripts/managed-outcome-verifier.mts b/scripts/managed-outcome-verifier.mtsnew file mode 100644index 0000000000..44533a92bd--- /dev/null+++ b/scripts/managed-outcome-verifier.mts@@ -0,0 +1,149 @@+/** Host CLI only. Fixed developer-owned checks are trusted code, not a sandbox. */+import { createHash, createPrivateKey, sign } from 'node:crypto';+import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';+import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { spawn } from 'node:child_process';+import { performance } from 'node:perf_hooks';+import { canonical, digest, observationOf, type Evidence, type Observation } from '../v3/@claude-flow/cli/src/services/managed-learning.js';++type Command = { argv: string[]; cwd: string; timeoutMs: number };+type Groups = Record<'acceptance' | 'safety' | 'replay' | 'adversarial', Command[]>;+export type HostManifest = {+ v: 1; root: string; sourceFiles: string[]; artifactFiles: string[];+ taskSpec: string; policySpec: string; corpusSpec: string; evaluatorSpec: string; costReceipt: string;+ taskType: Observation['taskType']; split: Observation['split']; trial: number;+ strategy: Observation['strategy']; budgetCents: number; checks: Groups; metrics: Command;+};+type CheckResult = { group: string; exitCode: number | null; signal: string | null; timedOut: boolean; overflow: boolean; durationMs: number; stdoutHash: string; stderrHash: string };+const HASH = /^[a-f0-9]{64}$/;+const groups = ['acceptance', 'safety', 'replay', 'adversarial'] as const;+function exact(v: unknown, keys: readonly string[]): asserts v is Record<string, unknown> {+ if (!v || typeof v !== 'object' || Array.isArray(v) || Object.keys(v).length !== keys.length || Object.keys(v).some(k => !keys.includes(k))) throw Error('Invalid closed host contract');+}+const sha = (data: string | Buffer) => createHash('sha256').update(data).digest('hex');+function beneath(root: string, path: string): boolean { const rel = relative(root, path); return rel === '' || (!rel.startsWith('..' + sep) && rel !== '..' && !isAbsolute(rel)); }+function regular(path: string, max = 128_000, hostOwned = false): Buffer {+ const before = lstatSync(path);+ if (!before.isFile() || before.isSymbolicLink() || (hostOwned && ((process.getuid && before.uid !== process.getuid()) || (before.mode & 0o022)))) throw Error('Host file ownership or type rejected');+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const s = fstatSync(fd);+ if (!s.isFile() || s.ino !== before.ino || s.dev !== before.dev || s.size > max) throw Error('Host file changed or exceeded limit');+ const buffer = Buffer.alloc(max + 1); let bytes = 0;+ while (bytes < buffer.length) { const count = readSync(fd, buffer, bytes, buffer.length - bytes, bytes); if (!count) break; bytes += count; }+ if (bytes > max) throw Error('Host file exceeds limit');+ return buffer.subarray(0, bytes);+ } finally { closeSync(fd); }+}+function contained(root: string, input: unknown, directory = false): string {+ if (typeof input !== 'string' || !input || isAbsolute(input) || input.includes('\0')) throw Error('Paths must be relative to host root');+ const path = resolve(root, input);+ if (!beneath(root, path)) throw Error('Path outside host root');+ let p = root;+ for (const component of relative(root, path).split(sep).filter(Boolean)) {+ p = resolve(p, component);+ if (lstatSync(p).isSymbolicLink()) throw Error('Symlink paths are not accepted');+ }+ if (!beneath(root, realpathSync(path)) || (directory && !lstatSync(path).isDirectory())) throw Error('Invalid contained path');+ return path;+}+function jsonFile(path: string, hostOwned = false): unknown { return JSON.parse(regular(path, 128_000, hostOwned).toString('utf8')); }+export function treeHash(root: string, paths: string[]): string {+ if (!Array.isArray(paths) || paths.length < 1 || paths.length > 100 || new Set(paths).size !== paths.length) throw Error('Explicit unique file list required');+ let bytes = 0;+ return digest(paths.slice().sort().map(name => {+ const data = regular(contained(root, name), 4_000_000); bytes += data.length;+ if (bytes > 16_000_000) throw Error('Tree exceeds limit');+ return { path: name, sha256: sha(data) };+ }));+}+function commandOf(value: unknown, root: string): Command {+ exact(value, ['argv', 'cwd', 'timeoutMs']);+ if (!Array.isArray(value.argv) || value.argv.length < 1 || value.argv.length > 32 || value.argv.some(v => typeof v !== 'string' || v.length > 4096 || v.includes('\0')) || !isAbsolute(value.argv[0]) || !Number.isSafeInteger(value.timeoutMs) || (value.timeoutMs as number) < 1 || (value.timeoutMs as number) > 30_000) throw Error('Invalid bounded argv');+ const executable = realpathSync(value.argv[0]);+ if (/^(?:ba|da|z|fi|c|tc|k)?sh$|^(?:env|cmd|powershell|pwsh)(?:\.exe)?$/i.test(basename(executable))) throw Error('Shell and executable-dispatch wrappers are not accepted');+ const stat = lstatSync(executable);+ if (!stat.isFile() || (stat.mode & 0o022) || !(stat.mode & 0o111)) throw Error('Unsafe executable');+ contained(root, value.cwd, true);+ return { argv: [executable, ...value.argv.slice(1)], cwd: value.cwd as string, timeoutMs: value.timeoutMs as number };+}+function manifestOf(value: unknown): HostManifest {+ exact(value, ['v', 'root', 'sourceFiles', 'artifactFiles', 'taskSpec', 'policySpec', 'corpusSpec', 'evaluatorSpec', 'costReceipt', 'taskType', 'split', 'trial', 'strategy', 'budgetCents', 'checks', 'metrics']);+ if (value.v !== 1 || typeof value.root !== 'string' || !isAbsolute(value.root) || lstatSync(value.root).isSymbolicLink() || !lstatSync(value.root).isDirectory()) throw Error('Invalid host root');+ const root = realpathSync(value.root);+ const strategy = value.strategy;+ exact(strategy, ['id', 'model', 'workers', 'template']);+ if (['id', 'model', 'template'].some(k => typeof strategy[k] !== 'string')) throw Error('Strategy identifiers must be literal strings');+ exact(value.checks, groups);+ const checks = {} as Groups;+ for (const group of groups) {+ const entries = value.checks[group];+ if (!Array.isArray(entries) || entries.length < 1 || entries.length > 4) throw Error('Every verification group needs executed checks');+ checks[group] = entries.map(v => commandOf(v, root));+ }+ return { ...value, root, checks, metrics: commandOf(value.metrics, root) } as HostManifest;+}+async function run(command: Command, root: string, group: string, deadline: number): Promise<{ report: CheckResult; stdout: string }> {+ const started = performance.now(), stdout: Buffer[] = [], stderr: Buffer[] = [];+ let bytes = 0, overflow = false, timedOut = false;+ if (Date.now() >= deadline) throw Error('Verifier deadline exceeded');+ const child = spawn(command.argv[0]!, command.argv.slice(1), { cwd: contained(root, command.cwd, true), shell: false, detached: true, env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C' }, stdio: ['ignore', 'pipe', 'pipe'] });+ const kill = () => { if (child.pid) { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* already exited */ } } };+ const timer = setTimeout(() => { timedOut = true; kill(); }, Math.min(command.timeoutMs, deadline - Date.now()));+ for (const [stream, chunks] of [[child.stdout, stdout], [child.stderr, stderr]] as const) stream.on('data', (data: Buffer) => { bytes += data.length; if (bytes > 64_000) { overflow = true; kill(); } else chunks.push(data); });+ return new Promise((resolveResult, reject) => {+ child.once('error', () => { clearTimeout(timer); kill(); reject(Error('Verifier executable failed')); });+ child.once('close', (exitCode, signal) => {+ clearTimeout(timer); kill();+ const out = Buffer.concat(stdout), err = Buffer.concat(stderr);+ resolveResult({ report: { group, exitCode, signal, timedOut, overflow, durationMs: Math.ceil(performance.now() - started), stdoutHash: sha(out), stderrHash: sha(err) }, stdout: out.toString('utf8') });+ });+ });+}++/** Manifest and key paths are supplied only by the trusted host CLI, never MCP. */+export async function verifyHostManifest(path: string): Promise<{ evidence: Evidence; report: { v: 1; sourceHash: string; artifactHash: string; evaluatorHash: string; costReceiptHash: string; costOrigin: string; checks: CheckResult[]; limitations: string } }> {+ if (process.platform === 'win32') throw Error('Verifier process-group lifecycle requires a POSIX host');+ const manifest = manifestOf(jsonFile(resolve(path), true));+ const keyPath = process.env.RUFLO_MANAGED_VERIFIER_PRIVATE_KEY_FILE;+ if (!keyPath || !isAbsolute(keyPath)) throw Error('Host signing key file is required');+ const keyDir = lstatSync(dirname(keyPath)), keyStat = lstatSync(keyPath);+ if (!keyDir.isDirectory() || keyDir.isSymbolicLink() || (keyDir.mode & 0o077) || (process.getuid && keyDir.uid !== process.getuid()) || keyStat.isSymbolicLink() || (keyStat.mode & 0o077)) throw Error('Signing key needs an owner-only directory and file');+ const root = manifest.root;+ const specs = Object.fromEntries(['taskSpec', 'policySpec', 'corpusSpec', 'evaluatorSpec'].map(k => [k, jsonFile(contained(root, manifest[k as keyof HostManifest]), true)]));+ const sourceHash = treeHash(root, manifest.sourceFiles), artifactHash = treeHash(root, manifest.artifactFiles);+ const taskHash = digest(specs.taskSpec), policyHash = digest(specs.policySpec), corpusHash = digest(specs.corpusSpec);+ const evaluatorHash = digest({ verifier: sha(regular(fileURLToPath(import.meta.url), 200_000)), spec: specs.evaluatorSpec, checks: manifest.checks, metrics: manifest.metrics });+ const cost = jsonFile(contained(root, manifest.costReceipt), true);+ exact(cost, ['v', 'origin', 'amountCents', 'taskHash', 'sourceHash', 'artifactHash', 'strategyHash', 'receiptId']);+ if (cost.v !== 1 || !['synthetic-fixture', 'provider-export'].includes(cost.origin as string) || !Number.isSafeInteger(cost.amountCents) || (cost.amountCents as number) <= 0 || (cost.amountCents as number) > 999_999_999 || cost.taskHash !== taskHash || cost.sourceHash !== sourceHash || cost.artifactHash !== artifactHash || cost.strategyHash !== digest(manifest.strategy) || typeof cost.receiptId !== 'string' || !HASH.test(cost.receiptId)) throw Error('Trusted cost receipt is not bound to this attempt');+ if (cost.origin === 'synthetic-fixture' && process.env.RUFLO_MANAGED_VERIFIER_ALLOW_SYNTHETIC !== '1') throw Error('Synthetic cost requires explicit host fixture mode and a dedicated fixture key');+ // Validate the full observation contract before spawning any trusted checks.+ const attemptId = digest({ taskHash, sourceHash, artifactHash, policyHash, corpusHash, evaluatorHash, strategy: manifest.strategy, split: manifest.split, trial: manifest.trial, costReceiptHash: digest(cost) });+ const proposed = observationOf({ v: 1, attemptId, taskHash, sourceHash, artifactHash, policyHash, corpusHash, evaluatorHash, taskType: manifest.taskType, split: manifest.split, trial: manifest.trial, strategy: manifest.strategy, budgetCents: manifest.budgetCents, costCents: cost.amountCents, durationMs: 0, checks: { acceptance: false, safety: false, replay: false, adversarial: false, drift: 1, driftThreshold: 0, rollbackRate: 1 } });+ const reports: CheckResult[] = [], outcomes = {} as Record<typeof groups[number], boolean>;+ const started = performance.now(), deadline = Date.now() + 120_000;+ for (const group of groups) {+ const results = [];+ for (const check of manifest.checks[group]) { const result = await run(check, root, group, deadline); reports.push(result.report); results.push(result.report.exitCode === 0 && !result.report.timedOut && !result.report.overflow); }+ outcomes[group] = results.every(Boolean);+ }+ const metricResult = await run(manifest.metrics, root, 'metrics', deadline); reports.push(metricResult.report);+ if (metricResult.report.exitCode !== 0 || metricResult.report.timedOut || metricResult.report.overflow || metricResult.stdout.length > 4096) throw Error('Independent metrics check failed');+ const metrics: unknown = JSON.parse(metricResult.stdout); exact(metrics, ['drift', 'driftThreshold', 'rollbackRate']);+ if (treeHash(root, manifest.sourceFiles) !== sourceHash || treeHash(root, manifest.artifactFiles) !== artifactHash || digest(jsonFile(contained(root, manifest.costReceipt), true)) !== digest(cost) || ['taskSpec', 'policySpec', 'corpusSpec', 'evaluatorSpec'].some(k => digest(jsonFile(contained(root, manifest[k as keyof HostManifest]), true)) !== digest(specs[k]))) throw Error('Host inputs changed during verification');+ const observation = observationOf({ ...proposed, durationMs: Math.ceil(performance.now() - started), checks: { ...outcomes, ...metrics } });+ // Key material is loaded only after all checks; children never inherit it or its path.+ const key = createPrivateKey(regular(keyPath, 16_384, true));+ if (key.asymmetricKeyType !== 'ed25519') throw Error('Host signer must use Ed25519');+ const signature = sign(null, Buffer.from(canonical(observation)), key).toString('base64');+ return { evidence: { observation, signature }, report: { v: 1, sourceHash, artifactHash, evaluatorHash, costReceiptHash: digest(cost), costOrigin: cost.origin as string, checks: reports, limitations: 'Fixed host-owned checks measure their declared contracts only; not a sandbox, universal safety proof, provider billing audit or release authorization. Synthetic fixture cost is not live spend.' } };+}++if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {+ try {+ if (process.argv.length !== 3) throw Error('One host manifest path is required');+ console.log(JSON.stringify(await verifyHostManifest(process.argv[2]!)));+ } catch { console.error('Managed outcome verification failed; no receipt emitted. Inspect trusted host inputs and check contracts.'); process.exitCode = 1; }+}diff --git a/v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts b/v3/@claude-flow/cli/__tests__/managed-agent-tools.test.tsindex 1bcce3b8ed..fea4212134 100644--- a/v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts+++ b/v3/@claude-flow/cli/__tests__/managed-agent-tools.test.ts@@ -8,12 +8,16 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { managedAgentTools } from '../src/mcp-tools/managed-agent-tools.js';const TOOL_NAMES = [+ 'managed_agent_capabilities',+ 'managed_agent_learning',+ 'managed_agent_control','managed_agent_create','managed_agent_prompt','managed_agent_status','managed_agent_events','managed_agent_list','managed_agent_terminate',+ 'managed_agent_interrupt',] as const;const tool = (name: string) => {@@ -37,7 +41,7 @@ describe('ADR-115 — managed_agent_* MCP tools', () => {if (prevClaude === undefined) delete process.env.CLAUDE_API_KEY; else process.env.CLAUDE_API_KEY = prevClaude;});- it('registers exactly the six managed_agent_* tools', () => {+ it('registers exactly the ten managed_agent_* tools', () => {const names = managedAgentTools.map(t => t.name).sort();expect(names).toEqual([...TOOL_NAMES].sort());});@@ -58,7 +62,7 @@ describe('ADR-115 — managed_agent_* MCP tools', () => {expect(new Set(descs).size).toBe(descs.length);});- for (const name of TOOL_NAMES) {+ for (const name of TOOL_NAMES.filter(name => name !== 'managed_agent_capabilities' && name !== 'managed_agent_learning')) {it(`${name} degrades gracefully with no API key (no throw, structured error, no network)`, async () => {// minimal valid-ish input per tool's required fieldsconst input: Record<string, unknown> =diff --git a/v3/@claude-flow/cli/__tests__/managed-learning-loop.test.ts b/v3/@claude-flow/cli/__tests__/managed-learning-loop.test.tsnew file mode 100644index 0000000000..578dab373e--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-learning-loop.test.ts@@ -0,0 +1,78 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { generateKeyPairSync, sign } from 'node:crypto';+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { canonical, digest, observationOf } from '../src/services/managed-learning.js';+import { learningStatus } from '../src/services/managed-learning-store.js';+import { cycleLearning } from '../src/services/managed-learning-loop.js';+import { managedLearningTool } from '../src/mcp-tools/managed-learning-tool.js';++const pair = generateKeyPairSync('ed25519'), key = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const scope = { taskType: 'implementation', policyHash: digest('policy'), evaluatorHash: digest('evaluator') };+const roots: string[] = [];+function root() { const p = mkdtempSync(join(tmpdir(), 'managed-cycle-')); roots.push(p); return p; }+function rows() {+ return ['baseline', 'candidate'].flatMap(id => [0, 1, 2].map(trial => {+ const observation = observationOf({ v: 1, ...scope, attemptId: digest(`${id}-${trial}`), taskHash: digest(`task-${trial}`), sourceHash: digest('source'), artifactHash: digest('artifact'), corpusHash: digest('train'), split: 'train', trial,+ strategy: { id, model: 'fixture', workers: 1, template: 'test' }, budgetCents: 100, costCents: id === 'candidate' ? 1 : 2, durationMs: 1,+ checks: { acceptance: true, safety: true, replay: true, adversarial: true, drift: 0, driftThreshold: .1, rollbackRate: 0 } });+ return { observation, signature: sign(null, Buffer.from(canonical(observation)), pair.privateKey).toString('base64') };+ }));+}+afterEach(() => { roots.splice(0).forEach(p => rmSync(p, { recursive: true, force: true })); vi.unstubAllEnvs(); });++describe('bounded managed improvement cycles', () => {+ it('records measured receipts, recommends, and replays without duplicate learning', async () => {+ const p = root(), input = { scope, evidence: rows() };+ const first = await cycleLearning(p, input, key, () => true);+ expect(first).toMatchObject({ phases: ['admitted', 'recorded', 'recommended'], recommendation: { selected: { strategy: { id: 'candidate' } } }, defaultsChanged: false, promotionRequested: false });+ const next = await cycleLearning(p, input, key, () => true);+ expect(next.cycleId).toBe(first.cycleId);+ expect(next.recorded).toHaveLength(0); expect(next.duplicates).toHaveLength(6);+ expect(learningStatus(p, key).verified).toBe(6);+ });+ it('validates the entire batch before mutation and refuses caller capabilities', async () => {+ const p = root(), evidence = rows(); evidence[5]!.signature = evidence[0]!.signature;+ await expect(cycleLearning(p, { scope, evidence }, key, () => true)).rejects.toThrow('Every cycle');+ expect(existsSync(join(p, '.claude-flow'))).toBe(false);+ for (const extra of [{ promote: true }, { commands: ['echo unsafe'] }, { publicKey: key }]) {+ await expect(cycleLearning(p, { scope, evidence: [], ...extra }, key, () => true)).rejects.toThrow();+ }+ });+ it('refuses unsigned, cross-cohort, unmeasured and oversized batches', async () => {+ const p = root(), evidence = rows();+ await expect(cycleLearning(p, { scope, evidence: [{ observation: evidence[0]!.observation }] }, key, () => true)).rejects.toThrow('authenticated');+ await expect(cycleLearning(p, { scope: { ...scope, policyHash: digest('other') }, evidence }, key, () => true)).rejects.toThrow('in scope');+ await expect(cycleLearning(p, { scope, evidence: Array(25).fill(evidence[0]) }, key, () => true)).rejects.toThrow('24');+ expect(learningStatus(p, key).observations).toBe(0);+ });+ it('bounds native admission before writes and supports observation-free advisory cycles', async () => {+ const p = root(), evidence = rows();+ const more = [...evidence, ...evidence.map(e => {+ const observation = { ...e.observation, attemptId: digest(e.observation.attemptId), taskHash: digest(e.observation.taskHash) };+ return { observation, signature: sign(null, Buffer.from(canonical(observation)), pair.privateKey).toString('base64') };+ })];+ await expect(cycleLearning(p, { scope, evidence: more, index: true }, key, () => true)).rejects.toThrow('six training');+ expect(existsSync(join(p, '.claude-flow'))).toBe(false);+ const empty = await cycleLearning(p, { scope, evidence: [] }, key, () => true);+ expect(empty).toMatchObject({ recorded: [], recommendation: { abstained: true }, defaultsChanged: false });+ const first = await cycleLearning(p, { scope, evidence }, key, () => true);+ const reverse = await cycleLearning(p, { scope, evidence: [...evidence].reverse() }, key, () => true);+ expect(reverse.cycleId).toBe(first.cycleId);+ });+ it('rechecks policy between phases and preserves a resumable atomic batch', async () => {+ const p = root(); let checks = 0;+ await expect(cycleLearning(p, { scope, evidence: rows() }, key, () => ++checks <= 2)).rejects.toThrow('policy');+ expect(learningStatus(p, key).verified).toBe(6);+ const retry = await cycleLearning(p, { scope, evidence: rows() }, key, () => true);+ expect(retry.duplicates).toHaveLength(6); expect(retry.recorded).toHaveLength(0);+ });+ it('keeps the MCP host flag and verifier boundary even for cycle input', async () => {+ vi.stubEnv('CLAUDE_FLOW_CWD', root()); vi.stubEnv('RUFLO_MANAGED_LEARNING', '0');+ expect(await managedLearningTool.handler({ action: 'cycle', cycle: { scope, evidence: rows() } })).toMatchObject({ success: false });+ vi.stubEnv('RUFLO_MANAGED_LEARNING', '1'); vi.stubEnv('RUFLO_MANAGED_VERIFIER_PUBLIC_KEY', key);+ expect(await managedLearningTool.handler({ action: 'cycle', cycle: { scope, evidence: rows() }, approved: true })).toMatchObject({ success: false });+ expect(await managedLearningTool.handler({ action: 'cycle', cycle: { scope, evidence: rows() } })).toMatchObject({ success: true, defaultsChanged: false });+ });+});diff --git a/v3/@claude-flow/cli/__tests__/managed-learning.test.ts b/v3/@claude-flow/cli/__tests__/managed-learning.test.tsnew file mode 100644index 0000000000..6c7115f350--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-learning.test.ts@@ -0,0 +1,260 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { generateKeyPairSync, sign } from 'node:crypto';+import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { canonical, digest, evaluate, evidenceOf, isVerified, manifestOf, observationOf, recommend, trustedEvidence, type Evidence, type Observation } from '../src/services/managed-learning.js';+import { evaluateLearning, indexLearning, learningStatus, recordLearning, recordLearningBatch, recommendLearning, recallLearning } from '../src/services/managed-learning-store.js';++const memory = vi.hoisted(() => ({ index: vi.fn(), recall: vi.fn() }));+vi.mock('../src/services/managed-memory-client.js', () => ({ nativeMemoryIndex: memory.index, nativeMemoryRecall: memory.recall }));+const pair = generateKeyPairSync('ed25519');+const publicKey = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const scope = { taskType: 'code-review' as const, policyHash: digest('policy'), evaluatorHash: digest('evaluator') };+const manifest = manifestOf({ taskHashes: [digest('held-one'), digest('held-two')], trials: [0, 1, 2] });+function observation(patch: Partial<Observation> = {}): Observation {+ return observationOf({ v: 1, attemptId: digest('attempt'), taskHash: digest('task'), sourceHash: digest('source'), artifactHash: digest('artifact'), corpusHash: digest(manifest), ...scope, split: 'train', trial: 0,+ strategy: { id: 'baseline', model: 'claude-test', workers: 1, template: 'review' }, budgetCents: 250, costCents: 100, durationMs: 100,+ checks: { acceptance: true, safety: true, replay: true, adversarial: true, drift: 0, driftThreshold: .05, rollbackRate: 0 }, ...patch });+}+function signed(o: Observation): Evidence { return { observation: o, signature: sign(null, Buffer.from(canonical(o)), pair.privateKey).toString('base64') }; }+function training(): Evidence[] {+ return ['baseline', 'candidate'].flatMap(id => [0, 1, 2].map(trial => signed(observation({ attemptId: digest(`train-${id}-${trial}`), taskHash: digest(`training-${trial}`), trial, strategy: { id, model: 'claude-test', workers: id === 'baseline' ? 1 : 2, template: 'review' }, costCents: id === 'baseline' ? 100 : 50 }))));+}+function heldout(): Evidence[] {+ return ['baseline', 'candidate'].flatMap(id => manifest.taskHashes.flatMap(taskHash => manifest.trials.map(trial => signed(observation({ attemptId: digest(`${id}-${taskHash}-${trial}`), taskHash, trial, split: 'holdout', strategy: { id, model: 'claude-test', workers: id === 'baseline' ? 1 : 2, template: 'review' }, costCents: id === 'baseline' ? 100 : 50 })))));+}+const roots: string[] = [];+const root = () => { const r = mkdtempSync(join(tmpdir(), 'managed-learning-')); roots.push(r); return r; };+afterEach(() => { for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }); memory.index.mockReset(); memory.recall.mockReset(); });++describe('canonical signature encoding', () => {+ // An Ed25519 signature is 64 bytes = 86 base64 characters + "==". The last character carries 4 unused bits that Node's+ // decoder ignores, so up to 16 different strings verify as the same signature. Each used to dedupe as a NEW record.+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+ function variantOf(signature: string): string {+ const last = B64.indexOf(signature[85]);+ const other = B64[(last & 0b111100) | ((last + 1) & 0b11)];+ return signature.slice(0, 85) + other + '==';+ }+ it('rejects a non-canonical re-encoding of a valid signature, though it still verifies as bytes', () => {+ const evidence = signed(observation());+ const variant = variantOf(evidence.signature!);+ expect(variant).not.toBe(evidence.signature);+ expect(Buffer.from(variant, 'base64').equals(Buffer.from(evidence.signature!, 'base64'))).toBe(true);+ expect(() => evidenceOf({ observation: evidence.observation, signature: variant })).toThrow('Invalid verifier signature');+ expect(evidenceOf(evidence).signature).toBe(evidence.signature);+ });+ it('cannot be used to store the same attempt twice', () => {+ const dir = root();+ const evidence = signed(observation());+ recordLearningBatch(dir, [evidence], publicKey);+ expect(() => recordLearningBatch(dir, [{ observation: evidence.observation, signature: variantOf(evidence.signature!) }], publicKey)).toThrow();+ expect(learningStatus(dir, publicKey).observations).toBe(1);+ });+});++describe('host verification boundary', () => {+ it('requires the host key and verifies all bound observation fields', () => {+ const evidence = signed(observation());+ expect(isVerified(evidence, publicKey)).toBe(true);+ expect(isVerified(evidence)).toBe(false);+ for (const key of ['sourceHash', 'artifactHash', 'policyHash', 'corpusHash', 'evaluatorHash']) {+ expect(isVerified({ ...evidence, observation: { ...evidence.observation, [key]: digest('tampered') } }, publicKey)).toBe(false);+ }+ });+ it('rejects self-asserted verified flags and arbitrary text', () => {+ expect(() => evidenceOf({ ...signed(observation()), verified: true })).toThrow();+ expect(() => observationOf({ ...observation(), prompt: 'private text' })).toThrow();+ });+ it('does not accept another signer or a mutated reloaded receipt', () => {+ const other = generateKeyPairSync('ed25519'); const evidence = signed(observation());+ expect(isVerified(evidence, other.publicKey.export({ type: 'spki', format: 'pem' }).toString())).toBe(false);+ evidence.observation.costCents = 1;+ expect(trustedEvidence([JSON.parse(JSON.stringify(evidence))], publicKey)).toHaveLength(0);+ });+ it('detaches and freezes trusted evidence; direct raw objects cannot enter routing', () => {+ const raw = signed(observation()); const trusted = trustedEvidence([raw], publicKey);+ raw.observation.strategy.id = 'poison';+ expect(trusted[0]!.observation.strategy.id).toBe('baseline');+ expect(Object.isFrozen(trusted[0]!.observation.strategy)).toBe(true);+ expect(() => recommend([raw], scope)).toThrow('Host-verified');+ });+ it.each([NaN, Infinity, -1, 2])('rejects out-of-domain verifier metric %s', drift => {+ expect(() => observationOf({ ...observation(), checks: { ...observation().checks, drift } })).toThrow();+ });+ it('requires actual measured metrics for learning', () => {+ expect(trustedEvidence([signed(observation({ costCents: null }))], publicKey)).toHaveLength(0);+ });+});++describe('cohort learning and independent heldout gate', () => {+ it('learns advisory cost efficiency only from trusted training evidence', () => {+ const result = recommend(trustedEvidence(training(), publicKey), scope);+ expect(result).toMatchObject({ advisory: true, defaultsChanged: false, selected: { strategy: { id: 'candidate' }, successesPerDollar: 2, samples: 3 } });+ const unsigned = training().map(e => ({ observation: e.observation }));+ expect(recommend(trustedEvidence(unsigned, publicKey), scope).abstained).toBe(true);+ });+ it('never uses heldout observations to propose a strategy', () => {+ expect(recommend(trustedEvidence(heldout(), publicKey), scope).abstained).toBe(true);+ });+ it('isolates policy/evaluator scope and respects latency bounds', () => {+ const verified = trustedEvidence(training(), publicKey);+ expect(recommend(verified, { ...scope, policyHash: digest('other') }).abstained).toBe(true);+ expect(recommend(verified, scope, 99).abstained).toBe(true);+ });+ it('accepts a synthetic complete equal-budget paired experiment without changing defaults', () => {+ expect(evaluate(trustedEvidence([...training(), ...heldout()], publicKey), scope, manifest, 'baseline', 'candidate')).toMatchObject({ eligible: true, delta: 1, pairedResults: 6, noRegression: true, defaultsChanged: false, metaharness: { accept: true } });+ });+ it('rejects an incomplete experiment and a changed corpus manifest', () => {+ expect(() => evaluate(trustedEvidence(heldout().slice(1), publicKey), scope, manifest, 'baseline', 'candidate')).toThrow('Missing');+ const different = manifestOf({ ...manifest, taskHashes: [digest('different'), manifest.taskHashes[1]!] });+ expect(() => evaluate(trustedEvidence(heldout(), publicKey), scope, different, 'baseline', 'candidate')).toThrow();+ });+ it.each(['safety', 'replay', 'adversarial'])('refuses promotion when %s fails', field => {+ const rows = heldout(); const target = rows.find(e => e.observation.strategy.id === 'candidate')!;+ target.observation.checks = { ...target.observation.checks, [field]: false }; rows[rows.indexOf(target)] = signed(target.observation);+ expect(evaluate(trustedEvidence(rows, publicKey), scope, manifest, 'baseline', 'candidate').eligible).toBe(false);+ });+ it('rejects cheaper output that regresses on a previously successful task', () => {+ const rows = heldout(); const target = rows.find(e => e.observation.strategy.id === 'candidate')!;+ target.observation.checks.acceptance = false; rows[rows.indexOf(target)] = signed(target.observation);+ expect(evaluate(trustedEvidence(rows, publicKey), scope, manifest, 'baseline', 'candidate')).toMatchObject({ eligible: false, noRegression: false });+ });+ it('requires matching source identities and admitted budgets', () => {+ for (const patch of [{ sourceHash: digest('other') }, { budgetCents: 251 }]) {+ const rows = heldout(); const target = rows.find(e => e.observation.strategy.id === 'candidate')!;+ rows[rows.indexOf(target)] = signed(observation({ ...target.observation, ...patch }));+ expect(() => evaluate(trustedEvidence(rows, publicKey), scope, manifest, 'baseline', 'candidate')).toThrow('differ');+ }+ });+ it('rejects training overlap, duplicate manifest tasks and duplicate attempts', () => {+ const rows = heldout(); rows.push(signed(observation({ attemptId: digest('overlap'), taskHash: manifest.taskHashes[0]!, strategy: rows[0]!.observation.strategy })));+ expect(() => evaluate(trustedEvidence(rows, publicKey), scope, manifest, 'baseline', 'candidate')).toThrow('overlap');+ expect(() => manifestOf({ ...manifest, taskHashes: [manifest.taskHashes[0], manifest.taskHashes[0]] })).toThrow('unique');+ const first = training()[0]!;+ expect(() => trustedEvidence([first, signed(observation({ ...first.observation, costCents: 1 }))], publicKey)).toThrow('Conflicting');+ });+});++describe('durable quarantine, attestation and RuVector bridge', () => {+ it('keeps observations quarantined until a valid host attestation arrives', () => {+ const r = root(), e = signed(observation());+ expect(recordLearning(r, { observation: e.observation }, publicKey)).toMatchObject({ stored: true, verified: false });+ expect(learningStatus(r, publicKey)).toMatchObject({ verified: 0, quarantined: 1 });+ expect(recordLearning(r, e, publicKey)).toMatchObject({ stored: true, verified: true });+ expect(learningStatus(r, publicKey)).toMatchObject({ verified: 1, quarantined: 0 });+ expect(recordLearning(r, e, publicKey).duplicate).toBe(true);+ expect(JSON.parse(readFileSync(join(r, '.claude-flow/managed-learning/summary.json'), 'utf8'))).toMatchObject({ verified: 1, advisory: true, defaultsChanged: false });+ });+ it('quarantine cannot reserve a future verified attempt ID', () => {+ const r = root(), actual = signed(observation());+ recordLearning(r, { observation: observation({ costCents: 1 }) }, publicKey);+ expect(recordLearning(r, actual, publicKey)).toMatchObject({ stored: true, verified: true });+ expect(learningStatus(r, publicKey)).toMatchObject({ verified: 1, quarantined: 1 });+ expect(trustedEvidence([{ observation: observation({ costCents: 1 }) }, actual], publicKey)).toHaveLength(1);+ });+ it('rejects fake receipts and conflicting immutable outcomes before overwriting', () => {+ const r = root(), e = signed(observation()); recordLearning(r, e, publicKey);+ expect(() => recordLearning(r, signed(observation({ costCents: 1 })), publicKey)).toThrow('Conflicting');+ expect(() => recordLearning(r, { ...e, observation: observation({ sourceHash: digest('tampered') }) }, publicKey)).toThrow('Untrusted');+ expect(learningStatus(r, publicKey).verified).toBe(1);+ });+ it('revalidates reloaded records instead of trusting a modified local file', () => {+ const r = root(); recordLearning(r, signed(observation()), publicKey);+ const p = join(r, '.claude-flow/managed-learning/state.json'); const state = JSON.parse(readFileSync(p, 'utf8'));+ state.records[0].observation.costCents = 1; writeFileSync(p, JSON.stringify(state));+ expect(learningStatus(r, publicKey)).toMatchObject({ verified: 0, quarantined: 1 });+ });+ it('persists advisory recommendations and an eligible comparison without promotion', () => {+ const r = root(); for (const e of [...training(), ...heldout()]) recordLearning(r, e, publicKey);+ expect(recommendLearning(r, scope, publicKey).selected?.strategy.id).toBe('candidate');+ expect(evaluateLearning(r, { scope, manifest, baselineId: 'baseline', candidateId: 'candidate' }, publicKey).eligible).toBe(true);+ expect(learningStatus(r, publicKey)).toMatchObject({ lastEvaluation: { eligible: true }, defaultsChanged: false });+ });+ it('invalidates cached advice when receipts or host verifier change', () => {+ const r = root(); for (const e of [...training(), ...heldout()]) recordLearning(r, e, publicKey);+ recommendLearning(r, scope, publicKey); evaluateLearning(r, { scope, manifest, baselineId: 'baseline', candidateId: 'candidate' }, publicKey);+ const other = generateKeyPairSync('ed25519').publicKey.export({ type: 'spki', format: 'pem' }).toString();+ expect(learningStatus(r, other)).toMatchObject({ verified: 0, lastRecommendation: { abstained: true }, lastEvaluation: null });+ const p = join(r, '.claude-flow/managed-learning/state.json'); const state = JSON.parse(readFileSync(p, 'utf8'));+ state.records.find((e: any) => e.observation.split === 'holdout').observation.costCents = 1;+ state.lastEvaluation = { eligible: true }; writeFileSync(p, JSON.stringify(state));+ expect(learningStatus(r, publicKey).lastEvaluation).toBeNull();+ });+ it('semantic recall revalidates every memory hit and excludes unsigned or heldout rows', async () => {+ const r = root(), rows = training(); for (const e of rows) recordLearning(r, e, publicKey);+ const valid = rows[0]!, forged = { observation: rows[1]!.observation };+ memory.recall.mockResolvedValue({ available: true, rows: [+ { key: digest(valid.observation), content: JSON.stringify(valid), score: .9, namespace: 'managed-workflow-evidence' },+ { key: digest(forged.observation), content: JSON.stringify(forged), score: 1, namespace: 'managed-workflow-evidence' },+ ] });+ const result = await recallLearning(r, scope, publicKey);+ expect(result).toMatchObject({ available: true, advisory: true, similarityIsVerification: false });+ expect(result.evidence).toHaveLength(1);+ expect(result.recommendation.selected?.strategy.id).toBe('candidate');+ expect(memory.recall).toHaveBeenCalledWith(r, expect.objectContaining({ taskType: scope.taskType, allowedIds: expect.arrayContaining([digest(valid.observation)]) }), expect.any(Function));+ });+ it('requires complete scoped hydrated child rows before receipt authentication', async () => {+ const r = root(), e = training()[0]!, key = digest(e.observation);+ recordLearning(r, e, publicKey);+ memory.recall.mockResolvedValue({ available: true, rows: [{ key, content: JSON.stringify(e), score: .5, namespace: 'managed-workflow-evidence' }] });+ expect((await recallLearning(r, scope, publicKey)).evidence).toHaveLength(1);+ memory.recall.mockResolvedValue({ available: true, rows: [{ key, content: JSON.stringify(e).slice(0, 60) + '...', score: .5, namespace: 'managed-workflow-evidence' }] });+ expect((await recallLearning(r, scope, publicKey)).evidence).toHaveLength(0);+ memory.recall.mockRejectedValue(Error('native child terminated'));+ expect(await recallLearning(r, scope, publicKey)).toMatchObject({ available: false, evidence: [], advisory: true });+ });+ it('does not disguise revoked recall authorization as an advisory backend failure', async () => {+ const r = root(); recordLearning(r, training()[0]!, publicKey);+ await expect(recallLearning(r, scope, publicKey, () => false)).rejects.toThrow('policy denied');+ expect(memory.recall).not.toHaveBeenCalled();+ let authorized = true;+ memory.recall.mockImplementation(async () => { authorized = false; throw Error('native child stopped'); });+ await expect(recallLearning(r, scope, publicKey, () => authorized)).rejects.toThrow('policy denied');+ authorized = true;+ memory.recall.mockImplementation(async () => { authorized = false; return { available: true, rows: [] }; });+ await expect(recallLearning(r, scope, publicKey, () => authorized)).rejects.toThrow('policy denied');+ });+ it('refuses symlink state locations and concurrent writer locks', () => {+ const r = root(), other = root(); symlinkSync(other, join(r, '.claude-flow'));+ expect(() => recordLearning(r, signed(observation()), publicKey)).toThrow('symlink');+ const r2 = root(); mkdirSync(join(r2, '.claude-flow/managed-learning'), { recursive: true });+ writeFileSync(join(r2, '.claude-flow/managed-learning/writer.lock'), 'held');+ expect(() => recordLearning(r2, signed(observation()), publicKey)).toThrow();+ });+ it('indexes only verified training evidence through native append-only storage', async () => {+ const r = root(), e = signed(observation()); recordLearning(r, e, publicKey);+ memory.index.mockResolvedValue({ durable: true, hasEmbedding: true });+ expect(await indexLearning(r, digest(e.observation), publicKey)).toMatchObject({ indexed: true, hasEmbedding: true });+ expect(memory.index).toHaveBeenCalledWith(r, expect.objectContaining({ id: digest(e.observation), value: JSON.stringify(e), taskType: scope.taskType }), expect.any(Function));+ memory.index.mockResolvedValue({ durable: false, hasEmbedding: false });+ await expect(indexLearning(r, digest(e.observation), publicKey)).rejects.toThrow('durable');+ });+ it('never writes a vector entry for holdout or unsigned evidence', async () => {+ for (const e of [{ observation: observation() }, signed(observation({ split: 'holdout' }))]) {+ const r = root(); recordLearning(r, e, publicKey);+ await expect(indexLearning(r, digest(e.observation), publicKey)).rejects.toThrow('Verified training');+ }+ expect(memory.index).not.toHaveBeenCalled();+ });+ it('records a bounded batch atomically and preserves replay idempotency', () => {+ const r = root(), rows = training();+ const results = recordLearningBatch(r, rows, publicKey);+ expect(results).toHaveLength(6); expect(results.every(row => row.stored)).toBe(true);+ expect(learningStatus(r, publicKey).verified).toBe(6);+ expect(recordLearningBatch(r, rows, publicKey).every(row => row.duplicate)).toBe(true);+ const before = readFileSync(join(r, '.claude-flow/managed-learning/state.json'), 'utf8');+ const conflict = signed(observation({ ...rows[0]!.observation, costCents: 1 }));+ expect(() => recordLearningBatch(r, [signed(observation({ attemptId: digest('new') })), conflict], publicKey)).toThrow('Conflicting');+ expect(readFileSync(join(r, '.claude-flow/managed-learning/state.json'), 'utf8')).toBe(before);+ });+ it('validates all batch inputs before writing and limits batch size', () => {+ const r = root(), row = signed(observation());+ expect(() => recordLearningBatch(r, [row, { observation: { ...row.observation, verified: true } }], publicKey)).toThrow();+ expect(learningStatus(r, publicKey).observations).toBe(0);+ expect(() => recordLearningBatch(r, [], publicKey)).toThrow('1 to 24');+ expect(() => recordLearningBatch(r, Array(25).fill(row), publicKey)).toThrow('1 to 24');+ });++});diff --git a/v3/@claude-flow/cli/__tests__/managed-memory-isolation.test.ts b/v3/@claude-flow/cli/__tests__/managed-memory-isolation.test.tsnew file mode 100644index 0000000000..5759443cd2--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-memory-isolation.test.ts@@ -0,0 +1,158 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { fork, type ChildProcess } from 'node:child_process';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import ts from 'typescript';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { ManagedMemoryClient, MANAGED_MEMORY_LIMITS } from '../src/services/managed-memory-client.js';+import { executeManagedMemory, type NativeMemoryAdapter } from '../src/services/managed-memory-worker.js';++const id = 'a'.repeat(64), other = 'b'.repeat(64), namespace = 'managed-workflow-evidence';+const roots: string[] = [], clients: ManagedMemoryClient[] = [];+const root = () => { const value = mkdtempSync(join(tmpdir(), 'managed-native-child-')); roots.push(value); return value; };+const request = { operation: 'index', id, value: '{"receipt":"bounded"}', taskType: 'code-review' } as const;+const wire = () => ({ v: 1, requestId: randomUUID(), ...request });+afterEach(() => { for (const c of clients.splice(0)) c.close(); for (const p of roots.splice(0)) rmSync(p, { recursive: true, force: true }); });++function sourceFixture(source: string, timeoutMs = 1000, idleMs = 5000) {+ const cwd = root(), file = join(cwd, 'fixed-host-fixture.mjs');+ writeFileSync(file, source);+ const children: ChildProcess[] = [];+ const launch = vi.fn(() => { const child = fork(file, [], { cwd, execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }); children.push(child); return child; });+ const client = new ManagedMemoryClient({ forkWorker: launch, timeoutMs, idleMs }); clients.push(client);+ return { client, launch, children, cwd };+}+function fixture(code: string, timeoutMs = 1000, idleMs = 5000) {+ return sourceFixture(`let pending; process.on('disconnect', () => process.exit(0)); process.on('message', async input => { if (input.grant === 'execute') { const m = pending; ${code} } else { pending = input; process.send({v:1,requestId:input.requestId,phase:'ready'}); } });`, timeoutMs, idleMs);+}+const goodReply = `process.send({v:1,requestId:m.requestId,ok:true,operation:'index',durable:true,hasEmbedding:true});`;++describe('actual child lifecycle containment', () => {+ it.each([`process.exit(134);`, `process.kill(process.pid, 'SIGKILL');`])('contains a child crash while the parent remains live', async code => {+ const { client, cwd } = fixture(code);+ await expect(client.run(cwd, request)).rejects.toThrow('parent remains available');+ expect(client.stats()).toEqual({ workers: 0, busy: 0 });+ expect(1 + 1).toBe(2);+ });+ it('kills an unresponsive child at a bounded deadline and releases its slot', async () => {+ const { client, cwd, children } = fixture('/* hang */', 100);+ const started = Date.now();+ await expect(client.run(cwd, request)).rejects.toThrow('timed out');+ expect(Date.now() - started).toBeLessThan(1500);+ expect(children[0]?.killed).toBe(true); expect(client.stats().workers).toBe(0);+ });+ it('reuses the same worker for sequential operations instead of reinitializing native modules', async () => {+ const { client, cwd, launch } = fixture(goodReply);+ await expect(client.run(cwd, request)).resolves.toMatchObject({ durable: true, hasEmbedding: true });+ await expect(client.run(cwd, request)).resolves.toMatchObject({ durable: true });+ expect(launch).toHaveBeenCalledTimes(1); expect(client.stats()).toEqual({ workers: 1, busy: 0 });+ });+ it('limits active native work to one global worker and has no unbounded queue', async () => {+ expect(MANAGED_MEMORY_LIMITS.workers).toBe(1);+ const { client, cwd, launch } = fixture('/* hang */', 100);+ const pending = client.run(cwd, request);+ await expect(client.run(cwd, request)).rejects.toThrow('busy');+ await expect(client.run(root(), request)).rejects.toThrow('limit');+ expect(launch).toHaveBeenCalledTimes(1); await expect(pending).rejects.toThrow();+ });+ it('cleans up idle workers and can restart after cleanup', async () => {+ const { client, cwd, launch } = fixture(goodReply, 1000, 20);+ await client.run(cwd, request); await new Promise(r => setTimeout(r, 50));+ expect(client.stats().workers).toBe(0);+ await client.run(cwd, request); expect(launch).toHaveBeenCalledTimes(2);+ });+ it.each([+ `process.send({v:1,requestId:'wrong',ok:true,operation:'index',durable:true,hasEmbedding:true});`,+ `process.send({v:1,requestId:m.requestId,ok:false,error:'secret upstream value'});`,+ `process.send({v:1,requestId:m.requestId,ok:true,operation:'index',durable:true,hasEmbedding:true,unexpected:'credential'});`,+ ])('rejects malformed or uncorrelated child output without leaking raw errors', async code => {+ const { client, cwd } = fixture(code);+ const error = await client.run(cwd, request).catch(e => String(e));+ expect(error).toContain('parent remains available'); expect(error).not.toContain('credential'); expect(error).not.toContain('secret upstream');+ });+ it('does not accept arbitrary commands, module paths or database paths from callers', async () => {+ const { client, cwd, launch } = fixture(goodReply);+ for (const extra of [{ command: 'node' }, { module: './evil.js' }, { dbPath: '/tmp/other.db' }, { root: '/tmp' }]) await expect(client.run(cwd, { ...request, ...extra })).rejects.toThrow('Invalid');+ expect(launch).not.toHaveBeenCalled();+ });+ it('checks payload bounds before spawning native work', async () => {+ const { client, cwd, launch } = fixture(goodReply);+ await expect(client.run(cwd, { ...request, value: 'x'.repeat(8193) })).rejects.toThrow('Invalid');+ await expect(client.run(cwd, { operation: 'recall', taskType: 'code-review', allowedIds: Array(501).fill(id) })).rejects.toThrow('Invalid');+ expect(launch).not.toHaveBeenCalled();+ });+ it('rechecks host authority after worker initialization and before admitting native writes', async () => {+ const source = `import {writeFileSync} from 'node:fs'; let pending; process.on('disconnect',()=>process.exit(0)); process.on('message', input=>{ if(input.operation){pending=input;process.send({v:1,requestId:input.requestId,phase:'ready'});} else if(input.grant==='execute'){process.send({v:1,requestId:pending.requestId,phase:'before-write'});} else if(input.grant==='write'){writeFileSync('write-admitted','yes');process.send({v:1,requestId:pending.requestId,ok:true,operation:'index',durable:true,hasEmbedding:true});}});`;+ for (const deniedAt of [3, 4]) {+ const { client, cwd } = sourceFixture(source); let calls = 0;+ await expect(client.run(cwd, request, () => ++calls < deniedAt)).rejects.toThrow('policy denied');+ expect(existsSync(join(cwd, 'write-admitted'))).toBe(false);+ }+ });+ it('reports in-flight revocation as an ambiguous admitted write, never verified success', async () => {+ const source = `import {writeFileSync} from 'node:fs'; let pending; process.on('disconnect',()=>process.exit(0)); process.on('message', input=>{ if(input.operation){pending=input;process.send({v:1,requestId:input.requestId,phase:'ready'});} else if(input.grant==='execute'){process.send({v:1,requestId:pending.requestId,phase:'before-write'});} else if(input.grant==='write'){writeFileSync('write-admitted','yes');process.send({v:1,requestId:pending.requestId,ok:true,operation:'index',durable:true,hasEmbedding:true});}});`;+ const { client, cwd } = sourceFixture(source); let calls = 0;+ await expect(client.run(cwd, request, () => ++calls < 5)).rejects.toThrow('admitted write may have completed');+ expect(existsSync(join(cwd, 'write-admitted'))).toBe(true);+ });+ it('denies a revoked operation before spawning a child', async () => {+ const { client, cwd, launch } = fixture(goodReply);+ await expect(client.run(cwd, request, () => false)).rejects.toThrow('policy denied');+ expect(launch).not.toHaveBeenCalled();+ });+ it('runs the emitted fixed worker on supported Node versions without loading native code for invalid input', async () => {+ const cwd = root(), entry = join(cwd, 'fixed-worker.mjs');+ const source = readFileSync(new URL('../src/services/managed-memory-worker.ts', import.meta.url), 'utf8');+ writeFileSync(entry, ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText);+ const child = fork(entry, [], { cwd, execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });+ try {+ const response = new Promise<any>((resolve, reject) => { child.once('message', resolve); child.once('error', reject); child.once('exit', () => reject(new Error('Fixed worker exited before response'))); });+ child.send({ operation: 'eval', command: 'ignored' });+ await expect(response).resolves.toEqual({ v: 1, ok: false, error: 'invalid-request' });+ } finally { child.kill('SIGKILL'); }+ });+});++describe('fixed native operations and full hydration', () => {+ function adapter() {+ return { getEntry: vi.fn(), storeEntry: vi.fn(), searchEntries: vi.fn() } satisfies NativeMemoryAdapter;+ }+ it('keeps requireNative append-only writes and confirms the exact row after persistence', async () => {+ const a = adapter(); a.getEntry.mockResolvedValueOnce({ success: true, found: false }).mockResolvedValueOnce({ success: true, found: true, entry: { key: id, namespace, content: request.value, hasEmbedding: true } });+ a.storeEntry.mockResolvedValue({ success: true });+ expect(await executeManagedMemory(wire(), a, '/project/.swarm/memory.db')).toMatchObject({ durable: true, hasEmbedding: true });+ expect(a.storeEntry).toHaveBeenCalledWith(expect.objectContaining({ requireNative: true, appendOnly: true, upsert: false, namespace, dbPath: '/project/.swarm/memory.db' }));+ });+ it('recognizes an existing exact native row without rewriting or claiming missing vectors', async () => {+ const a = adapter(); a.getEntry.mockResolvedValue({ success: true, found: true, entry: { key: id, namespace, content: request.value, hasEmbedding: false } });+ expect(await executeManagedMemory(wire(), a, '/project/.swarm/memory.db')).toMatchObject({ durable: true, hasEmbedding: false });+ expect(a.storeEntry).not.toHaveBeenCalled();+ });+ it('refuses a conflicting native row and uncertain persistence', async () => {+ const a = adapter(); a.getEntry.mockResolvedValue({ success: true, found: true, entry: { key: id, namespace, content: 'different' } });+ await expect(executeManagedMemory(wire(), a, '/project/.swarm/memory.db')).rejects.toThrow('conflicting');+ a.getEntry.mockResolvedValue({ success: true, found: false }); a.storeEntry.mockResolvedValue({ success: true, persistWarning: 'uncertain' });+ await expect(executeManagedMemory(wire(), a, '/project/.swarm/memory.db')).rejects.toThrow('persistence');+ });+ it('never calls the native append after a denied host write grant', async () => {+ const a = adapter(); a.getEntry.mockResolvedValue({ success: true, found: false });+ await expect(executeManagedMemory(wire(), a, '/project/.swarm/memory.db', async () => { throw Error('revoked'); })).rejects.toThrow('revoked');+ expect(a.storeEntry).not.toHaveBeenCalled();+ });+ it('hydrates full rows instead of forwarding search display previews', async () => {+ const a = adapter(), content = JSON.stringify({ signed: 'receipt'.repeat(100) });+ a.searchEntries.mockResolvedValue({ success: true, results: [{ key: id, namespace, score: .8, content: content.slice(0, 60) + '...' }, { key: other, namespace, score: .9 }] });+ a.getEntry.mockResolvedValue({ success: true, found: true, entry: { key: id, namespace, content } });+ const result = await executeManagedMemory({ v: 1, requestId: randomUUID(), operation: 'recall', taskType: 'code-review', allowedIds: [id] }, a, '/project/.swarm/memory.db');+ expect(result).toMatchObject({ available: true, rows: [{ key: id, namespace, score: .8, content }] });+ expect(a.getEntry).toHaveBeenCalledTimes(1);+ });+ it('rejects wrong scoped or oversized hydrated rows', async () => {+ const a = adapter(); a.searchEntries.mockResolvedValue({ success: true, results: [{ key: id, namespace, score: .8 }] });+ for (const entry of [{ key: id, namespace: 'other', content: '{}' }, { key: id, namespace, content: 'x'.repeat(8193) }]) {+ a.getEntry.mockResolvedValue({ success: true, found: true, entry });+ expect(await executeManagedMemory({ v: 1, requestId: randomUUID(), operation: 'recall', taskType: 'code-review', allowedIds: [id] }, a, '/project/.swarm/memory.db')).toMatchObject({ rows: [] });+ }+ });+});diff --git a/v3/@claude-flow/cli/__tests__/managed-mod-integration.test.ts b/v3/@claude-flow/cli/__tests__/managed-mod-integration.test.tsnew file mode 100644index 0000000000..f76e1e2b9c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-mod-integration.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';+import { readOptions } from '../../../../plugins/ruflo-agent/hooks/options';+import { managedCapabilities, managedVerdict, MANAGED_TOOLS } from '../../../../plugins/ruflo-agent/hooks/managed';+import { register } from '../../../../plugins/ruflo-agent/hooks/register';+import { newStats, statusText } from '../../../../plugins/ruflo-agent/hooks/status';+import { parseModStatus } from '../../../../plugins/ruflo-console/hooks/data/mods';+import { answer as workflowAnswer } from '../../../../plugins/ruflo-workflows/hooks/command';+import { managedAgentTools } from '../src/mcp-tools/managed-agent-tools.js';++const create = 'mcp__plugin_ruflo-core_ruflo__managed_agent_create';+const valid = { dynamicWorkflows: true, budgetCents: '2500', predefinedAgents: ['agent_abc'] };+const enabled = readOptions({ managedWorkflows: 'on' });++describe('mod admission', () => {+ it('disables dynamic cloud creation by default', () => {+ expect(managedVerdict(create, valid, readOptions(undefined))).toContain('off');+ });+ it('keeps the dynamic gate with secret guard off', () => {+ expect(managedVerdict(create, valid, readOptions({ guard: 'off' }))).toContain('off');+ });+ it('allows only explicitly enabled bounded creation', () => {+ expect(managedVerdict(create, valid, enabled)).toBeUndefined();+ expect(managedVerdict(create, { ...valid, budgetCents: '2501' }, enabled)).toContain('budget');+ });+ it.each([undefined, '', '0', '01', '25.00', '1e3', 2500, '9999999999'])('rejects malformed budget %s', budgetCents => {+ expect(managedVerdict(create, { ...valid, budgetCents }, enabled)).toContain('budget');+ });+ it.each(['nope', '0', '-1', '1.00', 500])('invalid configured cap fails closed: %s', maxBudgetCents => {+ const opts = readOptions({ managedWorkflows: 'on', maxBudgetCents } as any);+ expect(opts.maxBudgetCents).toBe(0);+ expect(managedVerdict(create, valid, opts)).toContain('budget');+ });+ it('requires predefined agents unless inline use was explicitly enabled', () => {+ const input = { dynamicWorkflows: true, budgetCents: '100' };+ expect(managedVerdict(create, input, enabled)).toContain('predefined');+ expect(managedVerdict(create, input, readOptions({ managedWorkflows: 'on', allowInlineAgents: 'on' }))).toBeUndefined();+ });+ it('reads flat and nested envelopes and rejects ambiguous input', () => {+ expect(managedVerdict(create, { input: valid }, enabled)).toBeUndefined();+ expect(managedVerdict(create, { arguments: valid }, enabled)).toBeUndefined();+ expect(managedVerdict(create, { input: {}, ...valid }, enabled)).toContain('malformed');+ expect(managedVerdict(create, { input: 'invalid' }, enabled)).toContain('malformed');+ });+ it('does not alter legacy creation or unrelated tools', () => {+ expect(managedVerdict(create, {}, readOptions(undefined))).toBeUndefined();+ expect(managedVerdict('unrelated', valid, readOptions(undefined))).toBeUndefined();+ });+ it('rejects unrestricted networking and malformed workflow opt-in', () => {+ expect(managedVerdict(create, { ...valid, networking: 'unrestricted' }, enabled)).toContain('network');+ expect(managedVerdict(create, { ...valid, dynamicWorkflows: 'true' }, enabled)).toContain('boolean');+ });+});++describe('capability discovery and console contract', () => {+ it('keeps plugin capability inventory aligned with actual MCP registration', () => {+ expect([...MANAGED_TOOLS].sort()).toEqual(managedAgentTools.map(t => t.name).sort());+ });+ it('reports runtime configuration without provider calls or key requirement', async () => {+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ try {+ const caps = await managedAgentTools.find(t => t.name === 'managed_agent_capabilities')!.handler({});+ expect(caps).toMatchObject({ networkCalled: false, betaAccess: 'unknown', remoteHealth: 'unknown' });+ expect(fetch).not.toHaveBeenCalled();+ } finally { vi.unstubAllGlobals(); }+ });+ it('reports actual full registry names without claiming readiness', () => {+ const caps = managedCapabilities([create], enabled);+ expect(caps).toContain(create); expect(caps).toContain('Missing:');+ expect(caps).toContain('not authorization');+ });+ it('writes policy metadata that the existing console parser can read', () => {+ const row = parseModStatus('agent-mod', statusText({ ...newStats(), lastDenied: 'policy', blocked: 1 }, enabled, 1000));+ expect(row).toMatchObject({ modVersion: '0.4.0', lastDenied: 'policy', blocked: 1 });+ expect(row?.summary).toContain('budget 2500 cents');+ expect(row?.summary?.length).toBeLessThanOrEqual(120);+ });+ it('workflow mod distinguishes missing, registered and unavailable discovery', async () => {+ const deps = { opts: { guard: true }, stats: { checked: 0, blocked: 0, seen: {} } } as any;+ expect(await workflowAnswer('managed', { ...deps, tools: async () => [] })).toContain('not registered');+ expect(await workflowAnswer('managed', { ...deps, tools: async () => ['managed_agent_capabilities'] })).toContain('does not establish authorization');+ expect(await workflowAnswer('managed', { ...deps, tools: async () => { throw Error('private'); } })).toContain('unknown');+ });+});++describe('registered hook execution', () => {+ function harness(options: object = {}) {+ const hooks = new Map<string, any>();+ const files = new Map<string, string>();+ const list = vi.fn().mockResolvedValue([]);+ (register as any)((name: string, ...args: any[]) => hooks.set(name, args.at(-1)), options);+ const $ = { fs: { write: async (p: string, t: string) => { files.set(p, t); } }, session: { root: async () => '/work' }, clock: { now: async () => 1000 }, command: { register: vi.fn() }, tool: { list } };+ return { hooks, $, files };+ }+ it('denies before dispatch, persists counters and never escalates a downstream deny', async () => {+ const h = harness({ guard: 'off' });+ await h.hooks.get('session.start')(h.$, {}, async () => ({}));+ const next = vi.fn();+ expect(await h.hooks.get('tool.call')(h.$, { tool: create, ...valid }, next)).toHaveProperty('deny');+ expect(next).not.toHaveBeenCalled();+ expect(JSON.parse(h.files.get('/work/.claude-flow/agent-mod/status.json')!)).toMatchObject({ blocked: 1, calls: 1 });+ const h2 = harness({ managedWorkflows: 'on' });+ expect(await h2.hooks.get('tool.call')(h2.$, { tool: create, ...valid }, async () => ({ deny: 'host policy' }))).toEqual({ deny: 'host policy' });+ });+ it('refreshes discovery locally and distinguishes registry failure', async () => {+ const h = harness(); const command = h.hooks.get('command.run');+ expect((await command(h.$, { args: 'capabilities' })).text).toContain('none');+ h.$.tool.list.mockResolvedValueOnce([{ name: create }]);+ expect((await command(h.$, { args: 'capabilities' })).text).toContain(create);+ h.$.tool.list.mockRejectedValueOnce(Error('secret error body'));+ expect((await command(h.$, { args: 'capabilities' })).text).toBe('Tool discovery unavailable; managed runtime readiness is unknown.');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/managed-run-collector.test.ts b/v3/@claude-flow/cli/__tests__/managed-run-collector.test.tsnew file mode 100644index 0000000000..83229ea40e--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-run-collector.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it, vi } from 'vitest';+import { COLLECTOR_LIMITS, ManagedRunCollector, type ManagedCollectorTransport } from '../src/services/managed-run-collector.js';+import type { ManagedEvent } from '../src/services/managed-workflows.js';++const event = (id: string, type: string, more: Record<string, unknown> = {}): ManagedEvent => ({ id, type, processed_at: '2026-10-24T00:00:00Z', ...more });+const idle = (id: string, reason = 'end_turn') => event(id, 'session.status_idle', { stop_reason: { type: reason } });+const transport = (events: ManagedEvent[] = [], status = 'idle') => ({ readEvents: vi.fn(async (_since?: string) => events), readSession: vi.fn(async () => ({ status })) });++describe('one explicit collector per session', () => {+ it('deduplicates simultaneous readers and caches only successful results', async () => {+ const collector = new ManagedRunCollector();+ let finish!: (events: ManagedEvent[]) => void;+ const t = transport(); t.readEvents.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const a = collector.refresh('sesn_a', t), b = collector.refresh('sesn_a', t);+ await Promise.resolve();+ expect(t.readEvents).toHaveBeenCalledTimes(1); expect(t.readSession).toHaveBeenCalledTimes(1);+ finish([idle('done')]);+ const [one, two] = await Promise.all([a, b]);+ expect(one).toEqual(two); expect(one).not.toBe(two);+ one.snapshot.status = 'tampered'; one.events.length = 0;+ expect((await collector.refresh('sesn_a', t)).snapshot.status).toBe('idle');+ expect(t.readEvents).toHaveBeenCalledTimes(1);+ });+ it('performs zero background work or snapshot-triggered provider reads', async () => {+ const timer = vi.spyOn(globalThis, 'setTimeout');+ try {+ let now = 0; const collector = new ManagedRunCollector({ now: () => now }), t = transport();+ await collector.refresh('sesn_a', t);+ now = 1_000_000; collector.snapshots(); collector.snapshots();+ expect(t.readEvents).toHaveBeenCalledTimes(1); expect(t.readSession).toHaveBeenCalledTimes(1);+ expect(timer).not.toHaveBeenCalled();+ } finally { timer.mockRestore(); }+ });+ it('uses inclusive watermark after TTL and handles processed queued events', async () => {+ let now = 0; const c = new ManagedRunCollector({ now: () => now }), t = transport([event('q', 'user.message', { processed_at: null })]);+ expect((await c.refresh('sesn_a', t)).events).toHaveLength(1);+ now = 1001; t.readEvents.mockResolvedValueOnce([event('q', 'user.message'), idle('done')]);+ const result = await c.refresh('sesn_a', t);+ expect(result.snapshot.providerFinished).toBe(true); expect(result.events).toHaveLength(2);+ now = 2002; t.readEvents.mockResolvedValueOnce([event('q', 'user.message'), idle('done')]); await c.refresh('sesn_a', t);+ expect(t.readEvents.mock.calls[2]?.[0]).toBe('2026-10-24T00:00:00Z');+ });+ it('retries failed singleflights and never invents an empty success', async () => {+ const c = new ManagedRunCollector(), t = transport();+ t.readEvents.mockRejectedValueOnce(Error('provider unavailable'));+ await expect(Promise.all([c.refresh('sesn_a', t), c.refresh('sesn_a', t)])).rejects.toThrow('unavailable');+ expect(c.snapshots()).toEqual([]);+ expect((await c.refresh('sesn_a', t)).snapshot.status).toBe('idle');+ expect(t.readEvents).toHaveBeenCalledTimes(2);+ });+ it('does not forget a running refresh', async () => {+ const c = new ManagedRunCollector(); let finish!: () => void;+ const t = transport(); t.readEvents.mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve([]); }));+ const pending = c.refresh('sesn_a', t); await Promise.resolve();+ expect(c.forget('sesn_a')).toBe(false); finish(); await pending;+ expect(c.forget('sesn_a')).toBe(true); expect(c.snapshots()).toEqual([]);+ });+});++describe('provider progress is distinct from verification', () => {+ it('replays 1,000 workers with duplicate reconnects, budget pause and failures', async () => {+ let now = 0; const c = new ManagedRunCollector({ now: () => now });+ const events: ManagedEvent[] = [event('run', 'workflow_run.created', { workflow_run_id: 'wrun_a', phases: [{ id: 'phase_a', name: 'Review' }] }), event('phase', 'workflow_run.phase_started', { workflow_run_id: 'wrun_a', workflow_run_phase_id: 'phase_a' })];+ for (let i = 0; i < 1000; i++) {+ const thread = { session_thread_id: `thread_${i}`, workflow_run_id: 'wrun_a', workflow_run_phase_id: 'phase_a' };+ events.push(event(`create_${i}`, 'session.thread_created', thread));+ events.push(event(`working_${i}`, 'session.thread_status_running', thread));+ events.push(event(`end_${i}`, 'session.thread_status_terminated', { ...thread, ...(i < 7 ? { error: { type: 'worker_failure' } } : {}) }));+ }+ events.push(event('ask', 'agent.mcp_tool_use', { evaluated_permission: 'ask' }), idle('pause', 'budget_reached'));+ const t = transport([...events, ...events]);+ t.readSession.mockResolvedValue({ status: 'idle', budget: { max_list_cost: { amount: '2500', currency: 'USD' } }, usage: { list_cost: { amount: '2503', currency: 'USD' } } } as any);+ const first = await c.refresh('sesn_a', t);+ expect(first.snapshot).toMatchObject({ threadCount: 1000, threadCounts: { ended: 993, failed: 7, idle: 0, running: 0 }, stopReason: 'budget_reached', providerFinished: false, workersInspected: false, acceptancePassed: false, verification: 'unverified', budgetCents: 2500, listCostCents: 2503, observedFailures: 7, blockedEventIds: ['ask'] });+ expect(first.snapshot.threads).toHaveLength(60); expect(first.events).toHaveLength(events.length);+ const nextPage = c.page('sesn_a', 60)!;+ expect(nextPage.threadOffset).toBe(60); expect(nextPage.threads[0]?.id).toBe('thread_60');+ expect(nextPage.threadCount).toBe(1000); expect(nextPage.threadCounts).toEqual(first.snapshot.threadCounts);+ expect(nextPage.updatedMs).toBe(first.snapshot.updatedMs); expect(t.readEvents).toHaveBeenCalledTimes(1);+ now = 1001; const replay = await c.refresh('sesn_a', t);+ expect(replay.snapshot.threadCounts).toEqual(first.snapshot.threadCounts);+ expect(replay.events).toHaveLength(first.events.length);+ expect(replay.snapshot.runs[0]?.phases).toEqual([{ id: 'phase_a', name: 'Review', status: 'running' }]);+ now = 2002;+ t.readEvents.mockResolvedValueOnce([event('confirm', 'user.tool_confirmation', { tool_use_id: 'ask', result: 'deny' }), event('phaseDone', 'workflow_run.phase_ended', { workflow_run_id: 'wrun_a', workflow_run_phase_id: 'phase_a' }), event('runDone', 'workflow_run.status_ended', { workflow_run_id: 'wrun_a', result: { type: 'completed' } })]);+ const ended = await c.refresh('sesn_a', t);+ expect(ended.snapshot.providerFinished).toBe(false); expect(ended.snapshot.blockedEventIds).toEqual([]);+ now = 3003; t.readEvents.mockResolvedValueOnce([idle('final')]);+ const done = await c.refresh('sesn_a', t);+ expect(done.snapshot.providerFinished).toBe(true); expect(done.snapshot.acceptancePassed).toBe(false); expect(done.snapshot.verification).toBe('unverified');+ });+ it('never reports interrupted work as provider completion', async () => {+ const c = new ManagedRunCollector();+ const result = await c.refresh('sesn_a', transport([event('int', 'user.interrupt'), idle('done')]));+ expect(result.snapshot.providerFinished).toBe(false);+ });+ it('current provider state prevents stale history claiming finished', async () => {+ const result = await new ManagedRunCollector().refresh('sesn_a', transport([idle('old')], 'running'));+ expect(result.snapshot.providerFinished).toBe(false);+ });+ it('tracks custom approvals and clears replies without exposing tool inputs', async () => {+ const c = new ManagedRunCollector({ ttlMs: 0 }), t = transport([event('call', 'agent.custom_tool_use', { input: { token: 'not-for-snapshot' } }), idle('wait', 'requires_action')]);+ const blocked = await c.refresh('sesn_a', t);+ expect(blocked.snapshot.blockedEventIds).toEqual(['call']); expect(JSON.stringify(blocked.snapshot)).not.toContain('not-for-snapshot');+ t.readEvents.mockResolvedValueOnce([event('reply', 'user.custom_tool_result', { custom_tool_use_id: 'call' })]);+ expect((await c.refresh('sesn_a', t)).snapshot.blockedEventIds).toEqual([]);+ });+});++describe('resource and integrity bounds', () => {+ it('refuses excess live sessions but evicts an inactive session', async () => {+ const c = new ManagedRunCollector();+ for (let i = 0; i < 6; i++) await c.refresh(`sesn_${i}`, transport([], 'running'));+ await expect(c.refresh('sesn_more', transport())).rejects.toThrow('limit');+ expect(c.forget('sesn_0')).toBe(true);+ await c.refresh('sesn_idle', transport());+ await c.refresh('sesn_more', transport());+ expect(c.snapshots()).toHaveLength(6);+ });+ it('rejects conflicting processed event IDs without changing the snapshot', async () => {+ const c = new ManagedRunCollector({ ttlMs: 0 }), t = transport([idle('same')]);+ const first = await c.refresh('sesn_a', t);+ t.readEvents.mockResolvedValueOnce([event('same', 'session.status_running')]);+ await expect(c.refresh('sesn_a', t)).rejects.toThrow('Conflicting');+ expect(c.snapshots()[0]).toEqual(first.snapshot);+ });+ it('enforces event and byte bounds before retaining partial batches', async () => {+ const c = new ManagedRunCollector();+ await expect(c.refresh('sesn_events', transport(Array.from({ length: COLLECTOR_LIMITS.events + 1 }, (_, i) => event(`e_${i}`, 'agent.thinking'))))).rejects.toThrow('limit');+ expect(c.snapshots()).toEqual([]);+ const huge = event('big', 'agent.thinking', { data: 'x'.repeat(COLLECTOR_LIMITS.bytes + 1) });+ await expect(c.refresh('sesn_bytes', transport([huge]))).rejects.toThrow('limit');+ expect(c.snapshots()).toEqual([]);+ });+ it.each(['', '../session', 'a'.repeat(129)])('refuses malformed session ID %s', async id => {+ const t = transport(); await expect(new ManagedRunCollector().refresh(id, t)).rejects.toThrow('Invalid');+ expect(t.readEvents).not.toHaveBeenCalled();+ });+ it('worker pages never trigger reads and reject invalid offsets', () => {+ const c = new ManagedRunCollector();+ expect(c.page('sesn_missing', 0)).toBeUndefined();+ for (const offset of [-1, 0.5, 10_000, Infinity]) expect(() => c.page('sesn_missing', offset)).toThrow('offset');+ });+});++it('deduplicates semantically identical event replay despite JSON property order', async () => {+ const c = new ManagedRunCollector({ ttlMs: 0 });+ const original = event('same', 'agent.tool_use', { input: { first: 1, second: 2 } });+ const t = transport([original]); await c.refresh('sesn_a', t);+ t.readEvents.mockResolvedValueOnce([{ input: { second: 2, first: 1 }, processed_at: original.processed_at, type: original.type, id: original.id }]);+ expect((await c.refresh('sesn_a', t)).events).toHaveLength(1);+});diff --git a/v3/@claude-flow/cli/__tests__/managed-run-store.test.ts b/v3/@claude-flow/cli/__tests__/managed-run-store.test.tsnew file mode 100644index 0000000000..8779559cda--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-run-store.test.ts@@ -0,0 +1,80 @@+import { afterEach, expect, it, vi } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { collectWithLease, executeManagedControl, publishManagedSnapshot } from '../src/services/managed-run-store.js';+import type { ManagedRunSnapshot } from '../src/services/managed-run-collector.js';++const roots: string[] = [];+const root = () => { const p = mkdtempSync(join(tmpdir(), 'managed-run-store-')); roots.push(p); return p; };+afterEach(() => { for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }); });+const sample = (): ManagedRunSnapshot => ({ sessionId: 'sesn_a', status: 'idle', stopReason: 'end_turn', budgetCents: 100, listCostCents: 11, providerFinished: true, workersInspected: false, acceptancePassed: false, verification: 'unverified', runs: [], threads: [], threadOffset: 0, threadCount: 0, threadCounts: { running: 0, ended: 0, failed: 0, idle: 0 }, blockedEventIds: [], observedFailures: 0, updatedMs: 1000 });+function controls() {+ return { policy: vi.fn(() => ({ enabled: true, sessions: ['sesn_a'] })), read: vi.fn(async () => ({ status: 'running' })), inspect: vi.fn(async () => sample()), interrupt: vi.fn(async () => ({})), terminate: vi.fn(async () => ({})) };+}++it('shares one collection and holds a real exclusive OS lease across processes', async () => {+ const r = root(); let done!: (v: object) => void;+ const operation = vi.fn(() => new Promise<object>(resolve => { done = resolve; }));+ const first = collectWithLease(r, 'sesn_a', operation), second = collectWithLease(r, 'sesn_a', operation);+ await Promise.resolve();+ const path = join(r, '.claude-flow/managed-workflows/sesn_a.collector.lock');+ const child = spawnSync(process.execPath, ['-e', 'try { require("node:fs").openSync(process.argv[1], "wx"); process.exit(1); } catch { process.exit(0); }', path]);+ expect(child.status).toBe(0); expect(operation).toHaveBeenCalledTimes(1);+ done({ events: 1000 });+ expect(await first).toEqual(await second);+});+it('fails closed on a preexisting collector lease instead of starting another poller', async () => {+ const r = root(); mkdirSync(join(r, '.claude-flow/managed-workflows'), { recursive: true });+ writeFileSync(join(r, '.claude-flow/managed-workflows/sesn_a.collector.lock'), 'stale');+ const operation = vi.fn(); await expect(collectWithLease(r, 'sesn_a', operation)).rejects.toThrow('leased');+ expect(operation).not.toHaveBeenCalled();+});+it('publishes bounded display facts that never claim acceptance', () => {+ const r = root(); publishManagedSnapshot(r, sample());+ const value = JSON.parse(readFileSync(join(r, '.claude-flow/managed-workflows/snapshot.json'), 'utf8'));+ expect(value.sessions[0]).toMatchObject({ providerFinished: true, workersInspected: false, acceptancePassed: false, verification: 'unverified' });+ expect(JSON.stringify(value)).not.toContain('api-key');+});+it('refuses caller approval flags and invalid session or worker-page inputs before provider reads', async () => {+ for (const input of [{ sessionId: 'sesn_a', action: 'terminate', approved: true }, { sessionId: '../x', action: 'inspect' }, { sessionId: 'sesn_a', action: 'inspect', threadOffset: -1 }]) {+ const c = controls(); await expect(executeManagedControl(input, c)).rejects.toThrow('Invalid'); expect(c.read).not.toHaveBeenCalled();+ }+});+it('refuses actions without fresh host policy permission', async () => {+ const c = controls(); c.policy.mockReturnValue({ enabled: false, sessions: ['sesn_a'] });+ await expect(executeManagedControl({ sessionId: 'sesn_a', action: 'terminate' }, c)).rejects.toThrow('denies');+ expect(c.read).not.toHaveBeenCalled(); expect(c.terminate).not.toHaveBeenCalled();+});+it('checks policy again after a provider read, defeating stale-console permission', async () => {+ const c = controls(); c.policy.mockReturnValueOnce({ enabled: true, sessions: ['sesn_a'] }).mockReturnValueOnce({ enabled: false, sessions: [] });+ await expect(executeManagedControl({ sessionId: 'sesn_a', action: 'terminate' }, c)).rejects.toThrow('changed');+ expect(c.read).toHaveBeenCalledTimes(1); expect(c.terminate).not.toHaveBeenCalled();+});+it('always reads provider state and leaves interruption distinct from termination', async () => {+ const c = controls();+ expect(await executeManagedControl({ sessionId: 'sesn_a', action: 'interrupt' }, c)).toMatchObject({ interruptRequested: true, cancellationConfirmed: false });+ expect(c.read).toHaveBeenCalledTimes(1); expect(c.interrupt).toHaveBeenCalledTimes(1);+ expect(await executeManagedControl({ sessionId: 'sesn_a', action: 'terminate' }, c)).toMatchObject({ cancellationConfirmed: true });+ expect(c.read).toHaveBeenCalledTimes(2); expect(c.terminate).toHaveBeenCalledTimes(1);+});+it('never confirms failed deletion or acts on an unknown provider state', async () => {+ const c = controls(); c.terminate.mockRejectedValueOnce(Error('provider failed'));+ await expect(executeManagedControl({ sessionId: 'sesn_a', action: 'terminate' }, c)).rejects.toThrow('provider failed');+ c.read.mockResolvedValueOnce({ status: 'unknown' });+ await expect(executeManagedControl({ sessionId: 'sesn_a', action: 'terminate' }, c)).rejects.toThrow('Unknown');+ expect(c.terminate).toHaveBeenCalledTimes(1);+});+it('inspects the requested worker page through the same checked dispatch', async () => {+ const c = controls(); await executeManagedControl({ sessionId: 'sesn_a', action: 'inspect', threadOffset: 60 }, c);+ expect(c.inspect).toHaveBeenCalledWith('sesn_a', 60); expect(c.interrupt).not.toHaveBeenCalled();+});++it('does not share an in-flight collection across credential scopes', async () => {+ const r = root(); let done!: () => void;+ const first = collectWithLease(r, 'sesn_a', () => new Promise<void>(resolve => { done = resolve; }), 'host-one');+ await Promise.resolve();+ await expect(collectWithLease(r, 'sesn_a', async () => ({}), 'host-two')).rejects.toThrow('credential scope');+ done(); await first;+});diff --git a/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts b/v3/@claude-flow/cli/__tests__/managed-workflows.test.tsnew file mode 100644index 0000000000..67eb9f57c5--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts@@ -0,0 +1,292 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { managedAgentTools } from '../src/mcp-tools/managed-agent-tools.js';+import { dynamicConfig, ManagedProgress, readManagedEvents, type ManagedEvent } from '../src/services/managed-workflows.js';++const event = (id: string, type: string, extra = {}): ManagedEvent => ({ id, type, processed_at: '2026-10-24T12:00:00Z', ...extra });+const idle = (id: string, reason = 'end_turn') => event(id, 'session.status_idle', { stop_reason: { type: reason } });+const call = (name: string, input: Record<string, unknown> = {}) => managedAgentTools.find(t => t.name === name)!.handler(input) as Promise<any>;+const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status });+let testRoot = '';+let fetchMock: ReturnType<typeof vi.fn>;++beforeEach(() => {+ testRoot = mkdtempSync(join(tmpdir(), 'managed-api-'));+ vi.stubEnv('CLAUDE_FLOW_CWD', testRoot);+ vi.stubEnv('ANTHROPIC_API_KEY', 'test-key-do-not-log');+ vi.stubEnv('RUFLO_MANAGED_AGENTS_BASE_URL', 'https://api.anthropic.com');+ fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock);+});+afterEach(() => { rmSync(testRoot, { recursive: true, force: true }); vi.useRealTimers(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); });++describe('dynamic workflow admission', () => {+ it('keeps legacy create unchanged and dynamic off', () => {+ expect(dynamicConfig({})).toMatchObject({ enabled: false, networking: { type: 'unrestricted' } });+ });+ it.each([undefined, '', '0', '01', '-1', '25.00', '1e3', 2500, '1000000000'])('rejects invalid cents %s before side effects', async budgetCents => {+ expect((await call('managed_agent_create', { dynamicWorkflows: true, budgetCents })).success).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('builds explicit bounded workflow config with restricted agents', () => {+ expect(dynamicConfig({ dynamicWorkflows: true, budgetCents: '2500', predefinedAgents: ['agent_abc'] })).toMatchObject({+ budget: { type: 'limit', max_list_cost: { amount: '2500', currency: 'USD' } },+ multiagent: { type: 'multiagent_20261001', subagents: { type: 'disabled' }, workflows: { inline_agents: { type: 'disabled' }, predefined_agents: ['agent_abc'] } },+ networking: { type: 'limited', allowed_hosts: [] },+ });+ });+ it.each([{ networking: 'unrestricted' }, { allowedHosts: ['*'] }, { allowedHosts: ['https://example.com'] }, { predefinedAgents: [] }, { predefinedAgents: ['../../x'] }, { dynamicWorkflows: 'true' }])('rejects malformed policy %j', async bad => {+ expect((await call('managed_agent_create', { dynamicWorkflows: true, budgetCents: '2500', ...bad })).success).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('attaches budget at session creation and multiagent to agent', async () => {+ fetchMock.mockResolvedValueOnce(json({ id: 'agent_a' })).mockResolvedValueOnce(json({ id: 'env_a' })).mockResolvedValueOnce(json({ id: 'sesn_a' }));+ const result = await call('managed_agent_create', { dynamicWorkflows: true, budgetCents: '2500', allowedHosts: ['github.com'] });+ expect(result.success).toBe(true);+ const bodies = fetchMock.mock.calls.map(c => JSON.parse(c[1].body));+ expect(bodies[0].multiagent.type).toBe('multiagent_20261001');+ expect(bodies[1].config.networking).toEqual({ type: 'limited', allowed_hosts: ['github.com'] });+ expect(bodies[2].budget.max_list_cost.amount).toBe('2500');+ });+});++describe('provider lifecycle evidence', () => {+ it('does not mistake an open workflow for completion', () => {+ const p = new ManagedProgress();+ p.accept([event('r', 'workflow_run.created', { workflow_run_id: 'w' }), idle('i')]);+ expect(p.snapshot()).toMatchObject({ finished: false, openRuns: 1, verification: 'unverified' });+ p.accept([event('end', 'workflow_run.status_ended', { workflow_run_id: 'w', result: { type: 'completed' } })]);+ expect(p.snapshot()).toMatchObject({ finished: false, needsThreadInspection: true, verification: 'unverified' });+ p.accept([idle('final')]);+ expect(p.snapshot().finished).toBe(true);+ });+ it.each(['budget_reached', 'requires_action'])('returns pause distinctly: %s', reason => {+ const p = new ManagedProgress(); p.accept([idle('i', reason)]);+ expect(p.snapshot()).toMatchObject({ blocked: true, finished: false });+ });+ it('does not erase an observed worker error when workflow completes', () => {+ const p = new ManagedProgress();+ p.accept([event('err', 'session.error'), event('e', 'workflow_run.status_ended', { workflow_run_id: 'w', result: { type: 'completed' } }), idle('i')]);+ expect(p.snapshot()).toMatchObject({ observedFailures: 1, verification: 'unverified' });+ });+ it('does not accept an interrupt idle as completion', () => {+ const p = new ManagedProgress(); p.accept([event('int', 'user.interrupt'), idle('i')]);+ expect(p.snapshot()).toMatchObject({ finished: false, interrupted: true });+ p.accept([event('next', 'user.message'), idle('nextIdle')]);+ expect(p.snapshot()).toMatchObject({ finished: true, interrupted: false });+ });+ it('deduplicates inclusive watermark replay and tracks usage', () => {+ const p = new ManagedProgress(); const events = [event('a', 'agent.message', { content: [{ type: 'text', text: 'hello' }] }), event('u', 'session.usage', { usage: { list_cost: { amount: '42', currency: 'USD' }, active_seconds: 10 } })];+ p.accept(events); p.accept(events);+ expect(p.snapshot()).toMatchObject({ assistantText: 'hello', eventCount: 2, listCost: { amount: '42' } });+ });+ it('handles queued user events when they later process', () => {+ const p = new ManagedProgress(); p.accept([event('q', 'user.message', { processed_at: null })]);+ expect(p.snapshot().eventCount).toBe(0);+ p.accept([event('q', 'user.message')]); expect(p.snapshot().eventCount).toBe(1);+ });+});++describe('pagination and observation', () => {+ it('follows opaque next_page with URL encoding and deduplicates', async () => {+ const read = vi.fn().mockResolvedValueOnce({ data: [idle('a')], next_page: 'opaque&x=y' }).mockResolvedValueOnce({ data: [idle('a'), idle('b')] });+ expect((await readManagedEvents(read)).map(e => e.id)).toEqual(['a', 'b']);+ expect(new URLSearchParams(read.mock.calls[1][0]).get('page')).toBe('opaque&x=y');+ });+ it('rejects cursor cycles', async () => {+ await expect(readManagedEvents(async () => ({ data: [], next_page: 'same' }))).rejects.toThrow('Repeated');+ });+ it.each([null, {}, { data: [null] }, { data: [{}] }, { data: [], next_page: 5 }])('fails closed on malformed pages %j', async value => {+ await expect(readManagedEvents(async () => value)).rejects.toThrow('Invalid');+ });+ it('propagates event HTTP failure without echoing upstream secrets', async () => {+ fetchMock.mockImplementation(() => json({ error: { message: 'test-key-do-not-log' } }, 403));+ const result = await call('managed_agent_events', { sessionId: 'sesn_a' });+ expect(result.success).toBe(false); expect(result.error).toContain('403'); expect(JSON.stringify(result)).not.toContain('test-key');+ });+ it('ignores historical idle before the acknowledged current message', async () => {+ vi.useFakeTimers();+ const initial = [idle('old'), event('current', 'user.message'), event('running', 'session.status_running')];+ fetchMock.mockResolvedValueOnce(json({ data: [event('current', 'user.message', { processed_at: null })] }))+ .mockResolvedValueOnce(json({ data: initial }))+ .mockResolvedValueOnce(json({ id: 'sesn_a', status: 'running' }))+ .mockResolvedValueOnce(json({ data: [...initial, event('text', 'agent.message', { content: [{ type: 'text', text: 'new answer' }] }), idle('new')] }))+ .mockResolvedValueOnce(json({ id: 'sesn_a', status: 'idle' }));+ const pending = call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'run', maxWaitMs: 5000 });+ await vi.advanceTimersByTimeAsync(1500);+ const result = await pending;+ expect(result).toMatchObject({ finished: true, assistantText: 'new answer', verification: 'unverified' });+ expect(fetchMock).toHaveBeenCalledTimes(5);+ expect(new URL(fetchMock.mock.calls[3][0]).searchParams.has('created_at[gte]')).toBe(true);+ });+ it('does not report the previous turn as the answer on a later poll while the new turn is still running', async () => {+ vi.useFakeTimers();+ // The provider returns the whole session history on every read. Pre-boundary events (the old turn's text and+ // its end_turn idle) were never fed to the tracker, so a later poll must keep ignoring them.+ const old = [event('oldText', 'agent.message', { content: [{ type: 'text', text: 'OLD ANSWER' }] }), idle('old')];+ const head = [...old, event('current', 'user.message'), event('running', 'session.status_running')];+ const partial = event('partial', 'agent.message', { content: [{ type: 'text', text: 'partial' }] });+ let eventReads = 0;+ fetchMock.mockImplementation((url: string, init?: { method?: string }) => {+ if (init?.method === 'POST') return json({ data: [event('current', 'user.message', { processed_at: null })] });+ if (url.includes('/events')) return json({ data: ++eventReads === 1 ? head : [...head, partial] });+ return json({ id: 'sesn_a', status: 'running' });+ });+ const pending = call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'run', maxWaitMs: 4000 });+ await vi.advanceTimersByTimeAsync(5000);+ const result = await pending;+ expect(eventReads).toBeGreaterThan(2);+ expect(result.finished).toBe(false);+ expect(result.assistantText).toBe('partial');+ expect(result.assistantText).not.toContain('OLD ANSWER');+ });+ it('rejects concurrent local prompts without sending twice', async () => {+ let release!: (value: Response) => void;+ fetchMock.mockReturnValueOnce(new Promise(resolve => { release = resolve; }));+ const first = call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'one' });+ expect((await call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'two' })).success).toBe(false);+ release(json({ data: [] })); await first;+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+ it('reads worker thread events through an encoded path', async () => {+ fetchMock.mockImplementation(() => json({ data: [event('err', 'session.error')] }));+ const result = await call('managed_agent_events', { sessionId: 'sesn_a', threadId: 'thread_a', raw: true });+ expect(fetchMock.mock.calls[0][0]).toContain('/threads/thread_a/events?limit=100');+ expect(result.observedFailures).toBe(1);+ });+ it('accepts legitimate tool confirmation result strings', async () => {+ fetchMock.mockImplementation(() => json({ data: [event('confirm', 'user.tool_confirmation', { result: 'allow' }), event('run', 'session.status_running'), idle('done')] }));+ expect((await call('managed_agent_events', { sessionId: 'sesn_a' })).finished).toBe(true);+ });+ it('rejects workflow lifecycle events without a run ID', async () => {+ fetchMock.mockImplementation(() => json({ data: [event('broken', 'workflow_run.created'), idle('done')] }));+ expect((await call('managed_agent_events', { sessionId: 'sesn_a' })).success).toBe(false);+ });+ it('does not contaminate a new prompt with old failed runs', async () => {+ const events = [event('oldErr', 'workflow_run.error', { workflow_run_id: 'old' }), event('oldEnd', 'workflow_run.status_ended', { workflow_run_id: 'old', result: { type: 'error' } }), idle('oldIdle'), event('current', 'user.message'), idle('done')];+ fetchMock.mockResolvedValueOnce(json({ data: [event('current', 'user.message')] })).mockResolvedValueOnce(json({ data: events })).mockResolvedValueOnce(json({ id: 'sesn_a', status: 'idle' }));+ expect(await call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'new task' })).toMatchObject({ success: true, finished: true, observedFailures: 0 });+ });+});++describe('transport and cleanup security', () => {+ it('marks ambiguous initial agent creation for inspection without blind cleanup', async () => {+ fetchMock.mockRejectedValueOnce(new Error('network outcome unknown'));+ expect(await call('managed_agent_create')).toMatchObject({ success: false, stage: 'agent', cleanupRequired: true });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ fetchMock.mockResolvedValueOnce(json({ id: 'unexpected' }));+ expect(await call('managed_agent_create')).toMatchObject({ success: false, stage: 'agent', cleanupRequired: true });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ it('does not reuse a generic model proxy or follow redirects', async () => {+ vi.stubEnv('ANTHROPIC_BASE_URL', 'https://wrong.example');+ fetchMock.mockImplementation(() => json({ id: 'sesn_a' }));+ await call('managed_agent_status', { sessionId: 'sesn_a' });+ expect(fetchMock.mock.calls[0][0]).toContain('https://api.anthropic.com/');+ expect(fetchMock.mock.calls[0][1].redirect).toBe('error');+ expect(fetchMock.mock.calls[0][1].headers['anthropic-beta']).toBe('managed-agents-2026-04-01');+ });+ it.each(['http://api.anthropic.com', 'https://user:[email protected]', 'https://example.com/path', 'https://example.com/?token=x'])('rejects unsafe endpoint %s', async base => {+ vi.stubEnv('RUFLO_MANAGED_AGENTS_BASE_URL', base);+ expect((await call('managed_agent_status', { sessionId: 'sesn_a' })).error).toContain('transport');+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('cleans up created resources after definite session rejection', async () => {+ fetchMock.mockResolvedValueOnce(json({ id: 'agent_a' })).mockResolvedValueOnce(json({ id: 'env_a' }))+ .mockResolvedValueOnce(json({}, 400)).mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(new Response(null, { status: 204 }));+ const result = await call('managed_agent_create', { dynamicWorkflows: true, budgetCents: '100' });+ expect(result).toMatchObject({ success: false, stage: 'session', environmentDeleted: true, agentDeleted: true });+ });+ it('preserves resources after ambiguous session creation failure', async () => {+ fetchMock.mockResolvedValueOnce(json({ id: 'agent_a' })).mockResolvedValueOnce(json({ id: 'env_a' })).mockRejectedValueOnce(new Error('socket closed'));+ const result = await call('managed_agent_create', { dynamicWorkflows: true, budgetCents: '100' });+ expect(result).toMatchObject({ success: false, stage: 'session', cleanupRequired: true });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });+ it('does not delete an environment if session deletion failed', async () => {+ fetchMock.mockImplementation(() => json({}, 500));+ expect((await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).success).toBe(false);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+ it('reports environment cleanup failure', async () => {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(json({}, 409));+ expect((await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).success).toBe(false);+ });+ it('never calls a queued interrupt confirmed cancellation', async () => {+ vi.stubEnv('RUFLO_MANAGED_CONTROL', '1'); vi.stubEnv('RUFLO_MANAGED_CONTROL_SESSIONS', 'sesn_a');+ fetchMock.mockImplementation(() => json({ id: 'sesn_a', status: 'running', data: [] }));+ expect(await call('managed_agent_interrupt', { sessionId: 'sesn_a' })).toMatchObject({ interruptRequested: true, cancellationConfirmed: false });+ });+});++describe('failures after a prompt was already sent', () => {+ it('reports the message id so a retry does not send a duplicate', async () => {+ fetchMock.mockResolvedValueOnce(json({ data: [event('sent', 'user.message', { processed_at: null })] })).mockImplementation(() => json({}, 500));+ const result = await call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'run', maxWaitMs: 2000 });+ expect(result.success).toBe(false);+ expect(result.messageId).toBe('sent');+ expect(String(result.note)).toMatch(/already sent/i);+ });+ it('a failed send reports no message id', async () => {+ fetchMock.mockImplementation(() => json({}, 500));+ const result = await call('managed_agent_prompt', { sessionId: 'sesn_a', message: 'run' });+ expect(result.success).toBe(false);+ expect(result.messageId).toBeUndefined();+ });+});++describe('the governed control plane covers its sibling tools', () => {+ const governed = (sessions: string) => { vi.stubEnv('RUFLO_MANAGED_CONTROL', '1'); vi.stubEnv('RUFLO_MANAGED_CONTROL_SESSIONS', sessions); };+ it('managed_agent_interrupt is refused by default and sends nothing to the provider', async () => {+ const result = await call('managed_agent_interrupt', { sessionId: 'sesn_a' });+ expect(result.success).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('managed_agent_interrupt is refused for a session outside the host allowlist', async () => {+ governed('sesn_a');+ expect((await call('managed_agent_interrupt', { sessionId: 'sesn_other' })).success).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('managed_agent_terminate keeps its default behaviour while the control plane is off', async () => {+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));+ expect((await call('managed_agent_terminate', { sessionId: 'sesn_whatever' })).success).toBe(true);+ });+ it('managed_agent_terminate honours the allowlist once the host enabled the control plane', async () => {+ governed('sesn_a');+ const result = await call('managed_agent_terminate', { sessionId: 'sesn_other', environmentId: 'env_x' });+ expect(result.success).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('managed_agent_terminate will not delete an environment that is not the session\'s own', async () => {+ governed('sesn_a');+ fetchMock.mockImplementation((url: string, init?: { method?: string }) => {+ if (init?.method === 'DELETE') return new Response(null, { status: 204 });+ return json({ id: 'sesn_a', status: 'running', environment_id: 'env_a' });+ });+ const result = await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_other' });+ expect(result).toMatchObject({ sessionDeleted: true, environmentDeleted: false, success: false });+ expect(fetchMock.mock.calls.some(c => String(c[0]).includes('/environments/'))).toBe(false);+ });+ it('managed_agent_terminate still removes the session\'s own environment under governance', async () => {+ governed('sesn_a');+ fetchMock.mockImplementation((url: string, init?: { method?: string }) => {+ if (init?.method === 'DELETE') return new Response(null, { status: 204 });+ return json({ id: 'sesn_a', status: 'running', environment_id: 'env_a' });+ });+ expect(await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).toMatchObject({ sessionDeleted: true, environmentDeleted: true, success: true });+ });+});++it('discards an observation when host credentials rotate during provider reads', async () => {+ fetchMock.mockImplementation(async (url: string) => {+ if (url.includes('/events?')) {+ process.env.ANTHROPIC_API_KEY = 'rotated-host-key';+ return json({ data: [idle('done')] });+ }+ return json({ id: 'sesn_a', status: 'idle' });+ });+ const result = await call('managed_agent_events', { sessionId: 'sesn_a' });+ expect(result.success).toBe(false);+ expect(result.error).toContain('scope changed');+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.tsindex 132af04c01..d4c85cdc2d 100644--- a/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts@@ -17,16 +17,24 @@* managed_agent_list → GET /v1/sessions* managed_agent_terminate→ DELETE /v1/sessions/{id} (+ optionally the env) ↔ wasm_agent_terminate*/--import type { MCPTool } from './types.js';--const API_BASE = process.env.ANTHROPIC_BASE_URL?.replace(/\/$/, '') || 'https://api.anthropic.com';+import { managedLearningTool } from './managed-learning-tool.js';+import { ManagedRunCollector } from '../services/managed-run-collector.js';+import { collectWithLease, executeManagedControl, publishManagedSnapshot, publishManagedTermination } from '../services/managed-run-store.js';+import { getProjectCwd, type MCPTool } from './types.js';+import { dynamicConfig, eventPage, readManagedEvents, ManagedProgress, type ManagedEvent } from '../services/managed-workflows.js';+// Dedicated override avoids forwarding credentials to a generic model proxy.+function apiBase(): string {+ const url = new URL(process.env.RUFLO_MANAGED_AGENTS_BASE_URL || 'https://api.anthropic.com');+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') {+ throw new Error('Managed Agents endpoint must be an HTTPS origin');+ }+ return url.origin;+}const BETA_HEADER = 'managed-agents-2026-04-01';const ANTHROPIC_VERSION = '2023-06-01';const DEFAULT_MODEL = 'claude-sonnet-4-6';const POLL_INTERVAL_MS = 1500;const DEFAULT_MAX_WAIT_MS = 180_000; // 3 min — long enough for a real task, bounded so a tool call never hangs forever-function apiKey(): string | null {return process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY || null;}@@ -50,89 +58,140 @@ async function maRequest<T = unknown>(method: 'GET' | 'POST' | 'DELETE',path: string,body?: unknown,+ timeoutMs = 30_000,): Promise<{ ok: true; status: number; data: T } | { ok: false; status: number; error: string; body?: unknown }> {const key = apiKey();if (!key) return { ok: false, status: 0, error: NEEDS_KEY.error };- let res: Response;try {- res = await fetch(`${API_BASE}/v1${path}`, {- method,- headers: headers(key),+ const res = await fetch(`${apiBase()}/v1${path}`, {+ method, headers: headers(key), redirect: 'error',body: body !== undefined ? JSON.stringify(body) : undefined,- signal: AbortSignal.timeout(30_000),+ signal: AbortSignal.timeout(Math.max(1, Math.min(timeoutMs, 30_000))),});- } catch (e) {- return { ok: false, status: 0, error: `network error calling ${method} /v1${path}: ${(e as Error).message}` };- }- const text = await res.text();- let parsed: unknown = undefined;- try { parsed = text ? JSON.parse(text) : undefined; } catch { /* leave undefined */ }- if (!res.ok) {- const apiErr = (parsed as { error?: { message?: string }; message?: string })?.error?.message- ?? (parsed as { message?: string })?.message- ?? text.slice(0, 300);- return { ok: false, status: res.status, error: `Managed Agents API ${res.status}: ${apiErr}`, body: parsed };+ // Never echo upstream bodies: they may contain prompts, keys or MCP tokens.+ if (!res.ok) { await res.body?.cancel(); return { ok: false, status: res.status, error: `Managed Agents API HTTP ${res.status}` }; }+ if (method === 'DELETE' && ![200, 204].includes(res.status)) { await res.body?.cancel(); return { ok: false, status: res.status, error: 'Provider deletion is not yet confirmed' }; }+ if (res.status === 204) return { ok: true, status: res.status, data: undefined as T };+ const reader = res.body?.getReader();+ const chunks: Uint8Array[] = [];+ let bytes = 0;+ if (reader) {+ try {+ while (true) {+ const chunk = await reader.read();+ if (chunk.done) break;+ bytes += chunk.value.byteLength;+ if (bytes > 8_000_000) { await reader.cancel(); throw new Error('response limit'); }+ chunks.push(chunk.value);+ }+ } finally { reader.releaseLock(); }+ }+ const text = Buffer.concat(chunks).toString('utf8');+ return { ok: true, status: res.status, data: (text ? JSON.parse(text) : undefined) as T };+ } catch {+ return { ok: false, status: 0, error: 'Managed Agents transport or response error; inspect provider status before retrying mutations' };}- return { ok: true, status: res.status, data: parsed as T };}// ---- shapes (only the fields we touch) -----------------------------------interface MaAgent { id: string; version?: number; name?: string; model?: { id: string } }interface MaEnvironment { id: string; name?: string; config?: unknown }interface MaSession { id: string; status?: string; title?: string; error?: string | null; agent?: MaAgent; environment_id?: string }-interface MaEvent { type: string; content?: Array<{ type: string; text?: string }>; name?: string; input?: unknown; id?: string; processed_at?: string; stop_reason?: { type: string } }+type MaEvent = ManagedEvent;-// ---- helpers ---------------------------------------------------------------function summarizeEvents(events: MaEvent[]): {- assistantText: string;- toolUses: Array<{ name: string; input: unknown }>;- status: string;- stopReason: string | null;- eventCount: number;-} {- let assistantText = '';- const toolUses: Array<{ name: string; input: unknown }> = [];- let status = 'unknown';- let stopReason: string | null = null;- for (const e of events) {- if (e.type === 'agent.message' && Array.isArray(e.content)) {- assistantText += e.content.filter(b => b.type === 'text').map(b => b.text ?? '').join('');- } else if (e.type === 'agent.tool_use') {- toolUses.push({ name: e.name ?? '?', input: e.input });- } else if (e.type === 'session.status_running') {- status = 'running';- } else if (e.type === 'session.status_idle') {- status = 'idle';- stopReason = e.stop_reason?.type ?? null;- } else if (e.type === 'session.status_error' || e.type === 'session.status_failed') {- status = 'error';- }- }- return { assistantText, toolUses, status, stopReason, eventCount: events.length };+function summarizeEvents(events: MaEvent[]) {+ const progress = new ManagedProgress();+ progress.accept(events);+ return progress.snapshot();}-async function fetchSessionEvents(sessionId: string): Promise<MaEvent[]> {- const r = await maRequest<{ data?: MaEvent[]; events?: MaEvent[] }>('GET', `/sessions/${encodeURIComponent(sessionId)}/events`);- if (!r.ok) return [];- const d = r.data;- return (d.data ?? d.events ?? []) as MaEvent[];+async function fetchSessionEvents(sessionId: string, since?: string, threadId?: string, deadline = Date.now() + 30_000, expectedScope = currentCollectorScope()): Promise<MaEvent[]> {+ return readManagedEvents(async query => {+ const thread = threadId ? `/threads/${encodeURIComponent(threadId)}` : '';+ const params = new URLSearchParams(query);+ if (threadId) { params.delete('order'); params.delete('created_at[gte]'); }+ if (currentCollectorScope() !== expectedScope) throw new Error('Managed credential scope changed during observation');+ if (Date.now() >= deadline) throw new Error('Managed Agents observation deadline reached');+ const r = await maRequest('GET', `/sessions/${encodeURIComponent(sessionId)}${thread}/events?${params}`, undefined, deadline - Date.now());+ if (!r.ok) throw new Error(r.error);+ if (currentCollectorScope() !== expectedScope) throw new Error('Managed credential scope changed during observation');+ return r.data;+ }, since);+}++let collectorScope = '';+let collector = new ManagedRunCollector();+// The scope only answers "did the project, endpoint or credential change since this collector was built". It never leaves the+// process, so it is a generation number, not a digest: the API key is compared in memory (it already lives in the environment)+// and is never fed to a hash function. Returning to an earlier value counts as a change, which is the safe direction.+let scopeInput = '';+let scopeGeneration = 0;+function currentCollectorScope() {+ const input = JSON.stringify([getProjectCwd(), apiBase(), apiKey()]);+ if (input !== scopeInput) { scopeInput = input; scopeGeneration++; }+ return `scope-${scopeGeneration}`;+}+function scopedCollector() {+ const scope = currentCollectorScope();+ if (scope !== collectorScope) { collector = new ManagedRunCollector(); collectorScope = scope; }+ return collector;+}+async function observeSession(sessionId: string, deadline = Date.now() + 30_000) {+ const root = getProjectCwd(), active = scopedCollector(), expectedScope = collectorScope;+ return collectWithLease(root, sessionId, async () => {+ const result = await active.refresh(sessionId, {+ readEvents: since => fetchSessionEvents(sessionId, since, undefined, deadline, expectedScope),+ readSession: async () => {+ if (currentCollectorScope() !== expectedScope) throw new Error('Managed credential scope changed during observation');+ const r = await maRequest<MaSession>('GET', `/sessions/${encodeURIComponent(sessionId)}`, undefined, deadline - Date.now());+ if (!r.ok) throw new Error(r.error);+ return r.data;+ },+ });+ if (currentCollectorScope() !== expectedScope) throw new Error('Managed credential scope changed during observation');+ // The snapshot only feeds the console. A write failure (size cap, stale lock) must not fail a successful provider read.+ try { publishManagedSnapshot(root, result.snapshot); } catch { /* best effort */ }+ return result;+ }, expectedScope);}-// Wait until the session is no longer "running": poll the event log for a-// terminal session.status_* event. Bounded by maxWaitMs.-async function waitForIdle(sessionId: string, maxWaitMs: number): Promise<{ done: boolean; events: MaEvent[] }> {+// Gate new-turn observations on the provider's acknowledged message ID, not+// on a local timestamp or a historical idle event. Calls are serialized locally.+const pendingPrompts = new Set<string>();+async function waitForIdle(sessionId: string, maxWaitMs: number, messageId: string) {const deadline = Date.now() + Math.max(1_000, Math.min(maxWaitMs, 600_000));- let events: MaEvent[] = [];+ const progress = new ManagedProgress();+ let started = false;while (Date.now() < deadline) {- events = await fetchSessionEvents(sessionId);- const terminal = events.some(e => e.type === 'session.status_idle' || e.type === 'session.status_error' || e.type === 'session.status_failed');- // Also stop early if the session record itself reports a non-running status- if (terminal) return { done: true, events };- await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));+ const { events } = await observeSession(sessionId, deadline);+ if (!started) {+ const boundary = events.findIndex(e => e.id === messageId && !!e.processed_at);+ if (boundary >= 0) {+ // Existing runs remain relevant when a user steers an active session.+ const prior = new ManagedProgress();+ const history = events.slice(0, boundary).filter(e => e.type.startsWith('workflow_run.'));+ prior.accept(history);+ const open = new Set(prior.snapshot().workflowRuns.filter(r => r.status !== 'ended').map(r => r.id));+ progress.accept(history.filter(e => e.workflow_run_id && open.has(e.workflow_run_id)));+ progress.accept(events.slice(boundary));+ started = true;+ }+ } else {+ // The provider returns the whole session history on every read. Keep ignoring everything before the+ // acknowledged message: its old end_turn idle would otherwise be applied on a later poll and report+ // the previous turn's answer as finished while the new turn is still running.+ const boundary = events.findIndex(e => e.id === messageId);+ if (boundary >= 0) progress.accept(events.slice(boundary));+ }+ const state = progress.snapshot();+ if (started && (state.finished || state.blocked || (state.interrupted && state.status === 'idle') || state.status === 'terminated')) return state;+ await new Promise(r => setTimeout(r, Math.min(POLL_INTERVAL_MS, Math.max(0, deadline - Date.now()))));}- return { done: false, events };+ return progress.snapshot();}+function definiteRejection(status: number): boolean { return [400, 401, 403, 404, 422].includes(status); }+function maName(prefix: string, given?: unknown): string {if (typeof given === 'string' && given.trim()) return given.trim().slice(0, 80);return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;@@ -141,10 +200,54 @@ function maName(prefix: string, given?: unknown): string {// ---------------------------------------------------------------------------export const managedAgentTools: MCPTool[] = [+ {+ name: 'managed_agent_capabilities',+ description: 'Inspect local Managed Agents adapter capabilities without network access or an API key. Use when native tool registration alone cannot establish adapter requirements, budget semantics or verification boundaries. Reports configuration facts only; it never verifies beta access, remote health or authorization. Pair with /agent-mod capabilities for plugin policy and registered tools; use wasm_agent_* for local execution.',+ category: 'agent',+ inputSchema: { type: 'object', properties: {} },+ handler: async () => ({+ runtime: 'managed', provider: 'anthropic', networkCalled: false,+ credentialConfigured: !!apiKey(), betaAccess: 'unknown', remoteHealth: 'unknown', authorization: 'host-policy-required',+ features: ['dynamic-workflows', 'budget-at-creation', 'limited-networking', 'predefined-agents', 'thread-inspection', 'interrupt-request', 'session-delete', 'verified-learning'],+ create: { dynamicWorkflows: true, budgetCents: 'positive integer US cents string', networking: 'limited', predefinedAgents: 'optional agent IDs; required by default mod policy' },+ controls: { budgetOvershoot: 'in-flight requests may finish', promptTimeout: 'observation only', interrupt: 'pause requested, not cancellation', verification: 'unverified' },+ integrations: { agentMod: '/agent-mod capabilities', workflowMod: '/wf-mod managed', console: 'Mods page reads agent-mod/status.json', evidence: 'independently verify before memory_* retention or RVF export' },+ learning: { enabled: process.env.RUFLO_MANAGED_LEARNING === '1', verifierConfigured: !!process.env.RUFLO_MANAGED_VERIFIER_PUBLIC_KEY, defaultsChanged: false },+ scope: 'Adapter facts do not grant tools, credentials, plugins or release authority. Mod admission is host-session-local, not global spend enforcement.',+ }),+ },+ {+ name: 'managed_agent_learning',+ description: 'Record structured workflow outcomes, inspect learning, recommend strategies, evaluate paired holdouts, or execute one bounded feedback cycle. Use when provider completion cannot establish correctness or teach routing safely. Verified evidence needs the host Ed25519 verifier. Native memory runs in isolated workers. MetaHarness eligibility is advisory and never changes defaults. Pair with managed_agent_events and managed_agent_control for provider observations and policy checked controls; use wasm_agent_* for local execution.',+ category: 'agent', inputSchema: managedLearningTool.inputSchema, handler: managedLearningTool.handler,+ },+ {+ name: 'managed_agent_control',+ description: 'Inspect, request interruption, or terminate one managed session through fresh host policy and provider-state checks. Use when native console snapshots are too stale to authorize a remote action. Requires host RUFLO_MANAGED_CONTROL=1 and an exact RUFLO_MANAGED_CONTROL_SESSIONS allowlist. No caller approval flag is accepted. Pair with managed_agent_events; use wasm_agent_terminate for local agents.',+ category: 'agent',+ inputSchema: { type: 'object', properties: { sessionId: { type: 'string' }, action: { type: 'string', enum: ['inspect', 'interrupt', 'terminate'] }, threadOffset: { type: 'integer', minimum: 0, maximum: 9999 } }, required: ['sessionId', 'action'] },+ handler: async input => {+ if (!apiKey()) return { success: false, ...NEEDS_KEY };+ try {+ const request = async (method: 'GET' | 'POST' | 'DELETE', id: string, body?: unknown) => {+ const r = await maRequest<MaSession>(method, `/sessions/${encodeURIComponent(id)}${method === 'POST' ? '/events' : ''}`, body);+ if (!r.ok) throw new Error(r.error);+ return r.data;+ };+ return await executeManagedControl(input, {+ policy: () => ({ enabled: process.env.RUFLO_MANAGED_CONTROL === '1', sessions: (process.env.RUFLO_MANAGED_CONTROL_SESSIONS ?? '').split(',').map(s => s.trim()).filter(Boolean) }),+ read: id => request('GET', id),+ inspect: async (id, offset) => { await observeSession(id); const page = scopedCollector().page(id, offset); if (!page) throw new Error('Snapshot unavailable'); publishManagedSnapshot(getProjectCwd(), page); return page; },+ interrupt: id => request('POST', id, { events: [{ type: 'user.interrupt' }] }),+ terminate: async id => { const result = await request('DELETE', id); try { publishManagedTermination(getProjectCwd(), id, scopedCollector()); } catch { /* the provider deletion is the fact; the local snapshot is best-effort */ } return result; },+ });+ } catch { return { success: false, error: 'Managed action refused: recheck current host policy, provider state and observation lease' }; }+ },+ },{name: 'managed_agent_create',description:- 'Spin up an Anthropic-managed cloud agent (Agent + Environment + Session) — the CLOUD counterpart of wasm_agent_create. Use when wasm_agent_create (local WASM sandbox) is wrong because the task is long-running/async (minutes-hours), needs a real cloud container with pre-installed packages + network, or persistent filesystem + transcript across turns. For a fast, free, ephemeral, offline agent use wasm_agent_create (rvagent). Needs ANTHROPIC_API_KEY + Managed Agents beta access. Returns {sessionId, agentId, environmentId}; pair with managed_agent_prompt.',+ 'Spin up an Anthropic-managed cloud agent (Agent + Environment + Session) — the CLOUD counterpart of wasm_agent_create. Use when wasm_agent_create (local WASM sandbox) is wrong because the task is long-running/async (minutes-hours), needs a real cloud container with pre-installed packages + network, or persistent filesystem + transcript across turns. For a fast, free, ephemeral, offline agent use wasm_agent_create (rvagent). Needs ANTHROPIC_API_KEY + Managed Agents beta access. Opt into dynamic workflows with dynamicWorkflows=true and mandatory budgetCents (integer US cents); networking is then limited. Returns {sessionId, agentId, environmentId}; pair with managed_agent_prompt.',category: 'agent',inputSchema: {type: 'object',@@ -160,13 +263,20 @@ export const managedAgentTools: MCPTool[] = [},skills: { type: 'array', description: 'Skills to attach to the agent', items: { type: 'object' } },packages: { type: 'object', description: 'Environment packages: {pip?:[], npm?:[], apt?:[], cargo?:[], gem?:[], go?:[]}' },- networking: { type: 'string', enum: ['unrestricted', 'restricted', 'none'], description: 'Environment networking (default: unrestricted)' },+ networking: { type: 'string', enum: ['unrestricted', 'restricted', 'none', 'limited'], description: 'Legacy default unrestricted; dynamic workflows require limited' },+ dynamicWorkflows: { type: 'boolean', description: 'Opt in to multiagent_20261001 dynamic workflows (requires budgetCents)' },+ budgetCents: { type: 'string', pattern: '^[1-9][0-9]{0,8}$', description: 'Positive integer US cents string; 2500 means $25; in-flight requests may overshoot' },+ allowedHosts: { type: 'array', items: { type: 'string' }, description: 'Exact allowed hostnames for dynamic workflow limited networking' },+ predefinedAgents: { type: 'array', minItems: 1, maxItems: 20, items: { type: 'string' }, description: 'Restrict workflows to these agent IDs; disables inline agents' },initScript: { type: 'string', description: 'Environment init script (bash, run at container start)' },},},handler: async (input) => {if (!apiKey()) return { success: false, ...NEEDS_KEY };+ let config: ReturnType<typeof dynamicConfig>;+ try { config = dynamicConfig(input); } catch (error) { return { success: false, error: (error as Error).message }; }+// 1. Agentconst agentBody: Record<string, unknown> = {name: maName('ruflo-managed', input.name),@@ -174,30 +284,44 @@ export const managedAgentTools: MCPTool[] = [tools: [{ type: 'agent_toolset_20260401' }],};if (typeof input.system === 'string') agentBody.system = input.system;+ if (config.multiagent) agentBody.multiagent = config.multiagent;if (Array.isArray(input.mcpServers) && input.mcpServers.length) agentBody.mcp_servers = input.mcpServers;if (Array.isArray(input.skills) && input.skills.length) agentBody.skills = input.skills;const a = await maRequest<MaAgent>('POST', '/agents', agentBody);- if (!a.ok) return { success: false, stage: 'agent', error: a.error };+ if (!a.ok) return { success: false, stage: 'agent', error: a.error, cleanupRequired: !definiteRejection(a.status) };+ if (!a.data || typeof a.data.id !== 'string' || !/^agent_[A-Za-z0-9]+$/.test(a.data.id)) return { success: false, stage: 'agent', error: 'Invalid agent acknowledgement; inspect provider resources before retrying', cleanupRequired: true };// 2. Environment- const net = (input.networking as string) || 'unrestricted';const envBody: Record<string, unknown> = {name: maName('ruflo-managed-env', input.name),- config: { type: 'cloud', networking: { type: net } },+ config: { type: 'cloud', networking: config.networking },};if (input.packages && typeof input.packages === 'object') (envBody.config as Record<string, unknown>).packages = { type: 'packages', ...(input.packages as object) };if (typeof input.initScript === 'string' && input.initScript) (envBody.config as Record<string, unknown>).init_script = input.initScript;const e = await maRequest<MaEnvironment>('POST', '/environments', envBody);- if (!e.ok) return { success: false, stage: 'environment', agentId: a.data.id, error: e.error };+ if (!e.ok) {+ if (!definiteRejection(e.status)) return { success: false, stage: 'environment', agentId: a.data.id, error: e.error, cleanupRequired: true };+ const cleanup = await maRequest('DELETE', `/agents/${encodeURIComponent(a.data.id)}`);+ return { success: false, stage: 'environment', agentId: a.data.id, error: e.error, agentDeleted: cleanup.ok };+ }++ if (!e.data || typeof e.data.id !== 'string' || !/^env_[A-Za-z0-9]+$/.test(e.data.id)) return { success: false, stage: 'environment', agentId: a.data.id, error: 'Invalid environment acknowledgement; inspect provider resources before retrying', cleanupRequired: true };// 3. Sessionconst s = await maRequest<MaSession>('POST', '/sessions', {agent: a.data.id,environment_id: e.data.id,title: maName('ruflo-managed session', input.title),+ ...(config.budget ? { budget: config.budget } : {}),});- if (!s.ok) return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: s.error };+ if (!s.ok) {+ if (!definiteRejection(s.status)) return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: s.error, cleanupRequired: true };+ const envCleanup = await maRequest('DELETE', `/environments/${encodeURIComponent(e.data.id)}`);+ const agentCleanup = await maRequest('DELETE', `/agents/${encodeURIComponent(a.data.id)}`);+ return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: s.error, environmentDeleted: envCleanup.ok, agentDeleted: agentCleanup.ok };+ }+ if (!s.data || typeof s.data.id !== 'string' || !/^sesn_[A-Za-z0-9]+$/.test(s.data.id)) return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: 'Invalid session acknowledgement; inspect provider resources before retrying', cleanupRequired: true };return {success: true,runtime: 'managed',@@ -207,7 +331,10 @@ export const managedAgentTools: MCPTool[] = [environmentId: e.data.id,status: s.data.status ?? 'idle',model: agentBody.model,- note: 'Cloud agent provisioned. Send work with managed_agent_prompt({sessionId, message}); inspect with managed_agent_events; clean up with managed_agent_terminate (it bills container time + tokens until you do).',+ dynamicWorkflows: config.enabled,+ budget: config.budget,+ verification: 'unverified',+ note: 'Cloud agent provisioned. Send work with managed_agent_prompt({sessionId, message}); inspect with managed_agent_events; clean up with managed_agent_terminate (running sessions consume runtime and tokens).',};},},@@ -232,28 +359,30 @@ export const managedAgentTools: MCPTool[] = [if (!sessionId) return { success: false, error: 'sessionId is required' };if (!message) return { success: false, error: 'message is required' };- const send = await maRequest('POST', `/sessions/${encodeURIComponent(sessionId)}/events`, {- events: [{ type: 'user.message', content: [{ type: 'text', text: message }] }],- });- if (!send.ok) return { success: false, stage: 'send', sessionId, error: send.error };-- const maxWait = typeof input.maxWaitMs === 'number' && input.maxWaitMs > 0 ? input.maxWaitMs : DEFAULT_MAX_WAIT_MS;- const { done, events } = await waitForIdle(sessionId, maxWait);- const sum = summarizeEvents(events);- return {- success: true,- runtime: 'managed',- sessionId,- finished: done,- status: sum.status,- stopReason: sum.stopReason,- assistantText: sum.assistantText,- toolUses: sum.toolUses,- eventCount: sum.eventCount,- note: done- ? undefined- : `Session still running after ${maxWait}ms — call managed_agent_events({sessionId}) to keep watching, or managed_agent_prompt again to steer.`,- };+ if (input.maxWaitMs !== undefined && (typeof input.maxWaitMs !== 'number' || !Number.isFinite(input.maxWaitMs) || input.maxWaitMs <= 0)) return { success: false, error: 'maxWaitMs must be finite and positive' };+ if (pendingPrompts.has(sessionId)) return { success: false, error: 'A prompt is already pending for this session' };+ pendingPrompts.add(sessionId);+ let sentMessageId: string | undefined;+ try {+ const send = await maRequest('POST', `/sessions/${encodeURIComponent(sessionId)}/events`, {+ events: [{ type: 'user.message', content: [{ type: 'text', text: message }] }],+ });+ if (!send.ok) return { success: false, stage: 'send', sessionId, error: send.error };+ const sent = eventPage(send.data).data.find(e => e.type === 'user.message');+ if (!sent) return { success: false, sessionId, error: 'Missing message acknowledgement; inspect events before retrying' };+ sentMessageId = sent.id;+ const maxWait = typeof input.maxWaitMs === 'number' ? input.maxWaitMs : DEFAULT_MAX_WAIT_MS;+ const state = await waitForIdle(sessionId, maxWait, sent.id);+ return {+ success: state.observedFailures === 0 && state.status !== 'terminated',+ runtime: 'managed', sessionId, messageId: sent.id, ...state,+ note: 'Provider output is unverified. Inspect workflow threads and independently test artifacts. A wait timeout does not stop remote execution; inspect events or terminate explicitly.',+ };+ } catch (error) {+ // Once the provider acknowledged the message, say so: a retry would send it twice.+ return { success: false, sessionId, finished: false, error: (error as Error).message,+ ...(sentMessageId ? { messageId: sentMessageId, note: 'The message was already sent; inspect events instead of resending.' } : {}) };+ } finally { pendingPrompts.delete(sessionId); }},},{@@ -280,6 +409,7 @@ export const managedAgentTools: MCPTool[] = [type: 'object',properties: {sessionId: { type: 'string', description: 'Session id' },+ threadId: { type: 'string', description: 'Optional child thread ID from session.thread_created; inspect worker failures' },raw: { type: 'boolean', description: 'Include the full raw event objects (default: summary + compact list)' },},required: ['sessionId'],@@ -288,22 +418,19 @@ export const managedAgentTools: MCPTool[] = [if (!apiKey()) return { ...NEEDS_KEY };const sessionId = String(input.sessionId ?? '');if (!sessionId) return { error: 'sessionId is required' };- const events = await fetchSessionEvents(sessionId);+ let events: MaEvent[];+ try { events = typeof input.threadId === 'string' ? await fetchSessionEvents(sessionId, undefined, input.threadId) : (await observeSession(sessionId)).events; } catch (error) { return { success: false, sessionId, error: (error as Error).message }; }const sum = summarizeEvents(events);const compact = events.map(e => {- if (e.type === 'agent.message') return { type: e.type, text: (e.content ?? []).filter(b => b.type === 'text').map(b => b.text ?? '').join('').slice(0, 500) };+ if (e.type === 'agent.message') return { type: e.type, text: (e.content ?? []).filter(b => b?.type === 'text').map(b => b.text ?? '').join('').slice(0, 500) };if (e.type === 'agent.tool_use') return { type: e.type, name: e.name, input: e.input };if (e.type === 'agent.tool_result') return { type: e.type, content: JSON.stringify(e.content ?? {}).slice(0, 500) };- return { type: e.type, ...(e.stop_reason ? { stop_reason: e.stop_reason } : {}) };+ return { id: e.id, type: e.type, workflowRunId: e.workflow_run_id, threadId: e.session_thread_id, result: e.result, ...(e.stop_reason ? { stop_reason: e.stop_reason } : {}) };});return {runtime: 'managed',sessionId,- status: sum.status,- stopReason: sum.stopReason,- assistantText: sum.assistantText,- toolUses: sum.toolUses,- eventCount: sum.eventCount,+ ...sum,events: input.raw ? events : compact,};},@@ -327,10 +454,25 @@ export const managedAgentTools: MCPTool[] = [};},},+ {+ name: 'managed_agent_interrupt',+ description: 'Request an interrupt for an Anthropic managed session. Use when native interruption cannot reach the remote cloud runtime; for local WASM use wasm_agent_terminate. This queues a pause, does not end workflow runs, and never confirms cancellation. Inspect managed_agent_events or explicitly terminate the session.',+ category: 'agent',+ inputSchema: { type: 'object', properties: { sessionId: { type: 'string', description: 'Managed session to interrupt' } }, required: ['sessionId'] },+ handler: async input => {+ if (!apiKey()) return { success: false, ...NEEDS_KEY };+ if (typeof input.sessionId !== 'string' || !input.sessionId) return { success: false, error: 'sessionId is required' };+ // No ungated path to a remote action: this uses the same host policy, session allowlist and fresh provider-state+ // check as managed_agent_control, so a prompt-injected caller cannot interrupt arbitrary organisation sessions.+ const control = managedAgentTools.find(t => t.name === 'managed_agent_control')!;+ const r = await control.handler({ sessionId: input.sessionId, action: 'interrupt' }) as Record<string, unknown>;+ return { ...r, sessionId: input.sessionId, interruptRequested: r.success === true, cancellationConfirmed: false };+ },+ },{name: 'managed_agent_terminate',description:- 'Delete a managed cloud-agent session (stops billing for it) — the CLOUD counterpart of wasm_agent_terminate. Use when native nothing applies because a cloud session keeps billing container time + tokens until deleted. For a local WASM agent use wasm_agent_terminate. Optionally also deletes the session\'s environment. Always call this when done with a managed agent.',+ 'Delete a managed cloud-agent session (stops billing for it) — the CLOUD counterpart of wasm_agent_terminate. Use when native nothing applies because a running cloud session consumes runtime and tokens. For a local WASM agent use wasm_agent_terminate. Optionally also deletes the session\'s environment. Always call this when done with a managed agent.',category: 'agent',inputSchema: {type: 'object',@@ -344,15 +486,35 @@ export const managedAgentTools: MCPTool[] = [if (!apiKey()) return { success: false, ...NEEDS_KEY };const sessionId = String(input.sessionId ?? '');if (!sessionId) return { success: false, error: 'sessionId is required' };+ // Default behaviour is unchanged. Once the host has switched on the governed control plane+ // (RUFLO_MANAGED_CONTROL=1) this tool obeys the same session allowlist, and may delete only that session's own environment.+ const governed = process.env.RUFLO_MANAGED_CONTROL === '1';+ if (governed && !(process.env.RUFLO_MANAGED_CONTROL_SESSIONS ?? '').split(',').map(x => x.trim()).filter(Boolean).includes(sessionId)) {+ return { success: false, error: 'Host managed control policy denies this session' };+ }+ const wantsEnvironment = typeof input.environmentId === 'string' && input.environmentId.length > 0;+ let ownEnvironment: string | undefined;+ if (governed && wantsEnvironment) {+ const g = await maRequest<MaSession>('GET', `/sessions/${encodeURIComponent(sessionId)}`);+ if (!g.ok) return { success: false, error: g.error };+ ownEnvironment = g.data.environment_id;+ }const s = await maRequest('DELETE', `/sessions/${encodeURIComponent(sessionId)}`);const result: Record<string, unknown> = { runtime: 'managed', sessionId, sessionDeleted: s.ok };+ // The deletion already happened; a failed local snapshot update must not turn it into an error or skip the environment.+ if (s.ok) { try { publishManagedTermination(getProjectCwd(), sessionId, scopedCollector()); } catch { result.snapshotUpdated = false; } }if (!s.ok) result.error = s.error;- if (typeof input.environmentId === 'string' && input.environmentId) {- const e = await maRequest('DELETE', `/environments/${encodeURIComponent(String(input.environmentId))}`);- result.environmentDeleted = e.ok;- if (!e.ok) result.environmentError = e.error;+ if (s.ok && wantsEnvironment) {+ if (governed && input.environmentId !== ownEnvironment) {+ result.environmentDeleted = false;+ result.environmentError = 'environmentId does not belong to this session';+ } else {+ const e = await maRequest('DELETE', `/environments/${encodeURIComponent(String(input.environmentId))}`);+ result.environmentDeleted = e.ok;+ if (!e.ok) result.environmentError = e.error;+ }}- result.success = s.ok;+ result.success = s.ok && result.environmentDeleted !== false;return result;},},diff --git a/v3/@claude-flow/cli/src/mcp-tools/managed-learning-tool.ts b/v3/@claude-flow/cli/src/mcp-tools/managed-learning-tool.tsnew file mode 100644index 0000000000..5f1931b98e--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/managed-learning-tool.ts@@ -0,0 +1,34 @@+/** Learning MCP boundary, kept separate from provider transport and native workers. */+import { getProjectCwd, type MCPTool } from './types.js';++export const managedLearningTool: Pick<MCPTool, 'inputSchema' | 'handler'> = {+ inputSchema: { type: 'object', properties: {+ action: { type: 'string', enum: ['status', 'record', 'recommend', 'evaluate', 'index', 'recall', 'cycle'] },+ evidence: { type: 'object', description: 'Closed version1 observation and optional host signature; caller trust labels rejected' },+ scope: { type: 'object', description: 'Exact taskType, policyHash and evaluatorHash cohort' },+ manifest: { type: 'object', description: 'Frozen unique heldout taskHashes and at least three trials' },+ cycle: { type: 'object', description: 'Closed scope/evidence batch, optional index, maxP95Ms and evaluation; no commands, keys or promotion flags' },+ baselineId: { type: 'string' }, candidateId: { type: 'string' }, id: { type: 'string' }, maxP95Ms: { type: 'number' },+ }, required: ['action'] },+ handler: async input => {+ if (input.action !== 'status' && process.env.RUFLO_MANAGED_LEARNING !== '1') return { success: false, error: 'Managed learning writes require host RUFLO_MANAGED_LEARNING=1' };+ const root = getProjectCwd(), key = process.env.RUFLO_MANAGED_VERIFIER_PUBLIC_KEY;+ const authorize = () => process.env.RUFLO_MANAGED_LEARNING === '1' && process.env.RUFLO_MANAGED_VERIFIER_PUBLIC_KEY === key && getProjectCwd() === root;+ try {+ const learning = await import('../services/managed-learning-store.js');+ if (input.action !== 'status' && !authorize()) throw new Error('Host learning policy changed');+ if (input.action === 'cycle') {+ if (Object.keys(input).some(k => !['action', 'cycle'].includes(k))) throw new Error('Invalid cycle envelope');+ const { cycleLearning } = await import('../services/managed-learning-loop.js');+ return { success: true, ...await cycleLearning(root, input.cycle, key, authorize) };+ }+ if (input.action === 'status') return { success: true, ...learning.learningStatus(root, key) };+ if (input.action === 'record') return { success: true, ...learning.recordLearning(root, input.evidence, key) };+ if (input.action === 'recommend') return { success: true, ...learning.recommendLearning(root, input.scope, key, input.maxP95Ms as number | undefined) };+ if (input.action === 'evaluate') return { success: true, ...learning.evaluateLearning(root, { scope: input.scope, manifest: input.manifest, baselineId: String(input.baselineId ?? ''), candidateId: String(input.candidateId ?? '') }, key) };+ if (input.action === 'recall') return { success: true, ...await learning.recallLearning(root, input.scope, key, authorize) };+ if (input.action === 'index') return { success: true, ...await learning.indexLearning(root, String(input.id ?? ''), key, authorize) };+ return { success: false, error: 'Unknown managed learning action' };+ } catch { return { success: false, error: 'Managed learning failed: validate metadata, verifier and store; state may persist, inspect status before retrying; no default changed' }; }+ },+};diff --git a/v3/@claude-flow/cli/src/services/managed-learning-loop.ts b/v3/@claude-flow/cli/src/services/managed-learning-loop.tsnew file mode 100644index 0000000000..6fb3691c2f--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-learning-loop.ts@@ -0,0 +1,63 @@+/** Bounded, replayable feedback cycle. Evaluation is never promotion authority. */+import { digest, evidenceOf, isVerified, manifestOf, scopeOf, trustedEvidence } from './managed-learning.js';+import { evaluateLearning, indexLearning, recallLearning, recordLearningBatch, recommendLearning } from './managed-learning-store.js';++export type ManagedCycleInput = {+ scope: unknown; evidence: unknown[]; index?: boolean; maxP95Ms?: number;+ evaluation?: { manifest: unknown; baselineId: string; candidateId: string };+};++function inputOf(value: unknown): ManagedCycleInput {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected a managed cycle');+ const v = value as Record<string, unknown>;+ if (Object.keys(v).some(k => !['scope', 'evidence', 'index', 'maxP95Ms', 'evaluation'].includes(k)) || !Array.isArray(v.evidence) || v.evidence.length > 24) throw new Error('Managed cycle accepts at most 24 signed outcomes');+ if (v.index !== undefined && typeof v.index !== 'boolean') throw new Error('Invalid indexing request');+ if (v.maxP95Ms !== undefined && (typeof v.maxP95Ms !== 'number' || !Number.isFinite(v.maxP95Ms) || v.maxP95Ms <= 0 || v.maxP95Ms > 86_400_000)) throw new Error('Invalid latency constraint');+ if (v.evaluation !== undefined) {+ const e = v.evaluation as Record<string, unknown>;+ if (!e || typeof e !== 'object' || Array.isArray(e) || Object.keys(e).length !== 3 || Object.keys(e).some(k => !['manifest', 'baselineId', 'candidateId'].includes(k)) || typeof e.baselineId !== 'string' || typeof e.candidateId !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(e.baselineId) || !/^[a-z][a-z0-9-]{0,39}$/.test(e.candidateId) || e.baselineId === e.candidateId) throw new Error('Invalid evaluation request');+ manifestOf(e.manifest);+ }+ scopeOf(v.scope);+ return structuredClone(v) as ManagedCycleInput;+}++/** authorize is host-owned and rechecked across asynchronous boundaries. */+export async function cycleLearning(root: string, value: unknown, publicKey: string | undefined, authorize: () => boolean) {+ const started = performance.now(), input = inputOf(value), scope = scopeOf(input.scope);+ const rows = input.evidence.map(evidenceOf);+ const check = () => { if (!authorize() || !publicKey) throw new Error('Host learning policy or verifier changed'); };+ check();+ // Reject the whole batch before any write; unsigned input cannot start a cycle.+ for (const e of rows) if (!isVerified(e, publicKey) || e.observation.costCents === null || e.observation.durationMs === null || e.observation.taskType !== scope.taskType || e.observation.policyHash !== scope.policyHash || e.observation.evaluatorHash !== scope.evaluatorHash) throw new Error('Every cycle outcome must be authenticated, measured and in scope');+ const trusted = trustedEvidence(rows, publicKey).sort((a, b) => digest(a.observation).localeCompare(digest(b.observation)));+ if (input.index && trusted.filter(e => e.observation.split === 'train').length > 6) throw new Error('Indexing cycles accept at most six training outcomes; split the batch');+ const cycleId = digest({ scope, evidence: trusted.map(e => digest(e.observation)).sort(), evaluation: input.evaluation ?? null, index: input.index ?? false, maxP95Ms: input.maxP95Ms ?? null });+ const recorded: string[] = [], duplicates: string[] = [], indexed: string[] = [], deferred: string[] = [];+ const phases: string[] = ['admitted'];+ // One atomic batch avoids per-row sync/summary work. Later native failures+ // leave a resumable signed batch, never a claimed indexed outcome.+ check();+ for (const r of trusted.length ? recordLearningBatch(root, trusted, publicKey) : []) {+ (r.duplicate ? duplicates : recorded).push(r.id);+ }+ phases.push('recorded');+ let memory: Awaited<ReturnType<typeof recallLearning>> | undefined;+ if (input.index) {+ const training = trusted.filter(e => e.observation.split === 'train');+ for (const e of training.slice(0, 6)) {+ check(); const r = await indexLearning(root, digest(e.observation), publicKey, authorize); check();+ if (r.indexed) indexed.push(r.id); else deferred.push(r.id);+ }+ phases.push('indexed');+ check(); memory = await recallLearning(root, scope, publicKey, authorize); check();+ phases.push('recalled');+ }+ check(); const recommendation = recommendLearning(root, scope, publicKey, input.maxP95Ms);+ phases.push('recommended');+ check(); const evaluation = input.evaluation ? evaluateLearning(root, { scope, ...input.evaluation }, publicKey) : null;+ if (evaluation) phases.push('evaluated');+ return { cycleId, phases, recorded, duplicates, indexed, deferred, recommendation, evaluation,+ memory: memory ? { available: memory.available, recalled: memory.evidence.length, backend: memory.backend } : null,+ elapsedMs: performance.now() - started, advisory: true, defaultsChanged: false, promotionRequested: false };+}diff --git a/v3/@claude-flow/cli/src/services/managed-learning-store.ts b/v3/@claude-flow/cli/src/services/managed-learning-store.tsnew file mode 100644index 0000000000..9af03fda60--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-learning-store.ts@@ -0,0 +1,181 @@+/** Project-local bounded evidence ledger. Local files are revalidated, never trusted by label. */+import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import { nativeMemoryIndex, nativeMemoryRecall } from './managed-memory-client.js';+import { digest, evidenceOf, evaluate, isVerified, manifestOf, recommend, scopeOf, trustedEvidence, type Evidence } from './managed-learning.js';++export const LEARNING_PATH = '.claude-flow/managed-learning/state.json';+const MAX_BYTES = 2_000_000;+type State = { version: 1; records: Evidence[]; confirmations?: Record<string, string>; recommendationInput?: { scope: unknown; maxP95Ms?: number }; evaluationInput?: { scope: unknown; manifest: unknown; baselineId: string; candidateId: string }; lastRecommendation?: ReturnType<typeof recommend>; lastEvaluation?: ReturnType<typeof evaluate>; updatedMs: number };++function directory(root: string, create = false): string {+ let dir = resolve(root);+ if (!lstatSync(dir).isDirectory()) throw new Error('Learning root must be a directory');+ for (const part of ['.claude-flow', 'managed-learning']) {+ dir = join(dir, part);+ if (!existsSync(dir)) { if (create) mkdirSync(dir, { mode: 0o700 }); else return join(resolve(root), '.claude-flow', 'managed-learning'); }+ if (existsSync(dir) && (!lstatSync(dir).isDirectory() || lstatSync(dir).isSymbolicLink())) throw new Error('Learning directory must not be a symlink');+ }+ return dir;+}++function read(dir: string): State {+ const path = join(dir, 'state.json');+ if (!existsSync(path)) return { version: 1, records: [], updatedMs: 0 };+ if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error('Learning state must be a regular file');+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ let text: string;+ try {+ const stat = fstatSync(fd);+ if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error('Learning state exceeds read limit');+ // Fixed buffer also bounds a file that grows after fstat.+ const buffer = Buffer.alloc(MAX_BYTES + 1);+ const size = readSync(fd, buffer, 0, buffer.length, 0);+ if (size > MAX_BYTES) throw new Error('Learning state exceeds read limit');+ text = buffer.subarray(0, size).toString('utf8');+ } finally { closeSync(fd); }+ const value = JSON.parse(text!) as State;+ if (value.version !== 1 || !Array.isArray(value.records) || value.records.length > 500 || !Number.isFinite(value.updatedMs)) throw new Error('Invalid learning state');+ value.records = value.records.map(evidenceOf);+ // Summaries are display-only; never rehydrate them as routing or promotion authority.+ return value;+}++function syncDirectory(dir: string): void { const fd = openSync(dir, constants.O_RDONLY); try { fsyncSync(fd); } finally { closeSync(fd); } }++function mutate<T>(root: string, action: (state: State) => T, publicKey?: string): T {+ const dir = directory(root, true);+ const lockPath = join(dir, 'writer.lock');+ const lock = openSync(lockPath, 'wx', 0o600);+ const temporary = join(dir, `${randomUUID()}.tmp`);+ try {+ syncDirectory(dir); // Refuse unsupported durability semantics before changing the ledger.+ const state = read(dir), result = action(state);+ state.updatedMs = Date.now();+ const payload = JSON.stringify(state);+ if (Buffer.byteLength(payload) > MAX_BYTES) throw new Error('Learning ledger is full');+ const fd = openSync(temporary, 'wx', 0o600);+ try { writeFileSync(fd, payload); fsyncSync(fd); } finally { closeSync(fd); }+ renameSync(temporary, join(dir, 'state.json'));+ syncDirectory(dir);+ // The console reads only this bounded advisory projection, never the full evidence ledger.+ const summary = summaryOf(state, publicKey);+ const summaryText = JSON.stringify(summary);+ if (Buffer.byteLength(summaryText) > 64_000) throw new Error('Learning summary limit exceeded');+ const summaryFd = openSync(temporary, 'wx', 0o600);+ try { writeFileSync(summaryFd, summaryText); fsyncSync(summaryFd); } finally { closeSync(summaryFd); }+ renameSync(temporary, join(dir, 'summary.json'));+ syncDirectory(dir);+ return result;+ } finally {+ if (existsSync(temporary)) unlinkSync(temporary);+ closeSync(lock); unlinkSync(lockPath);+ }+}++function summaryOf(state: State, publicKey?: string) {+ const verified = trustedEvidence(state.records, publicKey);+ let last: ReturnType<typeof recommend> | null = null;+ let evaluation: ReturnType<typeof evaluate> | null = null;+ try { if (state.recommendationInput) last = recommend(verified, scopeOf(state.recommendationInput.scope), state.recommendationInput.maxP95Ms); } catch { /* invalidated advice */ }+ try { if (state.evaluationInput) { const e = state.evaluationInput; evaluation = evaluate(verified, scopeOf(e.scope), manifestOf(e.manifest), e.baselineId, e.candidateId); } } catch { /* invalidated confirmation */ }+ const compact = (r: NonNullable<typeof last>['candidates'][number]) => ({ ...r, evidenceIds: r.evidenceIds.slice(0, 6) });+ return { version: 1, updatedMs: state.updatedMs, observations: state.records.length, verified: verified.length, quarantined: state.records.length - verified.length, training: verified.filter(e => e.observation.split === 'train').length, holdout: verified.filter(e => e.observation.split === 'holdout').length, verifierConfigured: !!publicKey,+ lastRecommendation: last ? { ...last, selected: last.selected ? compact(last.selected) : null, candidates: last.candidates.slice(0, 6).map(compact) } : null,+ lastEvaluation: evaluation ? { ...evaluation, evidenceIds: evaluation.evidenceIds.slice(0, 6) } : null,+ advisory: true, defaultsChanged: false };+}+export function learningStatus(root: string, publicKey?: string) { return summaryOf(read(directory(root)), publicKey); }++function applyRecord(state: State, evidence: Evidence, publicKey?: string) {+ const verified = isVerified(evidence, publicKey);+ const previous = state.records.find(e => e.observation.attemptId === evidence.observation.attemptId && isVerified(e, publicKey));+ if (previous && verified && digest(previous.observation) !== digest(evidence.observation)) throw new Error('Conflicting learning attempt; immutable verified observations cannot be overwritten');+ const duplicate = state.records.find(e => digest(e) === digest(evidence));+ if (duplicate) return { stored: false, duplicate: true, id: digest(evidence.observation), verified };+ const unsigned = state.records.find(e => !e.signature && digest(e.observation) === digest(evidence.observation));+ if (unsigned && verified) { unsigned.signature = evidence.signature; return { stored: true, duplicate: false, id: digest(evidence.observation), verified: true }; }+ if (!verified && state.records.filter(e => !isVerified(e, publicKey)).length >= 100) throw new Error('Learning quarantine is full');+ if (state.records.length >= 500) throw new Error('Learning ledger is full');+ state.records.push(evidence);+ return { stored: true, duplicate: false, id: digest(evidence.observation), verified };+}++/** Validate all input before acquiring the writer lock; publish the batch atomically. */+export function recordLearningBatch(root: string, inputs: unknown[], publicKey?: string) {+ if (!Array.isArray(inputs) || inputs.length < 1 || inputs.length > 24) throw new Error('Learning batch must contain 1 to 24 records');+ const evidence = inputs.map(evidenceOf);+ if (evidence.some(e => e.signature && !isVerified(e, publicKey))) throw new Error('Untrusted or mismatched verifier receipt');+ return mutate(root, state => evidence.map(e => applyRecord(state, e, publicKey)), publicKey);+}++export function recordLearning(root: string, input: unknown, publicKey?: string) {+ return recordLearningBatch(root, [input], publicKey)[0]!;+}++export function recommendLearning(root: string, scope: unknown, publicKey?: string, maxP95Ms?: number) {+ return mutate(root, state => {+ const result = recommend(trustedEvidence(state.records, publicKey), scopeOf(scope), maxP95Ms);+ state.recommendationInput = { scope: scopeOf(scope), maxP95Ms };+ state.lastRecommendation = result;+ return result;+ }, publicKey);+}++export function evaluateLearning(root: string, input: { scope: unknown; manifest: unknown; baselineId: string; candidateId: string }, publicKey?: string) {+ return mutate(root, state => {+ const result = evaluate(trustedEvidence(state.records, publicKey), scopeOf(input.scope), manifestOf(input.manifest), input.baselineId, input.candidateId);+ const cohort = result.corpusHash, experiment = digest({ scope: scopeOf(input.scope), baselineId: input.baselineId, candidateId: input.candidateId });+ if (state.confirmations?.[cohort] && state.confirmations[cohort] !== experiment) throw new Error('Heldout corpus is already bound to another confirmation experiment');+ state.confirmations = { ...(state.confirmations ?? {}), [cohort]: experiment };+ state.evaluationInput = { ...input, scope: scopeOf(input.scope), manifest: manifestOf(input.manifest) };+ state.lastEvaluation = result;+ return result;+ }, publicKey);+}++/** Export only verified training evidence to native append-only AgentDB/RuVector storage. */+export async function indexLearning(root: string, id: string, publicKey?: string, authorize: () => boolean = () => true) {+ if (!/^[a-f0-9]{64}$/.test(id)) throw new Error('Invalid evidence ID');+ const evidence = trustedEvidence(read(directory(root)).records, publicKey).find(e => digest(e.observation) === id && e.observation.split === 'train');+ if (!evidence) throw new Error('Verified training evidence required for indexing');+ if (!authorize()) throw new Error('Managed memory policy denied');+ const result = await nativeMemoryIndex(root, { id, value: JSON.stringify(evidence), taskType: evidence.observation.taskType }, authorize);+ if (!authorize()) throw new Error('Managed memory policy changed; admitted write may have completed');+ if (!result.durable) throw new Error('Native evidence index did not confirm durable persistence');+ return { indexed: result.hasEmbedding, durable: true, namespace: 'managed-workflow-evidence', id, hasEmbedding: result.hasEmbedding, advisory: true };+}++/** Memory similarity supplies recall evidence, never authority or a cherry-picked quality denominator. */+export async function recallLearning(root: string, input: unknown, publicKey?: string, authorize: () => boolean = () => true) {+ const scope = scopeOf(input);+ const local = trustedEvidence(read(directory(root)).records, publicKey).filter(e => e.observation.split === 'train' && e.observation.taskType === scope.taskType && e.observation.policyHash === scope.policyHash && e.observation.evaluatorHash === scope.evaluatorHash);+ const allowed = new Set(local.map(e => digest(e.observation)));+ let result: Awaited<ReturnType<typeof nativeMemoryRecall>>;+ if (!authorize()) throw new Error('Managed memory policy denied');+ try {+ result = await nativeMemoryRecall(root, { taskType: scope.taskType, allowedIds: [...allowed] }, authorize);+ }+ catch {+ if (!authorize()) throw new Error('Managed memory policy denied');+ return { available: false, backend: 'ruflo-memory-child', evidence: [], recommendation: recommend(local, scope), advisory: true, similarityIsVerification: false };+ }+ if (!authorize()) throw new Error('Managed memory policy denied');+ if (!result.available) return { available: false, backend: 'ruflo-memory-child', evidence: [], recommendation: recommend(local, scope), advisory: true, similarityIsVerification: false };+ const seen = new Set<string>();+ const evidence: Array<{ id: string; similarity: number; strategy: Evidence['observation']['strategy']; sourceHash: string }> = [];+ for (const hit of result.rows.slice(0, 20)) {+ if (hit.namespace !== 'managed-workflow-evidence' || !allowed.has(hit.key) || seen.has(hit.key) || !Number.isFinite(hit.score)) continue;+ seen.add(hit.key);+ try {+ // The child hydrates exact native rows, not display previews. The MCP+ // parent still authenticates every receipt and joins the local cohort.+ if (typeof hit.content !== 'string' || Buffer.byteLength(hit.content) > 8192) continue;+ const receipt = evidenceOf(JSON.parse(hit.content));+ if (!isVerified(receipt, publicKey) || digest(receipt.observation) !== hit.key) continue;+ evidence.push({ id: hit.key, similarity: hit.score, strategy: receipt.observation.strategy, sourceHash: receipt.observation.sourceHash });+ } catch { /* A missing or malformed row is not verified recall evidence. */ }+ }+ return { available: true, backend: 'ruflo-memory-child', evidence, recommendation: recommend(local, scope), advisory: true, similarityIsVerification: false };+}diff --git a/v3/@claude-flow/cli/src/services/managed-learning.ts b/v3/@claude-flow/cli/src/services/managed-learning.tsnew file mode 100644index 0000000000..b911933134--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-learning.ts@@ -0,0 +1,173 @@+/** Verified, advisory workflow learning. Caller labels never establish trust. */+import { createHash, createPublicKey, verify } from 'node:crypto';+import { accept } from './harness-benchmark.js';++export const TASK_TYPES = ['code-review', 'migration', 'research', 'test-generation', 'implementation', 'other'] as const;+export type Observation = {+ v: 1; attemptId: string; taskHash: string; sourceHash: string; artifactHash: string;+ policyHash: string; corpusHash: string; evaluatorHash: string;+ taskType: typeof TASK_TYPES[number]; split: 'train' | 'holdout'; trial: number;+ strategy: { id: string; model: string; workers: number; template: string };+ budgetCents: number; costCents: number | null; durationMs: number | null;+ checks: { acceptance: boolean; safety: boolean; replay: boolean; adversarial: boolean; drift: number; driftThreshold: number; rollbackRate: number };+};+export type Evidence = { observation: Observation; signature?: string };+export type Manifest = { taskHashes: string[]; trials: number[] };+const trusted = new WeakSet<object>();+const HASH = /^[a-f0-9]{64}$/;+const ID = /^[a-z][a-z0-9-]{0,39}$/;+const MODEL = /^[a-z][a-z0-9./-]{0,79}$/;+const object = (v: unknown): Record<string, unknown> => {+ if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('Expected an object');+ return v as Record<string, unknown>;+};+function exact(v: Record<string, unknown>, keys: string[]): void {+ if (Object.keys(v).length !== keys.length || Object.keys(v).some(k => !keys.includes(k))) throw new Error('Unknown or missing learning fields');+}+const integer = (v: unknown, min: number, max: number): boolean => typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;+const unit = (v: unknown): boolean => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;++export function canonical(v: unknown): string {+ if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']';+ if (v && typeof v === 'object') return '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonical((v as Record<string, unknown>)[k])).join(',') + '}';+ return JSON.stringify(v);+}+export const digest = (v: unknown): string => createHash('sha256').update(canonical(v)).digest('hex');++/** Closed metadata contract: no prompts, arbitrary commands, transcripts or caller trust labels. */+export function observationOf(value: unknown): Observation {+ const v = object(value);+ exact(v, ['v', 'attemptId', 'taskHash', 'sourceHash', 'artifactHash', 'policyHash', 'corpusHash', 'evaluatorHash', 'taskType', 'split', 'trial', 'strategy', 'budgetCents', 'costCents', 'durationMs', 'checks']);+ if (v.v !== 1 || !TASK_TYPES.includes(v.taskType as Observation['taskType']) || !['train', 'holdout'].includes(v.split as string) || !integer(v.trial, 0, 99)) throw new Error('Invalid learning cohort');+ for (const key of ['attemptId', 'taskHash', 'sourceHash', 'artifactHash', 'policyHash', 'corpusHash', 'evaluatorHash']) if (typeof v[key] !== 'string' || !HASH.test(v[key] as string)) throw new Error('Invalid evidence hash');+ const strategy = object(v.strategy);+ exact(strategy, ['id', 'model', 'workers', 'template']);+ if (!ID.test(String(strategy.id)) || !ID.test(String(strategy.template)) || !MODEL.test(String(strategy.model)) || !integer(strategy.workers, 1, 64)) throw new Error('Invalid workflow strategy');+ if (!integer(v.budgetCents, 1, 999_999_999) || (v.costCents !== null && !integer(v.costCents, 0, 999_999_999)) || (v.durationMs !== null && !integer(v.durationMs, 0, 86_400_000))) throw new Error('Invalid measured cost or duration');+ const checks = object(v.checks);+ exact(checks, ['acceptance', 'safety', 'replay', 'adversarial', 'drift', 'driftThreshold', 'rollbackRate']);+ if (['acceptance', 'safety', 'replay', 'adversarial'].some(k => typeof checks[k] !== 'boolean') || !unit(checks.drift) || !unit(checks.driftThreshold) || !unit(checks.rollbackRate)) throw new Error('Invalid verification measurements');+ // Detach caller objects, including nested strategy/checks, before hashing or persistence.+ return JSON.parse(JSON.stringify(v)) as Observation;+}++export function evidenceOf(value: unknown): Evidence {+ const v = object(value);+ if (Object.keys(v).some(k => !['observation', 'signature'].includes(k))) throw new Error('Unknown evidence fields');+ const observation = observationOf(v.observation);+ // Canonical form only: the last base64 character of a 64-byte signature has 4 unused bits that the decoder ignores, so+ // other spellings of the same bytes would verify yet digest differently and be stored as separate records.+ if (v.signature !== undefined && (typeof v.signature !== 'string' || !/^[A-Za-z0-9+/]{86}==$/.test(v.signature)+ || Buffer.from(v.signature, 'base64').toString('base64') !== v.signature)) throw new Error('Invalid verifier signature');+ return { observation, ...(v.signature ? { signature: v.signature as string } : {}) };+}++/** Public key is configured by the host, never accepted from an MCP argument or stored record. */+export function isVerified(evidence: Evidence, publicKey?: string): boolean {+ if (!publicKey || !evidence.signature) return false;+ try {+ const key = createPublicKey(publicKey);+ return key.asymmetricKeyType === 'ed25519' && verify(null, Buffer.from(canonical(evidence.observation)), key, Buffer.from(evidence.signature, 'base64'));+ } catch { return false; }+}++/** Revalidate every persisted record on each use; a JSON provenance label is not authority. */+export function trustedEvidence(records: unknown[], publicKey?: string): Evidence[] {+ const out: Evidence[] = [];+ const ids = new Map<string, string>();+ for (const raw of records) {+ const e = evidenceOf(raw);+ if (!isVerified(e, publicKey) || e.observation.costCents === null || e.observation.durationMs === null) continue;+ const hash = digest(e.observation);+ const previous = ids.get(e.observation.attemptId);+ if (previous && previous !== hash) throw new Error('Conflicting learning attempt');+ if (previous) continue;+ ids.set(e.observation.attemptId, hash);+ {+ Object.freeze(e.observation.strategy); Object.freeze(e.observation.checks); Object.freeze(e.observation); Object.freeze(e);+ trusted.add(e); out.push(e);+ }+ }+ return out;+}++export function manifestOf(value: unknown): Manifest {+ const m = object(value); exact(m, ['taskHashes', 'trials']);+ if (!Array.isArray(m.taskHashes) || m.taskHashes.length < 2 || m.taskHashes.length > 100 || m.taskHashes.some(h => typeof h !== 'string' || !HASH.test(h)) || new Set(m.taskHashes).size !== m.taskHashes.length) throw new Error('Manifest needs 2 to 100 unique task hashes');+ if (!Array.isArray(m.trials) || m.trials.length < 3 || m.trials.length > 10 || m.trials.some(t => !integer(t, 0, 99)) || new Set(m.trials).size !== m.trials.length) throw new Error('Manifest needs 3 to 10 unique trials');+ return { taskHashes: [...m.taskHashes].sort() as string[], trials: [...m.trials].sort((a, b) => a - b) as number[] };+}++export type Scope = { taskType: Observation['taskType']; policyHash: string; evaluatorHash: string };+export function scopeOf(value: unknown): Scope {+ const s = object(value); exact(s, ['taskType', 'policyHash', 'evaluatorHash']);+ if (!TASK_TYPES.includes(s.taskType as Observation['taskType']) || !HASH.test(String(s.policyHash)) || !HASH.test(String(s.evaluatorHash))) throw new Error('Invalid recommendation scope');+ return { taskType: s.taskType as Scope['taskType'], policyHash: s.policyHash as string, evaluatorHash: s.evaluatorHash as string };+}+const inScope = (o: Observation, s: Scope): boolean => o.taskType === s.taskType && o.policyHash === s.policyHash && o.evaluatorHash === s.evaluatorHash;+const success = (o: Observation): number => o.checks.acceptance && o.checks.safety ? 1 : 0;+const p95 = (values: number[]): number => [...values].sort((a, b) => a - b)[Math.max(0, Math.ceil(values.length * .95) - 1)] ?? 0;++/** Training evidence only; holdout records and unsigned observations cannot influence a pick. */+export function recommend(records: Evidence[], scope: Scope, maxP95Ms = 86_400_000) {+ if (records.some(e => !trusted.has(e))) throw new Error('Host-verified evidence required');+ if (!integer(maxP95Ms, 1, 86_400_000)) throw new Error('Invalid latency constraint');+ const groups = new Map<string, Evidence[]>();+ for (const e of records) {+ if (e.observation.split !== 'train' || !inScope(e.observation, scope)) continue;+ const key = canonical(e.observation.strategy);+ groups.set(key, [...(groups.get(key) ?? []), e]);+ }+ const candidates = [...groups.values()].flatMap(rows => {+ if (rows.length < 3 || new Set(rows.map(r => r.observation.taskHash)).size < 3) return [];+ const totalCost = rows.reduce((n, r) => n + (r.observation.costCents ?? 0), 0);+ const latency = p95(rows.map(r => r.observation.durationMs!));+ if (totalCost <= 0 || latency > maxP95Ms || rows.some(r => !r.observation.checks.safety)) return [];+ const successes = rows.reduce((n, r) => n + success(r.observation), 0);+ if (successes === 0) return [];+ return [{ strategy: rows[0]!.observation.strategy, samples: rows.length, successes, successRate: successes / rows.length, successesPerDollar: successes * 100 / totalCost, p95Ms: latency, evidenceIds: rows.map(r => digest(r.observation)).sort() }];+ }).sort((a, b) => b.successesPerDollar - a.successesPerDollar || a.p95Ms - b.p95Ms || canonical(a.strategy).localeCompare(canonical(b.strategy)));+ return { advisory: true, selected: candidates[0] ?? null, candidates, abstained: candidates.length === 0, reason: candidates.length ? 'Ranked by measured training successes per dollar within exact policy/evaluator scope' : 'Insufficient trusted training evidence within scope and latency constraint', defaultsChanged: false };+}++/** Complete paired heldout data, equal admitted budgets, source identity and existing MetaHarness conjunction. */+export function evaluate(records: Evidence[], scope: Scope, manifest: Manifest, baselineId: string, candidateId: string) {+ if (records.some(e => !trusted.has(e))) throw new Error('Host-verified evidence required');+ if (!ID.test(baselineId) || !ID.test(candidateId) || baselineId === candidateId) throw new Error('Distinct strategy IDs required');+ const corpusHash = digest(manifest);+ const relevant = records.filter(e => inScope(e.observation, scope) && [baselineId, candidateId].includes(e.observation.strategy.id));+ const trainingTasks = new Set(records.filter(e => inScope(e.observation, scope) && e.observation.split === 'train').map(e => e.observation.taskHash));+ if (manifest.taskHashes.some(h => trainingTasks.has(h))) throw new Error('Training and heldout tasks overlap');+ const rows = relevant.filter(e => e.observation.split === 'holdout' && e.observation.corpusHash === corpusHash);+ for (const id of [baselineId, candidateId]) if (new Set(rows.filter(r => r.observation.strategy.id === id).map(r => canonical(r.observation.strategy))).size !== 1) throw new Error('Missing or inconsistent strategy configuration');+ const paired: Array<[Observation, Observation]> = [];+ for (const taskHash of manifest.taskHashes) for (const trial of manifest.trials) {+ const pick = (id: string) => rows.filter(e => e.observation.taskHash === taskHash && e.observation.trial === trial && e.observation.strategy.id === id);+ const base = pick(baselineId), candidate = pick(candidateId);+ if (base.length !== 1 || candidate.length !== 1) throw new Error('Missing or duplicate paired heldout result');+ const b = base[0]!.observation, c = candidate[0]!.observation;+ if (b.sourceHash !== c.sourceHash || b.budgetCents !== c.budgetCents) throw new Error('Source identity or admitted budgets differ');+ paired.push([b, c]);+ }+ const base = paired.map(p => p[0]), candidate = paired.map(p => p[1]);+ const efficiency = (rows: Observation[]) => {+ const cost = rows.reduce((n, r) => n + r.costCents!, 0);+ if (cost <= 0) throw new Error('Positive measured cost required');+ return rows.reduce((n, r) => n + success(r), 0) * 100 / cost;+ };+ const baselineEfficiency = efficiency(base), candidateEfficiency = efficiency(candidate);+ if (baselineEfficiency <= 0) throw new Error('Nonzero baseline success required for relative improvement');+ const delta = candidateEfficiency / baselineEfficiency - 1;+ const total = baselineEfficiency + candidateEfficiency;+ const all = [...base, ...candidate];+ const gate = accept({+ heldOutScore: candidateEfficiency / total, baselineHeldOutScore: baselineEfficiency / total,+ redblue: all.every(o => o.checks.adversarial) ? 'PASS' : 'FAIL',+ drift: Math.max(...candidate.map(o => o.checks.drift)), driftThreshold: Math.min(...candidate.map(o => o.checks.driftThreshold)),+ replayDeterministic: all.every(o => o.checks.replay), receiptCoverage: 1,+ canaryRollbackRate: Math.max(...candidate.map(o => o.checks.rollbackRate)), baselineRollbackRate: Math.max(...base.map(o => o.checks.rollbackRate)),+ });+ const noRegression = paired.every(([b, c]) => success(c) >= success(b)) && all.every(o => o.checks.safety);+ const baselineP95Ms = p95(base.map(o => o.durationMs!)), candidateP95Ms = p95(candidate.map(o => o.durationMs!));+ return { advisory: true, eligible: gate.accept && delta >= .10 - Number.EPSILON && noRegression && candidateP95Ms <= baselineP95Ms, baselineP95Ms, candidateP95Ms, delta, baselineEfficiency, candidateEfficiency, pairedResults: paired.length, corpusHash, noRegression, metaharness: gate, defaultsChanged: false, evidenceIds: rows.map(r => digest(r.observation)).sort() };+}diff --git a/v3/@claude-flow/cli/src/services/managed-memory-client.ts b/v3/@claude-flow/cli/src/services/managed-memory-client.tsnew file mode 100644index 0000000000..13e295362a--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-memory-client.ts@@ -0,0 +1,163 @@+/** Native memory runs behind a bounded child boundary, never in the MCP process. */+import { fork, type ChildProcess } from 'node:child_process';+import { existsSync, realpathSync, statSync } from 'node:fs';+import { createRequire } from 'node:module';+import { randomUUID } from 'node:crypto';+import { fileURLToPath } from 'node:url';++export const MANAGED_MEMORY_NAMESPACE = 'managed-workflow-evidence';+export const MANAGED_MEMORY_LIMITS = { workers: 1, requestBytes: 80_000, resultBytes: 200_000, rows: 20, rowBytes: 8192, timeoutMs: 15_000, idleMs: 5000 } as const;+const HASH = /^[a-f0-9]{64}$/;+const TYPES = ['code-review', 'migration', 'research', 'test-generation', 'implementation', 'other'];+export type MemoryRequest = { operation: 'index'; id: string; value: string; taskType: string } | { operation: 'recall'; taskType: string; allowedIds: string[] };+export type MemoryRow = { key: string; namespace: typeof MANAGED_MEMORY_NAMESPACE; score: number; content: string };+export type MemoryResult = { operation: 'index'; durable: true; hasEmbedding: boolean } | { operation: 'recall'; available: boolean; rows: MemoryRow[] };+type Slot = { child: ChildProcess; root: string; busy: boolean; lastUsed: number; timer?: ReturnType<typeof setTimeout>; fail?: () => void };++function requestOf(value: unknown): MemoryRequest {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid managed memory request');+ const r = value as Record<string, unknown>;+ const keys = r.operation === 'index' ? ['operation', 'id', 'value', 'taskType'] : ['operation', 'taskType', 'allowedIds'];+ if (!['index', 'recall'].includes(String(r.operation)) || Object.keys(r).length !== keys.length || Object.keys(r).some(k => !keys.includes(k)) || !TYPES.includes(String(r.taskType))) throw new Error('Invalid managed memory request');+ if (r.operation === 'index' && (typeof r.id !== 'string' || !HASH.test(r.id) || typeof r.value !== 'string' || Buffer.byteLength(r.value) > MANAGED_MEMORY_LIMITS.rowBytes)) throw new Error('Invalid managed index request');+ if (r.operation === 'recall' && (!Array.isArray(r.allowedIds) || r.allowedIds.length > 500 || r.allowedIds.some(id => typeof id !== 'string' || !HASH.test(id)))) throw new Error('Invalid managed recall request');+ if (Buffer.byteLength(JSON.stringify(r)) > MANAGED_MEMORY_LIMITS.requestBytes) throw new Error('Managed memory request limit exceeded');+ return JSON.parse(JSON.stringify(r)) as MemoryRequest;+}++function resultOf(value: unknown, operation: MemoryRequest['operation'], requestId: string): MemoryResult {+ if (!value || typeof value !== 'object' || Array.isArray(value) || Buffer.byteLength(JSON.stringify(value)) > MANAGED_MEMORY_LIMITS.resultBytes) throw new Error('Invalid managed memory worker response');+ const r = value as Record<string, unknown>;+ if (r.v !== 1 || r.ok !== true || r.operation !== operation || r.requestId !== requestId) throw new Error('Managed native memory worker did not complete');+ if (operation === 'index') {+ if (Object.keys(r).some(k => !['v', 'ok', 'requestId', 'operation', 'durable', 'hasEmbedding'].includes(k)) || r.durable !== true || typeof r.hasEmbedding !== 'boolean') throw new Error('Unconfirmed managed memory persistence');+ return { operation, durable: true, hasEmbedding: r.hasEmbedding };+ }+ if (Object.keys(r).some(k => !['v', 'ok', 'requestId', 'operation', 'available', 'rows'].includes(k)) || typeof r.available !== 'boolean' || !Array.isArray(r.rows) || r.rows.length > MANAGED_MEMORY_LIMITS.rows) throw new Error('Invalid managed recall response');+ for (const raw of r.rows) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid managed recall row');+ const row = raw as Record<string, unknown>;+ if (Object.keys(row).length !== 4 || Object.keys(row).some(k => !['key', 'namespace', 'score', 'content'].includes(k)) || typeof row.key !== 'string' || !HASH.test(row.key) || row.namespace !== MANAGED_MEMORY_NAMESPACE || typeof row.score !== 'number' || !Number.isFinite(row.score) || row.score < -1 || row.score > 1 || typeof row.content !== 'string' || Buffer.byteLength(row.content) > MANAGED_MEMORY_LIMITS.rowBytes) throw new Error('Invalid managed recall row');+ }+ return { operation, available: r.available, rows: r.rows as MemoryRow[] };+}++function sourceLoader(): string {+ try { return createRequire(import.meta.url).resolve('tsx'); } catch { /* npx tsx can live outside project node_modules */ }+ for (let i = 0; i < process.execArgv.length; i++) {+ const arg = process.execArgv[i]!;+ const path = arg === '--import' ? process.execArgv[i + 1] : arg.startsWith('--import=') ? arg.slice(9) : undefined;+ if (!path) continue;+ const file = path.startsWith('file:') ? fileURLToPath(path) : path;+ if (/[/\\]node_modules[/\\]tsx[/\\]dist[/\\](?:loader\.mjs|esm[/\\]index\.mjs)$/.test(file) && existsSync(file)) return file;+ }+ throw new Error('Source managed memory worker requires tsx');+}++function launch(root: string): ChildProcess {+ const js = new URL('./managed-memory-worker.js', import.meta.url), ts = new URL('./managed-memory-worker.ts', import.meta.url);+ const compiled = existsSync(fileURLToPath(js));+ const entry = compiled ? js : ts;+ if (!existsSync(fileURLToPath(entry))) throw new Error('Managed memory worker is not installed');+ // Production uses emitted JS. Source development uses the project's declared+ // tsx dependency so internal .js imports resolve to TypeScript sources.+ const args = compiled ? [] : ['--import', sourceLoader()];+ const env: NodeJS.ProcessEnv = {};+ for (const key of ['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'CLAUDE_FLOW_DISABLE_BRIDGE', 'CLAUDE_FLOW_ENABLE_NATIVE_BRIDGE_ON_WINDOWS']) if (process.env[key] !== undefined) env[key] = process.env[key];+ // No provider credentials or startup hooks are inherited. Existing local+ // models may be used; indexing never initiates a model download.+ env.CLAUDE_FLOW_CWD = root; env.HF_HUB_OFFLINE = '1'; env.TRANSFORMERS_OFFLINE = '1';+ return fork(entry, [], { cwd: root, env, execArgv: args, stdio: ['ignore', 'ignore', 'ignore', 'ipc'], serialization: 'json' });+}++/** The optional fork callback is an in-process host test seam, not a serialized tool argument. */+export class ManagedMemoryClient {+ private readonly slots = new Map<string, Slot>();+ private readonly timeoutMs: number;+ private readonly idleMs: number;+ private readonly forkWorker: (root: string) => ChildProcess;+ constructor(options: { timeoutMs?: number; idleMs?: number; forkWorker?: (root: string) => ChildProcess } = {}) {+ this.timeoutMs = options.timeoutMs ?? MANAGED_MEMORY_LIMITS.timeoutMs;+ this.idleMs = options.idleMs ?? MANAGED_MEMORY_LIMITS.idleMs;+ this.forkWorker = options.forkWorker ?? launch;+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < 20 || this.timeoutMs > 60_000 || !Number.isFinite(this.idleMs) || this.idleMs < 20 || this.idleMs > 30_000) throw new Error('Invalid managed memory worker limits');+ }++ run(root: string, raw: unknown, authorize: () => boolean = () => true): Promise<MemoryResult> {+ let input: MemoryRequest, cwd: string;+ try {+ input = requestOf(raw); cwd = realpathSync(root);+ if (!statSync(cwd).isDirectory()) throw new Error('Invalid learning project root');+ } catch { return Promise.reject(new Error('Invalid managed memory operation or project root')); }+ try { if (!authorize()) return Promise.reject(new Error('Managed memory policy denied')); } catch { return Promise.reject(new Error('Managed memory policy denied')); }+ let slot = this.slots.get(cwd);+ if (slot?.busy) return Promise.reject(new Error('Managed memory worker is busy; retry later'));+ if (!slot) {+ if (this.slots.size >= MANAGED_MEMORY_LIMITS.workers) {+ const idle = [...this.slots.values()].filter(s => !s.busy).sort((a, b) => a.lastUsed - b.lastUsed)[0];+ if (!idle) return Promise.reject(new Error('Managed memory worker limit reached; retry later'));+ this.remove(idle);+ }+ try {+ slot = { child: this.forkWorker(cwd), root: cwd, busy: false, lastUsed: Date.now() };+ this.slots.set(cwd, slot);+ const owned = slot;+ slot.child.once('error', () => { owned.fail?.(); this.remove(owned); });+ slot.child.once('exit', () => { owned.fail?.(); this.remove(owned); });+ } catch { return Promise.reject(new Error('Managed native memory worker unavailable')); }+ }+ const owned = slot;+ const requestId = randomUUID();+ if (owned.timer) clearTimeout(owned.timer);+ owned.busy = true;+ return new Promise<MemoryResult>((resolve, reject) => {+ let settled = false, policyDenied = false, ready = false, writeGranted = false;+ const complete = (result?: MemoryResult) => {+ if (settled) return; settled = true; clearTimeout(timeout);+ owned.child.off('message', onMessage); owned.fail = undefined; owned.busy = false; owned.lastUsed = Date.now();+ if (result) {+ owned.timer = setTimeout(() => this.remove(owned), this.idleMs); owned.timer.unref();+ owned.child.unref(); owned.child.channel?.unref();+ resolve(result);+ } else { this.remove(owned); reject(new Error(policyDenied ? (writeGranted ? 'Managed memory policy changed; admitted write may have completed' : 'Managed memory policy denied before dispatch') : 'Managed native memory operation failed or timed out; parent remains available')); }+ };+ const onMessage = (value: unknown) => {+ try {+ if (!authorize()) { policyDenied = true; complete(); return; }+ const message = value as Record<string, unknown> | null;+ if (message?.phase !== undefined) {+ if (Object.keys(message).length !== 3 || message.v !== 1 || message.requestId !== requestId || !['ready', 'before-write'].includes(String(message.phase))) throw new Error('Invalid worker grant request');+ if (message.phase === 'ready') { if (ready) throw new Error('Repeated worker ready'); ready = true; }+ else { if (!ready || writeGranted || input.operation !== 'index') throw new Error('Invalid worker write grant'); writeGranted = true; }+ owned.child.send({ v: 1, requestId, grant: message.phase === 'ready' ? 'execute' : 'write' }, error => { if (error) complete(); });+ return;+ }+ if (!ready) throw new Error('Worker was not ready');+ complete(resultOf(value, input.operation, requestId));+ } catch { complete(); }+ };+ const timeout = setTimeout(() => complete(), this.timeoutMs);+ owned.fail = () => complete(); owned.child.on('message', onMessage);+ try {+ if (!authorize()) { policyDenied = true; complete(); return; }+ owned.child.send({ v: 1, requestId, ...input }, error => { if (error) complete(); });+ } catch { policyDenied = true; complete(); }+ });+ }++ stats(): { workers: number; busy: number } { return { workers: this.slots.size, busy: [...this.slots.values()].filter(s => s.busy).length }; }+ close(): void { for (const slot of [...this.slots.values()]) { slot.fail?.(); this.remove(slot); } }+ private remove(slot: Slot): void {+ if (slot.timer) clearTimeout(slot.timer);+ if (this.slots.get(slot.root) === slot) this.slots.delete(slot.root);+ if (!slot.child.killed) slot.child.kill('SIGKILL');+ }+}++export const managedMemoryClient = new ManagedMemoryClient();+export async function nativeMemoryIndex(root: string, input: Omit<Extract<MemoryRequest, { operation: 'index' }>, 'operation'>, authorize?: () => boolean) {+ return await managedMemoryClient.run(root, { operation: 'index', ...input }, authorize) as Extract<MemoryResult, { operation: 'index' }>;+}+export async function nativeMemoryRecall(root: string, input: Omit<Extract<MemoryRequest, { operation: 'recall' }>, 'operation'>, authorize?: () => boolean) {+ return await managedMemoryClient.run(root, { operation: 'recall', ...input }, authorize) as Extract<MemoryResult, { operation: 'recall' }>;+}diff --git a/v3/@claude-flow/cli/src/services/managed-memory-worker.ts b/v3/@claude-flow/cli/src/services/managed-memory-worker.tsnew file mode 100644index 0000000000..f858649a44--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-memory-worker.ts@@ -0,0 +1,135 @@+/** Fixed child entry. Native dependency loading must never move into the MCP parent. */+import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { pathToFileURL } from 'node:url';+import { createRequire } from 'node:module';++const NAMESPACE = 'managed-workflow-evidence';+const HASH = /^[a-f0-9]{64}$/;+const UUID = /^[a-f0-9-]{36}$/;+const TYPES = ['code-review', 'migration', 'research', 'test-generation', 'implementation', 'other'];+type Request = { v: 1; requestId: string; operation: 'index'; id: string; value: string; taskType: string } | { v: 1; requestId: string; operation: 'recall'; taskType: string; allowedIds: string[] };+type Row = { key: string; namespace: string; content: string; hasEmbedding?: boolean };+export type NativeMemoryAdapter = {+ getEntry: (options: Record<string, unknown>) => Promise<{ success: boolean; found: boolean; entry?: Row } | null>;+ storeEntry: (options: Record<string, unknown>) => Promise<{ success: boolean; persistWarning?: unknown; embedding?: { dimensions?: number }; error?: unknown } | null>;+ searchEntries: (options: Record<string, unknown>) => Promise<{ success: boolean; results: Array<{ key: string; namespace: string; score: number }> } | null>;+};++function requestOf(raw: unknown): Request {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Buffer.byteLength(JSON.stringify(raw)) > 80_000) throw new Error('invalid-request');+ const r = raw as Record<string, unknown>;+ const keys = r.operation === 'index' ? ['v', 'requestId', 'operation', 'id', 'value', 'taskType'] : ['v', 'requestId', 'operation', 'taskType', 'allowedIds'];+ if (r.v !== 1 || typeof r.requestId !== 'string' || !UUID.test(r.requestId) || !['index', 'recall'].includes(String(r.operation)) || Object.keys(r).length !== keys.length || Object.keys(r).some(k => !keys.includes(k)) || !TYPES.includes(String(r.taskType))) throw new Error('invalid-request');+ if (r.operation === 'index' && (typeof r.id !== 'string' || !HASH.test(r.id) || typeof r.value !== 'string' || Buffer.byteLength(r.value) > 8192)) throw new Error('invalid-request');+ if (r.operation === 'recall' && (!Array.isArray(r.allowedIds) || r.allowedIds.length > 500 || r.allowedIds.some(id => typeof id !== 'string' || !HASH.test(id)))) throw new Error('invalid-request');+ return r as unknown as Request;+}++const validRow = (row: Row | undefined, key: string): row is Row => !!row && row.key === key && row.namespace === NAMESPACE && typeof row.content === 'string' && Buffer.byteLength(row.content) <= 8192;++/** Pure operation seam for host tests. Serialized callers cannot supply an adapter. */+export async function executeManagedMemory(raw: unknown, adapter: NativeMemoryAdapter, dbPath: string, beforeWrite?: () => Promise<void>) {+ const r = requestOf(raw);+ if (r.operation === 'index') {+ const existing = await adapter.getEntry({ key: r.id, namespace: NAMESPACE, dbPath });+ if (!existing?.success) throw new Error('backend-unavailable');+ if (existing.found) {+ if (!validRow(existing.entry, r.id) || existing.entry.content !== r.value) throw new Error('conflicting-index');+ return { v: 1, requestId: r.requestId, ok: true, operation: 'index', durable: true, hasEmbedding: existing.entry.hasEmbedding === true };+ }+ await beforeWrite?.();+ const result = await adapter.storeEntry({ key: r.id, namespace: NAMESPACE, value: r.value, tags: ['managed-workflow', r.taskType], generateEmbeddingFlag: true, upsert: false, requireNative: true, appendOnly: true, dbPath, provenanceType: 'system_observation' });+ if (!result?.success || result.persistWarning) throw new Error('persistence-unconfirmed');+ // Observe the exact durable row after the append. Neither success nor a+ // signed local ledger alone establishes that the native row exists.+ const stored = await adapter.getEntry({ key: r.id, namespace: NAMESPACE, dbPath });+ if (!stored?.success || !stored.found || !validRow(stored.entry, r.id) || stored.entry.content !== r.value) throw new Error('persistence-unconfirmed');+ return { v: 1, requestId: r.requestId, ok: true, operation: 'index', durable: true, hasEmbedding: stored.entry.hasEmbedding === true };+ }+ const result = await adapter.searchEntries({ query: `managed workflow ${r.taskType}`, namespace: NAMESPACE, limit: 20, threshold: 0, dbPath });+ if (!result?.success || !Array.isArray(result.results)) return { v: 1, requestId: r.requestId, ok: true, operation: 'recall', available: false, rows: [] };+ const allowed = new Set(r.allowedIds), seen = new Set<string>();+ const rows: Array<{ key: string; namespace: string; score: number; content: string }> = [];+ for (const hit of result.results.slice(0, 20)) {+ if (!hit || hit.namespace !== NAMESPACE || typeof hit.key !== 'string' || !HASH.test(hit.key) || !allowed.has(hit.key) || seen.has(hit.key) || !Number.isFinite(hit.score) || hit.score < -1 || hit.score > 1) continue;+ seen.add(hit.key);+ const hydrated = await adapter.getEntry({ key: hit.key, namespace: NAMESPACE, dbPath });+ if (hydrated?.success && hydrated.found && validRow(hydrated.entry, hit.key)) rows.push({ key: hit.key, namespace: NAMESPACE, score: hit.score, content: hydrated.entry.content });+ }+ return { v: 1, requestId: r.requestId, ok: true, operation: 'recall', available: true, rows };+}++function databasePath(): string {+ const root = realpathSync(process.cwd()), dir = join(root, '.swarm');+ if (!existsSync(dir)) mkdirSync(dir, { mode: 0o700 });+ if (lstatSync(dir).isSymbolicLink() || !lstatSync(dir).isDirectory()) throw new Error('backend-unavailable');+ const path = join(dir, 'memory.db');+ if (existsSync(path) && (lstatSync(path).isSymbolicLink() || !lstatSync(path).isFile())) throw new Error('backend-unavailable');+ return path;+}++async function loadNative(dbPath: string): Promise<NativeMemoryAdapter> {+ // Transformers.js does not consistently honor the Python offline env flags.+ // Configure the exact module identity AgentDB loads, before registry init.+ const require = createRequire(import.meta.url);+ const memoryEntry = require.resolve('@claude-flow/memory');+ const agentEntry = createRequire(memoryEntry).resolve('agentdb');+ const owner = createRequire(agentEntry);+ for (const name of ['@huggingface/transformers', '@xenova/transformers']) {+ let path: string;+ try { path = owner.resolve(name); } catch { continue; }+ const modulePath = pathToFileURL(path).href;+ const model = await import(modulePath) as { env?: { allowRemoteModels: boolean } };+ if (model.env) model.env.allowRemoteModels = false;+ }+ const js = new URL('../memory/memory-bridge.js', import.meta.url);+ const moduleUrl = existsSync(fileURLToPath(js)) ? js : new URL('../memory/memory-bridge.ts', import.meta.url);+ // Deliberately nonliteral import: targeted boundary builds do not pull the+ // optional native dependency graph into the parent compilation.+ const modulePath = moduleUrl.href;+ const bridge = await import(modulePath) as Record<string, any>;+ const registry = await bridge.getControllerRegistry(dbPath);+ const agentdb = registry?.getAgentDB?.(), db = agentdb?.database;+ if (!db || agentdb.isWasm === true || typeof db.inTransaction !== 'boolean' || typeof db.transaction !== 'function' || db.memory !== false || typeof db.name !== 'string' || resolve(db.name) !== resolve(dbPath)) throw new Error('backend-unavailable');+ return { getEntry: bridge.bridgeGetEntry, searchEntries: bridge.bridgeSearchEntries, storeEntry: bridge.bridgeStoreEntry };+}++if (typeof process.send === 'function' && process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ let busy = false;+ let idle: ReturnType<typeof setTimeout> | undefined;+ let adapter: Promise<NativeMemoryAdapter> | undefined;+ let pendingGrant: { id: string; grant: string; resolve: () => void } | undefined;+ const ask = (id: string, phase: 'ready' | 'before-write') => new Promise<void>(resolve => {+ pendingGrant = { id, grant: phase === 'ready' ? 'execute' : 'write', resolve };+ process.send?.({ v: 1, requestId: id, phase });+ });+ process.once('disconnect', () => process.exit(0));+ process.on('message', async value => {+ if (value && typeof value === 'object' && 'grant' in value) {+ const message = value as Record<string, unknown>;+ if (Object.keys(message).length === 3 && message.v === 1 && message.requestId === pendingGrant?.id && message.grant === pendingGrant?.grant) { const grant = pendingGrant; pendingGrant = undefined; grant?.resolve(); }+ return;+ }+ if (idle) clearTimeout(idle);+ let request: Request;+ try { request = requestOf(value); } catch { process.send?.({ v: 1, ok: false, error: 'invalid-request' }); return; }+ if (busy) { process.send?.({ v: 1, requestId: request.requestId, ok: false, error: 'worker-busy' }); return; }+ busy = true;+ try {+ const path = databasePath();+ adapter ??= loadNative(path);+ const native = await adapter;+ await ask(request.requestId, 'ready');+ const result = await executeManagedMemory(request, native, path, () => ask(request.requestId, 'before-write'));+ if (Buffer.byteLength(JSON.stringify(result)) > 200_000) throw new Error('result-limit');+ process.send?.(result);+ } catch {+ // Upstream errors may carry prompts, SQL, paths or credentials.+ process.send?.({ v: 1, requestId: request.requestId, ok: false, error: 'native-operation-unavailable' });+ } finally {+ busy = false; idle = setTimeout(() => process.exit(0), 5000);+ }+ });+}diff --git a/v3/@claude-flow/cli/src/services/managed-run-collector.ts b/v3/@claude-flow/cli/src/services/managed-run-collector.tsnew file mode 100644index 0000000000..939ee7065e--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-run-collector.ts@@ -0,0 +1,175 @@+/** One explicit, bounded event collector per managed session. No background traffic. */+import { isDeepStrictEqual } from 'node:util';+import { eventPage, ManagedProgress, type ManagedEvent } from './managed-workflows.js';++export type ManagedSessionFacts = {+ status?: string;+ budget?: { max_list_cost?: { amount?: string; currency?: string } };+ usage?: { list_cost?: { amount?: string; currency?: string } };+};+export type ManagedCollectorTransport = {+ readEvents: (since?: string) => Promise<ManagedEvent[]>;+ readSession: () => Promise<ManagedSessionFacts>;+};+type Phase = { id: string; name: string; status: string };+type Thread = { id: string; runId: string | null; status: string; phaseId?: string };+export type ManagedRunSnapshot = {+ sessionId: string; status: string; stopReason: string | null; budgetCents: number | null; listCostCents: number | null;+ providerFinished: boolean; workersInspected: false; acceptancePassed: false; verification: 'unverified';+ runs: Array<{ id: string; status: string; result?: string; phases: Phase[] }>;+ threads: Thread[]; threadOffset: number; threadCount: number; threadCounts: { running: number; ended: number; failed: number; idle: number };+ blockedEventIds: string[]; observedFailures: number; updatedMs: number;+};+export type ManagedCollection = { events: ManagedEvent[]; snapshot: ManagedRunSnapshot };+type State = {+ events: Map<string, ManagedEvent>; bytes: number; progress: ManagedProgress; threads: Map<string, Thread>;+ phases: Map<string, Map<string, Phase>>; blocked: Set<string>; session: ManagedSessionFacts;+ flight?: Promise<ManagedCollection>; result?: ManagedCollection; lastRead: number; lastUsed: number;+};+export const COLLECTOR_LIMITS = { sessions: 6, events: 10_000, bytes: 16_000_000, shownThreads: 60, staleMs: 300_000 } as const;+const idOf = (v: unknown): string | undefined => typeof v === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(v) ? v : undefined;+const record = (v: unknown): Record<string, unknown> | undefined => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined;+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;+const cents = (v: unknown): number | null => {+ const r = record(v);+ return r && (r.currency === undefined || r.currency === 'USD') && typeof r.amount === 'string' && /^(?:0|[1-9][0-9]{0,8})$/.test(r.amount) ? Number(r.amount) : null;+};+const phaseName = (v: unknown, fallback: string): string => {+ if (typeof v !== 'string') return fallback;+ if (/sk-|ghp_|github_pat_|hf_|npm_|xox|AKIA|AIza|Bearer|PRIVATE KEY|password|secret|credential|[A-Za-z0-9_=-]{24,}|token["']?\s*[:=]/i.test(v)) return '[redacted phase]';+ return v.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, '').slice(0, 80) || fallback;+};++/** This cache is an observation aid. Cached facts never authorize an action. */+export class ManagedRunCollector {+ private readonly states = new Map<string, State>();+ private readonly now: () => number;+ private readonly ttlMs: number;+ constructor(options: { now?: () => number; ttlMs?: number } = {}) {+ this.now = options.now ?? Date.now;+ this.ttlMs = options.ttlMs ?? 1000;+ if (!Number.isFinite(this.ttlMs) || this.ttlMs < 0 || this.ttlMs > 60_000) throw new Error('Invalid collector TTL');+ }++ /** Singleflight includes event and session reads; a failed refresh is never cached as success. */+ refresh(sessionId: string, transport: ManagedCollectorTransport): Promise<ManagedCollection> {+ if (!idOf(sessionId)) return Promise.reject(new Error('Invalid managed session ID'));+ let state = this.states.get(sessionId);+ if (!state) {+ if (this.states.size >= COLLECTOR_LIMITS.sessions) {+ const oldest = [...this.states.entries()].filter(([, s]) => !s.flight && (this.now() - s.lastUsed >= COLLECTOR_LIMITS.staleMs || ['idle', 'terminated', 'error'].includes(s.result?.snapshot.status ?? 'unknown'))).sort((a, b) => a[1].lastUsed - b[1].lastUsed)[0];+ if (!oldest) return Promise.reject(new Error('Managed collector session limit reached'));+ this.states.delete(oldest[0]);+ }+ state = { events: new Map(), bytes: 0, progress: new ManagedProgress(), threads: new Map(), phases: new Map(), blocked: new Set(), session: {}, lastRead: -Infinity, lastUsed: this.now() };+ this.states.set(sessionId, state);+ }+ state.lastUsed = this.now();+ if (state.flight) return state.flight.then(clone);+ if (state.result && this.now() - state.lastRead < this.ttlMs) return Promise.resolve(clone(state.result));+ const s = state;+ // Start transport in a microtask so reentrant callers also see the flight.+ s.flight = Promise.resolve().then(async () => {+ const [events, session] = await Promise.all([transport.readEvents(s.progress.watermark()), transport.readSession()]);+ if (!record(session)) throw new Error('Invalid managed session response');+ const validated = eventPage({ data: events }).data;+ const additions: ManagedEvent[] = [];+ let bytes = s.bytes, total = s.events.size;+ const batch = new Map<string, ManagedEvent>();+ for (const input of validated) {+ const e = clone(input), previous = batch.get(e.id) ?? s.events.get(e.id);+ if (previous?.processed_at && !isDeepStrictEqual(previous, e)) throw new Error('Conflicting managed event replay');+ if (previous && isDeepStrictEqual(previous, e)) continue;+ bytes += Buffer.byteLength(JSON.stringify(e)) - (previous ? Buffer.byteLength(JSON.stringify(previous)) : 0);+ if (!previous) total++;+ if (total > COLLECTOR_LIMITS.events || bytes > COLLECTOR_LIMITS.bytes) throw new Error('Managed collector event limit exceeded');+ batch.set(e.id, e);+ }+ for (const e of batch.values()) additions.push(e);+ s.progress.accept(additions);+ s.bytes = bytes;+ for (const e of additions) { s.events.set(e.id, e); if (e.processed_at) this.observe(s, e); }+ s.session = clone(session);+ s.lastRead = this.now();+ const p = s.progress.snapshot();+ const threadCounts = { running: 0, ended: 0, failed: 0, idle: 0 };+ for (const t of s.threads.values()) {+ if (t.status === 'running') threadCounts.running++;+ else if (t.status === 'failed') threadCounts.failed++;+ else if (t.status === 'ended' || t.status === 'terminated') threadCounts.ended++;+ else threadCounts.idle++;+ }+ const snapshot: ManagedRunSnapshot = {+ sessionId, status: ['idle', 'running', 'rescheduling', 'terminated', 'error'].includes(session.status ?? '') ? session.status! : p.status,+ stopReason: p.stopReason === null || ['end_turn', 'budget_reached', 'requires_action'].includes(p.stopReason) ? p.stopReason : 'unknown', budgetCents: cents(session.budget?.max_list_cost), listCostCents: cents(session.usage?.list_cost) ?? cents(p.listCost),+ providerFinished: p.finished && session.status !== 'running' && session.status !== 'rescheduling' && session.status !== 'terminated',+ workersInspected: false, acceptancePassed: false, verification: 'unverified',+ runs: p.workflowRuns.map(r => ({ ...r, phases: [...(s.phases.get(r.id)?.values() ?? [])] })),+ threads: [...s.threads.values()].slice(0, COLLECTOR_LIMITS.shownThreads), threadOffset: 0, threadCount: s.threads.size, threadCounts,+ blockedEventIds: [...s.blocked], observedFailures: Math.max(p.observedFailures, threadCounts.failed), updatedMs: s.lastRead,+ };+ s.result = { events: [...s.events.values()], snapshot };+ return s.result;+ }).finally(() => { s.flight = undefined; });+ return s.flight.then(clone);+ }++ /** Pure observation, suitable for disk snapshot publication. Never invokes a transport. */+ snapshots(): ManagedRunSnapshot[] { return [...this.states.values()].flatMap(s => s.result ? [clone(s.result.snapshot)] : []); }++ /** A local worker page only. Aggregate counts and observation timestamp do not change. */+ page(sessionId: string, threadOffset = 0): ManagedRunSnapshot | undefined {+ if (!Number.isSafeInteger(threadOffset) || threadOffset < 0 || threadOffset >= COLLECTOR_LIMITS.events) throw new Error('Invalid managed thread offset');+ const state = this.states.get(sessionId);+ if (!state?.result) return undefined;+ return { ...clone(state.result.snapshot), threadOffset, threads: clone([...state.threads.values()].slice(threadOffset, threadOffset + COLLECTOR_LIMITS.shownThreads)) };+ }++ /** A collector doing work cannot be forgotten midflight. No remote work is interrupted. */+ forget(sessionId: string): boolean {+ const s = this.states.get(sessionId);+ return s?.flight ? false : this.states.delete(sessionId);+ }++ private observe(s: State, e: ManagedEvent): void {+ const runId = idOf(e.workflow_run_id);+ if (runId && e.type === 'workflow_run.created' && Array.isArray(e.phases)) {+ const phases = new Map<string, Phase>();+ for (const value of e.phases.slice(0, 100)) {+ const phase = record(value), id = idOf(phase?.id);+ if (id) phases.set(id, { id, name: phaseName(phase?.name, id), status: 'queued' });+ }+ s.phases.set(runId, phases);+ }+ if (runId && (e.type === 'workflow_run.phase_started' || e.type === 'workflow_run.phase_ended')) {+ const id = idOf(e.workflow_run_phase_id);+ if (id) {+ const phases = s.phases.get(runId) ?? new Map<string, Phase>();+ if (phases.size < 100 || phases.has(id)) phases.set(id, { id, name: phases.get(id)?.name ?? id, status: e.type.endsWith('started') ? 'running' : 'ended' });+ s.phases.set(runId, phases);+ }+ }+ const threadId = idOf(e.session_thread_id);+ if (threadId && e.type.startsWith('session.thread_')) {+ const t = s.threads.get(threadId) ?? { id: threadId, runId: runId ?? null, status: 'idle' };+ if (runId) t.runId = runId;+ const phaseId = idOf(e.workflow_run_phase_id); if (phaseId) t.phaseId = phaseId;+ if (e.type === 'session.thread_status_running') t.status = 'running';+ else if (e.type === 'session.thread_status_idle') t.status = 'idle';+ else if (e.type === 'session.thread_status_terminated') t.status = e.error || t.status === 'failed' ? 'failed' : 'ended';+ s.threads.set(threadId, t);+ }+ if (threadId && e.type === 'session.error') {+ const t = s.threads.get(threadId) ?? { id: threadId, runId: runId ?? null, status: 'failed' };+ t.status = 'failed'; s.threads.set(threadId, t);+ }+ const permission = typeof e.evaluated_permission === 'string' ? e.evaluated_permission : record(e.evaluated_permission)?.type;+ if (permission === 'ask' || e.type === 'agent.custom_tool_use') s.blocked.add(e.id);+ const answered = idOf(e.tool_use_id) ?? idOf(e.custom_tool_use_id);+ if (answered && ['user.tool_confirmation', 'user.custom_tool_result', 'user.tool_result'].includes(e.type)) s.blocked.delete(answered);+ const stop = record(e.stop_reason);+ if (stop?.type === 'requires_action' && Array.isArray(stop.event_ids)) for (const id of stop.event_ids) if (idOf(id)) s.blocked.add(id as string);+ }+}++export const sharedManagedCollector = new ManagedRunCollector();diff --git a/v3/@claude-flow/cli/src/services/managed-run-store.ts b/v3/@claude-flow/cli/src/services/managed-run-store.tsnew file mode 100644index 0000000000..954f6a2e08--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-run-store.ts@@ -0,0 +1,92 @@+/** Bounded console projections and a fail-closed cross-process collector lease. */+import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { ManagedRunSnapshot } from './managed-run-collector.js';++const flights = new Map<string, { scope: string; promise: Promise<unknown> }>();+function folder(root: string): string {+ let p = resolve(root);+ if (!lstatSync(p).isDirectory()) throw new Error('Invalid managed project root');+ for (const name of ['.claude-flow', 'managed-workflows']) {+ p = join(p, name);+ if (!existsSync(p)) mkdirSync(p, { mode: 0o700 });+ if (!lstatSync(p).isDirectory() || lstatSync(p).isSymbolicLink()) throw new Error('Managed snapshot directory must be regular');+ }+ return p;+}++/** Other processes fail rather than poll twice. Never automatically steal a lease. */+export function collectWithLease<T>(root: string, sessionId: string, action: () => Promise<T>, scope = ''): Promise<T> {+ if (!/^sesn_[A-Za-z0-9]+$/.test(sessionId)) return Promise.reject(new Error('Invalid managed session ID'));+ const path = join(folder(root), `${sessionId}.collector.lock`);+ const pending = flights.get(path);+ if (pending) return pending.scope === scope ? pending.promise.then(v => structuredClone(v) as T) : Promise.reject(new Error('Managed collector belongs to another credential scope'));+ let fd: number;+ try { fd = openSync(path, 'wx', 0o600); } catch { return Promise.reject(new Error('Managed collector is leased by another process; inspect before recovering a stale lease')); }+ const flight = Promise.resolve().then(action).finally(() => { closeSync(fd); unlinkSync(path); flights.delete(path); });+ flights.set(path, { scope, promise: flight });+ return flight.then(v => structuredClone(v));+}++/** Read only the fixed, capped projection. It has no authorization role. */+function previous(path: string): ManagedRunSnapshot[] {+ if (!existsSync(path)) return [];+ if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error('Invalid managed snapshot file');+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const buffer = Buffer.alloc(128_001);+ const count = readSync(fd, buffer, 0, buffer.length, 0);+ if (count > 128_000) throw new Error('Managed snapshot exceeds limit');+ const value = JSON.parse(buffer.subarray(0, count).toString('utf8'));+ if (value.version !== 1 || !Array.isArray(value.sessions) || value.sessions.length > 6) throw new Error('Invalid managed snapshot');+ return value.sessions;+ } finally { closeSync(fd); }+}++export function publishManagedSnapshot(root: string, snapshot: ManagedRunSnapshot): void {+ const dir = folder(root), lockPath = join(dir, 'snapshot.lock');+ const fd = openSync(lockPath, 'wx', 0o600), temp = join(dir, `${randomUUID()}.tmp`);+ try {+ const path = join(dir, 'snapshot.json');+ const old = previous(path);+ const sessions = [snapshot, ...old.filter(s => s.sessionId !== snapshot.sessionId)].slice(0, 6);+ if (JSON.stringify(sessions) === JSON.stringify(old)) return;+ const text = JSON.stringify({ version: 1, updatedMs: Date.now(), sessions });+ if (Buffer.byteLength(text) > 128_000) throw new Error('Managed snapshot exceeds limit');+ const out = openSync(temp, 'wx', 0o600);+ try { writeFileSync(out, text); fsyncSync(out); } finally { closeSync(out); }+ renameSync(temp, path);+ } finally { if (existsSync(temp)) unlinkSync(temp); closeSync(fd); unlinkSync(lockPath); }+}++export type ControlAction = 'inspect' | 'interrupt' | 'terminate';+/** Host settings are read again immediately before side effects, never from console facts. */+export async function executeManagedControl(input: Record<string, unknown>, deps: {+ policy: () => { enabled: boolean; sessions: string[] };+ read: (sessionId: string) => Promise<{ status?: string }>;+ inspect: (sessionId: string, offset: number) => Promise<unknown>;+ interrupt: (sessionId: string) => Promise<unknown>;+ terminate: (sessionId: string) => Promise<unknown>;+}) {+ const sessionId = input.sessionId, action = input.action;+ if (Object.keys(input).some(k => !['sessionId', 'action', 'threadOffset'].includes(k)) || typeof sessionId !== 'string' || !/^sesn_[A-Za-z0-9]+$/.test(sessionId) || !['inspect', 'interrupt', 'terminate'].includes(String(action))) throw new Error('Invalid managed control request');+ const offset = input.threadOffset ?? 0;+ if (!Number.isSafeInteger(offset) || (offset as number) < 0 || (offset as number) >= 10_000 || (action !== 'inspect' && input.threadOffset !== undefined)) throw new Error('Invalid managed worker page');+ const allowed = () => { const p = deps.policy(); return p.enabled && p.sessions.includes(sessionId); };+ if (!allowed()) throw new Error('Host managed control policy denies this session');+ const current = await deps.read(sessionId);+ if (!current || !['idle', 'running', 'rescheduling', 'terminated'].includes(current.status ?? '')) throw new Error('Unknown provider session state');+ if (!allowed()) throw new Error('Host managed control policy changed before dispatch');+ if (action === 'inspect') return { success: true, currentStatus: current.status, snapshot: await deps.inspect(sessionId, offset as number) };+ if (current.status === 'terminated') return { success: true, currentStatus: 'terminated', cancellationConfirmed: true };+ if (action === 'interrupt') return { success: true, currentStatus: current.status, interruptRequested: true, cancellationConfirmed: false, result: await deps.interrupt(sessionId) };+ return { success: true, currentStatus: current.status, cancellationConfirmed: true, result: await deps.terminate(sessionId) };+}++/** Successful provider deletion is a session fact, never an acceptance verdict. */+export function publishManagedTermination(root: string, sessionId: string, collector: { page: (id: string) => ManagedRunSnapshot | undefined; forget: (id: string) => boolean }): void {+ const snapshot = collector.page(sessionId);+ if (snapshot) publishManagedSnapshot(root, { ...snapshot, status: 'terminated', providerFinished: false, updatedMs: Date.now() });+ collector.forget(sessionId);+}diff --git a/v3/@claude-flow/cli/src/services/managed-workflows.ts b/v3/@claude-flow/cli/src/services/managed-workflows.tsnew file mode 100644index 0000000000..7f236eeb17--- /dev/null+++ b/v3/@claude-flow/cli/src/services/managed-workflows.ts@@ -0,0 +1,167 @@+/** Provider event semantics for ADR-115 / dynamic workflows. No model calls. */+export interface ManagedEvent {+ id: string;+ type: string;+ processed_at?: string | null;+ content?: Array<{ type: string; text?: string }>;+ name?: string;+ input?: unknown;+ stop_reason?: { type: string };+ workflow_run_id?: string | null;+ session_thread_id?: string;+ result?: { type: string } | string;+ [key: string]: unknown;+}++export interface EventPage { data: ManagedEvent[]; next_page?: string | null }++/** Validate untrusted pages before deriving lifecycle claims. */+export function eventPage(value: unknown): EventPage {+ if (!value || typeof value !== 'object') throw new Error('Invalid Managed Agents event page');+ const page = value as EventPage;+ if (!Array.isArray(page.data) || page.data.some(e => !e || typeof e.id !== 'string' || !e.id || typeof e.type !== 'string')) {+ throw new Error('Invalid Managed Agents events');+ }+ for (const e of page.data) {+ if (e.processed_at != null && (typeof e.processed_at !== 'string' || !Number.isFinite(Date.parse(e.processed_at)))) throw new Error('Invalid event timestamp');+ if (e.type === 'agent.message' && e.content !== undefined && (!Array.isArray(e.content) || e.content.some(b => !b || typeof b.type !== 'string' || (b.text !== undefined && typeof b.text !== 'string')))) throw new Error('Invalid event content');+ if (e.stop_reason != null && typeof e.stop_reason.type !== 'string') throw new Error('Invalid event stop reason');+ if (e.type === 'workflow_run.status_ended' && (!e.result || typeof e.result !== 'object' || typeof e.result.type !== 'string')) throw new Error('Invalid workflow result');+ if (e.type.startsWith('workflow_run.') && e.type !== 'workflow_run.error' && (typeof e.workflow_run_id !== 'string' || !e.workflow_run_id)) throw new Error('Invalid workflow ID');+ if (e.workflow_run_id != null && typeof e.workflow_run_id !== 'string') throw new Error('Invalid workflow ID');+ }+ if (page.next_page != null && (typeof page.next_page !== 'string' || !page.next_page || page.next_page.length > 4096)) {+ throw new Error('Invalid Managed Agents cursor');+ }+ return page;+}++/** Reads complete history, bounded and deduplicated. Cursor is opaque, never a URL. */+export async function readManagedEvents(+ read: (query: string) => Promise<unknown>,+ since?: string,+): Promise<ManagedEvent[]> {+ const events = new Map<string, ManagedEvent>();+ const cursors = new Set<string>();+ let bytes = 0;+ let cursor: string | undefined;+ for (let count = 0; count < 100; count++) {+ const query = new URLSearchParams({ order: 'asc', limit: '100' });+ if (cursor) query.set('page', cursor);+ if (since) query.set('created_at[gte]', since);+ const page = eventPage(await read(query.toString()));+ bytes += Buffer.byteLength(JSON.stringify(page), 'utf8');+ if (bytes > 16_000_000) throw new Error('Managed Agents transcript limit exceeded');+ for (const e of page.data) events.set(e.id, e);+ if (events.size > 10_000) throw new Error('Managed Agents event limit exceeded');+ if (!page.next_page) return [...events.values()];+ if (cursors.has(page.next_page)) throw new Error('Repeated Managed Agents cursor');+ cursors.add(page.next_page);+ cursor = page.next_page;+ }+ throw new Error('Managed Agents page limit exceeded');+}++/** Incremental reducer. Provider completion is always unverified. */+export class ManagedProgress {+ private seen = new Set<string>();+ private text: string[] = [];+ private tools: Array<{ name: string; input: unknown }> = [];+ private runs = new Map<string, { id: string; status: string; result?: string }>();+ private failures = 0;+ private status = 'unknown';+ private stopReason: string | null = null;+ private cost: unknown = null;+ private since: string | undefined;+ private bytes = 0;+ private finished = false;+ private interrupted = false;++ accept(events: ManagedEvent[]): void {+ for (const e of events) {+ // Queued user messages may be returned again after processing.+ if (!e.processed_at) continue;+ if (this.seen.has(e.id)) continue;+ if (this.seen.size >= 10_000) throw new Error('Managed Agents event limit exceeded');+ this.bytes += Buffer.byteLength(JSON.stringify(e), 'utf8');+ if (this.bytes > 16_000_000) throw new Error('Managed Agents transcript limit exceeded');+ this.seen.add(e.id);+ if (!this.since || e.processed_at > this.since) this.since = e.processed_at;+ if (e.type === 'user.message') {+ this.finished = false; this.interrupted = false;+ } else if (e.type === 'user.interrupt') {+ this.finished = false; this.interrupted = true;+ } else if (e.type === 'agent.message' && Array.isArray(e.content)) {+ this.text.push(e.content.filter(b => b?.type === 'text' && typeof b.text === 'string').map(b => b.text).join(''));+ } else if (e.type === 'agent.tool_use' || e.type === 'agent.mcp_tool_use') {+ this.tools.push({ name: e.name ?? '?', input: e.input });+ } else if (e.type === 'session.status_running') {+ this.status = 'running'; this.stopReason = null; this.finished = false;+ } else if (e.type === 'session.status_idle') {+ this.status = 'idle'; this.stopReason = e.stop_reason?.type ?? null;+ this.finished = this.stopReason === 'end_turn' && !this.interrupted && [...this.runs.values()].every(r => r.status === 'ended');+ } else if (e.type === 'session.status_terminated') {+ this.status = 'terminated'; this.finished = false;+ } else if (e.type === 'session.error' || e.type === 'session.status_error' || e.type === 'session.status_failed') {+ this.failures++;+ } else if (e.type === 'session.usage') {+ this.cost = e.usage && typeof e.usage === 'object' ? (e.usage as Record<string, unknown>).list_cost ?? null : null;+ }+ if (e.type === 'workflow_run.error') this.failures++;+ if (e.workflow_run_id && e.type.startsWith('workflow_run.')) {+ this.finished = false;+ const run = this.runs.get(e.workflow_run_id) ?? { id: e.workflow_run_id, status: 'running' };+ if (e.type === 'workflow_run.status_ended') {+ run.status = 'ended'; run.result = typeof e.result === 'object' ? e.result.type : 'unknown';+ if (run.result !== 'completed') this.failures++;+ } else if (e.type === 'workflow_run.status_idle' && run.status !== 'ended') run.status = 'idle';+ else if (e.type === 'workflow_run.status_running' && run.status !== 'ended') run.status = 'running';+ this.runs.set(run.id, run);+ }+ }+ }++ watermark(): string | undefined { return this.since; }++ snapshot() {+ const workflowRuns = [...this.runs.values()].map(r => ({ ...r }));+ const openRuns = workflowRuns.filter(r => r.status !== 'ended').length;+ const blocked = this.status === 'idle' && ['budget_reached', 'requires_action'].includes(this.stopReason ?? '');+ return {+ assistantText: this.text.join(''), toolUses: [...this.tools], status: this.status,+ stopReason: this.stopReason, eventCount: this.seen.size, workflowRuns, openRuns,+ finished: this.finished, interrupted: this.interrupted, blocked, observedFailures: this.failures, listCost: this.cost,+ verification: 'unverified' as const,+ needsThreadInspection: workflowRuns.length > 0,+ };+ }+}++/** Build only the supported configuration; do not pass arbitrary multiagent JSON. */+export function dynamicConfig(input: Record<string, unknown>) {+ if (input.dynamicWorkflows !== undefined && typeof input.dynamicWorkflows !== 'boolean') throw new Error('dynamicWorkflows must be boolean');+ const enabled = input.dynamicWorkflows === true;+ if (input.budgetCents !== undefined || enabled) {+ if (typeof input.budgetCents !== 'string' || !/^[1-9][0-9]{0,8}$/.test(input.budgetCents)) {+ throw new Error('budgetCents must be a positive integer cents string (maximum 999999999)');+ }+ }+ if (enabled && input.networking !== undefined && input.networking !== 'limited') throw new Error('Dynamic workflows require limited networking');+ const hosts = input.allowedHosts ?? [];+ if (!Array.isArray(hosts) || hosts.length > 100 || hosts.some(h => typeof h !== 'string' || h.length > 253 || !/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/i.test(h))) {+ throw new Error('allowedHosts must contain at most 100 exact hostnames');+ }+ const agents = input.predefinedAgents;+ if (agents !== undefined && (!Array.isArray(agents) || agents.length < 1 || agents.length > 20 || agents.some(a => typeof a !== 'string' || !/^agent_[A-Za-z0-9]+$/.test(a)))) {+ throw new Error('predefinedAgents must contain 1 to 20 agent IDs');+ }+ return {+ enabled,+ budget: input.budgetCents === undefined ? undefined : { type: 'limit', max_list_cost: { amount: input.budgetCents, currency: 'USD' } },+ multiagent: enabled ? {+ type: 'multiagent_20261001', subagents: { type: 'disabled' },+ workflows: { type: 'enabled', ...(agents ? { inline_agents: { type: 'disabled' }, predefined_agents: agents } : {}) },+ } : undefined,+ networking: enabled || input.networking === 'limited' ? { type: 'limited', allowed_hosts: hosts } : { type: input.networking ?? 'unrestricted' },+ };+}