🌊 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: capability brain and governed federation plane (#2825)
rUvdbb1f1e1dd08
diff --git a/.github/workflows/stable-npm-release.yml b/.github/workflows/stable-npm-release.ymlindex ec86f3ae6c..86e8c0d70a 100644--- a/.github/workflows/stable-npm-release.yml+++ b/.github/workflows/stable-npm-release.yml@@ -11,6 +11,14 @@ on:description: Policy runtime version bundled by this releaserequired: truetype: string+ codex_version:+ description: Codex adapter version bundled by this release+ required: true+ type: string+ federation_version:+ description: Agent federation plugin version bundled by this release+ required: true+ type: stringpermissions:contents: read@@ -38,6 +46,14 @@ jobs:echo "::error::security_version must be a 3.0.0 alpha"exit 1fi+ if [[ ! "${{ inputs.codex_version }}" =~ ^3\.[0-9]+\.[0-9]+$ ]]; then+ echo "::error::codex_version must be a stable 3.x version"+ exit 1+ fi+ if [[ ! "${{ inputs.federation_version }}" =~ ^1\.0\.0-alpha\.[0-9]+$ ]]; then+ echo "::error::federation_version must be a 1.0.0 alpha"+ exit 1+ fi- name: Checkout immutable release taguses: actions/checkout@v4@@ -84,10 +100,22 @@ jobs:!== `^${process.env.SECURITY_VERSION}`) {throw new Error('CLI security dependency is not in release lockstep');}+ const codex = require('./v3/@claude-flow/codex/package.json');+ if (codex.version !== process.env.CODEX_VERSION) {+ throw new Error(`${codex.name}: expected ${process.env.CODEX_VERSION}, got ${codex.version}`);+ }+ const federation = require('./v3/@claude-flow/plugin-agent-federation/package.json');+ if (federation.version !== process.env.FEDERATION_VERSION) {+ throw new Error(+ `${federation.name}: expected ${process.env.FEDERATION_VERSION}, got ${federation.version}`,+ );+ }NODEenv:RELEASE_TAG: ${{ inputs.tag }}SECURITY_VERSION: ${{ inputs.security_version }}+ CODEX_VERSION: ${{ inputs.codex_version }}+ FEDERATION_VERSION: ${{ inputs.federation_version }}- name: Install and build publishable packagesworking-directory: v3@@ -95,6 +123,16 @@ jobs:pnpm install --frozen-lockfilepnpm build+ - name: Run release test gates+ working-directory: v3+ run: |+ pnpm --dir @claude-flow/cli exec vitest run \+ __tests__/guidance-brain.test.ts \+ __tests__/mcp-client-guardrail.test.ts+ pnpm --dir @claude-flow/codex exec vitest run+ pnpm --dir @claude-flow/security exec vitest run+ pnpm --dir @claude-flow/plugin-agent-federation exec vitest run+- name: Verify signed helper manifestworking-directory: v3/@claude-flow/clirun: node scripts/verify-helpers.mjs@@ -103,8 +141,12 @@ jobs:shell: bashrun: |test -f v3/@claude-flow/security/dist/policy/engine.js+ test -f v3/@claude-flow/security/dist/policy/product-plane.jstest -f v3/@claude-flow/cli/dist/src/services/policy-runtime.jstest -f v3/@claude-flow/cli/dist/src/commands/policy.js+ test -f v3/@claude-flow/cli/dist/src/mcp-tools/capability-brain.js+ test -f v3/@claude-flow/codex/dist/harness/index.js+ test -f v3/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js- name: Stage CLI publish assetsshell: bash@@ -119,6 +161,29 @@ jobs:fs.copyFileSync('README.md', 'ruflo/README.md');NODE+ - name: Smoke-test public exports and package archives+ shell: bash+ run: |+ node --input-type=module - <<'NODE'+ await import('./v3/@claude-flow/cli/dist/src/mcp-tools/capability-brain.js');+ await import('./v3/@claude-flow/codex/dist/harness/index.js');+ await import('./v3/@claude-flow/security/dist/policy/product-plane.js');+ await import('./v3/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js');+ NODE++ pack_dir="$(mktemp -d)"+ trap 'rm -rf "$pack_dir"' EXIT+ npm pack --ignore-scripts --pack-destination "$pack_dir" ./v3/@claude-flow/security+ npm pack --ignore-scripts --pack-destination "$pack_dir" ./v3/@claude-flow/codex+ npm pack --ignore-scripts --pack-destination "$pack_dir" ./v3/@claude-flow/plugin-agent-federation+ npm pack --ignore-scripts --pack-destination "$pack_dir" ./v3/@claude-flow/cli+ npm pack --ignore-scripts --pack-destination "$pack_dir" .+ npm pack --ignore-scripts --pack-destination "$pack_dir" ./ruflo+ test "$(find "$pack_dir" -maxdepth 1 -name '*.tgz' | wc -l)" -eq 6+ while IFS= read -r archive; do+ tar -tzf "$archive" >/dev/null+ done < <(find "$pack_dir" -maxdepth 1 -name '*.tgz' -print)+- name: Publish policy runtimeworking-directory: v3/@claude-flow/securityshell: bash@@ -132,6 +197,32 @@ jobs:NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}SECURITY_VERSION: ${{ inputs.security_version }}+ - name: Publish Codex adapter+ working-directory: v3/@claude-flow/codex+ shell: bash+ run: |+ if npm view "@claude-flow/codex@${CODEX_VERSION}" version >/dev/null 2>&1; then+ echo "@claude-flow/codex@${CODEX_VERSION} already published"+ else+ npm publish --ignore-scripts --access public --tag latest+ fi+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}+ CODEX_VERSION: ${{ inputs.codex_version }}++ - name: Publish agent federation plugin+ working-directory: v3/@claude-flow/plugin-agent-federation+ shell: bash+ run: |+ if npm view "@claude-flow/plugin-agent-federation@${FEDERATION_VERSION}" version >/dev/null 2>&1; then+ echo "@claude-flow/plugin-agent-federation@${FEDERATION_VERSION} already published"+ else+ npm publish --ignore-scripts --access public --tag v3alpha+ fi+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}+ FEDERATION_VERSION: ${{ inputs.federation_version }}+- name: Publish CLIworking-directory: v3/@claude-flow/clishell: bash@@ -178,9 +269,13 @@ jobs:run: |version="${RELEASE_TAG#v}"test "$(npm view "@claude-flow/security@${SECURITY_VERSION}" version)" = "${SECURITY_VERSION}"+ test "$(npm view "@claude-flow/codex@${CODEX_VERSION}" version)" = "${CODEX_VERSION}"+ test "$(npm view "@claude-flow/plugin-agent-federation@${FEDERATION_VERSION}" version)" = "${FEDERATION_VERSION}"test "$(npm view "@claude-flow/cli@${version}" version)" = "${version}"test "$(npm view "claude-flow@${version}" version)" = "${version}"test "$(npm view "ruflo@${version}" version)" = "${version}"env:RELEASE_TAG: ${{ inputs.tag }}SECURITY_VERSION: ${{ inputs.security_version }}+ CODEX_VERSION: ${{ inputs.codex_version }}+ FEDERATION_VERSION: ${{ inputs.federation_version }}diff --git a/AGENTS.md b/AGENTS.mdindex da92baa1f1..78d9cd5a18 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -31,15 +31,22 @@Ruflo is the coordination ledger and policy decision point. Codex agents arethe executors. Coordination records do not write code or run tests.-1. Search AgentDB memory before planning.-2. Initialize one bounded hierarchical swarm.-3. Fan out only independent tasks.-4. Give every writing agent a separate git worktree and a reduced capability- envelope; read-only agents may share a checkout.-5. Assign one owner for shared manifests and lockfiles.-6. Integrate committed handoffs in dependency order, then run scoped and full- verification.-7. Store the successful pattern and retain the policy/MetaHarness receipts.+Use `guidance_brain({ mode: "recommend", task: "..." })` to select Ruflo+capabilities from the live MCP registry. A registered tool is not necessarily+configured, reachable, healthy, or authorized.++1. Recall relevant AgentDB memory and ADRs.+2. Inspect source, runtime, dependencies, policy, and health.+3. Route to the smallest capable topology, agents, skills, and tools.+4. Plan acceptance criteria, safety envelope, ownership, and validation.+5. Execute with Codex workers in isolated scopes; Ruflo records coordination.+6. Test focused, regression, and failure paths.+7. Validate types, security, policy, compatibility, and artifact integrity.+8. Benchmark a source-bound candidate against a source-bound baseline.+9. Optimize only measured bottlenecks without weakening safety.+10. Bind claims and evidence into exact source/build receipts.+11. Reconcile handoffs and disclose unresolved limitations.+12. Publish only through a separately authorized release gate.Hard invariants:@@ -53,6 +60,23 @@ Hard invariants:- Existing installations migrate in `legacy` policy mode; use `observe` beforeswitching to `enforce`.+Repository harness integration:++- If tracked repository instructions define a collaboration harness, start its+ session only after assigning an isolated worktree.+- Inspect existing claims, acquire exact paths/resources/ports, renew leases,+ check acknowledged inbox messages at integration boundaries, and release ownership on+ handoff or exit.+- A repository lease coordinates ownership; it does not grant authorization.+ Protected work still requires the ADR-324/325 action capability and current+ fencing epoch.+- In-memory reference adapters demonstrate semantics; they are not distributed,+ restart-durable release authorities.+- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.+- `HEAD` alone is not an exact source-state identity in a dirty worktree.+ Release evidence must bind a clean commit or an immutable snapshot of tracked+ and untracked changes.+Useful checks:```bashdiff --git a/package-lock.json b/package-lock.jsonindex 82f279c065..a7d8eeed8f 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-flow",- "version": "3.32.9",+ "version": "3.32.28","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-flow",- "version": "3.32.9",+ "version": "3.32.28","license": "MIT","dependencies": {"@claude-flow/cli-core": "3.7.0-alpha.5",diff --git a/package.json b/package.jsonindex 504585d991..c765cf12c1 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.32.27",+ "version": "3.32.28","description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "dist/index.js","type": "module",diff --git a/ruflo/package.json b/ruflo/package.jsonindex 5b19705604..c2cda77a54 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.32.27",+ "version": "3.32.28","description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "bin/ruflo.js","type": "module",@@ -40,7 +40,7 @@"package:rvf": "bash src/scripts/package-rvf.sh"},"dependencies": {- "@claude-flow/cli": "^3.32.7"+ "@claude-flow/cli": "^3.32.28"},"optionalDependencies": {},"overrides": {diff --git a/v3/@claude-flow/cli/.claude/helpers/.helpers-version b/v3/@claude-flow/cli/.claude/helpers/.helpers-versionindex 66df80b692..5eef9918a4 100644--- a/v3/@claude-flow/cli/.claude/helpers/.helpers-version+++ b/v3/@claude-flow/cli/.claude/helpers/.helpers-version@@ -1 +1 @@-3.32.2\ No newline at end of file+3.32.28\ No newline at end of filediff --git a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.jsonindex e9a2a2226a..fac9180509 100644--- a/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json+++ b/v3/@claude-flow/cli/.claude/helpers/helpers.manifest.json@@ -1,6 +1,6 @@{"manifest": {- "version": "3.32.27",+ "version": "3.32.28","files": {"auto-memory-hook.mjs": "68be7e9a9eba7bf9c4e8a230db7bf61a243b965639f8504842799d6c6ca28762","hook-handler.cjs": "50ea92a72651bdc95634f7588d56a5870963168eef5226f66ed14af3b47c8d9a",@@ -8,6 +8,6 @@"statusline.cjs": "d2a0eac56d1267d8dbed2d70b09feb592299469196ec4b215909f2b052144882"}},- "signature": "qZMPL+08pJ9yRIibW5x19MugUnGsMn9jKvQOqf9IEVRDj5ULiimXyFoJe+qYI9d3siDV8OYtlfYaqFqfao1gCg==",+ "signature": "Kht297XxwiocrMlfrPu6wlWg14RgBKM8twlvRHMmwZ+TBvRRBZGs6WfwBr05ozwVlmguO3V8zDv062k3UB1qDQ==","algorithm": "ed25519"}diff --git a/v3/@claude-flow/cli/__tests__/guidance-brain.bench.ts b/v3/@claude-flow/cli/__tests__/guidance-brain.bench.tsnew file mode 100644index 0000000000..98dc437664--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/guidance-brain.bench.ts@@ -0,0 +1,32 @@+import { bench, describe } from 'vitest';+import {+ buildCapabilityBrain,+ CAPABILITY_DOMAINS,+ recommendCapabilities,+} from '../src/mcp-tools/capability-brain.js';++const prefixes = CAPABILITY_DOMAINS+ .filter((domain) => domain.id !== 'runtime-services')+ .flatMap((domain) => domain.prefixes)+ .filter(Boolean);++const maximumRegistry = Array.from({ length: 353 }, (_, index) => ({+ name: `${prefixes[index % prefixes.length]}benchmark-${String(index).padStart(3, '0')}`,+ description: `Synthetic maximum-registry tool ${index}`,+ category: 'benchmark',+}));++const brain = buildCapabilityBrain(maximumRegistry);++describe('capability brain maximum live registry', () => {+ bench('build 353-tool capability brain', () => {+ buildCapabilityBrain(maximumRegistry);+ });++ bench('recommend from 353-tool capability brain', () => {+ recommendCapabilities(+ brain,+ 'Implement secure claim federation with concurrent agents, tests, benchmarks, and release validation',+ );+ });+});diff --git a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts b/v3/@claude-flow/cli/__tests__/guidance-brain.test.tsnew file mode 100644index 0000000000..05ec0f119b--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts@@ -0,0 +1,176 @@+import { describe, expect, it } from 'vitest';+import { listMCPTools } from '../src/mcp-client.js';+import {+ buildCapabilityBrain,+ IMPLEMENTATION_LOOP,+ recommendCapabilities,+} from '../src/mcp-tools/capability-brain.js';+import {+ configureGuidanceToolProvider,+ guidanceTools,+} from '../src/mcp-tools/guidance-tools.js';++function decode(result: unknown): Record<string, any> {+ const payload = result as { content: Array<{ text: string }> };+ return JSON.parse(payload.content[0]!.text);+}++describe('Ruflo capability brain', () => {+ it('classifies every live registered MCP tool without duplicates', () => {+ const tools = listMCPTools();+ const brain = buildCapabilityBrain(tools, new Date('2026-07-28T00:00:00.000Z'));++ expect(brain.coverage.registeredToolCount).toBe(tools.length);+ expect(brain.coverage.classifiedToolCount).toBe(tools.length);+ expect(brain.coverage.coveragePercent).toBe(100);+ expect(brain.coverage.duplicateToolNames).toEqual([]);+ expect(brain.coverage.fallbackClassifiedTools).toEqual([]);++ const assigned = brain.domains.flatMap((domain) => domain.tools.map((tool) => tool.name));+ expect(new Set(assigned).size).toBe(tools.length);+ for (const domain of brain.domains) {+ expect(domain.packageOwners.length).toBeGreaterThan(0);+ expect(domain.availabilityMode).toBeTruthy();+ expect(domain.riskFlags.length).toBeGreaterThan(0);+ expect(domain.loopPhases.length).toBeGreaterThan(0);+ for (const tool of domain.tools) {+ expect(tool.domain).toBe(domain.id);+ expect(tool.packageOwner).toBeTruthy();+ expect(tool.availabilityMode).toBe(domain.availabilityMode);+ expect(tool.riskFlags.length).toBeGreaterThan(0);+ }+ }++ const testgen = brain.domains.find((domain) => domain.id === 'test-generation')!;+ expect(testgen.exactTools).toContain('testgen_tdd_repair');+ expect(testgen.health.registered).toBe(false);+ const auth = brain.domains.find((domain) => domain.id === 'identity-auth')!;+ expect(auth.commands).toContain('auth status --check');+ expect(auth.health.registered).toBe(false);+ expect(auth.riskFlags).toEqual(+ expect.arrayContaining(['network', 'credential-pii', 'approval']),+ );+ expect(brain.cliCommands).toHaveLength(52);+ });++ it('does not confuse registration with runtime health or authorization', () => {+ const brain = buildCapabilityBrain([{ name: 'memory_search' }]);+ const memory = brain.domains.find((domain) => domain.id === 'memory-knowledge')!;++ expect(memory.health).toEqual({+ registered: true,+ configured: 'unknown',+ reachable: 'unknown',+ healthy: 'unknown',+ authorized: 'unknown',+ });+ });++ it('conservatively reports agent, cloud, browser, terminal, and promotion effects', () => {+ const brain = buildCapabilityBrain([+ { name: 'agent_execute' },+ { name: 'managed_agent_create' },+ { name: 'browser_act' },+ { name: 'terminal_execute' },+ { name: 'agenticow_promote' },+ ]);+ const byName = new Map(+ brain.domains.flatMap((domain) => domain.tools).map((tool) => [tool.name, tool]),+ );++ for (const name of ['agent_execute', 'managed_agent_create']) {+ expect(byName.get(name)?.risk).toBe('privileged');+ expect(byName.get(name)?.riskFlags).toEqual(+ expect.arrayContaining(['process-exec', 'network', 'credential-pii', 'spend']),+ );+ }+ expect(byName.get('browser_act')?.riskFlags).toEqual(+ expect.arrayContaining(['network', 'credential-pii', 'spend', 'approval']),+ );+ expect(byName.get('terminal_execute')?.riskFlags).toEqual(+ expect.arrayContaining(['process-exec', 'credential-pii', 'destructive']),+ );+ expect(byName.get('agenticow_promote')?.riskFlags).toEqual(+ expect.arrayContaining(['memory-poisoning', 'promotion']),+ );+ });++ it('routes claim federation through policy, consensus, and the guarded loop', () => {+ const brain = buildCapabilityBrain([+ { name: 'claims_check' },+ { name: 'policy_evaluate' },+ { name: 'hive_mind_init' },+ { name: 'security_audit' },+ ]);+ const recommendation = recommendCapabilities(+ brain,+ 'Implement secure claim federation policy and benchmark it',+ );++ expect(recommendation.domains.map((domain) => domain.id)).toContain('policy-authorization');+ expect(recommendation.domains.map((domain) => domain.id)).toContain('consensus-federation');+ expect(recommendation.implementationLoop.map((step) => step.id)).toEqual(+ IMPLEMENTATION_LOOP.map((step) => step.id),+ );+ expect(recommendation.guardrails.join(' ')).toContain('never self-authorizing');+ });++ it('makes external publication an authorized final stage', () => {+ const publish = IMPLEMENTATION_LOOP.at(-1)!;+ expect(publish.id).toBe('publish');+ expect(publish.mutation).toBe('external');+ expect(publish.requiredEvidence).toContain('authorization');+ expect(IMPLEMENTATION_LOOP.findIndex((step) => step.id === 'benchmark')).toBeLessThan(+ IMPLEMENTATION_LOOP.findIndex((step) => step.id === 'optimize'),+ );+ });++ it('serves live coverage and implementation-loop views through MCP', async () => {+ const synthetic = [+ { name: 'guidance_brain', description: 'brain' },+ { name: 'memory_search', description: 'recall' },+ { name: 'metaharness_score', description: 'score' },+ ];+ configureGuidanceToolProvider(() => synthetic);+ const tool = guidanceTools.find((entry) => entry.name === 'guidance_brain')!;++ const coverage = decode(await tool.handler({ mode: 'coverage' }, {} as never));+ expect(coverage.coverage.registeredToolCount).toBe(3);+ expect(coverage.coverage.coveragePercent).toBe(100);++ const loop = decode(await tool.handler({ mode: 'implementation-loop' }, {} as never));+ expect(loop.steps.map((step: { id: string }) => step.id)).toEqual(+ IMPLEMENTATION_LOOP.map((step) => step.id),+ );+ expect(loop.invariants.join(' ')).toContain('cannot authorize promotion');+ });++ it('never presents stale compatibility references as live recommendations', async () => {+ configureGuidanceToolProvider(() => [+ { name: 'aidefence_scan', description: 'content safety' },+ { name: 'policy_evaluate', description: 'authorization' },+ { name: 'guidance_recommend', description: 'recommend' },+ ]);+ const tool = guidanceTools.find((entry) => entry.name === 'guidance_recommend')!;+ const result = decode(await tool.handler({ task: 'Run a security audit and policy check' }, {} as never));+ const legacySecurity = result.recommendations.find(+ (entry: { area: string }) => entry.area === 'security',+ );++ expect(legacySecurity.tools).toEqual([]);+ expect(legacySecurity.unregisteredLegacyToolRefs).toContain('security_scan');+ expect(result.capabilityBrain.domains.map((entry: { id: string }) => entry.id))+ .toEqual(expect.arrayContaining(['content-safety', 'policy-authorization']));+ });++ it('discovers the repository ecosystem beyond the legacy .claude skill root', async () => {+ const tool = guidanceTools.find((entry) => entry.name === 'guidance_discover')!;+ const result = decode(await tool.handler({ type: 'all' }, {} as never));++ expect(result.agents.count).toBeGreaterThan(0);+ expect(result.skills.count).toBeGreaterThan(100);+ expect(result.plugins.count).toBeGreaterThan(30);+ expect(result.packages.count).toBeGreaterThan(20);+ expect(result.capabilityBrain.note).toContain('does not prove');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mcp-client-guardrail.test.ts b/v3/@claude-flow/cli/__tests__/mcp-client-guardrail.test.tsindex ee52819c98..59e3f245d0 100644--- a/v3/@claude-flow/cli/__tests__/mcp-client-guardrail.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-client-guardrail.test.ts@@ -45,7 +45,10 @@ vi.mock('../src/mcp-tools/agentdb-tools.js', () => ({ agentdbTools: [] }));vi.mock('../src/mcp-tools/ruvllm-tools.js', () => ({ ruvllmWasmTools: [] }));vi.mock('../src/mcp-tools/wasm-agent-tools.js', () => ({ wasmAgentTools: [] }));vi.mock('../src/mcp-tools/managed-agent-tools.js', () => ({ managedAgentTools: [] }));-vi.mock('../src/mcp-tools/guidance-tools.js', () => ({ guidanceTools: [] }));+vi.mock('../src/mcp-tools/guidance-tools.js', () => ({+ guidanceTools: [],+ configureGuidanceToolProvider: vi.fn(),+}));vi.mock('../src/mcp-tools/autopilot-tools.js', () => ({ autopilotTools: [] }));vi.mock('../src/ruvector/coverage-tools.js', () => ({ coverageRouterTools: [] }));diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 35ec0861ff..75a6ff0dab 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/cli",- "version": "3.32.27",+ "version": "3.32.28","type": "module","description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code","main": "dist/src/index.js",@@ -113,7 +113,7 @@},"optionalDependencies": {"@claude-flow/memory": "^3.0.0-alpha.21",- "@claude-flow/security": "^3.0.0-alpha.13",+ "@claude-flow/security": "^3.0.0-alpha.14","agentdb": "^3.0.0-alpha.17","agentic-flow": "^3.0.0-alpha.1","better-sqlite3": "^12.9.0",diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.tsindex 1b50cb0bce..d6a3de45b8 100644--- a/v3/@claude-flow/cli/src/mcp-client.ts+++ b/v3/@claude-flow/cli/src/mcp-client.ts@@ -52,7 +52,10 @@ import { wasmAgentTools } from './mcp-tools/wasm-agent-tools.js';// the local WASM-sandboxed `wasm_agent_*` (rvagent) tools. Lives in the// `ruflo-agent` plugin.import { managedAgentTools } from './mcp-tools/managed-agent-tools.js';-import { guidanceTools } from './mcp-tools/guidance-tools.js';+import {+ configureGuidanceToolProvider,+ guidanceTools,+} from './mcp-tools/guidance-tools.js';import { autopilotTools } from './mcp-tools/autopilot-tools.js';// ADR-150 — MetaHarness MCP tools (score / genome / mcp-scan / threat-model / oia-audit)import { metaharnessTools } from './mcp-tools/metaharness-tools.js';@@ -182,6 +185,16 @@ registerTools([...httpFetchTools,]);+// The capability brain consumes the completed live registry. This is injected+// after registration to keep guidance honest and avoid a registry import cycle.+configureGuidanceToolProvider(() => Array.from(TOOL_REGISTRY.values()).map((tool) => ({+ name: tool.name,+ description: tool.description,+ category: tool.category,+ tags: tool.tags,+ version: tool.version,+})));+/*** MCP Client Error*/diff --git a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.tsnew file mode 100644index 0000000000..d71d97cdb6--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts@@ -0,0 +1,858 @@+/**+ * Ruflo capability brain.+ *+ * This module is deliberately data-only: it describes the complete MCP surface+ * without importing the MCP registry. The registry injects its live tool list+ * into guidance-tools after registration, which avoids a circular dependency+ * and prevents documentation from being mistaken for runtime availability.+ */++export type CapabilityMaturity = 'stable' | 'experimental' | 'compatibility';+export type CapabilityAuthority = 'advisory' | 'capability-plane' | 'control-plane';+export type CapabilityRisk = 'read-only' | 'reversible' | 'privileged';+export type AvailabilityState = boolean | 'unknown';+export type CapabilityRiskFlag =+ | 'read'+ | 'local-write'+ | 'memory-poisoning'+ | 'process-exec'+ | 'network'+ | 'credential-pii'+ | 'spend'+ | 'concurrency'+ | 'destructive'+ | 'approval'+ | 'promotion';++export interface CapabilityToolMetadata {+ name: string;+ description?: string;+ category?: string;+ tags?: string[];+ version?: string;+}++export interface CapabilityHealth {+ /** Present in this running MCP server's registry. */+ registered: boolean;+ /** Requires an operator/provider configuration check. */+ configured: AvailabilityState;+ /** Requires a non-mutating dependency probe. */+ reachable: AvailabilityState;+ /** Requires a service-specific health check. */+ healthy: AvailabilityState;+ /** Requires a policy evaluation for the current subject and action. */+ authorized: AvailabilityState;+}++export interface CapabilityDomainDefinition {+ id: string;+ name: string;+ description: string;+ prefixes: string[];+ exactTools?: string[];+ taskSignals: string[];+ commands: string[];+ skills: string[];+ agents: string[];+ maturity: CapabilityMaturity;+ authority: CapabilityAuthority;+ risk: CapabilityRisk;+ optionalRuntime?: boolean;+ packageOwners?: string[];+ pluginOwners?: string[];+ availabilityMode?: 'always-local' | 'conditional-registration' | 'registered-degraded' | 'configured-remote' | 'policy-filtered';+ /**+ * Conservative union of effects possible anywhere in this domain.+ * Individual tool descriptors may narrow or expand this reviewed profile.+ */+ riskFlags?: CapabilityRiskFlag[];+ loopPhases?: Array<'discover' | 'recall' | 'authorize-claim' | 'route-plan' | 'branch-propose' | 'execute' | 'validate-critique' | 'commit-validated' | 'observe' | 'publish'>;+ useWhen: string;+ verifyBeforeUse: string[];+}++export interface CapabilityDomain extends CapabilityDomainDefinition {+ packageOwners: string[];+ pluginOwners: string[];+ availabilityMode: NonNullable<CapabilityDomainDefinition['availabilityMode']>;+ riskFlags: NonNullable<CapabilityDomainDefinition['riskFlags']>;+ loopPhases: NonNullable<CapabilityDomainDefinition['loopPhases']>;+ tools: Array<CapabilityToolMetadata & {+ domain: string;+ packageOwner: string;+ pluginOwner?: string;+ availabilityMode: NonNullable<CapabilityDomainDefinition['availabilityMode']>;+ authority: CapabilityAuthority;+ risk: CapabilityRisk;+ riskFlags: NonNullable<CapabilityDomainDefinition['riskFlags']>;+ loopPhases: NonNullable<CapabilityDomainDefinition['loopPhases']>;+ }>;+ health: CapabilityHealth;+}++export interface CapabilityBrain {+ schemaVersion: 'ruflo.capability-brain/v1';+ generatedAt: string;+ truthModel: {+ catalogued: string;+ registered: string;+ configured: string;+ reachable: string;+ healthy: string;+ authorized: string;+ };+ domains: CapabilityDomain[];+ cliCommands: string[];+ implementationLoop: ImplementationLoopStep[];+ coverage: {+ registeredToolCount: number;+ classifiedToolCount: number;+ coveragePercent: number;+ fallbackClassifiedTools: string[];+ duplicateToolNames: string[];+ };+}++/** Top-level commands from the CLI command loader. Kept as a checked manifest. */+export const RUFLO_CLI_COMMANDS = [+ 'init', 'start', 'status', 'task', 'session', 'agent', 'swarm', 'memory',+ 'mcp', 'config', 'migrate', 'hooks', 'workflow', 'hive-mind', 'process',+ 'daemon', 'version', 'neural', 'security', 'performance', 'providers',+ 'plugins', 'deployment', 'claims', 'policy', 'embeddings', 'completions',+ 'doctor', 'verify', 'analyze', 'route', 'progress', 'issues', 'update',+ 'ruvector', 'benchmark', 'guidance', 'appliance', 'appliance-advanced',+ 'transfer-store', 'cleanup', 'autopilot', 'gaia-bench', 'metaharness',+ 'eject', 'funnel', 'settings', 'auth', 'proxy', 'advisor', 'spinner',+ 'announcements',+] as const;++export interface ImplementationLoopStep {+ id: string;+ name: string;+ purpose: string;+ preferredTools: string[];+ requiredEvidence: string;+ mutation: 'none' | 'workspace' | 'external';+}++export const IMPLEMENTATION_LOOP: readonly ImplementationLoopStep[] = [+ {+ id: 'recall',+ name: 'Recall',+ purpose: 'Search Ruflo memory and relevant ADRs before choosing an approach.',+ preferredTools: ['memory_search', 'guidance_brain', 'guidance_recommend'],+ requiredEvidence: 'Relevant patterns and constraints, or an explicit no-match result.',+ mutation: 'none',+ },+ {+ id: 'inspect',+ name: 'Inspect',+ purpose: 'Read repository, runtime, dependency, policy, and health state.',+ preferredTools: ['analyze_project', 'system_status', 'policy_status', 'security_scan'],+ requiredEvidence: 'Observed source/runtime state with unknowns kept explicit.',+ mutation: 'none',+ },+ {+ id: 'route',+ name: 'Route',+ purpose: 'Select the smallest capable topology, agents, skills, and tools.',+ preferredTools: ['hooks_route', 'guidance_recommend', 'swarm_init'],+ requiredEvidence: 'Chosen route, ownership boundaries, and fallback behavior.',+ mutation: 'none',+ },+ {+ id: 'plan',+ name: 'Plan',+ purpose: 'Define acceptance criteria, safety envelope, leases, and validation.',+ preferredTools: ['task_create', 'workflow_create', 'claims_check'],+ requiredEvidence: 'Testable acceptance criteria and authorization boundary.',+ mutation: 'none',+ },+ {+ id: 'execute',+ name: 'Execute',+ purpose: 'Have the coding agent perform the actual scoped implementation.',+ preferredTools: ['agent_spawn', 'task_assign', 'terminal_execute'],+ requiredEvidence: 'Exact source-state change and implementation log.',+ mutation: 'workspace',+ },+ {+ id: 'test',+ name: 'Test',+ purpose: 'Run focused and regression tests, including failure paths.',+ preferredTools: ['terminal_execute', 'hooks_coverage-gaps', 'analyze_code'],+ requiredEvidence: 'Test command, result, environment, and failures.',+ mutation: 'workspace',+ },+ {+ id: 'validate',+ name: 'Validate',+ purpose: 'Check types, security, policy, compatibility, and artifact integrity.',+ preferredTools: ['security_audit', 'policy_evaluate', 'metaharness_threat-model'],+ requiredEvidence: 'Independent validation results bound to source state.',+ mutation: 'none',+ },+ {+ id: 'benchmark',+ name: 'Benchmark',+ purpose: 'Measure representative workload behavior against a baseline.',+ preferredTools: ['performance_benchmark', 'metaharness_score'],+ requiredEvidence: 'Reproducible baseline, candidate measurement, and environment.',+ mutation: 'none',+ },+ {+ id: 'optimize',+ name: 'Optimize',+ purpose: 'Improve only measured bottlenecks without weakening the safety envelope.',+ preferredTools: ['performance_profile', 'neural_optimize'],+ requiredEvidence: 'Measured improvement and unchanged correctness/security gates.',+ mutation: 'workspace',+ },+ {+ id: 'receipt',+ name: 'Receipt',+ purpose: 'Bind claims, tests, benchmarks, and decisions to exact source/build evidence.',+ preferredTools: ['claims_validate', 'memory_store'],+ requiredEvidence: 'Content-bound receipt with evidence strength stated honestly.',+ mutation: 'workspace',+ },+ {+ id: 'handoff',+ name: 'Handoff',+ purpose: 'Reconcile concurrent work and communicate remaining risks.',+ preferredTools: ['session_handoff', 'task_status', 'swarm_status'],+ requiredEvidence: 'Ownership reconciliation and explicit unresolved limitations.',+ mutation: 'none',+ },+ {+ id: 'publish',+ name: 'Publish',+ purpose: 'Publish only after an authorized release gate approves exact artifacts.',+ preferredTools: ['github_pr_create', 'github_release_create'],+ requiredEvidence: 'Human/policy authorization, clean source, immutable artifact digests, and green gates.',+ mutation: 'external',+ },+] as const;++/**+ * Domain order is significant: narrow/specialized matches precede broad+ * compatibility prefixes. Every registered tool is eventually classified by+ * the final runtime-services domain, but fallback classifications are reported.+ */+export const CAPABILITY_DOMAINS: readonly CapabilityDomainDefinition[] = [+ {+ id: 'guidance',+ name: 'Capability Guidance',+ description: 'Live capability inventory, task routing, workflow guidance, and system discovery.',+ prefixes: ['guidance_'],+ taskSignals: ['guidance', 'discover', 'capability', 'what can ruflo do'],+ commands: ['guidance compile', 'guidance retrieve', 'guidance gates', 'guidance optimize'],+ skills: [],+ agents: [],+ maturity: 'stable',+ authority: 'advisory',+ risk: 'read-only',+ useWhen: 'Choosing Ruflo capabilities or checking whether a claimed MCP function is actually registered.',+ verifyBeforeUse: ['Treat configured, reachable, healthy, and authorized as unknown until probed.'],+ },+ {+ id: 'identity-auth',+ name: 'Cognitum Identity & OAuth',+ description: 'Profile-aware PKCE/OOB authentication, credential status, consent-bound scopes, refresh, and local logout.',+ prefixes: ['auth_', 'oauth_'],+ taskSignals: ['auth', 'oauth', 'login', 'logout', 'credential', 'profile', 'scope', 'consent'],+ commands: ['auth login', 'auth login --no-browser', 'auth status', 'auth status --check', 'auth logout'],+ skills: ['security-audit'],+ agents: ['authentication', 'security-architect'],+ maturity: 'experimental',+ authority: 'control-plane',+ risk: 'privileged',+ availabilityMode: 'configured-remote',+ riskFlags: ['read', 'local-write', 'network', 'credential-pii', 'approval'],+ loopPhases: ['discover', 'authorize-claim', 'observe'],+ useWhen: 'A Cognitum-backed capability needs an explicit user identity and consent-bound scope.',+ verifyBeforeUse: [+ 'Use PKCE on interactive desktops and the implemented OOB/manual flow for headless use; RFC 8628 device polling is not implemented.',+ 'Noninteractive login fails closed unless --token-stdin is explicit.',+ 'Plain auth status is offline-safe; --check may refresh through the OS keychain.',+ 'Local logout cannot currently prove server-side token revocation.',+ ],+ },+ {+ id: 'policy-authorization',+ name: 'Policy Authorization',+ description: 'Policy-decision evaluation and status for exact subject/action/resource requests.',+ prefixes: ['policy_'],+ taskSignals: ['policy', 'authorization', 'permission', 'capability', 'access control'],+ commands: ['policy evaluate', 'policy status', 'guidance gates'],+ skills: ['claims', 'security-audit', 'v3-security-overhaul'],+ agents: ['security-architect', 'reviewer'],+ maturity: 'experimental',+ authority: 'control-plane',+ risk: 'privileged',+ availabilityMode: 'policy-filtered',+ riskFlags: ['approval'],+ loopPhases: ['authorize-claim', 'validate-critique', 'publish'],+ useWhen: 'Determining whether a principal may perform an exact action on an exact resource.',+ verifyBeforeUse: ['Confirm subject, action, resource, tenant, policy version, and freshness.', 'Remote MCP exposes evaluation/status only; administration remains local and authenticated.'],+ },+ {+ id: 'work-claims',+ name: 'Exclusive Work Claims',+ description: 'Repository/task ownership claims, handoffs, contention, stealing, and rebalance.',+ prefixes: ['claims_'],+ taskSignals: ['work claim', 'claim task', 'handoff', 'ownership', 'concurrent work', 'rebalance'],+ commands: ['claims claim', 'claims handoff', 'claims status'],+ skills: ['claims'],+ agents: ['coordinator'],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ riskFlags: ['concurrency', 'local-write'],+ loopPhases: ['authorize-claim', 'route-plan', 'observe'],+ useWhen: 'Coordinating exclusive repository or task ownership among concurrent workers.',+ verifyBeforeUse: ['A work claim prevents collisions; it does not grant product, network, or release authority.', 'Validate repository, path scope, owner, epoch, and expiry.'],+ },+ {+ id: 'content-safety',+ name: 'AIDefence Content Safety',+ description: 'Prompt/content safety, PII detection, learning, and security evidence.',+ prefixes: ['aidefence_', 'security_'],+ taskSignals: ['security', 'content safety', 'pii', 'prompt injection', 'threat', 'audit'],+ commands: ['security scan'],+ skills: ['security-audit', 'v3-security-overhaul'],+ agents: ['security-architect', 'reviewer'],+ maturity: 'experimental',+ authority: 'advisory',+ risk: 'read-only',+ riskFlags: ['read', 'credential-pii'],+ loopPhases: ['validate-critique', 'observe'],+ useWhen: 'Scanning untrusted content or collecting security evidence.',+ verifyBeforeUse: ['A score is evidence, not authorization.', 'Do not persist detected credentials or PII.'],+ },+ {+ id: 'metaharness-flywheel',+ name: 'MetaHarness, Darwin & Flywheel',+ description: 'Candidate scoring, static analysis, threat modeling, genome exploration, and controlled improvement loops.',+ prefixes: ['metaharness_', 'autopilot_'],+ taskSignals: ['metaharness', 'darwin', 'flywheel', 'genome', 'optimize', 'autopilot'],+ commands: ['metaharness score', 'metaharness genome', 'autopilot run'],+ skills: ['metaharness-brain', 'performance-analysis'],+ agents: ['performance-engineer', 'reviewer'],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'reversible',+ optionalRuntime: true,+ riskFlags: ['local-write', 'process-exec', 'network', 'spend', 'promotion'],+ loopPhases: ['branch-propose', 'validate-critique', 'observe'],+ useWhen: 'Exploring or evaluating candidate improvements under a separate promotion authority.',+ verifyBeforeUse: ['Darwin proposes; the Ruflo promotion gate decides.', 'Degraded/fallback runs are evaluation-only unless policy explicitly permits promotion.'],+ },+ {+ id: 'memory-knowledge',+ name: 'Memory, AgentDB & Embeddings',+ description: 'Persistent memory, semantic/vector retrieval, namespaces, embeddings, and AgentDB controllers.',+ prefixes: ['memory_', 'agentdb_', 'embeddings_'],+ taskSignals: ['memory', 'agentdb', 'vector', 'embedding', 'semantic', 'recall'],+ commands: ['memory search', 'memory store', 'memory retrieve'],+ skills: ['memory-management', 'agentdb-advanced', 'agentdb-vector-search'],+ agents: ['memory-specialist'],+ maturity: 'stable',+ authority: 'capability-plane',+ risk: 'reversible',+ optionalRuntime: true,+ riskFlags: ['read', 'local-write', 'memory-poisoning'],+ useWhen: 'Recalling prior patterns or storing validated, content-bound learning.',+ verifyBeforeUse: ['Memory recall is evidence, not authority.', 'Only commit validated learning; do not auto-promote policy.'],+ },+ {+ id: 'memory-branching',+ name: 'Copy-on-Write & Speculative Memory',+ description: 'Low-cost memory branching, checkpoint, rollback, comparison, and validated promotion.',+ prefixes: ['agenticow_'],+ taskSignals: ['branch memory', 'checkpoint', 'rollback', 'speculative'],+ commands: [],+ skills: ['agentdb-learning'],+ agents: [],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ optionalRuntime: true,+ riskFlags: ['local-write', 'memory-poisoning', 'promotion'],+ useWhen: 'Testing alternative memories or strategies without mutating the active lineage.',+ verifyBeforeUse: ['Promotion requires a validated receipt and separate authority.'],+ },+ {+ id: 'agents-runtimes',+ name: 'Agent Lifecycle & Runtimes',+ description: 'Local agents, managed cloud agents, WASM sandboxes, and inference runtimes.',+ prefixes: ['agent_', 'managed_agent_', 'wasm_agent_', 'wasm_gallery_', 'ruvllm_'],+ taskSignals: ['agent', 'worker', 'wasm', 'sandbox', 'inference', 'managed agent'],+ commands: ['agent spawn', 'agent status', 'agent stop'],+ skills: ['agent-coder', 'agent-tester', 'agent-reviewer'],+ agents: ['coder', 'tester', 'reviewer'],+ maturity: 'stable',+ authority: 'capability-plane',+ risk: 'privileged',+ optionalRuntime: true,+ riskFlags: ['local-write', 'process-exec', 'network', 'credential-pii', 'spend', 'destructive'],+ useWhen: 'Assigning bounded work to an agent runtime after ownership is clear.',+ verifyBeforeUse: ['A spawned agent is not proof of execution.', 'Check runtime availability, provider credentials, spend limits, network policy, and collect exact outputs.'],+ },+ {+ id: 'swarm-coordination',+ name: 'Swarm & Coordination',+ description: 'Topology-aware multi-agent coordination, task ownership, and collective scheduling.',+ prefixes: ['swarm_', 'coordination_', 'daa_'],+ taskSignals: ['swarm', 'concurrent', 'parallel', 'coordinate', 'multi-agent'],+ commands: ['swarm init', 'swarm status', 'swarm coordinate'],+ skills: ['swarm-orchestration', 'swarm-advanced'],+ agents: ['coordinator', 'coder', 'tester', 'reviewer'],+ maturity: 'stable',+ authority: 'capability-plane',+ risk: 'reversible',+ useWhen: 'A task has multiple independent workstreams or more than two files.',+ verifyBeforeUse: ['Use repository-scoped ownership and reconcile before merge.', 'Coordination records do not execute code.'],+ },+ {+ id: 'consensus-federation',+ name: 'Hive Mind & Consensus',+ description: 'Hive, quorum, voting, gossip, and distributed agreement primitives.',+ prefixes: ['hive_', 'hive-mind_', 'consensus_', 'quorum_'],+ taskSignals: ['hive', 'consensus', 'quorum', 'byzantine', 'federation'],+ commands: ['hive-mind init', 'hive-mind status'],+ skills: ['hive-mind', 'hive-mind-advanced'],+ agents: ['byzantine-coordinator', 'raft-manager'],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ useWhen: 'Multiple principals must agree while preserving an external authorization boundary.',+ verifyBeforeUse: ['Consensus is not authorization.', 'Authenticate membership and bind decisions to policy.'],+ },+ {+ id: 'tasks-workflows-sessions',+ name: 'Tasks, Workflows, Sessions & Progress',+ description: 'Task orchestration, reusable workflows, session state, progress, and handoff.',+ prefixes: ['task_', 'workflow_', 'session_', 'progress_'],+ taskSignals: ['task', 'workflow', 'session', 'handoff', 'progress'],+ commands: ['task create', 'task status', 'workflow run'],+ skills: ['workflow-automation'],+ agents: ['workflow', 'planner'],+ maturity: 'stable',+ authority: 'capability-plane',+ risk: 'reversible',+ useWhen: 'Tracking multi-step work or handing execution between agents/sessions.',+ verifyBeforeUse: ['Persist exact source/run identity rather than relying on prose status.'],+ },+ {+ id: 'hooks-learning-routing',+ name: 'Hooks, Coverage & Learning Routing',+ description: 'Lifecycle hooks, coverage-aware routing, background workers, and validated pattern capture.',+ prefixes: ['hooks_', 'coverage_'],+ taskSignals: ['hook', 'coverage', 'route', 'worker', 'learning'],+ commands: ['hooks pre-task', 'hooks post-task', 'hooks route', 'hooks coverage-gaps'],+ skills: ['hooks-automation'],+ agents: [],+ maturity: 'stable',+ authority: 'capability-plane',+ risk: 'reversible',+ riskFlags: ['local-write', 'memory-poisoning', 'concurrency'],+ useWhen: 'Routing work, measuring coverage, or recording validated outcomes.',+ verifyBeforeUse: ['Hooks advise and record; Codex or another executor performs the work.'],+ },+ {+ id: 'analysis-quality',+ name: 'Analysis & Quality',+ description: 'Code/project analysis, quality assessment, and change inspection.',+ prefixes: ['analyze_', 'analysis_'],+ taskSignals: ['analyze', 'review', 'quality', 'dependency'],+ commands: ['analyze code', 'analyze project'],+ skills: ['verification-quality'],+ agents: ['code-analyzer', 'reviewer'],+ maturity: 'stable',+ authority: 'advisory',+ risk: 'read-only',+ useWhen: 'Understanding a codebase or validating change impact.',+ verifyBeforeUse: ['Bind conclusions to the inspected source state.'],+ },+ {+ id: 'test-generation',+ name: 'TDD Test Generation',+ description: 'TDD repair and test-generation capability exported by Ruflo but intentionally reported as unregistered until the MCP registry enables it.',+ prefixes: ['testgen_'],+ exactTools: ['testgen_tdd_repair'],+ taskSignals: ['generate tests', 'tdd repair', 'test generation'],+ commands: [],+ skills: ['verification-quality'],+ agents: ['tester'],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'reversible',+ availabilityMode: 'registered-degraded',+ riskFlags: ['local-write'],+ loopPhases: ['execute', 'validate-critique'],+ useWhen: 'Generating or repairing tests once the testgen tool is explicitly registered.',+ verifyBeforeUse: ['Catalogued does not mean registered; check live health.registered.', 'Generated tests still require review and execution.'],+ },+ {+ id: 'performance-neural',+ name: 'Performance & Neural Optimization',+ description: 'Profiling, benchmarks, learned routing, pattern training, and optimization.',+ prefixes: ['performance_', 'neural_'],+ taskSignals: ['performance', 'benchmark', 'profile', 'latency', 'neural', 'train'],+ commands: ['performance benchmark', 'performance profile', 'neural train'],+ skills: ['performance-analysis', 'neural-training'],+ agents: ['performance-engineer'],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ optionalRuntime: true,+ riskFlags: ['read', 'local-write', 'memory-poisoning', 'process-exec', 'spend', 'promotion'],+ useWhen: 'A reproducible baseline exists and a measured optimization is needed.',+ verifyBeforeUse: ['Apply hard resource/safety constraints before Pareto ranking.', 'Re-run correctness and security gates after optimization.'],+ },+ {+ id: 'browser-web',+ name: 'Browser & Web Actions',+ description: 'Browser sessions, page actions, intent routing, and guarded HTTP probes.',+ prefixes: ['browser_', 'http_fetch'],+ taskSignals: ['browser', 'web page', 'navigate', 'click', 'http', 'fetch'],+ commands: ['browser open', 'browser act'],+ skills: [],+ agents: [],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ optionalRuntime: true,+ riskFlags: ['network', 'credential-pii', 'spend', 'approval'],+ useWhen: 'Interacting with web surfaces or testing endpoints under explicit network policy.',+ verifyBeforeUse: ['Check network target policy, authentication, side effects, and runtime provider health.'],+ },+ {+ id: 'github-delivery',+ name: 'GitHub & Delivery',+ description: 'Issues, pull requests, workflows, releases, repository automation, and handoff.',+ prefixes: ['github_', 'pr_', 'release_'],+ taskSignals: ['github', 'issue', 'pull request', 'merge', 'release', 'publish'],+ commands: ['github pr', 'github release'],+ skills: ['github-automation', 'github-release-management'],+ agents: ['pr-manager', 'release-manager'],+ maturity: 'stable',+ authority: 'control-plane',+ risk: 'privileged',+ riskFlags: ['network', 'credential-pii', 'approval', 'destructive'],+ useWhen: 'Managing GitHub state after explicit authorization and validation.',+ verifyBeforeUse: ['External writes require current authorization.', 'Publish immutable artifacts from a clean, exact source state.'],+ },+ {+ id: 'business-collaboration',+ name: 'AgentBBS & Business Pods',+ description: 'Federated business rooms, domain-affinity routing, and business-pod validation.',+ // Metadata classification only; execution remains behind the existing loadAgentbbs guard.+ prefixes: ['agentbbs_', 'business_pod_', 'federation_bbs_'],+ taskSignals: ['business pod', 'bbs', 'room', 'domain affinity'],+ commands: [],+ skills: [],+ agents: [],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ optionalRuntime: true,+ riskFlags: ['network', 'credential-pii', 'spend', 'concurrency'],+ useWhen: 'Coordinating business-domain agents across a federated room or pod.',+ verifyBeforeUse: ['Authenticate room membership and enforce claim/resource policy at ingress.'],+ },+ {+ id: 'configuration-transfer',+ name: 'Configuration & Transfer',+ description: 'Configuration state plus portable import, export, backup, and migration.',+ prefixes: ['config_', 'transfer_'],+ taskSignals: ['config', 'setup', 'import', 'export', 'backup', 'migrate'],+ commands: ['config show', 'memory export'],+ skills: [],+ agents: [],+ maturity: 'stable',+ authority: 'control-plane',+ risk: 'privileged',+ riskFlags: ['read', 'local-write', 'credential-pii', 'destructive'],+ useWhen: 'Inspecting configuration or moving Ruflo state between installations.',+ verifyBeforeUse: ['Redact secrets and validate destination compatibility before mutation.'],+ },+ {+ id: 'system-terminal',+ name: 'System & Terminal Compatibility',+ description: 'System diagnostics and legacy-compatible terminal execution surfaces.',+ prefixes: ['system_', 'terminal_', 'mcp_'],+ taskSignals: ['terminal', 'shell', 'doctor', 'system status'],+ commands: ['doctor', 'status'],+ skills: [],+ agents: [],+ maturity: 'compatibility',+ authority: 'control-plane',+ risk: 'privileged',+ riskFlags: ['read', 'local-write', 'process-exec', 'credential-pii', 'destructive', 'approval'],+ useWhen: 'Diagnosing Ruflo or using an MCP execution surface that policy explicitly permits.',+ verifyBeforeUse: ['Prefer native executor tools for ordinary shell/file work.', 'Validate command, cwd, environment, timeout, and destructive scope.'],+ },+ {+ id: 'runtime-services',+ name: 'Other Registered Runtime Services',+ description: 'Live MCP tools not yet assigned to a specialized domain; included so coverage is never silently incomplete.',+ prefixes: [],+ taskSignals: [],+ commands: [],+ skills: [],+ agents: [],+ maturity: 'experimental',+ authority: 'capability-plane',+ risk: 'privileged',+ useWhen: 'Only after inspecting the tool schema and policy because specialized guidance is not yet available.',+ verifyBeforeUse: ['Treat fallback classification as a guidance coverage gap.', 'Inspect the tool description, schema, side effects, and policy before use.'],+ },+] as const;++function toolMatchesDomain(tool: CapabilityToolMetadata, domain: CapabilityDomainDefinition): boolean {+ if (domain.exactTools?.includes(tool.name)) return true;+ return domain.prefixes.some((prefix) => tool.name.startsWith(prefix));+}++export function classifyCapabilityTool(tool: CapabilityToolMetadata): CapabilityDomainDefinition {+ return CAPABILITY_DOMAINS.find((domain) =>+ domain.id !== 'runtime-services' && toolMatchesDomain(tool, domain)+ ) ?? CAPABILITY_DOMAINS[CAPABILITY_DOMAINS.length - 1]!;+}++function defaultAvailabilityMode(+ definition: CapabilityDomainDefinition,+): NonNullable<CapabilityDomainDefinition['availabilityMode']> {+ if (definition.availabilityMode) return definition.availabilityMode;+ if (definition.id === 'browser-web') return 'conditional-registration';+ if (definition.id === 'github-delivery' || definition.id === 'business-collaboration') {+ return 'configured-remote';+ }+ if (definition.optionalRuntime) return 'registered-degraded';+ return 'always-local';+}++function defaultRiskFlags(+ definition: CapabilityDomainDefinition,+): NonNullable<CapabilityDomainDefinition['riskFlags']> {+ if (definition.riskFlags) return [...definition.riskFlags];+ if (definition.risk === 'read-only') return ['read'];+ if (definition.risk === 'reversible') return ['local-write'];+ return definition.authority === 'control-plane'+ ? ['approval', 'local-write']+ : ['local-write', 'concurrency'];+}++function defaultLoopPhases(+ definition: CapabilityDomainDefinition,+): NonNullable<CapabilityDomainDefinition['loopPhases']> {+ if (definition.loopPhases) return [...definition.loopPhases];+ if (definition.authority === 'advisory') return ['discover', 'validate-critique', 'observe'];+ if (definition.authority === 'control-plane') return ['authorize-claim', 'execute', 'publish'];+ return ['route-plan', 'execute', 'observe'];+}++const TOOL_OWNERSHIP: ReadonlyArray<{+ prefixes: string[];+ packageOwner: string;+ pluginOwner?: string;+}> = [+ { prefixes: ['policy_'], packageOwner: '@claude-flow/security', pluginOwner: 'ruflo-security-audit' },+ { prefixes: ['aidefence_', 'security_'], packageOwner: '@claude-flow/aidefence', pluginOwner: 'ruflo-aidefence' },+ { prefixes: ['claims_'], packageOwner: '@claude-flow/claims', pluginOwner: 'ruflo-core' },+ { prefixes: ['memory_'], packageOwner: '@claude-flow/memory', pluginOwner: 'ruflo-rag-memory' },+ { prefixes: ['agentdb_'], packageOwner: 'agentdb', pluginOwner: 'ruflo-agentdb' },+ { prefixes: ['embeddings_'], packageOwner: '@claude-flow/embeddings', pluginOwner: 'ruflo-rag-memory' },+ { prefixes: ['swarm_', 'coordination_'], packageOwner: '@claude-flow/swarm', pluginOwner: 'ruflo-swarm' },+ { prefixes: ['hooks_', 'coverage_'], packageOwner: '@claude-flow/hooks', pluginOwner: 'ruflo-loop-workers' },+ { prefixes: ['neural_'], packageOwner: '@claude-flow/neural', pluginOwner: 'ruflo-intelligence' },+ { prefixes: ['ruvllm_'], packageOwner: '@ruvector/ruvllm', pluginOwner: 'ruflo-ruvllm' },+ { prefixes: ['browser_'], packageOwner: '@claude-flow/browser', pluginOwner: 'ruflo-browser' },+ { prefixes: ['metaharness_'], packageOwner: 'metaharness', pluginOwner: 'ruflo-metaharness' },+ { prefixes: ['agenticow_'], packageOwner: 'agenticow', pluginOwner: 'ruflo-rvf' },+ { prefixes: ['federation_bbs_'], packageOwner: '@claude-flow/plugin-agent-federation', pluginOwner: 'ruflo-bbs-federation' },+ { prefixes: ['business_pod_'], packageOwner: '@claude-flow/cli', pluginOwner: 'ruflo-business-pods' },+ { prefixes: ['testgen_'], packageOwner: '@claude-flow/cli', pluginOwner: 'ruflo-testgen' },+ { prefixes: ['managed_agent_', 'wasm_agent_', 'wasm_gallery_'], packageOwner: '@claude-flow/cli', pluginOwner: 'ruflo-agent' },+ { prefixes: ['guidance_'], packageOwner: '@claude-flow/guidance', pluginOwner: 'ruflo-core' },+] as const;++function ownershipForTool(+ toolName: string,+ definition: CapabilityDomainDefinition,+): { packageOwner: string; pluginOwner?: string } {+ const explicit = TOOL_OWNERSHIP.find((entry) =>+ entry.prefixes.some((prefix) => toolName.startsWith(prefix))+ );+ if (explicit) {+ return {+ packageOwner: explicit.packageOwner,+ ...(explicit.pluginOwner ? { pluginOwner: explicit.pluginOwner } : {}),+ };+ }+ return {+ packageOwner: definition.packageOwners?.[0] ?? '@claude-flow/cli',+ ...(definition.pluginOwners?.[0] ? { pluginOwner: definition.pluginOwners[0] } : {}),+ };+}++export function buildCapabilityBrain(+ registeredTools: readonly CapabilityToolMetadata[],+ now = new Date(),+): CapabilityBrain {+ const seen = new Set<string>();+ const duplicates = new Set<string>();+ const toolsByDomain = new Map<string, CapabilityToolMetadata[]>();+ const fallbackClassifiedTools: string[] = [];++ for (const tool of registeredTools) {+ if (seen.has(tool.name)) duplicates.add(tool.name);+ seen.add(tool.name);+ const domain = classifyCapabilityTool(tool);+ if (domain.id === 'runtime-services') fallbackClassifiedTools.push(tool.name);+ const tools = toolsByDomain.get(domain.id) ?? [];+ tools.push({ ...tool });+ toolsByDomain.set(domain.id, tools);+ }++ const domains = CAPABILITY_DOMAINS.map((definition): CapabilityDomain => {+ const packageOwners = definition.packageOwners ?? ['@claude-flow/cli'];+ const pluginOwners = definition.pluginOwners ?? [];+ const availabilityMode = defaultAvailabilityMode(definition);+ const riskFlags = defaultRiskFlags(definition);+ const loopPhases = defaultLoopPhases(definition);+ const tools = (toolsByDomain.get(definition.id) ?? [])+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)+ .map((tool) => {+ const ownership = ownershipForTool(tool.name, definition);+ return {+ ...tool,+ domain: definition.id,+ packageOwner: ownership.packageOwner,+ ...(ownership.pluginOwner ? { pluginOwner: ownership.pluginOwner } : {}),+ availabilityMode,+ authority: definition.authority,+ risk: definition.risk,+ riskFlags: [...riskFlags],+ loopPhases: [...loopPhases],+ };+ });+ return {+ ...definition,+ prefixes: [...definition.prefixes],+ exactTools: definition.exactTools ? [...definition.exactTools] : undefined,+ taskSignals: [...definition.taskSignals],+ commands: [...definition.commands],+ skills: [...definition.skills],+ agents: [...definition.agents],+ packageOwners: [...packageOwners],+ pluginOwners: [...pluginOwners],+ availabilityMode,+ riskFlags,+ loopPhases,+ tools,+ health: {+ registered: tools.length > 0,+ configured: 'unknown',+ reachable: 'unknown',+ healthy: 'unknown',+ authorized: 'unknown',+ },+ };+ });++ const uniqueToolCount = seen.size;+ const classifiedToolCount = uniqueToolCount;+ return {+ schemaVersion: 'ruflo.capability-brain/v1',+ generatedAt: now.toISOString(),+ truthModel: {+ catalogued: 'Described by this version of Ruflo; it does not prove runtime presence.',+ registered: 'Present in this process MCP registry; it does not prove configuration or health.',+ configured: 'Required providers and settings are present.',+ reachable: 'Dependencies answer a non-mutating probe.',+ healthy: 'Dependencies satisfy their service-specific health contract.',+ authorized: 'Current subject is allowed to perform the exact action on the exact resource.',+ },+ domains,+ cliCommands: [...RUFLO_CLI_COMMANDS],+ implementationLoop: IMPLEMENTATION_LOOP.map((step) => ({+ ...step,+ preferredTools: [...step.preferredTools],+ })),+ coverage: {+ registeredToolCount: uniqueToolCount,+ classifiedToolCount,+ coveragePercent: uniqueToolCount === 0 ? 100 : 100,+ fallbackClassifiedTools: fallbackClassifiedTools.sort(),+ duplicateToolNames: [...duplicates].sort(),+ },+ };+}++export interface CapabilityRecommendation {+ task: string;+ domains: Array<{+ id: string;+ name: string;+ score: number;+ registeredTools: string[];+ health: CapabilityHealth;+ authority: CapabilityAuthority;+ risk: CapabilityRisk;+ verifyBeforeUse: string[];+ }>;+ implementationLoop: ImplementationLoopStep[];+ guardrails: string[];+}++export function recommendCapabilities(brain: CapabilityBrain, task: string): CapabilityRecommendation {+ const normalized = task.toLocaleLowerCase('en-US');+ const scored = brain.domains+ .filter((domain) => domain.id !== 'runtime-services')+ .map((domain) => {+ const score = domain.taskSignals.reduce((total, signal) =>+ normalized.includes(signal.toLocaleLowerCase('en-US')) ? total + 1 : total, 0);+ return { domain, score };+ })+ .filter(({ score }) => score > 0)+ .sort((left, right) => right.score - left.score || (+ left.domain.id < right.domain.id ? -1 : left.domain.id > right.domain.id ? 1 : 0+ ))+ .slice(0, 6);++ const selected = scored.length > 0+ ? scored+ : brain.domains+ .filter((domain) => ['guidance', 'tasks-workflows-sessions'].includes(domain.id))+ .map((domain) => ({ domain, score: 0 }));++ return {+ task,+ domains: selected.map(({ domain, score }) => ({+ id: domain.id,+ name: domain.name,+ score,+ registeredTools: domain.tools.map((tool) => tool.name),+ health: { ...domain.health },+ authority: domain.authority,+ risk: domain.risk,+ verifyBeforeUse: [...domain.verifyBeforeUse],+ })),+ implementationLoop: brain.implementationLoop.map((step) => ({+ ...step,+ preferredTools: step.preferredTools.filter((name) =>+ brain.domains.some((domain) => domain.tools.some((tool) => tool.name === name))+ ),+ })),+ guardrails: [+ 'Registered, configured, reachable, healthy, and authorized are independent facts.',+ 'Ruflo coordinates and records; the executor performs implementation.',+ 'Learning, optimization, consensus, and claims are capability-plane inputs, never self-authorizing promotion.',+ 'External publication requires explicit authority and exact source/build evidence.',+ ],+ };+}diff --git a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.tsindex 3a27450c64..7a85c2eb27 100644--- a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts@@ -10,45 +10,73 @@import { type MCPTool, getProjectCwd } from './types.js';import { validateIdentifier, validateText } from './validate-input.js';import { existsSync, readFileSync, readdirSync } from 'node:fs';-import { join, dirname } from 'node:path';+import { join, dirname, relative } from 'node:path';import { fileURLToPath } from 'node:url';+import {+ buildCapabilityBrain,+ recommendCapabilities,+ type CapabilityToolMetadata,+} from './capability-brain.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);-const CLI_ROOT = join(__dirname, '../../..');-/*** Find the project root by looking for .claude/ directory.* Tries CWD first (most common), then walks up from the CLI package location.*/function findProjectRoot(): string {- // Strategy 1: CWD (most reliable when invoked by user)- if (existsSync(join(getProjectCwd(), '.claude'))) {- return getProjectCwd();+ const cwd = getProjectCwd();+ let cwdIsCliPackage = false;+ const cwdManifest = join(cwd, 'package.json');+ if (existsSync(cwdManifest)) {+ try {+ const manifest = JSON.parse(readFileSync(cwdManifest, 'utf-8')) as { name?: string };+ cwdIsCliPackage = manifest.name === '@claude-flow/cli';+ } catch {+ // An invalid project manifest is not a reason to hide discoverable files.+ }}- // Strategy 2: Walk up from CLI package location- // CLI is at v3/@claude-flow/cli/ — project root is 4 levels up- const fromPackage = join(CLI_ROOT, '../../../..');- if (existsSync(join(fromPackage, '.claude'))) {- return fromPackage;+ // User projects with a local .claude directory remain the primary root.+ // Exclude the CLI package's own shipped .claude assets during repository+ // development; otherwise ecosystem discovery silently stops at the package.+ if (!cwdIsCliPackage && existsSync(join(cwd, '.claude'))) {+ return cwd;}- // Strategy 3: Walk up from CWD- let dir = getProjectCwd();+ // Walk up to a Git/workspace root. Worktrees use a .git file, so existsSync+ // is intentionally used instead of requiring a directory.+ let dir = cwd;for (let i = 0; i < 10; i++) {- if (existsSync(join(dir, '.claude'))) return dir;+ if (existsSync(join(dir, '.git'))) return dir;+ if (!(cwdIsCliPackage && dir === cwd) && existsSync(join(dir, '.claude'))) return dir;const parent = dirname(dir);if (parent === dir) break;dir = parent;}// Fallback: CWD- return getProjectCwd();+ return cwd;}const PROJECT_ROOT = findProjectRoot();+/**+ * Injected by mcp-client after every MCP tool has been registered. Keeping the+ * provider here avoids guidance importing the registry and creating a cycle.+ */+let liveToolProvider: () => readonly CapabilityToolMetadata[] = () => [];++export function configureGuidanceToolProvider(+ provider: () => readonly CapabilityToolMetadata[],+): void {+ liveToolProvider = provider;+}++function getCapabilityBrain() {+ return buildCapabilityBrain(liveToolProvider());+}+// ── Capability Catalog ──────────────────────────────────────interface CapabilityArea {@@ -315,9 +343,6 @@ const WORKFLOW_TEMPLATES: Record<string, { steps: string[]; agents: string[]; to// ── Dynamic Discovery ───────────────────────────────────────function discoverAgents(): string[] {- const agentsDir = join(PROJECT_ROOT, '.claude/agents');- if (!existsSync(agentsDir)) return [];-const agents: string[] = [];function walk(dir: string) {try {@@ -333,27 +358,117 @@ function discoverAgents(): string[] {}} catch { /* ignore */ }}- walk(agentsDir);+ const roots = [+ join(PROJECT_ROOT, '.claude/agents'),+ join(PROJECT_ROOT, '.agents/agents'),+ ];+ const pluginsDir = join(PROJECT_ROOT, 'plugins');+ if (existsSync(pluginsDir)) {+ for (const entry of readdirSync(pluginsDir, { withFileTypes: true })) {+ if (entry.isDirectory()) roots.push(join(pluginsDir, entry.name, 'agents'));+ }+ }+ for (const root of roots) {+ if (existsSync(root)) walk(root);+ }return [...new Set(agents)].sort();}function discoverSkills(): string[] {- const skillsDir = join(PROJECT_ROOT, '.claude/skills');- if (!existsSync(skillsDir)) return [];-const skills: string[] = [];- try {- const entries = readdirSync(skillsDir, { withFileTypes: true });- for (const entry of entries) {- if (entry.isDirectory()) {- const skillFile = join(skillsDir, entry.name, 'SKILL.md');- if (existsSync(skillFile)) {- skills.push(entry.name);+ function walk(dir: string) {+ try {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const target = join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(target);+ } else if (entry.name === 'SKILL.md') {+ const content = readFileSync(target, 'utf-8');+ const nameMatch = content.match(/^name:\s*(.+)$/m);+ skills.push(+ nameMatch+ ? nameMatch[1]!.trim().replace(/^["']|["']$/g, '')+ : relative(PROJECT_ROOT, dirname(target)),+ );}}+ } catch {+ // Missing or unreadable optional capability roots are reported by absence.+ }+ }++ const roots = [+ join(PROJECT_ROOT, '.claude/skills'),+ join(PROJECT_ROOT, '.agents/skills'),+ ];+ const pluginsDir = join(PROJECT_ROOT, 'plugins');+ if (existsSync(pluginsDir)) {+ for (const entry of readdirSync(pluginsDir, { withFileTypes: true })) {+ if (entry.isDirectory()) roots.push(join(pluginsDir, entry.name, 'skills'));+ }+ }+ for (const root of roots) {+ if (existsSync(root)) walk(root);+ }+ return [...new Set(skills)].sort();+}++function discoverPlugins(): Array<Record<string, unknown>> {+ const pluginsDir = join(PROJECT_ROOT, 'plugins');+ if (!existsSync(pluginsDir)) return [];+ const plugins: Array<Record<string, unknown>> = [];+ for (const entry of readdirSync(pluginsDir, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const manifestPath = join(pluginsDir, entry.name, '.claude-plugin', 'plugin.json');+ if (!existsSync(manifestPath)) continue;+ try {+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<string, unknown>;+ plugins.push({+ id: entry.name,+ name: manifest.name ?? entry.name,+ version: manifest.version ?? 'unknown',+ description: manifest.description ?? '',+ manifest: relative(PROJECT_ROOT, manifestPath),+ });+ } catch {+ plugins.push({+ id: entry.name,+ name: entry.name,+ version: 'unknown',+ manifest: relative(PROJECT_ROOT, manifestPath),+ invalidManifest: true,+ });+ }+ }+ return plugins.sort((left, right) => String(left.id).localeCompare(String(right.id), 'en-US'));+}++function discoverPackages(): Array<Record<string, unknown>> {+ const packagesDir = join(PROJECT_ROOT, 'v3', '@claude-flow');+ if (!existsSync(packagesDir)) return [];+ const packages: Array<Record<string, unknown>> = [];+ for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const manifestPath = join(packagesDir, entry.name, 'package.json');+ if (!existsSync(manifestPath)) continue;+ try {+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<string, unknown>;+ packages.push({+ name: manifest.name ?? entry.name,+ version: manifest.version ?? 'unknown',+ description: manifest.description ?? '',+ manifest: relative(PROJECT_ROOT, manifestPath),+ });+ } catch {+ packages.push({+ name: entry.name,+ version: 'unknown',+ manifest: relative(PROJECT_ROOT, manifestPath),+ invalidManifest: true,+ });}- } catch { /* ignore */ }- return skills.sort();+ }+ return packages.sort((left, right) => String(left.name).localeCompare(String(right.name), 'en-US'));}// ── MCP Tool Definitions ────────────────────────────────────@@ -378,20 +493,49 @@ const guidanceCapabilities: MCPTool = {handler: async (params: Record<string, unknown>) => {const area = params.area as string | undefined;const format = (params.format as string) || 'summary';+ const brain = getCapabilityBrain();if (area) { const v = validateIdentifier(area, 'area'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; }if (area) {const cap = CAPABILITY_CATALOG[area];- if (!cap) {- const available = Object.keys(CAPABILITY_CATALOG).join(', ');+ const brainDomain = brain.domains.find((domain) => domain.id === area);+ if (!cap && !brainDomain) {+ const available = [+ ...Object.keys(CAPABILITY_CATALOG),+ ...brain.domains.map((domain) => domain.id),+ ].filter((value, index, all) => all.indexOf(value) === index).join(', ');return { content: [{ type: 'text', text: JSON.stringify({ error: `Unknown area: ${area}`, available }, null, 2) }], isError: true };}- return { content: [{ type: 'text', text: JSON.stringify(cap, null, 2) }] };+ return {+ content: [{+ type: 'text',+ text: JSON.stringify({+ ...(cap ?? {}),+ legacyCatalogStatus: cap ? 'compatibility-only; tool names may be deprecated aliases' : undefined,+ legacyToolResolution: cap ? cap.tools.map((name) => ({+ name,+ registered: brain.domains.some((entry) => entry.tools.some((tool) => tool.name === name)),+ })) : undefined,+ capabilityBrain: brainDomain,+ }, null, 2),+ }],+ };}if (format === 'detailed') {- return { content: [{ type: 'text', text: JSON.stringify(CAPABILITY_CATALOG, null, 2) }] };+ return {+ content: [{+ type: 'text',+ text: JSON.stringify({+ legacyCatalog: {+ status: 'compatibility-only; use capabilityBrain for live routing',+ areas: CAPABILITY_CATALOG,+ },+ capabilityBrain: brain,+ }, null, 2),+ }],+ };}const summary = Object.entries(CAPABILITY_CATALOG).map(([key, val]) => ({@@ -404,7 +548,30 @@ const guidanceCapabilities: MCPTool = {whenToUse: val.whenToUse,}));- return { content: [{ type: 'text', text: JSON.stringify({ areas: summary, totalAreas: summary.length }, null, 2) }] };+ return {+ content: [{+ type: 'text',+ text: JSON.stringify({+ areas: summary,+ totalAreas: summary.length,+ live: {+ schemaVersion: brain.schemaVersion,+ registeredToolCount: brain.coverage.registeredToolCount,+ classifiedToolCount: brain.coverage.classifiedToolCount,+ coveragePercent: brain.coverage.coveragePercent,+ fallbackClassifiedTools: brain.coverage.fallbackClassifiedTools,+ domains: brain.domains.map((domain) => ({+ id: domain.id,+ name: domain.name,+ registeredToolCount: domain.tools.length,+ health: domain.health,+ authority: domain.authority,+ risk: domain.risk,+ })),+ },+ }, null, 2),+ }],+ };},};@@ -425,6 +592,8 @@ const guidanceRecommend: MCPTool = {const task = params.task as string;{ const v = validateText(task, 'task'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; }+ const brain = getCapabilityBrain();+ const capabilityRecommendation = recommendCapabilities(brain, task);const matches: Array<{ area: string; capability: CapabilityArea; workflow: string; score: number }> = [];@@ -463,6 +632,7 @@ const guidanceRecommend: MCPTool = {{ area: 'hooks-automation', reason: 'Use hooks for task routing and learning' },],tip: 'Use guidance_capabilities for a full list of all capability areas.',+ capabilityBrain: capabilityRecommendation,}, null, 2),}],};@@ -470,6 +640,9 @@ const guidanceRecommend: MCPTool = {const primaryWorkflow = recommendations[0]?.workflow;const template = primaryWorkflow ? WORKFLOW_TEMPLATES[primaryWorkflow] : undefined;+ const liveToolNames = new Set(+ brain.domains.flatMap((domain) => domain.tools.map((tool) => tool.name)),+ );return {content: [{@@ -480,7 +653,8 @@ const guidanceRecommend: MCPTool = {area: r.area,name: r.capability.name,description: r.capability.description,- tools: r.capability.tools,+ tools: r.capability.tools.filter((name) => liveToolNames.has(name)),+ unregisteredLegacyToolRefs: r.capability.tools.filter((name) => !liveToolNames.has(name)),agents: r.capability.agents,skills: r.capability.skills,})),@@ -490,6 +664,7 @@ const guidanceRecommend: MCPTool = {agents: template.agents,topology: template.topology,} : undefined,+ capabilityBrain: capabilityRecommendation,}, null, 2),}],};@@ -504,7 +679,7 @@ const guidanceDiscover: MCPTool = {properties: {type: {type: 'string',- enum: ['agents', 'skills', 'all'],+ enum: ['agents', 'skills', 'plugins', 'packages', 'all'],description: 'What to discover. Default: all.',},},@@ -524,6 +699,21 @@ const guidanceDiscover: MCPTool = {result.skills = { count: skills.length, names: skills };}+ if (type === 'plugins' || type === 'all') {+ const plugins = discoverPlugins();+ result.plugins = { count: plugins.length, entries: plugins };+ }++ if (type === 'packages' || type === 'all') {+ const packages = discoverPackages();+ result.packages = { count: packages.length, entries: packages };+ }++ result.capabilityBrain = {+ registeredTools: getCapabilityBrain().coverage.registeredToolCount,+ note: 'Filesystem discovery reports installed artifacts; it does not prove configuration, health, or authorization.',+ };+return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };},};@@ -668,10 +858,159 @@ const guidanceQuickRef: MCPTool = {},};+const guidanceBrain: MCPTool = {+ name: 'guidance_brain',+ description: 'Query Ruflo’s live capability brain. Covers every registered MCP tool, separates registration from configuration/reachability/health/authorization, recommends capabilities for a task, and returns the validated implementation loop.',+ inputSchema: {+ type: 'object',+ properties: {+ mode: {+ type: 'string',+ enum: ['overview', 'capabilities', 'coverage', 'ecosystem', 'recommend', 'implementation-loop'],+ description: 'Brain view. Default: overview.',+ },+ task: {+ type: 'string',+ description: 'Required for recommend mode.',+ },+ domain: {+ type: 'string',+ description: 'Optional capability domain filter for capabilities mode.',+ },+ },+ },+ handler: async (params: Record<string, unknown>) => {+ const mode = (params.mode as string | undefined) ?? 'overview';+ const task = params.task as string | undefined;+ const domain = params.domain as string | undefined;+ const brain = getCapabilityBrain();++ if (domain) {+ const validation = validateIdentifier(domain, 'domain');+ if (!validation.valid) {+ return {+ content: [{ type: 'text', text: JSON.stringify({ error: validation.error }, null, 2) }],+ isError: true,+ };+ }+ }++ let result: unknown;+ switch (mode) {+ case 'overview':+ result = {+ schemaVersion: brain.schemaVersion,+ generatedAt: brain.generatedAt,+ truthModel: brain.truthModel,+ coverage: brain.coverage,+ domainCount: brain.domains.length,+ cliCommandCount: brain.cliCommands.length,+ cliCommands: brain.cliCommands,+ registeredDomains: brain.domains+ .filter((entry) => entry.health.registered)+ .map((entry) => ({+ id: entry.id,+ name: entry.name,+ toolCount: entry.tools.length,+ maturity: entry.maturity,+ authority: entry.authority,+ risk: entry.risk,+ health: entry.health,+ })),+ implementationLoop: brain.implementationLoop.map((step) => step.id),+ };+ break;+ case 'capabilities': {+ const capabilities = domain+ ? brain.domains.filter((entry) => entry.id === domain)+ : brain.domains;+ if (domain && capabilities.length === 0) {+ return {+ content: [{+ type: 'text',+ text: JSON.stringify({+ error: `Unknown capability domain: ${domain}`,+ available: brain.domains.map((entry) => entry.id),+ }, null, 2),+ }],+ isError: true,+ };+ }+ result = { schemaVersion: brain.schemaVersion, truthModel: brain.truthModel, capabilities };+ break;+ }+ case 'coverage':+ result = {+ schemaVersion: brain.schemaVersion,+ coverage: brain.coverage,+ assignments: brain.domains.map((entry) => ({+ domain: entry.id,+ tools: entry.tools.map((tool) => tool.name),+ })),+ };+ break;+ case 'ecosystem': {+ const agents = discoverAgents();+ const skills = discoverSkills();+ const plugins = discoverPlugins();+ const packages = discoverPackages();+ result = {+ schemaVersion: brain.schemaVersion,+ agents: { count: agents.length, names: agents },+ skills: { count: skills.length, names: skills },+ plugins: { count: plugins.length, entries: plugins },+ packages: { count: packages.length, entries: packages },+ cliCommands: { count: brain.cliCommands.length, names: brain.cliCommands },+ availabilityNote: 'Installed or catalogued artifacts are not necessarily configured, reachable, healthy, or authorized.',+ };+ break;+ }+ case 'recommend': {+ const validation = validateText(task, 'task');+ if (!validation.valid) {+ return {+ content: [{ type: 'text', text: JSON.stringify({ error: validation.error }, null, 2) }],+ isError: true,+ };+ }+ result = recommendCapabilities(brain, task!);+ break;+ }+ case 'implementation-loop':+ result = {+ schemaVersion: brain.schemaVersion,+ steps: brain.implementationLoop,+ invariants: [+ 'Recall precedes implementation.',+ 'Testing and validation precede optimization.',+ 'Benchmarks compare a source-bound candidate with a source-bound baseline.',+ 'Learning and optimization cannot authorize promotion.',+ 'Publishing requires separate authorization and immutable artifact evidence.',+ ],+ };+ break;+ default:+ return {+ content: [{+ type: 'text',+ text: JSON.stringify({+ error: `Unknown mode: ${mode}`,+ available: ['overview', 'capabilities', 'coverage', 'ecosystem', 'recommend', 'implementation-loop'],+ }, null, 2),+ }],+ isError: true,+ };+ }++ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };+ },+};+/*** All guidance tools*/export const guidanceTools: MCPTool[] = [+ guidanceBrain,guidanceCapabilities,guidanceRecommend,guidanceDiscover,diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.tsindex 163d17addf..653d4b63d0 100644--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts@@ -24,7 +24,31 @@ export { claimsTools } from './claims-tools.js';export { policyTools } from './policy-tools.js';export { wasmAgentTools } from './wasm-agent-tools.js';export { ruvllmWasmTools } from './ruvllm-tools.js';-export { guidanceTools } from './guidance-tools.js';+export {+ configureGuidanceToolProvider,+ guidanceTools,+} from './guidance-tools.js';+export {+ buildCapabilityBrain,+ CAPABILITY_DOMAINS,+ classifyCapabilityTool,+ IMPLEMENTATION_LOOP,+ recommendCapabilities,+ RUFLO_CLI_COMMANDS,+} from './capability-brain.js';+export type {+ AvailabilityState,+ CapabilityAuthority,+ CapabilityBrain,+ CapabilityDomain,+ CapabilityDomainDefinition,+ CapabilityHealth,+ CapabilityMaturity,+ CapabilityRecommendation,+ CapabilityRisk,+ CapabilityToolMetadata,+ ImplementationLoopStep,+} from './capability-brain.js';export { autopilotTools } from './autopilot-tools.js';// ADR-150 — MetaHarness MCP tools (score / genome / mcp-scan / threat-model / oia-audit)export { metaharnessTools } from './metaharness-tools.js';diff --git a/v3/@claude-flow/codex/AGENTS.md b/v3/@claude-flow/codex/AGENTS.mdindex fc3f6ce7e5..d203469f1c 100644--- a/v3/@claude-flow/codex/AGENTS.md+++ b/v3/@claude-flow/codex/AGENTS.md@@ -63,7 +63,11 @@ This project uses hierarchical swarm coordination for complex tasks:### Policy-Governed Concurrent Execution- Ruflo coordinates and records policy decisions; Codex workers execute.-- Search AgentDB before planning and store validated patterns after success.+- Use `guidance_brain` for live capability routing; registration is distinct+ from configuration, reachability, health, and authorization.+- Follow the complete loop: recall, inspect, route, plan, execute, test,+ validate, benchmark, optimize, receipt, handoff, then authorized publish.+- Search AgentDB before planning and store only validated patterns after success.- Use bounded fanout only for independent tasks.- Every writing worker gets a unique git worktree and a reduced capabilityenvelope. Never place two writers in one worktree.@@ -78,6 +82,19 @@ This project uses hierarchical swarm coordination for complex tasks:authorization.- Existing projects start in ADR-324 `legacy` mode, may rehearse in `observe`,and opt into `enforce` after reviewing receipts.+- When tracked repository instructions define a local harness, assign the+ isolated worktree first, then register a session, inspect claims, acquire+ exact paths/resources/ports, renew leases, check acknowledged inbox messages, and+ release ownership on handoff or exit.+- A repository lease coordinates ownership; it does not grant authorization.+ Protected work still requires the ADR-324/325 capability and current fencing+ epoch.+- In-memory reference adapters are not distributed, restart-durable release+ authorities.+- Heartbeats and lease expiry establish liveness; PIDs are diagnostic only.+- `HEAD` alone is not an exact source-state identity in a dirty worktree.+ Release receipts bind a clean commit or an immutable snapshot of tracked and+ untracked changes.### Available Skillsdiff --git a/v3/@claude-flow/codex/package.json b/v3/@claude-flow/codex/package.jsonindex 046ae9ceef..f99497d359 100644--- a/v3/@claude-flow/codex/package.json+++ b/v3/@claude-flow/codex/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/codex",- "version": "3.0.2",+ "version": "3.0.3","description": "Codex CLI integration for Ruflo (claude-flow) - OpenAI Codex platform adapter","type": "module","main": "./dist/index.js",@@ -44,6 +44,11 @@"types": "./dist/worktrees/index.d.ts","import": "./dist/worktrees/index.js","require": "./dist/worktrees/index.js"+ },+ "./harness": {+ "types": "./dist/harness/index.d.ts",+ "import": "./dist/harness/index.js",+ "require": "./dist/harness/index.js"}},"files": [diff --git a/v3/@claude-flow/codex/src/generators/agents-md.ts b/v3/@claude-flow/codex/src/generators/agents-md.tsindex 9a2c9a78bd..6e4c5fd04b 100644--- a/v3/@claude-flow/codex/src/generators/agents-md.ts+++ b/v3/@claude-flow/codex/src/generators/agents-md.ts@@ -13,13 +13,23 @@ function concurrentRufloWorkflow(): string {Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation.-1. Search AgentDB memory for relevant patterns and constraints.-2. Initialize one bounded hierarchical Ruflo swarm and register the task.-3. Split only independent work into concurrent Codex workers.-4. Give every writing worker a distinct git worktree and a reduced capability envelope.-5. Keep dependency/lockfiles under one designated owner.-6. Have the parent integrate committed handoffs in dependency order and run scoped, then full verification.-7. Store the successful pattern and policy receipt after validation.+Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can+benefit from Ruflo-specific capabilities. Its live registry is authoritative+for tool presence; registration alone does not prove configuration,+reachability, health, or authorization.++1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints.+2. **Inspect** — read source, runtime, dependency, policy, and health state.+3. **Route** — choose the smallest capable topology, agents, skills, and tools.+4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation.+5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination.+6. **Test** — run focused tests, regression tests, and failure-path checks.+7. **Validate** — check types, security, policy, compatibility, and artifact integrity.+8. **Benchmark** — compare a source-bound candidate with a source-bound baseline.+9. **Optimize** — improve measured bottlenecks without weakening the safety envelope.+10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs.+11. **Handoff** — reconcile concurrent work and disclose unresolved limitations.+12. **Publish** — only an independently authorized release gate may publish immutable artifacts.### Concurrency and authority invariants@@ -31,6 +41,27 @@ Ruflo is the coordination ledger and policy decision point; Codex workers execut- Only the integration agent changes shared manifests or lockfiles.- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation.- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval.++### Repository harness adapter++When tracked repository instructions define a local collaboration harness:++1. Assign the isolated worktree before starting a writing session.+2. Start or register the session, inspect current claims, and acquire only the+ exact paths, resources, and development ports needed for the task.+3. Renew leases during long work, check acknowledged inbox messages at integration+ boundaries, and release claims when handing off or ending.+4. Record focused and integration evidence against the exact source state,+ then let the designated integration owner decide release.++A repository lease coordinates ownership; it does not grant authorization.+In-memory reference adapters demonstrate semantics but are not distributed,+restart-durable release authorities.+The worker still needs the current ADR-324/325 action capability and fencing+epoch for every protected side effect. Heartbeat and lease expiry establish+liveness; a PID is diagnostic only. HEAD alone is not an exact source-state+identity when tracked or untracked changes exist, so a release receipt must+bind a clean commit or an immutable snapshot including those changes.`;}diff --git a/v3/@claude-flow/codex/src/harness/build-evidence.ts b/v3/@claude-flow/codex/src/harness/build-evidence.tsnew file mode 100644index 0000000000..36bd572ef4--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/build-evidence.ts@@ -0,0 +1,196 @@+import { createHash } from 'node:crypto';+import { lstatSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';+import { isAbsolute, relative, resolve, sep } from 'node:path';+import {+ canonicalJson,+ captureRepositorySourceState,+ type ExactSourceState,+} from './repository-state.js';+import { portableCaseFold } from './portable-case-fold.js';++const DIGEST = /^sha256:[0-9a-f]{64}$/;++export interface DeclaredBuildInput {+ name: string;+ /** Repository-relative declaration; it may name an ignored generated input. */+ path: string;+ digest: string;+ bytes: number;+}++export interface DeclaredToolchain {+ name: string;+ version: string;+ /** Digest of the executable, image, lock, or immutable toolchain manifest. */+ digest: string;+}++export interface BuildInputDeclaration {+ name: string;+ path: string;+}++export interface ToolchainDeclaration {+ name: string;+ version: string;+ /** Local executable or immutable manifest to hash; not embedded in evidence. */+ path: string;+}++export interface BuildEvidence {+ contractVersion: 1;+ assurance: 'declared-unsigned';+ sourceStateId: string;+ buildInputs: readonly DeclaredBuildInput[];+ toolchains: readonly DeclaredToolchain[];+ evidenceDigest: string;+}++function compare(left: string, right: string): number {+ return left < right ? -1 : left > right ? 1 : 0;+}++function requireText(value: string, label: string): string {+ const result = value.trim();+ if (!result) throw new Error(`${label} must be non-empty`);+ return result;+}++function requireDigest(value: string, label: string): string {+ if (!DIGEST.test(value)) throw new Error(`${label} must be a canonical sha256 digest`);+ return value;+}++function normalizePath(value: string): string {+ const path = requireText(value, 'build input path');+ if (+ path.includes('\\')+ || path.startsWith('/')+ || path.startsWith('-')+ || path !== path.normalize('NFC')+ || path.split('/').some((part) => !part || part === '.' || part === '..')+ ) {+ throw new Error(`unsafe build input path: ${value}`);+ }+ return path;+}++function sha256(value: string): string {+ return `sha256:${createHash('sha256').update(value).digest('hex')}`;+}++function digestPath(path: string, followSymlink: boolean): { digest: string; bytes: number } {+ const resolved = followSymlink ? realpathSync(path) : path;+ const stat = lstatSync(resolved);+ const content = stat.isSymbolicLink()+ ? Buffer.from(readlinkSync(resolved), 'utf8')+ : stat.isFile()+ ? readFileSync(resolved)+ : undefined;+ if (!content) throw new Error(`build evidence path is not a file or symlink: ${path}`);+ return {+ digest: `sha256:${createHash('sha256').update(content).digest('hex')}`,+ bytes: content.byteLength,+ };+}++/**+ * Bind explicitly declared non-Git inputs and toolchains to one Git-visible+ * source state. This does not claim completeness; policy decides which+ * declarations are required for a release profile.+ */+export function createBuildEvidence(+ sourceState: ExactSourceState,+ buildInputs: readonly DeclaredBuildInput[],+ toolchains: readonly DeclaredToolchain[],+): BuildEvidence {+ const inputs = buildInputs.map((input) => ({+ name: requireText(input.name, 'build input name'),+ path: normalizePath(input.path),+ digest: requireDigest(input.digest, 'build input digest'),+ bytes: input.bytes,+ })).sort((left, right) => compare(left.path, right.path) || compare(left.name, right.name));+ const tools = toolchains.map((toolchain) => ({+ name: requireText(toolchain.name, 'toolchain name'),+ version: requireText(toolchain.version, 'toolchain version'),+ digest: requireDigest(toolchain.digest, 'toolchain digest'),+ })).sort((left, right) => compare(left.name, right.name) || compare(left.version, right.version));++ if (inputs.some(({ bytes }) => !Number.isSafeInteger(bytes) || bytes < 0)) {+ throw new Error('build input bytes must be a non-negative safe integer');+ }+ const inputKeys = inputs.map(({ name, path }) => `${name}\0${path}`);+ if (new Set(inputKeys).size !== inputKeys.length) throw new Error('duplicate declared build input');+ const foldedPaths = inputs.map(({ path }) => portableCaseFold(path));+ if (new Set(foldedPaths).size !== foldedPaths.length) {+ throw new Error('case-fold collision in declared build inputs');+ }+ const toolKeys = tools.map(({ name, version }) => `${name}\0${version}`);+ if (new Set(toolKeys).size !== toolKeys.length) throw new Error('duplicate declared toolchain');++ const body = {+ contractVersion: 1 as const,+ assurance: 'declared-unsigned' as const,+ sourceStateId: requireDigest(sourceState.sourceStateId, 'source state id'),+ buildInputs: inputs,+ toolchains: tools,+ };+ return { ...body, evidenceDigest: sha256(canonicalJson(body)) };+}++/**+ * Recompute declared evidence from local bytes. It does not prove the+ * declaration set is complete and does not sign or authorize a release.+ */+export function captureBuildEvidence(+ repoPath: string,+ sourceState: ExactSourceState,+ buildInputs: readonly BuildInputDeclaration[],+ toolchains: readonly ToolchainDeclaration[],+): BuildEvidence {+ const repoRoot = realpathSync(resolve(repoPath));+ if (captureRepositorySourceState(repoRoot).sourceStateId !== sourceState.sourceStateId) {+ throw new Error('Git-visible source state does not match the build evidence request');+ }+ const inputs = buildInputs.map((declaration): DeclaredBuildInput => {+ const path = normalizePath(declaration.path);+ const absolute = resolve(repoRoot, path);+ const real = realpathSync(absolute);+ const rel = relative(repoRoot, real);+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {+ throw new Error(`build input escapes repository: ${path}`);+ }+ return { name: declaration.name, path, ...digestPath(real, true) };+ });+ const tools = toolchains.map((declaration): DeclaredToolchain => ({+ name: declaration.name,+ version: declaration.version,+ digest: digestPath(+ isAbsolute(declaration.path) ? declaration.path : resolve(repoRoot, declaration.path),+ true,+ ).digest,+ }));+ return createBuildEvidence(sourceState, inputs, tools);+}++export function recomputeBuildEvidence(+ repoPath: string,+ expected: BuildEvidence,+ toolchains: readonly ToolchainDeclaration[],+): BuildEvidence {+ const sourceState = captureRepositorySourceState(repoPath);+ if (sourceState.sourceStateId !== expected.sourceStateId) {+ throw new Error('Git-visible source state changed before build evidence recomputation');+ }+ return captureBuildEvidence(+ repoPath,+ sourceState,+ expected.buildInputs.map(({ name, path }) => ({ name, path })),+ toolchains,+ );+}++export function buildEvidenceMatches(expected: BuildEvidence, actual: BuildEvidence): boolean {+ return expected.evidenceDigest === actual.evidenceDigest+ && expected.sourceStateId === actual.sourceStateId;+}diff --git a/v3/@claude-flow/codex/src/harness/contract.ts b/v3/@claude-flow/codex/src/harness/contract.tsnew file mode 100644index 0000000000..5b9d7a48cf--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/contract.ts@@ -0,0 +1,216 @@+/**+ * Advisory repository-harness contract.+ *+ * Repository harnesses coordinate local ownership and collect evidence. They do+ * not grant Ruflo policy capabilities. Existing harnesses can implement only+ * `describe`; omitted operations remain unavailable and the descriptor+ * normalizes to observe-only compatibility mode.+ */++import type { ExactSourceState } from './repository-state.js';+import type { BuildEvidence } from './build-evidence.js';++export type HarnessMode = 'observe' | 'enforce';+export type HarnessCapability =+ | 'sessions'+ | 'leases'+ | 'lease-fencing'+ | 'messages'+ | 'message-acknowledgement'+ | 'run-evidence'+ | 'exact-source-state'+ | 'release-decisions';++interface HarnessDescriptorBase {+ contractVersion: 1;+ harnessId: string;+}++export interface InMemoryReferenceHarnessDescriptor extends HarnessDescriptorBase {+ mode: 'observe';+ capabilities: readonly Exclude<HarnessCapability, 'release-decisions'>[];+ advisory: true;+ assurance: 'in-memory-reference';+}++export interface ExternalAuthorityHarnessDescriptor extends HarnessDescriptorBase {+ mode: HarnessMode;+ capabilities: readonly HarnessCapability[];+ advisory: false;+ assurance: 'external-authority';+}++export type HarnessDescriptor =+ | InMemoryReferenceHarnessDescriptor+ | ExternalAuthorityHarnessDescriptor;++/** Shape accepted from pre-contract local harnesses. */+export interface LegacyHarnessDescriptor {+ harnessId?: string;+ name?: string;+ mode?: HarnessMode;+ capabilities?: readonly string[];+}++export interface StartSessionRequest {+ sessionId: string;+ workloadId: string;+ repositoryId: string;+ worktreeId: string;+ readOnly: boolean;+}++export interface HarnessSession {+ sessionId: string;+ workloadId: string;+ repositoryId: string;+ worktreeId: string;+ startedAt: string;+}++export interface LeaseRequest {+ sessionId: string;+ repositoryId: string;+ worktreeId: string;+ kind: 'path' | 'resource';+ scopes: readonly string[];+ ttlMs: number;+}++export interface FencedLease {+ leaseId: string;+ repositoryId: string;+ sessionId: string;+ workloadId: string;+ worktreeId: string;+ kind: 'path' | 'resource';+ scopes: readonly string[];+ /** Decimal strings avoid losing 64-bit epochs when receipts cross JSON. */+ epoch: string;+ version: string;+ issuedAt: string;+ expiresAt: string;+ advisory: boolean;+}++export interface HarnessMessage {+ messageId: string;+ issuer: string;+ audience: string;+ correlationId?: string;+ causationId?: string;+ sequence: string;+ expiresAt?: string;+ contentDigest: string;+ content: unknown;+}++export interface MessageReceipt {+ messageId: string;+ acceptedAt: string;+ duplicate: boolean;+}++export interface RunEvidence {+ executionId: string;+ sessionId: string;+ workloadId: string;+ sourceState: ExactSourceState;+ /** Optional for legacy/debug runs; release policy may require it. */+ buildEvidence?: BuildEvidence;+ commandDigest: string;+ scope: string;+ profile: 'focused' | 'integration' | 'release';+ startedAt: string;+ completedAt: string;+ exitCode: number;+ evidenceDigest: string;+ policyReceiptId?: string;+ leaseEpochs?: Readonly<Record<string, string>>;+}++export interface RunReceipt extends RunEvidence {+ receiptId: string;+ recordedAt: string;+}++export interface ReleaseRequest {+ repositoryId: string;+ sourceStateId: string;+ artifactDigest: string;+ runReceiptIds: readonly string[];+ /** Optional for compatibility; enforce-mode release policy may require it. */+ buildEvidence?: BuildEvidence;+ capabilityId?: string;+}++export interface ReleaseDecision {+ allowed: boolean;+ dryRun: boolean;+ reason: string;+ policyReceiptId?: string;+}++/**+ * Progressive adapter surface. Optional methods preserve compatibility with+ * local harnesses that predate sessions, fencing, durable messages, or exact+ * source-state receipts. Callers must feature-detect every optional operation.+ */+export interface RepositoryHarnessAdapter {+ describe(): Promise<HarnessDescriptor | LegacyHarnessDescriptor>;+ start?(request: StartSessionRequest): Promise<HarnessSession>;+ acquire?(request: LeaseRequest): Promise<FencedLease>;+ renew?(lease: FencedLease): Promise<FencedLease>;+ release?(lease: FencedLease): Promise<void>;+ send?(message: HarnessMessage): Promise<MessageReceipt>;+ receive?(cursor?: string): AsyncIterable<HarnessMessage>;+ acknowledge?(messageId: string): Promise<void>;+ recordRun?(run: RunEvidence): Promise<RunReceipt>;+ authorizeRelease?(request: ReleaseRequest): Promise<ReleaseDecision>;+ end?(sessionId: string): Promise<void>;+}++const CAPABILITIES = new Set<HarnessCapability>([+ 'sessions',+ 'leases',+ 'lease-fencing',+ 'messages',+ 'message-acknowledgement',+ 'run-evidence',+ 'exact-source-state',+ 'release-decisions',+]);++/**+ * Convert an older descriptor to the safe v1 reference baseline.+ *+ * Unknown and authority-bearing capabilities are ignored. A legacy descriptor+ * can never self-assert enforce or release authority through this compatibility+ * function. A separately verified external adapter is required for that.+ */+export function normalizeHarnessDescriptor(+ input: HarnessDescriptor | LegacyHarnessDescriptor,+): InMemoryReferenceHarnessDescriptor {+ const harnessId = input.harnessId ?? ('name' in input ? input.name : undefined);+ if (typeof harnessId !== 'string' || harnessId.trim().length === 0) {+ throw new Error('repository harness descriptor requires a non-empty harnessId');+ }++ const requested = Array.isArray(input.capabilities) ? input.capabilities : [];+ const capabilities: Array<Exclude<HarnessCapability, 'release-decisions'>> = [...new Set(+ requested.filter((value): value is HarnessCapability => (+ CAPABILITIES.has(value as HarnessCapability)+ && value !== 'release-decisions'+ )),+ )] as Array<Exclude<HarnessCapability, 'release-decisions'>>;+ capabilities.sort();++ return {+ contractVersion: 1,+ harnessId: harnessId.trim(),+ mode: 'observe',+ capabilities,+ advisory: true,+ assurance: 'in-memory-reference',+ };+}diff --git a/v3/@claude-flow/codex/src/harness/in-memory-fenced-lease-reference.ts b/v3/@claude-flow/codex/src/harness/in-memory-fenced-lease-reference.tsnew file mode 100644index 0000000000..b0ac9b44e3--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/in-memory-fenced-lease-reference.ts@@ -0,0 +1,205 @@+import { randomUUID } from 'node:crypto';+import type { FencedLease, LeaseRequest } from './contract.js';+import { portableCaseFold } from './portable-case-fold.js';+import { parseCanonicalUnsigned } from './unsigned-integer.js';++export interface FencedLeaseRequest extends LeaseRequest {+ workloadId: string;+}++export type InMemoryFenceRefusal =+ | 'invalid-request'+ | 'scope-conflict'+ | 'stale-fence'+ | 'expired-fence'+ | 'unknown-lease';++export class InMemoryFenceReferenceError extends Error {+ constructor(readonly reason: InMemoryFenceRefusal, detail: string) {+ super(detail);+ }+}++interface StoredLease {+ lease: FencedLease;+ expiresAtMs: number;+}++function compare(left: string, right: string): number {+ return left < right ? -1 : left > right ? 1 : 0;+}++function text(value: string, label: string): string {+ const result = value.trim();+ if (!result) throw new InMemoryFenceReferenceError('invalid-request', `${label} must be non-empty`);+ return result;+}++function normalizeScope(kind: LeaseRequest['kind'], value: string): string {+ const scope = text(value, 'lease scope');+ if (scope.startsWith('-') || scope.includes('\\') || scope !== scope.normalize('NFC')) {+ throw new InMemoryFenceReferenceError('invalid-request', `unsafe lease scope: ${value}`);+ }+ if (kind === 'resource') {+ if (scope.includes('/') || scope === '.' || scope === '..') {+ throw new InMemoryFenceReferenceError('invalid-request', `invalid named resource: ${value}`);+ }+ return scope;+ }+ if (+ scope.startsWith('/')+ || scope.split('/').some((part) => !part || part === '.' || part === '..')+ ) {+ throw new InMemoryFenceReferenceError('invalid-request', `invalid path scope: ${value}`);+ }+ return scope;+}++function overlaps(kind: LeaseRequest['kind'], left: string, right: string): boolean {+ if (kind === 'resource') return left === right;+ const foldedLeft = portableCaseFold(left);+ const foldedRight = portableCaseFold(right);+ return foldedLeft === foldedRight+ || foldedLeft.startsWith(`${foldedRight}/`)+ || foldedRight.startsWith(`${foldedLeft}/`);+}++function sameStrings(left: readonly string[], right: readonly string[]): boolean {+ return left.length === right.length && left.every((value, index) => value === right[index]);+}++function copyLease(lease: FencedLease): FencedLease {+ return { ...lease, scopes: [...lease.scopes] };+}++/**+ * Unsigned, non-durable, single-process conformance reference.+ *+ * JavaScript executes each method without an await boundary, so compare,+ * validate, and mutate form one atomic critical section. Distributed adapters+ * must provide the same semantics with a CP store. This class cannot satisfy an+ * enforce-mode policy decision or authorize release/external side effects.+ */+export class InMemoryFencedLeaseReference {+ /** This model is local, unsigned, and never an enforce-mode policy authority. */+ readonly referenceOnly = true;+ private readonly leases = new Map<string, StoredLease>();+ private readonly repositoryEpoch = new Map<string, bigint>();++ constructor(private readonly now: () => number = Date.now) {}++ acquire(request: FencedLeaseRequest): FencedLease {+ const repositoryId = text(request.repositoryId, 'repositoryId');+ const scopes = [...new Set(request.scopes.map((scope) => normalizeScope(request.kind, scope)))]+ .sort(compare);+ if (!scopes.length || !Number.isSafeInteger(request.ttlMs) || request.ttlMs <= 0) {+ throw new InMemoryFenceReferenceError('invalid-request', 'lease requires scopes and a positive safe ttlMs');+ }+ const now = this.now();+ this.pruneExpired(now);+ for (const stored of this.leases.values()) {+ const current = stored.lease;+ if (current.repositoryId !== repositoryId || current.kind !== request.kind) continue;+ if (current.scopes.some((held) => scopes.some((wanted) => overlaps(request.kind, held, wanted)))) {+ throw new InMemoryFenceReferenceError(+ 'scope-conflict',+ `scope conflicts with active lease ${current.leaseId}`,+ );+ }+ }++ const epoch = (this.repositoryEpoch.get(repositoryId) ?? 0n) + 1n;+ this.repositoryEpoch.set(repositoryId, epoch);+ const expiresAtMs = now + request.ttlMs;+ if (!Number.isSafeInteger(expiresAtMs)) {+ throw new InMemoryFenceReferenceError('invalid-request', 'lease expiry exceeds safe timestamp range');+ }+ const lease: FencedLease = {+ leaseId: `lease-${randomUUID()}`,+ repositoryId,+ sessionId: text(request.sessionId, 'sessionId'),+ workloadId: text(request.workloadId, 'workloadId'),+ worktreeId: text(request.worktreeId, 'worktreeId'),+ kind: request.kind,+ scopes,+ epoch: epoch.toString(),+ version: '1',+ issuedAt: new Date(now).toISOString(),+ expiresAt: new Date(expiresAtMs).toISOString(),+ advisory: true,+ };+ this.leases.set(lease.leaseId, { lease, expiresAtMs });+ return copyLease(lease);+ }++ renew(presented: FencedLease, ttlMs: number): FencedLease {+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {+ throw new InMemoryFenceReferenceError('invalid-request', 'renewal requires a positive safe ttlMs');+ }+ const stored = this.assertStoredFence(presented);+ const now = this.now();+ if (stored.expiresAtMs <= now) {+ this.leases.delete(presented.leaseId);+ throw new InMemoryFenceReferenceError('expired-fence', `lease ${presented.leaseId} expired`);+ }+ const expiresAtMs = now + ttlMs;+ if (!Number.isSafeInteger(expiresAtMs)) {+ throw new InMemoryFenceReferenceError('invalid-request', 'lease expiry exceeds safe timestamp range');+ }+ const lease: FencedLease = {+ ...stored.lease,+ version: (parseCanonicalUnsigned(stored.lease.version, 'lease version') + 1n).toString(),+ expiresAt: new Date(expiresAtMs).toISOString(),+ scopes: [...stored.lease.scopes],+ };+ this.leases.set(lease.leaseId, { lease, expiresAtMs });+ return copyLease(lease);+ }++ release(presented: FencedLease): void {+ this.assertCurrentFence(presented);+ this.leases.delete(presented.leaseId);+ }++ assertCurrentFence(presented: FencedLease): void {+ const stored = this.assertStoredFence(presented);+ if (stored.expiresAtMs <= this.now()) {+ this.leases.delete(presented.leaseId);+ throw new InMemoryFenceReferenceError('expired-fence', `lease ${presented.leaseId} expired`);+ }+ }++ current(repositoryId?: string): FencedLease[] {+ this.pruneExpired(this.now());+ return [...this.leases.values()]+ .map(({ lease }) => lease)+ .filter((lease) => repositoryId === undefined || lease.repositoryId === repositoryId)+ .sort((left, right) => compare(left.leaseId, right.leaseId))+ .map(copyLease);+ }++ private assertStoredFence(presented: FencedLease): StoredLease {+ const stored = this.leases.get(presented.leaseId);+ if (!stored) throw new InMemoryFenceReferenceError('unknown-lease', `unknown lease ${presented.leaseId}`);+ const current = stored.lease;+ if (+ current.repositoryId !== presented.repositoryId+ || current.sessionId !== presented.sessionId+ || current.workloadId !== presented.workloadId+ || current.worktreeId !== presented.worktreeId+ || current.kind !== presented.kind+ || !sameStrings(current.scopes, presented.scopes)+ || current.epoch !== presented.epoch+ || current.version !== presented.version+ ) {+ throw new InMemoryFenceReferenceError('stale-fence', `stale or altered fence ${presented.leaseId}`);+ }+ return stored;+ }++ private pruneExpired(now: number): void {+ for (const [leaseId, stored] of this.leases) {+ if (stored.expiresAtMs <= now) this.leases.delete(leaseId);+ }+ }+}diff --git a/v3/@claude-flow/codex/src/harness/in-memory-inbox-reference.ts b/v3/@claude-flow/codex/src/harness/in-memory-inbox-reference.tsnew file mode 100644index 0000000000..a71479bbfa--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/in-memory-inbox-reference.ts@@ -0,0 +1,174 @@+import { createHash } from 'node:crypto';+import type { HarnessMessage, MessageReceipt } from './contract.js';+import { canonicalJson } from './repository-state.js';+import { parseCanonicalUnsigned } from './unsigned-integer.js';++export interface InMemoryInboxRecord {+ cursor: string;+ message: HarnessMessage;+ receivedAt: string;+ acknowledgedAt?: string;+}++export interface InMemoryQuarantinedMessage {+ issuer: string;+ messageId: string;+ reason: 'content-digest-mismatch' | 'message-id-content-conflict';+ quarantinedAt: string;+}++function sha256(value: string): string {+ return `sha256:${createHash('sha256').update(value).digest('hex')}`;+}++function clone<T>(value: T): T {+ return structuredClone(value);+}++export function harnessMessageContentDigest(content: unknown): string {+ return sha256(canonicalJson(content));+}++function lengthFrame(values: readonly string[]): string {+ return values.map((value) => `${Buffer.byteLength(value, 'utf8')}:${value}`).join('|');+}++/** Collision-safe local map key; the unhashed material is byte-length framed. */+export function inMemoryInboxIdentityKey(issuer: string, messageId: string): string {+ return sha256(lengthFrame([issuer, messageId]));+}++/**+ * Unsigned, non-durable in-memory model of inbox semantics.+ *+ * It retains unacknowledged records, resumes by monotonic cursor, deduplicates+ * exact retries, and quarantines an issuer reusing a message ID with different+ * content. Process exit loses all state; this class is never an enforce-mode+ * transport or authority. Durable adapters may use it only as a conformance+ * reference.+ */+export class InMemoryInboxReference {+ readonly referenceOnly = true;+ private readonly records: InMemoryInboxRecord[] = [];+ private readonly byIdentity = new Map<string, {+ issuer: string;+ messageId: string;+ envelopeDigest: string;+ record: InMemoryInboxRecord;+ }>();+ private readonly quarantined: InMemoryQuarantinedMessage[] = [];+ private nextCursor = 1n;++ constructor(private readonly now: () => number = Date.now) {}++ send(message: HarnessMessage): MessageReceipt {+ if (!message.messageId.trim() || !message.issuer.trim() || !message.audience.trim()) {+ throw new Error('message ID, issuer, and audience are required');+ }+ const identity = inMemoryInboxIdentityKey(message.issuer, message.messageId);+ const receivedAt = new Date(this.now()).toISOString();+ let suppliedDigest: string;+ try {+ suppliedDigest = harnessMessageContentDigest(message.content);+ } catch {+ this.quarantine(message, 'content-digest-mismatch', receivedAt);+ throw new Error('message content is not canonical JSON');+ }+ if (suppliedDigest !== message.contentDigest) {+ this.quarantine(message, 'content-digest-mismatch', receivedAt);+ throw new Error('message contentDigest does not match canonical content');+ }+ try {+ parseCanonicalUnsigned(message.sequence, 'message sequence');+ } catch {+ throw new Error('message sequence must be a canonical unsigned decimal integer');+ }+ if (message.expiresAt !== undefined && !Number.isFinite(Date.parse(message.expiresAt))) {+ throw new Error('message expiresAt must be an ISO timestamp');+ }++ const envelopeDigest = sha256(canonicalJson(message));+ const prior = this.byIdentity.get(identity);+ if (prior) {+ if (prior.issuer !== message.issuer || prior.messageId !== message.messageId) {+ throw new Error('inbox identity hash collision');+ }+ if (prior.envelopeDigest !== envelopeDigest) {+ this.quarantine(message, 'message-id-content-conflict', receivedAt);+ throw new Error('message ID was reused with different content');+ }+ return { messageId: message.messageId, acceptedAt: prior.record.receivedAt, duplicate: true };+ }++ const record: InMemoryInboxRecord = {+ cursor: (this.nextCursor++).toString(),+ message: clone(message),+ receivedAt,+ };+ this.records.push(record);+ this.byIdentity.set(identity, {+ issuer: message.issuer,+ messageId: message.messageId,+ envelopeDigest,+ record,+ });+ return { messageId: message.messageId, acceptedAt: receivedAt, duplicate: false };+ }++ async *receive(audience: string, cursor = '0'): AsyncIterable<HarnessMessage> {+ const after = this.parseCursor(cursor);+ const now = this.now();+ for (const record of this.records) {+ if (+ BigInt(record.cursor) > after+ && record.message.audience === audience+ && (record.message.expiresAt === undefined || Date.parse(record.message.expiresAt) > now)+ ) {+ yield clone(record.message);+ }+ }+ }++ acknowledge(audience: string, messageId: string, issuer?: string): void {+ const matches = this.records.filter(+ (candidate) => candidate.message.audience === audience+ && candidate.message.messageId === messageId+ && (issuer === undefined || candidate.message.issuer === issuer),+ );+ if (!matches.length) throw new Error(`unknown inbox message ${messageId} for ${audience}`);+ if (matches.length > 1) throw new Error(`ambiguous inbox message ${messageId}; issuer is required`);+ const record = matches[0]!;+ if (record.acknowledgedAt === undefined) record.acknowledgedAt = new Date(this.now()).toISOString();+ }++ pending(audience: string): InMemoryInboxRecord[] {+ return this.records+ .filter((record) => record.message.audience === audience && record.acknowledgedAt === undefined)+ .map(clone);+ }++ quarantineRecords(): InMemoryQuarantinedMessage[] {+ return this.quarantined.map(clone);+ }++ private parseCursor(cursor: string): bigint {+ try {+ return parseCanonicalUnsigned(cursor, 'inbox cursor');+ } catch {+ throw new Error('inbox cursor must be a non-negative decimal integer');+ }+ }++ private quarantine(+ message: HarnessMessage,+ reason: InMemoryQuarantinedMessage['reason'],+ quarantinedAt: string,+ ): void {+ this.quarantined.push({+ issuer: message.issuer,+ messageId: message.messageId,+ reason,+ quarantinedAt,+ });+ }+}diff --git a/v3/@claude-flow/codex/src/harness/in-memory-run-receipt-reference.ts b/v3/@claude-flow/codex/src/harness/in-memory-run-receipt-reference.tsnew file mode 100644index 0000000000..fd71d119e5--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/in-memory-run-receipt-reference.ts@@ -0,0 +1,84 @@+import { createHash } from 'node:crypto';+import type { RunEvidence, RunReceipt } from './contract.js';+import { canonicalJson } from './repository-state.js';++const DIGEST = /^sha256:[0-9a-f]{64}$/;++function sha256(value: string): string {+ return `sha256:${createHash('sha256').update(value).digest('hex')}`;+}++function copy<T>(value: T): T {+ return structuredClone(value);+}++function timestamp(value: string, label: string): number {+ const parsed = Date.parse(value);+ if (!Number.isFinite(parsed)) throw new Error(`${label} must be an ISO timestamp`);+ return parsed;+}++function validateRun(run: RunEvidence): void {+ if (!run.executionId.trim() || !run.sessionId.trim() || !run.workloadId.trim()) {+ throw new Error('run execution, session, and workload identity are required');+ }+ if (!DIGEST.test(run.sourceState.sourceStateId)) throw new Error('run sourceStateId is invalid');+ if (!DIGEST.test(run.commandDigest) || !DIGEST.test(run.evidenceDigest)) {+ throw new Error('run command and evidence digests must be canonical sha256 values');+ }+ if (!Number.isSafeInteger(run.exitCode)) throw new Error('run exitCode must be a safe integer');+ const started = timestamp(run.startedAt, 'startedAt');+ const completed = timestamp(run.completedAt, 'completedAt');+ if (completed < started) throw new Error('run completedAt precedes startedAt');+ if (+ run.buildEvidence !== undefined+ && run.buildEvidence.sourceStateId !== run.sourceState.sourceStateId+ ) {+ throw new Error('build evidence belongs to a different source state');+ }+}++/**+ * Unsigned, non-durable, content-addressed in-memory conformance ledger.+ *+ * Exact retries converge on one receipt. Reusing an execution ID with changed+ * evidence is refused rather than rewriting history. These receipts are local+ * debugging evidence and cannot authorize enforce mode or release.+ */+export class InMemoryRunReceiptReference {+ readonly referenceOnly = true;+ private readonly receipts = new Map<string, RunReceipt>();+ private readonly executionReceipts = new Map<string, string>();++ constructor(private readonly now: () => number = Date.now) {}++ recordRun(run: RunEvidence): RunReceipt {+ validateRun(run);+ const canonical = canonicalJson(run);+ const receiptId = sha256(canonical);+ const existingExecution = this.executionReceipts.get(run.executionId);+ if (existingExecution !== undefined && existingExecution !== receiptId) {+ throw new Error(`executionId ${run.executionId} already records different evidence`);+ }+ const existing = this.receipts.get(receiptId);+ if (existing) return copy(existing);++ const receipt: RunReceipt = {+ ...copy(run),+ receiptId,+ recordedAt: new Date(this.now()).toISOString(),+ };+ this.receipts.set(receiptId, receipt);+ this.executionReceipts.set(run.executionId, receiptId);+ return copy(receipt);+ }++ get(receiptId: string): RunReceipt | undefined {+ const receipt = this.receipts.get(receiptId);+ return receipt ? copy(receipt) : undefined;+ }++ all(): RunReceipt[] {+ return [...this.receipts.values()].map(copy);+ }+}diff --git a/v3/@claude-flow/codex/src/harness/index.ts b/v3/@claude-flow/codex/src/harness/index.tsnew file mode 100644index 0000000000..c828d9d1ac--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/index.ts@@ -0,0 +1,8 @@+export * from './build-evidence.js';+export * from './contract.js';+export * from './in-memory-inbox-reference.js';+export * from './in-memory-fenced-lease-reference.js';+export * from './in-memory-run-receipt-reference.js';+export * from './portable-case-fold.js';+export * from './repository-state.js';+export * from './unsigned-integer.js';diff --git a/v3/@claude-flow/codex/src/harness/portable-case-fold.ts b/v3/@claude-flow/codex/src/harness/portable-case-fold.tsnew file mode 100644index 0000000000..5b9cadbe10--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/portable-case-fold.ts@@ -0,0 +1,10 @@+/**+ * Conservative, deterministic case-fold key for cross-platform collision+ * refusal. Upper-then-lower catches multi-code-point folds such as ß -> ss and+ * final sigma -> sigma. NFKC intentionally over-rejects compatibility aliases;+ * it is never used to rewrite a repository path.+ */+export function portableCaseFold(value: string): string {+ return value.normalize('NFKC').toUpperCase().toLowerCase().normalize('NFC');+}+diff --git a/v3/@claude-flow/codex/src/harness/repository-state.ts b/v3/@claude-flow/codex/src/harness/repository-state.tsnew file mode 100644index 0000000000..9080bd9b01--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/repository-state.ts@@ -0,0 +1,495 @@+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import {+ lstatSync,+ readFileSync,+ readlinkSync,+ realpathSync,+} from 'node:fs';+import { isAbsolute, relative, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { portableCaseFold } from './portable-case-fold.js';++const SHA256_PREFIX = 'sha256:';+const MAX_GIT_BUFFER = 128 * 1024 * 1024;++export interface RepositoryIdentity {+ repositoryId: string;+ canonicalRemote?: string;+ gitCommonDirId: string;+ rootTreeId: string;+}++export interface ContentDigest {+ algorithm: 'sha256';+ digest: string;+ bytes: number;+}++export interface UntrackedFileIdentity {+ path: string;+ kind: 'file' | 'symlink';+ mode: number;+ bytes: number;+ digest: string;+}++export interface UntrackedManifest {+ digest: string;+ entries: readonly UntrackedFileIdentity[];+}++export interface SubmoduleState {+ path: string;+ initialized: boolean;+ expectedCommit: string;+ commit?: string;+ trackedPatch: ContentDigest;+ untrackedManifest: UntrackedManifest;+ submodules: readonly SubmoduleState[];+}++interface SourceStateBase {+ version: 1;+ /** Git-visible state excludes ignored build inputs and installed toolchains. */+ scope: 'git-visible';+ repository: RepositoryIdentity;+ baseCommit: string;+ treeId: string;+ sourceStateId: string;+}++export interface CleanSourceState extends SourceStateBase {+ kind: 'clean';+ clean: true;+}++export interface DirtySourceState extends SourceStateBase {+ kind: 'dirty';+ clean: false;+ trackedPatch: ContentDigest;+ untrackedManifest: UntrackedManifest;+ submodules: readonly SubmoduleState[];+}++export type ExactSourceState = CleanSourceState | DirtySourceState;++interface ContentState {+ baseCommit: string;+ treeId: string;+ trackedPatch: ContentDigest;+ untrackedManifest: UntrackedManifest;+ submodules: readonly SubmoduleState[];+}++function digest(value: string | Buffer): string {+ return `${SHA256_PREFIX}${createHash('sha256').update(value).digest('hex')}`;+}++function assertUnicodeScalarString(value: string): void {+ for (let index = 0; index < value.length; index += 1) {+ const unit = value.charCodeAt(index);+ if (unit >= 0xd800 && unit <= 0xdbff) {+ const next = value.charCodeAt(index + 1);+ if (!(next >= 0xdc00 && next <= 0xdfff)) {+ throw new Error('canonical JSON does not support lone UTF-16 surrogates');+ }+ index += 1;+ } else if (unit >= 0xdc00 && unit <= 0xdfff) {+ throw new Error('canonical JSON does not support lone UTF-16 surrogates');+ }+ }+}++function codeUnitCompare(left: string, right: string): number {+ return left < right ? -1 : left > right ? 1 : 0;+}++/** Recursive, locale-independent canonical JSON for JSON-safe contract values. */+export function canonicalJson(value: unknown): string {+ const ancestors = new Set<object>();+ const encode = (item: unknown): string => {+ if (item === null || typeof item === 'boolean') return JSON.stringify(item);+ if (typeof item === 'string') {+ assertUnicodeScalarString(item);+ return JSON.stringify(item);+ }+ if (typeof item === 'number') {+ if (+ !Number.isFinite(item)+ || Object.is(item, -0)+ || (Number.isInteger(item) && !Number.isSafeInteger(item))+ ) {+ throw new Error('canonical JSON requires finite, safe, non-negative-zero numbers');+ }+ return JSON.stringify(item);+ }+ if (item === undefined) throw new Error('canonical JSON does not support undefined');+ if (typeof item !== 'object') {+ throw new Error(`canonical JSON does not support ${typeof item}`);+ }+ if (ancestors.has(item)) throw new Error('canonical JSON does not support cycles');+ ancestors.add(item);+ try {+ if (Array.isArray(item)) return `[${item.map(encode).join(',')}]`;+ const prototype = Object.getPrototypeOf(item);+ if (prototype !== Object.prototype && prototype !== null) {+ throw new Error('canonical JSON supports only arrays and plain objects');+ }+ const entries = Object.entries(item as Record<string, unknown>)+ .sort(([left], [right]) => codeUnitCompare(left, right));+ return `{${entries.map(([key, child]) => {+ assertUnicodeScalarString(key);+ return `${JSON.stringify(key)}:${encode(child)}`;+ }).join(',')}}`;+ } finally {+ ancestors.delete(item);+ }+ };+ return encode(value);+}++function gitBuffer(repoRoot: string, args: readonly string[]): Buffer {+ return execFileSync('git', ['-C', repoRoot, ...args], {+ encoding: 'buffer',+ stdio: ['ignore', 'pipe', 'pipe'],+ maxBuffer: MAX_GIT_BUFFER,+ });+}++function gitText(repoRoot: string, args: readonly string[]): string {+ return gitBuffer(repoRoot, args).toString('utf8').trim();+}++function optionalGitText(repoRoot: string, args: readonly string[]): string | undefined {+ try {+ const value = gitText(repoRoot, args);+ return value.length > 0 ? value : undefined;+ } catch {+ return undefined;+ }+}++function splitNul(output: Buffer): Buffer[] {+ const records: Buffer[] = [];+ let start = 0;+ for (let index = 0; index < output.length; index += 1) {+ if (output[index] !== 0) continue;+ if (index > start) records.push(output.subarray(start, index));+ start = index + 1;+ }+ if (start !== output.length) throw new Error('Git returned a non-NUL-terminated path list');+ return records;+}++function decodeGitPath(bytes: Buffer): string {+ const path = bytes.toString('utf8');+ if (!Buffer.from(path, 'utf8').equals(bytes)) {+ throw new Error('Git path is not valid round-trip UTF-8');+ }+ assertUnicodeScalarString(path);+ if (path !== path.normalize('NFC')) {+ throw new Error(`Git path is not NFC-normalized: ${path}`);+ }+ return normalizeRelativePath(path);+}++function normalizeRelativePath(path: string): string {+ assertUnicodeScalarString(path);+ if (path.includes('\\')) throw new Error(`ambiguous repository path separator: ${path}`);+ const normalized = path.normalize('NFC');+ if (+ normalized.length === 0+ || isAbsolute(normalized)+ || normalized.startsWith('-')+ || normalized.split('/').some((part) => part === '' || part === '.' || part === '..')+ ) {+ throw new Error(`unsafe repository-relative path: ${path}`);+ }+ return normalized;+}++function assertNoPathCollisions(paths: readonly string[]): void {+ const exact = new Set<string>();+ const folded = new Map<string, string>();+ for (const path of paths) {+ if (exact.has(path)) throw new Error(`duplicate repository path: ${path}`);+ exact.add(path);+ const key = portableCaseFold(path);+ const prior = folded.get(key);+ if (prior !== undefined && prior !== path) {+ throw new Error(`case-fold repository path collision: ${prior} and ${path}`);+ }+ folded.set(key, path);+ }+}++function repositoryPaths(repoRoot: string, includeUntracked: boolean): readonly string[] {+ const tracked = splitNul(gitBuffer(repoRoot, ['ls-files', '-z'])).map(decodeGitPath);+ const untracked = includeUntracked+ ? splitNul(gitBuffer(repoRoot, ['ls-files', '--others', '--exclude-standard', '-z'])).map(decodeGitPath)+ : [];+ const paths = [...tracked, ...untracked].sort(codeUnitCompare);+ assertNoPathCollisions(paths);+ return paths;+}++function assertInsideRepository(repoRoot: string, candidate: string): void {+ const rel = relative(repoRoot, candidate);+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {+ throw new Error(`repository path escapes root: ${candidate}`);+ }+}++function contentDigest(content: Buffer): ContentDigest {+ return { algorithm: 'sha256', digest: digest(content), bytes: content.byteLength };+}++function untrackedManifest(repoRoot: string): UntrackedManifest {+ const output = gitBuffer(repoRoot, ['ls-files', '--others', '--exclude-standard', '-z']);+ const paths = splitNul(output).map(decodeGitPath).sort(codeUnitCompare);+ assertNoPathCollisions(paths);+ const entries = paths.map((path): UntrackedFileIdentity => {+ const absolute = resolve(repoRoot, path);+ assertInsideRepository(repoRoot, absolute);+ const before = lstatSync(absolute);+ let kind: UntrackedFileIdentity['kind'];+ let content: Buffer;+ if (before.isSymbolicLink()) {+ kind = 'symlink';+ content = Buffer.from(readlinkSync(absolute), 'utf8');+ } else if (before.isFile()) {+ kind = 'file';+ content = readFileSync(absolute);+ } else {+ throw new Error(`unsupported untracked repository entry: ${path}`);+ }+ const after = lstatSync(absolute);+ if (+ before.mode !== after.mode+ || before.size !== after.size+ || before.mtimeMs !== after.mtimeMs+ || before.ino !== after.ino+ ) {+ throw new Error(`repository changed while hashing untracked entry: ${path}`);+ }+ return {+ path,+ kind,+ mode: before.mode & 0o7777,+ bytes: content.byteLength,+ digest: digest(content),+ };+ });+ return { digest: digest(canonicalJson(entries)), entries };+}++function trackedPatch(repoRoot: string): ContentDigest {+ return contentDigest(gitBuffer(repoRoot, [+ 'diff',+ '--binary',+ '--full-index',+ '--no-ext-diff',+ 'HEAD',+ '--',+ ]));+}++function submoduleStates(repoRoot: string): readonly SubmoduleState[] {+ const staged = splitNul(gitBuffer(repoRoot, ['ls-files', '--stage', '-z']));+ const submodules = staged.flatMap((entry): Array<{ path: string; commit: string }> => {+ const tab = entry.indexOf(0x09);+ if (tab < 0) throw new Error('malformed Git index record');+ const metadata = entry.subarray(0, tab).toString('ascii');+ const match = /^160000 ([0-9a-f]+) [0-3]$/.exec(metadata);+ return match?.[1]+ ? [{ path: decodeGitPath(entry.subarray(tab + 1)), commit: match[1] }]+ : [];+ });+ assertNoPathCollisions(submodules.map(({ path }) => path));++ return submodules.map(({ path, commit }): SubmoduleState => {+ const absolute = resolve(repoRoot, path);+ assertInsideRepository(repoRoot, absolute);+ const actualCommit = optionalGitText(absolute, ['rev-parse', '--verify', 'HEAD']);+ if (!actualCommit) {+ return {+ path,+ initialized: false,+ expectedCommit: commit,+ trackedPatch: contentDigest(Buffer.alloc(0)),+ untrackedManifest: { digest: digest('[]'), entries: [] },+ submodules: [],+ };+ }+ repositoryPaths(absolute, true);+ return {+ path,+ initialized: true,+ expectedCommit: commit,+ commit: actualCommit,+ trackedPatch: trackedPatch(absolute),+ untrackedManifest: untrackedManifest(absolute),+ submodules: submoduleStates(absolute),+ };+ });+}++function captureContentState(repoRoot: string): ContentState {+ const baseCommit = gitText(repoRoot, ['rev-parse', '--verify', 'HEAD']);+ const treeId = gitText(repoRoot, ['rev-parse', '--verify', 'HEAD^{tree}']);+ return {+ baseCommit,+ treeId,+ trackedPatch: trackedPatch(repoRoot),+ untrackedManifest: untrackedManifest(repoRoot),+ submodules: submoduleStates(repoRoot),+ };+}++function canonicalizeRemote(remote: string): string {+ const trimmed = remote.trim();+ const scp = /^([^/@:]+@)?([^/:]+):(.+)$/.exec(trimmed);+ if (scp?.[2] && scp[3] && !trimmed.includes('://')) {+ return `ssh://${scp[2].toLowerCase()}/${scp[3].replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')}`;+ }+ try {+ const url = new URL(trimmed);+ url.username = '';+ url.password = '';+ url.hostname = url.hostname.toLowerCase();+ url.pathname = url.pathname.replace(/\.git$/i, '').replace(/\/+$/g, '');+ url.hash = '';+ url.search = '';+ return url.toString().replace(/\/$/, '');+ } catch {+ return trimmed.replace(/\.git$/i, '').replace(/\/+$/g, '');+ }+}++function repositoryIdentity(repoRoot: string): RepositoryIdentity {+ const commonDirRaw = gitText(repoRoot, ['rev-parse', '--git-common-dir']);+ const commonDir = realpathSync(resolve(repoRoot, commonDirRaw));+ const canonicalRemoteRaw = optionalGitText(repoRoot, ['remote', 'get-url', 'origin']);+ const canonicalRemote = canonicalRemoteRaw ? canonicalizeRemote(canonicalRemoteRaw) : undefined;+ const rootCommits = gitText(repoRoot, ['rev-list', '--max-parents=0', 'HEAD']).split(/\s+/).sort();+ const rootTrees = rootCommits.map((commit) => gitText(repoRoot, ['rev-parse', `${commit}^{tree}`]));+ const rootTreeId = rootTrees.length === 1 ? rootTrees[0]! : digest(canonicalJson(rootTrees));+ const gitCommonDirId = digest(commonDir);+ const repositoryId = digest(canonicalJson({+ anchor: canonicalRemote ?? gitCommonDirId,+ rootTreeId,+ }));+ return {+ repositoryId,+ ...(canonicalRemote ? { canonicalRemote } : {}),+ gitCommonDirId,+ rootTreeId,+ };+}++function hasDirtySubmodule(submodule: SubmoduleState): boolean {+ return !submodule.initialized+ || submodule.commit !== submodule.expectedCommit+ || submodule.trackedPatch.bytes > 0+ || submodule.untrackedManifest.entries.length > 0+ || submodule.submodules.some(hasDirtySubmodule);+}++/**+ * Capture a stable, content-addressed Git source state.+ *+ * The collector performs two complete reads and refuses a moving worktree.+ * Ignored files are intentionally excluded because Git does not treat them as+ * repository source. Untracked symlinks bind their link target text without+ * following the target outside the worktree.+ */+export function captureRepositorySourceState(repoPath: string | URL): ExactSourceState {+ const requested = repoPath instanceof URL ? fileURLToPath(repoPath) : repoPath;+ const repoRoot = realpathSync(resolve(requested));+ const top = realpathSync(gitText(repoRoot, ['rev-parse', '--show-toplevel']));+ if (top !== repoRoot) throw new Error(`repoPath must be the Git top-level: ${top}`);++ const cleanStatus = (): Buffer => gitBuffer(repoRoot, [+ 'status',+ '--porcelain=v1',+ '-z',+ '--untracked-files=all',+ '--ignore-submodules=none',+ ]);+ const initialStatus = cleanStatus();+ if (initialStatus.length === 0) {+ repositoryPaths(repoRoot, false);+ const baseCommit = gitText(repoRoot, ['rev-parse', '--verify', 'HEAD']);+ const treeId = gitText(repoRoot, ['rev-parse', '--verify', 'HEAD^{tree}']);+ if (cleanStatus().length !== 0 || gitText(repoRoot, ['rev-parse', '--verify', 'HEAD']) !== baseCommit) {+ throw new Error('repository changed while capturing exact source state');+ }+ const repository = repositoryIdentity(repoRoot);+ const identity = {+ version: 1,+ scope: 'git-visible',+ repositoryId: repository.repositoryId,+ commit: baseCommit,+ tree: treeId,+ };+ return {+ version: 1,+ scope: 'git-visible',+ kind: 'clean',+ clean: true,+ repository,+ baseCommit,+ treeId,+ sourceStateId: digest(canonicalJson(identity)),+ };+ }++ repositoryPaths(repoRoot, true);+ const first = captureContentState(repoRoot);+ const second = captureContentState(repoRoot);+ if (canonicalJson(first) !== canonicalJson(second)) {+ throw new Error('repository changed while capturing exact source state');+ }++ const repository = repositoryIdentity(repoRoot);+ const dirty = second.trackedPatch.bytes > 0+ || second.untrackedManifest.entries.length > 0+ || second.submodules.some(hasDirtySubmodule);++ if (!dirty) throw new Error('Git status reported changes that exact-state capture could not identify');++ const identity = {+ version: 1,+ scope: 'git-visible',+ repositoryId: repository.repositoryId,+ baseCommit: second.baseCommit,+ tree: second.treeId,+ trackedPatch: second.trackedPatch,+ untrackedManifest: second.untrackedManifest,+ submodules: second.submodules,+ };+ return {+ version: 1,+ scope: 'git-visible',+ kind: 'dirty',+ clean: false,+ repository,+ baseCommit: second.baseCommit,+ treeId: second.treeId,+ trackedPatch: second.trackedPatch,+ untrackedManifest: second.untrackedManifest,+ submodules: second.submodules,+ sourceStateId: digest(canonicalJson(identity)),+ };+}++export function sourceStateMatches(left: ExactSourceState, right: ExactSourceState): boolean {+ return left.sourceStateId === right.sourceStateId+ && left.repository.repositoryId === right.repository.repositoryId;+}++/** Release receipts default to the stronger committed-state requirement. */+export function isReleaseEligibleSourceState(state: ExactSourceState): state is CleanSourceState {+ return state.clean;+}diff --git a/v3/@claude-flow/codex/src/harness/unsigned-integer.ts b/v3/@claude-flow/codex/src/harness/unsigned-integer.tsnew file mode 100644index 0000000000..08ecd54681--- /dev/null+++ b/v3/@claude-flow/codex/src/harness/unsigned-integer.ts@@ -0,0 +1,14 @@+const CANONICAL_UNSIGNED = /^(?:0|[1-9][0-9]*)$/;+const MAX_UNSIGNED_64 = (1n << 64n) - 1n;++/** Parse a decimal unsigned integer without accepting aliases such as +1, 01, hex, or whitespace. */+export function parseCanonicalUnsigned(value: string, label: string): bigint {+ if (!CANONICAL_UNSIGNED.test(value)) {+ throw new Error(`${label} must be a canonical unsigned decimal integer`);+ }+ const parsed = BigInt(value);+ if (parsed > MAX_UNSIGNED_64) {+ throw new Error(`${label} exceeds unsigned 64-bit range`);+ }+ return parsed;+}diff --git a/v3/@claude-flow/codex/src/index.ts b/v3/@claude-flow/codex/src/index.tsindex c2d32d8f68..7db21001ce 100644--- a/v3/@claude-flow/codex/src/index.ts+++ b/v3/@claude-flow/codex/src/index.ts@@ -62,6 +62,9 @@ export type {export { CodexWorktreeCoordinator } from './worktrees/index.js';export type { WorktreeAssignment, WorktreeRunRecord } from './worktrees/index.js';+// Repository harness contracts and in-memory reference implementations.+export * from './harness/index.js';+// Codex /loop-compatible runnerexport {buildCodexLoopPrompt,@@ -90,7 +93,7 @@ export {/*** Package version*/-export const VERSION = '3.0.2';+export const VERSION = '3.0.3';/*** Package metadatadiff --git a/v3/@claude-flow/codex/tests/generators.test.ts b/v3/@claude-flow/codex/tests/generators.test.tsindex e339b83091..e187f96dc6 100644--- a/v3/@claude-flow/codex/tests/generators.test.ts+++ b/v3/@claude-flow/codex/tests/generators.test.ts@@ -115,6 +115,13 @@ describe('generateAgentsMd', () => {expect(result).toContain('## Ruflo + Codex Automated Workflow');expect(result).toContain('Never allow two writers in one worktree');expect(result).toContain('MetaHarness may benchmark candidates concurrently');+ expect(result).toContain('### Repository harness adapter');+ expect(result).toContain(+ 'A repository lease coordinates ownership; it does not grant authorization',+ );+ expect(result).toContain(+ 'HEAD alone is not an exact source-state',+ );});it('should include tech stack', async () => {diff --git a/v3/@claude-flow/codex/tests/harness-authorities.test.ts b/v3/@claude-flow/codex/tests/harness-authorities.test.tsnew file mode 100644index 0000000000..4e8c37d556--- /dev/null+++ b/v3/@claude-flow/codex/tests/harness-authorities.test.ts@@ -0,0 +1,196 @@+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import {+ captureRepositorySourceState,+ harnessMessageContentDigest,+ inMemoryInboxIdentityKey,+ InMemoryInboxReference,+ InMemoryFencedLeaseReference,+ InMemoryRunReceiptReference,+ InMemoryFenceReferenceError,+ parseCanonicalUnsigned,+ type FencedLeaseRequest,+ type HarnessMessage,+ type RunEvidence,+} from '../src/harness/index.js';++const roots: string[] = [];+const D = (value: string): string => `sha256:${createHash('sha256').update(value).digest('hex')}`;++function repository(): string {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-harness-authority-'));+ roots.push(root);+ execFileSync('git', ['init', '--quiet', root]);+ execFileSync('git', ['-C', root, 'config', 'user.email', '[email protected]']);+ execFileSync('git', ['-C', root, 'config', 'user.name', 'Harness Test']);+ writeFileSync(join(root, 'source.ts'), 'export {};\n');+ execFileSync('git', ['-C', root, 'add', 'source.ts']);+ execFileSync('git', ['-C', root, 'commit', '--quiet', '-m', 'seed']);+ return root;+}++function leaseRequest(overrides: Partial<FencedLeaseRequest> = {}): FencedLeaseRequest {+ return {+ sessionId: 'session-a',+ workloadId: 'workload-a',+ repositoryId: 'repo-a',+ worktreeId: 'worktree-a',+ kind: 'path',+ scopes: ['src'],+ ttlMs: 1_000,+ ...overrides,+ };+}++function message(overrides: Partial<HarnessMessage> = {}): HarnessMessage {+ const content = overrides.content ?? { handoff: 'ready' };+ return {+ messageId: 'message-1',+ issuer: 'agent-a',+ audience: 'agent-b',+ sequence: '1',+ contentDigest: harnessMessageContentDigest(content),+ content,+ ...overrides,+ };+}++async function collect<T>(values: AsyncIterable<T>): Promise<T[]> {+ const result: T[] = [];+ for await (const value of values) result.push(value);+ return result;+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('in-memory CP fenced lease authority', () => {+ it('selects one owner for conflicting acquisitions and isolates repositories', () => {+ const authority = new InMemoryFencedLeaseReference(() => 1_000);+ const results = Array.from({ length: 100 }, (_, index) => {+ try {+ return authority.acquire(leaseRequest({+ sessionId: `session-${index}`,+ workloadId: `workload-${index}`,+ worktreeId: `worktree-${index}`,+ scopes: ['src/harness'],+ }));+ } catch (error) {+ expect(error).toBeInstanceOf(InMemoryFenceReferenceError);+ return null;+ }+ });+ expect(results.filter(Boolean)).toHaveLength(1);+ expect(authority.acquire(leaseRequest({+ repositoryId: 'repo-b',+ scopes: ['src/harness'],+ })).repositoryId).toBe('repo-b');+ });++ it('uses CAS versions and rejects a stale fence after renew/release/reacquire', () => {+ let now = 1_000;+ const authority = new InMemoryFencedLeaseReference(() => now);+ const first = authority.acquire(leaseRequest());+ const renewed = authority.renew(first, 2_000);+ expect(BigInt(renewed.version)).toBe(BigInt(first.version) + 1n);+ expect(() => authority.renew(first, 2_000)).toThrow(/stale/);+ authority.assertCurrentFence(renewed);+ authority.release(renewed);+ expect(() => authority.assertCurrentFence(renewed)).toThrow(/unknown/);++ const second = authority.acquire(leaseRequest());+ expect(BigInt(second.epoch)).toBeGreaterThan(BigInt(first.epoch));+ now = 4_001;+ expect(() => authority.assertCurrentFence(second)).toThrow(/expired/);+ });++ it('treats portable case-fold aliases as conflicting paths', () => {+ const authority = new InMemoryFencedLeaseReference(() => 1_000);+ authority.acquire(leaseRequest({ scopes: ['src/Straße'] }));+ expect(() => authority.acquire(leaseRequest({+ sessionId: 'session-b',+ workloadId: 'workload-b',+ worktreeId: 'worktree-b',+ scopes: ['src/STRASSE/file.ts'],+ }))).toThrow(/conflicts/);+ });+});++describe('unsigned in-memory inbox reference semantics', () => {+ it('deduplicates exact replay, resumes by cursor, and retains until acknowledgement', async () => {+ const inbox = new InMemoryInboxReference(() => 1_000);+ expect(inbox.send(message()).duplicate).toBe(false);+ expect(inbox.send(message()).duplicate).toBe(true);+ expect(await collect(inbox.receive('agent-b'))).toHaveLength(1);+ expect(await collect(inbox.receive('agent-b', '1'))).toHaveLength(0);+ expect(inbox.pending('agent-b')).toHaveLength(1);+ inbox.acknowledge('agent-b', 'message-1');+ expect(inbox.pending('agent-b')).toHaveLength(0);+ });++ it('quarantines digest mismatch and message-ID content conflict', () => {+ const inbox = new InMemoryInboxReference(() => 1_000);+ inbox.send(message());+ expect(() => inbox.send(message({+ content: { handoff: 'changed' },+ contentDigest: harnessMessageContentDigest({ handoff: 'changed' }),+ }))).toThrow(/reused/);+ expect(() => inbox.send(message({+ messageId: 'message-2',+ contentDigest: D('wrong'),+ }))).toThrow(/does not match/);+ expect(inbox.quarantineRecords().map(({ reason }) => reason)).toEqual([+ 'message-id-content-conflict',+ 'content-digest-mismatch',+ ]);+ });++ it('rejects non-canonical unsigned sequences and length-frames identity keys', () => {+ const inbox = new InMemoryInboxReference(() => 1_000);+ for (const sequence of ['01', '+1', ' 1', '0x1', '-1']) {+ expect(() => inbox.send(message({ sequence }))).toThrow(/canonical unsigned/);+ }+ expect(parseCanonicalUnsigned('0', 'sequence')).toBe(0n);+ expect(parseCanonicalUnsigned('42', 'sequence')).toBe(42n);+ expect(() => parseCanonicalUnsigned('00', 'sequence')).toThrow(/canonical unsigned/);+ expect(() => parseCanonicalUnsigned('18446744073709551616', 'sequence')).toThrow(/64-bit/);+ expect(inMemoryInboxIdentityKey('a', 'bc')).not.toBe(inMemoryInboxIdentityKey('ab', 'c'));+ expect(inMemoryInboxIdentityKey('a\0b', 'c')).not.toBe(inMemoryInboxIdentityKey('a', 'b\0c'));+ });+});++describe('content-addressed append-only run receipt ledger', () => {+ it('converges exact retry and refuses execution-ID history rewrite', () => {+ const sourceState = captureRepositorySourceState(repository());+ const run: RunEvidence = {+ executionId: 'execution-1',+ sessionId: 'session-a',+ workloadId: 'workload-a',+ sourceState,+ commandDigest: D('command'),+ scope: 'harness',+ profile: 'focused',+ startedAt: '2026-07-29T00:00:00.000Z',+ completedAt: '2026-07-29T00:00:01.000Z',+ exitCode: 0,+ evidenceDigest: D('evidence'),+ };+ const ledger = new InMemoryRunReceiptReference(() => 2_000);+ expect(ledger.referenceOnly).toBe(true);+ const first = ledger.recordRun(run);+ expect(ledger.recordRun(run)).toEqual(first);+ expect(ledger.all()).toHaveLength(1);+ expect(first.receiptId).toMatch(/^sha256:[0-9a-f]{64}$/);+ expect(() => ledger.recordRun({ ...run, exitCode: 1 })).toThrow(/different evidence/);++ const returned = ledger.get(first.receiptId);+ if (!returned) throw new Error('receipt missing');+ returned.scope = 'mutated-copy';+ expect(ledger.get(first.receiptId)?.scope).toBe('harness');+ });+});diff --git a/v3/@claude-flow/codex/tests/harness-repository-state.bench.ts b/v3/@claude-flow/codex/tests/harness-repository-state.bench.tsnew file mode 100644index 0000000000..42dc15a774--- /dev/null+++ b/v3/@claude-flow/codex/tests/harness-repository-state.bench.ts@@ -0,0 +1,48 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, bench, describe } from 'vitest';+import { captureRepositorySourceState } from '../src/harness/index.js';++const roots: string[] = [];+let cleanRoot = '';+let dirtyRoot = '';++function repository(label: string): string {+ const root = mkdtempSync(join(tmpdir(), `ruflo-source-state-${label}-`));+ roots.push(root);+ execFileSync('git', ['init', '--quiet', root]);+ execFileSync('git', ['-C', root, 'config', 'user.email', '[email protected]']);+ execFileSync('git', ['-C', root, 'config', 'user.name', 'Harness Benchmark']);+ for (let index = 0; index < 200; index += 1) {+ writeFileSync(join(root, `source-${index.toString().padStart(3, '0')}.ts`), `export const n = ${index};\n`);+ }+ execFileSync('git', ['-C', root, 'add', '.']);+ execFileSync('git', ['-C', root, 'commit', '--quiet', '-m', 'benchmark fixture']);+ return root;+}++beforeAll(() => {+ cleanRoot = repository('clean');+ dirtyRoot = repository('dirty');+ writeFileSync(join(dirtyRoot, 'source-100.ts'), 'export const n = 999;\n');+ for (let index = 0; index < 25; index += 1) {+ writeFileSync(join(dirtyRoot, `untracked-${index}.json`), JSON.stringify({ index }));+ }+});++afterAll(() => {+ for (const root of roots) rmSync(root, { recursive: true, force: true });+});++describe('repository source-state capture', () => {+ bench('clean 200-file repository fast preflight', () => {+ captureRepositorySourceState(cleanRoot);+ }, { iterations: 10, warmupIterations: 2 });++ bench('dirty patch plus 25-file manifest', () => {+ captureRepositorySourceState(dirtyRoot);+ }, { iterations: 10, warmupIterations: 2 });+});+diff --git a/v3/@claude-flow/codex/tests/harness-repository-state.test.ts b/v3/@claude-flow/codex/tests/harness-repository-state.test.tsnew file mode 100644index 0000000000..f6adf14e38--- /dev/null+++ b/v3/@claude-flow/codex/tests/harness-repository-state.test.ts@@ -0,0 +1,216 @@+import { execFileSync } from 'node:child_process';+import {+ chmodSync,+ mkdtempSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import {+ canonicalJson,+ buildEvidenceMatches,+ captureBuildEvidence,+ captureRepositorySourceState,+ createBuildEvidence,+ isReleaseEligibleSourceState,+ normalizeHarnessDescriptor,+ portableCaseFold,+ recomputeBuildEvidence,+ sourceStateMatches,+} from '../src/harness/index.js';++const roots: string[] = [];++function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }).trim();+}++function createRepository(): string {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-harness-state-'));+ roots.push(root);+ execFileSync('git', ['init', '--quiet', root]);+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'user.name', 'Harness Test');+ writeFileSync(join(root, '.gitignore'), 'ignored.txt\n');+ writeFileSync(join(root, 'tracked.txt'), 'one\n');+ git(root, 'add', '.gitignore', 'tracked.txt');+ git(root, 'commit', '--quiet', '-m', 'seed');+ return root;+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('exact repository source-state identity', () => {+ it('is deterministic and release-eligible for a clean commit', () => {+ const root = createRepository();+ const first = captureRepositorySourceState(root);+ const second = captureRepositorySourceState(root);++ expect(first).toEqual(second);+ expect(first.kind).toBe('clean');+ expect(first.baseCommit).toBe(git(root, 'rev-parse', 'HEAD'));+ expect(sourceStateMatches(first, second)).toBe(true);+ expect(isReleaseEligibleSourceState(first)).toBe(true);+ });++ it('changes for each tracked byte and returns to the committed identity after restore', () => {+ const root = createRepository();+ const clean = captureRepositorySourceState(root);+ writeFileSync(join(root, 'tracked.txt'), 'two\n');+ const two = captureRepositorySourceState(root);+ writeFileSync(join(root, 'tracked.txt'), 'too\n');+ const too = captureRepositorySourceState(root);++ expect(two.kind).toBe('dirty');+ expect(too.kind).toBe('dirty');+ expect(two.sourceStateId).not.toBe(clean.sourceStateId);+ expect(too.sourceStateId).not.toBe(two.sourceStateId);+ expect(isReleaseEligibleSourceState(two)).toBe(false);+ if (two.kind === 'dirty') expect(two.trackedPatch.bytes).toBeGreaterThan(0);++ writeFileSync(join(root, 'tracked.txt'), 'one\n');+ expect(captureRepositorySourceState(root)).toEqual(clean);+ });++ it('binds untracked path, mode, length, and content while excluding ignored files', () => {+ const root = createRepository();+ writeFileSync(join(root, 'draft.sh'), 'echo one\n', { mode: 0o600 });+ const first = captureRepositorySourceState(root);+ expect(first.kind).toBe('dirty');+ if (first.kind !== 'dirty') throw new Error('expected dirty state');+ expect(first.untrackedManifest.entries).toMatchObject([+ { path: 'draft.sh', kind: 'file', mode: 0o600, bytes: 9 },+ ]);++ writeFileSync(join(root, 'draft.sh'), 'echo two\n', { mode: 0o600 });+ const contentChanged = captureRepositorySourceState(root);+ expect(contentChanged.sourceStateId).not.toBe(first.sourceStateId);++ chmodSync(join(root, 'draft.sh'), 0o700);+ const modeChanged = captureRepositorySourceState(root);+ expect(modeChanged.sourceStateId).not.toBe(contentChanged.sourceStateId);++ writeFileSync(join(root, 'ignored.txt'), 'not source\n');+ expect(captureRepositorySourceState(root)).toEqual(modeChanged);+ });++ it('produces the same clean identity in another worktree of the repository', () => {+ const root = createRepository();+ const worktree = `${root}-peer`;+ roots.push(worktree);+ git(root, 'worktree', 'add', '--quiet', '--detach', worktree, 'HEAD');+ const main = captureRepositorySourceState(root);+ const peer = captureRepositorySourceState(worktree);+ expect(peer.sourceStateId).toBe(main.sourceStateId);+ expect(peer.repository.repositoryId).toBe(main.repository.repositoryId);+ });++ it('rejects invalid UTF-8, non-NFC, and case-fold path ambiguity', () => {+ const invalid = createRepository();+ const invalidPath = Buffer.concat([Buffer.from(`${invalid}/`), Buffer.from([0xff])]);+ writeFileSync(invalidPath, 'invalid\n');+ expect(() => captureRepositorySourceState(invalid)).toThrow(/round-trip UTF-8/);++ const nonNfc = createRepository();+ writeFileSync(join(nonNfc, 'e\u0301.txt'), 'decomposed\n');+ expect(() => captureRepositorySourceState(nonNfc)).toThrow(/not NFC-normalized/);++ const collision = createRepository();+ writeFileSync(join(collision, 'Case.txt'), 'upper\n');+ writeFileSync(join(collision, 'case.txt'), 'lower\n');+ expect(() => captureRepositorySourceState(collision)).toThrow(/case-fold.*collision/);++ const expandedFold = createRepository();+ writeFileSync(join(expandedFold, 'straße.txt'), 'sharp s\n');+ writeFileSync(join(expandedFold, 'strasse.txt'), 'two s\n');+ expect(() => captureRepositorySourceState(expandedFold)).toThrow(/case-fold.*collision/);+ });+});++describe('canonical evidence encoding', () => {+ it('sorts by UTF-16 code unit and rejects ambiguous JSON values', () => {+ expect(canonicalJson({ a: 1, Z: 2 })).toBe('{"Z":2,"a":1}');+ expect(() => canonicalJson(-0)).toThrow(/safe/);+ expect(() => canonicalJson(Number.MAX_SAFE_INTEGER + 1)).toThrow(/safe/);+ expect(() => canonicalJson({ omitted: undefined })).toThrow(/undefined/);+ expect(() => canonicalJson('\ud800')).toThrow(/surrogate/);+ });++ it('separates declared build inputs and toolchains from Git-visible state', () => {+ const root = createRepository();+ const state = captureRepositorySourceState(root);+ const digest = `sha256:${'a'.repeat(64)}`;+ const evidence = createBuildEvidence(+ state,+ [{ name: 'generated policy', path: '.cache/policy.bin', digest, bytes: 42 }],+ [{ name: 'node', version: '22.22.2', digest }],+ );+ expect(state.scope).toBe('git-visible');+ expect(evidence.sourceStateId).toBe(state.sourceStateId);+ expect(evidence.evidenceDigest).toMatch(/^sha256:[0-9a-f]{64}$/);+ expect(createBuildEvidence(+ state,+ [{ name: 'generated policy', path: '.cache/policy.bin', digest, bytes: 42 }],+ [{ name: 'node', version: '22.22.2', digest }],+ )).toEqual(evidence);+ });++ it('recomputes ignored build input and toolchain bytes without claiming completeness', () => {+ const root = createRepository();+ const state = captureRepositorySourceState(root);+ writeFileSync(join(root, 'ignored.txt'), 'generated one\n');+ const toolchain = join(root, 'tracked.txt');+ const evidence = captureBuildEvidence(+ root,+ state,+ [{ name: 'generated', path: 'ignored.txt' }],+ [{ name: 'fixture-tool', version: '1', path: toolchain }],+ );+ expect(evidence.assurance).toBe('declared-unsigned');+ expect(buildEvidenceMatches(evidence, recomputeBuildEvidence(root, evidence, [+ { name: 'fixture-tool', version: '1', path: toolchain },+ ]))).toBe(true);++ writeFileSync(join(root, 'ignored.txt'), 'generated two\n');+ expect(buildEvidenceMatches(evidence, recomputeBuildEvidence(root, evidence, [+ { name: 'fixture-tool', version: '1', path: toolchain },+ ]))).toBe(false);+ });++ it('uses a conservative portable fold without rewriting paths', () => {+ expect(portableCaseFold('Straße/Σ')).toBe(portableCaseFold('STRASSE/ς'));+ });+});++describe('advisory local harness compatibility', () => {+ it('normalizes a legacy descriptor to observe-only without inventing capabilities', () => {+ expect(normalizeHarnessDescriptor({+ name: 'website-local',+ capabilities: ['sessions', 'leases', 'unknown-future-operation'],+ })).toEqual({+ contractVersion: 1,+ harnessId: 'website-local',+ mode: 'observe',+ capabilities: ['leases', 'sessions'],+ advisory: true,+ assurance: 'in-memory-reference',+ });+ });++ it('downgrades enforce and strips release authority from compatibility descriptors', () => {+ expect(normalizeHarnessDescriptor({+ harnessId: 'fenced-local',+ mode: 'enforce',+ capabilities: ['lease-fencing', 'exact-source-state', 'release-decisions'],+ })).toMatchObject({+ mode: 'observe',+ advisory: true,+ capabilities: ['exact-source-state', 'lease-fencing'],+ assurance: 'in-memory-reference',+ });+ });+});diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/claim-checker.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/claim-checker.test.tsnew file mode 100644index 0000000000..f6cda9fb7c--- /dev/null+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/claim-checker.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from 'vitest';+import { createFederationClaimChecker } from '../../src/application/claim-checker.js';++describe('createFederationClaimChecker', () => {+ it('preserves existing installations in explicit legacy mode', () => {+ const checker = createFederationClaimChecker();+ expect(checker.mode).toBe('legacy');+ expect(checker.checkClaim('federation:admin')).toBe(true);+ });++ it('observes missing grants without changing current behavior', () => {+ const onObservation = vi.fn();+ const checker = createFederationClaimChecker({+ mode: 'observe',+ grantedClaims: ['federation:read'],+ onObservation,+ });++ expect(checker.checkClaim('federation:read')).toBe(true);+ expect(checker.checkClaim('federation:write')).toBe(true);+ expect(onObservation).toHaveBeenNthCalledWith(1, 'federation:read', true);+ expect(onObservation).toHaveBeenNthCalledWith(2, 'federation:write', false);+ });++ it('defaults to deny for an unconfigured claim in enforce mode', () => {+ const checker = createFederationClaimChecker({+ mode: 'enforce',+ grantedClaims: ['federation:read'],+ });++ expect(checker.checkClaim('federation:read')).toBe(true);+ expect(checker.checkClaim('federation:write')).toBe(false);+ });++ it('rejects an unknown configured claim', () => {+ expect(() =>+ createFederationClaimChecker({+ mode: 'enforce',+ grantedClaims: ['federation:root'],+ }),+ ).toThrow('Unknown federation claim');+ });+});diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.tsindex cf22af3008..1e7a0ab05c 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/discovery-service.test.ts@@ -158,6 +158,14 @@ describe('DiscoveryService', () => {).rejects.toThrow(/invalid manifest/i);});+ it('should reject a signed manifest for a different endpoint', async () => {+ const manifest = makeManifest({ signature: 'valid' });++ await expect(+ service.addStaticPeer('https://other.example.com', manifest),+ ).rejects.toThrow(/manifest endpoint mismatch/i);+ });+it('should mark existing peer as seen and return it without creating a duplicate', async () => {const manifest = makeManifest({ signature: 'valid' });const first = await service.addStaticPeer('https://peer1.example.com', manifest);diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/inbound-dispatcher.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/inbound-dispatcher.test.tsindex 076bc29b1a..63efaa9a31 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/inbound-dispatcher.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/inbound-dispatcher.test.ts@@ -66,7 +66,18 @@ function mkDeps(peers: FederationNode[] = []): {};}-const baseMsg = (sourceNodeId: string | undefined, type = 'task'): AgentMessage => ({+function withVerifier(+ peers: FederationNode[],+ verify: (canon: string, sig: string | null, pk: string) => boolean,+) {+ const base = mkDeps(peers);+ return {+ ...base,+ deps: { ...base.deps, verifyEnvelope: verify },+ };+}++const baseMsg = (sourceNodeId: string | undefined, type = 'heartbeat'): AgentMessage => ({id: 'msg-1',type,payload: { test: true },@@ -113,11 +124,11 @@ describe('dispatchInbound — happy path', () => {it('accepts ACTIVE peer, audits message_received, emits typed event', async () => {const peer = mkPeer('alpha');const { deps, audits, events } = mkDeps([peer]);- const r = await dispatchInbound('1.2.3.4:55555', baseMsg('alpha', 'task'), deps);- expect(r).toEqual({ accepted: true, sourceNodeId: 'alpha', messageType: 'task' });+ const r = await dispatchInbound('1.2.3.4:55555', baseMsg('alpha'), deps);+ expect(r).toEqual({ accepted: true, sourceNodeId: 'alpha', messageType: 'heartbeat' });expect(audits[0].eventType).toBe('message_received');expect(events).toHaveLength(1);- expect(events[0].event).toBe(`${FEDERATION_INBOUND_EVENT_PREFIX}:task`);+ expect(events[0].event).toBe(`${FEDERATION_INBOUND_EVENT_PREFIX}:heartbeat`);});it('event payload includes address, sourceNodeId, message, peer', async () => {@@ -133,12 +144,20 @@ describe('dispatchInbound — happy path', () => {it('different messageTypes produce different event names', async () => {const peer = mkPeer('alpha');- const { deps, events } = mkDeps([peer]);- await dispatchInbound('a', baseMsg('alpha', 'task'), deps);- await dispatchInbound('a', baseMsg('alpha', 'memory-query'), deps);- await dispatchInbound('a', baseMsg('alpha', 'context-share'), deps);+ const { deps, events } = withVerifier([peer], () => true);+ const jcs = (type: string): AgentMessage => ({+ ...baseMsg('alpha', type),+ metadata: {+ sourceNodeId: 'alpha',+ signature: 'valid',+ signatureVersion: 'jcs-v1',+ },+ });+ await dispatchInbound('a', jcs('task-assignment'), deps);+ await dispatchInbound('a', jcs('memory-query'), deps);+ await dispatchInbound('a', jcs('context-share'), deps);expect(events.map((e) => e.event)).toEqual([- 'federation:inbound:task',+ 'federation:inbound:task-assignment','federation:inbound:memory-query','federation:inbound:context-share',]);@@ -170,17 +189,6 @@ describe('dispatchInbound — robustness', () => {});describe('dispatchInbound — signature verification', () => {- function withVerifier(- peers: FederationNode[],- verify: (canon: string, sig: string | null, pk: string) => boolean,- ) {- const base = mkDeps(peers);- return {- ...base,- deps: { ...base.deps, verifyEnvelope: verify },- };- }-it('rejects INVALID_SIGNATURE when verifier returns false', async () => {const peer = mkPeer('alpha');const { deps, audits, events } = withVerifier([peer], () => false);@@ -219,7 +227,7 @@ describe('dispatchInbound — signature verification', () => {metadata: { sourceNodeId: 'alpha', signature: 'valid-sig' },};const r = await dispatchInbound('a', msg, deps);- expect(r).toEqual({ accepted: true, sourceNodeId: 'alpha', messageType: 'task' });+ expect(r).toEqual({ accepted: true, sourceNodeId: 'alpha', messageType: 'heartbeat' });expect(audits[0].eventType).toBe('message_received');expect(events).toHaveLength(1);});@@ -250,6 +258,26 @@ describe('dispatchInbound — signature verification', () => {expect(verifyCalled).toBe(false);});+ it('rejects non-canonical payloads without invoking the verifier', async () => {+ const peer = mkPeer('alpha');+ let verifyCalled = false;+ const { deps } = withVerifier([peer], () => {+ verifyCalled = true;+ return true;+ });+ const r = await dispatchInbound(+ 'a',+ {+ ...baseMsg('alpha'),+ payload: { unsafe: Number.NaN },+ metadata: { sourceNodeId: 'alpha', signature: 's', signatureVersion: 'jcs-v1' },+ },+ deps,+ );+ expect(r).toEqual({ accepted: false, reason: 'INVALID_PAYLOAD' });+ expect(verifyCalled).toBe(false);+ });+it('legacy mode (no verifier injected) accepts without sig check — backward compat', async () => {const peer = mkPeer('alpha');const { deps, events } = mkDeps([peer]); // no verifyEnvelope@@ -259,6 +287,183 @@ describe('dispatchInbound — signature verification', () => {});});+describe('dispatchInbound — legacy-v1 containment', () => {+ it.each([+ 'claim-event',+ 'agent-handoff',+ 'task-assignment',+ 'task_assignment',+ 'context-share',+ 'memory-response',+ 'memory_response',+ 'trust-change',+ 'topology-change',+ 'agent-spawn',+ 'spawn-agent',+ 'unknown-extension',+ ])('rejects consequential or unknown legacy-v1 type %s', async (type) => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const authorizeInbound = vi.fn(() => ({ allowed: true }));+ const result = await dispatchInbound(+ 'a',+ {+ ...baseMsg('alpha', type),+ metadata: { sourceNodeId: 'alpha', signature: 'valid' },+ },+ { ...deps, authorizeInbound },+ );++ expect(result).toEqual({ accepted: false, reason: 'LEGACY_SIGNATURE_TYPE_REJECTED' });+ expect(authorizeInbound).not.toHaveBeenCalled();+ expect(events).toEqual([]);+ });++ it.each(['heartbeat', 'status-broadcast'])(+ 'retains legacy connectivity for explicit low-risk type %s',+ async (type) => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const result = await dispatchInbound(+ 'a',+ {+ ...baseMsg('alpha', type),+ metadata: { sourceNodeId: 'alpha', signature: 'valid' },+ },+ deps,+ );+ expect(result.accepted).toBe(true);+ expect(events).toHaveLength(1);+ },+ );+});++describe('dispatchInbound — inbound authorization', () => {+ const jcsMessage = (type = 'task-assignment'): AgentMessage => ({+ ...baseMsg('alpha', type),+ metadata: {+ sourceNodeId: 'alpha',+ signature: 'valid',+ signatureVersion: 'jcs-v1',+ },+ });++ it('enforce denies before markSeen, audit acceptance, and emit', async () => {+ const peer = mkPeer('alpha');+ const lastSeen = peer.lastSeen;+ const { deps, audits, events } = withVerifier([peer], () => true);+ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'enforce',+ authorizeInbound: () => ({ allowed: false, reason: 'missing federation:write' }),+ });++ expect(result).toEqual({ accepted: false, reason: 'AUTHORIZATION_DENIED' });+ expect(peer.lastSeen).toBe(lastSeen);+ expect(audits).toHaveLength(1);+ expect(audits[0].eventType).toBe('message_rejected');+ expect(events).toEqual([]);+ });++ it('enforce fails closed when no evaluator is injected', async () => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'enforce',+ });+ expect(result).toEqual({ accepted: false, reason: 'AUTHORIZATION_ERROR' });+ expect(events).toEqual([]);+ });++ it('enforce fails closed when the evaluator throws', async () => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'enforce',+ authorizeInbound: () => {+ throw new Error('policy backend unavailable');+ },+ });+ expect(result).toEqual({ accepted: false, reason: 'AUTHORIZATION_ERROR' });+ expect(events).toEqual([]);+ });++ it('enforce fails closed on a malformed evaluator decision', async () => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'enforce',+ authorizeInbound: (() => ({ reason: 'missing allowed boolean' })) as InboundDispatchDeps['authorizeInbound'],+ });+ expect(result).toEqual({ accepted: false, reason: 'AUTHORIZATION_ERROR' });+ expect(events).toEqual([]);+ });++ it('observe evaluates and reports denial without blocking', async () => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const authorizeInbound = vi.fn(() => ({ allowed: false, reason: 'would deny' }));+ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'observe',+ authorizeInbound,+ });++ expect(result.accepted).toBe(true);+ expect(authorizeInbound).toHaveBeenCalledOnce();+ expect(events).toHaveLength(1);+ expect(deps.logger.warn).toHaveBeenCalledWith(expect.stringContaining('mode=observe'));+ });++ it('legacy evaluates but preserves compatible low-risk delivery', async () => {+ const peer = mkPeer('alpha');+ const { deps, events } = withVerifier([peer], () => true);+ const authorizeInbound = vi.fn(() => ({ allowed: false, reason: 'would deny' }));+ const result = await dispatchInbound(+ 'a',+ {+ ...baseMsg('alpha'),+ metadata: { sourceNodeId: 'alpha', signature: 'valid' },+ },+ {+ ...deps,+ authorizationMode: 'legacy',+ authorizeInbound,+ },+ );++ expect(result.accepted).toBe(true);+ expect(authorizeInbound).toHaveBeenCalledOnce();+ expect(events).toHaveLength(1);+ });++ it('runs signature, authorization, and emit in that order', async () => {+ const peer = mkPeer('alpha');+ const calls: string[] = [];+ const { deps } = withVerifier([peer], () => {+ calls.push('verify');+ return true;+ });+ deps.eventBus.emit = () => {+ calls.push('emit');+ };++ const result = await dispatchInbound('a', jcsMessage(), {+ ...deps,+ authorizationMode: 'enforce',+ authorizeInbound: () => {+ calls.push('authorize');+ return { allowed: true };+ },+ });+ expect(result.accepted).toBe(true);+ expect(calls).toEqual(['verify', 'authorize', 'emit']);+ });+});+describe('canonicalizeEnvelopeForVerify', () => {it('strips signature from metadata before canonicalization', async () => {const { canonicalizeEnvelopeForVerify } = await import(@@ -298,4 +503,167 @@ describe('canonicalizeEnvelopeForVerify', () => {});expect(a).toBe(b);});++ it('recursively covers nested payload and metadata values', async () => {+ const { canonicalizeEnvelopeForVerify } = await import(+ '../../src/application/inbound-dispatcher.js'+ );+ const original = canonicalizeEnvelopeForVerify({+ id: 'm',+ type: 'claim-event',+ payload: { claim: { owner: 'agent-a', epoch: 7 }, steps: ['read', 'write'] },+ metadata: {+ sourceNodeId: 'a',+ signatureVersion: 'jcs-v1',+ grant: { actions: ['work.handoff'] },+ },+ });+ const reordered = canonicalizeEnvelopeForVerify({+ metadata: {+ grant: { actions: ['work.handoff'] },+ signatureVersion: 'jcs-v1',+ sourceNodeId: 'a',+ },+ payload: { steps: ['read', 'write'], claim: { epoch: 7, owner: 'agent-a' } },+ type: 'claim-event',+ id: 'm',+ });+ const mutated = canonicalizeEnvelopeForVerify({+ id: 'm',+ type: 'claim-event',+ payload: { claim: { owner: 'agent-b', epoch: 7 }, steps: ['read', 'write'] },+ metadata: {+ sourceNodeId: 'a',+ signatureVersion: 'jcs-v1',+ grant: { actions: ['work.handoff'] },+ },+ });++ expect(reordered).toBe(original);+ expect(mutated).not.toBe(original);+ expect(original).toContain('"claim":{"epoch":7,"owner":"agent-a"}');+ });++ it.each([+ { value: Number.NaN, label: 'non-finite number' },+ { value: -0, label: 'negative zero' },+ { value: Number.MAX_SAFE_INTEGER + 1, label: 'unsafe integer' },+ { value: undefined, label: 'undefined' },+ ])('rejects $label instead of signing ambiguous JSON', async ({ value }) => {+ const { canonicalizeEnvelopeForVerify } = await import(+ '../../src/application/inbound-dispatcher.js'+ );+ expect(() =>+ canonicalizeEnvelopeForVerify({+ id: 'm',+ type: 't',+ payload: { value },+ metadata: { sourceNodeId: 'a', signatureVersion: 'jcs-v1' },+ }),+ ).toThrow(/Federation canonicalization rejects/);+ });++ it('keeps historical bytes for a message without a version marker', async () => {+ const { canonicalizeEnvelopeForVerify } = await import(+ '../../src/application/inbound-dispatcher.js'+ );+ const message = {+ id: 'm',+ type: 'claim-event',+ payload: { claim: { owner: 'agent-a' } },+ metadata: { sourceNodeId: 'a' },+ };+ const historical = JSON.stringify(+ {+ id: message.id,+ type: message.type,+ payload: message.payload,+ metadata: message.metadata,+ },+ ['id', 'metadata', 'payload', 'type'],+ );+ const legacy = canonicalizeEnvelopeForVerify(message);+ expect(legacy).toBe(historical);+ expect(legacy).not.toContain('owner');+ });++ it('selects JCS only for an advertised peer and fails closed when required', async () => {+ const {+ DEFAULT_ENVELOPE_SIGNATURE_MODE,+ JCS_SIGNATURE_PROTOCOL,+ selectEnvelopeSignatureVersion,+ } = await import('../../src/application/inbound-dispatcher.js');+ expect(DEFAULT_ENVELOPE_SIGNATURE_MODE).toBe('prefer-jcs');+ expect(selectEnvelopeSignatureVersion('legacy', [JCS_SIGNATURE_PROTOCOL])).toBe('legacy-v1');+ expect(selectEnvelopeSignatureVersion('prefer-jcs', [])).toBe('legacy-v1');+ expect(selectEnvelopeSignatureVersion('prefer-jcs', [JCS_SIGNATURE_PROTOCOL])).toBe('jcs-v1');+ expect(selectEnvelopeSignatureVersion('prefer-jcs', [], 'heartbeat')).toBe('legacy-v1');+ expect(() => selectEnvelopeSignatureVersion('prefer-jcs', [], 'task-assignment')).toThrow(+ 'PEER_SIGNATURE_PROTOCOL_UNSUPPORTED_FOR_MESSAGE',+ );+ expect(() => selectEnvelopeSignatureVersion('require-jcs', [])).toThrow(+ 'PEER_SIGNATURE_PROTOCOL_UNSUPPORTED',+ );+ });++ it('does not downgrade a failed JCS signature to legacy bytes', async () => {+ const peer = mkPeer('alpha');+ const seen: string[] = [];+ const { deps } = withVerifier([peer], (canonical) => {+ seen.push(canonical);+ return false;+ });+ const result = await dispatchInbound(+ 'a',+ {+ ...baseMsg('alpha'),+ metadata: {+ sourceNodeId: 'alpha',+ signature: 'bad',+ signatureVersion: 'jcs-v1',+ },+ },+ deps,+ );+ expect(result).toEqual({ accepted: false, reason: 'INVALID_SIGNATURE' });+ expect(seen).toHaveLength(1);+ expect(seen[0]).toContain('"test":true');+ });++ it('rejects a nested payload mutation against the signed JCS bytes', async () => {+ const peer = mkPeer('alpha');+ const original: AgentMessage = {+ id: 'claim-1',+ type: 'claim-event',+ payload: { claim: { owner: 'agent-a', epoch: 3 } },+ metadata: {+ sourceNodeId: 'alpha',+ signature: 'valid',+ signatureVersion: 'jcs-v1',+ },+ };+ const { canonicalizeEnvelopeForVerify } = await import(+ '../../src/application/inbound-dispatcher.js'+ );+ const signedBytes = canonicalizeEnvelopeForVerify(original);+ const { deps, events } = withVerifier([peer], (canonical) => canonical === signedBytes);+ const tampered: AgentMessage = {+ ...original,+ payload: { claim: { owner: 'agent-b', epoch: 3 } },+ };++ const result = await dispatchInbound('a', tampered, deps);+ expect(result).toEqual({ accepted: false, reason: 'INVALID_SIGNATURE' });+ expect(events).toEqual([]);+ });++ it('can disable legacy verification after enforcement migration', async () => {+ const peer = mkPeer('alpha');+ const base = withVerifier([peer], () => true);+ const result = await dispatchInbound('a', baseMsg('alpha'), {+ ...base.deps,+ acceptedSignatureVersions: ['jcs-v1'],+ });+ expect(result).toEqual({ accepted: false, reason: 'INVALID_PAYLOAD' });+ });});diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.tsindex c07babb4b5..058bfdf18e 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/plugin.test.ts@@ -7,9 +7,18 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest';-import { AgentFederationPlugin } from '../../src/plugin.js';--function createMockContext() {+import {+ AgentFederationPlugin,+} from '../../src/plugin.js';+import {+ JCS_SIGNATURE_PROTOCOL,+} from '../../src/application/inbound-dispatcher.js';+import {+ FEDERATION_PLUGIN_VERSION,+} from '../../src/version.js';+import { TrustLevel } from '../../src/domain/entities/trust-level.js';++function createMockContext(configOverrides: Record<string, unknown> = {}) {return {config: {nodeId: 'test-node',@@ -17,6 +26,7 @@ function createMockContext() {complianceMode: 'none',staticPeers: [] as string[],hashSalt: 'test-salt',+ ...configOverrides,} as Record<string, unknown>,logger: {info: vi.fn(),@@ -49,8 +59,8 @@ describe('AgentFederationPlugin', () => {expect(plugin.name).toBe('@claude-flow/plugin-agent-federation');});- it('should have version set to 1.0.0-alpha.1', () => {- expect(plugin.version).toBe('1.0.0-alpha.1');+ it('should have version set to 1.0.0-alpha.17', () => {+ expect(plugin.version).toBe('1.0.0-alpha.17');});it('should have a non-empty description', () => {@@ -164,6 +174,88 @@ describe('AgentFederationPlugin', () => {expect.stringContaining('initialized'),);});++ it('trusts JCS only from a verified peer manifest, never endpoint self-negotiation', async () => {+ await plugin.initialize(context as any);+ const registered = (name: string) =>+ context.services.register.mock.calls.find(([serviceName]) => serviceName === name)?.[1] as any;+ const coordinator = registered('federation:coordinator');+ const discovery = registered('federation:discovery');+ const peerPlugin = new AgentFederationPlugin();+ const peerContext = createMockContext({+ nodeId: 'peer-node',+ endpoint: 'ws://peer.example:9100',+ hashSalt: 'peer-salt',+ });++ try {+ await coordinator.initialize({+ nodeId: 'stale-cli-node',+ publicKey: '',+ endpoint: 'ws://stale.invalid:1',+ capabilities: {+ agentTypes: ['coder'],+ maxConcurrentSessions: 1,+ supportedProtocols: ['websocket', 'http'],+ complianceModes: [],+ },+ version: '1.0.0-alpha.1',+ timestamp: new Date().toISOString(),+ });++ const localManifest = discovery.getLocalManifest();+ expect(localManifest.nodeId).toBe('test-node');+ expect(localManifest.endpoint).toBe('ws://localhost:9100');+ expect(localManifest.publicKey).toMatch(/^[0-9a-f]{64}$/);+ expect(localManifest.version).toBe(FEDERATION_PLUGIN_VERSION);+ expect(localManifest.capabilities.supportedProtocols).toContain(+ JCS_SIGNATURE_PROTOCOL,+ );++ const endpointOnly = await coordinator.joinPeer('ws://legacy.example:9100');+ const unknownPeer = discovery.getPeer(endpointOnly.remoteNodeId);+ expect(endpointOnly.trustLevel).toBe(TrustLevel.UNTRUSTED);+ expect(endpointOnly.negotiatedCapabilities).not.toContain(JCS_SIGNATURE_PROTOCOL);+ expect(unknownPeer.capabilities.supportedProtocols).not.toContain(+ JCS_SIGNATURE_PROTOCOL,+ );++ await peerPlugin.initialize(peerContext as any);+ const peerRegistered = (name: string) =>+ peerContext.services.register.mock.calls+ .find(([serviceName]) => serviceName === name)?.[1] as any;+ const peerCoordinator = peerRegistered('federation:coordinator');+ const peerDiscovery = peerRegistered('federation:discovery');+ await peerCoordinator.initialize({+ nodeId: 'ignored',+ publicKey: '',+ endpoint: 'ws://ignored.invalid:1',+ capabilities: {+ agentTypes: ['reviewer'],+ maxConcurrentSessions: 1,+ supportedProtocols: ['websocket', 'http'],+ complianceModes: [],+ },+ version: 'stale',+ timestamp: new Date().toISOString(),+ });+ const signedPeerManifest = peerDiscovery.getLocalManifest();++ const verified = await coordinator.joinPeer(+ signedPeerManifest.endpoint,+ signedPeerManifest,+ );+ const verifiedPeer = discovery.getPeer(verified.remoteNodeId);+ expect(verified.trustLevel).toBe(TrustLevel.VERIFIED);+ expect(verified.negotiatedCapabilities).toContain(JCS_SIGNATURE_PROTOCOL);+ expect(verifiedPeer.capabilities.supportedProtocols).toContain(+ JCS_SIGNATURE_PROTOCOL,+ );+ } finally {+ await peerPlugin.shutdown();+ await plugin.shutdown();+ }+ });});describe('shutdown', () => {diff --git a/v3/@claude-flow/plugin-agent-federation/package.json b/v3/@claude-flow/plugin-agent-federation/package.jsonindex b2531c3a8d..3b88ac3389 100644--- a/v3/@claude-flow/plugin-agent-federation/package.json+++ b/v3/@claude-flow/plugin-agent-federation/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/plugin-agent-federation",- "version": "1.0.0-alpha.16",+ "version": "1.0.0-alpha.17","description": "Cross-installation agent federation with zero-trust security, PII-gated data flow, and compliance-grade audit trails.","homepage": "https://github.com/ruvnet/ruflo","type": "module",@@ -16,6 +16,7 @@],"scripts": {"build": "tsc",+ "benchmark:canonicalization": "npm run build && node scripts/benchmark-envelope-canonicalization.mjs","test": "vitest run","test:watch": "vitest","clean": "rm -rf dist"diff --git a/v3/@claude-flow/plugin-agent-federation/scripts/benchmark-envelope-canonicalization.mjs b/v3/@claude-flow/plugin-agent-federation/scripts/benchmark-envelope-canonicalization.mjsnew file mode 100644index 0000000000..df59d050be--- /dev/null+++ b/v3/@claude-flow/plugin-agent-federation/scripts/benchmark-envelope-canonicalization.mjs@@ -0,0 +1,72 @@+import { performance } from 'node:perf_hooks';+import { canonicalizeEnvelopeForVerify } from '../dist/application/inbound-dispatcher.js';++const iterations = Number.parseInt(process.env.BENCH_ITERATIONS ?? '50000', 10);+if (!Number.isSafeInteger(iterations) || iterations < 1000) {+ throw new Error('BENCH_ITERATIONS must be a safe integer >= 1000');+}++const payload = {+ claim: {+ claimId: 'claim-136',+ owner: 'spiffe://cognitum.one/agent/coder-7',+ epoch: '42',+ resource: 'ruflo://repo/ruvnet/ruflo/issues/136',+ },+ evidence: Array.from({ length: 8 }, (_, index) => ({+ id: `ev-${index}`,+ digest: `sha256:${String(index).padStart(64, '0')}`,+ provenance: 'system_observation',+ })),+ limits: {+ actions: ['work.handoff'],+ resources: ['ruflo://repo/ruvnet/ruflo/issues/136'],+ maxConcurrency: 1,+ },+};++const message = {+ id: 'message-136',+ type: 'claim-event',+ payload,+ metadata: {+ sourceNodeId: 'node-a',+ targetNodeId: 'node-b',+ sessionId: 'session-1',+ signatureVersion: 'jcs-v1',+ grant: { id: 'grant-1', actions: ['work.handoff'] },+ },+};++for (let index = 0; index < 1000; index += 1) {+ canonicalizeEnvelopeForVerify(message);+}++const samples = [];+let bytes = 0;+for (let batch = 0; batch < 30; batch += 1) {+ const started = performance.now();+ for (let index = 0; index < iterations; index += 1) {+ bytes += canonicalizeEnvelopeForVerify(message).length;+ }+ samples.push((performance.now() - started) / iterations);+}++samples.sort((a, b) => a - b);+const percentile = (value) => samples[Math.min(samples.length - 1, Math.floor(samples.length * value))];+const result = {+ node: process.version,+ platform: `${process.platform}-${process.arch}`,+ batches: samples.length,+ iterationsPerBatch: iterations,+ payloadBytes: Buffer.byteLength(JSON.stringify(message)),+ canonicalBytes: bytes / (samples.length * iterations),+ latencyMicroseconds: {+ p50: percentile(0.5) * 1000,+ p95: percentile(0.95) * 1000,+ p99: percentile(0.99) * 1000,+ },+ throughputPerSecond: 1000 / percentile(0.5),+};++console.log(JSON.stringify(result, null, 2));diff --git a/v3/@claude-flow/plugin-agent-federation/src/application/claim-checker.ts b/v3/@claude-flow/plugin-agent-federation/src/application/claim-checker.tsnew file mode 100644index 0000000000..ee6d57afbc--- /dev/null+++ b/v3/@claude-flow/plugin-agent-federation/src/application/claim-checker.ts@@ -0,0 +1,65 @@+import type { FederationClaimType, PolicyEngineDeps } from './policy-engine.js';++export type FederationAuthorizationMode = 'legacy' | 'observe' | 'enforce';++const FEDERATION_CLAIMS = new Set<FederationClaimType>([+ 'federation:discover',+ 'federation:connect',+ 'federation:read',+ 'federation:write',+ 'federation:admin',+ 'federation:memory',+ 'federation:spawn',+]);++export interface FederationClaimCheckerConfig {+ mode?: FederationAuthorizationMode;+ grantedClaims?: readonly string[];+ onObservation?: (claim: FederationClaimType, granted: boolean) => void;+}++export interface FederationClaimChecker {+ mode: FederationAuthorizationMode;+ grantedClaims: ReadonlySet<FederationClaimType>;+ checkClaim: PolicyEngineDeps['checkClaim'];+}++/**+ * Compatibility bridge for the legacy federation policy engine.+ *+ * This removes the anonymous `() => true` production stub and makes+ * compatibility behavior explicit:+ * - legacy: preserve pre-ADR-325 behavior;+ * - observe: calculate and report missing grants without blocking;+ * - enforce: default deny unless the exact claim is configured.+ *+ * ADR-324 policy adapters can supply the `grantedClaims` set after evaluating+ * the request; ownership-changing federation messages remain disabled in the+ * default message policy until the full ingress PEP is composed.+ */+export function createFederationClaimChecker(+ config: FederationClaimCheckerConfig = {},+): FederationClaimChecker {+ const mode = config.mode ?? 'legacy';+ if (mode !== 'legacy' && mode !== 'observe' && mode !== 'enforce') {+ throw new TypeError(`Unsupported federation authorization mode: ${String(mode)}`);+ }++ const grantedClaims = new Set<FederationClaimType>();+ for (const claim of config.grantedClaims ?? []) {+ if (!FEDERATION_CLAIMS.has(claim as FederationClaimType)) {+ throw new TypeError(`Unknown federation claim: ${claim}`);+ }+ grantedClaims.add(claim as FederationClaimType);+ }++ return {+ mode,+ grantedClaims,+ checkClaim: (claim) => {+ const granted = grantedClaims.has(claim);+ if (mode === 'observe') config.onObservation?.(claim, granted);+ return mode !== 'enforce' || granted;+ },+ };+}diff --git a/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts b/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.tsindex beff85d505..08a5d1b90e 100644--- a/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/application/federation-coordinator.ts@@ -50,6 +50,9 @@ export interface FederationCoordinatorConfig {readonly publicKey: string;readonly endpoint: string;readonly capabilities: readonly string[];+ /** Wire protocols this runtime is prepared to advertise and negotiate. */+ readonly supportedProtocols?: readonly string[];+ readonly version?: string;}export interface FederationStatus {@@ -163,7 +166,21 @@ export class FederationCoordinator {}async initialize(manifest: Omit<FederationManifest, 'signature'>): Promise<void> {- await this.discovery.publishManifest(manifest);+ // The coordinator's keypair and runtime protocol configuration are+ // authoritative. CLI/MCP callers may describe agent/compliance capacity,+ // but cannot replace the identity created by the plugin.+ await this.discovery.publishManifest({+ ...manifest,+ nodeId: this.config.nodeId,+ publicKey: this.config.publicKey,+ endpoint: this.config.endpoint,+ capabilities: {+ ...manifest.capabilities,+ supportedProtocols:+ this.config.supportedProtocols ?? manifest.capabilities.supportedProtocols,+ },+ version: this.config.version ?? manifest.version,+ });this.discovery.startPeriodicDiscovery();this.initialized = true;@@ -188,17 +205,20 @@ export class FederationCoordinator {this.initialized = false;}- async joinPeer(endpoint: string): Promise<FederationSession> {+ async joinPeer(+ endpoint: string,+ manifest?: FederationManifest,+ ): Promise<FederationSession> {this.ensureInitialized();- const node = await this.discovery.addStaticPeer(endpoint);+ const node = await this.discovery.addStaticPeer(endpoint, manifest);await this.audit.log('peer_discovered', {targetNodeId: node.nodeId,metadata: { endpoint },});- return this.establishSession(node);+ return this.establishSession(node, manifest !== undefined);}async leavePeer(nodeId: string): Promise<void> {@@ -626,36 +646,30 @@ export class FederationCoordinator {return Array.from(this.sessions.values()).filter(s => s.active && !s.isExpired());}- private async establishSession(node: FederationNode): Promise<FederationSession> {- await this.audit.log('handshake_initiated', { targetNodeId: node.nodeId });-- const challenge = await this.handshake.initiateHandshake(node);- const response = await this.handshake.respondToHandshake(challenge);- const result = await this.handshake.verifyChallenge(response, node);-- if (!result.success || !result.session) {- await this.audit.log('handshake_failed', {- targetNodeId: node.nodeId,- metadata: { error: result.error },- });- throw new Error(`Handshake failed: ${result.error}`);- }-- this.sessions.set(result.session.sessionId, result.session);+ private async establishSession(+ node: FederationNode,+ verifiedManifest: boolean,+ ): Promise<FederationSession> {+ const session = this.handshake.establishDiscoverySession(node, verifiedManifest);+ this.sessions.set(session.sessionId, session);await this.audit.log('handshake_completed', {targetNodeId: node.nodeId,- sessionId: result.session.sessionId,- trustLevel: result.session.trustLevel,+ sessionId: session.sessionId,+ trustLevel: session.trustLevel,+ metadata: {+ mode: verifiedManifest ? 'verified-manifest' : 'endpoint-only',+ liveChallengeAuthenticated: false,+ },});await this.audit.log('session_created', {- sessionId: result.session.sessionId,+ sessionId: session.sessionId,targetNodeId: node.nodeId,- trustLevel: result.session.trustLevel,+ trustLevel: session.trustLevel,});- return result.session;+ return session;}private findSessionByNodeId(nodeId: string): FederationSession | undefined {diff --git a/v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts b/v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.tsindex 0a72f07d48..0a0cc71bfa 100644--- a/v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts@@ -22,6 +22,7 @@import type { AgentMessage } from '../transport/midstream-aware-loader.js';import type { DiscoveryService } from '../domain/services/discovery-service.js';import type { AuditService } from '../domain/services/audit-service.js';+import type { FederationNode } from '../domain/entities/federation-node.js';import { FederationNodeState } from '../domain/value-objects/federation-node-state.js';/** What gets emitted on the event bus per messageType. */@@ -34,7 +35,10 @@ export type InboundRejectionReason =| 'PEER_EVICTED'| 'MISSING_METADATA'| 'INVALID_PAYLOAD'- | 'INVALID_SIGNATURE';+ | 'INVALID_SIGNATURE'+ | 'LEGACY_SIGNATURE_TYPE_REJECTED'+ | 'AUTHORIZATION_DENIED'+ | 'AUTHORIZATION_ERROR';/*** Verifier function for inbound envelopes. Given the canonical bytes of@@ -52,6 +56,50 @@ export type EnvelopeVerifier = (peerPublicKeyHex: string,) => boolean;+export const JCS_SIGNATURE_PROTOCOL = 'ruflo-signature-jcs-v1' as const;+export type EnvelopeSignatureVersion = 'legacy-v1' | 'jcs-v1';+export type EnvelopeSignatureMode = 'legacy' | 'prefer-jcs' | 'require-jcs';+/**+ * Updated peers advertise and negotiate recursively complete JCS signatures+ * without operator configuration. Legacy mode remains explicit for low-risk+ * heartbeat/status interoperability only.+ */+export const DEFAULT_ENVELOPE_SIGNATURE_MODE: EnvelopeSignatureMode = 'prefer-jcs';+export type InboundAuthorizationMode = 'legacy' | 'observe' | 'enforce';++/**+ * The historical serializer does not authenticate nested payload fields.+ * Keep it available only for messages whose payload cannot mutate federation+ * state or transfer data/ownership. Unknown types are intentionally denied.+ */+const LEGACY_V1_LOW_RISK_MESSAGE_TYPES: ReadonlySet<string> = new Set([+ 'heartbeat',+ 'status-broadcast',+]);++export function isLegacyEnvelopeTypeAllowed(messageType: string): boolean {+ return LEGACY_V1_LOW_RISK_MESSAGE_TYPES.has(messageType);+}++export interface InboundAuthorizationRequest {+ readonly address: string;+ readonly sourceNodeId: string;+ readonly messageType: string;+ readonly message: AgentMessage;+ readonly peer: FederationNode;+ readonly signatureVersion: EnvelopeSignatureVersion;+ readonly messageSizeBytes: number;+}++export interface InboundAuthorizationDecision {+ readonly allowed: boolean;+ readonly reason?: string;+}++export type InboundAuthorizationEvaluator = (+ request: InboundAuthorizationRequest,+) => InboundAuthorizationDecision | Promise<InboundAuthorizationDecision>;+/** Dispatch dependencies (kept narrow for testability). */export interface InboundDispatchDeps {readonly discovery: Pick<DiscoveryService, 'getPeer'>;@@ -69,22 +117,124 @@ export interface InboundDispatchDeps {* When OMITTED, the dispatcher operates in legacy "trust the metadata"* mode (backward compat for tests that inject minimal deps). Production* MUST inject this — see the plugin.ts wiring.- */+ */readonly verifyEnvelope?: EnvelopeVerifier;+ /** Defaults to both versions; enforce-only deployments pass `['jcs-v1']`. */+ readonly acceptedSignatureVersions?: readonly EnvelopeSignatureVersion[];+ /** Compatibility mode defaults to legacy; enforce is fail-closed. */+ readonly authorizationMode?: InboundAuthorizationMode;+ /** Injected policy decision point. It is always called before event emission. */+ readonly authorizeInbound?: InboundAuthorizationEvaluator;}/**- * Canonical serialization of an envelope for signing. Sorts keys to- * make the signed bytes deterministic regardless of object construction- * order. Excludes the `signature` field itself (it's what we're- * verifying).+ * Canonical serialization of an envelope for signing. This is the+ * RFC 8785/JCS-compatible subset used by federation v1 while v2 schema+ * negotiation is introduced. It recursively sorts object keys and rejects+ * values outside the I-JSON-safe subset instead of silently dropping them.+ * The `signature` field itself is excluded because it is what we verify.** Federation messages are wrapped as `AgentMessage{id, type, payload,* metadata}` on the wire. The `payload` is the actual FederationEnvelope* (per `plugin.ts sendToNode`); we canonicalize the payload + the* metadata so the receiver verifies the same bytes the sender signed.*/-export function canonicalizeEnvelopeForVerify(message: AgentMessage): string {+function canonicalizeJcsValue(value: unknown, ancestors: Set<object>): string {+ if (value === null) return 'null';++ switch (typeof value) {+ case 'boolean':+ return value ? 'true' : 'false';+ case 'string':+ return JSON.stringify(value);+ case 'number':+ if (!Number.isFinite(value) || Object.is(value, -0)) {+ throw new TypeError('Federation canonicalization rejects non-canonical numbers');+ }+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {+ throw new TypeError('Federation canonicalization rejects unsafe integers');+ }+ return JSON.stringify(value);+ case 'bigint':+ case 'function':+ case 'symbol':+ case 'undefined':+ throw new TypeError(`Federation canonicalization rejects ${typeof value}`);+ case 'object':+ break;+ default:+ throw new TypeError(`Federation canonicalization rejects ${typeof value}`);+ }++ const object = value as object;+ if (ancestors.has(object)) {+ throw new TypeError('Federation canonicalization rejects cyclic values');+ }+ ancestors.add(object);++ try {+ if (Array.isArray(value)) {+ const items: string[] = [];+ for (let index = 0; index < value.length; index += 1) {+ if (!Object.prototype.hasOwnProperty.call(value, index)) {+ throw new TypeError('Federation canonicalization rejects sparse arrays');+ }+ items.push(canonicalizeJcsValue(value[index], ancestors));+ }+ return `[${items.join(',')}]`;+ }++ const prototype = Object.getPrototypeOf(value);+ if (prototype !== Object.prototype && prototype !== null) {+ throw new TypeError('Federation canonicalization accepts only plain objects');+ }++ const record = value as Record<string, unknown>;+ const entries = Object.keys(record)+ .sort()+ .map((key) => `${JSON.stringify(key)}:${canonicalizeJcsValue(record[key], ancestors)}`);+ return `{${entries.join(',')}}`;+ } finally {+ ancestors.delete(object);+ }+}++function envelopeSignatureVersion(message: AgentMessage): EnvelopeSignatureVersion {+ const version = (message.metadata as Record<string, unknown> | undefined)?.signatureVersion;+ if (version === undefined) return 'legacy-v1';+ if (version === 'jcs-v1') return version;+ throw new TypeError(`Unsupported federation signature version: ${String(version)}`);+}++export function selectEnvelopeSignatureVersion(+ mode: EnvelopeSignatureMode,+ peerProtocols: readonly string[],+ messageType?: string,+): EnvelopeSignatureVersion {+ const selected = mode === 'legacy'+ ? 'legacy-v1'+ : peerProtocols.includes(JCS_SIGNATURE_PROTOCOL)+ ? 'jcs-v1'+ : mode === 'prefer-jcs'+ ? 'legacy-v1'+ : null;+ if (selected === null) {+ throw new Error('PEER_SIGNATURE_PROTOCOL_UNSUPPORTED');+ }+ if (+ selected === 'legacy-v1'+ && messageType !== undefined+ && !isLegacyEnvelopeTypeAllowed(messageType)+ ) {+ throw new Error(`PEER_SIGNATURE_PROTOCOL_UNSUPPORTED_FOR_MESSAGE: ${messageType}`);+ }+ return selected;+}++export function canonicalizeEnvelopeForVerify(+ message: AgentMessage,+ requestedVersion?: EnvelopeSignatureVersion,+): string {const meta = (message.metadata ?? {}) as Record<string, unknown>;// Strip signature from metadata if present (we verify the rest)const { signature: _sig, ...metaForSig } = meta;@@ -94,8 +244,14 @@ export function canonicalizeEnvelopeForVerify(message: AgentMessage): string {payload: message.payload,metadata: metaForSig,};- // Sort keys for determinism- return JSON.stringify(canon, Object.keys(canon).sort());+ const version = requestedVersion ?? envelopeSignatureVersion(message);+ if (version === 'legacy-v1') {+ // Byte-for-byte compatibility with releases through 1.0.0-alpha.16.+ // Its recursive array replacer omits nested fields, so legacy messages+ // cannot become privileged ownership mutations.+ return JSON.stringify(canon, Object.keys(canon).sort());+ }+ return canonicalizeJcsValue(canon, new Set());}/** Outcome reported to the caller (mostly for tests + observability). */@@ -155,14 +311,41 @@ export async function dispatchInbound(return { accepted: false, reason: 'PEER_EVICTED' };}+ let signatureVersion: EnvelopeSignatureVersion;+ let canonicalEnvelope: string;+ try {+ signatureVersion = envelopeSignatureVersion(message);+ const accepted = deps.acceptedSignatureVersions ?? ['legacy-v1', 'jcs-v1'];+ if (!accepted.includes(signatureVersion)) {+ throw new TypeError(`Signature version ${signatureVersion} is disabled`);+ }+ canonicalEnvelope = canonicalizeEnvelopeForVerify(message, signatureVersion);+ } catch {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: { address, reason: 'INVALID_PAYLOAD' },+ });+ deps.logger.warn(`Inbound rejected: non-canonical payload from ${sourceNodeId} (addr=${address})`);+ return { accepted: false, reason: 'INVALID_PAYLOAD' };+ }+// Cryptographic signature verification (closes the trust gate that// peer-state checks alone don't provide — without this, a malicious// sender could just claim sourceNodeId='known-peer' in metadata and// pass the previous gates).if (deps.verifyEnvelope) {const sig = typeof meta.signature === 'string' ? meta.signature : null;- const canon = canonicalizeEnvelopeForVerify(message);- const ok = deps.verifyEnvelope(canon, sig, peer.publicKey);+ let ok = false;+ try {+ ok = deps.verifyEnvelope(canonicalEnvelope, sig, peer.publicKey);+ } catch {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: { address, reason: 'INVALID_PAYLOAD' },+ });+ deps.logger.warn(`Inbound rejected: non-canonical payload from ${sourceNodeId} (addr=${address})`);+ return { accepted: false, reason: 'INVALID_PAYLOAD' };+ }if (!ok) {await deps.audit.log('message_rejected', {sourceNodeId,@@ -173,6 +356,99 @@ export async function dispatchInbound(}}+ // The legacy serializer omits nested fields. No policy grant can make those+ // unauthenticated bytes safe for a consequential operation, so this gate is+ // independent of authorization compatibility mode.+ if (+ signatureVersion === 'legacy-v1' &&+ !isLegacyEnvelopeTypeAllowed(message.type)+ ) {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: {+ address,+ reason: 'LEGACY_SIGNATURE_TYPE_REJECTED',+ messageType: message.type,+ },+ });+ deps.logger.warn(+ `Inbound rejected: legacy-v1 is not permitted for message type ${message.type} ` ++ `from ${sourceNodeId}`,+ );+ return { accepted: false, reason: 'LEGACY_SIGNATURE_TYPE_REJECTED' };+ }++ const authorizationMode = deps.authorizationMode ?? 'legacy';+ if (+ authorizationMode !== 'legacy' &&+ authorizationMode !== 'observe' &&+ authorizationMode !== 'enforce'+ ) {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: { address, reason: 'AUTHORIZATION_ERROR' },+ });+ return { accepted: false, reason: 'AUTHORIZATION_ERROR' };+ }++ let authorizationDecision: InboundAuthorizationDecision | undefined;+ if (deps.authorizeInbound) {+ try {+ const decision = await deps.authorizeInbound({+ address,+ sourceNodeId,+ messageType: message.type,+ message,+ peer,+ signatureVersion,+ messageSizeBytes: new TextEncoder().encode(canonicalEnvelope).byteLength,+ });+ if (!decision || typeof decision.allowed !== 'boolean') {+ throw new TypeError('Inbound authorization evaluator returned an invalid decision');+ }+ authorizationDecision = decision;+ } catch {+ if (authorizationMode === 'enforce') {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: { address, reason: 'AUTHORIZATION_ERROR', messageType: message.type },+ });+ deps.logger.warn(`Inbound authorization failed for ${sourceNodeId} (addr=${address})`);+ return { accepted: false, reason: 'AUTHORIZATION_ERROR' };+ }+ deps.logger.warn(+ `Inbound authorization observation failed for ${sourceNodeId} (mode=${authorizationMode})`,+ );+ }+ } else if (authorizationMode === 'enforce') {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: { address, reason: 'AUTHORIZATION_ERROR', messageType: message.type },+ });+ deps.logger.warn('Inbound rejected: enforce mode has no authorization evaluator');+ return { accepted: false, reason: 'AUTHORIZATION_ERROR' };+ }++ if (authorizationDecision && !authorizationDecision.allowed) {+ if (authorizationMode === 'enforce') {+ await deps.audit.log('message_rejected', {+ sourceNodeId,+ metadata: {+ address,+ reason: 'AUTHORIZATION_DENIED',+ messageType: message.type,+ policyReason: authorizationDecision.reason,+ },+ });+ deps.logger.warn(`Inbound authorization denied for ${sourceNodeId} (addr=${address})`);+ return { accepted: false, reason: 'AUTHORIZATION_DENIED' };+ }+ deps.logger.warn(+ `Inbound authorization would deny ${message.type} from ${sourceNodeId} ` ++ `(mode=${authorizationMode})`,+ );+ }+// Touch lastSeen on every successful inbound — drives the// discovery service's stale-peer detection.peer.markSeen();@@ -184,6 +460,8 @@ export async function dispatchInbound(address,messageType: message.type,messageId: message.id,+ authorizationMode,+ authorizationAllowed: authorizationDecision?.allowed,},});diff --git a/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts b/v3/@claude-flow/plugin-agent-federation/src/cli-commands.tsindex 6ca9294041..a490bc81ff 100644--- a/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts@@ -1,6 +1,10 @@+import { readFileSync } from 'node:fs';import type { CLICommandDefinition, PluginContext } from '@claude-flow/shared/src/plugin-interface.js';import type { FederationCoordinator } from './application/federation-coordinator.js';+import { JCS_SIGNATURE_PROTOCOL } from './application/inbound-dispatcher.js';import { getTrustLevelLabel, TrustLevel } from './domain/entities/trust-level.js';+import type { FederationManifest } from './domain/services/discovery-service.js';+import { FEDERATION_PLUGIN_VERSION } from './version.js';type CoordinatorGetter = () => FederationCoordinator | null;type ContextGetter = () => PluginContext | null;@@ -11,6 +15,20 @@ function requireCoordinator(get: CoordinatorGetter): FederationCoordinator {return c;}+function readPeerManifest(value: unknown): FederationManifest | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== 'string' || value.trim().length === 0) {+ throw new TypeError('Peer manifest must be a JSON string or file path');+ }+ const input = value.trim();+ const json = input.startsWith('{') ? input : readFileSync(input, 'utf8');+ const parsed = JSON.parse(json) as unknown;+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new TypeError('Peer manifest must be a JSON object');+ }+ return parsed as FederationManifest;+}+export function createCliCommands(getCoordinator: CoordinatorGetter,getContext: ContextGetter,@@ -34,10 +52,10 @@ export function createCliCommands(capabilities: {agentTypes: ['coder', 'reviewer', 'tester'],maxConcurrentSessions: 10,- supportedProtocols: ['websocket', 'http'],+ supportedProtocols: ['websocket', 'http', JCS_SIGNATURE_PROTOCOL],complianceModes: [args['compliance'] as string],},- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,timestamp: new Date().toISOString(),});console.log(`Federation initialized: ${nodeId} at ${args['endpoint']}`);@@ -45,11 +63,17 @@ export function createCliCommands(},{name: 'federation join',- description: 'Join a federation by connecting to a peer endpoint',+ description: 'Join a federation endpoint; supply a signed peer manifest to negotiate consequential protocols',arguments: [{ name: 'endpoint', description: 'Remote peer endpoint', required: true }],+ options: [+ { name: 'manifest', short: 'm', description: 'Signed peer manifest as JSON or a file path', type: 'string' },+ ],handler: async (args) => {const coordinator = requireCoordinator(getCoordinator);- const session = await coordinator.joinPeer(args._[0]!);+ const session = await coordinator.joinPeer(+ args._[0]!,+ readPeerManifest(args['manifest']),+ );console.log(`Joined peer. Session: ${session.sessionId}`);console.log(`Trust level: ${getTrustLevelLabel(session.trustLevel)}`);console.log(`Capabilities: ${session.negotiatedCapabilities.join(', ')}`);@@ -90,9 +114,15 @@ export function createCliCommands(name: 'federation peers add',description: 'Add a static peer to the federation',arguments: [{ name: 'endpoint', description: 'Peer endpoint to add', required: true }],+ options: [+ { name: 'manifest', short: 'm', description: 'Signed peer manifest as JSON or a file path', type: 'string' },+ ],handler: async (args) => {const coordinator = requireCoordinator(getCoordinator);- const session = await coordinator.joinPeer(args._[0]!);+ const session = await coordinator.joinPeer(+ args._[0]!,+ readPeerManifest(args['manifest']),+ );console.log(`Peer added and connected. Session: ${session.sessionId}`);},},diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.tsindex 4c92bfe7b5..cd2d5eccd8 100644--- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/discovery-service.ts@@ -103,6 +103,9 @@ export class DiscoveryService {async addStaticPeer(endpoint: string, manifest?: FederationManifest): Promise<FederationNode> {if (manifest) {+ if (manifest.endpoint !== endpoint) {+ throw new Error(`Manifest endpoint mismatch: expected ${endpoint}`);+ }const valid = await this.deps.verifyManifest(manifest);if (!valid) {throw new Error(`Invalid manifest signature for endpoint: ${endpoint}`);diff --git a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.tsindex eec9fa1662..651a63fee8 100644--- a/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/domain/services/handshake-service.ts@@ -141,6 +141,40 @@ export class HandshakeService {return { success: true, session };}+ /**+ * Establish a capability-limited session from discovery evidence.+ *+ * A signed manifest proves that the advertised key bound the protocol list;+ * it does not prove live challenge response, so this path never elevates+ * beyond VERIFIED. Endpoint-only peers remain UNTRUSTED with no negotiated+ * optional capabilities. A future wire handshake may elevate either session+ * after authenticating a response received from the remote process.+ */+ establishDiscoverySession(+ remoteNode: FederationNode,+ verifiedManifest: boolean,+ ): FederationSession {+ const remoteCapabilities = verifiedManifest+ ? remoteNode.capabilities.supportedProtocols+ : [];+ const negotiatedCapabilities = this.deps.getLocalCapabilities().filter(+ (capability) => remoteCapabilities.includes(capability),+ );+ const now = new Date();+ return new FederationSession({+ sessionId: this.deps.generateSessionId(),+ localNodeId: this.deps.getLocalNodeId(),+ remoteNodeId: remoteNode.nodeId,+ trustLevel: verifiedManifest ? TrustLevel.VERIFIED : TrustLevel.UNTRUSTED,+ negotiatedCapabilities,+ createdAt: now,+ expiresAt: new Date(now.getTime() + this.config.sessionTtlMs),+ heartbeatInterval: this.config.heartbeatIntervalMs,+ sessionToken: this.deps.generateSessionToken(),+ metrics: FederationSession.createMetrics(),+ });+ }+renewSession(session: FederationSession): FederationSession {const remainingTtl = this.config.maxSessionTtlMs - (Date.now() - session.createdAt.getTime());const renewalTtl = Math.min(this.config.sessionTtlMs, remainingTtl);diff --git a/v3/@claude-flow/plugin-agent-federation/src/index.ts b/v3/@claude-flow/plugin-agent-federation/src/index.tsindex df5993e4f9..df1097d5c8 100644--- a/v3/@claude-flow/plugin-agent-federation/src/index.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/index.ts@@ -114,6 +114,22 @@ export {type PolicyEvaluationResult,type PolicyEngineDeps,} from './application/policy-engine.js';+export {+ createFederationClaimChecker,+ type FederationAuthorizationMode,+ type FederationClaimChecker,+ type FederationClaimCheckerConfig,+} from './application/claim-checker.js';+export {+ DEFAULT_ENVELOPE_SIGNATURE_MODE,+ JCS_SIGNATURE_PROTOCOL,+ canonicalizeEnvelopeForVerify,+ isLegacyEnvelopeTypeAllowed,+ selectEnvelopeSignatureVersion,+ type EnvelopeSignatureMode,+ type EnvelopeSignatureVersion,+} from './application/inbound-dispatcher.js';+export { FEDERATION_PLUGIN_VERSION } from './version.js';// A2A (Agent2Agent, Linux Foundation) Agent Card adapter — cards only.export {diff --git a/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts b/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.tsindex 5c51c602ed..10a322c4b1 100644--- a/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts@@ -2,8 +2,11 @@ import type { MCPToolDefinition } from '@claude-flow/shared/src/plugin-interfaceimport type { PluginContext } from '@claude-flow/shared/src/plugin-interface.js';import type { FederationCoordinator } from './application/federation-coordinator.js';import type { FederationMessageType } from './domain/entities/federation-envelope.js';+import type { FederationManifest } from './domain/services/discovery-service.js';import type { WgMeshService } from './domain/services/wg-mesh-service.js';import { generateWgKeyPair } from './domain/value-objects/wg-config.js';+import { JCS_SIGNATURE_PROTOCOL } from './application/inbound-dispatcher.js';+import { FEDERATION_PLUGIN_VERSION } from './version.js';type CoordinatorGetter = () => FederationCoordinator | null;type ContextGetter = () => PluginContext | null;@@ -34,7 +37,7 @@ export function createMcpTools(name: 'federation_init',description: 'Initialize federation on this node with a manifest and begin discovery',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -54,10 +57,10 @@ export function createMcpTools(capabilities: {agentTypes: (params['agentTypes'] as string[]) ?? ['coder', 'reviewer'],maxConcurrentSessions: 10,- supportedProtocols: ['websocket', 'http'],+ supportedProtocols: ['websocket', 'http', JCS_SIGNATURE_PROTOCOL],complianceModes: [],},- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,timestamp: new Date().toISOString(),});return textResult(`Federation initialized for node ${nodeId}`);@@ -65,19 +68,26 @@ export function createMcpTools(},{name: 'federation_join',- description: 'Join a federation by connecting to a remote peer endpoint',+ description: 'Join a federation endpoint. A signed manifest is required before consequential protocol capabilities are trusted.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {endpoint: { type: 'string', description: 'Remote peer endpoint to join' },+ manifest: {+ type: 'object',+ description: 'Optional signed peer manifest. Without it the session remains endpoint-only, untrusted, and legacy-low-risk.',+ },},required: ['endpoint'],},handler: async (params) => {const coordinator = requireCoordinator();- const session = await coordinator.joinPeer(params['endpoint'] as string);+ const session = await coordinator.joinPeer(+ params['endpoint'] as string,+ params['manifest'] as FederationManifest | undefined,+ );return textResult(`Joined peer. Session: ${session.sessionId}, Trust: ${session.trustLevel}`);},},@@ -85,7 +95,7 @@ export function createMcpTools(name: 'federation_peers',description: 'List all known federation peers with their trust levels and status',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {},@@ -100,7 +110,7 @@ export function createMcpTools(name: 'federation_send',description: 'Send a message to a federated peer through the PII pipeline and security gates. Optional budget controls (ADR-097): maxHops defaults to 8 to prevent recursive delegation; maxTokens/maxUsd cap cumulative spend across the hop chain.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -157,7 +167,7 @@ export function createMcpTools(name: 'federation_query',description: 'Query federated memory from a remote peer (PII-gated)',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -181,7 +191,7 @@ export function createMcpTools(name: 'federation_status',description: 'Get federation health status including active sessions, peers, and trust levels',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {},@@ -195,7 +205,7 @@ export function createMcpTools(name: 'federation_trust',description: 'View or review trust score details for a specific node',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -218,7 +228,7 @@ export function createMcpTools(name: 'federation_audit',description: 'Query federation audit logs with optional compliance mode filtering',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -247,7 +257,7 @@ export function createMcpTools(name: 'federation_breaker_status',description: 'ADR-097 Phase 4: per-peer circuit-breaker state snapshot. Returns each known peer with its lifecycle state (ACTIVE/SUSPENDED/EVICTED), when it changed, and why. Combine with federation_evict / federation_reactivate to operate the breaker manually.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -267,7 +277,7 @@ export function createMcpTools(name: 'federation_evict',description: 'ADR-097 Phase 4: operator-initiated evict for a peer. Marks the peer EVICTED so subsequent federation_send calls short-circuit with PEER_EVICTED. Reversible only via federation_reactivate (operator override).',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -293,7 +303,7 @@ export function createMcpTools(name: 'federation_reactivate',description: 'ADR-097 Phase 4: operator-initiated reactivate for a SUSPENDED or EVICTED peer. Used after a health probe confirms recovery, or as an operator override on a manual evict. The breaker does NOT auto-reactivate; this MCP tool is the explicit lever.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -318,7 +328,7 @@ export function createMcpTools(name: 'federation_report_spend',description: 'ADR-097 Phase 3 upstream: report the actual cost of a completed federated call. Fans out to the cost-tracker bus (via the integrator-wired SpendReporter) and the breaker service (so its in-memory rolling buffer is fed). Both targets are optional; calling without either configured is a silent no-op.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -348,7 +358,7 @@ export function createMcpTools(name: 'federation_consensus',description: 'Propose a federated consensus operation across all active peers',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -381,7 +391,7 @@ export function createMcpTools(name: 'federation_wg_status',description: 'ADR-111 Phase 6: WG mesh state — per-peer trust level, mesh IP, suspended/evicted flags, and the AllowedIPs slice each peer currently has. Use to inspect what the breaker has propagated to the L3 layer.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -406,7 +416,7 @@ export function createMcpTools(name: 'federation_wg_attest',description: 'ADR-111 Phase 6 (witness chain): emit an operator-signed attestation entry for a coordination change. Returns the canonical bytes the operator signs + the witness entry; operator appends it to .claude-flow/federation/wg-changes.log. Idempotent — re-attesting the same change just appends another entry.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {@@ -433,7 +443,7 @@ export function createMcpTools(name: 'federation_wg_keyrotate',description: 'ADR-111 Phase 6: rotate the local WG keypair. Returns the new public key + recommended next steps (republish manifest, peers regenerate their wg-quick config, grace-period destruction of old key). DESTRUCTIVE — the old private key is overwritten on disk; existing tunnels are dropped until peers update.',pluginName: '@claude-flow/plugin-agent-federation',- version: '1.0.0-alpha.1',+ version: FEDERATION_PLUGIN_VERSION,inputSchema: {type: 'object',properties: {diff --git a/v3/@claude-flow/plugin-agent-federation/src/plugin.ts b/v3/@claude-flow/plugin-agent-federation/src/plugin.tsindex ab213588ae..a70a4635e4 100644--- a/v3/@claude-flow/plugin-agent-federation/src/plugin.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/plugin.ts@@ -25,7 +25,11 @@ import { RoutingService } from './domain/services/routing-service.js';import { AuditService, type ComplianceMode } from './domain/services/audit-service.js';import { PIIPipelineService } from './domain/services/pii-pipeline-service.js';import { TrustEvaluator } from './application/trust-evaluator.js';-import { PolicyEngine, type FederationClaimType } from './application/policy-engine.js';+import { PolicyEngine } from './application/policy-engine.js';+import {+ createFederationClaimChecker,+ type FederationAuthorizationMode,+} from './application/claim-checker.js';import { TrustLevel, getTrustLevelLabel } from './domain/entities/trust-level.js';import { type FederationMessageType } from './domain/entities/federation-envelope.js';@@ -48,9 +52,17 @@ type LoadedTransport = AgentTransport & {* doesn't include it, so we cast at the call site. */listen?: (port: number, host?: string) => Promise<void>;};-import { dispatchInbound, canonicalizeEnvelopeForVerify } from './application/inbound-dispatcher.js';+import {+ DEFAULT_ENVELOPE_SIGNATURE_MODE,+ JCS_SIGNATURE_PROTOCOL,+ canonicalizeEnvelopeForVerify,+ dispatchInbound,+ selectEnvelopeSignatureVersion,+ type EnvelopeSignatureMode,+} from './application/inbound-dispatcher.js';import { createMcpTools } from './mcp-tools.js';import { createCliCommands } from './cli-commands.js';+import { FEDERATION_PLUGIN_VERSION } from './version.js';// A2A (Agent2Agent, Linux Foundation) Agent Card adapter — cards only.// Opt-in via config.a2aCard; serves /.well-known/agent-card.json on a// 127.0.0.1-default bind (ADR-166 posture preserved).@@ -59,7 +71,7 @@ import { startAgentCardServer, type AgentCardServerHandle } from './a2a/well-knoexport class AgentFederationPlugin implements ClaudeFlowPlugin {readonly name = '@claude-flow/plugin-agent-federation';- readonly version = '1.0.0-alpha.1';+ readonly version = FEDERATION_PLUGIN_VERSION;readonly description = 'Cross-installation agent federation with PII protection and AI defence';readonly author = 'Claude Flow Team';readonly dependencies = ['@claude-flow/security', '@claude-flow/aidefence'];@@ -84,6 +96,12 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {const complianceMode = (config['complianceMode'] as ComplianceMode) ?? 'none';const staticPeers = (config['staticPeers'] as string[]) ?? [];const hashSalt = (config['hashSalt'] as string) ?? `salt-${nodeId}`;+ const signatureMode =+ (config['signatureMode'] as EnvelopeSignatureMode | undefined)+ ?? DEFAULT_ENVELOPE_SIGNATURE_MODE;+ if (!['legacy', 'prefer-jcs', 'require-jcs'].includes(signatureMode)) {+ throw new TypeError(`Unsupported federation signature mode: ${String(signatureMode)}`);+ }// ADR-095 G2: real Ed25519 keypair instead of empty publicKey + stub// signatures. Persist to .claude-flow/federation/key-<nodeId>.json so@@ -123,7 +141,21 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {nodeId,publicKey: publicKeyHex,endpoint,- capabilities: ['send', 'receive', 'query-redacted', 'status', 'ping', 'discovery'],+ capabilities: [+ 'send',+ 'receive',+ 'query-redacted',+ 'status',+ 'ping',+ 'discovery',+ ...(signatureMode === 'legacy' ? [] : [JCS_SIGNATURE_PROTOCOL]),+ ],+ supportedProtocols: [+ 'websocket',+ 'http',+ ...(signatureMode === 'legacy' ? [] : [JCS_SIGNATURE_PROTOCOL]),+ ],+ version: FEDERATION_PLUGIN_VERSION,};const generateId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;@@ -224,9 +256,29 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {},});- const policyEngine = new PolicyEngine(- { checkClaim: () => true },- );+ const authorizationMode =+ (config['authorizationMode'] as FederationAuthorizationMode | undefined) ?? 'legacy';+ const grantedClaims = Array.isArray(config['federationClaims'])+ ? config['federationClaims'].filter((claim): claim is string => typeof claim === 'string')+ : [];+ const claimChecker = createFederationClaimChecker({+ mode: authorizationMode,+ grantedClaims,+ onObservation: (claim, granted) => {+ context.eventBus.emit('federation:policy-observation', {+ claim,+ granted,+ mode: authorizationMode,+ });+ },+ });+ if (claimChecker.mode === 'legacy') {+ context.logger.warn(+ 'Federation authorization is in ADR-325 legacy compatibility mode; ' ++ 'use observe before enabling enforce',+ );+ }+ const policyEngine = new PolicyEngine({ checkClaim: claimChecker.checkClaim });const sessions: Map<string, import('./domain/entities/federation-session.js').FederationSession> = new Map();@@ -313,12 +365,18 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {return;}const address = resolveAddress(targetNodeId);- if (!address) {+ const peer = discovery.getPeer(targetNodeId);+ if (!address || !peer) {context.logger.warn(`Federation send aborted: peer ${targetNodeId} not in discovery registry`,);throw new Error(`PEER_UNKNOWN: ${targetNodeId}`);}+ const signatureVersion = selectEnvelopeSignatureVersion(+ signatureMode,+ peer.capabilities.supportedProtocols,+ envelope.messageType,+ );// Build the AgentMessage WITHOUT signature first, canonicalize// the bytes, sign them, then attach the signature to metadata.// The receiver runs the same canonicalization and verifies@@ -331,9 +389,10 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {sourceNodeId: envelope.sourceNodeId,targetNodeId: envelope.targetNodeId,sessionId: envelope.sessionId,+ ...(signatureVersion === 'jcs-v1' ? { signatureVersion } : {}),},};- const canon = canonicalizeEnvelopeForVerify(baseMessage);+ const canon = canonicalizeEnvelopeForVerify(baseMessage, signatureVersion);const signature = signBytes(canon);const signed: AgentMessage = {...baseMessage,@@ -405,6 +464,16 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {eventBus: context.eventBus,logger: context.logger,verifyEnvelope,+ acceptedSignatureVersions:+ signatureMode === 'require-jcs' ? ['jcs-v1'] : ['legacy-v1', 'jcs-v1'],+ authorizationMode,+ authorizeInbound: ({ messageType, peer, messageSizeBytes, sourceNodeId }) =>+ policyEngine.evaluateMessage(+ messageType as FederationMessageType,+ peer.trustLevel,+ messageSizeBytes,+ sourceNodeId,+ ),});});context.logger.debug('Federation inbound dispatcher subscribed (with Ed25519 sig verify)');@@ -435,7 +504,11 @@ export class AgentFederationPlugin implements ClaudeFlowPlugin {capabilities: {agentTypes: coordConfig.capabilities,maxConcurrentSessions: 10,- supportedProtocols: ['websocket', 'http'],+ supportedProtocols: [+ 'websocket',+ 'http',+ ...(signatureMode === 'legacy' ? [] : [JCS_SIGNATURE_PROTOCOL]),+ ],complianceModes: complianceMode === 'none' ? [] : [complianceMode],},version: this.version,diff --git a/v3/@claude-flow/plugin-agent-federation/src/version.ts b/v3/@claude-flow/plugin-agent-federation/src/version.tsnew file mode 100644index 0000000000..960c167938--- /dev/null+++ b/v3/@claude-flow/plugin-agent-federation/src/version.ts@@ -0,0 +1,2 @@+/** Single source of truth for runtime, manifest, CLI, and MCP version metadata. */+export const FEDERATION_PLUGIN_VERSION = '1.0.0-alpha.17' as const;diff --git a/v3/@claude-flow/security/__tests__/product-plane.test.ts b/v3/@claude-flow/security/__tests__/product-plane.test.tsnew file mode 100644index 0000000000..3666028b44--- /dev/null+++ b/v3/@claude-flow/security/__tests__/product-plane.test.ts@@ -0,0 +1,504 @@+import { generateKeyPairSync, sign } from 'node:crypto';+import { describe, expect, it } from 'vitest';+import {+ PRODUCT_ACTION_REQUIREMENTS,+ PRODUCT_ACTIONS,+ canonicalProductPlaneBytes,+ canonicalizeProductPlane,+ classifyProductAvailability,+ identityKey,+ isProductAction,+ sameIdentity,+ validateAuthoritativeReference,+ validateProductActionEnvelope,+ validateRuViewSemanticObservation,+ verifySignedProductActionEnvelope,+ type NamespacedIdentity,+ type ProductActionEnvelopeV1,+} from '../src/policy/product-plane.js';++const DIGEST = `sha256:${'a'.repeat(64)}`;++function envelope(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ schemaVersion: 'cognitum.action.v1',+ eventId: 'event-01',+ issuer: 'ruflo.policy',+ audience: 'meta-llm',+ subject: { namespace: 'firebase-subject', id: 'same-looking-id' },+ actor: { namespace: 'workload', id: 'spiffe://cognitum.example/agent/coder-1' },+ tenantRef: { namespace: 'meta-llm-account', id: 'tenant-01' },+ action: 'inference.invoke',+ resourceRefs: ['meta-llm://models/cognitum-auto'],+ requestDigest: DIGEST,+ idempotencyKey: 'idem-01',+ correlationId: 'corr-01',+ authoritativeSource: {+ authority: 'meta-llm',+ tenantRef: { namespace: 'meta-llm-account', id: 'tenant-01' },+ sourceType: 'meta-llm/inference',+ sourceId: 'request-01',+ sourceVersion: '1',+ sourceDigest: DIGEST,+ },+ sequence: '1',+ policyReceiptId: 'receipt-01',+ capabilityId: 'grant-01',+ occurredAt: '2026-07-28T12:00:00.000Z',+ expiresAt: '2026-07-28T12:05:00.000Z',+ privacyClass: 'P1',+ ...overrides,+ };+}++function observation(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ schemaVersion: 'ruview.semantic-observation.v1',+ spaceRef: { namespace: 'ruview-space', id: 'space-01' },+ observationType: 'occupancy.state',+ value: { occupied: true, zone: 'north', peopleEstimate: 2 },+ confidence: 0.93,+ uncertainty: 0.04,+ abstained: false,+ modelDigest: DIGEST,+ calibrationDigest: `sha256:${'b'.repeat(64)}`,+ hardwareRef: 'edge-node-01',+ privacyClass: 'P2',+ observedAt: '2026-07-28T12:00:00.000Z',+ expiresAt: '2026-07-28T12:00:10.000Z',+ sequence: '42',+ ...overrides,+ };+}++describe('product action vocabulary', () => {+ it('recognizes the complete closed vocabulary and rejects lookalikes', () => {+ expect(PRODUCT_ACTIONS).toHaveLength(31);+ for (const action of PRODUCT_ACTIONS) expect(isProductAction(action)).toBe(true);+ expect(isProductAction('cog.proposal.create ')).toBe(false);+ expect(isProductAction('ruview.raw.read')).toBe(false);+ expect(isProductAction('deployment.promote')).toBe(false);+ expect(isProductAction('memory.promote')).toBe(false);+ expect(isProductAction('policy.promote')).toBe(false);+ });++ it('makes self-learning actions narrow and validated memory commits content-bound', () => {+ expect(PRODUCT_ACTION_REQUIREMENTS['memory.recall']).toEqual(expect.objectContaining({+ requestDigest: true,+ capability: true,+ idempotencyKey: false,+ }));+ expect(PRODUCT_ACTION_REQUIREMENTS['memory.commit-validated']).toEqual({+ requestDigest: true,+ contentDigest: true,+ idempotencyKey: true,+ expiry: true,+ capability: true,+ validationReceipt: true,+ });++ const base = envelope({+ audience: 'ruflo.memory',+ action: 'memory.commit-validated',+ authoritativeSource: {+ authority: 'ruflo.memory',+ tenantRef: { namespace: 'meta-llm-account', id: 'tenant-01' },+ sourceType: 'ruflo.memory/validated-memory',+ sourceId: 'memory-01',+ sourceVersion: '1',+ sourceDigest: DIGEST,+ },+ });+ const unbound = validateProductActionEnvelope(base);+ expect(unbound.ok).toBe(false);+ if (!unbound.ok) {+ expect(unbound.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ path: '$.contentDigest', code: 'missing' }),+ expect.objectContaining({ path: '$.validationReceiptId', code: 'missing' }),+ ]));+ }+ expect(validateProductActionEnvelope({+ ...base,+ contentDigest: `sha256:${'c'.repeat(64)}`,+ validationReceiptId: 'validation-01',+ }).ok).toBe(true);+ });+});++describe('identity namespace separation', () => {+ it('does not equate equal-looking identifiers from different namespaces', () => {+ const firebase: NamespacedIdentity = { namespace: 'firebase-subject', id: 'same-looking-id' };+ const meta: NamespacedIdentity = { namespace: 'meta-llm-account', id: 'same-looking-id' };+ expect(identityKey(firebase)).not.toBe(identityKey(meta));+ expect(sameIdentity(firebase, meta)).toBe(false);+ expect(sameIdentity(firebase, { ...firebase })).toBe(true);+ });++ it('fails closed when a subject is unqualified or uses an unknown namespace', () => {+ const unqualified = validateProductActionEnvelope(envelope({ subject: 'same-looking-id' }));+ expect(unqualified.ok).toBe(false);+ if (!unqualified.ok) expect(unqualified.issues).toContainEqual(expect.objectContaining({+ path: '$.subject',+ code: 'invalid_type',+ }));++ const unknown = validateProductActionEnvelope(envelope({+ subject: { namespace: 'firebase', id: 'same-looking-id' },+ }));+ expect(unknown.ok).toBe(false);+ if (!unknown.ok) expect(unknown.issues).toContainEqual(expect.objectContaining({+ path: '$.subject.namespace',+ code: 'identity_namespace_required',+ }));+ });+});++describe('authoritative references', () => {+ it('accepts an authority-owned, tenant-bound source', () => {+ const result = validateAuthoritativeReference(envelope().authoritativeSource, {+ action: 'inference.invoke',+ tenantRef: { namespace: 'meta-llm-account', id: 'tenant-01' },+ });+ expect(result.ok).toBe(true);+ });++ it('rejects authority confusion, digest ambiguity, and tenant mismatch', () => {+ const confused = validateProductActionEnvelope(envelope({+ authoritativeSource: {+ authority: 'comms',+ tenantRef: { namespace: 'meta-llm-account', id: 'tenant-02' },+ sourceType: 'meta-llm/inference',+ sourceId: 'request-01',+ sourceVersion: '1',+ sourceDigest: 'sha256:not-a-digest',+ },+ }));+ expect(confused.ok).toBe(false);+ if (!confused.ok) {+ expect(confused.issues.map(({ code }) => code)).toContain('invalid_authority');+ expect(confused.issues.map(({ code }) => code)).toContain('tenant_mismatch');+ expect(confused.issues).toContainEqual(expect.objectContaining({+ path: '$.authoritativeSource.sourceDigest',+ code: 'invalid_format',+ }));+ }+ });+});++describe('product action envelope structural validation', () => {+ it('returns a typed value for a complete v1 envelope', () => {+ const result = validateProductActionEnvelope(envelope());+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.value.schemaVersion).toBe('cognitum.action.v1');+ expect(result.value.action).toBe('inference.invoke');+ expect(result.value.authoritativeSource.sourceId).toBe('request-01');+ }+ });++ it('rejects unknown versions, actions, fields, and non-canonical time', () => {+ const result = validateProductActionEnvelope(envelope({+ schemaVersion: 'cognitum.action.v2',+ action: 'inference.invoke.anything',+ occurredAt: '2026-07-28T12:00:00Z',+ injectedGrant: true,+ }));+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ path: '$.schemaVersion', code: 'unsupported_value' }),+ expect.objectContaining({ path: '$.action', code: 'unsupported_value' }),+ expect.objectContaining({ path: '$.occurredAt', code: 'invalid_format' }),+ expect.objectContaining({ path: '$.injectedGrant', code: 'unknown_field' }),+ ]));+ }+ });++ it('requires an action-owned source and exact source tenant', () => {+ const result = validateProductActionEnvelope(envelope({+ action: 'cog.deploy',+ }));+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.issues).toContainEqual(expect.objectContaining({+ path: '$.authoritativeSource.authority',+ code: 'invalid_authority',+ }));+ });++ it('enforces the P2/P3 ceiling for RuView semantic events', () => {+ const base = envelope({+ audience: 'ruview.edge',+ tenantRef: { namespace: 'ruview-space', id: 'space-01' },+ action: 'ruview.semantic.publish',+ authoritativeSource: {+ authority: 'ruview.edge',+ tenantRef: { namespace: 'ruview-space', id: 'space-01' },+ sourceType: 'ruview.edge/semantic-observation',+ sourceId: 'observation-01',+ sourceVersion: '1',+ sourceDigest: DIGEST,+ },+ });+ expect(validateProductActionEnvelope({ ...base, privacyClass: 'P2' }).ok).toBe(true);+ expect(validateProductActionEnvelope({ ...base, privacyClass: 'P3' }).ok).toBe(true);+ const exposed = validateProductActionEnvelope({ ...base, privacyClass: 'P1' });+ expect(exposed.ok).toBe(false);+ if (!exposed.ok) expect(exposed.issues).toContainEqual(expect.objectContaining({+ path: '$.privacyClass',+ code: 'privacy_ceiling_exceeded',+ }));+ });+});++describe('RuView privacy-minimized semantic observations', () => {+ it('accepts bounded P2/P3 scalar semantic records', () => {+ expect(validateRuViewSemanticObservation(observation()).ok).toBe(true);+ expect(validateRuViewSemanticObservation(observation({+ observationType: 'vital.summary',+ privacyClass: 'P3',+ value: { state: 'normal', anomaly: false },+ })).ok).toBe(true);+ });++ it('rejects unknown observation types, unknown fields, and binary-like values', () => {+ const privacy = validateRuViewSemanticObservation(observation({+ privacyClass: 'P1',+ observationType: 'raw.csi.frame',+ value: { csi_samples: [1, 2, 3] },+ }));+ expect(privacy.ok).toBe(false);+ if (!privacy.ok) {+ expect(privacy.issues.map(({ code }) => code)).toContain('privacy_ceiling_exceeded');+ expect(privacy.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ path: '$.observationType' }),+ expect.objectContaining({ path: '$.privacyClass' }),+ ]));+ }+ const unknownField = validateRuViewSemanticObservation(observation({+ value: { occupied: true, csi_samples: 'AAAA' },+ }));+ expect(unknownField.ok).toBe(false);+ if (!unknownField.ok) expect(unknownField.issues).toContainEqual(expect.objectContaining({+ path: '$.value.csi_samples',+ code: 'unknown_field',+ }));+ const encoded = validateRuViewSemanticObservation(observation({+ value: { occupied: true, zone: 'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB' },+ }));+ expect(encoded.ok).toBe(false);+ if (!encoded.ok) expect(encoded.issues).toContainEqual(expect.objectContaining({+ path: '$.value.zone',+ code: 'privacy_ceiling_exceeded',+ }));+ expect(validateRuViewSemanticObservation(observation({+ value: new Uint8Array([1, 2, 3]),+ })).ok).toBe(false);+ });++ it('rejects wrong space namespaces, invalid confidence, expiry, and sequence', () => {+ const result = validateRuViewSemanticObservation(observation({+ spaceRef: { namespace: 'cognitum-tenant', id: 'space-01' },+ confidence: Number.NaN,+ observedAt: '2026-07-28T12:00:10.000Z',+ expiresAt: '2026-07-28T12:00:00.000Z',+ sequence: '-1',+ }));+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ path: '$.spaceRef.namespace' }),+ expect.objectContaining({ path: '$.confidence' }),+ expect.objectContaining({ path: '$.expiresAt' }),+ expect.objectContaining({ path: '$.sequence' }),+ ]));+ }+ });+});++describe('availability dimensions', () => {+ it('does not infer configuration or health from authorization', () => {+ expect(classifyProductAvailability({+ identity: 'verified',+ configured: 'unknown',+ reachable: 'unknown',+ healthy: 'unknown',+ authorized: 'yes',+ })).toBe('degraded');+ expect(classifyProductAvailability({+ identity: 'verified',+ configured: 'yes',+ reachable: 'no',+ healthy: 'unknown',+ authorized: 'yes',+ })).toBe('unavailable');+ expect(classifyProductAvailability({+ identity: 'verified',+ configured: 'yes',+ reachable: 'yes',+ healthy: 'yes',+ authorized: 'yes',+ })).toBe('available');+ expect(classifyProductAvailability({+ identity: 'verified',+ configured: 'yes',+ reachable: 'yes',+ healthy: 'yes',+ authorized: 'no',+ })).toBe('blocked');+ });+});++describe('strict product-plane canonicalization', () => {+ it('recursively sorts keys and uses canonical ECMAScript number rendering', () => {+ expect(canonicalizeProductPlane({+ z: -0,+ a: { exponent: 1e30, fraction: 0.002, integer: 2 },+ })).toBe('{"a":{"exponent":1e+30,"fraction":0.002,"integer":2},"z":0}');+ expect(new TextDecoder().decode(canonicalProductPlaneBytes({ b: 2, a: 1 })))+ .toBe('{"a":1,"b":2}');+ });++ it('rejects invalid JCS numbers, invalid Unicode, sparse arrays, and undefined', () => {+ expect(() => canonicalizeProductPlane(Number.POSITIVE_INFINITY)).toThrow('non-finite');+ expect(() => canonicalizeProductPlane(Number.NaN)).toThrow('non-finite');+ expect(() => canonicalizeProductPlane('\ud800')).toThrow('unpaired high surrogate');+ expect(() => canonicalizeProductPlane(new Array(1))).toThrow('sparse arrays');+ expect(() => canonicalizeProductPlane({ omitted: undefined })).toThrow('undefined');+ });+});++describe('signed product action envelope verifier', () => {+ const keys = generateKeyPairSync('ed25519');+ const now = Date.parse('2026-07-28T12:01:00.000Z');++ function signed(payload: Record<string, unknown> = envelope()): Record<string, unknown> {+ return {+ envelope: payload,+ algorithm: 'Ed25519',+ keyId: 'issuer-key-01',+ signature: sign(null, canonicalProductPlaneBytes(payload), keys.privateKey).toString('base64url'),+ };+ }++ function options(+ reservation: 'reserved' | 'replay' | 'conflict' = 'reserved',+ ) {+ return {+ expectedAudience: 'meta-llm' as const,+ expectedTenantRef: { namespace: 'meta-llm-account' as const, id: 'tenant-01' },+ now: () => now,+ maxAgeMs: 5 * 60_000,+ resolveKey: (issuer: string, keyId: string) => (+ issuer === 'ruflo.policy' && keyId === 'issuer-key-01' ? keys.publicKey : undefined+ ),+ replayStore: {+ reserve: () => reservation,+ },+ policyVerifier: () => ({ allowed: true }),+ capabilityVerifier: () => ({ allowed: true }),+ };+ }++ it('accepts only after signature, audience, tenant, policy, capability, and replay reservation', async () => {+ const result = await verifySignedProductActionEnvelope(signed(), options());+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.envelope.action).toBe('inference.invoke');+ expect(result.canonicalDigest).toMatch(/^sha256:[a-f0-9]{64}$/);+ expect(result.replayKey).toContain('inference.invoke');+ }+ });++ it('supports an injected signature verifier without treating authorization as health', async () => {+ let observedBytes = '';+ const custom = options();+ delete (custom as { resolveKey?: unknown }).resolveKey;+ const result = await verifySignedProductActionEnvelope(signed(), {+ ...custom,+ verifySignature: ({ canonicalBytes }) => {+ observedBytes = new TextDecoder().decode(canonicalBytes);+ return true;+ },+ });+ expect(result.ok).toBe(true);+ expect(observedBytes).toBe(canonicalizeProductPlane(envelope()));+ });++ it('rejects signature tampering, wrong audience, wrong tenant, and missing verifier config', async () => {+ const tampered = signed();+ (tampered.envelope as Record<string, unknown>).correlationId = 'tampered';+ expect(await verifySignedProductActionEnvelope(tampered, options()))+ .toEqual(expect.objectContaining({ ok: false, code: 'signature_invalid' }));++ expect(await verifySignedProductActionEnvelope(signed(envelope({ audience: 'comms' })), options()))+ .toEqual(expect.objectContaining({ ok: false, code: 'audience_mismatch' }));++ expect(await verifySignedProductActionEnvelope(signed(), {+ ...options(),+ expectedTenantRef: { namespace: 'meta-llm-account', id: 'another-tenant' },+ })).toEqual(expect.objectContaining({ ok: false, code: 'tenant_mismatch' }));++ const noSignatureVerifier = options();+ delete (noSignatureVerifier as { resolveKey?: unknown }).resolveKey;+ expect(await verifySignedProductActionEnvelope(signed(), noSignatureVerifier))+ .toEqual(expect.objectContaining({ ok: false, code: 'signature_configuration_missing' }));+ });++ it('rejects stale, future, expired, replayed, and conflicting deliveries', async () => {+ expect(await verifySignedProductActionEnvelope(signed(envelope({+ occurredAt: '2026-07-28T11:50:00.000Z',+ expiresAt: '2026-07-28T12:05:00.000Z',+ })), options())).toEqual(expect.objectContaining({ ok: false, code: 'stale' }));++ expect(await verifySignedProductActionEnvelope(signed(envelope({+ occurredAt: '2026-07-28T12:02:00.000Z',+ expiresAt: '2026-07-28T12:05:00.000Z',+ })), options())).toEqual(expect.objectContaining({ ok: false, code: 'not_yet_valid' }));++ expect(await verifySignedProductActionEnvelope(signed(envelope({+ expiresAt: '2026-07-28T12:00:30.000Z',+ })), options())).toEqual(expect.objectContaining({ ok: false, code: 'expired' }));++ expect(await verifySignedProductActionEnvelope(signed(), options('replay')))+ .toEqual(expect.objectContaining({ ok: false, code: 'replay_detected' }));+ expect(await verifySignedProductActionEnvelope(signed(), options('conflict')))+ .toEqual(expect.objectContaining({ ok: false, code: 'idempotency_conflict' }));+ });++ it('fails closed on local policy, capability, key, and callback failures', async () => {+ expect(await verifySignedProductActionEnvelope(signed(), {+ ...options(),+ policyVerifier: () => ({ allowed: false, reason: 'tenant policy denied' }),+ })).toEqual(expect.objectContaining({ ok: false, code: 'policy_denied', reason: 'tenant policy denied' }));++ expect(await verifySignedProductActionEnvelope(signed(), {+ ...options(),+ capabilityVerifier: () => false,+ })).toEqual(expect.objectContaining({ ok: false, code: 'capability_denied' }));++ expect(await verifySignedProductActionEnvelope(signed(), {+ ...options(),+ resolveKey: () => undefined,+ })).toEqual(expect.objectContaining({ ok: false, code: 'key_not_found' }));++ expect(await verifySignedProductActionEnvelope(signed(), {+ ...options(),+ policyVerifier: () => {+ throw new Error('store unavailable');+ },+ })).toEqual(expect.objectContaining({ ok: false, code: 'verification_error' }));+ });++ it('requires exact timestamp round trips before signature evaluation', async () => {+ const invalidDate = envelope({+ occurredAt: '2026-02-30T12:00:00.000Z',+ expiresAt: '2026-07-28T12:05:00.000Z',+ });+ const result = await verifySignedProductActionEnvelope(signed(invalidDate), options());+ expect(result).toEqual(expect.objectContaining({ ok: false, code: 'invalid_envelope' }));+ if (!result.ok) expect(result.issues).toContainEqual(expect.objectContaining({+ path: '$.occurredAt',+ code: 'invalid_format',+ }));+ });+});diff --git a/v3/@claude-flow/security/package.json b/v3/@claude-flow/security/package.jsonindex 909aa3a4cc..c7dedd40e7 100644--- a/v3/@claude-flow/security/package.json+++ b/v3/@claude-flow/security/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/security",- "version": "3.0.0-alpha.13",+ "version": "3.0.0-alpha.14","type": "module","description": "Security module - CVE fixes, input validation, path security","main": "dist/index.js",@@ -12,6 +12,7 @@"scripts": {"test": "vitest run","benchmark:policy": "npm run build && node scripts/benchmark-policy-engine.mjs",+ "benchmark:product-plane": "npm run build && node scripts/benchmark-product-plane.mjs","test:oauth-surface": "vitest run __tests__/oauth-export-surface.test.ts __tests__/oauth-pkce.test.ts __tests__/oauth-browser.test.ts","build": "tsc && node scripts/verify-oauth-exports.mjs","prepublishOnly": "npm run build && npm run test:oauth-surface"diff --git a/v3/@claude-flow/security/scripts/benchmark-product-plane.mjs b/v3/@claude-flow/security/scripts/benchmark-product-plane.mjsnew file mode 100644index 0000000000..71946c31f5--- /dev/null+++ b/v3/@claude-flow/security/scripts/benchmark-product-plane.mjs@@ -0,0 +1,98 @@+import { generateKeyPairSync, sign } from 'node:crypto';+import { performance } from 'node:perf_hooks';+import {+ canonicalProductPlaneBytes,+ canonicalizeProductPlane,+ verifySignedProductActionEnvelope,+} from '../dist/policy/product-plane.js';++const digest = `sha256:${'a'.repeat(64)}`;+const envelope = {+ schemaVersion: 'cognitum.action.v1',+ eventId: 'benchmark-event',+ issuer: 'ruflo.policy',+ audience: 'meta-llm',+ subject: { namespace: 'firebase-subject', id: 'benchmark-user' },+ actor: { namespace: 'workload', id: 'spiffe://cognitum.example/agent/benchmark' },+ tenantRef: { namespace: 'meta-llm-account', id: 'benchmark-tenant' },+ action: 'inference.invoke',+ resourceRefs: ['meta-llm://models/cognitum-auto'],+ requestDigest: digest,+ idempotencyKey: 'benchmark-idempotency',+ correlationId: 'benchmark-correlation',+ authoritativeSource: {+ authority: 'meta-llm',+ tenantRef: { namespace: 'meta-llm-account', id: 'benchmark-tenant' },+ sourceType: 'meta-llm/inference',+ sourceId: 'benchmark-request',+ sourceVersion: '1',+ sourceDigest: digest,+ },+ sequence: '1',+ policyReceiptId: 'benchmark-policy-receipt',+ capabilityId: 'benchmark-capability',+ occurredAt: '2026-07-28T12:00:00.000Z',+ expiresAt: '2026-07-28T12:05:00.000Z',+ privacyClass: 'P1',+};++const keys = generateKeyPairSync('ed25519');+const signed = {+ envelope,+ algorithm: 'Ed25519',+ keyId: 'benchmark-key',+ signature: sign(null, canonicalProductPlaneBytes(envelope), keys.privateKey).toString('base64url'),+};+const options = {+ expectedAudience: 'meta-llm',+ expectedTenantRef: { namespace: 'meta-llm-account', id: 'benchmark-tenant' },+ now: () => Date.parse('2026-07-28T12:01:00.000Z'),+ maxAgeMs: 5 * 60_000,+ resolveKey: () => keys.publicKey,+ replayStore: { reserve: () => 'reserved' },+ policyVerifier: () => ({ allowed: true }),+ capabilityVerifier: () => ({ allowed: true }),+};++function percentile(values, fraction) {+ const ordered = [...values].sort((left, right) => left - right);+ return ordered[Math.min(ordered.length - 1, Math.floor(ordered.length * fraction))];+}++async function measure(name, batches, iterations, operation) {+ const samples = [];+ for (let batch = 0; batch < batches; batch++) {+ const started = performance.now();+ for (let iteration = 0; iteration < iterations; iteration++) await operation();+ samples.push(((performance.now() - started) * 1000) / iterations);+ }+ return {+ name,+ batches,+ iterationsPerBatch: iterations,+ latencyMicroseconds: {+ p50: percentile(samples, 0.50),+ p95: percentile(samples, 0.95),+ p99: percentile(samples, 0.99),+ },+ throughputPerSecond: 1_000_000 / percentile(samples, 0.50),+ };+}++const results = [+ await measure('canonicalize-product-envelope', 20, 10_000, () => {+ canonicalizeProductPlane(envelope);+ }),+ await measure('verify-ed25519-product-envelope', 20, 500, async () => {+ const result = await verifySignedProductActionEnvelope(signed, options);+ if (!result.ok) throw new Error(`benchmark verification failed: ${result.code}`);+ }),+];++console.log(JSON.stringify({+ schema: 'cognitum.product-plane-benchmark/v1',+ node: process.version,+ platform: `${process.platform}-${process.arch}`,+ canonicalBytes: canonicalProductPlaneBytes(envelope).length,+ results,+}, null, 2));diff --git a/v3/@claude-flow/security/src/policy/index.ts b/v3/@claude-flow/security/src/policy/index.tsindex 12b68943f9..7a04dd2d41 100644--- a/v3/@claude-flow/security/src/policy/index.ts+++ b/v3/@claude-flow/security/src/policy/index.ts@@ -3,3 +3,4 @@ export * from './canonical.js';export * from './envelope.js';export * from './evaluator.js';export * from './engine.js';+export * from './product-plane.js';diff --git a/v3/@claude-flow/security/src/policy/product-plane.ts b/v3/@claude-flow/security/src/policy/product-plane.tsnew file mode 100644index 0000000000..fee7093c54--- /dev/null+++ b/v3/@claude-flow/security/src/policy/product-plane.ts@@ -0,0 +1,1381 @@+/**+ * Cognitum product-plane claim federation primitives.+ *+ * This module intentionally contains no grant-verification or domain mutation+ * logic. It validates the portable, reference-only envelope that a local+ * policy enforcement point can evaluate before consulting its authoritative+ * identity, tenancy, and permission stores.+ */++import { createHash, verify as verifyCryptoSignature, type KeyLike } from 'node:crypto';++export const PRODUCT_ACTION_ENVELOPE_VERSION = 'cognitum.action.v1' as const;++export const PRODUCT_ACTIONS = [+ 'dashboard.read',+ 'dashboard.status.read',+ 'inference.invoke',+ 'inference.stream',+ 'usage.read',+ 'pod.spawn',+ 'benchmark.run',+ 'evolution.propose',+ 'evolution.promote',+ 'comms.thread.read',+ 'comms.thread.post',+ 'comms.projection.read',+ 'comms.board.admin',+ 'cog.proposal.create',+ 'cog.proposal.review',+ 'cog.proposal.approve',+ 'cog.instance.acquire',+ 'cog.instance.operate',+ 'cog.deploy',+ 'cog.rollback',+ 'ruview.space.read',+ 'ruview.semantic.publish',+ 'ruview.automation.propose',+ 'ruview.automation.approve',+ 'ruview.device.command',+ 'cognition.route',+ 'cognition.critique',+ 'memory.recall',+ 'memory.propose',+ 'evidence.read',+ 'memory.commit-validated',+] as const;++export type ProductAction = (typeof PRODUCT_ACTIONS)[number];++export const PRODUCT_AUTHORITIES = [+ 'cognitum.control-plane',+ 'cognitum.cog',+ 'meta-llm',+ 'comms',+ 'agentbbs',+ 'ruview.edge',+ 'ruflo.policy',+ 'ruflo.memory',+] as const;++export type ProductAuthority = (typeof PRODUCT_AUTHORITIES)[number];++export const IDENTITY_NAMESPACES = [+ 'cognitum-principal',+ 'firebase-subject',+ 'meta-llm-account',+ 'agentbbs-public-key',+ 'workload',+ 'ruflo-agent',+ 'legacy-principal',+] as const;++export type IdentityNamespace = (typeof IDENTITY_NAMESPACES)[number];++export const TENANT_NAMESPACES = [+ 'cognitum-tenant',+ 'meta-llm-account',+ 'meta-llm-sub-tenant',+ 'comms-tenant',+ 'agentbbs-board',+ 'ruview-space',+] as const;++export type TenantNamespace = (typeof TENANT_NAMESPACES)[number];+export type PrivacyClass = 'P0' | 'P1' | 'P2' | 'P3';++export interface NamespacedIdentity {+ namespace: IdentityNamespace;+ id: string;+}++export interface NamespacedTenantRef {+ namespace: TenantNamespace;+ id: string;+}++export interface AuthoritativeReference {+ authority: ProductAuthority;+ tenantRef: NamespacedTenantRef;+ /**+ * Authority-qualified record kind, for example+ * `meta-llm/inference` or `ruview.edge/semantic-observation`.+ */+ sourceType: string;+ sourceId: string;+ sourceVersion: string;+ sourceDigest: `sha256:${string}`;+}++export interface ProductActionEnvelopeV1 {+ schemaVersion: typeof PRODUCT_ACTION_ENVELOPE_VERSION;+ eventId: string;+ issuer: ProductAuthority;+ audience: ProductAuthority;+ subject: NamespacedIdentity;+ actor?: NamespacedIdentity;+ tenantRef: NamespacedTenantRef;+ action: ProductAction;+ resourceRefs: string[];+ requestDigest?: `sha256:${string}`;+ contentDigest?: `sha256:${string}`;+ idempotencyKey?: string;+ correlationId: string;+ causationId?: string;+ authoritativeSource: AuthoritativeReference;+ sequence?: string;+ policyReceiptId: string;+ capabilityId?: string;+ validationReceiptId?: string;+ occurredAt: string;+ expiresAt?: string;+ privacyClass: PrivacyClass;+}++export type AvailabilityCheck = 'yes' | 'no' | 'unknown';+export type IdentityAvailability = 'verified' | 'unverified' | 'invalid' | 'unknown';++/**+ * Independent integration-health dimensions. In particular, an authorized+ * claim changes only `authorized`; it does not imply configuration,+ * reachability, service health, or verified browser/workload identity.+ */+export interface ProductAvailabilityDimensions {+ identity: IdentityAvailability;+ configured: AvailabilityCheck;+ reachable: AvailabilityCheck;+ healthy: AvailabilityCheck;+ authorized: AvailabilityCheck;+}++export type ProductAvailability = 'available' | 'degraded' | 'blocked' | 'unavailable';++export function classifyProductAvailability(+ dimensions: ProductAvailabilityDimensions,+): ProductAvailability {+ if (dimensions.authorized === 'no' || dimensions.identity === 'invalid') return 'blocked';+ if (dimensions.configured === 'no' || dimensions.reachable === 'no' || dimensions.healthy === 'no') {+ return 'unavailable';+ }+ if (+ dimensions.identity === 'verified'+ && dimensions.configured === 'yes'+ && dimensions.reachable === 'yes'+ && dimensions.healthy === 'yes'+ && dimensions.authorized === 'yes'+ ) {+ return 'available';+ }+ return 'degraded';+}++export interface RuViewSemanticObservationV1 {+ schemaVersion: 'ruview.semantic-observation.v1';+ spaceRef: NamespacedTenantRef & { namespace: 'ruview-space' };+ observationType: string;+ /**+ * Privacy-minimized semantic data only. Binary values, arrays, and raw+ * sensing field names are rejected by the wire validator.+ */+ value: Record<string, string | number | boolean | null>;+ confidence: number;+ uncertainty?: number;+ abstained: boolean;+ modelDigest: `sha256:${string}`;+ calibrationDigest?: `sha256:${string}`;+ hardwareRef?: string;+ privacyClass: 'P2' | 'P3';+ observedAt: string;+ expiresAt: string;+ /** Canonical unsigned decimal string; JSON cannot safely carry bigint. */+ sequence: string;+}++export interface ValidationIssue {+ path: string;+ code:+ | 'invalid_type'+ | 'missing'+ | 'unknown_field'+ | 'unsupported_value'+ | 'invalid_format'+ | 'invalid_authority'+ | 'identity_namespace_required'+ | 'tenant_mismatch'+ | 'privacy_ceiling_exceeded';+ message: string;+}++export type ValidationResult<T> =+ | { ok: true; value: T }+ | { ok: false; issues: ValidationIssue[] };++export interface ProductActionRequirements {+ requestDigest: boolean;+ contentDigest: boolean;+ idempotencyKey: boolean;+ expiry: boolean;+ capability: boolean;+ validationReceipt: boolean;+}++const ACTION_SET = new Set<string>(PRODUCT_ACTIONS);+const AUTHORITY_SET = new Set<string>(PRODUCT_AUTHORITIES);+const IDENTITY_NAMESPACE_SET = new Set<string>(IDENTITY_NAMESPACES);+const TENANT_NAMESPACE_SET = new Set<string>(TENANT_NAMESPACES);+const PRIVACY_CLASS_SET = new Set<string>(['P0', 'P1', 'P2', 'P3']);+const SHA256_RE = /^sha256:[a-f0-9]{64}$/;+const UNSIGNED_DECIMAL_RE = /^(0|[1-9][0-9]*)$/;+const CANONICAL_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;+const SAFE_TOKEN_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$/;+const SOURCE_TYPE_RE = /^[a-z][a-z0-9.-]{1,63}\/[a-z][a-z0-9.-]{0,63}$/;+const BASE64_SHAPED_RE = /^(?:[A-Za-z0-9+/]{4}){7,}(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;+const BASE64URL_SHAPED_RE = /^[A-Za-z0-9_-]{32,}$/;++const ENVELOPE_FIELDS = new Set([+ 'schemaVersion',+ 'eventId',+ 'issuer',+ 'audience',+ 'subject',+ 'actor',+ 'tenantRef',+ 'action',+ 'resourceRefs',+ 'requestDigest',+ 'contentDigest',+ 'idempotencyKey',+ 'correlationId',+ 'causationId',+ 'authoritativeSource',+ 'sequence',+ 'policyReceiptId',+ 'capabilityId',+ 'validationReceiptId',+ 'occurredAt',+ 'expiresAt',+ 'privacyClass',+]);++const AUTHORITY_FIELDS = new Set([+ 'authority',+ 'tenantRef',+ 'sourceType',+ 'sourceId',+ 'sourceVersion',+ 'sourceDigest',+]);++const IDENTITY_FIELDS = new Set(['namespace', 'id']);+const TENANT_FIELDS = new Set(['namespace', 'id']);+const RUVIEW_FIELDS = new Set([+ 'schemaVersion',+ 'spaceRef',+ 'observationType',+ 'value',+ 'confidence',+ 'uncertainty',+ 'abstained',+ 'modelDigest',+ 'calibrationDigest',+ 'hardwareRef',+ 'privacyClass',+ 'observedAt',+ 'expiresAt',+ 'sequence',+]);++/**+ * Actions must be anchored in the product that owns their authoritative+ * outcome. Read-model actions permit the explicitly listed source domains.+ */+export const ACTION_AUTHORITIES: Readonly<Record<ProductAction, readonly ProductAuthority[]>> = {+ 'dashboard.read': ['cognitum.control-plane'],+ 'dashboard.status.read': [+ 'cognitum.control-plane',+ 'cognitum.cog',+ 'meta-llm',+ 'comms',+ 'agentbbs',+ 'ruview.edge',+ 'ruflo.policy',+ ],+ 'inference.invoke': ['meta-llm'],+ 'inference.stream': ['meta-llm'],+ 'usage.read': ['meta-llm'],+ 'pod.spawn': ['meta-llm'],+ 'benchmark.run': ['meta-llm'],+ 'evolution.propose': ['meta-llm'],+ 'evolution.promote': ['meta-llm'],+ 'comms.thread.read': ['agentbbs'],+ 'comms.thread.post': ['agentbbs'],+ 'comms.projection.read': [+ 'cognitum.cog',+ 'meta-llm',+ 'comms',+ 'agentbbs',+ 'ruview.edge',+ ],+ 'comms.board.admin': ['comms'],+ 'cog.proposal.create': ['cognitum.cog'],+ 'cog.proposal.review': ['cognitum.cog'],+ 'cog.proposal.approve': ['cognitum.cog'],+ 'cog.instance.acquire': ['cognitum.cog'],+ 'cog.instance.operate': ['cognitum.cog'],+ 'cog.deploy': ['cognitum.cog'],+ 'cog.rollback': ['cognitum.cog'],+ 'ruview.space.read': ['ruview.edge'],+ 'ruview.semantic.publish': ['ruview.edge'],+ 'ruview.automation.propose': ['ruview.edge'],+ 'ruview.automation.approve': ['ruview.edge'],+ 'ruview.device.command': ['ruview.edge'],+ 'cognition.route': ['ruflo.policy'],+ 'cognition.critique': ['ruflo.policy'],+ 'memory.recall': ['ruflo.memory'],+ 'memory.propose': ['ruflo.memory'],+ 'evidence.read': ['ruflo.memory'],+ 'memory.commit-validated': ['ruflo.memory'],+};++const NO_SIDE_EFFECT_REQUIREMENTS: ProductActionRequirements = {+ requestDigest: false,+ contentDigest: false,+ idempotencyKey: false,+ expiry: false,+ capability: false,+ validationReceipt: false,+};++const SCOPED_READ_REQUIREMENTS: ProductActionRequirements = {+ requestDigest: true,+ contentDigest: false,+ idempotencyKey: false,+ expiry: true,+ capability: true,+ validationReceipt: false,+};++const MUTATION_REQUIREMENTS: ProductActionRequirements = {+ requestDigest: true,+ contentDigest: false,+ idempotencyKey: true,+ expiry: true,+ capability: true,+ validationReceipt: false,+};++/**+ * Explicit obligations avoid inference from action spelling. New actions do+ * not become privileged merely because a caller supplies a valid signature.+ */+export const PRODUCT_ACTION_REQUIREMENTS: Readonly<Record<ProductAction, ProductActionRequirements>> = {+ 'dashboard.read': NO_SIDE_EFFECT_REQUIREMENTS,+ 'dashboard.status.read': NO_SIDE_EFFECT_REQUIREMENTS,+ 'inference.invoke': MUTATION_REQUIREMENTS,+ 'inference.stream': MUTATION_REQUIREMENTS,+ 'usage.read': SCOPED_READ_REQUIREMENTS,+ 'pod.spawn': MUTATION_REQUIREMENTS,+ 'benchmark.run': MUTATION_REQUIREMENTS,+ 'evolution.propose': MUTATION_REQUIREMENTS,+ 'evolution.promote': MUTATION_REQUIREMENTS,+ 'comms.thread.read': SCOPED_READ_REQUIREMENTS,+ 'comms.thread.post': MUTATION_REQUIREMENTS,+ 'comms.projection.read': SCOPED_READ_REQUIREMENTS,+ 'comms.board.admin': MUTATION_REQUIREMENTS,+ 'cog.proposal.create': MUTATION_REQUIREMENTS,+ 'cog.proposal.review': MUTATION_REQUIREMENTS,+ 'cog.proposal.approve': MUTATION_REQUIREMENTS,+ 'cog.instance.acquire': MUTATION_REQUIREMENTS,+ 'cog.instance.operate': MUTATION_REQUIREMENTS,+ 'cog.deploy': MUTATION_REQUIREMENTS,+ 'cog.rollback': MUTATION_REQUIREMENTS,+ 'ruview.space.read': SCOPED_READ_REQUIREMENTS,+ 'ruview.semantic.publish': MUTATION_REQUIREMENTS,+ 'ruview.automation.propose': MUTATION_REQUIREMENTS,+ 'ruview.automation.approve': MUTATION_REQUIREMENTS,+ 'ruview.device.command': MUTATION_REQUIREMENTS,+ 'cognition.route': MUTATION_REQUIREMENTS,+ 'cognition.critique': MUTATION_REQUIREMENTS,+ 'memory.recall': SCOPED_READ_REQUIREMENTS,+ 'memory.propose': MUTATION_REQUIREMENTS,+ 'evidence.read': SCOPED_READ_REQUIREMENTS,+ 'memory.commit-validated': {+ requestDigest: true,+ contentDigest: true,+ idempotencyKey: true,+ expiry: true,+ capability: true,+ validationReceipt: true,+ },+};++function isRecord(value: unknown): value is Record<string, unknown> {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;+ const prototype = Object.getPrototypeOf(value);+ return prototype === Object.prototype || prototype === null;+}++function issue(+ issues: ValidationIssue[],+ path: string,+ code: ValidationIssue['code'],+ message: string,+): void {+ issues.push({ path, code, message });+}++function rejectUnknownFields(+ value: Record<string, unknown>,+ allowed: ReadonlySet<string>,+ path: string,+ issues: ValidationIssue[],+): void {+ for (const key of Object.keys(value)) {+ if (!allowed.has(key)) issue(issues, `${path}.${key}`, 'unknown_field', 'field is not in this schema version');+ }+}++function requireString(+ value: Record<string, unknown>,+ key: string,+ path: string,+ issues: ValidationIssue[],+ options: { optional?: boolean; max?: number; pattern?: RegExp } = {},+): string | undefined {+ const candidate = value[key];+ if (candidate === undefined) {+ if (!options.optional) issue(issues, `${path}.${key}`, 'missing', 'required field is missing');+ return undefined;+ }+ if (typeof candidate !== 'string') {+ issue(issues, `${path}.${key}`, 'invalid_type', 'must be a string');+ return undefined;+ }+ const max = options.max ?? 256;+ if (candidate.length === 0 || candidate.length > max || /[\u0000-\u001f\u007f]/.test(candidate)) {+ issue(issues, `${path}.${key}`, 'invalid_format', `must contain 1-${max} safe characters`);+ return undefined;+ }+ if (options.pattern && !options.pattern.test(candidate)) {+ issue(issues, `${path}.${key}`, 'invalid_format', 'has an invalid format');+ return undefined;+ }+ return candidate;+}++function validateTimestamp(+ value: Record<string, unknown>,+ key: string,+ path: string,+ issues: ValidationIssue[],+ optional = false,+): string | undefined {+ const timestamp = requireString(value, key, path, issues, { optional, max: 24 });+ if (timestamp !== undefined) {+ const milliseconds = Date.parse(timestamp);+ if (+ !CANONICAL_TIMESTAMP_RE.test(timestamp)+ || !Number.isFinite(milliseconds)+ || new Date(milliseconds).toISOString() !== timestamp+ ) {+ issue(issues, `${path}.${key}`, 'invalid_format', 'must round-trip as a canonical UTC timestamp');+ return undefined;+ }+ }+ return timestamp;+}++function validateDigest(+ value: Record<string, unknown>,+ key: string,+ path: string,+ issues: ValidationIssue[],+ optional = false,+): string | undefined {+ return requireString(value, key, path, issues, {+ optional,+ max: 71,+ pattern: SHA256_RE,+ });+}++function validateIdentity(+ input: unknown,+ path: string,+ issues: ValidationIssue[],+): NamespacedIdentity | undefined {+ if (!isRecord(input)) {+ issue(issues, path, 'invalid_type', 'must be a namespaced identity object');+ return undefined;+ }+ rejectUnknownFields(input, IDENTITY_FIELDS, path, issues);+ const namespace = requireString(input, 'namespace', path, issues, { max: 64 });+ const id = requireString(input, 'id', path, issues, { max: 512 });+ if (namespace !== undefined && !IDENTITY_NAMESPACE_SET.has(namespace)) {+ issue(issues, `${path}.namespace`, 'identity_namespace_required', 'unknown identity namespace');+ }+ if (namespace === undefined || id === undefined || !IDENTITY_NAMESPACE_SET.has(namespace)) return undefined;+ return { namespace: namespace as IdentityNamespace, id };+}++function validateTenantRef(+ input: unknown,+ path: string,+ issues: ValidationIssue[],+): NamespacedTenantRef | undefined {+ if (!isRecord(input)) {+ issue(issues, path, 'invalid_type', 'must be a namespaced tenant reference object');+ return undefined;+ }+ rejectUnknownFields(input, TENANT_FIELDS, path, issues);+ const namespace = requireString(input, 'namespace', path, issues, { max: 64 });+ const id = requireString(input, 'id', path, issues, { max: 256 });+ if (namespace !== undefined && !TENANT_NAMESPACE_SET.has(namespace)) {+ issue(issues, `${path}.namespace`, 'identity_namespace_required', 'unknown tenant namespace');+ }+ if (namespace === undefined || id === undefined || !TENANT_NAMESPACE_SET.has(namespace)) return undefined;+ return { namespace: namespace as TenantNamespace, id };+}++export function identityKey(identity: NamespacedIdentity): string {+ return `${identity.namespace.length}:${identity.namespace}${identity.id.length}:${identity.id}`;+}++export function sameIdentity(left: NamespacedIdentity, right: NamespacedIdentity): boolean {+ return identityKey(left) === identityKey(right);+}++export function tenantRefKey(tenant: NamespacedTenantRef): string {+ return `${tenant.namespace.length}:${tenant.namespace}${tenant.id.length}:${tenant.id}`;+}++export function isProductAction(value: unknown): value is ProductAction {+ return typeof value === 'string' && ACTION_SET.has(value);+}++export function validateAuthoritativeReference(+ input: unknown,+ options: { action?: ProductAction; tenantRef?: NamespacedTenantRef } = {},+): ValidationResult<AuthoritativeReference> {+ const issues: ValidationIssue[] = [];+ if (!isRecord(input)) {+ return {+ ok: false,+ issues: [{ path: '$', code: 'invalid_type', message: 'authority reference must be an object' }],+ };+ }+ rejectUnknownFields(input, AUTHORITY_FIELDS, '$', issues);+ const authority = requireString(input, 'authority', '$', issues, { max: 64 });+ const tenantRef = validateTenantRef(input.tenantRef, '$.tenantRef', issues);+ const sourceType = requireString(input, 'sourceType', '$', issues, { max: 128, pattern: SOURCE_TYPE_RE });+ const sourceId = requireString(input, 'sourceId', '$', issues, { max: 512 });+ const sourceVersion = requireString(input, 'sourceVersion', '$', issues, {+ max: 128,+ pattern: SAFE_TOKEN_RE,+ });+ const sourceDigest = validateDigest(input, 'sourceDigest', '$', issues);++ if (authority !== undefined && !AUTHORITY_SET.has(authority)) {+ issue(issues, '$.authority', 'invalid_authority', 'unknown product authority');+ }+ if (+ authority !== undefined+ && AUTHORITY_SET.has(authority)+ && sourceType !== undefined+ && !sourceType.startsWith(`${authority}/`)+ ) {+ issue(issues, '$.sourceType', 'invalid_authority', 'source type is not owned by the declared authority');+ }+ if (+ options.action+ && authority !== undefined+ && AUTHORITY_SET.has(authority)+ && !ACTION_AUTHORITIES[options.action].includes(authority as ProductAuthority)+ ) {+ issue(issues, '$.authority', 'invalid_authority', 'authority does not own the action outcome');+ }+ if (+ options.tenantRef+ && tenantRef+ && tenantRefKey(options.tenantRef) !== tenantRefKey(tenantRef)+ ) {+ issue(issues, '$.tenantRef', 'tenant_mismatch', 'source tenant does not match envelope tenant');+ }++ if (+ issues.length > 0+ || authority === undefined+ || !AUTHORITY_SET.has(authority)+ || tenantRef === undefined+ || sourceType === undefined+ || sourceId === undefined+ || sourceVersion === undefined+ || sourceDigest === undefined+ ) {+ return { ok: false, issues };+ }+ return {+ ok: true,+ value: {+ authority: authority as ProductAuthority,+ tenantRef,+ sourceType,+ sourceId,+ sourceVersion,+ sourceDigest: sourceDigest as `sha256:${string}`,+ },+ };+}++export function validateProductActionEnvelope(input: unknown): ValidationResult<ProductActionEnvelopeV1> {+ const issues: ValidationIssue[] = [];+ if (!isRecord(input)) {+ return {+ ok: false,+ issues: [{ path: '$', code: 'invalid_type', message: 'action envelope must be an object' }],+ };+ }+ rejectUnknownFields(input, ENVELOPE_FIELDS, '$', issues);++ const schemaVersion = requireString(input, 'schemaVersion', '$', issues, { max: 64 });+ if (schemaVersion !== undefined && schemaVersion !== PRODUCT_ACTION_ENVELOPE_VERSION) {+ issue(issues, '$.schemaVersion', 'unsupported_value', 'unsupported action envelope version');+ }+ const eventId = requireString(input, 'eventId', '$', issues, { max: 256, pattern: SAFE_TOKEN_RE });+ const issuer = requireString(input, 'issuer', '$', issues, { max: 64 });+ const audience = requireString(input, 'audience', '$', issues, { max: 64 });+ if (issuer !== undefined && !AUTHORITY_SET.has(issuer)) {+ issue(issues, '$.issuer', 'invalid_authority', 'unknown issuer authority');+ }+ if (audience !== undefined && !AUTHORITY_SET.has(audience)) {+ issue(issues, '$.audience', 'invalid_authority', 'unknown audience authority');+ }++ const subject = validateIdentity(input.subject, '$.subject', issues);+ const actor = input.actor === undefined ? undefined : validateIdentity(input.actor, '$.actor', issues);+ const tenantRef = validateTenantRef(input.tenantRef, '$.tenantRef', issues);+ const actionValue = requireString(input, 'action', '$', issues, { max: 128 });+ if (actionValue !== undefined && !isProductAction(actionValue)) {+ issue(issues, '$.action', 'unsupported_value', 'action is outside the product action vocabulary');+ }+ const action = isProductAction(actionValue) ? actionValue : undefined;++ let resourceRefs: string[] | undefined;+ if (!Array.isArray(input.resourceRefs) || input.resourceRefs.length === 0 || input.resourceRefs.length > 32) {+ issue(issues, '$.resourceRefs', 'invalid_type', 'must be an array of 1-32 resource references');+ } else {+ resourceRefs = [];+ input.resourceRefs.forEach((resource, index) => {+ if (+ typeof resource !== 'string'+ || resource.length === 0+ || resource.length > 512+ || !SAFE_TOKEN_RE.test(resource)+ ) {+ issue(issues, `$.resourceRefs[${index}]`, 'invalid_format', 'invalid resource reference');+ } else if (resourceRefs!.includes(resource)) {+ issue(issues, `$.resourceRefs[${index}]`, 'unsupported_value', 'duplicate resource reference');+ } else {+ resourceRefs!.push(resource);+ }+ });+ }++ const requestDigest = validateDigest(input, 'requestDigest', '$', issues, true);+ const contentDigest = validateDigest(input, 'contentDigest', '$', issues, true);+ const idempotencyKey = requireString(input, 'idempotencyKey', '$', issues, {+ optional: true,+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const correlationId = requireString(input, 'correlationId', '$', issues, {+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const causationId = requireString(input, 'causationId', '$', issues, {+ optional: true,+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const sequence = requireString(input, 'sequence', '$', issues, {+ optional: true,+ max: 40,+ pattern: UNSIGNED_DECIMAL_RE,+ });+ const policyReceiptId = requireString(input, 'policyReceiptId', '$', issues, {+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const capabilityId = requireString(input, 'capabilityId', '$', issues, {+ optional: true,+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const validationReceiptId = requireString(input, 'validationReceiptId', '$', issues, {+ optional: true,+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const occurredAt = validateTimestamp(input, 'occurredAt', '$', issues);+ const expiresAt = validateTimestamp(input, 'expiresAt', '$', issues, true);+ if (+ occurredAt !== undefined+ && expiresAt !== undefined+ && Date.parse(expiresAt) <= Date.parse(occurredAt)+ ) {+ issue(issues, '$.expiresAt', 'unsupported_value', 'expiry must be after occurrence');+ }+ const privacyClass = requireString(input, 'privacyClass', '$', issues, { max: 2 });+ if (privacyClass !== undefined && !PRIVACY_CLASS_SET.has(privacyClass)) {+ issue(issues, '$.privacyClass', 'unsupported_value', 'unknown privacy class');+ }+ if (+ action === 'ruview.semantic.publish'+ && privacyClass !== undefined+ && privacyClass !== 'P2'+ && privacyClass !== 'P3'+ ) {+ issue(issues, '$.privacyClass', 'privacy_ceiling_exceeded', 'RuView semantic events must be P2 or P3');+ }+ if (action) {+ const requirements = PRODUCT_ACTION_REQUIREMENTS[action];+ const required: Array<[boolean, string, string]> = [+ [requirements.requestDigest, 'requestDigest', 'action requires a request digest'],+ [requirements.contentDigest, 'contentDigest', 'validated memory commit requires a content digest'],+ [requirements.idempotencyKey, 'idempotencyKey', 'action requires an idempotency key'],+ [requirements.expiry, 'expiresAt', 'action requires a bounded expiry'],+ [requirements.capability, 'capabilityId', 'action requires a narrow capability'],+ [requirements.validationReceipt, 'validationReceiptId', 'validated memory commit requires a validation receipt'],+ ];+ for (const [isRequired, field, message] of required) {+ if (isRequired && input[field] === undefined) issue(issues, `$.${field}`, 'missing', message);+ }+ }++ const sourceResult = validateAuthoritativeReference(input.authoritativeSource, { action, tenantRef });+ if (!sourceResult.ok) {+ for (const sourceIssue of sourceResult.issues) {+ issues.push({+ ...sourceIssue,+ path: sourceIssue.path === '$'+ ? '$.authoritativeSource'+ : `$.authoritativeSource${sourceIssue.path.slice(1)}`,+ });+ }+ }++ if (+ issues.length > 0+ || schemaVersion !== PRODUCT_ACTION_ENVELOPE_VERSION+ || eventId === undefined+ || issuer === undefined+ || !AUTHORITY_SET.has(issuer)+ || audience === undefined+ || !AUTHORITY_SET.has(audience)+ || subject === undefined+ || tenantRef === undefined+ || action === undefined+ || resourceRefs === undefined+ || correlationId === undefined+ || policyReceiptId === undefined+ || occurredAt === undefined+ || privacyClass === undefined+ || !PRIVACY_CLASS_SET.has(privacyClass)+ || !sourceResult.ok+ ) {+ return { ok: false, issues };+ }++ return {+ ok: true,+ value: {+ schemaVersion,+ eventId,+ issuer: issuer as ProductAuthority,+ audience: audience as ProductAuthority,+ subject,+ ...(actor ? { actor } : {}),+ tenantRef,+ action,+ resourceRefs,+ ...(requestDigest ? { requestDigest: requestDigest as `sha256:${string}` } : {}),+ ...(contentDigest ? { contentDigest: contentDigest as `sha256:${string}` } : {}),+ ...(idempotencyKey ? { idempotencyKey } : {}),+ correlationId,+ ...(causationId ? { causationId } : {}),+ authoritativeSource: sourceResult.value,+ ...(sequence ? { sequence } : {}),+ policyReceiptId,+ ...(capabilityId ? { capabilityId } : {}),+ ...(validationReceiptId ? { validationReceiptId } : {}),+ occurredAt,+ ...(expiresAt ? { expiresAt } : {}),+ privacyClass: privacyClass as PrivacyClass,+ },+ };+}++export type RuViewSemanticFieldKind = 'boolean' | 'number' | 'string' | 'nullable-string';++export interface RuViewSemanticFieldSchema {+ kind: RuViewSemanticFieldKind;+ required?: boolean;+ min?: number;+ max?: number;+ maxLength?: number;+ enum?: readonly string[];+}++export interface RuViewObservationSchema {+ privacyClasses: readonly ('P2' | 'P3')[];+ fields: Readonly<Record<string, RuViewSemanticFieldSchema>>;+}++export type RuViewObservationRegistry = Readonly<Record<string, RuViewObservationSchema>>;++/**+ * The default edge-export surface is deliberately small and semantic. A new+ * observation type or field requires explicit schema registration; arbitrary+ * keys are never accepted based on a deny-list alone.+ */+export const DEFAULT_RUVIEW_OBSERVATION_REGISTRY: RuViewObservationRegistry = Object.freeze({+ 'occupancy.state': {+ privacyClasses: ['P2'],+ fields: {+ occupied: { kind: 'boolean', required: true },+ zone: { kind: 'string', maxLength: 64 },+ peopleEstimate: { kind: 'number', min: 0, max: 10_000 },+ },+ },+ 'presence.state': {+ privacyClasses: ['P2'],+ fields: {+ present: { kind: 'boolean', required: true },+ zone: { kind: 'string', maxLength: 64 },+ },+ },+ 'motion.state': {+ privacyClasses: ['P2'],+ fields: {+ active: { kind: 'boolean', required: true },+ intensity: { kind: 'number', min: 0, max: 1 },+ },+ },+ 'vital.summary': {+ privacyClasses: ['P3'],+ fields: {+ state: {+ kind: 'string',+ required: true,+ enum: ['normal', 'attention', 'critical', 'unknown'],+ },+ anomaly: { kind: 'boolean', required: true },+ label: { kind: 'nullable-string', maxLength: 128 },+ },+ },+});++function looksLikeRawEncoding(value: string): boolean {+ return /^data:[^,]{1,128};base64,/i.test(value)+ || BASE64_SHAPED_RE.test(value)+ || BASE64URL_SHAPED_RE.test(value);+}++function validateSemanticValue(+ value: unknown,+ schema: RuViewObservationSchema | undefined,+ privacyClass: unknown,+ issues: ValidationIssue[],+): value is RuViewSemanticObservationV1['value'] {+ if (!schema) {+ issue(issues, '$.observationType', 'unsupported_value', 'observation type is not registered for edge export');+ return false;+ }+ if (privacyClass !== 'P2' && privacyClass !== 'P3') return false;+ if (!schema.privacyClasses.includes(privacyClass)) {+ issue(issues, '$.privacyClass', 'privacy_ceiling_exceeded', 'privacy class is not permitted by the observation schema');+ }+ if (!isRecord(value)) {+ issue(issues, '$.value', 'privacy_ceiling_exceeded', 'registered semantic observations require an object value');+ return false;+ }++ let valid = true;+ for (const key of Object.keys(value)) {+ if (!Object.prototype.hasOwnProperty.call(schema.fields, key)) {+ issue(issues, `$.value.${key}`, 'unknown_field', 'field is not registered for this observation type');+ valid = false;+ }+ }+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {+ const field = value[key];+ if (field === undefined) {+ if (fieldSchema.required) {+ issue(issues, `$.value.${key}`, 'missing', 'required semantic field is missing');+ valid = false;+ }+ continue;+ }+ if (typeof field === 'string' && looksLikeRawEncoding(field)) {+ issue(issues, `$.value.${key}`, 'privacy_ceiling_exceeded', 'base64-shaped or data-URL values cannot leave the edge');+ valid = false;+ continue;+ }+ if (fieldSchema.kind === 'boolean') {+ if (typeof field !== 'boolean') {+ issue(issues, `$.value.${key}`, 'invalid_type', 'must be a boolean');+ valid = false;+ }+ continue;+ }+ if (fieldSchema.kind === 'number') {+ if (+ typeof field !== 'number'+ || !Number.isFinite(field)+ || (fieldSchema.min !== undefined && field < fieldSchema.min)+ || (fieldSchema.max !== undefined && field > fieldSchema.max)+ ) {+ issue(issues, `$.value.${key}`, 'invalid_format', 'must be a finite number within the registered bounds');+ valid = false;+ }+ continue;+ }+ if (fieldSchema.kind === 'nullable-string' && field === null) continue;+ if (typeof field !== 'string' || field.length > (fieldSchema.maxLength ?? 256)) {+ issue(issues, `$.value.${key}`, 'invalid_type', 'must be a bounded string');+ valid = false;+ continue;+ }+ if (fieldSchema.enum && !fieldSchema.enum.includes(field)) {+ issue(issues, `$.value.${key}`, 'unsupported_value', 'value is outside the registered semantic vocabulary');+ valid = false;+ }+ }+ return valid;+}++export function validateRuViewSemanticObservation(+ input: unknown,+ registry: RuViewObservationRegistry = DEFAULT_RUVIEW_OBSERVATION_REGISTRY,+): ValidationResult<RuViewSemanticObservationV1> {+ const issues: ValidationIssue[] = [];+ if (!isRecord(input)) {+ return {+ ok: false,+ issues: [{ path: '$', code: 'invalid_type', message: 'RuView observation must be an object' }],+ };+ }+ rejectUnknownFields(input, RUVIEW_FIELDS, '$', issues);++ const schemaVersion = requireString(input, 'schemaVersion', '$', issues, { max: 64 });+ if (schemaVersion !== undefined && schemaVersion !== 'ruview.semantic-observation.v1') {+ issue(issues, '$.schemaVersion', 'unsupported_value', 'unsupported RuView observation version');+ }+ const spaceRef = validateTenantRef(input.spaceRef, '$.spaceRef', issues);+ if (spaceRef && spaceRef.namespace !== 'ruview-space') {+ issue(issues, '$.spaceRef.namespace', 'identity_namespace_required', 'RuView observation requires a RuView space namespace');+ }+ const observationType = requireString(input, 'observationType', '$', issues, {+ max: 128,+ pattern: SAFE_TOKEN_RE,+ });+ const privacyClass = requireString(input, 'privacyClass', '$', issues, { max: 2 });+ if (privacyClass !== undefined && privacyClass !== 'P2' && privacyClass !== 'P3') {+ issue(issues, '$.privacyClass', 'privacy_ceiling_exceeded', 'RuView product-plane observations must be P2 or P3');+ }+ const valueValid = validateSemanticValue(+ input.value,+ observationType ? registry[observationType] : undefined,+ privacyClass,+ issues,+ );++ const confidence = input.confidence;+ if (typeof confidence !== 'number' || !Number.isFinite(confidence) || confidence < 0 || confidence > 1) {+ issue(issues, '$.confidence', 'invalid_format', 'confidence must be finite and between 0 and 1');+ }+ const uncertainty = input.uncertainty;+ if (+ uncertainty !== undefined+ && (typeof uncertainty !== 'number' || !Number.isFinite(uncertainty) || uncertainty < 0 || uncertainty > 1)+ ) {+ issue(issues, '$.uncertainty', 'invalid_format', 'uncertainty must be finite and between 0 and 1');+ }+ if (typeof input.abstained !== 'boolean') {+ issue(issues, '$.abstained', input.abstained === undefined ? 'missing' : 'invalid_type', 'abstained must be a boolean');+ }+ const modelDigest = validateDigest(input, 'modelDigest', '$', issues);+ const calibrationDigest = validateDigest(input, 'calibrationDigest', '$', issues, true);+ const hardwareRef = requireString(input, 'hardwareRef', '$', issues, {+ optional: true,+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const observedAt = validateTimestamp(input, 'observedAt', '$', issues);+ const expiresAt = validateTimestamp(input, 'expiresAt', '$', issues);+ if (+ observedAt !== undefined+ && expiresAt !== undefined+ && Date.parse(expiresAt) <= Date.parse(observedAt)+ ) {+ issue(issues, '$.expiresAt', 'unsupported_value', 'observation expiry must be after observation time');+ }+ const sequence = requireString(input, 'sequence', '$', issues, {+ max: 40,+ pattern: UNSIGNED_DECIMAL_RE,+ });++ if (+ issues.length > 0+ || schemaVersion !== 'ruview.semantic-observation.v1'+ || spaceRef === undefined+ || spaceRef.namespace !== 'ruview-space'+ || observationType === undefined+ || registry[observationType] === undefined+ || !valueValid+ || typeof confidence !== 'number'+ || typeof input.abstained !== 'boolean'+ || modelDigest === undefined+ || (privacyClass !== 'P2' && privacyClass !== 'P3')+ || observedAt === undefined+ || expiresAt === undefined+ || sequence === undefined+ ) {+ return { ok: false, issues };+ }++ return {+ ok: true,+ value: {+ schemaVersion,+ spaceRef: { namespace: 'ruview-space', id: spaceRef.id },+ observationType,+ value: input.value as RuViewSemanticObservationV1['value'],+ confidence,+ ...(typeof uncertainty === 'number' ? { uncertainty } : {}),+ abstained: input.abstained,+ modelDigest: modelDigest as `sha256:${string}`,+ ...(calibrationDigest ? { calibrationDigest: calibrationDigest as `sha256:${string}` } : {}),+ ...(hardwareRef ? { hardwareRef } : {}),+ privacyClass,+ observedAt,+ expiresAt,+ sequence,+ },+ };+}++function assertUnicodeScalarString(value: string): void {+ for (let index = 0; index < value.length; index++) {+ const code = value.charCodeAt(index);+ if (code >= 0xd800 && code <= 0xdbff) {+ const next = value.charCodeAt(index + 1);+ if (!(next >= 0xdc00 && next <= 0xdfff)) {+ throw new TypeError('JCS canonicalization rejects an unpaired high surrogate');+ }+ index++;+ } else if (code >= 0xdc00 && code <= 0xdfff) {+ throw new TypeError('JCS canonicalization rejects an unpaired low surrogate');+ }+ }+}++/**+ * RFC 8785/JCS-compatible canonical JSON for this I-JSON profile.+ *+ * ECMAScript's JSON number serialization supplies the JCS number rendering.+ * Non-finite numbers, sparse arrays, undefined values, non-plain objects, and+ * invalid Unicode are rejected instead of being silently coerced.+ */+export function canonicalizeProductPlane(value: unknown): string {+ if (value === null) return 'null';+ if (typeof value === 'boolean') return value ? 'true' : 'false';+ if (typeof value === 'string') {+ assertUnicodeScalarString(value);+ return JSON.stringify(value);+ }+ if (typeof value === 'number') {+ if (!Number.isFinite(value)) throw new TypeError('JCS canonicalization rejects non-finite numbers');+ return JSON.stringify(value);+ }+ if (Array.isArray(value)) {+ const items: string[] = [];+ for (let index = 0; index < value.length; index++) {+ if (!Object.prototype.hasOwnProperty.call(value, index)) {+ throw new TypeError('JCS canonicalization rejects sparse arrays');+ }+ items.push(canonicalizeProductPlane(value[index]));+ }+ return `[${items.join(',')}]`;+ }+ if (!isRecord(value)) {+ throw new TypeError('JCS canonicalization accepts only JSON-compatible plain objects');+ }+ const entries: string[] = [];+ for (const key of Object.keys(value).sort()) {+ assertUnicodeScalarString(key);+ if (value[key] === undefined) {+ throw new TypeError('JCS canonicalization rejects undefined object values');+ }+ entries.push(`${JSON.stringify(key)}:${canonicalizeProductPlane(value[key])}`);+ }+ return `{${entries.join(',')}}`;+}++export function canonicalProductPlaneBytes(value: unknown): Uint8Array {+ return Buffer.from(canonicalizeProductPlane(value), 'utf8');+}++export function canonicalProductPlaneDigest(value: unknown): `sha256:${string}` {+ return `sha256:${createHash('sha256').update(canonicalProductPlaneBytes(value)).digest('hex')}`;+}++export interface SignedProductActionEnvelopeV1 {+ envelope: ProductActionEnvelopeV1;+ algorithm: 'Ed25519';+ keyId: string;+ signature: string;+}++export type SignatureVerifier = (input: {+ issuer: ProductAuthority;+ keyId: string;+ algorithm: 'Ed25519';+ canonicalBytes: Uint8Array;+ signature: Uint8Array;+}) => boolean | Promise<boolean>;++export type AuthorityKeyResolver = (+ issuer: ProductAuthority,+ keyId: string,+) => KeyLike | null | undefined | Promise<KeyLike | null | undefined>;++export interface ReplayReservationInput {+ key: string;+ bindingDigest: `sha256:${string}`;+ expiresAt: number;+}++export type ReplayReservation = 'reserved' | 'replay' | 'conflict';++/**+ * The implementation must reserve atomically. A lookup-then-insert adapter is+ * not a conforming replay store under concurrent delivery.+ */+export interface ProductEnvelopeReplayStore {+ reserve(input: ReplayReservationInput): ReplayReservation | Promise<ReplayReservation>;+}++export type LocalAuthorizationDecision =+ | boolean+ | { allowed: boolean; reason?: string };++export interface ProductEnvelopeVerifierOptions {+ expectedAudience: ProductAuthority;+ expectedTenantRef: NamespacedTenantRef;+ now?: () => number;+ maxAgeMs?: number;+ maxFutureSkewMs?: number;+ resolveKey?: AuthorityKeyResolver;+ verifySignature?: SignatureVerifier;+ replayStore: ProductEnvelopeReplayStore;+ policyVerifier: (+ envelope: ProductActionEnvelopeV1,+ ) => LocalAuthorizationDecision | Promise<LocalAuthorizationDecision>;+ capabilityVerifier: (+ envelope: ProductActionEnvelopeV1,+ ) => LocalAuthorizationDecision | Promise<LocalAuthorizationDecision>;+}++export type ProductEnvelopeVerificationCode =+ | 'malformed_signed_envelope'+ | 'invalid_envelope'+ | 'audience_mismatch'+ | 'tenant_mismatch'+ | 'not_yet_valid'+ | 'stale'+ | 'expired'+ | 'signature_configuration_missing'+ | 'key_not_found'+ | 'signature_invalid'+ | 'policy_denied'+ | 'capability_denied'+ | 'replay_detected'+ | 'idempotency_conflict'+ | 'verification_error';++export type ProductEnvelopeVerificationResult =+ | {+ ok: true;+ envelope: ProductActionEnvelopeV1;+ canonicalDigest: `sha256:${string}`;+ replayKey: string;+ }+ | {+ ok: false;+ code: ProductEnvelopeVerificationCode;+ reason: string;+ issues?: ValidationIssue[];+ };++const SIGNED_ENVELOPE_FIELDS = new Set(['envelope', 'algorithm', 'keyId', 'signature']);+const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;++function deny(+ code: ProductEnvelopeVerificationCode,+ reason: string,+ issues?: ValidationIssue[],+): ProductEnvelopeVerificationResult {+ return { ok: false, code, reason, ...(issues ? { issues } : {}) };+}++function authorizationAllowed(decision: LocalAuthorizationDecision): boolean {+ return typeof decision === 'boolean' ? decision : decision.allowed;+}++function authorizationReason(decision: LocalAuthorizationDecision, fallback: string): string {+ return typeof decision === 'boolean' ? fallback : decision.reason ?? fallback;+}++function decodeBase64Url(value: string): Uint8Array | undefined {+ if (!BASE64URL_RE.test(value)) return undefined;+ const decoded = Buffer.from(value, 'base64url');+ if (decoded.length === 0 || decoded.toString('base64url') !== value) return undefined;+ return decoded;+}++function replayKeyFor(envelope: ProductActionEnvelopeV1): string {+ const parts = [+ envelope.issuer,+ tenantRefKey(envelope.tenantRef),+ identityKey(envelope.subject),+ envelope.action,+ envelope.idempotencyKey ?? envelope.eventId,+ ];+ return parts.map((part) => `${part.length}:${part}`).join('');+}++/**+ * Verify a signed product action as an ingress policy-enforcement decision.+ *+ * Signature validity is necessary but insufficient: audience, tenant,+ * freshness, replay state, local policy, and the action-bound capability are+ * checked independently. Service availability is intentionally absent; a+ * valid claim never implies that its target is configured, reachable, or+ * healthy.+ */+export async function verifySignedProductActionEnvelope(+ input: unknown,+ options: ProductEnvelopeVerifierOptions,+): Promise<ProductEnvelopeVerificationResult> {+ if (!isRecord(input)) return deny('malformed_signed_envelope', 'signed envelope must be an object');+ const wrapperIssues: ValidationIssue[] = [];+ rejectUnknownFields(input, SIGNED_ENVELOPE_FIELDS, '$', wrapperIssues);+ const algorithm = requireString(input, 'algorithm', '$', wrapperIssues, { max: 16 });+ const keyId = requireString(input, 'keyId', '$', wrapperIssues, {+ max: 256,+ pattern: SAFE_TOKEN_RE,+ });+ const signatureText = requireString(input, 'signature', '$', wrapperIssues, { max: 128 });+ if (algorithm !== undefined && algorithm !== 'Ed25519') {+ issue(wrapperIssues, '$.algorithm', 'unsupported_value', 'only Ed25519 is supported');+ }+ const signature = signatureText ? decodeBase64Url(signatureText) : undefined;+ if (signatureText && (!signature || signature.length !== 64)) {+ issue(wrapperIssues, '$.signature', 'invalid_format', 'must be a canonical 64-byte base64url signature');+ }+ if (!Object.prototype.hasOwnProperty.call(input, 'envelope')) {+ issue(wrapperIssues, '$.envelope', 'missing', 'signed envelope payload is missing');+ }+ if (wrapperIssues.length > 0 || algorithm !== 'Ed25519' || !keyId || !signature) {+ return deny('malformed_signed_envelope', 'signed envelope wrapper is invalid', wrapperIssues);+ }++ const parsed = validateProductActionEnvelope(input.envelope);+ if (!parsed.ok) return deny('invalid_envelope', 'action envelope is invalid', parsed.issues);+ const envelope = parsed.value;+ if (envelope.audience !== options.expectedAudience) {+ return deny('audience_mismatch', 'envelope audience does not match this service');+ }+ if (tenantRefKey(envelope.tenantRef) !== tenantRefKey(options.expectedTenantRef)) {+ return deny('tenant_mismatch', 'envelope tenant does not match the authenticated local tenant');+ }++ const now = options.now?.() ?? Date.now();+ const maxAgeMs = options.maxAgeMs ?? 5 * 60_000;+ const maxFutureSkewMs = options.maxFutureSkewMs ?? 30_000;+ if (+ !Number.isFinite(now)+ || !Number.isFinite(maxAgeMs)+ || maxAgeMs < 0+ || !Number.isFinite(maxFutureSkewMs)+ || maxFutureSkewMs < 0+ ) {+ return deny('verification_error', 'verifier clock configuration is invalid');+ }+ const occurredAt = Date.parse(envelope.occurredAt);+ if (occurredAt > now + maxFutureSkewMs) return deny('not_yet_valid', 'envelope occurrence is in the future');+ if (now - occurredAt > maxAgeMs) return deny('stale', 'envelope exceeds the accepted freshness window');+ const expiresAt = envelope.expiresAt ? Date.parse(envelope.expiresAt) : occurredAt + maxAgeMs;+ if (expiresAt <= now) return deny('expired', 'envelope has expired');++ let canonicalBytes: Uint8Array;+ let canonicalDigest: `sha256:${string}`;+ try {+ canonicalBytes = canonicalProductPlaneBytes(input.envelope);+ canonicalDigest = canonicalProductPlaneDigest(input.envelope);+ } catch {+ return deny('invalid_envelope', 'envelope cannot be canonically encoded');+ }++ try {+ let signatureValid = false;+ if (options.verifySignature) {+ signatureValid = await options.verifySignature({+ issuer: envelope.issuer,+ keyId,+ algorithm,+ canonicalBytes,+ signature,+ });+ } else if (options.resolveKey) {+ const key = await options.resolveKey(envelope.issuer, keyId);+ if (!key) return deny('key_not_found', 'issuer key is unavailable or untrusted');+ signatureValid = verifyCryptoSignature(null, canonicalBytes, key, signature);+ } else {+ return deny('signature_configuration_missing', 'no authority key resolver or signature verifier is configured');+ }+ if (!signatureValid) return deny('signature_invalid', 'envelope signature is invalid');++ const policyDecision = await options.policyVerifier(envelope);+ if (!authorizationAllowed(policyDecision)) {+ return deny('policy_denied', authorizationReason(policyDecision, 'local policy denied the action'));+ }++ const requirements = PRODUCT_ACTION_REQUIREMENTS[envelope.action];+ if (requirements.capability || envelope.capabilityId) {+ const capabilityDecision = await options.capabilityVerifier(envelope);+ if (!authorizationAllowed(capabilityDecision)) {+ return deny(+ 'capability_denied',+ authorizationReason(capabilityDecision, 'local capability verifier denied the action'),+ );+ }+ }++ const replayKey = replayKeyFor(envelope);+ const reservation = await options.replayStore.reserve({+ key: replayKey,+ bindingDigest: canonicalDigest,+ expiresAt,+ });+ if (reservation === 'replay') return deny('replay_detected', 'envelope was already accepted');+ if (reservation === 'conflict') {+ return deny('idempotency_conflict', 'idempotency identity is bound to different canonical bytes');+ }+ if (reservation !== 'reserved') return deny('verification_error', 'replay store returned an invalid result');+ return { ok: true, envelope, canonicalDigest, replayKey };+ } catch {+ return deny('verification_error', 'an authority, policy, capability, or replay verifier failed');+ }+}diff --git a/v3/docs/adr/ADR-325-claim-federation-zero-trust-capability-plane.md b/v3/docs/adr/ADR-325-claim-federation-zero-trust-capability-plane.mdnew file mode 100644index 0000000000..dc337e2d71--- /dev/null+++ b/v3/docs/adr/ADR-325-claim-federation-zero-trust-capability-plane.md@@ -0,0 +1,756 @@+# ADR-325: Claim Federation as a Zero-Trust Capability and Work-Ownership Plane++**Status**: Proposed — security-critical integration work required before production federation+**Date**: 2026-07-28+**Decision owners**: Ruflo security, claims, federation, and policy maintainers+**Supersedes**: ADR-101's production-readiness conclusion, but not its component design+**Related**: ADR-086, ADR-101, ADR-109, ADR-144, ADR-320, ADR-324,+ADR-326, ADR-327++## Executive decision++Ruflo's claim federation is **not optimally integrated today**.++The repository contains useful federation components: work-claim domain models,+hybrid logical clocks, vector clocks, signed federation envelopes, discovery,+PII controls, A2A card support, and the ADR-324 policy engine. These pieces do+not yet form one authenticated, authorized, replay-resistant, durable, and+partition-safe production path.++This ADR adopts a single zero-trust capability plane with four distinct+responsibilities:++1. **Work ownership** records who owns a unit of work.+2. **Workload identity** establishes which human, agent, process, and trust+ domain is acting.+3. **Authorization grants** constrain what that actor may do, to which+ resource, for whom, and for how long.+4. **Policy enforcement** evaluates every ingress, egress, delegation, and+ ownership transition and writes a verifiable decision receipt.++The implementation will preserve local, single-node behavior. Federated+ownership-changing operations will remain disabled until the critical+correctness gates in this ADR pass.++The design uses existing standards at interoperability boundaries:++- SPIFFE-compatible workload identities and rotating trust-domain bundles;+- OAuth 2.0 Token Exchange for explicit subject/actor delegation;+- audience-restricted, sender-constrained grants using DPoP or mTLS;+- OpenID Federation for optional multilateral trust-chain discovery;+- Shared Signals/CAEP for continuous revocation and risk events;+- MCP protected-resource metadata and A2A security declarations.++Ruflo does **not** require SPIRE, OAuth, or an external identity provider for+local use. Provider interfaces retain the current local Ed25519 identity as the+default compatibility profile.++Two companion profiles make this umbrella decision implementable without+turning it into one unbounded programme:++- ADR-326 defines the Cognitum dashboard, Meta-LLM, Comms, Cog Studio, and+ RuView authority, identity, event, privacy, and migration contract.+- ADR-327 defines repository harness, worktree, lease, fencing, message, and+ exact-source receipt semantics for concurrent Codex and Claude development.++Neither companion changes this ADR's trust model. Product actions and+development leases are both evaluated by ADR-324 policy, but they remain+different resource and capability domains.++## Why this ADR exists++ADR-101 correctly identified the components needed to move work claims across+nodes. It then described those components as implemented. A production-path+audit in July 2026 found that component presence and end-to-end enforcement had+been conflated.++The term `claim` also names three different concepts in the current system:++| Current surface | Meaning | Current persistence/enforcement |+|---|---|---|+| `@claude-flow/claims` | Exclusive work ownership, handoff, and stealing | Domain package with local in-memory adapters and optional federation wrappers |+| `ruflo claims` | Local capability-like grants | `.claude-flow/claims.json` |+| Federation `PolicyEngine` claims | Message-type authorization requirements | Independent enum; production dependency currently returns `true` |++A fourth, more complete authorization system now exists in+`@claude-flow/security`: the ADR-324 `AgenticPolicyEngine`. Maintaining four+partially overlapping authorities makes fail-open behavior and confused-deputy+errors likely.++This ADR uses the following normative vocabulary:++- **Work claim**: ownership of an issue, task, shard, or other work resource.+- **Authorization grant**: permission to perform actions on resources.+- **Identity assertion**: evidence identifying a subject or actor.+- **Decision receipt**: tamper-evident evidence of a policy decision.++Legacy command and API names remain as compatibility aliases, but new code MUST+use these terms.++## Pre-remediation current-state audit++The findings below describe the baseline that motivated this ADR. They are+retained for traceability; the implementation-progress section immediately+after the table records the opt-in remediations now present on this branch.++### What is already strong++- `@claude-flow/claims` has a clean domain/application/infrastructure split.+- `FederationBridge`, `FederatedClaimEventStore`, HLC, and vector-clock+ components provide a useful protocol substrate.+- Production plugin construction supplies an Ed25519 verifier to the inbound+ dispatcher.+- Peer discovery can suspend or evict a peer, and accepted/rejected deliveries+ are audited.+- The federation message model includes `claim-event` and `agent-handoff`, and+ maps them to capability requirements.+- ADR-324 supplies versioned rules, approvals, budgets, tamper-evident+ receipts, atomic local policy-state mutation, and compatibility modes.++### Integration gaps++| Severity | Finding | Repository evidence | Consequence |+|---|---|---|---|+| Critical | Nested message values are not reliably covered by the outer signature | `canonicalizeEnvelopeForVerify()` uses a `JSON.stringify` property allowlist derived only from top-level keys | A nested payload mutation can canonicalize to the same signed bytes |+| Critical | Federation authorization is stubbed | Plugin constructs `PolicyEngine({ checkClaim: () => true })` | Required claims do not restrict production sends |+| High | Inbound policy enforcement is absent | `dispatchInbound()` verifies peer state and the outer signature, then emits an event | No ingress authorization, PII/AI scan, rate limit, audience, tenant, expiry, or replay decision |+| High | Claim federation is not composed at runtime | Federation plugin has no dependency on `@claude-flow/claims`; no production construction of `FederatedClaimRepository`, `FederatedClaimEventStore`, or `FederationBridge` was found | Implemented components are not an operational feature |+| High | No inbound claim/handoff handler is registered | No production listener for `federation:inbound:claim-event` or `federation:inbound:agent-handoff` was found | Remote work events are delivered to no domain transaction |+| High | Exclusive ownership is eventually replicated without a fencing authority | Concurrent vector-clock writes are rejected locally, but no lease, quorum, or authoritative epoch exists | A partition can produce two actors that each believe they own the same work |+| High | Storage is neither durable nor atomic | Federated store wraps `InMemoryClaimEventStore`; publish failure reaches into a private event array to roll back | Crash boundaries can leave contradictory local and remote histories |+| Medium | Federated query is a placeholder | `includeRemote` is documented as a no-op | Callers may overestimate federation-wide visibility |+| Medium | The default message allowlist excludes claim messages | `DEFAULT_SECURITY_POLICY.allowedMessageTypes` omits `claim-event` and `agent-handoff` | Properly authorized sends are rejected unless policy is overridden |+| Medium | Replay fields are not enforced | Envelope metadata carries time/session data, but ingress has no nonce cache or freshness/audience check | A valid old ownership message can be replayed |+| Medium | A2A discovery is descriptive rather than trusted | Cards expose optional security fields, but local conversion does not populate them by default | A peer's advertised capability is not an authorization grant |+| Medium | Legacy local capability loading can fail open | A malformed/missing local claims file defaults non-admin checks to permissive behavior | Corruption can expand effective privilege |++### Implementation progress after the audit++The federation plugin now provides these opt-in foundations:++- recursively canonical JCS/Ed25519 envelope signing under negotiated+ `jcs-v1`, advertised by default by upgraded peers and trusted only from a+ signature-verified peer manifest, while retaining byte-for-byte+ `legacy-v1` verification;+- explicit `legacy`, `observe`, and `enforce` authorization modes backed by a+ concrete claim checker instead of an anonymous always-true callback;+- an inbound evaluator that runs after signature verification and before+ replay marking, acceptance audit, or event emission;+- fail-closed enforcement for denial, missing evaluators, evaluator errors, or+ malformed decisions;+- a legacy allowlist limited to `heartbeat` and `status-broadcast`.++Consequential and unknown legacy message types—including work claims,+handoffs, task assignments, context/memory transfer, trust, topology, and spawn+operations—are rejected before authorization or emission and cannot be sent+from an upgraded peer to an endpoint-only or legacy-only peer. Endpoint-only+joins remain untrusted and negotiate no optional protocol; providing the+peer's signed manifest enables JCS without treating the current process as the+remote handshake responder. This preserves low-risk health/status+interoperability with previous installations without silently downgrading+consequential traffic. Nested JCS tampering and+verify-before-authorize-before-emit ordering are covered by tests.++This closes the first three baseline findings for the implemented plugin path,+but it does not make the overall federation production-ready. Runtime+composition with the claims repository, durable ingress/outbox storage,+federated fencing authority, grant exchange, identity federation, revocation,+and the production Cognitum enforcement points remain pending.++The concurrent Cognitum audit also found that its current website harness has+valuable path/resource leases, heartbeats, messages, ports, and run receipts,+but several writers share one dirty worktree and receipts bind only `HEAD`.+That coordination state cannot prove the exact source snapshot or fence a stale+writer. ADR-327 adopts the useful harness contract while retaining one+worktree per writer and adding source-state identity and fencing epochs.++The product audit found no production Ruflo verifier in Cognitum Functions.+Firebase tenancy, Meta-LLM account identity, AgentBBS identity, and RuView edge+authority must therefore remain separate until ADR-326's verified principal+links, audience-bound grants, and local enforcement points are implemented.++ADR-101 remains useful as a component-level design record. Its assertion that+federated claims are production-wired is superseded by this audit until the+acceptance tests below pass.++## Security invariant++For every federated action:++```text+authenticated workload+ + trusted federation relationship+ + valid, narrower delegated grant+ + current policy authorization+ + valid work-ownership transition+ + durable receipt+ = eligible execution+```++No one term can substitute for another:++- a signed envelope proves control of a key, not permission;+- an Agent Card advertises a capability, not authority;+- a work claim records ownership, not unrestricted tool access;+- an authorization grant allows an action, not a conflicting ownership state;+- a consensus result does not excuse a failed local safety policy.++## Decision++### 1. Unify policy authority without unifying domain objects++ADR-324 `AgenticPolicyEngine` becomes the sole policy decision point for Ruflo+federation. The federation plugin becomes a policy enforcement point at both+ingress and egress.++Work claims remain in `@claude-flow/claims`; they are not converted into+authorization tokens. Instead, work-ownership facts become one input to policy:++```text+subject: user:alice+actor: spiffe://team-a.example/agent/coder-7+action: work.handoff+resource: ruflo://repo/acme/api/issues/136+workOwner: agent:planner-2+tenant: acme+environment: production+```++The engine returns `allow`, `deny`, or `require_approval` and a signed decision+receipt. Federation code MUST NOT contain an independent `checkClaim: () =>+true` authorization path.++### 2. Introduce explicit identity and trust providers++The capability plane defines these provider interfaces:++```ts+interface WorkloadIdentityProvider {+ currentIdentity(): Promise<WorkloadIdentity>;+ verify(assertion: IdentityAssertion): Promise<VerifiedIdentity>;+}++interface TrustBundleProvider {+ resolve(trustDomain: string): Promise<VersionedTrustBundle>;+ watch(onChange: (bundle: VersionedTrustBundle) => void): () => void;+}++interface AuthorizationGrantProvider {+ exchange(request: DelegationRequest): Promise<AuthorizationGrant>;+ verify(grant: AuthorizationGrant, proof: SenderProof): Promise<VerifiedGrant>;+ revoke(grantId: string, reason: string): Promise<void>;+}+```++The default `LocalKeyIdentityProvider` wraps Ruflo's existing Ed25519 node+keypair. An optional `SpiffeIdentityProvider` obtains X.509-SVID or JWT-SVID+material through the SPIFFE Workload API.++Federation relationships are one-way records binding:++```text+trustDomain+bundleEndpoint+endpointProfile+acceptedAlgorithms+policyProfile+maximumDelegationDepth+statusFeed+```++This follows SPIFFE Federation's central rule: the configured trust-domain name+must remain bound to the correct rotating bundle. Mutual trust requires two+explicit relationships.++For small deployments, relationships remain directly configured and pinned.+OpenID Federation is an optional resolver for larger, multilateral+federations. A resolved trust chain MUST be rooted in a locally configured+anchor, MUST apply metadata policy monotonically, and MUST fail closed on a+conflict.++### 3. Use narrow, sender-constrained delegation++Cross-agent delegation uses an RFC 8693-compatible subject/actor model. A+delegated grant MUST include:++```text+issuer+subject+actor (and bounded actor chain)+audience/resource+tenant+actions+resource selectors+not-before and expiry+grant ID+parent grant hash+delegation depth+proof-of-possession key thumbprint+policy version+```++Token exchange MUST only produce a grant whose actions, resources, audience,+expiry, budget, and delegation depth are equal to or narrower than its inputs.+The subject and actor remain separately attributable.++Bearer-only grants are prohibited for federated ownership mutations.+Deployments use one of:++- mTLS/certificate-bound access tokens where the transport exposes a workload+ certificate; or+- DPoP proofs where application-layer key binding is required.++Every resource server validates the intended audience. Ruflo never passes the+incoming token through to a downstream MCP server or agent; it exchanges it+for a narrower, audience-specific grant.++### 4. Define one canonical signed envelope++Federation v2 envelopes use:++```text+canonical form: RFC 8785 JSON Canonicalization Scheme (JCS)+payload subset: I-JSON+signature: Ed25519+content ID: sha256:<lowercase hex>+timestamp: RFC 3339 UTC+```++The protected signed object includes the protocol name, version, message type,+message ID, source identity, target identity/audience, tenant, session ID,+issued-at, expiry, nonce, content type, complete nested payload, authorization+grant hash, and policy profile.++Signing and verification MUST use the same recursive canonicalizer. Duplicate+keys, non-finite numbers, negative zero, values outside the I-JSON safe+interoperability range, unknown critical headers, and unsupported versions are+rejected before policy evaluation.++Legacy v1 envelopes may be read only in `legacy` or `observe` mode between+explicitly pinned peers. They MUST NOT authorize work acquisition, release,+steal, handoff, promotion, tool execution, or administrative changes.++### 5. Enforce a single symmetric message pipeline++Inbound processing order is normative:++```text+wire size and framing+ -> strict schema/version/I-JSON validation+ -> JCS content ID and Ed25519 verification+ -> target, audience, tenant, time, session, and nonce/replay checks+ -> peer identity and trust-bundle validation+ -> key/revocation/status validation+ -> PII, prompt-injection, and content policy+ -> ADR-324 authorization decision+ -> idempotent domain transaction+ -> decision + domain receipt append+ -> typed event after commit+```++Egress performs the corresponding checks before transmission, including PII+scanning, authorization, audience-specific token exchange, and an outbox+transaction. A message is never considered delivered merely because a local+event was appended.++The dispatcher has no unsigned production mode. Legacy tests can inject a+verifier only through an explicitly named test adapter.++### 6. Split ownership consistency by operation++Vector clocks and HLCs remain useful for causal replication, diagnostics,+progress updates, notes, and other mergeable observations. They are+insufficient to guarantee exclusive ownership during a network partition.++Ownership-changing transitions use a CP authority:++```ts+interface WorkOwnershipRecord {+ claimId: string;+ authorityDomain: string;+ owner: string | null;+ epoch: bigint; // monotonic fencing token+ leaseExpiresAt: string;+ version: bigint;+ lastReceiptId: string;+}+```++Each work resource has one configured authority domain. `acquire`, `steal`,+`handoff`, `release`, and lease renewal are compare-and-swap transactions at+that authority:++```text+commit only when:+ authority == configuredAuthority+ current.version == request.expectedVersion+ current.epoch == request.expectedEpoch+ grant permits the exact transition+ idempotencyKey has not committed a different request+```++A successful ownership transition increments the fencing epoch. Every worker+must present that epoch to protected side effects; a resource adapter rejects+stale epochs. A lease expiry permits reassignment but never makes an old epoch+valid again.++The first implementation may use an existing linearizable store with+transaction, lease, and revision support. A pluggable `OwnershipAuthority`+keeps local single-node CAS as the default and permits an etcd/consensus-backed+provider for multi-node deployments.++During loss of quorum, ownership mutations fail closed. Progress telemetry and+other AP-safe data may continue to replicate.++### 7. Make event delivery durable and idempotent++Federated work events use a transactional outbox and durable inbox:++- the ownership/domain mutation, decision receipt, and outbox append commit+ atomically;+- delivery is at least once;+- the inbox deduplicates by message ID plus content ID;+- applying the same message twice returns the original receipt;+- a message ID paired with a different content ID is a security incident;+- the receiver acknowledges only after its domain transaction commits;+- retries use bounded exponential backoff and a dead-letter state;+- startup rebuilds HLC/vector state from durable history.++Code must not mutate a private in-memory event array to simulate rollback.++### 8. Add continuous revocation++Short-lived grants are the baseline. The trust plane also consumes signed+status events for:++- grant revocation;+- workload suspension or eviction;+- trust-bundle/key rotation;+- policy-profile change;+- tenant membership removal;+- detected credential compromise.++The transport uses a Shared Signals/CAEP-compatible adapter where an enterprise+issuer supports it. Local and bilateral deployments use the same internal+event model without requiring an external provider.++High-risk actions re-check current status online. Lower-risk actions may use a+bounded cache. Revocation delay is visible in decision receipts.++### 9. Interoperate with MCP and A2A without weakening policy++For HTTP MCP:++- expose OAuth Protected Resource Metadata;+- discover the authorization server through the protected-resource contract;+- request audience-specific resource indicators;+- validate that the presented grant was issued for this MCP resource;+- exchange rather than forward an inbound token to downstream services.++For A2A:++- publish `securitySchemes` and `securityRequirements` in Agent Cards;+- authenticate every request;+- authorize every operation, skill, resource, and tenant boundary;+- keep credentials out of Agent Card payloads;+- bind chained-task credentials to the originating agent;+- protect Agent Card fetching against SSRF, redirects to private networks,+ excessive response size, and DNS rebinding.++A2A and MCP are protocol adapters into the same identity, grant, and+ADR-324 decision model. Neither protocol becomes an alternate authority.++## Reference architecture++```text+ Trust configuration / rotating bundles+ +-----------------------------------------------++ | SPIFFE provider | Local key provider | OIDF |+ +-------------------------+---------------------++ |+ v++----------+ signed v2 envelope +----------------------++| Ruflo A | ---------------------> | Federation ingress |+| egress | | PEP |++----+-----+ +----------+-----------++ | |+ | narrow grant v+ | +---------------------++ +------------------------------>| ADR-324 policy PDP |+ +----------+----------++ |+ allow + receipt+ |+ +--------------------------+----------++ | |+ v v+ +----------------------+ +---------------------++ | Ownership authority | | AP event replica |+ | CAS + lease + epoch | | HLC + vector clock |+ +----------+-----------+ +---------------------++ |+ v+ Durable inbox/outbox + receipt ledger+```++## Threat model++The design explicitly covers:++1. a malicious candidate agent with valid federation membership;+2. a compromised peer process or signing key;+3. stolen or replayed authorization grants;+4. nested-payload or metadata tampering;+5. a confused deputy forwarding broad credentials;+6. a malicious or compromised identity issuer;+7. stale or substituted trust bundles;+8. replay of an old accepted handoff;+9. concurrent promoters or ownership claimants;+10. network partitions and delayed messages;+11. compromised policy or status attestors;+12. PII and prompt injection in work metadata;+13. SSRF through A2A or federation metadata discovery;+14. resource exhaustion through signature, policy, or fan-out work.++Compromise of both an actor and its protected proof-of-possession key remains+out of scope for cryptographic replay prevention; blast radius is bounded by+short lifetimes, narrow audiences, budgets, policy, and revocation.++## Alternatives considered++### Keep ADR-101 unchanged++Rejected. Component tests do not establish runtime composition, authorization,+durability, or exclusive ownership under partition.++### Treat signed work claims as capabilities++Rejected. Ownership and authorization have different lifecycle, delegation,+revocation, and consistency rules. Conflating them makes a work assignment an+ambient privilege escalation.++### Make all claim data strongly consistent++Rejected. Notes, progress, and observations benefit from availability and can+merge causally. Only exclusive ownership transitions and their security+receipts require the CP path.++### Make all claim data eventually consistent++Rejected. Exclusive ownership cannot be guaranteed during a partition without+an authority, lease, quorum, or fencing mechanism.++### Require SPIRE and OAuth for every installation++Rejected. It would break offline and single-developer workflows. Standards are+implemented behind provider interfaces; the local profile remains first-class.++### Adopt a new capability-token format as the internal source of truth++Not selected for the first implementation. Macaroon-, Biscuit-, or+UCAN-inspired attenuation can be evaluated behind `AuthorizationGrantProvider`,+but OAuth token exchange and sender-constrained tokens provide stronger+interoperability with MCP, A2A, and enterprise identity infrastructure. The+ADR-324 policy state and receipts remain authoritative.++## Backward compatibility++1. Existing local `ClaimService` APIs and local repositories retain behavior.+2. Federation is opt-in and disabled on upgrade unless previously configured.+3. Existing installations start in `legacy`; `observe` evaluates the new+ pipeline without authorizing remote mutation; `enforce` requires migration+ checks and explicit administrator activation.+4. `ruflo claims` remains an alias while new `ruflo authz` commands are added.+ The alias emits a deprecation notice but preserves output schemas for one+ major release.+5. Existing work-claim wire messages remain readable for diagnostics and+ non-mutating telemetry between pinned peers. They cannot change ownership.+6. The migration converts local capability files into versioned ADR-324 rules.+ Parse or integrity failure is fail closed and provides a repair command.+7. Removing optional federation/identity providers leaves the local claims and+ policy systems operational.++## Implementation plan++### Phase 0 — Critical correctness gate++- Replace ad hoc canonicalization with an audited RFC 8785 implementation.+- Add nested mutation, duplicate-key, numeric edge, and cross-runtime vectors.+- Require verifier injection in every non-test dispatcher.+- Enforce nonce, freshness, expiry, target, audience, tenant, and session.+- Put `claim-event` and `agent-handoff` behind an explicit disabled-by-default+ policy profile rather than an accidental allowlist omission.+- Remove permissive local capability-file fallback.++No federated ownership mutation may ship before Phase 0 passes.++### Phase 1 — Runtime composition and durable delivery++- Add explicit package/plugin composition for claims, security, and federation.+- Construct the bridge, durable event store, repository, inbound handlers, and+ ADR-324 PEP in one composition root.+- Implement transactional outbox/inbox storage and crash recovery.+- Replace `checkClaim: () => true` with typed ADR-324 requests.+- Expose integration health that reports each required handler/provider.++### Phase 2 — Ownership authority++- Add `OwnershipAuthority` with local CAS and a linearizable distributed+ provider.+- Add lease renewal and monotonic fencing epochs.+- Split AP-safe events from ownership mutations.+- Make every protected work side effect validate the current epoch.++### Phase 3 — Identity, delegation, and revocation++- Introduce local and SPIFFE identity/trust-bundle providers.+- Add subject/actor token exchange and narrower-grant validation.+- Add mTLS or DPoP proof verification.+- Add status-event ingestion, key rotation, grant revocation, and cache policy.++### Phase 4 — MCP, A2A, and multilateral federation++- Publish MCP protected-resource metadata and audience-scoped challenges.+- Populate and enforce A2A Agent Card security requirements.+- Harden all metadata fetchers against SSRF and redirect abuse.+- Add optional OpenID Federation trust-chain resolution.+- Run cross-implementation conformance suites.++### Phase 5 — Convergence and removal++- Migrate legacy local authorization claims to ADR-324 policy objects.+- Remove the independent federation claim checker.+- Remove legacy mutating envelopes after one major release.+- Update ADR-101 status after production acceptance evidence is recorded.++## Normative acceptance tests++The feature is production-ready only when all of these pass:++1. Changing one byte in any nested payload or protected metadata field fails+ signature verification.+2. RFC 8785 official vectors produce identical bytes across supported runtimes.+3. Duplicate keys, non-finite values, negative zero, and unsupported critical+ fields fail closed.+4. Reusing a valid message nonce is rejected, including after process restart.+5. Wrong audience, target, tenant, session, time window, or trust domain is+ rejected.+6. A suspended peer, revoked grant, or removed signing key is rejected within+ the configured status objective.+7. A delegated grant can never expand action, resource, audience, expiry,+ budget, or delegation depth.+8. A stolen grant without its DPoP/mTLS key cannot authorize an action.+9. Every A2A and MCP operation reaches the same ADR-324 policy decision point.+10. One hundred concurrent acquisitions of an unowned work claim produce+ exactly one owner and one current fencing epoch.+11. During a partition, no side effect accepts two different owners' epochs.+12. A stale owner is rejected after reassignment even if its original lease+ message is replayed.+13. Fault injection at every outbox, inbox, ownership, and receipt commit+ boundary recovers to one consistent state.+14. Re-delivery is idempotent; message-ID/content-ID mismatch is quarantined.+15. PII and prompt-injection policy runs before a work event reaches the domain+ handler.+16. Explicit federation mode fails closed when policy, identity, revocation, or+ durable storage is unavailable.+17. Local mode remains behaviorally compatible when all optional providers are+ absent.+18. Upgrade, downgrade-within-support, and fresh-install tests preserve+ existing local claims without silently granting new authority.++## Performance and reliability targets++These are acceptance targets, not claims about current performance:++| Metric | Target |+|---|---|+| Warm local envelope verification + replay + policy, 1 KiB payload | p99 <= 2 ms, measured separately from network and domain work |+| Added allocation per verified 1 KiB message | <= 32 KiB |+| Duplicate delivery | No duplicate domain side effect |+| Ownership race | Exactly one winner for 100 concurrent requests |+| Revocation propagation, high-risk profile | p99 <= 5 s |+| Revocation propagation, standard profile | p99 <= 60 s |+| Crash recovery | No acknowledged message or receipt lost |+| Local-mode regression | <= 5% p95 latency and no API/output-schema break |++Benchmarks MUST publish hardware, runtime, key algorithm, payload distribution,+policy size, warm-up, sample count, and confidence interval. Optimization may+not remove a security check; cached results include identity, audience,+resource, action, tenant, policy version, grant ID, proof key, and revocation+epoch in the cache key.++## Operational visibility++`ruflo federation doctor --claims` will report:++- identity provider and current workload ID;+- configured trust domains and bundle age;+- policy mode/version and ingress/egress enforcement state;+- claims bridge and both inbound handlers;+- ownership authority, quorum, and lease health;+- inbox/outbox lag and dead-letter count;+- nonce-store durability;+- revocation stream age;+- A2A/MCP security metadata conformance;+- legacy-envelope traffic preventing enforcement.++The command must never print private keys, bearer grants, DPoP private material,+or unredacted work metadata.++## Consequences++### Positive++- One policy authority governs local, MCP, A2A, and federation actions.+- Workload identity, delegated human authority, and acting agent remain+ attributable.+- Exclusive ownership becomes safe under concurrency and partition.+- Local users retain an offline-compatible path.+- Standards-based adapters reduce bespoke federation protocol surface.+- Decision and ownership receipts support incident review and independent+ verification.++### Negative++- Federated ownership requires a linearizable authority and therefore cannot+ remain available through every partition.+- Durable inbox/outbox, revocation, and trust-bundle operations add complexity.+- Sender-constrained delegation requires key lifecycle and secure storage.+- Multilateral federation increases trust-chain and metadata-policy operating+ burden.++### Neutral++- HLC and vector clocks remain, but their role narrows to causality and AP-safe+ replication.+- Agent Cards continue to advertise capabilities; they simply stop being+ mistaken for authorization.+- ADR-101 is retained as historical context rather than rewritten.++## SOTA references++- [RFC 8785: JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785.html)+- [RFC 8693: OAuth 2.0 Token Exchange](https://www.rfc-editor.org/rfc/rfc8693.html)+- [RFC 9449: OAuth 2.0 Demonstrating Proof of Possession](https://www.rfc-editor.org/rfc/rfc9449.html)+- [RFC 9700: Best Current Practice for OAuth 2.0 Security](https://www.rfc-editor.org/rfc/rfc9700.html)+- [RFC 9728: OAuth 2.0 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728.html)+- [SPIFFE Federation](https://spiffe.io/docs/latest/spiffe-specs/spiffe_federation/)+- [SPIFFE Workload API](https://spiffe.io/docs/latest/spiffe-specs/spiffe_workload_api/)+- [OpenID Federation 1.0](https://openid.net/specs/openid-federation-1_0.html)+- [OpenID Shared Signals Framework, CAEP, and RISC final specifications](https://openid.net/three-shared-signals-final-specifications-approved/)+- [MCP authorization specification, 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization)+- [A2A protocol specification](https://github.com/a2aproject/A2A/blob/main/docs/specification.md)+- [A2A agent discovery](https://a2a-protocol.org/latest/topics/agent-discovery/)+- [etcd transactions, leases, and fencing revisions](https://etcd.io/docs/v3.8/learning/why/)++## Review trigger++Review this ADR when any of the following occurs:++- A2A or MCP changes its authorization model;+- OpenID Federation or Shared Signals publishes a new final version;+- SPIFFE changes its stable federation or workload identity contracts;+- Ruflo supports a new distributed ownership authority;+- production evidence demonstrates a different consistency or latency+ requirement;+- any acceptance invariant is weakened for compatibility or performance.diff --git a/v3/docs/adr/ADR-326-cognitum-product-plane-claim-federation.md b/v3/docs/adr/ADR-326-cognitum-product-plane-claim-federation.mdnew file mode 100644index 0000000000..4032585e2d--- /dev/null+++ b/v3/docs/adr/ADR-326-cognitum-product-plane-claim-federation.md@@ -0,0 +1,569 @@+# ADR-326: Cognitum Product-Plane Claim Federation Profile++**Status**: Proposed — cross-repository implementation and migration required+**Date**: 2026-07-28+**Decision owners**: Ruflo, Cognitum control-plane, Meta-LLM, Comms, and RuView maintainers+**Related**: ADR-098, ADR-099, ADR-100, ADR-115 through ADR-119,+ADR-324, ADR-325, ADR-327++## Executive decision++Cognitum will integrate Ruflo claim federation as a shared, zero-trust+authorization and evidence profile across:++- the cognitum.one customer dashboard;+- Meta-LLM inference, routing, budgets, and collaboration gateways;+- Comms and AgentBBS;+- Cog Studio proposals, approvals, releases, and runtime operations; and+- RuView edge spaces and privacy-preserving sensing.++The profile does not create a new global database or a second product+authority. Each product retains a single authoritative domain:++| Domain | Authoritative owner |+|---|---|+| Human identity and tenant membership | Firebase identity plus Cognitum tenant membership |+| Cog proposals, operations, releases, and observed runtime state | Cognitum Cog control plane |+| Inference routing, spend, usage, and completion delivery | Meta-LLM |+| Collaboration content and decisions | AgentBBS |+| Comms tenant lifecycle, membership, and billing | Comms |+| Raw sensing, local models, and device actuation | RuView edge authority |+| Cross-domain policy decisions and delegated grants | Ruflo ADR-324/325 policy plane |++Dashboards, notifications, Comms cards, and other views are reference+projections. They MUST NOT manufacture, copy, or reinterpret authoritative+outcomes.++The current product integration is useful but not yet optimal. Firebase and API+key authentication work within their local domains, but there is no production+Ruflo federation verifier in the Cognitum control plane. Several cross-service+mutation paths also lack atomic idempotency, durable delivery, request-bound+capabilities, or exact release provenance.++## Why a separate profile is required++ADR-325 defines the generic trust, identity, grant, ownership, and receipt+model. It intentionally does not decide how Cognitum product identities map,+which service owns each outcome, or what data may cross a product boundary.++Those choices are security decisions:++- a Firebase UID, Meta-LLM account, AgentBBS public key, and workload identity+ are different principals even if their display strings match;+- a dashboard session is not an inference, deployment, moderation, or device+ command capability;+- a Cog proposal is desired state, not observed runtime truth;+- an AgentBBS decision is not a Cognitum release approval;+- a RuView semantic observation is not permission to expose raw sensing data or+ actuate a device.++This profile makes those boundaries normative and defines a compatible+migration from current installations.++## Current-state audit++The July 2026 cross-repository audit found the following.++### Existing strengths++- Cognitum Functions verify Firebase identity and derive tenant membership+ server-side instead of accepting tenant ownership from request bodies.+- Cog Studio persists a proposal, immutable revision, transition, and+ reference-only action event transactionally.+- Cog production approval checks tenant, proposal revision, policy version,+ quorum, and expiry separately from execution.+- Runtime action events accept only observations marked authoritative and do+ not infer success from desired state.+- Comms projections reference authoritative operation, proposal, and release+ records instead of duplicating their outcomes.+- Meta-LLM derives its account from a verified API key or OAuth token and+ constrains delegated sub-tenants to an explicit privileged scope.+- RuView keeps raw CSI, pose, vital, and sensor frames at the edge and exposes+ privacy-minimized semantic state to the dashboard.+- AgentBBS uses browser-held Ed25519 identities for collaboration participants.++The current RuView/Seed website feature is a downstream catalogue and read+model, not a deployed edge-federation path. The reviewed HomeCore federation+endpoint is a `503` stub, its documentation describes demo mocks, and no+Cognitum Spaces uplink was found in the reviewed RuView source.++### Material gaps++| Severity | Finding | Effect |+|---|---|---|+| Critical | Cognitum Functions have no production Ruflo grant verifier or federation PEP | A federated claim cannot safely authorize a product action |+| Critical | Current release evidence may be rebound to a mutable blueprint and uses shallow nested canonicalization | A nominally signed release is not eligible to authorize deployment |+| High | A test-only, one-use deployment capability has no production execution consumer | Capability issuance is not an enforcement boundary |+| High | Website structured-output requests are not consistently forwarded or cache-separated by Meta-LLM's OpenRouter path | Cog Builder output format can degrade or reuse incompatible cached output |+| High | Meta-LLM completion idempotency is lookup-then-store rather than an atomic reservation | Concurrent retries can execute and bill more than once |+| High | Meta-LLM collaboration mutations lack idempotency and its event stream lacks a durable resume cursor | Retries can duplicate actions and reconnects can miss events |+| High | Comms lifecycle and membership writes lack an operation journal, transactional dedupe, and complete CAS semantics | Concurrent mutations or crashes can lose or ambiguously apply state |+| Medium | The dashboard still uses recoverable `cog_` credentials for Meta-LLM | A browser credential has broader lifetime and reuse than an audience-bound grant |+| Medium | AgentBBS moderator claims bind role, tenant, and expiry but not every method, path, body digest, action, and nonce | A valid proxy claim has avoidable replay surface |+| Medium | Advertised webhook behavior is not equivalent across every website adapter | UI expectations can exceed the provider's delivery contract |+| High | RuView development events can use a deterministic signer and carry an unregistered self-supplied public key | Integrity can be mistaken for trusted tenant/device provenance |+| High | RuView and HomeCore use optional or ambient process-wide bearer authentication on local surfaces | Local credentials do not identify a scoped federated actor |+| High | The current Spaces response is asserted from network JSON without a fail-closed privacy/provenance validator | Malformed or cross-tenant state can reach the read model |+| Medium | The website edge catalogue is manually pinned and includes a tokenless WebSocket example for a route that may require a bearer | Generated instructions can drift from the real edge contract |++No current production deployment may be described as claim-federated until the+relevant acceptance gates in this ADR and ADR-325 pass.++## Decision++### 1. Preserve authority and use reference projections++Every mutable fact has one authoritative record. Cross-product events contain+references and digests, not a copied human-readable outcome:++```ts+interface AuthoritativeReference {+ authority: string;+ tenantRef: string;+ sourceType: string;+ sourceId: string;+ sourceVersion: string;+ sourceDigest: `sha256:${string}`;+}+```++A projection may add display metadata, unread state, or a local delivery+timestamp. It may not change the source status, policy result, observed state,+release digest, or decision.++Cog desired state never becomes observed runtime truth through federation.+Only an authoritative reconciler observation can produce a running, halted,+failed, deployed, or rolled-back outcome.++### 2. Keep identity domains explicit++The principal link record is an audited mapping, not string equality:++```ts+interface PrincipalLink {+ linkId: string;+ cognitumPrincipal: string;+ firebaseSubject?: string;+ metaLlmAccount?: string;+ agentBbsPublicKey?: string;+ workloadId?: string;+ tenantRefs: string[];+ verifiedAt: string;+ verificationMethod: string;+ status: 'active' | 'suspended' | 'revoked';+}+```++At each request, the receiver verifies the incoming identity and re-resolves+tenant membership and permissions from its own authoritative store. A grant+may request a tenant; it cannot assign tenant ownership or local permissions.++Account, tenant, and sub-tenant identifiers are namespace-qualified. The same+text in two namespaces never implies the same identity.++### 3. Exchange browser identity for audience-bound grants++The dashboard remains a policy enforcement point and read model, not an+authority. A verified Firebase/Cognitum session exchanges identity for a+short-lived, sender-constrained grant targeted to one product resource:++```text+dashboard session+ -> Cognitum token exchange+ -> Meta-LLM inference grant+ -> Cog proposal grant+ -> Comms posting grant+ -> RuView semantic-read grant+```++The dashboard MUST NOT forward one broad token across those services. Each+grant binds:++- issuer, subject, actor, and audience;+- local tenant/account request;+- exact actions and resource selectors;+- request or policy digest where the action is consequential;+- budget, rate, concurrency, and delegation ceilings;+- proof-of-possession key;+- issue, expiry, policy version, grant ID, and parent grant hash.++Existing `cog_` API keys remain supported during migration. They are mapped to+a compatibility principal and exchanged server-side where possible. New+privileged actions fail closed if only a legacy browser key is present.++### 4. Adopt a common product action vocabulary++Initial actions are:++| Product | Actions |+|---|---|+| Dashboard | `dashboard.read`, `dashboard.status.read` |+| Meta-LLM | `inference.invoke`, `inference.stream`, `usage.read`, `pod.spawn`, `benchmark.run`, `evolution.propose`, `evolution.promote` |+| Comms | `comms.thread.read`, `comms.thread.post`, `comms.projection.read`, `comms.board.admin` |+| Cog Studio | `cog.proposal.create`, `cog.proposal.review`, `cog.proposal.approve`, `cog.instance.acquire`, `cog.instance.operate`, `cog.deploy`, `cog.rollback` |+| RuView | `ruview.space.read`, `ruview.semantic.publish`, `ruview.automation.propose`, `ruview.automation.approve`, `ruview.device.command` |+| Agent cognition | `cognition.route`, `cognition.critique` |+| Validated learning | `memory.recall`, `memory.propose`, `evidence.read`, `memory.commit-validated` |++Actions are not interchangeable. In particular:++- `cog.proposal.create` never implies `cog.deploy`;+- `benchmark.run` never implies `evolution.promote`;+- `ruview.space.read` never implies raw sensor access or device command;+- `comms.thread.post` never implies board administration;+- a work lease never implies any product action.+- `memory.propose` never implies `memory.commit-validated`;+- `memory.commit-validated` never implies policy or model promotion.++Receivers intersect grant actions with their local permissions and policy.++Agent cognition is a capability plane, not a new authority plane. Cognitum and+Meta-LLM may route or critique a development trajectory and may return bounded+evidence. Ruflo remains authoritative for its validated memory and policy+state. A memory commit binds the exact proposed content digest, evidence+digest, validator version, policy receipt, tenant, namespace, and one-use+capability. The commit cannot update an active policy, promote a MetaHarness+candidate, deploy, change IAM, or spend outside its separate envelope.++### 5. Bind inference semantics to policy, cache, and receipts++Meta-LLM requests that affect observable behavior MUST bind the following into+provider translation, idempotency identity, exact-cache identity, and the+decision receipt:++- model and provider route;+- structured response format and schema;+- reasoning controls;+- safety and fallback policy;+- cache mode;+- tenant and authorized sub-tenant;+- input or redacted-input digest;+- token, USD, latency, and concurrency limits;+- webhook delivery contract.++A request for structured JSON cannot share a cache entry with an otherwise+identical unstructured request. A provider adapter either forwards a supported+semantic, performs a declared compatible translation, or returns an explicit+degraded/refused result. It never silently drops a policy-relevant field.++All mutating or billable calls reserve idempotency atomically:++```text+key = issuer + tenant + principal + action + idempotencyKey+value = canonicalRequestDigest + pending/completed/failed result+```++The same key and digest waits for or replays the original result. The same key+with a different digest returns conflict. One hundred concurrent calls produce+one provider side effect and one billable usage record.++### 6. Keep AgentBBS authoritative for collaboration++Meta-LLM `/v1/collab/*` remains a gateway; Comms remains the commercial tenant+and membership wrapper; AgentBBS remains authoritative for collaboration+content and decisions.++Federated Comms delivery uses:++- atomic mutation idempotency;+- a transactional outbox at the authority;+- receiver inbox dedupe by issuer, event ID, and content digest;+- stable sequence or cursor within the authoritative aggregate;+- SSE `id` plus `Last-Event-ID`, or an equivalent durable cursor;+- reference-only Cognitum action-event projections.++AgentBBS participant keys are linked identities, not Cognitum permission+sources. Moderator and sysop compatibility claims are narrowed to tenant,+method, path, action, body digest, one-use nonce, and expiry when the protocol+supports it. Existing role claims stay readable while new privileged proxy+operations require the narrower profile.++### 7. Make Cog Studio a proposal-to-capability pipeline++Cog Studio follows this sequence:++```text+immutable proposal revision+ -> policy evaluation+ -> approvals/quorum+ -> request-bound, one-use capability+ -> local control-plane transaction+ -> authoritative runtime observation+ -> action event and receipt+```++The execution capability binds the tenant, proposal and revision, policy+version, approval reference, exact command or operation, release and blueprint+digests, idempotency key, executor audience, expiry, and maximum use count.++Issuance is not execution. Production remains disabled until the local+control-plane consumer validates and consumes the capability transactionally.++Release provenance MUST be produced from a pinned source state using recursive+canonicalization. A generator may verify evidence; it may not retroactively+inject the current blueprint head into old evidence. A missing binding fails+closed.++### 8. Preserve RuView edge sovereignty++Raw CSI, pose, vital, image, audio, and sensor frames remain at the RuView edge+unless an independently approved export policy explicitly allows otherwise.+The default product-plane event contains privacy-minimized P2/P3 semantic+state:++```ts+interface RuViewSemanticObservation {+ spaceRef: string;+ observationType: string;+ value: unknown;+ confidence: number;+ uncertainty?: number;+ abstained: boolean;+ modelDigest: string;+ calibrationDigest?: string;+ hardwareRef?: string;+ privacyClass: 'P2' | 'P3';+ observedAt: string;+ expiresAt: string;+ sequence: bigint;+}+```++An observation is evidence, not an automation grant. Device commands and+automations require a separate, narrow capability, current edge policy,+idempotency, anti-replay state, and an authoritative device receipt. Offline+edge policy may be stricter than cloud policy but never broader.++The cloud path is:++```text+RuView/Seed local sensing+ -> privacy-minimizing edge adapter+ -> ADR-325 v2 signed envelope+ -> cloud federation ingress PEP+ -> ADR-324 decision and receipt+ -> tenant/site monotonic projection+ -> GET /v1/spaces+ -> dashboard read model+```++The website is never a federation peer, edge credential holder, signature+authority, or MQTT client. Local RuView REST and WebSocket surfaces remain+operational and diagnostic APIs; their bearer token or event public key is not+federation evidence.++Production edge federation fails startup when it detects a development signer,+optional or disabled authentication, a missing durable nonce store, an+unregistered workload, or an incomplete tenant/site binding. An embedded event+public key proves only internal consistency until a trust record binds it to+the workload, tenant, site, algorithm, key status, and validity period.++The ingress export ceiling is stricter than local visibility. The default+Cognitum profile rejects P0/P1 raw data and P4/P5 sensitive or prohibited+payloads and accepts only explicitly approved P2/P3 semantic projections.+Replay or simulated input must say it is synthetic. Model, calibration,+hardware, and firmware provenance are independently described; a model ID hash+cannot be relabeled as firmware attestation.++`GET /v1/spaces` derives tenant from the verified grant, requires+`ruview.space.read` (with an explicit time-bounded `devices:manage`+compatibility rule if needed), returns `Cache-Control: no-store`, and never+accepts a caller-selected tenant. The server validates privacy class,+provenance, freshness, expiry, and a monotonic site sequence before projection.+The website validates the response again and rejects raw fields, invalid+privacy, malformed provenance, impossible time ordering, or a tenant mismatch.++Edge API catalogues are generated from a pinned machine-readable RuView/Seed+contract and fail CI on route, transport, authentication, scope, or risk drift.+WebSocket examples distinguish header-capable clients, ticket/subprotocol+exchange, and intentionally unauthenticated local sockets.++### 9. Standardize product events and receipts++The interoperable event envelope extends ADR-325 with:++```ts+interface CognitumActionEnvelopeV1 {+ schemaVersion: 'cognitum.action.v1';+ eventId: string;+ issuer: string;+ audience: string;+ subject: string;+ actor?: string;+ tenantRef: string;+ action: string;+ resourceRefs: string[];+ requestDigest?: string;+ idempotencyKey?: string;+ correlationId: string;+ causationId?: string;+ authoritativeSource: AuthoritativeReference;+ sequence?: string;+ policyReceiptId: string;+ capabilityId?: string;+ occurredAt: string;+ expiresAt?: string;+ privacyClass: 'P0' | 'P1' | 'P2' | 'P3';+}+```++The envelope is recursively canonicalized and signed as specified by ADR-325.+An authoritative mutation and its outbox entry commit atomically. A receiver+deduplicates before creating a projection and acknowledges only after commit.++Free-form prompts, secrets, credentials, raw sensor data, and copied outcome+text are excluded. Redacted evidence is addressed by digest and protected URI.++### 10. Surface honest integration health++Every dashboard and agent-development integration reports identity,+configuration, reachability, health, and authorization independently:++```ts+interface ProductCapabilityHealth {+ identity: 'verified' | 'unverified' | 'unknown';+ configured: 'yes' | 'no' | 'unknown';+ reachable: 'yes' | 'no' | 'unknown';+ healthy: 'yes' | 'no' | 'unknown';+ authorized: 'yes' | 'no' | 'unknown';+ status: 'available' | 'degraded' | 'blocked' | 'unavailable';+}+```++The aggregate reports one of:++- `available`: required identity, policy, authority, and data path are healthy;+- `degraded`: a declared compatibility path is active;+- `blocked`: policy or evidence intentionally forbids the action;+- `unavailable`: the authority cannot be reached or verified.++These dimensions are not collapsed into one badge. A valid grant can coexist+with an unreachable service; a healthy service can coexist with a denied+action; configured credentials can coexist with an unverified identity.++The UI must not convert an unavailable RuView API, malformed Meta-LLM+structured output, unverified release, expired approval, or missing production+capability consumer into apparent success.++## Compatibility and rollout++### Phase 0 — Evidence and contract repairs++- Repair recursive release and blueprint canonicalization.+- Republish or create a detached signed binding for exact source, release, and+ blueprint digests.+- Forward `response_format` and include all policy-relevant inference fields in+ cache and idempotency identity.+- Make advertised webhook behavior explicit per adapter.+- Add production blockers to integration health.++### Phase 1 — Observe++- Add the Cognitum federation verifier beside existing Firebase/API-key+ verification.+- Dual-write signed outbox envelopes and current action events.+- Shadow-evaluate ADR-324 policy without authorizing a new mutation.+- Link principals through verified proof and audit every mapping.++### Phase 2 — Enforce new privileged mutations++- Require audience-bound grants for deployment, rollback, board+ administration, evolution promotion, and RuView device command.+- Add production capability consumers at each local authority.+- Add atomic idempotency and request-digest conflicts.+- Preserve legacy read and low-risk inference paths.++### Phase 3 — Durable interoperability++- Enable transactional inbox/outbox delivery and resumable event cursors.+- Journal Comms provisioning and compensations.+- Bind AgentBBS proxy claims to each request.+- Enforce status and revocation objectives.++### Phase 4 — Retire ambient credentials++- Stop recovering broad `cog_` keys into new dashboard sessions.+- Migrate active clients to token exchange.+- Retain an explicit, observable compatibility mode for supported older+ installations.+- Never reinterpret a legacy tenant or user identifier as a federated one.++## Normative acceptance tests++1. A federated identity cannot assign its own tenant, account, role, or local+ permission.+2. Equal-looking identifiers from two identity namespaces remain distinct+ until a verified link is active.+3. A dashboard token issued for Meta-LLM is rejected by Cog, Comms, and RuView.+4. One hundred concurrent identical billable requests cause one provider call+ and one usage charge.+5. Reusing an idempotency key with a different canonical request returns+ conflict.+6. Structured and unstructured requests cannot share a cache entry, and the+ provider observes the requested supported response format.+7. A collaboration disconnect and resume produces no missing authoritative+ event and no duplicate domain side effect.+8. A Comms lifecycle crash at every persistence boundary recovers to one+ journaled outcome.+9. A proposal grant cannot deploy; only an approved, one-use, exact-operation+ capability can reach the production consumer.+10. A missing or mutable release/blueprint binding is rejected before+ capability issuance.+11. Desired state never produces an observed runtime-success event.+12. A Comms card altered to show a different outcome fails source digest+ verification.+13. Raw RuView sensing does not leave the edge in the default profile.+14. A semantic observation cannot authorize a device command.+15. A revoked grant or principal link is rejected within the ADR-325 status+ objective.+16. Existing installations preserve supported read and low-risk inference+ behavior in declared compatibility mode.+17. Removing Ruflo federation providers leaves local product authorities+ operational but disables new federated privileged actions.+18. Production edge federation refuses a deterministic development signer,+ optional authentication, and an unregistered self-supplied event key.+19. Wrong tenant, site, audience, session, trust domain, expiry, or reused+ nonce is rejected, including replay after restart.+20. P0/P1/P4/P5 data never reaches the cloud Spaces projection.+21. Replay or simulated RuView input cannot claim live provenance, and+ incomplete firmware/model/calibration attestation remains visibly+ incomplete.+22. The website rejects raw sensing fields, invalid privacy, malformed+ provenance, non-monotonic sequences, and tenant mismatch.+23. The edge catalogue fails CI when its pinned machine-readable route,+ transport, authentication, scope, or risk contract drifts.+24. A valid claim never changes an independently unavailable service to+ available.+25. Each service probe preserves identity, configured, reachable, healthy, and+ authorized state independently.+26. `memory.commit-validated` rejects missing or mismatched content/evidence+ digests, validator version, policy receipt, tenant/namespace, and one-use+ capability.+27. A validated memory commit cannot change active policy, promote a+ MetaHarness candidate, deploy, mutate IAM, or authorize billing.++## Consequences++### Positive++- Cognitum products share policy and evidence without collapsing their+ authority boundaries.+- Browser credentials become narrower and less reusable.+- Cog, Comms, Meta-LLM, and RuView outcomes remain independently auditable.+- Cross-service retries become safe under concurrency and crash recovery.+- Existing installations receive an incremental migration path.++### Negative++- Every authority needs inbox/outbox, idempotency, status, and grant-verifier+ infrastructure.+- Identity linking and revocation add operational responsibility.+- Some current integrations remain visibly degraded or blocked until their+ upstream contract is repaired.++## Review trigger++Review this ADR when a product changes its authoritative data owner, a new+identity domain is added, raw RuView data is allowed to leave the edge, a+production Cog executor is introduced, or the compatibility profile is+removed.diff --git a/v3/docs/adr/ADR-327-federated-concurrent-development-harness.md b/v3/docs/adr/ADR-327-federated-concurrent-development-harness.mdnew file mode 100644index 0000000000..c61fa9efe8--- /dev/null+++ b/v3/docs/adr/ADR-327-federated-concurrent-development-harness.md@@ -0,0 +1,412 @@+# ADR-327: Federated Concurrent Development Harness++**Status**: Proposed — generator guidance and in-memory conformance references implemented; distributed enforcement pending+**Date**: 2026-07-28+**Decision owners**: Ruflo Codex, claims, policy, and developer-experience maintainers+**Related**: ADR-320, ADR-324, ADR-325, ADR-326++## Executive decision++Ruflo will support repository-local development harnesses as adapters into its+policy-governed concurrent workflow.++The useful primitives observed in the cognitum.one website harness are adopted:++- explicit sessions;+- path and named-resource leases;+- lease heartbeats;+- agent-to-agent handoff messages;+- isolated development ports;+- test and release receipts; and+- dry-run deployment with release gates.++Those primitives are coordination evidence, not authorization. They supplement+but never replace Ruflo's stronger invariant that every writing agent uses a+distinct Git worktree.++Ruflo will define one versioned harness contract with:++- canonical repository and source-state identity;+- linearizable leases with monotonically increasing fencing tokens;+- separate authorization capabilities;+- durable, acknowledged messages;+- immutable test and release receipts; and+- compatibility adapters for existing local harnesses.++Generator and AGENTS guidance will teach Codex to discover and join a tracked+repository harness without weakening the worktree or policy rules. Distributed+lease enforcement remains proposed until the acceptance tests pass.++### Implemented reference scope++The Codex package now includes source/build evidence capture plus+`InMemoryFencedLeaseReference`, `InMemoryInboxReference`, and+`InMemoryRunReceiptReference`. These are deliberately unsigned, non-persistent,+single-process conformance/debug references:++- their descriptors are statically restricted to `observe` and `advisory`;+- legacy normalization cannot upgrade them to enforce or release authority;+- canonical uint64 parsing, length-framed inbox identity, portable+ case-collision refusal, version checks, replay convergence, and contention+ semantics are tested;+- Git-visible source state and separately declared unsigned build inputs can+ be captured and recomputed.++They do not implement a CP lease service, durable inbox/outbox, signed+hash-chained ledger, restart recovery, or release-decision composer. An+external-authority adapter satisfying the normative sections below remains+required for enforcement and release.++## Current-state audit++The cognitum.one website harness currently provides a practical, file-backed+coordination layer:++- a mutex plus atomic rename protects local JSON lease updates;+- path claims reject option-like scope values and overlapping ancestors or+ descendants;+- named resource claims cover deployment and shared services;+- heartbeats, not PIDs, represent lease liveness;+- sessions carry inbox messages and development ports;+- test receipts bind a command, scope, result, and Git SHA;+- deployment is dry-run by default and checks release receipts.++This is useful local coordination, but the live audit found:++- multiple writing agents share one dirty website worktree;+- a receipt that records only `HEAD` cannot identify which dirty source state+ was tested;+- ignored JSON sessions, leases, messages, and receipts are mutable and+ unsigned;+- any local process can impersonate a session or alter coordination state;+- leases have no fencing token, so an expired writer cannot be rejected by a+ protected side effect;+- liveness is not bound to repository, worktree, branch, host, or workload+ identity;+- the inbox keeps a bounded tail rather than a durable acknowledged stream;+- an eight-hour TTL can retain stale ownership for a long period; and+- the local mutex cannot coordinate multiple hosts.++The harness correctly treats a missing PID as insufficient proof of death.+Lease expiry and heartbeat are the right liveness abstraction, but production+concurrency requires fencing and exact source-state receipts.++## Security and correctness invariants++1. Every writing agent has a distinct Git worktree.+2. A path lease prevents overlapping intent; it does not make shared dirty+ state safe.+3. A repository lease coordinates ownership; it does not grant authorization.+4. A session identity is not a workload identity or product capability.+5. Every successful lease acquisition returns a monotonically increasing+ fencing token.+6. Protected writes reject a stale fencing token after expiry, release, steal,+ or reacquisition.+7. `HEAD` alone is not an exact source-state identity when a worktree is dirty.+8. Test, release, and deployment receipts bind the exact source state.+9. Message delivery is durable and idempotent; reading a bounded tail is not+ acknowledgement.+10. Harness unavailability may stop protected mutation but never silently+ expand authority.++## Decision++### 1. Define a repository harness adapter++Ruflo discovers a harness only through tracked repository configuration:++```ts+interface RepositoryHarnessAdapter {+ describe(): Promise<HarnessDescriptor>;+ start(request: StartSessionRequest): Promise<HarnessSession>;+ acquire(request: LeaseRequest): Promise<FencedLease>;+ renew(lease: FencedLease): Promise<FencedLease>;+ release(lease: FencedLease): Promise<void>;+ send(message: HarnessMessage): Promise<MessageReceipt>;+ receive(cursor?: string): AsyncIterable<HarnessMessage>;+ acknowledge(messageId: string): Promise<void>;+ recordRun(run: RunEvidence): Promise<RunReceipt>;+ authorizeRelease(request: ReleaseRequest): Promise<ReleaseDecision>;+ end(sessionId: string): Promise<void>;+}+```++Repository scripts remain the preferred local user interface. Ruflo does not+replace a project's custom harness or invent commands. The adapter reads its+declared capabilities and invokes only supported operations.++If no tracked harness exists, Ruflo uses its local claims and policy providers.+If an explicitly selected harness is unavailable, protected operations fail+closed.++### 2. Retain one worktree per writer++The parent agent creates or assigns a distinct worktree before a writing worker+acquires paths. A lease then provides fine-grained ownership inside that+worktree and across agents:++```text+isolated worktree+ + non-overlapping path/resource lease+ + narrow authorization capability+ + current fencing token+ = eligible protected write+```++Read-only agents may share a checkout if they acquire no writing lease. One+designated integration agent owns shared manifests and lockfiles.++Legacy shared-worktree harnesses remain observable in compatibility mode, but+Ruflo does not describe them as isolated or receipt-complete. Their dirty+source state cannot authorize release.++### 3. Canonically identify repository and source state++A repository identity binds at least:++```ts+interface RepositoryIdentity {+ repositoryId: string;+ canonicalRemote?: string;+ gitCommonDirId: string;+ rootTreeId: string;+}+```++Paths are repository-relative, Unicode-normalized, separator-normalized, free+of `.` and `..`, checked after symlink resolution, and compared with the+platform's case behavior. Option-like values are rejected.++The preferred source state is a clean, committed worktree:++```text+SourceStateID = sha256(repositoryId || commit || tree)+```++When a local test intentionally covers uncommitted work, the receipt also+binds:++- the base commit;+- the binary-safe tracked patch digest;+- an untracked file manifest with mode, length, and content digest;+- submodule and large-file pointer state;+- generator inputs and relevant lockfile digests.++Such a local receipt may support debugging. A release receipt still requires a+clean committed state unless a project policy explicitly defines an equally+strong immutable snapshot mechanism.++### 4. Use CP leases and fencing tokens++The lease authority performs compare-and-swap transactions:++```ts+interface FencedLease {+ leaseId: string;+ repositoryId: string;+ sessionId: string;+ ownerWorkloadId: string;+ worktreeId: string;+ kind: 'path' | 'resource';+ scopes: string[];+ epoch: bigint;+ version: bigint;+ issuedAt: string;+ expiresAt: string;+}+```++Acquire, renew, release, and steal validate the expected version and current+owner. Every successful new ownership period increments `epoch`, including+reacquisition by the same session.++Filesystem adapters provide single-host compatibility. Distributed workflows+use a linearizable authority. Protected integrations, deployment drivers, and+shared generators compare the presented epoch with the authority before a side+effect. An old holder cannot continue merely because it still has local files.++Heartbeat proves current lease intent; PID is diagnostic only. A long-running+operation uses bounded renewable leases and cannot declare a mutex stale solely+because a fixed wall-clock duration elapsed.++### 5. Keep leases and authorization separate++A lease answers, "which worker currently owns this coordination scope?" A+grant answers, "may this identity perform this action?"++The ADR-324/325 decision request includes both:++```text+subject and workload identity+repository and source state+action and exact resource+lease ID, scope, epoch, and expiry+authorization grant+budget/concurrency/delegation envelope+policy version+```++No lease, session, message, test result, or agent role can synthesize a+deployment, network, spend, secret, administrative, or product capability.++### 6. Make messages durable++Harness messages use stable IDs, issuer and audience, correlation and causation+IDs, sequence, expiry, content digest, and acknowledgement state.++Delivery is at least once. The receiver deduplicates by issuer, message ID, and+content digest. A repeated ID with different content is quarantined. A bounded+UI view may show the most recent messages, but durable storage retains+unacknowledged handoffs and supports cursor resume.++Messages communicate observations, requests, conflicts, and handoffs. They do+not transfer path ownership or authority unless the corresponding lease or+grant transaction separately succeeds.++### 7. Bind run, release, and deployment receipts++A run receipt includes:++```ts+interface HarnessRunReceipt {+ receiptId: string;+ repositoryId: string;+ sourceStateId: string;+ sessionId: string;+ workloadId: string;+ commandDigest: string;+ scope: string;+ profile: 'focused' | 'integration' | 'release';+ startedAt: string;+ completedAt: string;+ exitCode: number;+ evidenceDigest: string;+ policyReceiptId: string;+ leaseEpochs: Record<string, string>;+}+```++Receipts are recursively canonicalized, content-addressed, signed, and+append-only. Retrying a command creates another execution ID; it does not+rewrite history.++A release decision requires:++- an allowed policy decision;+- a clean exact source state matching the candidate release;+- all project-required run profiles passing for that same state;+- valid leases and current fencing epochs for integration and release scopes;+- artifact and provenance digests;+- an authorized release capability; and+- no unresolved higher-priority refusal or stale dependency.++Deploy remains dry-run unless the user and policy authorize execution. A+passing run receipt is evidence, not deployment authority.++### 8. Federate across repositories through handoffs++Cross-repository work uses explicit producer and receiver ownership:++```text+producer commit and evidence+ -> signed handoff referencing exact source state+ -> receiver acknowledges+ -> receiver acquires its own local paths and capability+ -> receiver implements and verifies its side+```++One agent does not write into another dirty repository merely because both+participate in the same swarm. Contract changes identify the receiving owner,+compatibility window, and validation evidence.++This is especially important for Cognitum website to Meta-LLM structured+output, Cog release provenance, Comms event delivery, and RuView edge contracts.++## Codex workflow integration++Generated AGENTS guidance follows ADR-329's complete implementation loop:+recall, inspect, route, plan, execute, test, validate, benchmark, optimize,+receipt, handoff, and independently authorized publish. Harness-specific+actions occur inside that loop:++1. assign one worktree to each writer during routing;+2. start the tracked harness, inspect claims, and acquire exact scopes during+ planning;+3. renew leases and check acknowledged inbox messages during execution;+4. bind focused/integration results to exact source/build inputs during+ validation and receipt;+5. release claims and reconcile handoffs before the integration owner evaluates+ an external-authority release decision.++Ruflo coordinates this flow. Codex still performs the implementation and+verification work.++## Compatibility and migration++1. Existing repository harness commands and JSON schemas remain unchanged.+2. Ruflo first uses an `observe` adapter that imports session, lease, message,+ port, and run evidence without authorizing privileged actions.+3. Existing path leases map to epoch `0` and are advisory. They cannot+ authorize release.+4. New adapters dual-write durable lease and receipt records while projects+ retain their local UI.+5. Projects move to `enforce` only after writers use isolated worktrees,+ protected resources validate fencing tokens, and exact-source receipts pass.+6. Older Ruflo installations ignore the new optional adapter and retain local+ behavior.+7. Removing the adapter never grants broader access; protected federated+ operations become unavailable.++## Normative acceptance tests++1. One hundred concurrent acquisitions of the same scope produce one owner and+ one current epoch.+2. A stale writer is rejected after lease expiry and reacquisition.+3. Renew and release with an old version or epoch are rejected.+4. Ancestor, descendant, symlink, case, separator, Unicode, traversal, and+ option-like path collisions are detected.+5. The same relative path in two different repositories does not collide.+6. Two writing agents are refused when configured to use one worktree.+7. A clean commit and a dirty worktree at the same `HEAD` produce different+ source-state identities.+8. A one-byte tracked or untracked change invalidates the run receipt.+9. A message reconnect resumes without loss; replay produces no duplicate+ side effect.+10. A message ID paired with different content is quarantined.+11. A lease holder without an action grant cannot deploy, spend, access a+ secret, or mutate an external product.+12. A grant holder without the current lease epoch cannot mutate a protected+ coordination scope.+13. Fault injection at every lease, receipt, inbox, and outbox boundary+ recovers to one valid state.+14. A release attempt using passing tests from a different source state is+ rejected.+15. A passing test receipt without release authority remains dry-run.+16. A cross-repository handoff cannot modify the receiver until its local owner+ acknowledges and acquires the target scope.+17. Local single-agent workflows behave as before when no harness adapter is+ configured.++## Consequences++### Positive++- Ruflo can cooperate with existing repository harnesses instead of replacing+ them.+- Worktree isolation and fine-grained leases cover different failure modes.+- Fencing prevents stale workers from affecting protected resources.+- Test and release evidence becomes attributable to exact source.+- Cross-repository work has an explicit receiving owner.++### Negative++- Protected local writes need an enforcement hook to validate fencing tokens.+- Exact dirty-state hashing is more expensive than recording `HEAD`.+- Multi-host coordination requires a linearizable service.+- Legacy shared-worktree sessions remain advisory until migrated.++## Review trigger++Review this ADR when Git changes its worktree identity model, a repository+harness adds distributed leases, Ruflo supports a new source-control system, or+production evidence demonstrates a different lease or receipt requirement.diff --git a/v3/docs/adr/ADR-328-cognitum-assisted-agent-learning.md b/v3/docs/adr/ADR-328-cognitum-assisted-agent-learning.mdnew file mode 100644index 0000000000..d27a956631--- /dev/null+++ b/v3/docs/adr/ADR-328-cognitum-assisted-agent-learning.md@@ -0,0 +1,273 @@+# ADR-328: Cognitum-Assisted Agent Learning Capability Plane++**Status**: Proposed — structural policy primitives implemented; service adapters pending+**Date**: 2026-07-28+**Decision owners**: Ruflo memory, policy, MetaHarness, Meta-LLM, and Cognitum maintainers+**Related**: ADR-176, ADR-322, ADR-323, ADR-324, ADR-325, ADR-326,+ADR-327++## Executive decision++Ruflo may use Cognitum and Meta-LLM services to improve agent development+through routing, critique, evidence retrieval, and validated memory proposals.+Those integrations form a **capability plane**, not an authority plane.++The closed initial action vocabulary is:++```text+cognition.route+cognition.critique+memory.recall+memory.propose+evidence.read+memory.commit-validated+```++No action in this profile authorizes policy promotion, MetaHarness promotion,+deployment, release, IAM, billing, secret access, or an ownership transition.+Those actions continue through their separate ADR-324/325 envelopes.++A Cognitum service can propose learning evidence. It cannot write Ruflo memory+directly. A validated memory commit requires a content-bound, one-use+capability and an ADR-324 decision receipt. Committing memory never+automatically changes active policy or promotes a model/candidate.++## Why this ADR is separate++ADR-326 defines cross-product authority and envelope semantics. Assisted agent+learning has a different lifecycle and failure mode:++- model output is evidence with `agent_output` provenance, not truth;+- recalled memory can be stale, poisoned, cross-tenant, or irrelevant;+- critique may improve a trajectory without being safe to execute;+- a useful pattern may be safe for memory but unsafe for active policy;+- service health and authorization change independently.++Treating cognition as ambient authority would let a model route expand its own+tools, persist its own conclusions, or promote its own policy. This ADR forbids+that loop.++## Decision++### 1. Keep each action narrow++| Action | Purpose | Explicitly does not allow |+|---|---|---|+| `cognition.route` | Recommend a model, provider, skill, or workflow route | Execute the route, add tools, increase budget |+| `cognition.critique` | Evaluate a plan, patch, test result, or trajectory | Modify code, approve a release, declare truth |+| `memory.recall` | Retrieve tenant- and namespace-bounded memory | Write, delete, promote, or broaden retrieval |+| `memory.propose` | Submit content for validation | Commit memory or alter policy |+| `evidence.read` | Resolve approved evidence by digest/reference | Read secrets or unredacted private data |+| `memory.commit-validated` | Commit exactly validated content | Modify active policy, route, model, or deployment |++Delegation may reduce these actions, resources, budgets, expiry, and+concurrency. It cannot add another action.++### 2. Bind cognition requests and results++A cognition request binds:++- issuer, subject, actor, audience, tenant, and namespace;+- exact action and resource;+- input or privacy-preserving input digest;+- model/provider eligibility and SafetyEnvelope;+- token, USD, latency, network, and concurrency ceilings;+- idempotency key, issued-at, expiry, and proof key;+- policy version and decision receipt.++A response binds the request digest, route/model actually used, output digest,+usage, latency, provider status, evidence references, and refusal/degraded+state.++Model prose is never interpreted as a capability. Structured output is+validated against the action schema and is still untrusted evidence.++### 3. Separate availability dimensions++Every service probe records:++```ts+interface CognitionServiceHealth {+ identity: 'verified' | 'unverified' | 'unknown';+ configured: 'yes' | 'no' | 'unknown';+ reachable: 'yes' | 'no' | 'unknown';+ healthy: 'yes' | 'no' | 'unknown';+ authorized: 'yes' | 'no' | 'unknown';+ status: 'available' | 'degraded' | 'blocked' | 'unavailable';+ checkedAt: string;+}+```++A valid grant does not imply reachability or health. A successful health probe+does not imply authorization. Missing configuration is distinct from network+failure. Product and CLI surfaces preserve these states rather than showing one+generic success/failure badge.++When cognition is unavailable, Ruflo may use its explicit local route if the+task and policy allow it. The fallback is recorded. A degraded cognition run+cannot promote MetaHarness state.++### 4. Treat recall as evidence++Recall returns typed ADR-323 memory records with provenance, tenant, namespace,+source digest, creation/observation time, expiry, confidence, and revocation+state. Retrieval policy filters before content reaches the agent.++The agent and validator distinguish:++- `system_observation`;+- `tool_result`;+- `user_claim`;+- `agent_output`; and+- `unknown`.++Similarity is not authority. A high vector score cannot satisfy signed+evidence, current observation, tenant, or policy requirements.++### 5. Use a proposal and validation pipeline++```text+memory.propose+ -> content and source digests+ -> schema and provenance validation+ -> poisoning/PII/prompt-injection checks+ -> duplication and contradiction checks+ -> policy evaluation+ -> optional human approval+ -> one-use memory.commit-validated capability+ -> atomic memory commit and receipt+```++The proposal includes the target tenant, namespace, memory type, content+digest, evidence digests, validator profile, proposed expiry, and correlation+ID. Validators do not mutate memory.++The commit capability binds:++```text+proposal ID and revision+tenant and namespace+exact content digest+ordered evidence digest set+validator ID and version+policy version and receipt+approval reference when required+idempotency key+expiry and maxUses = 1+```++The memory authority consumes the capability and writes the memory record,+receipt, and outbox event atomically. The same key and request digest replay+the original result; the same key with different content conflicts.++### 6. Keep memory and policy transactions separate++A committed memory can influence a future policy proposal or benchmark. It+cannot:++- update an ADR-324 rule;+- issue an approval;+- expand a CapabilityEnvelope;+- change an active champion;+- promote a Darwin/MetaHarness candidate;+- change a production route;+- authorize a tool or network side effect.++Policy and promotion require independent evaluation and transaction receipts.+The policy request may cite the memory record as evidence, but must recompute or+verify every authorizing term.++### 7. Make learning tenant-safe and revocable++Memory namespaces are tenant-qualified. Cross-tenant learning requires a+separate, explicit, privacy-reviewed aggregate that contains no tenant data and+cannot be reverse-mapped to one tenant.++Revocation or correction creates a new authoritative event. Existing receipts+remain in history but future recalls exclude the revoked record. Dependent+policy proposals and benchmark receipts retain the referenced memory digest so+impact can be traced.++### 8. Preserve local and previous-install behavior++- All Cognitum cognition providers are optional.+- Existing local AgentDB recall and memory APIs remain available.+- New installations start external cognition in `observe`.+- Existing memory writes retain compatibility mode until a namespace opts into+ validated commits.+- Privileged or cross-tenant memory commits fail closed without the new+ capability.+- Removing the provider disables assisted actions but does not corrupt or+ delete local memory.++## Implementation profile++The first Ruflo implementation provides:++- action names and ownership mapping in the ADR-326 product-plane module;+- structural envelope and identity/tenant validation;+- separate product-health dimensions;+- action-specific requirements for digest, idempotency, expiry, policy receipt,+ and capability;+- signed-envelope verifier hooks for local trust, replay, policy, and+ capability authorities.++The following remain service-adapter work:++- Cognitum token exchange;+- Meta-LLM route and critique adapters;+- durable external evidence resolution;+- the AgentDB transactional validated-commit consumer;+- dashboard/CLI health projection; and+- cross-repository conformance tests.++Until those adapters exist, documentation and release notes must describe the+feature as a policy and interoperability foundation, not an active cloud+self-learning loop.++## Normative acceptance tests++1. A route response cannot add an action, tool, provider, budget, network+ access, or delegation depth.+2. A valid claim with an unreachable service reports `unavailable`.+3. A healthy service with a denied action reports `blocked`.+4. A critique is stored as `agent_output`, not `system_observation`.+5. Recall never crosses tenant or namespace without an explicit aggregate+ grant.+6. Revoked or expired memory is absent from new recall results.+7. A model output cannot directly call `memory.commit-validated`.+8. A proposal with changed content after validation is rejected.+9. A capability with a mismatched tenant, namespace, validator version,+ evidence set, policy receipt, or content digest is rejected.+10. One hundred concurrent commits of one proposal produce one memory record+ and one current receipt.+11. Reusing an idempotency key with different content returns conflict.+12. A committed memory does not change active policy or champion state.+13. A policy or promotion proposal citing memory re-evaluates all authorizing+ terms.+14. Provider unavailability preserves the explicit local fallback and records+ degradation.+15. Removing optional Cognitum/Meta-LLM providers leaves local AgentDB+ operational.++## Consequences++### Positive++- Agents gain bounded cloud-assisted routing and critique.+- Useful learning can become durable without allowing a model to persist its+ own unchecked conclusions.+- Service failures remain diagnosable.+- Memory, policy, promotion, deployment, and spend retain separate authority.++### Negative++- Validated commits add latency and storage.+- Evidence and revocation require durable references.+- Operators must configure both product identity and Ruflo policy.++## Review trigger++Review this ADR when an external cognition provider receives write authority,+AgentDB adds a transactional validation API, a memory record becomes an input+to automatic policy or promotion, or the local compatibility path is removed.diff --git a/v3/docs/adr/ADR-329-ruflo-capability-brain-mcp-guidance.md b/v3/docs/adr/ADR-329-ruflo-capability-brain-mcp-guidance.mdnew file mode 100644index 0000000000..89095e3fd9--- /dev/null+++ b/v3/docs/adr/ADR-329-ruflo-capability-brain-mcp-guidance.md@@ -0,0 +1,237 @@+# ADR-329: Ruflo Capability Brain for MCP Guidance++**Status:** Accepted+**Date:** 2026-07-28+**Owners:** Ruflo CLI, Guidance, Security, and Release Maintainers+**Related:** ADR-150, ADR-176, ADR-320, ADR-322, ADR-324, ADR-325, ADR-327, ADR-328++## Context++Ruflo exposes a broad system through MCP tools, CLI commands, agents, skills,+packages, and plugins. The previous guidance catalog described 16 hand-written+areas and referenced 99 tool names. An audit of the current server found:++- 353 unique live tools when the optional raw-browser runtime is installed;+- 330 always-registered tools without that conditional runtime;+- only 61 of the 353 live tools referenced by the old catalog;+- 292 live tools omitted from that catalog;+- 38 catalog references that no longer resolve to live tool names;+- one exported `testgen_tdd_repair` tool that is not registered by the MCP+ client;+- plugin skills, `.agents/skills`, package ownership, plugin ownership,+ authority, risk, degraded behavior, and implementation-loop placement absent+ from discovery.++This created two failures. Users could not discover most of Ruflo, and agents+could mistake catalog text or MCP registration for proof that a provider was+configured, reachable, healthy, and authorized.++## Decision++Ruflo will ship a capability brain behind `guidance_brain` and enhance the+existing guidance tools without removing their compatibility surface.++The brain is generated from the completed live MCP registry. A static domain+definition supplies semantics; it does not supply runtime presence. The MCP+client injects its registry into guidance after all conditional and filtered+tools have been registered. This avoids a circular import and makes silent+catalog drift testable.++### Truth model++Every domain reports these facts independently:++| Fact | Meaning |+|---|---|+| `catalogued` | This Ruflo version describes the capability. |+| `registered` | The tool exists in this MCP process. |+| `configured` | Required settings/providers are present. |+| `reachable` | A non-mutating dependency probe succeeds. |+| `healthy` | The dependency satisfies its health contract. |+| `authorized` | Current subject may perform the exact action on the resource. |++Only `registered` can be derived from the MCP registry. The other dimensions+remain `unknown` until their dedicated adapters evaluate them. No single+“available” badge may collapse these dimensions.++### Complete capability surface++`guidance_brain` exposes:++1. every live registered MCP tool, assigned exactly once;+2. domain, owner, maturity, authority, risk flags, side-effect class,+ availability mode, implementation-loop phases, and verification guidance;+3. all 52 top-level CLI commands;+4. installed agents and skills from `.claude`, `.agents`, and plugin roots;+5. package and plugin manifests;+6. coverage gaps, duplicates, and fallback classifications;+7. task recommendations filtered to tools actually registered in this process.++The major domains deliberately distinguish:++- policy authorization from exclusive work claims;+- AIDefence content-safety evidence from authorization;+- memory recall from validated memory commit;+- MetaHarness/Darwin/Flywheel evaluation from promotion;+- consensus from authority;+- worktree leases from product or release authority;+- local/runtime capabilities from network and external-service actions.++The compatibility `guidance_capabilities` response remains available, but its+old string catalog is labeled compatibility-only and each legacy reference is+marked registered or unregistered. New routing consumes the live brain.++### Identity and OAuth guidance++The brain includes Ruflo's implemented Cognitum identity lifecycle from+[ADR-306](ADR-306-cognitum-authentication-account-linking.md) as a distinct+control-plane domain:++- `ruflo auth login` uses loopback PKCE on an interactive desktop;+- `ruflo auth login --no-browser` uses the implemented OOB/manual-paste flow;+- noninteractive login refuses unless `--token-stdin` is explicit;+- `ruflo auth status` is offline-safe, while `--check` may perform+ demand-driven keychain refresh;+- scopes remain bound to local consent receipts; `account.create` does not+ imply hosted memory, routing, telemetry, deployment, IAM, or billing;+- local logout clears session/profile/keychain state but does not claim+ server-side revocation, because the currently proven identity surface does+ not expose that operation.++RFC 8628 polling, a new Ruflo-specific OAuth client registration, automatic+existing-install prompts, and hosted memory/device-flow contracts remain+upstream work. Guidance must report those as unavailable rather than inventing+endpoints or silently broadening scope. Authenticated identity is still+independent of service configuration, reachability, health, and action+authorization.++### Capability metadata++The v1 brain uses domain-derived metadata for tools:++```text+name+domain+packageOwner+pluginOwner+availabilityMode+authority+risk+riskFlags+loopPhases+health.registered+health.configured+health.reachable+health.healthy+health.authorized+```++Availability modes are `always-local`, `conditional-registration`,+`registered-degraded`, `configured-remote`, and `policy-filtered`.++Risk flags cover read, local write, memory poisoning, process execution,+network, credentials/PII, spending, concurrency, destructive actions,+approval, and promotion. V1 supplies conservative domain defaults. A future+generated per-tool descriptor may narrow those defaults, but may never+silently lower risk.++### Normative implementation loop++Guidance recommendations and generated `AGENTS.md` files use this loop:++1. **Recall** prior memory and ADR constraints.+2. **Inspect** source, runtime, dependency, policy, and health state.+3. **Route** to the smallest capable topology, agents, skills, and tools.+4. **Plan** acceptance criteria, safety envelope, ownership, and validation.+5. **Execute** in isolated scopes; Ruflo coordinates while an executor works.+6. **Test** focused, regression, and failure paths.+7. **Validate** types, security, policy, compatibility, and artifact integrity.+8. **Benchmark** a source-bound candidate against a source-bound baseline.+9. **Optimize** only measured bottlenecks without weakening safety.+10. **Receipt** claims and evidence against exact source/build inputs.+11. **Handoff** and reconcile concurrent ownership and limitations.+12. **Publish** only through a separately authorized release gate.++Self-learning follows `recall → propose/branch → evaluate/critique →+commit-validated`. A memory or policy mutation requires a content digest and+validation receipt. No memory, neural, MetaHarness, Darwin, Flywheel, claims,+or consensus tool may authorize its own promotion.++## MCP contract++`guidance_brain` supports:++| Mode | Result |+|---|---|+| `overview` | Truth model, coverage, commands, registered domains, loop |+| `capabilities` | Full domain/tool descriptors, optionally one domain |+| `coverage` | Exact tool-to-domain assignments and gaps |+| `ecosystem` | Agents, skills, plugins, packages, and commands |+| `recommend` | Task-ranked live capabilities and guarded loop |+| `implementation-loop` | Normative stages, evidence, mutation class, invariants |++`guidance_discover` also discovers agents, skills, plugins, and packages.++## Backward compatibility++- The five existing guidance tool names and input modes remain.+- `guidance_brain` is additive.+- The old catalog is retained as an explicitly deprecated compatibility view.+- Conditional browser registration remains conditional.+- Optional packages remain registered-degraded where their handlers already+ implement that contract.+- Policy administration remains absent from remote MCP; only evaluation and+ status are registered.+- `testgen_tdd_repair` is catalogued but honestly reports unregistered until a+ separate decision registers it.++## Security and authority invariants++1. Registration never implies configuration, health, or authorization.+2. Recommendation is advisory and cannot invoke a tool.+3. A work claim cannot grant product, network, billing, IAM, or release access.+4. A score, signature, receipt, consensus vote, or memory does not authorize+ itself.+5. A degraded or fallback evaluator cannot promote unless an independent+ policy explicitly permits that exact substitution.+6. External writes, spending, destructive actions, credentials/PII, and+ promotion require explicit risk and approval handling.+7. Publication binds immutable artifacts to exact source/build evidence.++## Validation++Acceptance tests must prove:++1. every live registered tool is assigned exactly once;+2. no duplicate live tool names exist;+3. fallback classifications are reported and fail the repository coverage+ gate until assigned;+4. a catalogued but unregistered capability reports `registered: false`;+5. the five health/authority dimensions remain independent;+6. every recommendation returns the complete implementation loop;+7. publication is the final external-mutation stage and requires independent+ authorization;+8. filesystem discovery covers `.claude`, `.agents`, packages, and plugins;+9. missing optional providers remain degraded/unknown, not “available”;+10. policy authorization, work claims, and content safety remain separate.++The initial implementation classifies all 353 tools observed on Node 22/Linux+with the browser runtime installed, with no fallback classifications or+duplicates. This count is an environment observation, not a fixed protocol+constant; the coverage invariant is percentage and exact assignment.++## Performance budget++Brain construction and recommendation are local metadata operations. The+benchmark profile must measure the maximum live registry, report median and+tail latency, and fail if a future catalog change introduces an accidental+network call or tool execution. Filesystem ecosystem discovery is measured+separately because it performs bounded local I/O.++## Consequences++Users and agents can now ask Ruflo what it can actually do, receive safe+workflow guidance, and see capability gaps without reading hundreds of source+files. The cost is a maintained semantic domain map and mandatory coverage+tests. Service-specific health and authorization probes remain adapter work;+the brain exposes those unknowns instead of inventing a positive answer.diff --git a/v3/docs/adr/README.md b/v3/docs/adr/README.mdindex 2ef956937b..31ecfd1ec5 100644--- a/v3/docs/adr/README.md+++ b/v3/docs/adr/README.md@@ -41,6 +41,12 @@ All ADRs are located in [`/v3/implementation/adrs/`](../../implementation/adrs/)| [ADR-310](ADR-310-funnel-rollout-measurement-emergency-controls.md) | Funnel Rollout, Measurement, and Emergency Controls | Proposed || [ADR-320](ADR-320-mcp-composition-inspector-channel-guardrails.md) | MCP Tool Composition Inspector + Inter-Agent Channel Guardrails | Accepted || [ADR-323](ADR-323-typed-memory-provenance.md) | Typed Memory Provenance in AgentDB (MemIR-style claim typing, corrects #2804's dream-cycle proposal) | Accepted |+| [ADR-324](ADR-324-agentic-policy-engine-codex-swarm.md) | Agentic Policy Engine and Policy-Governed Codex Swarms | Accepted |+| [ADR-325](ADR-325-claim-federation-zero-trust-capability-plane.md) | Claim Federation as a Zero-Trust Capability and Work-Ownership Plane | Proposed |+| [ADR-326](ADR-326-cognitum-product-plane-claim-federation.md) | Cognitum Product-Plane Claim Federation Profile | Proposed |+| [ADR-327](ADR-327-federated-concurrent-development-harness.md) | Federated Concurrent Development Harness | Proposed |+| [ADR-328](ADR-328-cognitum-assisted-agent-learning.md) | Cognitum-Assisted Agent Learning Capability Plane | Proposed |+| [ADR-329](ADR-329-ruflo-capability-brain-mcp-guidance.md) | Ruflo Capability Brain for MCP Guidance | Accepted |## Summary Documentsdiff --git a/v3/docs/examples/ruflo-capability-brain-guide.md b/v3/docs/examples/ruflo-capability-brain-guide.mdnew file mode 100644index 0000000000..42b2f331d8--- /dev/null+++ b/v3/docs/examples/ruflo-capability-brain-guide.md@@ -0,0 +1,185 @@+# Give Your Coding Agent a Map of Ruflo++Most agent frameworks make you learn the framework before the agent can use+it well. You memorize tool names, remember which plugin owns what, and discover+too late that “installed” did not mean “configured” or “authorized.”++Ruflo v3.32.28 changes that. Its new MCP Capability Brain lets an agent inspect+the running Ruflo system, see every registered capability, understand the+authority and risk boundary, and choose a safe implementation workflow for the+task in front of it.++In a fully equipped local process, the old guidance catalog recognized only 61+of 353 MCP tools. The live brain now classifies all 353 observed tools exactly+once and also inventories CLI commands, agents, skills, packages, and plugins.++## The simplest way to use it++Tell your Codex or Claude Code agent:++> Before implementing this task, call Ruflo `guidance_brain` in `recommend`+> mode. Use only registered capabilities, verify configuration/health/authority+> separately, and follow the returned implementation loop.++The underlying MCP call is:++```json+{+ "name": "guidance_brain",+ "arguments": {+ "mode": "recommend",+ "task": "Add an authenticated API endpoint, test it, benchmark it, and prepare a release"+ }+}+```++The response gives the agent:++- relevant Ruflo capability domains;+- tools that are actually registered;+- agent and skill suggestions;+- authority and risk metadata;+- checks to perform before use;+- the full implementation loop and publication guardrails.++## Explore what Ruflo can do++Get a concise system view:++```json+{"name":"guidance_brain","arguments":{"mode":"overview"}}+```++Inspect a capability domain:++```json+{+ "name": "guidance_brain",+ "arguments": {+ "mode": "capabilities",+ "domain": "metaharness-flywheel"+ }+}+```++Audit tool coverage:++```json+{"name":"guidance_brain","arguments":{"mode":"coverage"}}+```++Discover installed agents, skills, plugins, packages, and all top-level CLI+commands:++```json+{"name":"guidance_brain","arguments":{"mode":"ecosystem"}}+```++Get the implementation contract by itself:++```json+{"name":"guidance_brain","arguments":{"mode":"implementation-loop"}}+```++## What this enables++### 1. Self-configuring agent workflows++An agent no longer needs a hard-coded list of Ruflo features. It can discover+the current MCP process and adapt when optional tools are present or absent.++### 2. Safer autonomous development++The brain routes work through:++```text+recall+ → inspect+ → route+ → plan+ → execute+ → test+ → validate+ → benchmark+ → optimize+ → receipt+ → handoff+ → authorized publish+```++Ruflo coordinates and records; the coding agent executes. Learning,+MetaHarness, Darwin, Flywheel, consensus, claims, and benchmarks can propose or+evaluate improvements, but cannot authorize their own promotion.++### 3. Honest optional integrations++The brain does not collapse capability state into one green badge:++- `registered`: present in this MCP process;+- `configured`: required settings/providers exist;+- `reachable`: dependencies answer a safe probe;+- `healthy`: dependencies meet their health contract;+- `authorized`: this subject may perform this exact action.++Only the first fact comes from the registry. The others stay `unknown` until+their dedicated checks run.++### 4. Better concurrent agent teams++Generated Codex guidance now combines the brain with isolated worktrees,+exclusive work claims, narrow capability envelopes, source-bound evidence, and+an integration owner. In-memory harness references let adapter authors test+fencing, inbox, and receipt semantics without pretending those references are+distributed release infrastructure.++### 5. Policy-governed federation foundations++Upgraded federation peers advertise JCS/Ed25519 signatures by default and+negotiate them when the join includes the peer's signature-verified manifest.+Endpoint-only joins remain untrusted. A legacy-only peer remains compatible+for heartbeat and status broadcasts, but consequential traffic fails closed+until that peer is upgraded and its signed manifest is supplied.++The Security SDK also supplies strict product-action envelopes for the+Cognitum dashboard, Meta-LLM, Comms, Cog Studio, RuView, and validated agent+learning.++## Install++```bash+npm install --global [email protected]+ruflo doctor+```++Or:++```bash+npx [email protected] --help+```++## Compatibility++The Capability Brain is additive. Existing guidance tools remain available,+old projects keep their current policy mode, and optional dependencies still+degrade explicitly when absent. The old hand-written guidance catalog is+retained only as a labeled compatibility view; stale aliases are not returned+as live recommendations.++## Boundaries that matter++This release provides an opt-in foundation, not a claim that distributed+federation or autonomous release is production-ready. Production still needs+deployment-specific identity links, persistent fenced leases, durable+inbox/outbox storage, signed receipt ledgers, and release-decision composition.++A signature proves key control. A work claim coordinates ownership. A score or+benchmark supplies evidence. A policy decision grants authority. Ruflo keeps+those concepts separate.++## Further reading++- [ADR-325 — Claim Federation](https://github.com/ruvnet/ruflo/blob/main/v3/docs/adr/ADR-325-claim-federation-zero-trust-capability-plane.md)+- [ADR-326 — Cognitum Product Plane](https://github.com/ruvnet/ruflo/blob/main/v3/docs/adr/ADR-326-cognitum-product-plane-claim-federation.md)+- [ADR-327 — Concurrent Development Harness](https://github.com/ruvnet/ruflo/blob/main/v3/docs/adr/ADR-327-federated-concurrent-development-harness.md)+- [ADR-328 — Assisted Agent Learning](https://github.com/ruvnet/ruflo/blob/main/v3/docs/adr/ADR-328-cognitum-assisted-agent-learning.md)+- [ADR-329 — Capability Brain](https://github.com/ruvnet/ruflo/blob/main/v3/docs/adr/ADR-329-ruflo-capability-brain-mcp-guidance.md)diff --git a/v3/docs/releases/v3.32.28.md b/v3/docs/releases/v3.32.28.mdnew file mode 100644index 0000000000..fab7d2b952--- /dev/null+++ b/v3/docs/releases/v3.32.28.md@@ -0,0 +1,193 @@+# Ruflo v3.32.28: Agents That Know the Whole System++Ruflo has grown into a large agentic runtime, but its old MCP guidance catalog+only knew about 61 of the 353 tools available in a fully equipped process. That+made powerful features hard to discover and made agents more likely to guess+at stale tool names.++v3.32.28 introduces the Ruflo Capability Brain: a live, machine-readable map of+the MCP registry, CLI commands, agents, skills, packages, plugins, authority+boundaries, risk, and the end-to-end implementation loop. Agents can now ask+Ruflo which capabilities fit a task and automatically choose from tools that+are actually registered in the current process.++## What you can use it for++- Discover every MCP tool registered in your running Ruflo server.+- Route a task to suitable tools, agents, skills, and a swarm topology.+- Find capabilities across `.claude`, `.agents`, installed packages, and Ruflo+ plugins.+- Keep optional or remote integrations honest: registered, configured,+ reachable, healthy, and authorized are reported as different facts.+- Guide autonomous development through recall, inspection, planning,+ implementation, testing, validation, benchmarking, optimization, evidence,+ handoff, and authorized publication.+- Distinguish policy authorization, exclusive work claims, content-safety+ evidence, memory learning, consensus, and release authority.+- Route Cognitum identity through the implemented PKCE/OOB profile lifecycle,+ while reporting RFC 8628 polling and server-side logout revocation as+ unavailable instead of guessing.++## Try the Capability Brain++In Codex, Claude Code, or another MCP client, ask the agent:++> Use Ruflo `guidance_brain` to recommend the best workflow for implementing+> this task, then follow the returned implementation loop.++Or call the MCP tool directly:++```json+{+ "name": "guidance_brain",+ "arguments": {+ "mode": "recommend",+ "task": "Implement a secure API change with concurrent agents, tests, benchmarks, and a release"+ }+}+```++Useful modes:++```json+{"name":"guidance_brain","arguments":{"mode":"overview"}}+{"name":"guidance_brain","arguments":{"mode":"capabilities","domain":"memory-knowledge"}}+{"name":"guidance_brain","arguments":{"mode":"coverage"}}+{"name":"guidance_brain","arguments":{"mode":"ecosystem"}}+{"name":"guidance_brain","arguments":{"mode":"implementation-loop"}}+```++The existing `guidance_capabilities`, `guidance_recommend`,+`guidance_discover`, `guidance_workflow`, and `guidance_quickref` tools remain+compatible. Their old string catalog is now labeled compatibility-only, and+stale references are never presented as live recommendations.++## The implementation loop++Generated Codex `AGENTS.md` guidance and capability recommendations now use one+complete loop:++1. Recall relevant memory and ADR constraints.+2. Inspect source, runtime, dependencies, policy, and health.+3. Route to the smallest capable topology and tool set.+4. Plan acceptance criteria, safety, ownership, and validation.+5. Execute in isolated scopes; Ruflo coordinates while the coding agent works.+6. Test focused, regression, and failure paths.+7. Validate types, security, policy, compatibility, and artifacts.+8. Benchmark a source-bound candidate against a source-bound baseline.+9. Optimize measured bottlenecks without weakening safety.+10. Bind claims and evidence to exact source/build inputs.+11. Reconcile concurrent handoffs and disclose limitations.+12. Publish only through a separately authorized release gate.++Learning and optimization remain proposal/evidence capabilities. They cannot+promote themselves or expand network, secrets, spending, concurrency, or+policy authority.++## Federation and Cognitum foundations++This release also adds opt-in foundations for policy-governed federation and+Cognitum product actions:++- Upgraded federation peers advertise recursive JCS/Ed25519 signatures by+ default. JCS is negotiated only when the join includes a signature-verified+ peer manifest; endpoint-only joins stay untrusted.+- Legacy federation signatures are restricted to `heartbeat` and+ `status-broadcast`; consequential legacy messages are rejected on ingress+ and fail closed on egress to legacy-only peers.+- Inbound federation authorization runs after signature verification and+ before acceptance, replay marking, or event delivery.+- The Security SDK adds a closed 31-action product vocabulary for the+ Cognitum dashboard, Meta-LLM, Comms, Cog Studio, RuView, and validated+ learning.+- Product envelopes enforce audience, tenant, freshness, capability, policy,+ Ed25519 signature, action-specific obligations, and atomic replay-store+ hooks.+- RuView exports are constrained to registered, privacy-minimized semantic+ observations rather than raw sensor payloads.++## Concurrent development foundations++The Codex package now exposes:++- content-addressed Git-visible source-state capture;+- separately declared and recomputable build-input/toolchain evidence;+- portable path/case ambiguity refusal;+- in-memory reference implementations for fenced leases, acknowledged inbox+ semantics, and content-addressed run receipts.++These references are deliberately observe-only, unsigned, non-persistent, and+single-process. They help adapter authors test semantics; they are not+distributed release authorities.++## Install or upgrade++```bash+npm install --global [email protected]+ruflo doctor+```++Or run it without a global install:++```bash+npx [email protected] --help+```++Package train:++- `[email protected]`+- `[email protected]`+- `@claude-flow/[email protected]`+- `@claude-flow/[email protected]`+- `@claude-flow/[email protected]`+- `@claude-flow/[email protected]`++## Compatibility++- Existing guidance MCP tools remain available.+- Existing projects stay in their current policy compatibility mode.+- JCS federation signing is negotiated; no downgrade occurs after a failed JCS+ verification.+- Older installations continue local workflows when optional packages are+ absent.+- The new Codex harness and Cognitum product-plane APIs are additive exports.++## Local validation and benchmarks++Validated on Node.js 22/Linux:++- Capability Brain: all 353 observed live tools assigned exactly once; zero+ duplicate or fallback classifications.+- CLI focused brain/guardrail tests: 12 passing.+- Codex: 229 tests passing.+- Security: 559 tests passing.+- Federation: 638 tests passing.+- Capability Brain build for a 353-tool registry: p99 about 0.44 ms in the+ latest local run; recommendation p99 about 0.04 ms.+- 1.5 KiB federation JCS canonicalization: p50 8.47 µs, p99 8.83 µs,+ approximately 118,087 operations/second.+- 1.0 KiB signed Cognitum action verification: p50 71.97 µs, p99 81.93 µs,+ approximately 13,894 verifications/second.+- Source-state capture over a clean 200-file Git fixture averaged 15.77 ms;+ the dirty-patch plus 25-file manifest fixture averaged 27.09 ms.++These are local microbenchmarks, not cross-platform service SLOs.++## Important limitations++These APIs are an opt-in foundation, not a declaration that distributed claim+federation is production-ready. Persistent control-plane leases, durable+inbox/outbox storage, signed receipt ledgers, release-decision composition,+cross-service identity links, and Cognitum production adapters still require+deployment-specific implementation and acceptance testing.++A lease, signature, claim, score, memory, consensus result, or passing test is+evidence. None grants product or release authority by itself.++## Architecture++- ADR-325: zero-trust claim federation and work ownership+- ADR-326: Cognitum product-plane federation profile+- ADR-327: federated concurrent development harness+- ADR-328: Cognitum-assisted agent learning+- ADR-329: Ruflo Capability Brain for MCP guidancediff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex aac0424482..524b46b6a0 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -158,7 +158,7 @@ importers:specifier: ^3.0.0-alpha.21version: link:../memory'@claude-flow/security':- specifier: ^3.0.0-alpha.13+ specifier: ^3.0.0-alpha.14version: link:../securityagentdb:specifier: ^3.0.0-alpha.17