π 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: ADR-164 agentbbs business autopilot β Phases 1-4 (4 MCP tools, 7 pods, http_fetch, atomic budget tracker) (#2503)
rUv19e4277e12eb
diff --git a/.github/workflows/business-pods-smoke.yml b/.github/workflows/business-pods-smoke.ymlnew file mode 100644index 0000000000..f8f7efd5c4--- /dev/null+++ b/.github/workflows/business-pods-smoke.yml@@ -0,0 +1,61 @@+# ADR-164 Phase 2 β sales-pod smoke contract.+#+# Asserts that the business-pod template surface (sales.json + pod-schema+# validator + business_pod_validate MCP tool + pod-tick.mjs dry-run runner)+# stays green on every PR that touches the relevant files.+name: business-pods-smoke++on:+ push:+ branches: [main]+ paths:+ - 'plugins/ruflo-business-pods/**'+ - 'v3/@claude-flow/cli/src/business-pods/**'+ - 'v3/@claude-flow/cli/src/mcp-tools/business-pod-tools.ts'+ - 'v3/@claude-flow/cli/src/mcp-tools/index.ts'+ - 'v3/@claude-flow/cli/src/mcp-client.ts'+ - '.github/workflows/business-pods-smoke.yml'+ pull_request:+ paths:+ - 'plugins/ruflo-business-pods/**'+ - 'v3/@claude-flow/cli/src/business-pods/**'+ - 'v3/@claude-flow/cli/src/mcp-tools/business-pod-tools.ts'+ - 'v3/@claude-flow/cli/src/mcp-tools/index.ts'+ - 'v3/@claude-flow/cli/src/mcp-client.ts'+ - '.github/workflows/business-pods-smoke.yml'+ workflow_dispatch:++jobs:+ smoke:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ with:+ version: 8+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'pnpm'+ cache-dependency-path: v3/pnpm-lock.yaml+ - name: install + build CLI (pnpm, v3 workspace)+ # The root package.json uses npm/workspaces but the v3/ tree is a+ # pnpm workspace (v3/pnpm-workspace.yaml). npm chokes on+ # `workspace:*` here β use pnpm in the v3 dir instead.+ working-directory: v3+ run: |+ pnpm install --frozen-lockfile+ # Build ALL workspace packages in topological order β the cli has+ # cross-package deps (e.g. imports @claude-flow/swarm/dist/...)+ # that pnpm's dependency-aware filter can't discover from+ # package.json alone. `pnpm -r build` runs the build script across+ # the whole workspace, dep-first.+ pnpm -r --no-bail build || pnpm --filter @claude-flow/cli build+ - name: vitest β business-pod-tools+ working-directory: v3/@claude-flow/cli+ run: pnpm vitest run __tests__/business-pod-tools.test.ts+ - name: node --test β pod-tick+ run: node --test plugins/ruflo-business-pods/scripts/pod-tick.test.mjs+ - name: smoke contract+ run: bash plugins/ruflo-business-pods/scripts/smoke.shdiff --git a/.github/workflows/no-agentbbs-smoke.yml b/.github/workflows/no-agentbbs-smoke.ymlnew file mode 100644index 0000000000..0b60a2e31e--- /dev/null+++ b/.github/workflows/no-agentbbs-smoke.yml@@ -0,0 +1,173 @@+# ADR-164 architectural constraint enforcement.+#+# "Ruflo remains operational if the agentbbs package is removed."+#+# This workflow asserts three architectural rules from ADR-164 Β§5.1.1:+# 1. agentbbs lives in `optionalDependencies`, NEVER `dependencies`+# 2. Every code path that touches agentbbs in v3/@claude-flow/cli/src/+# is preceded by `loadAgentbbs()` (or a dynamic `import('agentbbs')`)+# 3. Runtime drill: with `--no-optional` / unreachable registry, the smoke+# contract exits 0 (graceful degradation).+#+# If this job ever fails, an agentbbs API has accidentally been promoted to+# a hard runtime requirement β breaking the optional-dep playbook from+# ADR-150 / agenticow / metaharness. The fix is either to make the new code+# path graceful, or to write a new ADR that supersedes the constraint.+name: no-agentbbs-smoke++on:+ push:+ branches: [main]+ paths:+ - 'plugins/ruflo-bbs-federation/**'+ - 'v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts'+ - 'v3/@claude-flow/cli/src/mcp-client.ts'+ - 'v3/@claude-flow/cli/src/mcp-tools/index.ts'+ - 'v3/@claude-flow/cli/package.json'+ - 'scripts/smoke-agentbbs.sh'+ - '.github/workflows/no-agentbbs-smoke.yml'+ pull_request:+ paths:+ - 'plugins/ruflo-bbs-federation/**'+ - 'v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts'+ - 'v3/@claude-flow/cli/src/mcp-client.ts'+ - 'v3/@claude-flow/cli/src/mcp-tools/index.ts'+ - 'v3/@claude-flow/cli/package.json'+ - 'scripts/smoke-agentbbs.sh'+ - '.github/workflows/no-agentbbs-smoke.yml'+ workflow_dispatch:++jobs:+ smoke-without-agentbbs:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'++ - name: Rule 1 β agentbbs must NOT appear in non-optional dependencies anywhere+ # Static check: every package.json that could carry the dep must list+ # agentbbs only under optionalDependencies. If it appears in+ # `dependencies` anywhere, we've broken the architectural constraint.+ run: |+ node -e "+ const { readFileSync, readdirSync, statSync } = require('fs');+ const { join } = require('path');+ const candidates = [+ 'package.json',+ 'ruflo/package.json',+ 'v3/@claude-flow/cli/package.json',+ ];+ try {+ for (const p of readdirSync('plugins')) {+ const pj = join('plugins', p, 'package.json');+ try { statSync(pj); candidates.push(pj); } catch {}+ }+ } catch {}+ const offenders = [];+ for (const c of candidates) {+ let json;+ try { json = JSON.parse(readFileSync(c, 'utf-8')); } catch { continue; }+ for (const dep of Object.keys(json.dependencies || {})) {+ if (/^agentbbs$/.test(dep)) {+ offenders.push({ file: c, dep });+ }+ }+ }+ if (offenders.length) {+ console.error('ADR-164 architectural constraint violated:');+ for (const o of offenders) console.error(' ' + o.file + ' β ' + o.dep + ' in dependencies (must be optionalDependencies)');+ process.exit(1);+ }+ console.log('OK β agentbbs is not in non-optional dependencies anywhere.');+ "++ - name: Rule 2 β every `agentbbs` usage in cli/src must be guarded by loadAgentbbs / dynamic import+ # Walk every .ts under v3/@claude-flow/cli/src that mentions agentbbs.+ # For each match, the SAME file must also reference loadAgentbbs() OR+ # use a dynamic import('agentbbs'). Static `import ... from 'agentbbs'`+ # is forbidden β it would make the dep mandatory.+ run: |+ node -e "+ const { readFileSync, readdirSync, statSync } = require('fs');+ const { join } = require('path');+ const root = 'v3/@claude-flow/cli/src';+ const offenders = [];+ function walk(dir) {+ for (const e of readdirSync(dir)) {+ const p = join(dir, e);+ const st = statSync(p);+ if (st.isDirectory()) { walk(p); continue; }+ if (!p.endsWith('.ts')) continue;+ const src = readFileSync(p, 'utf-8');+ // Static import β forbidden:+ if (/^\s*import\s+[^;]*from\s+['\"]agentbbs['\"]/m.test(src)) {+ offenders.push({ file: p, reason: 'static import of agentbbs' });+ continue;+ }+ // If file mentions agentbbs at all, require a guard β except+ // for files that ONLY re-export our own agentbbsTools symbol+ // (the symbol itself contains the loadAgentbbs guard).+ if (/agentbbs/.test(src)) {+ // Strip benign re-exports + comment mentions, then check the rest.+ // Patterns we treat as safe (do not require their own loadAgentbbs guard):+ // - `export { agentbbsTools } from './agentbbs-tools.js';`+ // - `import { agentbbsTools } from './mcp-tools/agentbbs-tools.js';`+ // - `...agentbbsTools,`+ // - any comment line mentioning agentbbs+ const stripped = src+ .replace(/^\s*\/\/.*$/gm, '') // single-line comments+ .replace(/\/\*[\s\S]*?\*\//g, '') // block comments+ .replace(/export\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['\"][^'\"]+agentbbs-tools[^'\"]*['\"];?/g, '')+ .replace(/import\s+\{[^}]*agentbbsTools[^}]*\}\s+from\s+['\"][^'\"]+agentbbs-tools[^'\"]*['\"];?/g, '')+ .replace(/\.\.\.agentbbsTools,?/g, '');+ if (/agentbbs/.test(stripped)) {+ const guarded = /loadAgentbbs|import\(['\"]agentbbs['\"]\)/m.test(src);+ if (!guarded) {+ offenders.push({ file: p, reason: 'agentbbs reference without loadAgentbbs/dynamic import guard' });+ }+ }+ }+ }+ }+ walk(root);+ if (offenders.length) {+ console.error('ADR-164 rule 2 violated:');+ for (const o of offenders) console.error(' ' + o.file + ': ' + o.reason);+ process.exit(1);+ }+ console.log('OK β every agentbbs reference under ' + root + ' is dynamically guarded.');+ "++ - uses: pnpm/action-setup@v4+ with:+ version: 8+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'pnpm'+ cache-dependency-path: v3/pnpm-lock.yaml++ - name: Rule 3 β runtime drill (surgically remove agentbbs only, run smoke)+ # Install everything (so other optional deps like agentdb stay available+ # for transitive consumers β they have their own degradation paths)+ # but DELETE node_modules/agentbbs to force loadAgentbbs() to return null.+ # smoke-agentbbs.sh accepts DEGRADED:agentbbs-not-found as a PASS for+ # step 8, so the whole script should still exit 0.+ # Uses pnpm (the v3/ workspace's real package manager) since some root+ # deps use the `workspace:*` protocol that npm doesn't support.+ run: |+ set -e+ (cd v3 && pnpm install --frozen-lockfile)+ # Build whole workspace dep-first (cli has cross-package deps the+ # `...` filter can't discover from package.json alone)+ (cd v3 && pnpm -r --no-bail build || pnpm --filter @claude-flow/cli build)+ # Surgically remove agentbbs from every install location it landed.+ find v3 -type d -name agentbbs -path '*node_modules*' -exec rm -rf {} + 2>/dev/null || true+ # Sanity check β the package really is gone+ if find v3 -type d -name agentbbs -path '*node_modules*' 2>/dev/null | grep -q . ; then+ echo "ERROR: agentbbs still in node_modules"; exit 1+ fi+ bash scripts/smoke-agentbbs.shdiff --git a/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json b/plugins/ruflo-bbs-federation/.claude-plugin/plugin.jsonnew file mode 100644index 0000000000..45871f14d9--- /dev/null+++ b/plugins/ruflo-bbs-federation/.claude-plugin/plugin.json@@ -0,0 +1,25 @@+{+ "name": "ruflo-bbs-federation",+ "description": "AgentBBS federated business-domain BBS room integration for ruflo (ADR-164 Phase 1). Exposes federation_bbs_register / federation_bbs_publish / federation_bbs_watch / federation_bbs_human_join MCP tools that wrap the agentbbs Rust workspace as a special-tier federation peer. agentbbs lives in optionalDependencies; every handler gracefully degrades to {degraded:true} when the package is missing, mirroring the architectural constraint pattern from ADR-150 and agenticow (PR #2500).",+ "version": "0.1.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },+ "homepage": "https://github.com/ruvnet/ruflo",+ "license": "MIT",+ "keywords": [+ "ruflo",+ "bbs",+ "federation",+ "agentbbs",+ "business-autopilot",+ "domain-pods",+ "cockpit",+ "ed25519",+ "optional-dependency",+ "graceful-degradation",+ "adr-164",+ "phase-1-mvp"+ ]+}diff --git a/plugins/ruflo-business-pods/.claude-plugin/plugin.json b/plugins/ruflo-business-pods/.claude-plugin/plugin.jsonnew file mode 100644index 0000000000..8ecd9a3e95--- /dev/null+++ b/plugins/ruflo-business-pods/.claude-plugin/plugin.json@@ -0,0 +1,25 @@+{+ "name": "ruflo-business-pods",+ "description": "ADR-164 Phase 2 β business-domain pod templates for the federated business autopilot. Ships the sales pod template (templates/sales.json) and a single-tick runner (scripts/pod-tick.mjs) that pre-flights templates via business_pod_validate, reserves budget through a file-based stub ledger (atomic SQLite tracker is Phase 3 per ADR-164.1), resolves each agent role against ruflo's agent registry, constructs dry-run prompts, and posts an envelope summary to the room via federation_bbs_publish. Dry-run by default β --live is reserved for Phase 3 Managed-Agent + claude-p wiring.",+ "version": "0.1.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },+ "homepage": "https://github.com/ruvnet/ruflo",+ "license": "MIT",+ "keywords": [+ "ruflo",+ "pods",+ "business",+ "sales",+ "adr-164",+ "adr-164.1",+ "phase-2",+ "pod-template",+ "pod-tick",+ "budget-reservation",+ "dry-run-default",+ "agent-registry-resolution"+ ]+}diff --git a/plugins/ruflo-business-pods/scripts/pod-tick.mjs b/plugins/ruflo-business-pods/scripts/pod-tick.mjsnew file mode 100755index 0000000000..e72429748a--- /dev/null+++ b/plugins/ruflo-business-pods/scripts/pod-tick.mjs@@ -0,0 +1,466 @@+#!/usr/bin/env node+/**+ * pod-tick.mjs β One iteration of a business pod (ADR-164 Phase 2).+ *+ * Dry-run by default; --live is reserved for Phase 3 (Managed-Agent + claude-p+ * wiring) and refuses to engage in this Phase 2 build.+ *+ * Lifecycle for one tick:+ * 1. Load pod template, validate against pod-schema (hand-rolled, no AJV dep).+ * 2. Resolve every agent.agentType against ruflo's agent registry (KNOWN_AGENT_TYPES).+ * Unknown types are fatal with an actionable message.+ * 3. Reserve budget via the Phase-2 file-based stub ledger+ * (basePath/budget/<roomId>.json). TODO(adr-164.1): swap to the atomic+ * SQLite tracker once Phase 3 lands.+ * 4. For each agent: construct a dry-run prompt (kickoff text scoped to the+ * pod's bench description + domain). Log prompts; skip in dry-run mode.+ * 5. Commit the reservation with actual_usd. In dry-run actual_usd = $0.+ * 6. Append a structured envelope summary to the room's JSONL log (Phase 1+ * backing store; same path the federation_bbs_publish MCP tool writes).+ * 7. Emit a single JSON line to stdout: {podName, tickId, agentsRan,+ * totalUsd, envelopeId, status} β /loop ingests this verbatim.+ *+ * CLI:+ * pod-tick.mjs --pod-template <path> [--base-path <dir>] [--dry-run|--live]+ * [--budget-cap-usd <amount>] [--tick-id <id>]+ *+ * Exit codes:+ * 0 β tick succeeded (status === 'success')+ * 2 β invalid template / unknown agent type / budget exhausted / arg error+ * 3 β --live mode requested (refused in Phase 2)+ */++import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';+import { resolve, dirname, join, isAbsolute } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createHash, randomBytes } from 'node:crypto';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const PLUGIN_ROOT = resolve(__dirname, '..');++// ---------- arg parsing ----------------------------------------------------++function parseArgs(argv) {+ const args = {+ podTemplate: null,+ basePath: null,+ dryRun: true,+ live: false,+ budgetCapUsd: null,+ tickId: null,+ };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--pod-template') args.podTemplate = argv[++i];+ else if (a === '--base-path') args.basePath = argv[++i];+ else if (a === '--dry-run') args.dryRun = true;+ else if (a === '--live') { args.live = true; args.dryRun = false; }+ else if (a === '--budget-cap-usd') args.budgetCapUsd = Number(argv[++i]);+ else if (a === '--tick-id') args.tickId = argv[++i];+ else if (a === '--help' || a === '-h') {+ printUsage();+ process.exit(0);+ }+ }+ return args;+}++function printUsage() {+ process.stdout.write(`pod-tick.mjs β one tick of a business pod (ADR-164 Phase 2)++Usage:+ pod-tick.mjs [--pod-template <path>] [--base-path <dir>] [--dry-run|--live]+ [--budget-cap-usd <amount>] [--tick-id <id>]++Defaults:+ --pod-template templates/sales.json (relative to plugin root)+ --base-path <cwd>/.business-pods+ --dry-run true (--live is refused in Phase 2)+`);+}++// ---------- minimal pod-schema validator (mirrors cli/src/business-pods) ----++// The validator is duplicated in this script because the script must be+// runnable from a checkout without a pre-built CLI. If pod-schema.ts grows,+// this copy is the one to keep tracking β the smoke contract pins it.++const PII_POLICIES = ['soc2', 'gdpr', 'hipaa', 'permissive'];+const KNOWN_AGENT_TYPES = new Set([+ 'coder', 'researcher', 'tester', 'reviewer', 'architect', 'system-architect',+ 'coordinator', 'analyst', 'optimizer', 'security-architect', 'security-auditor',+ 'memory-specialist', 'swarm-specialist', 'performance-engineer', 'core-architect',+ 'test-architect', 'planner', 'task-orchestrator', 'perf-analyzer', 'backend-dev',+ 'api-docs', 'cicd-engineer', 'code-analyzer', 'database-specialist',+ // ADR-164 Phase 3 β added for the marketing/hr pods (content drafting ++ // onboarding-template generation). Mirror in pod-schema.ts KNOWN_AGENT_TYPES.+ 'base-template-generator',+]);+const CRON_RE = /^([\d*/,\-]+\s+){4,5}[\d*/,\-]+$/;++function isObject(v) { return typeof v === 'object' && v !== null && !Array.isArray(v); }+function fail(msg, path) {+ const err = new Error(`pod-template at ${path}: ${msg}`);+ err.path = path;+ throw err;+}+function reqStr(o, k, p) { if (typeof o[k] !== 'string' || !o[k]) fail(`field "${k}" must be non-empty string`, p); return o[k]; }+function reqNum(o, k, p) { if (typeof o[k] !== 'number' || !Number.isFinite(o[k])) fail(`field "${k}" must be finite number`, p); return o[k]; }+function reqBool(o, k, p) { if (typeof o[k] !== 'boolean') fail(`field "${k}" must be boolean`, p); return o[k]; }+function reqArr(o, k, p) { if (!Array.isArray(o[k])) fail(`field "${k}" must be array`, p); return o[k]; }++function validatePodTemplate(json) {+ if (!isObject(json)) fail('pod-template must be a JSON object', '/');+ const name = reqStr(json, 'name', '/');+ if (!/^[a-z][a-z0-9-]*$/.test(name)) fail('name must be lowercase-kebab', '/');+ const displayName = reqStr(json, 'displayName', '/');+ const roomId = reqStr(json, 'roomId', '/');+ if (!/^[A-Za-z0-9_.\-:/@#]+$/.test(roomId)) {+ fail('roomId may only contain [A-Za-z0-9_.\\-:/@#]', '/');+ }+ const agents = reqArr(json, 'agents', '/').map((a, i) => {+ const p = `/agents[${i}]`;+ if (!isObject(a)) fail('agent must be object', p);+ return {+ role: reqStr(a, 'role', p),+ agentType: reqStr(a, 'agentType', p),+ description: reqStr(a, 'description', p),+ preferLocal: reqBool(a, 'preferLocal', p),+ };+ });+ if (agents.length === 0) fail('agents must have β₯1 entry', '/');+ const allowedMcpTools = reqArr(json, 'allowedMcpTools', '/').map((t, i) => {+ if (typeof t !== 'string' || !t) fail('allowedMcpTools entries must be non-empty strings', `/allowedMcpTools[${i}]`);+ return t;+ });+ if (allowedMcpTools.length === 0) fail('allowedMcpTools must have β₯1 entry', '/');+ const benchRaw = json.bench;+ if (!isObject(benchRaw)) fail('bench must be object', '/bench');+ const bench = {+ name: reqStr(benchRaw, 'name', '/bench'),+ description: reqStr(benchRaw, 'description', '/bench'),+ successCriteria: reqArr(benchRaw, 'successCriteria', '/bench'),+ scheduleHours: reqNum(benchRaw, 'scheduleHours', '/bench'),+ };+ if (bench.successCriteria.length === 0) fail('bench.successCriteria must have β₯1 entry', '/bench');+ if (bench.scheduleHours < 1) fail('bench.scheduleHours must be β₯1', '/bench');+ const piiPolicy = reqStr(json, 'piiPolicy', '/');+ if (!PII_POLICIES.includes(piiPolicy)) fail(`piiPolicy must be one of ${PII_POLICIES.join(', ')}`, '/');+ const budgetUsdMonthly = reqNum(json, 'budgetUsdMonthly', '/');+ if (budgetUsdMonthly < 0) fail('budgetUsdMonthly must be β₯0', '/');+ const budgetUsdPerRun = reqNum(json, 'budgetUsdPerRun', '/');+ if (budgetUsdPerRun < 0) fail('budgetUsdPerRun must be β₯0', '/');+ if (budgetUsdMonthly > 0 && budgetUsdPerRun > budgetUsdMonthly) {+ fail('budgetUsdPerRun must not exceed budgetUsdMonthly', '/');+ }+ const preferLocalExecution = reqBool(json, 'preferLocalExecution', '/');+ const cronSchedule = reqStr(json, 'cronSchedule', '/');+ if (!CRON_RE.test(cronSchedule)) fail('cronSchedule must be POSIX cron (5 or 6 fields)', '/');+ const auditView = json.auditReadView;+ if (!isObject(auditView)) fail('auditReadView must be object', '/auditReadView');+ const auditReadView = {+ includedEventTypes: reqArr(auditView, 'includedEventTypes', '/auditReadView'),+ retentionDays: reqNum(auditView, 'retentionDays', '/auditReadView'),+ };+ if (auditReadView.retentionDays < 1) fail('auditReadView.retentionDays must be β₯1', '/auditReadView');+ let reservationExpiryMs;+ if (json.reservationExpiryMs !== undefined) {+ const v = reqNum(json, 'reservationExpiryMs', '/');+ if (v < 5_000 || v > 300_000) fail('reservationExpiryMs must be within [5000, 300000] ms (ADR-164.1 Β§3.2)', '/');+ reservationExpiryMs = v;+ }+ return {+ name, displayName, roomId, agents, allowedMcpTools, bench, piiPolicy,+ budgetUsdMonthly, budgetUsdPerRun, preferLocalExecution, cronSchedule,+ auditReadView, reservationExpiryMs,+ };+}++// ---------- Phase-2 file-based budget ledger stub --------------------------+// TODO(adr-164.1): replace with atomic SQLite tracker in Phase 3. The+// reservation/commit/release semantics here are file-write best-effort and+// NOT crash-safe under concurrent writers. This is acceptable for Phase 2+// dry-run; production live-mode (Phase 3) must use the atomic tracker.++function loadLedger(path) {+ if (!existsSync(path)) {+ return { roomId: '', month: '', reserved: 0, spent: 0, reservations: [] };+ }+ return JSON.parse(readFileSync(path, 'utf-8'));+}++function saveLedger(path, ledger) {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify(ledger, null, 2));+}++function currentMonthKey() {+ const d = new Date();+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;+}++function resetIfNewMonth(ledger, roomId) {+ const month = currentMonthKey();+ if (ledger.month !== month || ledger.roomId !== roomId) {+ return { roomId, month, reserved: 0, spent: 0, reservations: [] };+ }+ return ledger;+}++function pruneExpired(ledger, nowMs) {+ const live = ledger.reservations.filter((r) => r.expiresAtMs > nowMs);+ const pruned = ledger.reservations.length - live.length;+ if (pruned > 0) {+ let releasedAmount = 0;+ for (const r of ledger.reservations) {+ if (r.expiresAtMs <= nowMs) releasedAmount += r.amountUsd;+ }+ ledger.reserved = Math.max(0, ledger.reserved - releasedAmount);+ ledger.reservations = live;+ }+ return ledger;+}++function reserveBudget(ledger, amount, expiryMs) {+ const now = Date.now();+ ledger = pruneExpired(ledger, now);+ const available = Math.max(0, (ledger.monthlyCap ?? Infinity) - ledger.reserved - ledger.spent);+ if (amount > available) {+ return { ok: false, reason: 'BUDGET_EXHAUSTED', available };+ }+ const id = `res-${randomBytes(6).toString('hex')}`;+ ledger.reservations.push({+ id,+ amountUsd: amount,+ createdAtMs: now,+ expiresAtMs: now + expiryMs,+ });+ ledger.reserved += amount;+ return { ok: true, reservationId: id };+}++function commitReservation(ledger, reservationId, actualUsd) {+ const r = ledger.reservations.find((x) => x.id === reservationId);+ if (!r) return { ok: false, reason: 'RESERVATION_NOT_FOUND' };+ ledger.reservations = ledger.reservations.filter((x) => x.id !== reservationId);+ ledger.reserved = Math.max(0, ledger.reserved - r.amountUsd);+ ledger.spent += actualUsd;+ return { ok: true };+}++// ---------- prompt construction (dry-run logged only) ----------------------++function constructPrompt(podTemplate, agent) {+ // The dry-run kickoff prompt the agent would receive. Keep it scoped to+ // the bench description so live-mode wiring (Phase 3) inherits the same+ // shape.+ const criteria = podTemplate.bench.successCriteria.map((s) => ` - ${s}`).join('\n');+ return [+ `You are the ${agent.role} (${agent.agentType}) for the ${podTemplate.displayName} pod.`,+ ``,+ `Pod bench: ${podTemplate.bench.name}`,+ `Bench description: ${podTemplate.bench.description}`,+ `Success criteria:`,+ criteria,+ ``,+ `Your role: ${agent.description}`,+ ``,+ `Kickoff task: Review the past ${podTemplate.bench.scheduleHours}h of #${podTemplate.roomId} activity.`,+ `Identify the 3 highest-priority items relevant to your role, then post a`,+ `summary envelope (msgType=task-result) to room "${podTemplate.roomId}" via`,+ `federation_bbs_publish. Adhere to PII policy: ${podTemplate.piiPolicy}.`,+ ].join('\n');+}++// ---------- envelope publish (Phase 1 backing store) -----------------------++function roomIdFromLabel(label) {+ const norm = String(label).replace(/^#/, '').toLowerCase();+ const h = createHash('sha256').update(`agentbbs:room:${norm}`).digest('hex').slice(0, 8);+ return `${norm}-${h}`;+}++function roomLogPath(basePath, derivedRoomId) {+ return join(basePath, '.agentbbs', `room-${derivedRoomId}.jsonl`);+}++function nextSeq(path) {+ if (!existsSync(path)) return 1;+ const lines = readFileSync(path, 'utf-8').split(/\r?\n/).filter(Boolean);+ if (lines.length === 0) return 1;+ try {+ const last = JSON.parse(lines[lines.length - 1]);+ return (last.seq ?? lines.length) + 1;+ } catch {+ return lines.length + 1;+ }+}++function publishEnvelope(basePath, roomLabel, msgType, payload) {+ const roomId = roomIdFromLabel(roomLabel);+ const path = roomLogPath(basePath, roomId);+ mkdirSync(dirname(path), { recursive: true });+ const envelope = {+ envelopeId: randomBytes(12).toString('hex'),+ roomId,+ seq: nextSeq(path),+ msgType,+ payload,+ timestamp: new Date().toISOString(),+ };+ appendFileSync(path, JSON.stringify(envelope) + '\n');+ return envelope;+}++// ---------- main tick ------------------------------------------------------++async function runTick(args) {+ if (args.live) {+ process.stderr.write(+ 'ERROR: --live mode is Phase 3 β requires Managed Agent integration and ' ++ 'claude-p wiring; do not flip to live in CI. Exiting.\n',+ );+ process.exit(3);+ }++ const templatePath = args.podTemplate+ ? (isAbsolute(args.podTemplate) ? args.podTemplate : resolve(process.cwd(), args.podTemplate))+ : join(PLUGIN_ROOT, 'templates', 'sales.json');++ if (!existsSync(templatePath)) {+ process.stderr.write(`ERROR: pod template not found: ${templatePath}\n`);+ process.exit(2);+ }++ let raw;+ try {+ raw = JSON.parse(readFileSync(templatePath, 'utf-8'));+ } catch (e) {+ process.stderr.write(`ERROR: failed to parse template JSON: ${e.message}\n`);+ process.exit(2);+ }++ let template;+ try {+ template = validatePodTemplate(raw);+ } catch (e) {+ process.stderr.write(`ERROR: ${e.message}\n`);+ process.exit(2);+ }++ // Resolve agent types against the registry.+ const unknown = template.agents+ .map((a) => a.agentType)+ .filter((t) => !KNOWN_AGENT_TYPES.has(t));+ if (unknown.length > 0) {+ process.stderr.write(+ `ERROR: unknown agent types in pod template: ${unknown.join(', ')}\n` ++ `Known types: ${[...KNOWN_AGENT_TYPES].sort().join(', ')}\n`,+ );+ process.exit(2);+ }++ // Budget reservation.+ const basePath = args.basePath+ ? (isAbsolute(args.basePath) ? args.basePath : resolve(process.cwd(), args.basePath))+ : resolve(process.cwd(), '.business-pods');+ const ledgerPath = join(basePath, 'budget', `${template.roomId}.json`);+ let ledger = resetIfNewMonth(loadLedger(ledgerPath), template.roomId);+ ledger.monthlyCap = template.budgetUsdMonthly === 0 ? Infinity : template.budgetUsdMonthly;+ const capForTick = args.budgetCapUsd !== null && args.budgetCapUsd >= 0+ ? Math.min(template.budgetUsdPerRun, args.budgetCapUsd)+ : template.budgetUsdPerRun;+ const expiryMs = template.reservationExpiryMs ?? 60_000;++ const reserve = reserveBudget(ledger, capForTick, expiryMs);+ if (!reserve.ok) {+ saveLedger(ledgerPath, ledger);+ const out = {+ podName: template.name,+ tickId: args.tickId ?? `tick-${randomBytes(4).toString('hex')}`,+ agentsRan: 0,+ totalUsd: 0,+ envelopeId: null,+ status: 'failed',+ reason: reserve.reason,+ };+ process.stdout.write(JSON.stringify(out) + '\n');+ process.exit(2);+ }+ saveLedger(ledgerPath, ledger);++ const tickId = args.tickId ?? `tick-${randomBytes(4).toString('hex')}`;++ // Build prompts (dry-run only logs them).+ const prompts = [];+ for (const agent of template.agents) {+ const prompt = constructPrompt(template, agent);+ prompts.push({ role: agent.role, agentType: agent.agentType, prompt });+ if (args.dryRun) {+ process.stderr.write(+ `\n[dry-run] ${agent.role} (${agent.agentType}):\n` ++ prompt.split('\n').map((l) => ` ${l}`).join('\n') + '\n',+ );+ }+ }++ // Commit. Dry-run actual = $0.+ const actualUsd = args.dryRun ? 0 : capForTick; // live path is gated above+ commitReservation(ledger, reserve.reservationId, actualUsd);+ saveLedger(ledgerPath, ledger);++ // Publish summary envelope to the room (federation_bbs_publish backing store).+ const envelope = publishEnvelope(basePath, template.roomId, 'pod-status', {+ podName: template.name,+ tickId,+ agentsRan: template.agents.length,+ totalUsd: actualUsd,+ dryRun: args.dryRun,+ promptShas: prompts.map((p) => ({+ role: p.role,+ sha: createHash('sha256').update(p.prompt).digest('hex').slice(0, 12),+ })),+ });++ const result = {+ podName: template.name,+ tickId,+ agentsRan: template.agents.length,+ totalUsd: actualUsd,+ envelopeId: envelope.envelopeId,+ status: 'success',+ dryRun: args.dryRun,+ };+ process.stdout.write(JSON.stringify(result) + '\n');+ return result;+}++// ---------- entrypoint -----------------------------------------------------++const args = parseArgs(process.argv.slice(2));++// Allow being imported by tests without auto-running the tick.+const isDirectInvocation = process.argv[1] && resolve(process.argv[1]) === resolve(__filename);+if (isDirectInvocation) {+ runTick(args).catch((err) => {+ process.stderr.write(`FATAL: ${err.stack || err.message}\n`);+ process.exit(2);+ });+}++export {+ parseArgs,+ validatePodTemplate,+ KNOWN_AGENT_TYPES,+ reserveBudget,+ commitReservation,+ pruneExpired,+ loadLedger,+ saveLedger,+ resetIfNewMonth,+ constructPrompt,+ publishEnvelope,+ roomIdFromLabel,+ runTick,+};diff --git a/plugins/ruflo-business-pods/scripts/pod-tick.test.mjs b/plugins/ruflo-business-pods/scripts/pod-tick.test.mjsnew file mode 100644index 0000000000..962640baec--- /dev/null+++ b/plugins/ruflo-business-pods/scripts/pod-tick.test.mjs@@ -0,0 +1,288 @@+/**+ * pod-tick.mjs tests β uses Node's built-in test runner (no extra deps).+ * Run with: node --test scripts/pod-tick.test.mjs+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ parseArgs,+ validatePodTemplate,+ KNOWN_AGENT_TYPES,+ reserveBudget,+ commitReservation,+ pruneExpired,+ resetIfNewMonth,+ constructPrompt,+ publishEnvelope,+} from './pod-tick.mjs';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const PLUGIN_ROOT = resolve(__dirname, '..');+const SALES_TEMPLATE = join(PLUGIN_ROOT, 'templates', 'sales.json');+const POD_TICK = join(__dirname, 'pod-tick.mjs');++function tmp(prefix = 'pod-tick-') {+ return mkdtempSync(join(tmpdir(), prefix));+}++test('parseArgs β defaults: dryRun=true, live=false', () => {+ const a = parseArgs([]);+ assert.equal(a.dryRun, true);+ assert.equal(a.live, false);+ assert.equal(a.podTemplate, null);+});++test('parseArgs β --live flips dryRun off', () => {+ const a = parseArgs(['--live']);+ assert.equal(a.live, true);+ assert.equal(a.dryRun, false);+});++test('validatePodTemplate β sales.json validates verbatim', () => {+ const sales = JSON.parse(readFileSync(SALES_TEMPLATE, 'utf-8'));+ const t = validatePodTemplate(sales);+ assert.equal(t.name, 'sales');+ assert.equal(t.agents.length, 4);+ assert.equal(t.reservationExpiryMs, 60_000);+});++test('validatePodTemplate β reservationExpiryMs out of bounds rejected', () => {+ const sales = JSON.parse(readFileSync(SALES_TEMPLATE, 'utf-8'));+ sales.reservationExpiryMs = 1;+ assert.throws(() => validatePodTemplate(sales), /reservationExpiryMs must be within/);+});++test('KNOWN_AGENT_TYPES β every sales-pod agentType is registered', () => {+ const sales = JSON.parse(readFileSync(SALES_TEMPLATE, 'utf-8'));+ for (const a of sales.agents) {+ assert.ok(+ KNOWN_AGENT_TYPES.has(a.agentType),+ `agentType "${a.agentType}" not in KNOWN_AGENT_TYPES`,+ );+ }+});++test('reserveBudget/commit β happy path returns reservationId then commits', () => {+ let ledger = resetIfNewMonth({}, 'sales');+ ledger.monthlyCap = 50;+ const r = reserveBudget(ledger, 0.5, 60_000);+ assert.equal(r.ok, true);+ assert.ok(r.reservationId.startsWith('res-'));+ assert.equal(ledger.reserved, 0.5);+ const c = commitReservation(ledger, r.reservationId, 0); // dry-run actual = $0+ assert.equal(c.ok, true);+ assert.equal(ledger.reserved, 0);+ assert.equal(ledger.spent, 0);+});++test('reserveBudget β refuses when budget exhausted', () => {+ let ledger = resetIfNewMonth({}, 'sales');+ ledger.monthlyCap = 1;+ ledger.spent = 0.95;+ const r = reserveBudget(ledger, 0.5, 60_000);+ assert.equal(r.ok, false);+ assert.equal(r.reason, 'BUDGET_EXHAUSTED');+});++test('pruneExpired β releases reservations past their expiry', () => {+ let ledger = resetIfNewMonth({}, 'sales');+ ledger.monthlyCap = 50;+ reserveBudget(ledger, 1.0, 60_000);+ // Manually expire the only reservation by rewinding its expiresAtMs.+ ledger.reservations[0].expiresAtMs = Date.now() - 1000;+ ledger = pruneExpired(ledger, Date.now());+ assert.equal(ledger.reservations.length, 0);+ assert.equal(ledger.reserved, 0);+});++test('constructPrompt β includes role, bench description, PII policy', () => {+ const sales = JSON.parse(readFileSync(SALES_TEMPLATE, 'utf-8'));+ const t = validatePodTemplate(sales);+ const p = constructPrompt(t, t.agents[0]);+ assert.match(p, /lead-gen-agent/);+ assert.match(p, /researcher/);+ assert.match(p, /sales-pipeline-bench/);+ assert.match(p, /PII policy: soc2/);+});++test('publishEnvelope β appends a JSONL row to the room log', () => {+ const work = tmp();+ try {+ const env = publishEnvelope(work, 'sales', 'pod-status', { foo: 'bar' });+ assert.ok(env.envelopeId);+ assert.equal(env.msgType, 'pod-status');+ // The room log path uses a derived roomId β find it by listing the dir.+ const fs = readFileSync(join(work, '.agentbbs', `room-${env.roomId}.jsonl`), 'utf-8');+ const parsed = JSON.parse(fs.trim().split('\n')[0]);+ assert.equal(parsed.msgType, 'pod-status');+ assert.deepEqual(parsed.payload, { foo: 'bar' });+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});++test('CLI: dry-run on sales.json exits 0 with expected stdout shape', () => {+ const work = tmp();+ try {+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', SALES_TEMPLATE,+ '--base-path', work,+ '--dry-run',+ '--tick-id', 'test-tick-1',+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 0, `non-zero exit: stderr=${res.stderr}`);+ const out = JSON.parse(res.stdout.trim().split('\n').pop());+ assert.equal(out.podName, 'sales');+ assert.equal(out.tickId, 'test-tick-1');+ assert.equal(out.agentsRan, 4);+ assert.equal(out.totalUsd, 0);+ assert.equal(out.status, 'success');+ assert.equal(out.dryRun, true);+ assert.ok(out.envelopeId);++ // Dry-run prompts are logged to stderr, one per agent+ assert.match(res.stderr, /lead-gen-agent/);+ assert.match(res.stderr, /pipeline-analyst/);+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});++test('CLI: --live exits 3 with refusal message (Phase 2 gate)', () => {+ const work = tmp();+ try {+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', SALES_TEMPLATE,+ '--base-path', work,+ '--live',+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 3);+ assert.match(res.stderr, /Phase 3/);+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});++test('CLI: unknown agent type produces actionable error', () => {+ const work = tmp();+ try {+ const badTemplate = JSON.parse(readFileSync(SALES_TEMPLATE, 'utf-8'));+ badTemplate.agents[0].agentType = 'not-a-real-agent-xyz';+ const badPath = join(work, 'bad-sales.json');+ writeFileSync(badPath, JSON.stringify(badTemplate));+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', badPath,+ '--base-path', work,+ '--dry-run',+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 2);+ assert.match(res.stderr, /unknown agent types.*not-a-real-agent-xyz/);+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});++test('CLI: budget reservation creates ledger and commits to $0 on dry-run', () => {+ const work = tmp();+ try {+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', SALES_TEMPLATE,+ '--base-path', work,+ '--dry-run',+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 0);+ const ledgerPath = join(work, 'budget', 'sales.json');+ assert.ok(existsSync(ledgerPath), 'budget ledger should exist');+ const ledger = JSON.parse(readFileSync(ledgerPath, 'utf-8'));+ assert.equal(ledger.roomId, 'sales');+ assert.equal(ledger.spent, 0); // dry-run actual = $0+ assert.equal(ledger.reserved, 0); // reservation committed and released+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});++// ADR-164 Phase 3 β every additional pod template (marketing/finance/ops/+// support/hr/exec) must validate and produce a successful dry-run tick. The+// existing sales template is covered by 'CLI: dry-run on sales.json' above;+// this loop covers the new six.+const PHASE3_PODS = ['marketing', 'finance', 'ops', 'support', 'hr', 'exec'];+for (const pod of PHASE3_PODS) {+ test(`Phase 3: ${pod}.json validates and dry-runs cleanly`, () => {+ const podPath = join(PLUGIN_ROOT, 'templates', `${pod}.json`);+ // schema validation first+ const raw = JSON.parse(readFileSync(podPath, 'utf-8'));+ const t = validatePodTemplate(raw);+ assert.equal(t.name, pod);+ // every agentType must be in the registry β pod-tick.mjs hard-checks this+ for (const a of t.agents) {+ assert.ok(+ KNOWN_AGENT_TYPES.has(a.agentType),+ `${pod}.json agentType "${a.agentType}" not in KNOWN_AGENT_TYPES`,+ );+ }+ // dry-run the tick end-to-end+ const work = tmp(`pod-tick-${pod}-`);+ try {+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', podPath,+ '--base-path', work,+ '--dry-run',+ '--tick-id', `phase3-${pod}-tick`,+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 0, `non-zero exit for ${pod}: stderr=${res.stderr}`);+ const out = JSON.parse(res.stdout.trim().split('\n').pop());+ assert.equal(out.podName, pod);+ assert.equal(out.tickId, `phase3-${pod}-tick`);+ assert.equal(out.agentsRan, t.agents.length);+ assert.equal(out.totalUsd, 0); // dry-run actual = $0+ assert.equal(out.status, 'success');+ assert.equal(out.dryRun, true);+ assert.ok(out.envelopeId);+ // envelope JSONL exists+ const ledgerPath = join(work, 'budget', `${t.roomId}.json`);+ assert.ok(existsSync(ledgerPath), `${pod} ledger should exist`);+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+ });+}++test('CLI: envelope is written to room JSONL backing store', async () => {+ const work = tmp();+ try {+ const res = spawnSync('node', [+ POD_TICK,+ '--pod-template', SALES_TEMPLATE,+ '--base-path', work,+ '--dry-run',+ ], { encoding: 'utf-8' });+ assert.equal(res.status, 0);+ const out = JSON.parse(res.stdout.trim().split('\n').pop());+ // Find the JSONL log produced by publishEnvelope+ const { readdirSync } = await import('node:fs');+ const agentbbsDir = join(work, '.agentbbs');+ const files = readdirSync(agentbbsDir);+ const log = files.find((f) => f.startsWith('room-') && f.endsWith('.jsonl'));+ assert.ok(log, `expected room jsonl file in ${agentbbsDir}`);+ const lines = readFileSync(join(agentbbsDir, log), 'utf-8').trim().split('\n');+ const last = JSON.parse(lines[lines.length - 1]);+ assert.equal(last.envelopeId, out.envelopeId);+ assert.equal(last.msgType, 'pod-status');+ assert.equal(last.payload.podName, 'sales');+ } finally {+ rmSync(work, { recursive: true, force: true });+ }+});diff --git a/plugins/ruflo-business-pods/scripts/smoke.sh b/plugins/ruflo-business-pods/scripts/smoke.shnew file mode 100755index 0000000000..d763983f47--- /dev/null+++ b/plugins/ruflo-business-pods/scripts/smoke.sh@@ -0,0 +1,248 @@+#!/usr/bin/env bash+# Structural + functional smoke test for ruflo-business-pods v0.1.0+# (ADR-164 Phase 2). Verifies:+#+# 1. plugin.json declares 0.1.0 with the expected adr-164/phase-2 keywords+# 2. templates/sales.json exists and validates against the pod-schema+# 3. scripts/pod-tick.mjs exists, parses, and is executable+# 4. Vitest suite passes (cli/__tests__/business-pod-tools.test.ts)+# 5. ADR-112 tool-description audit still passes (was 349 before, now β₯350)+# 6. Dry-run of sales pod tick exits 0 with expected stdout shape+# 7. Budget ledger created + reservation row inserted + committed+# 8. federation_bbs_publish envelope written to expected room JSONL file+#+# Exit 0 = all PASS; exit 1 = at least one FAIL.++set -u+ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"+PLUGIN="$ROOT/plugins/ruflo-business-pods"+CLI="$ROOT/v3/@claude-flow/cli"+PASS=0+FAIL=0+step() { printf "β %s ... " "$1"; }+ok() { printf "PASS\n"; PASS=$((PASS+1)); }+bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }++step "1. plugin.json declares 0.1.0 with adr-164 + phase-2 keywords"+v=$(grep -E '"version"' "$PLUGIN/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)+if [[ "$v" != "0.1.0" ]]; then+ bad "expected 0.1.0, got '$v'"+else+ miss=""+ for k in ruflo pods business sales adr-164 adr-164.1 phase-2 pod-template pod-tick budget-reservation dry-run-default agent-registry-resolution; do+ grep -q "\"$k\"" "$PLUGIN/.claude-plugin/plugin.json" || miss="$miss $k"+ done+ [[ -z "$miss" ]] && ok || bad "missing keywords:$miss"+fi++step "2. templates/sales.json exists and validates"+F="$PLUGIN/templates/sales.json"+if [[ ! -f "$F" ]]; then+ bad "missing sales.json"+else+ # Validate by piping into pod-tick.mjs's validator in a one-shot invocation+ if node -e "+ import('$PLUGIN/scripts/pod-tick.mjs').then(m => {+ const t = JSON.parse(require('node:fs').readFileSync('$F','utf-8'));+ const v = m.validatePodTemplate(t);+ if (v.name !== 'sales') process.exit(1);+ if (v.reservationExpiryMs !== 60000) process.exit(1);+ console.log('validated');+ }).catch(e => { console.error(e.message); process.exit(1); });+ " >/dev/null 2>&1; then+ ok+ else+ bad "sales.json failed pod-schema validation"+ fi+fi++step "3. scripts/pod-tick.mjs exists, parses, and is executable"+F="$PLUGIN/scripts/pod-tick.mjs"+miss=""+[[ -f "$F" ]] || miss="$miss missing"+[[ -x "$F" ]] || miss="$miss not-executable"+node --check "$F" 2>/dev/null || miss="$miss syntax-error"+[[ -z "$miss" ]] && ok || bad "$miss"++step "4. vitest suite passes (business-pod-tools.test.ts)"+# When CI runs --ignore-optional (no-metaharness / no-agentbbs runtime drills),+# vitest itself may not be installed. Skip with a clear marker rather than fail+# β the full vitest run is gated by the main test-suite jobs anyway.+if [[ ! -d "$CLI/node_modules/vitest" ]]; then+ printf "SKIP (no vitest β --ignore-optional install)\n"; PASS=$((PASS+1))+elif (cd "$CLI" && npx vitest run __tests__/business-pod-tools.test.ts >/dev/null 2>&1); then+ ok+else+ bad "vitest failed (run from $CLI for details)"+fi++step "5. ADR-112 tool-description audit passes (no regressions)"+if (cd "$ROOT" && node scripts/audit-tool-descriptions.mjs >/dev/null 2>&1); then+ ok+else+ bad "audit-tool-descriptions.mjs reported regression"+fi++step "6. dry-run of sales pod tick exits 0 with expected stdout shape"+TMPDIR_BASE="$(mktemp -d -t business-pods-smoke-XXXXXX)"+OUT="$(node "$PLUGIN/scripts/pod-tick.mjs" \+ --pod-template "$PLUGIN/templates/sales.json" \+ --base-path "$TMPDIR_BASE" \+ --dry-run \+ --tick-id "smoke-tick" 2>/dev/null)" || OUT=""+if [[ -z "$OUT" ]]; then+ bad "pod-tick.mjs produced no output"+else+ if node -e "+ const o = JSON.parse(\`$OUT\`.trim().split('\n').pop());+ if (o.podName !== 'sales') { console.error('podName mismatch'); process.exit(1); }+ if (o.tickId !== 'smoke-tick') { console.error('tickId mismatch'); process.exit(1); }+ if (o.agentsRan !== 4) { console.error('agentsRan mismatch'); process.exit(1); }+ if (o.totalUsd !== 0) { console.error('totalUsd should be 0 in dry-run'); process.exit(1); }+ if (o.status !== 'success') { console.error('status not success'); process.exit(1); }+ if (!o.envelopeId) { console.error('no envelopeId'); process.exit(1); }+ " 2>/dev/null; then+ ok+ else+ bad "stdout shape mismatch: $OUT"+ fi+fi++step "7. budget ledger created + reservation committed in dry-run"+LEDGER="$TMPDIR_BASE/budget/sales.json"+if [[ ! -f "$LEDGER" ]]; then+ bad "ledger not created at $LEDGER"+else+ if node -e "+ const l = JSON.parse(require('node:fs').readFileSync('$LEDGER','utf-8'));+ if (l.roomId !== 'sales') process.exit(1);+ if (l.spent !== 0) process.exit(1);+ if (l.reserved !== 0) process.exit(1);+ " 2>/dev/null; then+ ok+ else+ bad "ledger contents wrong"+ fi+fi++step "8. envelope written to room JSONL backing store"+shopt -s nullglob+LOGS=( "$TMPDIR_BASE/.agentbbs"/room-*.jsonl )+shopt -u nullglob+if [[ ${#LOGS[@]} -eq 0 ]]; then+ bad "no room-*.jsonl produced"+else+ LAST_LINE="$(tail -n 1 "${LOGS[0]}")"+ if node -e "+ const e = JSON.parse(\`$LAST_LINE\`);+ if (e.msgType !== 'pod-status') process.exit(1);+ if (!e.envelopeId) process.exit(1);+ if (e.payload.podName !== 'sales') process.exit(1);+ " 2>/dev/null; then+ ok+ else+ bad "envelope payload missing or malformed: $LAST_LINE"+ fi+fi++# --- ADR-164 Phase 3: 6 additional pod templates + domain-affinity router ---++PHASE3_PODS=(marketing finance ops support hr exec)++step "9. Phase 3: all 7 pod templates validate against pod-schema"+ALL_PODS=(sales "${PHASE3_PODS[@]}")+miss9=""+for p in "${ALL_PODS[@]}"; do+ F="$PLUGIN/templates/${p}.json"+ if [[ ! -f "$F" ]]; then+ miss9="$miss9 ${p}.json(missing)"+ continue+ fi+ if ! node -e "+ import('$PLUGIN/scripts/pod-tick.mjs').then(m => {+ const t = JSON.parse(require('node:fs').readFileSync('$F','utf-8'));+ const v = m.validatePodTemplate(t);+ if (v.name !== '$p') process.exit(1);+ }).catch(e => { console.error(e.message); process.exit(1); });+ " >/dev/null 2>&1; then+ miss9="$miss9 ${p}.json(invalid)"+ fi+done+[[ -z "$miss9" ]] && ok || bad "templates failed:$miss9"++step "10. Phase 3: dry-run each pod's tick exits 0 with status=success"+TMP3="$(mktemp -d -t business-pods-smoke3-XXXXXX)"+miss10=""+for p in "${PHASE3_PODS[@]}"; do+ WORK="$TMP3/$p"+ OUT="$(node "$PLUGIN/scripts/pod-tick.mjs" \+ --pod-template "$PLUGIN/templates/${p}.json" \+ --base-path "$WORK" \+ --dry-run \+ --tick-id "smoke-${p}-tick" 2>/dev/null)" || OUT=""+ if [[ -z "$OUT" ]]; then+ miss10="$miss10 ${p}(no-output)"+ continue+ fi+ if ! node -e "+ const o = JSON.parse(\`$OUT\`.trim().split('\n').pop());+ if (o.podName !== '$p') process.exit(1);+ if (o.status !== 'success') process.exit(1);+ if (o.totalUsd !== 0) process.exit(1);+ if (!o.envelopeId) process.exit(1);+ " 2>/dev/null; then+ miss10="$miss10 ${p}(stdout-mismatch)"+ fi+done+rm -rf "$TMP3"+[[ -z "$miss10" ]] && ok || bad "pods failed dry-run:$miss10"++step "11. business_pod_route_backend returns expected backend per Β§3.4"+# When CI runs --ignore-optional drills, the cli dist may not be present (the+# build step is gated on full install). Skip cleanly in that case.+if [[ ! -f "$CLI/dist/src/mcp-tools/business-pod-tools.js" ]]; then+ printf "SKIP (no dist β --ignore-optional install)\n"; PASS=$((PASS+1))+ printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"; [[ $FAIL -eq 0 ]] || exit 1+ exit 0+fi+# Smoke check three pods against the deterministic routing rule:+# preferLocalExecution=true β 'local-stdio'+# else AND budgetUsdMonthly >= 50 β 'cloud-managed'+# else β 'remote-peer'+# Per the validated templates:+# sales: preferLocal=false, budget=50 β cloud-managed+# marketing: preferLocal=false, budget=40 β remote-peer+# finance: preferLocal=true β local-stdio+if (cd "$CLI" && node --experimental-vm-modules -e "+ (async () => {+ const m = await import('./dist/src/mcp-tools/business-pod-tools.js');+ const find = (n) => m.businessPodTools.find((t) => t.name === n);+ const tool = find('business_pod_route_backend');+ if (!tool) { console.error('tool not found'); process.exit(1); }+ const fs = await import('node:fs');+ const p = await import('node:path');+ const tplDir = p.resolve('$PLUGIN/templates');+ const cases = [+ ['sales', 'cloud-managed'],+ ['marketing', 'remote-peer'],+ ['finance', 'local-stdio'],+ ];+ for (const [name, expected] of cases) {+ const podTemplate = JSON.parse(fs.readFileSync(p.join(tplDir, name + '.json'), 'utf-8'));+ const r = await tool.handler({ podTemplate });+ if (!r.success || r.backend !== expected) {+ console.error('case ' + name + ' expected ' + expected + ' got ' + JSON.stringify(r));+ process.exit(1);+ }+ }+ })().catch((e) => { console.error(e.message); process.exit(1); });+" >/dev/null 2>&1); then+ ok+else+ bad "business_pod_route_backend smoke failed (cli build may be stale: cd $CLI && npm run build)"+fi++rm -rf "$TMPDIR_BASE"++printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"+[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-business-pods/skills/pod-sales/SKILL.md b/plugins/ruflo-business-pods/skills/pod-sales/SKILL.mdnew file mode 100644index 0000000000..9645ed81cd--- /dev/null+++ b/plugins/ruflo-business-pods/skills/pod-sales/SKILL.md@@ -0,0 +1,55 @@+---+name: pod-sales+description: Run one tick of the sales business-pod (ADR-164 Β§4.1, Phase 2). Loads templates/sales.json, validates it against the pod-schema, resolves agents against ruflo's agent registry, reserves budget via the Phase-2 file-based stub ledger (atomic SQLite tracker is Phase 3 per ADR-164.1), constructs per-agent dry-run prompts, posts a summary envelope to room "sales" via the federation_bbs_publish JSONL backing store, and emits a structured {podName, tickId, agentsRan, totalUsd, envelopeId, status} line for /loop ingestion. Dry-run by default; --live is reserved for Phase 3.+argument-hint: "[--pod-template <path>] [--base-path <dir>] [--dry-run|--live] [--budget-cap-usd <amt>] [--tick-id <id>]"+allowed-tools: Bash+---++Surfaces `pod-tick.mjs` as a single-shot skill for the sales pod. Use when+Claude Code needs to demonstrate, smoke-test, or schedule one iteration of+the sales autopilot without spawning real LLM workers.++## Algorithm++Implementation: [`scripts/pod-tick.mjs`](../../scripts/pod-tick.mjs).++1. Parse args (`--pod-template`, `--base-path`, `--dry-run` / `--live`,+ `--budget-cap-usd`, `--tick-id`). `--live` is refused with exit code 3+ in Phase 2.+2. Load the pod template JSON (default: `templates/sales.json`).+3. Validate via `validatePodTemplate(json)` β schema in+ `v3/@claude-flow/cli/src/business-pods/pod-schema.ts` and inlined in+ `pod-tick.mjs` so the script runs without a built CLI. Throws with a+ JSON-pointer path on the first violation.+4. Resolve every `agent.agentType` against `KNOWN_AGENT_TYPES`. Unknown+ types abort with exit code 2 and an actionable error.+5. Reserve `min(budgetUsdPerRun, --budget-cap-usd)` USD against the+ file-based ledger at `<base-path>/budget/<roomId>.json`. Honors+ `reservationExpiryMs` (default 60_000 ms, bounded to [5000, 300000]+ per ADR-164.1 Β§3.2). `TODO(adr-164.1)`: swap the file ledger for the+ atomic SQLite tracker in Phase 3.+6. Build per-agent prompts (kickoff scoped to the bench description ++ pod's PII policy). In `--dry-run` they are logged to stderr and the+ model is never invoked.+7. Commit the reservation. Dry-run actual = $0; live actual = the+ reserved amount (Phase 3 wires real `claude -p` `--max-budget-usd`+ reporting).+8. Append a `pod-status` envelope to the Phase-1 backing store at+ `<base-path>/.agentbbs/room-<derivedRoomId>.jsonl` so subsequent+ `federation_bbs_watch` calls see the tick.+9. Emit a single JSON line on stdout:+ `{podName, tickId, agentsRan, totalUsd, envelopeId, status}`.++## Exit codes++- `0` β tick succeeded (`status === 'success'`)+- `2` β invalid template / unknown agent type / budget exhausted / arg error+- `3` β `--live` requested (refused in Phase 2)++## Phase 3 surfaces (not in this build)++- `--live` mode: dispatch each prompt through `claude -p` headless or a+ Managed Agent and capture the actual `--max-budget-usd` reported spend.+- Atomic SQLite budget tracker (ADR-164.1 Β§3.2).+- Multi-pod variants (`pod-marketing`, `pod-finance`, ...) β each gets its+ own skill once Phase 3 ships.diff --git a/plugins/ruflo-business-pods/templates/exec.json b/plugins/ruflo-business-pods/templates/exec.jsonnew file mode 100644index 0000000000..87984ae585--- /dev/null+++ b/plugins/ruflo-business-pods/templates/exec.json@@ -0,0 +1,54 @@+{+ "name": "exec",+ "displayName": "Executive",+ "roomId": "exec",+ "agents": [+ {+ "role": "cross-pod-synthesizer",+ "agentType": "task-orchestrator",+ "description": "Aggregates status envelopes from every sub-pod and produces an end-of-day executive summary",+ "preferLocal": true+ },+ {+ "role": "strategic-architect",+ "agentType": "system-architect",+ "description": "Detects cross-domain architectural risk signals and proposes mitigations",+ "preferLocal": true+ },+ {+ "role": "exec-researcher",+ "agentType": "researcher",+ "description": "Researches external market/risk context for the daily executive briefing",+ "preferLocal": true+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "exec-dashboard-bench",+ "description": "Measures executive-summary quality and cross-pod escalation timeliness. PII policy is GDPR β most restrictive across all pods because #exec synthesizes envelopes from every sub-pod including finance and HR. Trust note (ADR-164 Β§3.5.4): #exec requires the `share-context` capability which on Day 1 may need the founder-bootstrap CLI escape hatch (`ruflo federation trust elevate <bbs-node-id> --to TRUSTED --reason ... --audit`) because organic trust accrual (minInteractions: 500) has not yet completed. The bench treats this as a known transient; subsequent ticks operate under accrued TRUSTED level.",+ "successCriteria": [+ "Executive summary produced at least every 24h",+ "All P1 escalations from sub-pods acknowledged in #exec within 15 min",+ "No cross-domain risk signal older than 1h unreviewed",+ "share-context capability check: if not yet TRUSTED, bench logs a structured warning citing ADR-164 Β§3.5.4 founder-bootstrap escape hatch"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "gdpr",+ "budgetUsdMonthly": 60,+ "budgetUsdPerRun": 2.50,+ "preferLocalExecution": true,+ "cronSchedule": "0 17 * * 1-5",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result", "pod-status", "human-override-ack"],+ "retentionDays": 365+ },+ "reservationExpiryMs": 90000+}diff --git a/plugins/ruflo-business-pods/templates/finance.json b/plugins/ruflo-business-pods/templates/finance.jsonnew file mode 100644index 0000000000..7e369b2b05--- /dev/null+++ b/plugins/ruflo-business-pods/templates/finance.json@@ -0,0 +1,54 @@+{+ "name": "finance",+ "displayName": "Finance",+ "roomId": "finance",+ "agents": [+ {+ "role": "reconcile-agent",+ "agentType": "code-analyzer",+ "description": "Reconciles transactions against the local ledger and reports anomalies",+ "preferLocal": true+ },+ {+ "role": "query-optimizer",+ "agentType": "perf-analyzer",+ "description": "Optimizes finance reporting queries and tracks query-cost drift",+ "preferLocal": true+ },+ {+ "role": "ledger-keeper",+ "agentType": "database-specialist",+ "description": "Maintains schema integrity of the local finance ledger DB",+ "preferLocal": true+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "finance-accuracy-bench",+ "description": "Measures reconciliation accuracy and classification latency per cycle. GDPR-grade PII handling; HIPAA-compatible event taxonomy. All execution stays on local node; cloud routing is forbidden by policy.",+ "successCriteria": [+ "Reconciliation error rate < 0.1% of transactions",+ "All transactions classified within 24h",+ "No budget over-run alerts older than 4h unacknowledged",+ "Zero transactions leave the local node (cloud-routed agents fail the bench)"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "gdpr",+ "budgetUsdMonthly": 80,+ "budgetUsdPerRun": 1.50,+ "preferLocalExecution": true,+ "cronSchedule": "0 6,18 * * 1-5",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result", "pod-status"],+ "retentionDays": 365+ },+ "reservationExpiryMs": 180000+}diff --git a/plugins/ruflo-business-pods/templates/hr.json b/plugins/ruflo-business-pods/templates/hr.jsonnew file mode 100644index 0000000000..590c4fbd50--- /dev/null+++ b/plugins/ruflo-business-pods/templates/hr.json@@ -0,0 +1,54 @@+{+ "name": "hr",+ "displayName": "Human Resources",+ "roomId": "hr",+ "agents": [+ {+ "role": "policy-retriever",+ "agentType": "researcher",+ "description": "Surfaces policy answers for employee queries with citations to source documents",+ "preferLocal": true+ },+ {+ "role": "onboarding-template-gen",+ "agentType": "base-template-generator",+ "description": "Generates onboarding-checklist templates per role and tracks completion",+ "preferLocal": true+ },+ {+ "role": "policy-doc-keeper",+ "agentType": "api-docs",+ "description": "Maintains the canonical policy/handbook documents and surfaces drift between versions",+ "preferLocal": true+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "hr-compliance-bench",+ "description": "Measures policy-query coverage and onboarding-tracking accuracy. PII policy is GDPR β employee data is treated with finance-grade sensitivity per ADR-164 Appendix A.",+ "successCriteria": [+ "No onboarding step older than 48h without status update",+ "All leave/policy queries classified within 24h",+ "Policy query response latency < 5 min",+ "Zero employee-PII envelopes routed off the local node"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "gdpr",+ "budgetUsdMonthly": 30,+ "budgetUsdPerRun": 1.00,+ "preferLocalExecution": true,+ "cronSchedule": "0 10 * * 1-5",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result", "pod-status"],+ "retentionDays": 365+ },+ "reservationExpiryMs": 120000+}diff --git a/plugins/ruflo-business-pods/templates/marketing.json b/plugins/ruflo-business-pods/templates/marketing.jsonnew file mode 100644index 0000000000..97099489bd--- /dev/null+++ b/plugins/ruflo-business-pods/templates/marketing.json@@ -0,0 +1,53 @@+{+ "name": "marketing",+ "displayName": "Marketing",+ "roomId": "marketing",+ "agents": [+ {+ "role": "campaign-researcher",+ "agentType": "researcher",+ "description": "Surveys the past 24h of #marketing traffic and identifies underperforming campaigns",+ "preferLocal": false+ },+ {+ "role": "content-drafter",+ "agentType": "base-template-generator",+ "description": "Drafts blog posts, ad copy, and outreach templates for human review",+ "preferLocal": false+ },+ {+ "role": "martech-integrator",+ "agentType": "api-docs",+ "description": "Maintains marketing-tech integration docs (HubSpot, Mailchimp, Segment) and surfaces drift",+ "preferLocal": false+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "marketing-output-bench",+ "description": "Measures content production rate and campaign-metric accuracy over the past 24h",+ "successCriteria": [+ "At least 1 draft piece of content per 24h cycle",+ "Campaign metric delta reported within 12h of cycle start",+ "No SEO/research queue item older than 72h pending"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 40,+ "budgetUsdPerRun": 0.30,+ "preferLocalExecution": false,+ "cronSchedule": "0 9 * * 1-5",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ },+ "reservationExpiryMs": 60000+}diff --git a/plugins/ruflo-business-pods/templates/ops.json b/plugins/ruflo-business-pods/templates/ops.jsonnew file mode 100644index 0000000000..a0ac7daf41--- /dev/null+++ b/plugins/ruflo-business-pods/templates/ops.json@@ -0,0 +1,67 @@+{+ "name": "ops",+ "displayName": "Operations",+ "roomId": "ops",+ "agents": [+ {+ "role": "deploy-scout",+ "agentType": "cicd-engineer",+ "description": "Tracks deployment pipeline state and surfaces red builds within 30 min",+ "preferLocal": true+ },+ {+ "role": "infra-monitor",+ "agentType": "perf-analyzer",+ "description": "Monitors service health, latency p95, and uptime against SLO targets",+ "preferLocal": true+ },+ {+ "role": "incident-analyzer",+ "agentType": "code-analyzer",+ "description": "Triages incident traces, classifies root-cause patterns, and escalates P1 to #exec",+ "preferLocal": true+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join",+ "aidefence_analyze",+ "aidefence_scan",+ "aidefence_stats",+ "terminal_execute",+ "agent_execute",+ "http_fetch"+ ],+ "_allowedMcpTools_notes": [+ "TODO(phase-3-http-fetch): http_fetch MCP tool is referenced per ADR-164 Β§4.4 + Β§5.1.8 but does not exist yet β it is a Phase 3 prerequisite. The validator accepts the unknown tool name and the smoke contract surfaces a structured warning rather than a hard rejection. The ops bench scenario (synthetic 200/500 HTTP probe) cannot pass until http_fetch ships per ADR-164 Β§5.1.8 (URL allowlist, 30s timeout, 256 KB cap, no auth pass-through without explicit authAllowedUrls entry, audit logging on every call).",+ "aidefence_* β alerting and threat-detection signals from the AIDefence subsystem",+ "terminal_execute β shell execution for ops scripts (e.g. health-check probes, log scrapes)",+ "agent_execute β delegates to cloud Managed Agents with AWS/GCP/Azure SDK access for cloud-infra ops (Phase 4)",+ "Cloud-provider MCP servers (e.g. aws-mcp, gcp-mcp) are deployment-specific; NOT bundled. Must be registered per-installation via ruflo mcp config add."+ ],+ "bench": {+ "name": "ops-availability-bench",+ "description": "Measures service availability and incident response lag. Includes the synthetic-HTTP-endpoint test per ADR-164 Β§4.4: probe a synthetic endpoint returning 200 OK 90% of the time and 500 OK 10% of the time; the pod MUST detect the 500-rate and post an alert envelope to #ops within 60 seconds. The bench depends on http_fetch (TODO phase-3-http-fetch) and degrades to a stub-warning when http_fetch is unavailable.",+ "successCriteria": [+ "No unacknowledged P1 alert older than 15 min",+ "Deployment pipeline green or escalated within 30 min",+ "Infra health check at least every 4h",+ "HTTP endpoint monitor: detect 500-rate on synthetic 90/10 endpoint and post alert to #ops within 60s (requires http_fetch β see TODO phase-3-http-fetch)"+ ],+ "scheduleHours": 1+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 50,+ "budgetUsdPerRun": 0.05,+ "preferLocalExecution": true,+ "cronSchedule": "*/30 * * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ },+ "reservationExpiryMs": 60000+}diff --git a/plugins/ruflo-business-pods/templates/sales.json b/plugins/ruflo-business-pods/templates/sales.jsonnew file mode 100644index 0000000000..cf3d2c2777--- /dev/null+++ b/plugins/ruflo-business-pods/templates/sales.json@@ -0,0 +1,59 @@+{+ "name": "sales",+ "displayName": "Sales",+ "roomId": "sales",+ "agents": [+ {+ "role": "lead-gen-agent",+ "agentType": "researcher",+ "description": "Discovers and qualifies inbound leads from the past 24h of #sales activity",+ "preferLocal": false+ },+ {+ "role": "crm-sync-agent",+ "agentType": "backend-dev",+ "description": "Syncs pipeline state to CRM via webhook and reports drift",+ "preferLocal": false+ },+ {+ "role": "outreach-drafter",+ "agentType": "api-docs",+ "description": "Drafts outreach emails for human review",+ "preferLocal": false+ },+ {+ "role": "pipeline-analyst",+ "agentType": "perf-analyzer",+ "description": "Monitors pipeline velocity and flags stalls in #sales",+ "preferLocal": false+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "sales-pipeline-bench",+ "description": "Measures pipeline movement per cycle",+ "successCriteria": [+ "At least 1 new lead qualified per 24h cycle",+ "CRM sync error rate < 5%",+ "No outreach draft older than 48h pending in queue"+ ],+ "scheduleHours": 6+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 50,+ "budgetUsdPerRun": 0.50,+ "preferLocalExecution": false,+ "cronSchedule": "0 */6 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ },+ "reservationExpiryMs": 60000+}diff --git a/plugins/ruflo-business-pods/templates/support.json b/plugins/ruflo-business-pods/templates/support.jsonnew file mode 100644index 0000000000..874d149208--- /dev/null+++ b/plugins/ruflo-business-pods/templates/support.json@@ -0,0 +1,53 @@+{+ "name": "support",+ "displayName": "Customer Support",+ "roomId": "support",+ "agents": [+ {+ "role": "ticket-triager",+ "agentType": "researcher",+ "description": "Classifies and prioritises inbound tickets across severity and product surface",+ "preferLocal": false+ },+ {+ "role": "response-drafter",+ "agentType": "api-docs",+ "description": "Drafts first-response replies citing relevant docs for human review",+ "preferLocal": false+ },+ {+ "role": "trace-analyzer",+ "agentType": "code-analyzer",+ "description": "Inspects bug-report traces and routes likely defects to #ops",+ "preferLocal": false+ }+ ],+ "allowedMcpTools": [+ "memory_store",+ "memory_search",+ "federation_bbs_register",+ "federation_bbs_publish",+ "federation_bbs_watch",+ "federation_bbs_human_join"+ ],+ "bench": {+ "name": "support-response-bench",+ "description": "Measures first-response latency and classification accuracy over the past 24h",+ "successCriteria": [+ "First-response draft within 2h of ticket open",+ "Classification accuracy > 90% (spot-checked by human weekly)",+ "Escalations routed within 30 min of P1 classification"+ ],+ "scheduleHours": 1+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 40,+ "budgetUsdPerRun": 0.02,+ "preferLocalExecution": false,+ "cronSchedule": "*/15 * * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 180+ },+ "reservationExpiryMs": 60000+}diff --git a/scripts/smoke-agentbbs.sh b/scripts/smoke-agentbbs.shnew file mode 100755index 0000000000..7ea1316ebc--- /dev/null+++ b/scripts/smoke-agentbbs.sh@@ -0,0 +1,97 @@+#!/usr/bin/env bash+# Structural + functional smoke test for agentbbs MCP tools (ADR-164 Phase 1).+#+# Verifies:+# 1. Source files exist where mcp-client expects them+# 2. dist artifact exists (build ran)+# 3. Optional dependency is declared in v3/@claude-flow/cli/package.json+# 4. Tool registration lines are present in mcp-tools/index.ts+# 5. mcp-client.ts imports + registers agentbbsTools+# 6. all 4 tool names present in the source file+# 7. Vitest suite passes+# 8. End-to-end register β publish β watch cycle via dist handlers+# (accepts DEGRADED:agentbbs-not-found as a pass β graceful degradation)+#+# Exit 0 = all PASS; exit 1 = at least one FAIL.++set -u+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+CLI="$ROOT/v3/@claude-flow/cli"+PASS=0+FAIL=0+step() { printf "β %s ... " "$1"; }+ok() { printf "PASS\n"; PASS=$((PASS+1)); }+bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }++step "1. agentbbs-tools.ts exists in cli/src/mcp-tools/"+[[ -f "$CLI/src/mcp-tools/agentbbs-tools.ts" ]] && ok || bad "missing source file"++step "2. dist/.../agentbbs-tools.js exists (build ran)"+[[ -f "$CLI/dist/src/mcp-tools/agentbbs-tools.js" ]] && ok || bad "missing dist file (run 'npm run build' in $CLI)"++step "3. optionalDependencies declares agentbbs"+if grep -q '"agentbbs"' "$CLI/package.json"; then ok ; else bad "agentbbs not in package.json"; fi++step "4. mcp-tools/index.ts re-exports agentbbsTools"+if grep -q "agentbbsTools" "$CLI/src/mcp-tools/index.ts"; then ok ; else bad "not re-exported"; fi++step "5. mcp-client.ts imports and registers agentbbsTools"+if grep -q "import { agentbbsTools }" "$CLI/src/mcp-client.ts" && \+ grep -q "\.\.\.agentbbsTools" "$CLI/src/mcp-client.ts" ; then+ ok+else+ bad "not registered in mcp-client.ts"+fi++step "6. all 4 tool names present in tool file"+miss=""+for t in federation_bbs_register federation_bbs_publish federation_bbs_watch federation_bbs_human_join; do+ grep -q "name: '$t'" "$CLI/src/mcp-tools/agentbbs-tools.ts" || miss="$miss $t"+done+[[ -z "$miss" ]] && ok || bad "missing tool names:$miss"++step "7. vitest suite passes"+if (cd "$CLI" && npx vitest run __tests__/agentbbs-tools.test.ts >/dev/null 2>&1); then+ ok+else+ bad "vitest failed (run from $CLI for details)"+fi++step "8. end-to-end register β publish β watch cycle via handlers"+DRIVER="$(mktemp -t agentbbs-smoke.XXXXXX).mjs"+TMPDIR_BASE="$(mktemp -d -t agentbbs-smoke-XXXXXX)"+cat > "$DRIVER" <<EOF+import { agentbbsTools } from '$CLI/dist/src/mcp-tools/agentbbs-tools.js';++const find = n => { const t = agentbbsTools.find(x => x.name === n); if (!t) throw new Error('not found: ' + n); return t; };++const r1 = await find('federation_bbs_register').handler({ basePath: '$TMPDIR_BASE', roomLabel: '#sales' });+if (!r1.success) throw new Error('register failed: ' + JSON.stringify(r1));+if (r1.degraded) { console.log('DEGRADED:agentbbs-not-found'); process.exit(0); }++const roomId = r1.roomId;+const r2 = await find('federation_bbs_publish').handler({+ basePath: '$TMPDIR_BASE', roomId, msgType: 'task-result',+ payload: { agent: 'smoke', leads: 1 },+});+if (!r2.success || !r2.envelopeId) throw new Error('publish failed: ' + JSON.stringify(r2));++const r3 = await find('federation_bbs_watch').handler({ basePath: '$TMPDIR_BASE', roomId });+if (!r3.success || r3.count < 1) throw new Error('watch failed: ' + JSON.stringify(r3));++const r4 = await find('federation_bbs_human_join').handler({ roomId, ttlSeconds: 120 });+if (!r4.success || !r4.handshakeToken) throw new Error('human_join failed: ' + JSON.stringify(r4));++console.log('OK');+EOF+OUT=$(node "$DRIVER" 2>&1) || true+case "$OUT" in+ "OK") ok ;;+ "DEGRADED:agentbbs-not-found") ok ;; # graceful-degraded path is also a pass+ *) bad "$OUT" ;;+esac+rm -f "$DRIVER"+rm -rf "$TMPDIR_BASE"++printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"+[[ $FAIL -eq 0 ]] || exit 1diff --git a/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts b/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.tsnew file mode 100644index 0000000000..5386bda5d9--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/agentbbs-tools.test.ts@@ -0,0 +1,183 @@+/**+ * Tests for agentbbs MCP tools (ADR-164 Phase 1).+ *+ * Two surfaces under test:+ * 1. STRUCTURAL β exposure, schema, validation. Runs regardless of agentbbs presence.+ * 2. HAPPY PATH β gated on agentbbs being importable via it.skipIf(!havePkg).+ *+ * The degraded path is exercised structurally: when agentbbs is missing,+ * every handler returns `{degraded: true, reason: 'agentbbs-not-found'}`+ * matching the metaharness / agenticow / testgen contract.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { agentbbsTools } from '../src/mcp-tools/agentbbs-tools.js';++function findTool(name: string) {+ const t = agentbbsTools.find(t => t.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++// Detect agentbbs availability at module scope so it.skipIf evaluates correctly.+let havePkg = false;+try { await import('agentbbs'); havePkg = true; } catch { havePkg = false; }++describe('agentbbs MCP tools β structural contract', () => {+ it('exposes exactly 4 tools (register / publish / watch / human_join)', () => {+ const names = agentbbsTools.map(t => t.name).sort();+ expect(names).toEqual([+ 'federation_bbs_human_join',+ 'federation_bbs_publish',+ 'federation_bbs_register',+ 'federation_bbs_watch',+ ]);+ });++ it('every tool has an object inputSchema with handler + β₯80-char description', () => {+ for (const t of agentbbsTools) {+ expect(t.inputSchema.type).toBe('object');+ expect(t.inputSchema.properties).toBeDefined();+ expect(typeof t.handler).toBe('function');+ expect(t.description.length).toBeGreaterThanOrEqual(80);+ // ADR-112 β descriptions must carry "Use when ... is wrong because ..." guidance.+ expect(t.description).toMatch(/Use when/i);+ expect(t.description).toMatch(/wrong because/i);+ }+ });++ it('register rejects path traversal in basePath', async () => {+ const register = findTool('federation_bbs_register');+ await expect(register.handler({+ basePath: '../../../../etc/passwd',+ roomLabel: '#sales',+ })).rejects.toThrow(/disallowed characters/);+ });++ it('register rejects an illegal roomLabel', async () => {+ const register = findTool('federation_bbs_register');+ await expect(register.handler({+ roomLabel: 'evil; rm -rf /',+ })).rejects.toThrow(/may only contain/);+ });++ it('register accepts conventional #-prefixed room labels', async () => {+ // Even when agentbbs is missing we should validate inputs first OR degrade+ // β but the contract is: validation errors must surface as throws.+ // With agentbbs missing we get a degraded result instead of validation.+ // So this test only meaningfully covers regex acceptance shape.+ expect(/^[A-Za-z0-9_.\-:/@#]+$/.test('#sales')).toBe(true);+ expect(/^[A-Za-z0-9_.\-:/@#]+$/.test('finance')).toBe(true);+ expect(/^[A-Za-z0-9_.\-:/@#]+$/.test('hr/onboarding')).toBe(true);+ });++ it('publish rejects malformed msgType (validation runs before optional-dep check)', async () => {+ const publish = findTool('federation_bbs_publish');+ await expect(publish.handler({+ roomId: 'sales-12345678',+ msgType: 'bad type with spaces',+ payload: {},+ })).rejects.toThrow(/msgType must be alnum/);+ });++ it('publish rejects non-object payload', async () => {+ const publish = findTool('federation_bbs_publish');+ await expect(publish.handler({+ roomId: 'sales-12345678',+ msgType: 'task-result',+ payload: 'not an object',+ })).rejects.toThrow(/payload must be a JSON object/);+ });++ it('all 4 tools return {degraded:true, reason:"agentbbs-not-found"} when agentbbs is missing', async () => {+ if (havePkg) return; // happy-path case is covered elsewhere+ for (const t of agentbbsTools) {+ const minimalInput: Record<string, unknown> =+ t.name === 'federation_bbs_register' ? { roomLabel: '#sales' } :+ t.name === 'federation_bbs_publish' ? { roomId: 'sales-12345678', msgType: 'task-result', payload: {} } :+ t.name === 'federation_bbs_watch' ? { roomId: 'sales-12345678' } :+ t.name === 'federation_bbs_human_join' ? { roomId: 'sales-12345678' } :+ {};+ const r: any = await t.handler(minimalInput);+ expect(r.success).toBe(true);+ expect(r.degraded).toBe(true);+ expect(r.reason).toBe('agentbbs-not-found');+ }+ });+});++describe('agentbbs MCP tools β happy path (real package)', () => {+ let workdir: string;+ let roomId: string;++ beforeAll(() => {+ workdir = mkdtempSync(join(tmpdir(), 'agentbbs-tools-'));+ });++ afterAll(() => {+ try { rmSync(workdir, { recursive: true, force: true }); } catch { /* ignore */ }+ });++ it.skipIf(!havePkg)('register: creates a room and persists registry', async () => {+ const register = findTool('federation_bbs_register');+ const r: any = await register.handler({ basePath: workdir, roomLabel: '#sales' });+ expect(r.success).toBe(true);+ expect(r.degraded).toBeUndefined();+ expect(r.trustLevel).toBe('attested');+ expect(r.roomId).toMatch(/^sales-[0-9a-f]{8}$/);+ expect(r.nodeId).toMatch(/^[0-9a-f]{16}$/);+ roomId = r.roomId;+ const reg = JSON.parse(readFileSync(join(workdir, 'rooms.json'), 'utf-8'));+ expect(reg[roomId]).toBeDefined();+ expect(reg[roomId].roomLabel).toBe('#sales');+ });++ it.skipIf(!havePkg)('publish: writes a ReplicateMessage envelope to the room log', async () => {+ const publish = findTool('federation_bbs_publish');+ const r: any = await publish.handler({+ basePath: workdir,+ roomId,+ msgType: 'task-result',+ payload: { agent: 'lead-gen', leadsQualified: 3 },+ });+ expect(r.success).toBe(true);+ expect(r.degraded).toBeUndefined();+ expect(r.envelopeId).toBeTruthy();+ expect(r.recipientHopCount).toBe(0);+ expect(existsSync(join(workdir, `room-${roomId}.jsonl`))).toBe(true);+ });++ it.skipIf(!havePkg)('watch: returns envelopes from the room log with monotonic seq', async () => {+ const watch = findTool('federation_bbs_watch');+ const r: any = await watch.handler({ basePath: workdir, roomId, limit: 50 });+ expect(r.success).toBe(true);+ expect(r.envelopes.length).toBeGreaterThan(0);+ // Seq must be strictly monotonic+ let lastSeq = 0;+ for (const e of r.envelopes) {+ expect(e.seq).toBeGreaterThan(lastSeq);+ lastSeq = e.seq;+ }+ });++ it.skipIf(!havePkg)('human_join: mints a single-use Ed25519-signed token that expires in the future', async () => {+ const join = findTool('federation_bbs_human_join');+ const before = Date.now();+ const r: any = await join.handler({ roomId: 'sales-12345678', ttlSeconds: 120 });+ const after = Date.now();+ expect(r.success).toBe(true);+ expect(r.degraded).toBeUndefined();+ expect(r.handshakeToken).toBeTruthy();+ expect(r.handshakeToken.length).toBeGreaterThan(50);+ expect(r.webUrl).toMatch(/^https:\/\/agentbbs\.local\//);+ expect(r.sshCommand).toMatch(/^ssh /);+ const expiresAt = new Date(r.expiresAt).getTime();+ expect(expiresAt).toBeGreaterThan(before);+ // Expiry must be β€ ttlSeconds from now (within a wide margin to absorb scheduling jitter).+ expect(expiresAt - after).toBeLessThanOrEqual(120 * 1000 + 1000);+ expect(expiresAt - before).toBeGreaterThanOrEqual(120 * 1000 - 1000);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/bbs-budget-tracker.test.ts b/v3/@claude-flow/cli/__tests__/bbs-budget-tracker.test.tsnew file mode 100644index 0000000000..4a7808d5e7--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/bbs-budget-tracker.test.ts@@ -0,0 +1,311 @@+/**+ * Tests for AtomicBbsRoomBudgetTracker β ADR-164.1.+ *+ * Implements Tests 1, 2, 3, 6 from Β§9. Test 4 (mid-transaction crash) is+ * covered by a synchronous throw-during-reserve scenario; Test 5 (clock-skew+ * backward) is intentionally skipped as it requires system-clock control+ * beyond what the test harness exposes β see ADR-164.1 Β§9 Test 5 for the+ * design intent.+ *+ * Uses better-sqlite3 in-memory mode for speed.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { createRequire } from 'node:module';++import {+ AtomicBbsRoomBudgetTracker,+ clampReservationExpiry,+ RESERVATION_EXPIRY_FLOOR_MS,+ RESERVATION_EXPIRY_CEILING_MS,+ createAtomicTrackerIfEnabled,+ type BudgetAuditSink,+ type SqliteDatabase,+} from '../src/business-pods/bbs-budget-tracker.js';++// Resolve better-sqlite3 via CJS require so tests work even when ESM+// resolution from this nested test depth has trouble locating the+// hoisted v3-level dependency.+const cjsRequire = createRequire(import.meta.url);+type DatabaseCtor = new (filename: string) => SqliteDatabase;++function openDb(): SqliteDatabase {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const Database = cjsRequire('better-sqlite3') as DatabaseCtor;+ return new Database(':memory:');+}++let db: SqliteDatabase;+let auditEvents: Array<{ type: string; payload: Record<string, unknown> }>;+let audit: BudgetAuditSink;++beforeEach(() => {+ db = openDb();+ auditEvents = [];+ audit = {+ emit: (type, payload) => { auditEvents.push({ type, payload }); },+ };+});++afterEach(() => {+ try { db.close(); } catch { /* noop */ }+});++// ---------- clamp ---------------------------------------------------------++describe('clampReservationExpiry', () => {+ it('clamps small values up to the 5s floor', () => {+ expect(clampReservationExpiry(1000)).toBe(RESERVATION_EXPIRY_FLOOR_MS);+ });+ it('clamps large values down to the 5min ceiling', () => {+ expect(clampReservationExpiry(60 * 60 * 1000)).toBe(RESERVATION_EXPIRY_CEILING_MS);+ });+ it('passes through values within bounds', () => {+ expect(clampReservationExpiry(30_000)).toBe(30_000);+ });+});++// ---------- Test 1: serial reserves under a cap (drop-in for Β§9 Test 1) --++describe('Test 1 β serial reserves under a $1.00 cap', () => {+ it('exactly 20 of 100 callers reserving $0.05 succeed; 80 BUDGET_EXCEEDED; total = $1.00', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit, defaultExpiryMs: 60_000 });+ tracker.registerRoom('sales-test', 1.0);++ let ok = 0;+ let exceeded = 0;+ for (let i = 0; i < 100; i++) {+ const r = tracker.reserve('sales-test', `caller-${i}`, 0.05);+ if (r.ok) ok++;+ else if (r.error === 'BUDGET_EXCEEDED') exceeded++;+ }+ expect(ok).toBe(20);+ expect(exceeded).toBe(80);++ const rows = tracker.listReservations('sales-test').filter((r) => r.state === 'reserved');+ expect(rows.length).toBe(20);+ const sum = rows.reduce((acc, r) => acc + Number(r.estimated_usd), 0);+ expect(sum).toBeCloseTo(1.0, 6);+ });+});++// ---------- Test 2: block β release β allow 10 of 50 ---------------------++describe('Test 2 β release frees budget for subsequent callers', () => {+ it('first $0.50 reserve blocks 50 callers; release frees 10 of next 50', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit, defaultExpiryMs: 60_000 });+ tracker.registerRoom('sales-test2', 1.0);++ const initial = tracker.reserve('sales-test2', 'initial', 0.5);+ expect(initial.ok).toBe(true);+ if (!initial.ok) throw new Error('unreachable');+ const reservationIdA = initial.reservationId;++ // Step B: 50 reserves of $0.05 β all should fail (0.50 + 0.05 = 0.55 OK+ // for the first call, but cumulative reserved + 0.05 must exceed cap to fail).+ // 0.50 reserved + 50 Γ 0.05 = 0.50 + 2.50 = 3.00 way over. Each individual+ // call sees 0.50 + NΓ0.05 already reserved, so callers 1-10 succeed and+ // 11-50 fail (0.50 reserved + 0.50 in step B = 1.00 cap reached after 10).+ let phaseBOk = 0;+ let phaseBFail = 0;+ for (let i = 0; i < 50; i++) {+ const r = tracker.reserve('sales-test2', `phaseB-${i}`, 0.05);+ if (r.ok) phaseBOk++;+ else phaseBFail++;+ }+ expect(phaseBOk).toBe(10);+ expect(phaseBFail).toBe(40);++ // Step C: release the initial $0.50.+ const rel = tracker.release(reservationIdA);+ expect(rel.ok).toBe(true);++ // Step D: another 50 β should see exactly 10 succeed (0.50 freed β 10 Γ 0.05).+ let phaseDOk = 0;+ let phaseDFail = 0;+ for (let i = 0; i < 50; i++) {+ const r = tracker.reserve('sales-test2', `phaseD-${i}`, 0.05);+ if (r.ok) phaseDOk++;+ else phaseDFail++;+ }+ expect(phaseDOk).toBe(10);+ expect(phaseDFail).toBe(40);+ });+});++// ---------- Test 3: expiry frees budget after sweepExpired() --------------++describe('Test 3 β expiry frees budget for next caller', () => {+ it('after sweepExpired() an expired reservation no longer blocks new reserves', () => {+ let mockNow = 1_000_000;+ const tracker = new AtomicBbsRoomBudgetTracker({+ db, audit,+ defaultExpiryMs: 5_000, // floor β clamp goes to 5000ms+ clock: () => mockNow,+ });+ tracker.registerRoom('hr-test', 0.10);++ const a = tracker.reserve('hr-test', 'agent-1', 0.10);+ expect(a.ok).toBe(true);++ // Step B: should be BUDGET_EXCEEDED (live reservation occupies full cap).+ const b = tracker.reserve('hr-test', 'agent-2', 0.05);+ expect(b.ok).toBe(false);+ if (b.ok) throw new Error('unreachable');+ expect(b.error).toBe('BUDGET_EXCEEDED');++ // Step C: advance clock past expiry, then sweep.+ mockNow += 6_000;+ const swept = tracker.sweepExpired();+ expect(swept).toBe(1);++ // Step D: next reserve succeeds (the expired row is excluded from totals).+ const d = tracker.reserve('hr-test', 'agent-2', 0.05);+ expect(d.ok).toBe(true);+ });++ it('expired reservation is excluded from gate check BEFORE sweep (window query check)', () => {+ let mockNow = 2_000_000;+ const tracker = new AtomicBbsRoomBudgetTracker({+ db, audit,+ defaultExpiryMs: 5_000,+ clock: () => mockNow,+ });+ tracker.registerRoom('window-test', 0.10);++ const a = tracker.reserve('window-test', 'agent-1', 0.10);+ expect(a.ok).toBe(true);++ // Advance past expiry but DO NOT call sweepExpired().+ mockNow += 6_000;++ // Per ADR-164.1 Β§7.2 "phantom debt intentional bias" β even unswepped+ // expired rows must be excluded from the reserve() gate check.+ const b = tracker.reserve('window-test', 'agent-2', 0.05);+ expect(b.ok).toBe(true);+ });+});++// ---------- Test 6: COMMIT_AFTER_EXPIRY closes Expired Commit Leak --------++describe('Test 6 β COMMIT_AFTER_EXPIRY captures the real spend (Β§8.1 fix)', () => {+ it('late commit records spend, marks committed_post_expiry, emits audit', () => {+ let mockNow = 3_000_000;+ const tracker = new AtomicBbsRoomBudgetTracker({+ db, audit,+ defaultExpiryMs: 5_000,+ clock: () => mockNow,+ });+ tracker.registerRoom('commit-late', 1.0);++ const r = tracker.reserve('commit-late', 'agent-1', 0.30);+ expect(r.ok).toBe(true);+ if (!r.ok) throw new Error('unreachable');+ const reservationId = r.reservationId;++ // Advance past expiry β reservation is now expired but not committed.+ mockNow += 6_000;++ // Late commit: should succeed with warned: 'COMMIT_AFTER_EXPIRY'.+ const c = tracker.commit(reservationId, 0.30);+ expect(c.ok).toBe(true);+ if (!c.ok) throw new Error('unreachable');+ expect('warned' in c && c.warned).toBe('COMMIT_AFTER_EXPIRY');+ if ('warned' in c) {+ expect(c.finalRemaining).toBeCloseTo(0.70, 6);+ }++ // Audit emitted the high-priority envelope.+ const evt = auditEvents.find((e) => e.type === 'reservation.committed_post_expiry');+ expect(evt).toBeDefined();+ expect(evt!.payload.reservationId).toBe(reservationId);++ // The post-expiry commit counts against the budget.+ const next = tracker.reserve('commit-late', 'agent-2', 0.70);+ expect(next.ok).toBe(true);++ // Now fully spent β even a tiny additional reserve is BUDGET_EXCEEDED.+ const tiny = tracker.reserve('commit-late', 'agent-3', 0.01);+ expect(tiny.ok).toBe(false);+ if (tiny.ok) throw new Error('unreachable');+ expect(tiny.error).toBe('BUDGET_EXCEEDED');+ });++ it('happy-path commit (within window) returns committed:true without warning', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit, defaultExpiryMs: 60_000 });+ tracker.registerRoom('commit-clean', 1.0);+ const r = tracker.reserve('commit-clean', 'agent-1', 0.20);+ expect(r.ok).toBe(true);+ if (!r.ok) throw new Error('unreachable');++ const c = tracker.commit(r.reservationId, 0.18);+ expect(c.ok).toBe(true);+ if (!c.ok) throw new Error('unreachable');+ expect('committed' in c && c.committed).toBe(true);+ if ('committed' in c) {+ expect(c.finalRemaining).toBeCloseTo(0.82, 6);+ }+ });++ it('double-commit returns ALREADY_FINALIZED', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit, defaultExpiryMs: 60_000 });+ tracker.registerRoom('double-commit', 1.0);+ const r = tracker.reserve('double-commit', 'agent-1', 0.10);+ if (!r.ok) throw new Error('expected ok');+ expect(tracker.commit(r.reservationId, 0.10).ok).toBe(true);+ const second = tracker.commit(r.reservationId, 0.05);+ expect(second.ok).toBe(false);+ if (second.ok) throw new Error('unreachable');+ expect(second.error).toBe('ALREADY_FINALIZED');+ });++ it('commit on unknown id returns NOT_FOUND', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit });+ const c = tracker.commit('does-not-exist', 0.10);+ expect(c.ok).toBe(false);+ if (c.ok) throw new Error('unreachable');+ expect(c.error).toBe('NOT_FOUND');+ });++ it('release on committed reservation returns ALREADY_FINALIZED', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit, defaultExpiryMs: 60_000 });+ tracker.registerRoom('release-blocked', 1.0);+ const r = tracker.reserve('release-blocked', 'agent-1', 0.10);+ if (!r.ok) throw new Error('expected ok');+ expect(tracker.commit(r.reservationId, 0.10).ok).toBe(true);+ const rel = tracker.release(r.reservationId);+ expect(rel.ok).toBe(false);+ if (rel.ok) throw new Error('unreachable');+ expect(rel.error).toBe('ALREADY_FINALIZED');+ });++ it('reserve on unknown room returns ROOM_NOT_FOUND', () => {+ const tracker = new AtomicBbsRoomBudgetTracker({ db, audit });+ const r = tracker.reserve('no-such-room', 'agent-1', 0.10);+ expect(r.ok).toBe(false);+ if (r.ok) throw new Error('unreachable');+ expect(r.error).toBe('ROOM_NOT_FOUND');+ });+});++// ---------- feature-flag factory ------------------------------------------++describe('createAtomicTrackerIfEnabled feature flag', () => {+ it('returns null when CLAUDE_FLOW_BBS_ATOMIC_BUDGET is unset', () => {+ const prev = process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET;+ delete process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET;+ expect(createAtomicTrackerIfEnabled({ db })).toBeNull();+ if (prev !== undefined) process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET = prev;+ });++ it('returns the atomic tracker when flag is set to "1"', () => {+ const prev = process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET;+ process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET = '1';+ try {+ const tr = createAtomicTrackerIfEnabled({ db });+ expect(tr).toBeInstanceOf(AtomicBbsRoomBudgetTracker);+ } finally {+ if (prev === undefined) delete process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET;+ else process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET = prev;+ }+ });+});diff --git a/v3/@claude-flow/cli/__tests__/business-pod-tools.test.ts b/v3/@claude-flow/cli/__tests__/business-pod-tools.test.tsnew file mode 100644index 0000000000..39f63e1d99--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/business-pod-tools.test.ts@@ -0,0 +1,352 @@+/**+ * Tests for business_pod_validate + business_pod_route_backend MCP tools+ * + pod-schema validator + domain-affinity policy+ * (ADR-164 Phase 2 + Phase 3, ADR-164.1 reservationExpiryMs bound).+ */+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { businessPodTools } from '../src/mcp-tools/business-pod-tools.js';+import {+ validatePodTemplate,+ PodTemplateValidationError,+ type PodTemplate,+} from '../src/business-pods/pod-schema.js';+import {+ selectAgentBackend,+ CLOUD_BUDGET_THRESHOLD_USD,+} from '../src/business-pods/domain-affinity-policy.js';++function findTool(name: string) {+ const t = businessPodTools.find((x) => x.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++const TEMPLATES_DIR = resolve(+ __dirname,+ '../../../../plugins/ruflo-business-pods/templates',+);+const POD_NAMES = ['sales', 'marketing', 'finance', 'ops', 'support', 'hr', 'exec'] as const;+const loadJson = (name: string): unknown =>+ JSON.parse(readFileSync(resolve(TEMPLATES_DIR, `${name}.json`), 'utf-8'));++const salesJson = loadJson('sales');++function clone<T>(v: T): T {+ return JSON.parse(JSON.stringify(v));+}++describe('pod-schema validator β structural', () => {+ it('rejects non-object input with JSON-pointer "/"', () => {+ expect(() => validatePodTemplate('not an object')).toThrow(PodTemplateValidationError);+ expect(() => validatePodTemplate(null)).toThrow(/pod-template must be a JSON object/);+ expect(() => validatePodTemplate([])).toThrow(/pod-template must be a JSON object/);+ });++ it('rejects missing required fields with structured error', () => {+ expect(() => validatePodTemplate({})).toThrow(/field "name" must be a non-empty string/);+ expect(() => validatePodTemplate({ name: 'sales' })).toThrow(/displayName/);+ });++ it('rejects malformed name (must be lowercase-kebab)', () => {+ const t = clone(salesJson) as Record<string, unknown>;+ t.name = 'Sales Pod';+ expect(() => validatePodTemplate(t)).toThrow(/lowercase-kebab/);+ });++ it('rejects empty agents array', () => {+ const t = clone(salesJson) as any;+ t.agents = [];+ expect(() => validatePodTemplate(t)).toThrow(/agents must have β₯1 entry/);+ });++ it('rejects empty allowedMcpTools array', () => {+ const t = clone(salesJson) as any;+ t.allowedMcpTools = [];+ expect(() => validatePodTemplate(t)).toThrow(/allowedMcpTools must have β₯1 entry/);+ });++ it('rejects empty bench.successCriteria', () => {+ const t = clone(salesJson) as any;+ t.bench.successCriteria = [];+ expect(() => validatePodTemplate(t)).toThrow(/successCriteria must have β₯1 entry/);+ });++ it('rejects invalid piiPolicy', () => {+ const t = clone(salesJson) as any;+ t.piiPolicy = 'invalid';+ expect(() => validatePodTemplate(t)).toThrow(/piiPolicy must be one of/);+ });++ it('rejects malformed cronSchedule', () => {+ const t = clone(salesJson) as any;+ t.cronSchedule = 'every six hours';+ expect(() => validatePodTemplate(t)).toThrow(/cronSchedule must be a POSIX cron expression/);+ });++ it('rejects budgetUsdPerRun exceeding budgetUsdMonthly', () => {+ const t = clone(salesJson) as any;+ t.budgetUsdPerRun = 100;+ t.budgetUsdMonthly = 50;+ expect(() => validatePodTemplate(t)).toThrow(/budgetUsdPerRun must not exceed budgetUsdMonthly/);+ });++ it('rejects negative budgets', () => {+ const t = clone(salesJson) as any;+ t.budgetUsdMonthly = -1;+ expect(() => validatePodTemplate(t)).toThrow(/budgetUsdMonthly must be β₯0/);+ });++ it('ADR-164.1 Β§3.2 β reservationExpiryMs below 5000 ms is rejected', () => {+ const t = clone(salesJson) as any;+ t.reservationExpiryMs = 1000;+ expect(() => validatePodTemplate(t)).toThrow(/reservationExpiryMs must be within \[5000, 300000\] ms/);+ });++ it('ADR-164.1 Β§3.2 β reservationExpiryMs above 300000 ms is rejected', () => {+ const t = clone(salesJson) as any;+ t.reservationExpiryMs = 600_000;+ expect(() => validatePodTemplate(t)).toThrow(/reservationExpiryMs must be within \[5000, 300000\] ms/);+ });++ it('reservationExpiryMs is optional β omitting it validates', () => {+ const t = clone(salesJson) as any;+ delete t.reservationExpiryMs;+ expect(() => validatePodTemplate(t)).not.toThrow();+ });++ it('accepts the Phase 2 sales.json template verbatim', () => {+ const t = validatePodTemplate(salesJson) as PodTemplate;+ expect(t.name).toBe('sales');+ expect(t.roomId).toBe('sales');+ expect(t.agents.length).toBe(4);+ expect(t.piiPolicy).toBe('soc2');+ expect(t.budgetUsdMonthly).toBe(50);+ expect(t.reservationExpiryMs).toBe(60_000);+ });+});++describe('Phase 3 β all 7 pod templates validate', () => {+ for (const name of POD_NAMES) {+ it(`${name}.json validates without errors`, () => {+ const raw = loadJson(name);+ const t = validatePodTemplate(raw);+ expect(t.name).toBe(name);+ expect(t.agents.length).toBeGreaterThanOrEqual(1);+ expect(t.allowedMcpTools.length).toBeGreaterThanOrEqual(1);+ expect(t.bench.successCriteria.length).toBeGreaterThanOrEqual(1);+ });+ }++ it('ops.json bench description references the synthetic-HTTP-endpoint test (ADR-164 Β§4.4)', () => {+ const ops = validatePodTemplate(loadJson('ops')) as PodTemplate;+ expect(ops.bench.description).toMatch(/synthetic.*endpoint/i);+ expect(ops.bench.description).toMatch(/200/);+ expect(ops.bench.description).toMatch(/500/);+ expect(ops.bench.description).toMatch(/60 seconds|60s/i);+ expect(ops.allowedMcpTools).toContain('http_fetch');+ expect(ops.allowedMcpTools).toContain('aidefence_analyze');+ expect(ops.allowedMcpTools).toContain('terminal_execute');+ expect(ops.allowedMcpTools).toContain('agent_execute');+ });++ it('exec.json bench description references the founder-bootstrap trust elevation (ADR-164 Β§3.5.4)', () => {+ const exec = validatePodTemplate(loadJson('exec')) as PodTemplate;+ expect(exec.bench.description).toMatch(/share-context/);+ expect(exec.bench.description).toMatch(/3\.5\.4|founder-bootstrap|escape hatch/i);+ });++ it('finance.json + hr.json + exec.json use gdpr piiPolicy (most restrictive)', () => {+ for (const n of ['finance', 'hr', 'exec'] as const) {+ const t = validatePodTemplate(loadJson(n)) as PodTemplate;+ expect(t.piiPolicy).toBe('gdpr');+ expect(t.preferLocalExecution).toBe(true);+ }+ });+});++describe('business_pod_validate MCP tool', () => {+ it('exposes business_pod_validate with required schema shape', () => {+ const t = findTool('business_pod_validate');+ expect(t.name).toBe('business_pod_validate');+ expect(t.inputSchema.type).toBe('object');+ expect(t.inputSchema.properties).toBeDefined();+ expect(typeof t.handler).toBe('function');+ // ADR-112 β description must be β₯80 chars and carry use-when guidance.+ expect(t.description.length).toBeGreaterThanOrEqual(80);+ expect(t.description).toMatch(/Use when/i);+ expect(t.description).toMatch(/wrong because/i);+ });++ it('exposes business_pod_route_backend with required schema shape', () => {+ const t = findTool('business_pod_route_backend');+ expect(t.name).toBe('business_pod_route_backend');+ expect(t.inputSchema.type).toBe('object');+ expect(t.inputSchema.properties).toBeDefined();+ expect(typeof t.handler).toBe('function');+ // ADR-112 β description must be β₯80 chars and carry use-when guidance.+ expect(t.description.length).toBeGreaterThanOrEqual(80);+ expect(t.description).toMatch(/Use when/i);+ expect(t.description).toMatch(/wrong because/i);+ });++ it('exposes exactly 2 business-pod tools (Phase 2 + Phase 3)', () => {+ expect(businessPodTools.length).toBe(2);+ });++ it('happy path: returns {success:true, valid:true, template, warnings}', async () => {+ const tool = findTool('business_pod_validate');+ const r: any = await tool.handler({ podTemplate: salesJson });+ expect(r.success).toBe(true);+ expect(r.valid).toBe(true);+ expect(r.template.name).toBe('sales');+ expect(r.warnings).toEqual([]);+ });++ it('error path: returns {success:false, valid:false, error, path}', async () => {+ const tool = findTool('business_pod_validate');+ const bad = clone(salesJson) as any;+ bad.reservationExpiryMs = 1000;+ const r: any = await tool.handler({ podTemplate: bad });+ expect(r.success).toBe(false);+ expect(r.valid).toBe(false);+ expect(r.error).toMatch(/reservationExpiryMs/);+ expect(r.path).toBe('/');+ });++ it('error path: non-object podTemplate is rejected before validation', async () => {+ const tool = findTool('business_pod_validate');+ const r: any = await tool.handler({ podTemplate: 'not an object' });+ expect(r.success).toBe(false);+ expect(r.valid).toBe(false);+ expect(r.error).toMatch(/podTemplate must be a JSON object/);+ });++ it('warns (does not fail) on unknown agent types', async () => {+ const tool = findTool('business_pod_validate');+ const withUnknown = clone(salesJson) as any;+ withUnknown.agents[0].agentType = 'not-a-real-agent-type-xyz';+ const r: any = await tool.handler({ podTemplate: withUnknown });+ expect(r.success).toBe(true);+ expect(r.valid).toBe(true);+ expect(r.warnings.length).toBeGreaterThan(0);+ expect(r.warnings[0]).toMatch(/not-a-real-agent-type-xyz/);+ });+});++describe('Phase 3 β domain-affinity policy (selectAgentBackend)', () => {+ // Synthesize the four combinations of (preferLocalExecution Γ budget vs threshold)+ // off the sales template β keeps the test independent of pod-file edits.+ const base = clone(salesJson) as PodTemplate;++ it('preferLocalExecution=true β local-stdio regardless of budget', () => {+ const t = { ...base, preferLocalExecution: true, budgetUsdMonthly: 999 };+ const d = selectAgentBackend(t);+ expect(d.backend).toBe('local-stdio');+ expect(d.reason).toMatch(/local stdio/);+ });++ it('preferLocalExecution=true β local-stdio even with budget=0', () => {+ const t = { ...base, preferLocalExecution: true, budgetUsdMonthly: 0, budgetUsdPerRun: 0 };+ const d = selectAgentBackend(t);+ expect(d.backend).toBe('local-stdio');+ });++ it(`preferLocalExecution=false AND budgetUsdMonthly >= ${CLOUD_BUDGET_THRESHOLD_USD} β cloud-managed`, () => {+ const t = {+ ...base,+ preferLocalExecution: false,+ budgetUsdMonthly: CLOUD_BUDGET_THRESHOLD_USD,+ };+ const d = selectAgentBackend(t);+ expect(d.backend).toBe('cloud-managed');+ expect(d.reason).toMatch(/cloud Managed Agents/);+ });++ it(`preferLocalExecution=false AND budgetUsdMonthly < ${CLOUD_BUDGET_THRESHOLD_USD} β remote-peer`, () => {+ const t = {+ ...base,+ preferLocalExecution: false,+ budgetUsdMonthly: CLOUD_BUDGET_THRESHOLD_USD - 1,+ budgetUsdPerRun: 0.05,+ };+ const d = selectAgentBackend(t);+ expect(d.backend).toBe('remote-peer');+ expect(d.reason).toMatch(/federation peer node/);+ });++ it('rejects malformed input (non-object)', () => {+ expect(() => selectAgentBackend(null as any)).toThrow(/must be a validated PodTemplate/);+ expect(() => selectAgentBackend('not a pod' as any)).toThrow(/must be a validated PodTemplate/);+ });++ it('rejects pod missing preferLocalExecution', () => {+ const t: any = { ...base };+ delete t.preferLocalExecution;+ expect(() => selectAgentBackend(t)).toThrow(/preferLocalExecution must be boolean/);+ });++ it('rejects pod with non-finite budgetUsdMonthly', () => {+ const t: any = { ...base, budgetUsdMonthly: Number.NaN };+ expect(() => selectAgentBackend(t)).toThrow(/budgetUsdMonthly must be a finite number/);+ });+});++describe('Phase 3 β business_pod_route_backend MCP tool', () => {+ it('routes the sales template per Β§3.4 rules', async () => {+ const tool = findTool('business_pod_route_backend');+ const r: any = await tool.handler({ podTemplate: salesJson });+ expect(r.success).toBe(true);+ expect(r.valid).toBe(true);+ // sales has preferLocalExecution=false and budgetUsdMonthly=50 β cloud-managed.+ expect(r.backend).toBe('cloud-managed');+ expect(r.pod.name).toBe('sales');+ expect(r.pod.budgetUsdMonthly).toBe(50);+ expect(r.reason).toMatch(/cloud Managed Agents/);+ });++ it('routes the marketing template (budget=40, preferLocal=false) to remote-peer', async () => {+ const tool = findTool('business_pod_route_backend');+ const r: any = await tool.handler({ podTemplate: loadJson('marketing') });+ expect(r.success).toBe(true);+ expect(r.backend).toBe('remote-peer');+ });++ it('routes the finance template (preferLocal=true) to local-stdio', async () => {+ const tool = findTool('business_pod_route_backend');+ const r: any = await tool.handler({ podTemplate: loadJson('finance') });+ expect(r.success).toBe(true);+ expect(r.backend).toBe('local-stdio');+ });++ it('accepts a podTemplatePath string and resolves it', async () => {+ const tool = findTool('business_pod_route_backend');+ const r: any = await tool.handler({+ podTemplatePath: resolve(TEMPLATES_DIR, 'hr.json'),+ });+ expect(r.success).toBe(true);+ expect(r.backend).toBe('local-stdio');+ expect(r.pod.name).toBe('hr');+ });++ it('rejects malformed input (no podTemplate and no podTemplatePath)', async () => {+ const tool = findTool('business_pod_route_backend');+ const r: any = await tool.handler({});+ expect(r.success).toBe(false);+ expect(r.valid).toBe(false);+ expect(r.error).toMatch(/podTemplate.*or.*podTemplatePath/);+ });++ it('rejects a malformed pod template with structured error path', async () => {+ const tool = findTool('business_pod_route_backend');+ const bad = clone(salesJson) as any;+ bad.reservationExpiryMs = 1;+ const r: any = await tool.handler({ podTemplate: bad });+ expect(r.success).toBe(false);+ expect(r.valid).toBe(false);+ expect(r.error).toMatch(/reservationExpiryMs/);+ expect(r.path).toBe('/');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/http-fetch-tools.test.ts b/v3/@claude-flow/cli/__tests__/http-fetch-tools.test.tsnew file mode 100644index 0000000000..3781c00e08--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/http-fetch-tools.test.ts@@ -0,0 +1,271 @@+/**+ * Tests for http_fetch MCP tool (ADR-164 Β§5.1.8, Phase 4).+ *+ * Coverage:+ * - URL allowlist (default-blocks file://, ftp://, RFC-1918, loopback, link-local)+ * - Opt-in via CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 reaches a local server+ * - Header sanitization (default-rejects Authorization / Cookie / X-Auth-*)+ * - Opt-in via CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1 passes the header+ * - Hard timeout aborts via AbortController+ * - Response truncation honours maxResponseBytes+ * - Happy path against a local mock node:http server+ * - Default User-Agent injected if caller did not provide one+ */+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';+import http from 'node:http';+import type { AddressInfo } from 'node:net';++import {+ httpFetchTools,+ httpFetchExecute,+ validateUrl,+ validateHeaders,+ HttpFetchValidationError,+} from '../src/mcp-tools/http-fetch-tools.js';++function findTool(name: string) {+ const t = httpFetchTools.find((x) => x.name === name);+ if (!t) throw new Error(`tool not found: ${name}`);+ return t;+}++// ---------- mock server for happy-path + truncation + timeout tests --------++let server: http.Server;+let port: number;+let lastUA: string | undefined;+let lastAuth: string | undefined;+let lastMethod: string | undefined;+let lastBody: string | undefined;++beforeAll(async () => {+ await new Promise<void>((resolve) => {+ server = http.createServer((req, res) => {+ lastUA = req.headers['user-agent'] as string | undefined;+ lastAuth = req.headers['authorization'] as string | undefined;+ lastMethod = req.method;++ // Collect body+ const chunks: Buffer[] = [];+ req.on('data', (c) => chunks.push(c));+ req.on('end', () => {+ lastBody = Buffer.concat(chunks).toString('utf-8');++ const url = req.url ?? '/';+ if (url === '/ok') {+ res.writeHead(200, { 'content-type': 'text/plain', 'x-server': 'mock' });+ res.end('hello-world');+ } else if (url === '/big') {+ // 1MB+ body β should trigger truncation when maxResponseBytes < 1MB+ res.writeHead(200, { 'content-type': 'application/octet-stream' });+ res.end(Buffer.alloc(2 * 1024 * 1024, 0x41));+ } else if (url === '/slow') {+ // Never respond β caller must abort+ // Keep connection open. Don't write headers either.+ // Will be terminated when the test server closes.+ } else if (url === '/echo') {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ method: req.method, body: lastBody }));+ } else if (url === '/500') {+ res.writeHead(500, { 'content-type': 'text/plain' });+ res.end('server-error');+ } else {+ res.writeHead(404);+ res.end('not-found');+ }+ });+ });+ server.listen(0, '127.0.0.1', () => {+ port = (server.address() as AddressInfo).port;+ resolve();+ });+ });+});++afterAll(async () => {+ // Force-close to terminate any lingering /slow request+ await new Promise<void>((resolve) => {+ server.closeAllConnections?.();+ server.close(() => resolve());+ });+});++// ---------- env-flag isolation -----------------------------------++const originalEnv = { ...process.env };+beforeEach(() => {+ delete process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE;+ delete process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH;+});+afterEach(() => {+ process.env = { ...originalEnv };+});++// ---------- URL allowlist tests ----------------------------------++describe('http_fetch β URL allowlist (default-deny)', () => {+ it('rejects file:// URLs', () => {+ expect(() => validateUrl('file:///etc/passwd')).toThrow(HttpFetchValidationError);+ });++ it('rejects ftp:// URLs', () => {+ expect(() => validateUrl('ftp://example.com/x')).toThrow(/protocol/);+ });++ it('rejects localhost', () => {+ expect(() => validateUrl('http://localhost/foo')).toThrow(/loopback|private/i);+ });++ it('rejects 127.0.0.1', () => {+ expect(() => validateUrl('http://127.0.0.1/foo')).toThrow(/loopback|private/i);+ });++ it('rejects 10.x RFC1918', () => {+ expect(() => validateUrl('http://10.0.0.5/foo')).toThrow(/loopback|private/i);+ });++ it('rejects 192.168.x.x RFC1918', () => {+ expect(() => validateUrl('http://192.168.1.1/foo')).toThrow(/loopback|private/i);+ });++ it('rejects 172.16.x.x RFC1918', () => {+ expect(() => validateUrl('http://172.20.0.1/foo')).toThrow(/loopback|private/i);+ });++ it('rejects 169.254.x.x link-local', () => {+ expect(() => validateUrl('http://169.254.169.254/latest')).toThrow(/loopback|private/i);+ });++ it('allows public host (example.com) by hostname check alone', () => {+ expect(() => validateUrl('https://example.com/foo')).not.toThrow();+ });++ it('opt-in CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 unlocks private addresses', () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ expect(() => validateUrl('http://127.0.0.1/foo')).not.toThrow();+ expect(() => validateUrl('http://10.0.0.5/foo')).not.toThrow();+ });+});++// ---------- header sanitization tests ----------------------------++describe('http_fetch β header sanitization (default-deny auth)', () => {+ it('rejects Authorization header by default', () => {+ expect(() => validateHeaders({ Authorization: 'Bearer abc' })).toThrow(/not allowed/i);+ });+ it('rejects Cookie header by default', () => {+ expect(() => validateHeaders({ Cookie: 'sid=abc' })).toThrow(/not allowed/i);+ });+ it('rejects X-Auth-Token by default', () => {+ expect(() => validateHeaders({ 'X-Auth-Token': 'abc' })).toThrow(/not allowed/i);+ });+ it('accepts benign headers', () => {+ const h = validateHeaders({ Accept: 'application/json', 'X-Pod': 'ops' });+ expect(h.Accept).toBe('application/json');+ expect(h['X-Pod']).toBe('ops');+ });+ it('opt-in CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1 unlocks auth headers', () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH = '1';+ expect(() => validateHeaders({ Authorization: 'Bearer abc' })).not.toThrow();+ });+});++// ---------- happy path / timeout / truncation --------------------++describe('http_fetch β execution path against a mock server', () => {+ it('happy-path GET returns 200 and body', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({ url: `http://127.0.0.1:${port}/ok` });+ expect(result.success).toBe(true);+ expect(result.status).toBe(200);+ expect(result.body).toBe('hello-world');+ expect(result.bodyTruncated).toBe(false);+ });++ it('default User-Agent is sent when caller omits it', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ lastUA = undefined;+ await httpFetchExecute({ url: `http://127.0.0.1:${port}/ok` });+ expect(lastUA).toMatch(/^ruflo-http-fetch\//);+ });++ it('aborts on timeout', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({+ url: `http://127.0.0.1:${port}/slow`,+ timeoutMs: 100,+ });+ expect(result.success).toBe(false);+ expect(result.errorCode).toBe('TIMEOUT');+ expect(result.durationMs).toBeGreaterThanOrEqual(80);+ expect(result.durationMs).toBeLessThan(5_000);+ }, 10_000);++ it('truncates the response when body exceeds maxResponseBytes', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({+ url: `http://127.0.0.1:${port}/big`,+ maxResponseBytes: 1024,+ });+ expect(result.success).toBe(true);+ expect(result.bodyTruncated).toBe(true);+ expect(result.bytesRead).toBeLessThanOrEqual(1024);+ expect(result.body.length).toBeLessThanOrEqual(1024);+ }, 10_000);++ it('refuses to call when URL is private and flag is off', async () => {+ const result = await httpFetchExecute({ url: `http://127.0.0.1:${port}/ok` });+ expect(result.success).toBe(false);+ expect(result.errorCode).toBe('PRIVATE_ADDRESS');+ });++ it('refuses Authorization header without env flag', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({+ url: `http://127.0.0.1:${port}/ok`,+ headers: { Authorization: 'Bearer abc' },+ });+ expect(result.success).toBe(false);+ expect(result.errorCode).toBe('FORBIDDEN_HEADER');+ });++ it('POST with body echoes back through /echo', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({+ url: `http://127.0.0.1:${port}/echo`,+ method: 'POST',+ body: 'hello',+ });+ expect(result.success).toBe(true);+ expect(result.status).toBe(200);+ const parsed = JSON.parse(result.body);+ expect(parsed.method).toBe('POST');+ expect(parsed.body).toBe('hello');+ });++ it('reports non-2xx status without throwing', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const result = await httpFetchExecute({ url: `http://127.0.0.1:${port}/500` });+ expect(result.success).toBe(true);+ expect(result.status).toBe(500);+ expect(result.body).toBe('server-error');+ });+});++// ---------- MCP tool wiring -------------------------------------++describe('http_fetch β MCP tool registration', () => {+ it('exports http_fetch tool with required schema fields', () => {+ const tool = findTool('http_fetch');+ expect(tool.description.length).toBeGreaterThan(80);+ expect(tool.description).toMatch(/Use when/i);+ expect(tool.inputSchema.required).toEqual(['url']);+ });++ it('tool.handler dispatches to httpFetchExecute', async () => {+ process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE = '1';+ const tool = findTool('http_fetch');+ const result = (await tool.handler({ url: `http://127.0.0.1:${port}/ok` })) as { status: number };+ expect(result.status).toBe(200);+ });+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 1f5741c676..2d6daa07e7 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -106,6 +106,7 @@"yaml": "^2.8.0"},"optionalDependencies": {+ "agentbbs": "~0.1.0","agenticow": "~0.2.3","@claude-flow/aidefence": "^3.0.2","@claude-flow/codex": "^3.0.0-alpha.8",diff --git a/v3/@claude-flow/cli/src/business-pods/bbs-budget-tracker.ts b/v3/@claude-flow/cli/src/business-pods/bbs-budget-tracker.tsnew file mode 100644index 0000000000..4c419e074e--- /dev/null+++ b/v3/@claude-flow/cli/src/business-pods/bbs-budget-tracker.ts@@ -0,0 +1,472 @@+/**+ * BbsRoomBudgetTracker β Atomic reserve / commit / release token-bucket+ * backed by better-sqlite3 (ADR-164.1 Β§3-Β§5).+ *+ * Closes the read-then-write race in ADR-164's first-draft tracker by routing+ * every state transition through a single `BEGIN IMMEDIATE` transaction that+ * acquires the SQLite write lock atomically with the gate check. The+ * `_lock_bump` column write is a belt-and-suspenders explicit write inside+ * the transaction so the lock acquisition is visible to code review and+ * query-log analysis (Β§3.2 peer-review clarification).+ *+ * Architectural constraints (ADR-164.1):+ * - Default OFF: this module is opt-in behind `CLAUDE_FLOW_BBS_ATOMIC_BUDGET=1`.+ * The pod-tick.mjs file-based stub remains the default until the flag is+ * flipped per ADR-164.1 Β§12.4.+ * - `committed_post_expiry` state machine implemented per Β§5.3 β late+ * commits on expired reservations ARE accepted (the API spend already+ * happened), transition to `committed_post_expiry`, charge the budget,+ * and return `warned: 'COMMIT_AFTER_EXPIRY'`. This closes the Β§8.1+ * Expired Commit Leak surfaced by peer review on 2026-06-29.+ * - `expires_at` is clamped to [5_000, 300_000] ms (Β§3.2).+ * - WAL + synchronous=NORMAL + busy_timeout=500 for write throughput.+ *+ * The sweeper interval (`sweepExpired()`) is exposed as a manual method;+ * callers are expected to drive it on a setInterval β that integration lives+ * at the call site, not in this file, per ADR-164.1 Β§7.1.+ *+ * @module @claude-flow/cli/business-pods/bbs-budget-tracker+ */++import { randomUUID } from 'node:crypto';++// `better-sqlite3` is a transitive dep (hoisted from v3 monorepo). We type+// the Database interface structurally here so the module compiles even when+// better-sqlite3 has not been installed at this package's depth β at runtime+// the caller passes a Database instance constructed from their own require.+export interface SqliteDatabase {+ pragma(name: string): unknown;+ prepare(sql: string): SqliteStatement;+ exec(sql: string): void;+ close(): void;+}++export interface SqliteStatement {+ run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };+ get(...params: unknown[]): Record<string, unknown> | undefined;+ all(...params: unknown[]): Record<string, unknown>[];+}++// ---------- expiry-window clamp -------------------------------------------++export const RESERVATION_EXPIRY_FLOOR_MS = 5_000;+export const RESERVATION_EXPIRY_CEILING_MS = 300_000;+export const RESERVATION_EXPIRY_DEFAULT_MS = 60_000;++export function clampReservationExpiry(raw: number | undefined): number {+ if (raw === undefined || !Number.isFinite(raw)) {+ const envVal = Number(process.env.CLAUDE_FLOW_BBS_RESERVATION_EXPIRY_MS);+ if (Number.isFinite(envVal) && envVal > 0) {+ return Math.max(RESERVATION_EXPIRY_FLOOR_MS, Math.min(RESERVATION_EXPIRY_CEILING_MS, envVal));+ }+ return RESERVATION_EXPIRY_DEFAULT_MS;+ }+ return Math.max(RESERVATION_EXPIRY_FLOOR_MS, Math.min(RESERVATION_EXPIRY_CEILING_MS, raw));+}++// ---------- error / result shapes (match ADR-164.1 Β§4.1 verbatim) ---------++export type ReserveResult =+ | { ok: true; reservationId: string; remainingAfterReserve: number }+ | { ok: false; error: 'BUDGET_EXCEEDED' | 'ROOM_NOT_FOUND' };++export type CommitResult =+ | { ok: true; committed: true; finalRemaining: number }+ | { ok: true; warned: 'COMMIT_AFTER_EXPIRY'; finalRemaining: number }+ | { ok: false; error: 'NOT_FOUND' | 'ALREADY_FINALIZED' };++export type ReleaseResult =+ | { ok: true; released: true }+ | { ok: false; error: 'NOT_FOUND' | 'ALREADY_FINALIZED' };++// ---------- schema migration ----------------------------------------------++export const SCHEMA_SQL = `+PRAGMA journal_mode = WAL;+PRAGMA synchronous = NORMAL;+PRAGMA busy_timeout = 500;++CREATE TABLE IF NOT EXISTS bbs_budget_rooms (+ room_id TEXT NOT NULL PRIMARY KEY,+ monthly_cap_usd REAL NOT NULL CHECK (monthly_cap_usd >= 0),+ billing_month TEXT NOT NULL,+ _lock_bump INTEGER NOT NULL DEFAULT 0+);++CREATE TABLE IF NOT EXISTS bbs_budget_reservations (+ reservation_id TEXT NOT NULL PRIMARY KEY,+ room_id TEXT NOT NULL REFERENCES bbs_budget_rooms(room_id),+ caller_node_id TEXT NOT NULL,+ estimated_usd REAL NOT NULL CHECK (estimated_usd >= 0),+ actual_usd REAL,+ state TEXT NOT NULL+ CHECK (state IN ('reserved','committed','released','expired','committed_post_expiry')),+ reserved_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ committed_at INTEGER,+ audit_envelope_id TEXT NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_reservations_room_month+ ON bbs_budget_reservations (room_id, reserved_at);++CREATE INDEX IF NOT EXISTS idx_reservations_expiry+ ON bbs_budget_reservations (state, expires_at);+`;++// ---------- helpers --------------------------------------------------------++function currentBillingMonth(now: number): string {+ const d = new Date(now);+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;+}++function billingMonthStartMs(billingMonth: string): number {+ const [y, m] = billingMonth.split('-').map((n) => Number(n));+ return Date.UTC(y!, (m! - 1), 1, 0, 0, 0, 0);+}++// ---------- audit hook -----------------------------------------------------++export interface BudgetAuditSink {+ emit(eventType: 'reservation.committed_post_expiry' | 'reservation.committed' | 'reservation.released' | 'reservation.reserved' | 'reservation.budget_exceeded',+ payload: Record<string, unknown>): void;+}++const noopAudit: BudgetAuditSink = { emit: () => undefined };++// ---------- the tracker ----------------------------------------------------++export interface AtomicBbsRoomBudgetTrackerOptions {+ /** SQLite database handle (caller-owned, opened in WAL mode). */+ db: SqliteDatabase;+ /** Override the default 60s reservation window (clamped to [5s, 300s]). */+ defaultExpiryMs?: number;+ /** Audit sink β receives reservation lifecycle events. */+ audit?: BudgetAuditSink;+ /** Inject Date.now() for tests. */+ clock?: () => number;+}++export class AtomicBbsRoomBudgetTracker {+ private readonly db: SqliteDatabase;+ private readonly defaultExpiryMs: number;+ private readonly audit: BudgetAuditSink;+ private readonly clock: () => number;++ constructor(opts: AtomicBbsRoomBudgetTrackerOptions) {+ this.db = opts.db;+ this.defaultExpiryMs = clampReservationExpiry(opts.defaultExpiryMs);+ this.audit = opts.audit ?? noopAudit;+ this.clock = opts.clock ?? Date.now;++ // Ensure schema is present. exec() is a no-op for tables that already+ // exist due to IF NOT EXISTS.+ this.db.exec(SCHEMA_SQL);+ }++ /**+ * Register (or update) a room and its monthly cap. Idempotent.+ */+ registerRoom(roomId: string, monthlyCapUsd: number): void {+ const billingMonth = currentBillingMonth(this.clock());+ this.db+ .prepare(+ `INSERT INTO bbs_budget_rooms (room_id, monthly_cap_usd, billing_month, _lock_bump)+ VALUES (?, ?, ?, 0)+ ON CONFLICT(room_id) DO UPDATE SET monthly_cap_usd = excluded.monthly_cap_usd`,+ )+ .run(roomId, monthlyCapUsd, billingMonth);+ }++ /**+ * Atomically check budget and insert a reservation row in a single+ * BEGIN IMMEDIATE transaction. See ADR-164.1 Β§5.2.+ */+ reserve(+ roomId: string,+ callerId: string,+ estimatedUsd: number,+ opts?: { auditEnvelopeId?: string; expiryMs?: number },+ ): ReserveResult {+ if (!Number.isFinite(estimatedUsd) || estimatedUsd < 0) {+ throw new Error('estimatedUsd must be a non-negative finite number');+ }+ const auditEnvelopeId = opts?.auditEnvelopeId ?? `audit-${randomUUID()}`;+ const expiryMs = clampReservationExpiry(opts?.expiryMs ?? this.defaultExpiryMs);++ const nowMs = this.clock();+ const billingMonth = currentBillingMonth(nowMs);+ const billingMonthStart = billingMonthStartMs(billingMonth);++ const beginStmt = this.db.prepare('BEGIN IMMEDIATE');+ const commitStmt = this.db.prepare('COMMIT');+ const rollbackStmt = this.db.prepare('ROLLBACK');++ beginStmt.run();+ let transactionOpen = true;+ try {+ // Step 1: touch the room header row (the _lock_bump write makes the+ // lock acquisition visible per Β§3.2 peer-review note).+ const bumpRes = this.db+ .prepare(+ `UPDATE bbs_budget_rooms+ SET _lock_bump = _lock_bump + 1,+ billing_month = CASE WHEN billing_month = ? THEN billing_month ELSE ? END+ WHERE room_id = ?`,+ )+ .run(billingMonth, billingMonth, roomId);++ if (bumpRes.changes === 0) {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'ROOM_NOT_FOUND' };+ }++ const roomRow = this.db+ .prepare(`SELECT monthly_cap_usd, billing_month FROM bbs_budget_rooms WHERE room_id = ?`)+ .get(roomId) as { monthly_cap_usd: number; billing_month: string } | undefined;++ if (!roomRow) {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'ROOM_NOT_FOUND' };+ }++ const monthlyCap = roomRow.monthly_cap_usd;++ // Step 3: compute committed + live-reserved totals within this billing month.+ const totals = this.db+ .prepare(+ `SELECT+ COALESCE(SUM(CASE WHEN state IN ('committed','committed_post_expiry') THEN actual_usd ELSE 0 END), 0) AS committed_total,+ COALESCE(SUM(CASE WHEN state = 'reserved' AND expires_at > ? THEN estimated_usd ELSE 0 END), 0) AS reserved_total+ FROM bbs_budget_reservations+ WHERE room_id = ? AND reserved_at >= ?`,+ )+ .get(nowMs, roomId, billingMonthStart) as { committed_total: number; reserved_total: number };++ const committedTotal = totals.committed_total ?? 0;+ const reservedTotal = totals.reserved_total ?? 0;+ const projected = committedTotal + reservedTotal + estimatedUsd;++ if (projected > monthlyCap + 1e-9) {+ rollbackStmt.run();+ transactionOpen = false;+ this.audit.emit('reservation.budget_exceeded', {+ roomId, callerId, estimatedUsd, committedTotal, reservedTotal, monthlyCap,+ });+ return { ok: false, error: 'BUDGET_EXCEEDED' };+ }++ // Step 5: insert the reservation.+ const reservationId = `res-${randomUUID()}`;+ const expiresAt = nowMs + expiryMs;+ this.db+ .prepare(+ `INSERT INTO bbs_budget_reservations+ (reservation_id, room_id, caller_node_id, estimated_usd, actual_usd,+ state, reserved_at, expires_at, committed_at, audit_envelope_id)+ VALUES (?, ?, ?, ?, NULL, 'reserved', ?, ?, NULL, ?)`,+ )+ .run(reservationId, roomId, callerId, estimatedUsd, nowMs, expiresAt, auditEnvelopeId);++ commitStmt.run();+ transactionOpen = false;++ const remaining = monthlyCap - (committedTotal + reservedTotal + estimatedUsd);+ this.audit.emit('reservation.reserved', {+ reservationId, roomId, callerId, estimatedUsd, expiresAt, remaining,+ });+ return { ok: true, reservationId, remainingAfterReserve: remaining };+ } catch (err) {+ if (transactionOpen) {+ try { rollbackStmt.run(); } catch { /* already-rolled */ }+ }+ throw err;+ }+ }++ /**+ * Commit the reservation with the actual cost. Late commits (expired+ * before commit landed) ARE accepted, transitioned to+ * 'committed_post_expiry', charged to the budget, and surfaced via+ * `warned: 'COMMIT_AFTER_EXPIRY'` plus a `reservation.committed_post_expiry`+ * audit emit. See ADR-164.1 Β§5.3 + Β§8.1.+ */+ commit(reservationId: string, actualUsd: number): CommitResult {+ if (!Number.isFinite(actualUsd) || actualUsd < 0) {+ throw new Error('actualUsd must be a non-negative finite number');+ }+ const nowMs = this.clock();++ const beginStmt = this.db.prepare('BEGIN IMMEDIATE');+ const commitStmt = this.db.prepare('COMMIT');+ const rollbackStmt = this.db.prepare('ROLLBACK');++ beginStmt.run();+ let transactionOpen = true;+ try {+ const row = this.db+ .prepare(+ `SELECT state, room_id, estimated_usd, reserved_at, expires_at+ FROM bbs_budget_reservations+ WHERE reservation_id = ?`,+ )+ .get(reservationId) as+ | { state: string; room_id: string; estimated_usd: number; reserved_at: number; expires_at: number }+ | undefined;++ if (!row) {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'NOT_FOUND' };+ }++ if (row.state === 'committed' || row.state === 'committed_post_expiry' ||+ row.state === 'released' || row.state === 'expired') {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'ALREADY_FINALIZED' };+ }++ // state is 'reserved' here. Decide committed vs committed_post_expiry.+ const lateCommit = row.expires_at <= nowMs;+ const newState = lateCommit ? 'committed_post_expiry' : 'committed';++ this.db+ .prepare(+ `UPDATE bbs_budget_reservations+ SET state = ?, actual_usd = ?, committed_at = ?+ WHERE reservation_id = ?`,+ )+ .run(newState, actualUsd, nowMs, reservationId);++ // Re-compute remaining for the return value.+ const billingMonth = currentBillingMonth(nowMs);+ const billingMonthStart = billingMonthStartMs(billingMonth);+ const totals = this.db+ .prepare(+ `SELECT+ COALESCE(SUM(CASE WHEN state IN ('committed','committed_post_expiry') THEN actual_usd ELSE 0 END), 0) AS committed_total,+ COALESCE(SUM(CASE WHEN state = 'reserved' AND expires_at > ? THEN estimated_usd ELSE 0 END), 0) AS reserved_total+ FROM bbs_budget_reservations+ WHERE room_id = ? AND reserved_at >= ?`,+ )+ .get(nowMs, row.room_id, billingMonthStart) as { committed_total: number; reserved_total: number };++ const roomRow = this.db+ .prepare(`SELECT monthly_cap_usd FROM bbs_budget_rooms WHERE room_id = ?`)+ .get(row.room_id) as { monthly_cap_usd: number } | undefined;++ const monthlyCap = roomRow?.monthly_cap_usd ?? 0;+ const finalRemaining = monthlyCap - ((totals.committed_total ?? 0) + (totals.reserved_total ?? 0));++ commitStmt.run();+ transactionOpen = false;++ if (lateCommit) {+ // Emit the high-priority audit envelope per Β§8.1.+ this.audit.emit('reservation.committed_post_expiry', {+ reservationId, roomId: row.room_id, actualUsd, finalRemaining,+ reservedAt: row.reserved_at, expiresAt: row.expires_at, committedAt: nowMs,+ });+ return { ok: true, warned: 'COMMIT_AFTER_EXPIRY', finalRemaining };+ }++ this.audit.emit('reservation.committed', {+ reservationId, roomId: row.room_id, actualUsd, finalRemaining,+ });+ return { ok: true, committed: true, finalRemaining };+ } catch (err) {+ if (transactionOpen) {+ try { rollbackStmt.run(); } catch { /* already-rolled */ }+ }+ throw err;+ }+ }++ /**+ * Release a reservation (caller decided not to proceed). State must be+ * 'reserved'; any other state is ALREADY_FINALIZED.+ */+ release(reservationId: string): ReleaseResult {+ const beginStmt = this.db.prepare('BEGIN IMMEDIATE');+ const commitStmt = this.db.prepare('COMMIT');+ const rollbackStmt = this.db.prepare('ROLLBACK');++ beginStmt.run();+ let transactionOpen = true;+ try {+ const row = this.db+ .prepare(`SELECT state, room_id FROM bbs_budget_reservations WHERE reservation_id = ?`)+ .get(reservationId) as { state: string; room_id: string } | undefined;++ if (!row) {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'NOT_FOUND' };+ }++ if (row.state !== 'reserved') {+ rollbackStmt.run();+ transactionOpen = false;+ return { ok: false, error: 'ALREADY_FINALIZED' };+ }++ this.db+ .prepare(`UPDATE bbs_budget_reservations SET state = 'released' WHERE reservation_id = ?`)+ .run(reservationId);++ commitStmt.run();+ transactionOpen = false;++ this.audit.emit('reservation.released', { reservationId, roomId: row.room_id });+ return { ok: true, released: true };+ } catch (err) {+ if (transactionOpen) {+ try { rollbackStmt.run(); } catch { /* already-rolled */ }+ }+ throw err;+ }+ }++ /**+ * Sweep expired reservations: transition 'reserved' rows whose expiry has+ * passed to 'expired'. Callers should drive this on a setInterval per+ * ADR-164.1 Β§7.1 (default cadence 5s; this method does NOT install the+ * timer β that's the integration site's responsibility).+ * Returns the number of rows updated.+ */+ sweepExpired(): number {+ const result = this.db+ .prepare(+ `UPDATE bbs_budget_reservations+ SET state = 'expired'+ WHERE state = 'reserved' AND expires_at < ?`,+ )+ .run(this.clock());+ return result.changes;+ }++ /**+ * Diagnostic read: list reservations for a room. Not on the hot path.+ */+ listReservations(roomId: string): Array<Record<string, unknown>> {+ return this.db+ .prepare(`SELECT * FROM bbs_budget_reservations WHERE room_id = ? ORDER BY reserved_at`)+ .all(roomId);+ }+}++/**+ * Feature-flagged factory per ADR-164.1 Β§12.3. Returns an atomic tracker+ * when `CLAUDE_FLOW_BBS_ATOMIC_BUDGET=1`, otherwise returns null so the+ * caller can keep using the file-based stub in pod-tick.mjs.+ */+export function createAtomicTrackerIfEnabled(+ opts: AtomicBbsRoomBudgetTrackerOptions,+): AtomicBbsRoomBudgetTracker | null {+ if (process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET !== '1') return null;+ return new AtomicBbsRoomBudgetTracker(opts);+}diff --git a/v3/@claude-flow/cli/src/business-pods/domain-affinity-policy.ts b/v3/@claude-flow/cli/src/business-pods/domain-affinity-policy.tsnew file mode 100644index 0000000000..64f1db6e9c--- /dev/null+++ b/v3/@claude-flow/cli/src/business-pods/domain-affinity-policy.ts@@ -0,0 +1,86 @@+/**+ * Domain-affinity routing policy β ADR-164 Β§3.4.+ *+ * Surfaces a deterministic routing decision for `@metaharness/router` to use+ * before its KRR cost-optimal step. The policy is intentionally tiny β+ * three branches over `preferLocalExecution` and `budgetUsdMonthly` β so the+ * decision is auditable from the pod template alone, no learned-weight side+ * effects.+ *+ * Rules (per the Phase-3 brief):+ * 1. `preferLocalExecution === true` β 'local-stdio'+ * 2. `preferLocalExecution === false` AND `budgetUsdMonthly >= 50` β 'cloud-managed'+ * 3. otherwise β 'remote-peer'+ *+ * The boundary `>= 50` matches the Phase-2 sales template (budget 50/month) β+ * it routes the canonical reference pod to the cloud-managed backend. Pods+ * below the threshold default to the federation peer-node backend.+ *+ * Wire point: `@metaharness/router` reads the result and supplies it as a+ * routing hint *before* its KRR step. The router is free to override on+ * latency/cost grounds β domain affinity is a policy floor, not a hard gate.+ *+ * @module @claude-flow/cli/business-pods/domain-affinity-policy+ */++import type { PodTemplate } from './pod-schema.js';++/** Three backends @metaharness/router can target for a pod tick. */+export type AgentBackend = 'local-stdio' | 'remote-peer' | 'cloud-managed';++/** Threshold for `cloud-managed` routing. Pods at or above this monthly+ * spend default to cloud-managed when they are *not* local-pinned. */+export const CLOUD_BUDGET_THRESHOLD_USD = 50;++/** Structured routing decision. `reason` is rendered into the routing+ * rationale via `hooks_explain` so operators can see why each pod was+ * routed where it was. */+export interface BackendDecision {+ backend: AgentBackend;+ reason: string;+}++/**+ * Decide which backend `@metaharness/router` should prefer for a pod tick.+ *+ * @param pod A validated PodTemplate. Validation is the caller's+ * responsibility; this function will throw on malformed input+ * (specifically on missing `preferLocalExecution` or+ * `budgetUsdMonthly`).+ */+export function selectAgentBackend(pod: PodTemplate): BackendDecision {+ if (pod === null || typeof pod !== 'object') {+ throw new TypeError('selectAgentBackend: pod must be a validated PodTemplate object');+ }+ if (typeof pod.preferLocalExecution !== 'boolean') {+ throw new TypeError(+ 'selectAgentBackend: pod.preferLocalExecution must be boolean (validate via pod-schema first)',+ );+ }+ if (typeof pod.budgetUsdMonthly !== 'number' || !Number.isFinite(pod.budgetUsdMonthly)) {+ throw new TypeError(+ 'selectAgentBackend: pod.budgetUsdMonthly must be a finite number (validate via pod-schema first)',+ );+ }++ if (pod.preferLocalExecution) {+ return {+ backend: 'local-stdio',+ reason: `pod "${pod.name}" preferLocalExecution=true β domain-affinity policy pins to local stdio`,+ };+ }+ if (pod.budgetUsdMonthly >= CLOUD_BUDGET_THRESHOLD_USD) {+ return {+ backend: 'cloud-managed',+ reason:+ `pod "${pod.name}" preferLocalExecution=false and budgetUsdMonthly=${pod.budgetUsdMonthly} ` ++ `>= ${CLOUD_BUDGET_THRESHOLD_USD} β routes to cloud Managed Agents`,+ };+ }+ return {+ backend: 'remote-peer',+ reason:+ `pod "${pod.name}" preferLocalExecution=false and budgetUsdMonthly=${pod.budgetUsdMonthly} ` ++ `< ${CLOUD_BUDGET_THRESHOLD_USD} β routes to federation peer node`,+ };+}diff --git a/v3/@claude-flow/cli/src/business-pods/pod-schema.ts b/v3/@claude-flow/cli/src/business-pods/pod-schema.tsnew file mode 100644index 0000000000..90b75d441d--- /dev/null+++ b/v3/@claude-flow/cli/src/business-pods/pod-schema.ts@@ -0,0 +1,317 @@+/**+ * Pod template schema validator (ADR-164 Β§3.3 + ADR-164.1 Β§3.2).+ *+ * Defines the `PodTemplate` type that every business-pod JSON file under+ * `plugins/ruflo-business-pods/templates/` MUST conform to, and a hand-rolled+ * validator that throws structured errors on invalid templates. No external+ * deps (no AJV, no zod) β the schema is small enough to validate by hand and+ * doing so keeps the cli's optional-dep surface unchanged.+ *+ * @module @claude-flow/cli/business-pods/pod-schema+ */++export type PiiPolicy = 'soc2' | 'gdpr' | 'hipaa' | 'permissive';++export interface PodAgent {+ /** Role label inside the pod, e.g. "lead-gen-agent". */+ role: string;+ /** Must resolve to a known ruflo agent type (researcher / coder / ...). */+ agentType: string;+ /** Human-readable description of what the agent does in this pod. */+ description: string;+ /** Routing hint β true = prefer local stdio execution. */+ preferLocal: boolean;+}++export interface PodBench {+ /** Bench identifier, e.g. "sales-pipeline-bench". */+ name: string;+ /** What the bench measures. */+ description: string;+ /** Acceptance criteria β non-empty list of human-readable bullets. */+ successCriteria: string[];+ /** Cadence between bench evaluations (hours, β₯1). */+ scheduleHours: number;+}++export interface PodAuditReadView {+ /** Event types surfaced to the business-owner read view. */+ includedEventTypes: string[];+ /** Retention window for the read view (days, β₯1). */+ retentionDays: number;+}++export interface PodTemplate {+ /** Canonical pod name (matches BBS roomId). */+ name: string;+ /** Display name for the cockpit. */+ displayName: string;+ /** BBS room this pod serves, e.g. "sales". */+ roomId: string;+ /** Ordered list of pod agent compositions. */+ agents: PodAgent[];+ /** Allow-list of MCP tools the pod's agents may invoke. */+ allowedMcpTools: string[];+ /** Bench definition for periodic Darwin /loop scoring. */+ bench: PodBench;+ /** PII compliance mode applied to every envelope in/out of this room. */+ piiPolicy: PiiPolicy;+ /** Monthly USD hard cap (0 = unlimited; not recommended). */+ budgetUsdMonthly: number;+ /** Estimated USD per pod tick β drives reservation amount. */+ budgetUsdPerRun: number;+ /** If true, @metaharness/router routes to local first. */+ preferLocalExecution: boolean;+ /** POSIX cron expression for the perpetual /loop scheduler. */+ cronSchedule: string;+ /** Compliance audit-log projection. */+ auditReadView: PodAuditReadView;+ /**+ * Reservation expiry for the atomic budget tracker β ADR-164.1 Β§3.2.+ * Bounded to [5000, 300000] ms (5 s β 5 min). Default 60_000 if omitted.+ */+ reservationExpiryMs?: number;+}++/**+ * Structured validation error β carries the JSON pointer that caused it so+ * callers can render a precise message.+ */+export class PodTemplateValidationError extends Error {+ constructor(message: string, public path: string) {+ super(`pod-template at ${path}: ${message}`);+ this.name = 'PodTemplateValidationError';+ }+}++const PII_POLICIES: PiiPolicy[] = ['soc2', 'gdpr', 'hipaa', 'permissive'];++function isObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}++function requireString(parent: Record<string, unknown>, key: string, path: string): string {+ const v = parent[key];+ if (typeof v !== 'string' || v.length === 0) {+ throw new PodTemplateValidationError(`field "${key}" must be a non-empty string`, path);+ }+ return v;+}++function requireNumber(parent: Record<string, unknown>, key: string, path: string): number {+ const v = parent[key];+ if (typeof v !== 'number' || !Number.isFinite(v)) {+ throw new PodTemplateValidationError(`field "${key}" must be a finite number`, path);+ }+ return v;+}++function requireBoolean(parent: Record<string, unknown>, key: string, path: string): boolean {+ const v = parent[key];+ if (typeof v !== 'boolean') {+ throw new PodTemplateValidationError(`field "${key}" must be a boolean`, path);+ }+ return v;+}++function requireArray<T>(parent: Record<string, unknown>, key: string, path: string,+ itemValidator: (item: unknown, ipath: string) => T): T[] {+ const v = parent[key];+ if (!Array.isArray(v)) {+ throw new PodTemplateValidationError(`field "${key}" must be an array`, path);+ }+ return v.map((item, idx) => itemValidator(item, `${path}/${key}[${idx}]`));+}++function validatePodAgent(item: unknown, path: string): PodAgent {+ if (!isObject(item)) throw new PodTemplateValidationError('agent must be an object', path);+ return {+ role: requireString(item, 'role', path),+ agentType: requireString(item, 'agentType', path),+ description: requireString(item, 'description', path),+ preferLocal: requireBoolean(item, 'preferLocal', path),+ };+}++function validatePodBench(item: unknown, path: string): PodBench {+ if (!isObject(item)) throw new PodTemplateValidationError('bench must be an object', path);+ const name = requireString(item, 'name', path);+ const description = requireString(item, 'description', path);+ const successCriteria = requireArray(item, 'successCriteria', path, (s, sp) => {+ if (typeof s !== 'string' || s.length === 0) {+ throw new PodTemplateValidationError('successCriteria entries must be non-empty strings', sp);+ }+ return s;+ });+ if (successCriteria.length === 0) {+ throw new PodTemplateValidationError('bench.successCriteria must have β₯1 entry', path);+ }+ const scheduleHours = requireNumber(item, 'scheduleHours', path);+ if (scheduleHours < 1) {+ throw new PodTemplateValidationError('bench.scheduleHours must be β₯1', path);+ }+ return { name, description, successCriteria, scheduleHours };+}++function validateAuditReadView(item: unknown, path: string): PodAuditReadView {+ if (!isObject(item)) {+ throw new PodTemplateValidationError('auditReadView must be an object', path);+ }+ const includedEventTypes = requireArray(item, 'includedEventTypes', path, (s, sp) => {+ if (typeof s !== 'string' || s.length === 0) {+ throw new PodTemplateValidationError('includedEventTypes entries must be non-empty strings', sp);+ }+ return s;+ });+ const retentionDays = requireNumber(item, 'retentionDays', path);+ if (retentionDays < 1) {+ throw new PodTemplateValidationError('auditReadView.retentionDays must be β₯1', path);+ }+ return { includedEventTypes, retentionDays };+}++// POSIX cron β five or six space-separated fields. Permissive on field+// contents (digits, *, -, /, ,) β actual cron evaluation happens at schedule+// time. We only catch obviously malformed values here.+const CRON_RE = /^([\d*/,\-]+\s+){4,5}[\d*/,\-]+$/;++/**+ * Validate `json` and return a typed `PodTemplate`. Throws+ * `PodTemplateValidationError` with a JSON-pointer-style path on failure.+ *+ * Used by:+ * - `business_pod_validate` MCP tool β returns the error verbatim+ * - `pod-tick.mjs` β pre-flight check before any pod execution+ * - any external schema-loader that wants typed templates+ */+export function validatePodTemplate(json: unknown): PodTemplate {+ if (!isObject(json)) {+ throw new PodTemplateValidationError('pod-template must be a JSON object', '/');+ }+ const name = requireString(json, 'name', '/');+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {+ throw new PodTemplateValidationError('name must be lowercase-kebab (e.g. "sales")', '/');+ }+ const displayName = requireString(json, 'displayName', '/');+ const roomId = requireString(json, 'roomId', '/');+ if (!/^[A-Za-z0-9_.\-:/@#]+$/.test(roomId)) {+ throw new PodTemplateValidationError(+ 'roomId may only contain [A-Za-z0-9_.\\-:/@#]',+ '/',+ );+ }+ const agents = requireArray(json, 'agents', '/', validatePodAgent);+ if (agents.length === 0) {+ throw new PodTemplateValidationError('agents must have β₯1 entry', '/');+ }+ const allowedMcpTools = requireArray(json, 'allowedMcpTools', '/', (t, tp) => {+ if (typeof t !== 'string' || t.length === 0) {+ throw new PodTemplateValidationError(+ 'allowedMcpTools entries must be non-empty strings',+ tp,+ );+ }+ return t;+ });+ if (allowedMcpTools.length === 0) {+ throw new PodTemplateValidationError('allowedMcpTools must have β₯1 entry', '/');+ }+ const bench = validatePodBench(json.bench, '/bench');+ const piiPolicy = requireString(json, 'piiPolicy', '/');+ if (!PII_POLICIES.includes(piiPolicy as PiiPolicy)) {+ throw new PodTemplateValidationError(+ `piiPolicy must be one of: ${PII_POLICIES.join(', ')}`,+ '/',+ );+ }+ const budgetUsdMonthly = requireNumber(json, 'budgetUsdMonthly', '/');+ if (budgetUsdMonthly < 0) {+ throw new PodTemplateValidationError('budgetUsdMonthly must be β₯0', '/');+ }+ const budgetUsdPerRun = requireNumber(json, 'budgetUsdPerRun', '/');+ if (budgetUsdPerRun < 0) {+ throw new PodTemplateValidationError('budgetUsdPerRun must be β₯0', '/');+ }+ if (budgetUsdMonthly > 0 && budgetUsdPerRun > budgetUsdMonthly) {+ throw new PodTemplateValidationError(+ 'budgetUsdPerRun must not exceed budgetUsdMonthly',+ '/',+ );+ }+ const preferLocalExecution = requireBoolean(json, 'preferLocalExecution', '/');+ const cronSchedule = requireString(json, 'cronSchedule', '/');+ if (!CRON_RE.test(cronSchedule)) {+ throw new PodTemplateValidationError(+ 'cronSchedule must be a POSIX cron expression (5 or 6 fields)',+ '/',+ );+ }+ const auditReadView = validateAuditReadView(json.auditReadView, '/auditReadView');++ let reservationExpiryMs: number | undefined;+ if (json.reservationExpiryMs !== undefined) {+ const v = requireNumber(json, 'reservationExpiryMs', '/');+ // ADR-164.1 Β§3.2 β bounded to [5_000, 300_000] ms.+ if (v < 5_000 || v > 300_000) {+ throw new PodTemplateValidationError(+ 'reservationExpiryMs must be within [5000, 300000] ms (ADR-164.1 Β§3.2)',+ '/',+ );+ }+ reservationExpiryMs = v;+ }++ return {+ name,+ displayName,+ roomId,+ agents,+ allowedMcpTools,+ bench,+ piiPolicy: piiPolicy as PiiPolicy,+ budgetUsdMonthly,+ budgetUsdPerRun,+ preferLocalExecution,+ cronSchedule,+ auditReadView,+ reservationExpiryMs,+ };+}++/**+ * Known ruflo agent types β kept in sync with src/commands/agent.ts AGENT_TYPES.+ * The list is duplicated here intentionally so pod-tick.mjs can run without+ * importing the entire commands module.+ *+ * If a new agent type is added to AGENT_TYPES, mirror it here.+ */+export const KNOWN_AGENT_TYPES = [+ 'coder',+ 'researcher',+ 'tester',+ 'reviewer',+ 'architect',+ 'system-architect',+ 'coordinator',+ 'analyst',+ 'optimizer',+ 'security-architect',+ 'security-auditor',+ 'memory-specialist',+ 'swarm-specialist',+ 'performance-engineer',+ 'core-architect',+ 'test-architect',+ 'planner',+ 'task-orchestrator',+ 'perf-analyzer',+ 'backend-dev',+ 'api-docs',+ 'cicd-engineer',+ 'code-analyzer',+ 'database-specialist',+ // ADR-164 Phase 3 β added for the marketing/hr pods (content drafting ++ // onboarding-template generation). Mirror this addition in the JS copy+ // inside plugins/ruflo-business-pods/scripts/pod-tick.mjs.+ 'base-template-generator',+] as const;diff --git a/v3/@claude-flow/cli/src/mcp-client.ts b/v3/@claude-flow/cli/src/mcp-client.tsindex 072d0dd5f8..4efe5f7244 100644--- a/v3/@claude-flow/cli/src/mcp-client.ts+++ b/v3/@claude-flow/cli/src/mcp-client.ts@@ -53,6 +53,15 @@ import { metaharnessTools } from './mcp-tools/metaharness-tools.js';// agenticow@~0.2.3 β Copy-On-Write memory branching tools (162-byte branches);// optional runtime dep, every handler returns `{degraded: true}` when missing.import { agenticowTools } from './mcp-tools/agenticow-tools.js';+// ADR-164 β AgentBBS federated business-domain BBS rooms (Phase 1).+// Optional runtime dep, every handler returns `{degraded: true}` when missing.+import { agentbbsTools } from './mcp-tools/agentbbs-tools.js';+// ADR-164 Phase 2 β Business-pod template validation (pure local, no optional deps).+import { businessPodTools } from './mcp-tools/business-pod-tools.js';+// ADR-164 Phase 4 Β§5.1.8 β http_fetch MCP tool (secure-by-default HTTP probe+// for ops-pod synthetic-endpoint benches). Default-rejects private addresses+// + auth headers; opt-in via CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE / _AUTH=1.+import { httpFetchTools } from './mcp-tools/http-fetch-tools.js';// #1916: coverage-aware routing tools β defined in ruvector/coverage-tools.ts// but were never registered, so the `ruflo hooks coverage-*` CLI subcommands// failed with `Tool not found: hooks_coverage-route`.@@ -139,6 +148,13 @@ registerTools([...metaharnessTools,// agenticow@~0.2.3 β COW memory branching (4 tools, graceful-degraded when missing)...agenticowTools,+ // ADR-164 β AgentBBS federated business-domain BBS rooms (4 tools, Phase 1, graceful-degraded)+ ...agentbbsTools,+ // ADR-164 Phase 2 + Phase 3 β business_pod_validate + business_pod_route_backend+ // (2 tools, no optional dep β schema validator + Β§3.4 domain-affinity router)+ ...businessPodTools,+ // ADR-164 Phase 4 Β§5.1.8 β http_fetch (1 tool, secure-by-default HTTP probe)+ ...httpFetchTools,]);/**diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.tsnew file mode 100644index 0000000000..e47408a94e--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-tools.ts@@ -0,0 +1,426 @@+/**+ * AgentBBS MCP Tools β Federated business-domain BBS room surface (ADR-164 Phase 1).+ *+ * Exposes the `agentbbs@~0.1.0` (a sibling BBS-style federation peer by the same+ * author as ruflo) as MCP tools so ruflo agents can register business rooms+ * (#sales, #finance, #marketing, ...), publish/watch typed envelopes, and+ * mint single-use human-join tokens for SSH/web cockpit access.+ *+ * Motivation:+ * ADR-164 wires the "business autopilot" cockpit on top of the existing+ * ruflo federation primitives (FederationEnvelope, PII pipeline, budget+ * circuit breaker). The 4 tools here are the ruflo-side handles into the+ * agentbbs Rust workspace (`crates/agentbbs-federation/` and+ * `crates/agentbbs-mcp/`) that already implement Ed25519-signed envelopes+ * and an MCP transport. Phase 1 ships the surface; Phases 2-5 wire deeper.+ *+ * Architectural constraint (mirrors metaharness-tools.ts / agenticow-tools.ts):+ * - `agentbbs` lives in `optionalDependencies` β must NOT be a hard runtime dep+ * - When the package is missing, every tool returns+ * `{success: true, degraded: true, reason: 'agentbbs-not-found'}`+ * so callers see one contract regardless of install state+ * - Phase 1: polling-based watch (streaming subscriptions are Phase 4)+ *+ * @module @claude-flow/cli/mcp-tools/agentbbs+ */++import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';+import { resolve, isAbsolute, join } from 'node:path';+import { randomBytes, createHash } from 'node:crypto';+import type { MCPTool } from './types.js';+import { getProjectCwd } from './types.js';++const PACKAGE_NAME = 'agentbbs';++// Cache: amortize dynamic-import cost across handler calls.+// null = not yet attempted; false = unavailable; module = loaded.+let _agentbbsMod: any = null;+let _loadAttempted = false;++async function loadAgentbbs(): Promise<any | null> {+ if (_loadAttempted) return _agentbbsMod || null;+ _loadAttempted = true;+ try {+ _agentbbsMod = await import(PACKAGE_NAME);+ return _agentbbsMod;+ } catch (err: any) {+ if (err && (err.code === 'ERR_MODULE_NOT_FOUND' || err.code === 'MODULE_NOT_FOUND' ||+ /Cannot find (module|package)/i.test(String(err?.message)))) {+ _agentbbsMod = false;+ return null;+ }+ throw err;+ }+}++function degradedResult(reason: string): { success: true; degraded: true; reason: string } {+ return { success: true, degraded: true, reason };+}++function resolveBasePath(input?: string): string {+ const p = input && typeof input === 'string' && input.length > 0+ ? input+ : '.agentbbs';+ if (/\.\.[\\/]|\0/.test(p)) throw new Error('basePath contains disallowed characters');+ const abs = isAbsolute(p) ? p : resolve(getProjectCwd(), p);+ return abs;+}++function validateRoomLabel(label: string): string {+ if (!label || typeof label !== 'string') throw new Error('roomLabel is required');+ if (label.length > 128) throw new Error('roomLabel exceeds 128 chars');+ // Rooms are conventionally `#sales`, `#finance`, etc. β keep `#` in the allow-list.+ if (!/^[A-Za-z0-9_.\-:/@#]+$/.test(label)) {+ throw new Error('roomLabel may only contain [A-Za-z0-9_.\\-:/@#]');+ }+ return label;+}++function validateRoomId(roomId: string): string {+ if (!roomId || typeof roomId !== 'string') throw new Error('roomId is required');+ if (roomId.length > 128) throw new Error('roomId exceeds 128 chars');+ if (!/^[A-Za-z0-9_.\-:/@#]+$/.test(roomId)) {+ throw new Error('roomId may only contain [A-Za-z0-9_.\\-:/@#]');+ }+ return roomId;+}++function ensureDir(dir: string): void {+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+}++function roomIdFromLabel(label: string): string {+ // Stable, deterministic roomId β strip leading `#`, lowercase, and append a+ // short hash so we don't collide across two rooms with the same canonical+ // label but different policies. Phase 1: deterministic over (label).+ const norm = label.replace(/^#/, '').toLowerCase();+ const h = createHash('sha256').update(`agentbbs:room:${norm}`).digest('hex').slice(0, 8);+ return `${norm}-${h}`;+}++function roomLogPath(basePath: string, roomId: string): string {+ return join(basePath, `room-${roomId}.jsonl`);+}++function roomsRegistryPath(basePath: string): string {+ return join(basePath, 'rooms.json');+}++interface BbsEnvelope {+ envelopeId: string;+ roomId: string;+ seq: number;+ msgType: string;+ payload: unknown;+ timestamp: string;+ signature?: string;+}++function readEnvelopes(path: string): BbsEnvelope[] {+ if (!existsSync(path)) return [];+ const raw = readFileSync(path, 'utf-8');+ const out: BbsEnvelope[] = [];+ for (const line of raw.split(/\r?\n/)) {+ if (!line.trim()) continue;+ try { out.push(JSON.parse(line)); } catch { /* skip malformed line */ }+ }+ return out;+}++function nextSeq(path: string): number {+ const env = readEnvelopes(path);+ if (env.length === 0) return 1;+ return (env[env.length - 1].seq ?? env.length) + 1;+}++/**+ * Ephemeral per-process Ed25519 keypair for human-join token signing.+ * Phase 1 contract: keys are NOT persisted across process restart β every+ * invocation can mint tokens but cross-process replay protection is the+ * agentbbs server's responsibility (nonce JTI tracking, per ADR-164 Β§3.2.4).+ * Phase 2+ will wire this to the existing federation Ed25519 keypair.+ */+let _signingKey: { priv: Uint8Array; pub: Uint8Array } | null = null;+async function getSigningKey(): Promise<{ priv: Uint8Array; pub: Uint8Array }> {+ if (_signingKey) return _signingKey;+ // Use @noble/ed25519 (already a hard dep of @claude-flow/cli for IPFS signing).+ const ed: any = await import('@noble/ed25519');+ const priv = ed.utils.randomPrivateKey+ ? ed.utils.randomPrivateKey()+ : randomBytes(32);+ const pub: Uint8Array = await (ed.getPublicKeyAsync ?? ed.getPublicKey)(priv);+ _signingKey = { priv, pub };+ return _signingKey;+}++function base64url(buf: Buffer | Uint8Array): string {+ return Buffer.from(buf).toString('base64')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ .replace(/=+$/, '');+}++export const agentbbsTools: MCPTool[] = [+ {+ name: 'federation_bbs_register',+ description: 'agentbbs@~0.1.0 β Register a BBS room as a named federation peer (ADR-164 Phase 1). Maps a business-domain label like "#sales" or "#finance" to a stable roomId and emits an attested PeerHello envelope. Use when you are scaffolding the business-autopilot cockpit and need a room handle that subsequent publish/watch calls can target. Calling FederationCoordinator.joinPeer() directly is wrong because it bypasses the room policy bag (PII mode, budget cap, preferLocal routing) that the BBS plugin layers on top. Optional dep β degrades to {degraded:true} when missing.',+ category: 'federation',+ tags: ['agentbbs', 'federation', 'bbs', 'register', 'adr-164'],+ inputSchema: {+ type: 'object',+ properties: {+ basePath: {+ type: 'string',+ description: 'Directory where BBS room state is persisted (defaults to <cwd>/.agentbbs).',+ },+ roomLabel: {+ type: 'string',+ description: 'Human-readable room label, e.g. "#sales" or "finance". May include alnum + _.-:/@# .',+ },+ agentbbsBin: {+ type: 'string',+ description: 'Optional explicit path to the agentbbs binary. Reserved for Phase 2 wire-up; ignored in Phase 1.',+ },+ },+ required: ['roomLabel'],+ },+ handler: async (input) => {+ // Validate inputs FIRST so callers see deterministic errors regardless of+ // optional-dep state. Degradation is a runtime-state branch, not a way+ // to mask malformed requests.+ const roomLabel = validateRoomLabel(String(input.roomLabel));+ const basePath = resolveBasePath(input.basePath as string | undefined);++ const api = await loadAgentbbs();+ if (!api) return degradedResult('agentbbs-not-found');++ ensureDir(basePath);++ const roomId = roomIdFromLabel(roomLabel);+ const registryPath = roomsRegistryPath(basePath);+ const registry: Record<string, { roomId: string; roomLabel: string; registeredAt: string; trustLevel: string }> =+ existsSync(registryPath) ? JSON.parse(readFileSync(registryPath, 'utf-8')) : {};++ // Idempotent β re-registering the same label updates timestamp but keeps id stable.+ const entry = {+ roomId,+ roomLabel,+ registeredAt: new Date().toISOString(),+ trustLevel: 'attested',+ };+ registry[roomId] = entry;+ writeFileSync(registryPath, JSON.stringify(registry, null, 2));++ // Emit a synthetic PeerHello envelope into the room log so watchers see the join.+ const logPath = roomLogPath(basePath, roomId);+ const env: BbsEnvelope = {+ envelopeId: base64url(randomBytes(12)),+ roomId,+ seq: nextSeq(logPath),+ msgType: 'PeerHello',+ payload: { roomLabel, trustLevel: 'attested' },+ timestamp: entry.registeredAt,+ };+ appendFileSync(logPath, JSON.stringify(env) + '\n');++ // nodeId: deterministic per (cwd, roomId) so re-registers reuse identity.+ const nodeId = createHash('sha256')+ .update(`agentbbs:node:${basePath}:${roomId}`)+ .digest('hex')+ .slice(0, 16);++ return {+ success: true,+ roomId,+ nodeId,+ trustLevel: 'attested' as const,+ };+ },+ },+ {+ name: 'federation_bbs_publish',+ description: 'agentbbs β Publish a domain event from a pod agent to a BBS room (ADR-164 Phase 1). Wraps the payload in a ReplicateMessage envelope (envelopeId, seq, ts, msgType, payload) and appends it to the room log. Use when an agent has produced a typed event (pod-status, task-result, alert, human-override-ack, bench-result) that the human cockpit or other pods need to see. Storing into raw memory_store is wrong because it skips the room-scoped budget cap, PII pipeline gating, and monotonic seq numbering that ADR-164 Β§3.2.2 requires. Optional dep β degrades to {degraded:true} when missing.',+ category: 'federation',+ tags: ['agentbbs', 'federation', 'bbs', 'publish', 'adr-164'],+ inputSchema: {+ type: 'object',+ properties: {+ basePath: {+ type: 'string',+ description: 'Directory where BBS room state is persisted (defaults to <cwd>/.agentbbs).',+ },+ roomId: {+ type: 'string',+ description: 'Target room identifier as returned by federation_bbs_register.',+ },+ msgType: {+ type: 'string',+ description: 'Typed event kind (pod-status / task-result / alert / human-override-ack / bench-result).',+ },+ payload: {+ type: 'object',+ description: 'Event-specific JSON-serializable payload.',+ },+ signature: {+ type: 'string',+ description: 'Optional Ed25519 signature over the canonical envelope bytes. Phase 1: pass-through.',+ },+ },+ required: ['roomId', 'msgType', 'payload'],+ },+ handler: async (input) => {+ const basePath = resolveBasePath(input.basePath as string | undefined);+ const roomId = validateRoomId(String(input.roomId));+ const msgType = String(input.msgType ?? '');+ if (!msgType) throw new Error('msgType is required');+ if (msgType.length > 64 || !/^[A-Za-z0-9_-]+$/.test(msgType)) {+ throw new Error('msgType must be alnum + _ - and β€64 chars');+ }+ if (typeof input.payload !== 'object' || input.payload === null) {+ throw new Error('payload must be a JSON object');+ }++ const api = await loadAgentbbs();+ if (!api) return degradedResult('agentbbs-not-found');++ ensureDir(basePath);+ const logPath = roomLogPath(basePath, roomId);+ const env: BbsEnvelope = {+ envelopeId: base64url(randomBytes(12)),+ roomId,+ seq: nextSeq(logPath),+ msgType,+ payload: input.payload,+ timestamp: new Date().toISOString(),+ signature: input.signature ? String(input.signature) : undefined,+ };+ appendFileSync(logPath, JSON.stringify(env) + '\n');++ // Phase 1: recipientHopCount is always 0 (single-node). Phase 4+ will+ // surface real hop counts from the WG mesh transport.+ return {+ success: true,+ envelopeId: env.envelopeId,+ recipientHopCount: 0,+ };+ },+ },+ {+ name: 'federation_bbs_watch',+ description: 'agentbbs β Poll recent envelopes from a BBS room (ADR-164 Phase 1). Returns envelopes newer than the optional sinceEnvelopeId, up to limit. Use when a pod agent needs to see incoming human overrides, new tasks, or peer events posted to its room. Polling memory_search for the room namespace is wrong because it loses the monotonic seq ordering and re-runs PII gating per query; this tool reads the canonical envelope log directly. Phase 1 is polling β Phase 4 layers streaming on the same surface. Optional dep β degrades to {degraded:true} when missing.',+ category: 'federation',+ tags: ['agentbbs', 'federation', 'bbs', 'watch', 'adr-164'],+ inputSchema: {+ type: 'object',+ properties: {+ basePath: {+ type: 'string',+ description: 'Directory where BBS room state is persisted (defaults to <cwd>/.agentbbs).',+ },+ roomId: {+ type: 'string',+ description: 'Room identifier to watch.',+ },+ sinceEnvelopeId: {+ type: 'string',+ description: 'Only return envelopes strictly after this id. Omit to return the most recent window.',+ },+ limit: {+ type: 'integer',+ description: 'Maximum envelopes to return (default 50, max 500).',+ },+ },+ required: ['roomId'],+ },+ handler: async (input) => {+ const basePath = resolveBasePath(input.basePath as string | undefined);+ const roomId = validateRoomId(String(input.roomId));++ const api = await loadAgentbbs();+ if (!api) return degradedResult('agentbbs-not-found');++ const limitRaw = typeof input.limit === 'number' ? input.limit : 50;+ const limit = Math.max(1, Math.min(500, Math.trunc(limitRaw)));+ const sinceEnvelopeId = input.sinceEnvelopeId ? String(input.sinceEnvelopeId) : undefined;++ const logPath = roomLogPath(basePath, roomId);+ const all = readEnvelopes(logPath);++ let slice = all;+ if (sinceEnvelopeId) {+ const idx = all.findIndex(e => e.envelopeId === sinceEnvelopeId);+ slice = idx >= 0 ? all.slice(idx + 1) : all;+ }+ const envelopes = slice.slice(-limit);+ return {+ success: true,+ roomId,+ envelopes,+ count: envelopes.length,+ hasMore: slice.length > envelopes.length,+ };+ },+ },+ {+ name: 'federation_bbs_human_join',+ description: 'agentbbs β Mint a single-use Ed25519-signed token a human business owner presents to the agentbbs SSH/web front door to join a room (ADR-164 Β§3.2.4). Returns webUrl + sshCommand + handshakeToken + expiresAt. Use when the cockpit operator needs scoped, time-limited access to a room without sharing the federation root keypair. Issuing a permanent bearer token is wrong because the agentbbs server enforces single-use JTI replay protection and the 15-min default TTL β a long-lived token defeats both. Optional dep β degrades to {degraded:true} when missing.',+ category: 'federation',+ tags: ['agentbbs', 'federation', 'bbs', 'human-join', 'token', 'adr-164'],+ inputSchema: {+ type: 'object',+ properties: {+ roomId: {+ type: 'string',+ description: 'Room the token authorizes.',+ },+ ttlSeconds: {+ type: 'integer',+ description: 'Token lifetime in seconds. Max 900 (15 min). Default 300.',+ },+ },+ required: ['roomId'],+ },+ handler: async (input) => {+ const roomId = validateRoomId(String(input.roomId));++ const api = await loadAgentbbs();+ if (!api) return degradedResult('agentbbs-not-found');++ const ttlRaw = typeof input.ttlSeconds === 'number' ? input.ttlSeconds : 300;+ const ttlSeconds = Math.max(30, Math.min(900, Math.trunc(ttlRaw)));+ const now = Date.now();+ const expiresAt = new Date(now + ttlSeconds * 1000).toISOString();+ const nonce = base64url(randomBytes(16));++ const payload = { roomId, nonce, expiresAt };+ const canonical = JSON.stringify(payload);++ const ed: any = await import('@noble/ed25519');+ const { priv, pub } = await getSigningKey();+ const sigBytes: Uint8Array = await (ed.signAsync ?? ed.sign)(+ new TextEncoder().encode(canonical),+ priv,+ );++ // Token format: base64url(JSON{payload, sig, pub}). Single string, easy+ // to paste into an SSH command line. The verifier reconstructs canonical+ // bytes from payload and checks sig against pub.+ const token = base64url(Buffer.from(JSON.stringify({+ payload,+ sig: base64url(sigBytes),+ pub: base64url(pub),+ })));++ const webUrl = `https://agentbbs.local/rooms/${encodeURIComponent(roomId)}?token=${token}`;+ const sshCommand = `ssh -p 2222 agentbbs.local -- join ${roomId} ${token}`;++ return {+ success: true,+ webUrl,+ sshCommand,+ handshakeToken: token,+ expiresAt,+ };+ },+ },+];diff --git a/v3/@claude-flow/cli/src/mcp-tools/business-pod-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/business-pod-tools.tsnew file mode 100644index 0000000000..0f45ec3277--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/business-pod-tools.ts@@ -0,0 +1,182 @@+/**+ * Business-pod MCP tools β ADR-164 Phase 2 + Phase 3.+ *+ * Phase 2 surfaces pod-template validation (`business_pod_validate`).+ * Phase 3 adds the domain-affinity routing decision (`business_pod_route_backend`)+ * so any caller (agent, /loop driver, CI workflow) can ask "which backend+ * should @metaharness/router prefer for this pod?" without re-implementing+ * the Β§3.4 rules. The decision is structural and deterministic β no learned+ * weights, no schedule, just (preferLocalExecution, budgetUsdMonthly).+ *+ * Both tools accept either a pod template *object* or a string *path* to a+ * JSON file. The path form is provided so /loop drivers can avoid loading+ * the template themselves; the object form is for callers that already have+ * the validated template in hand.+ *+ * @module @claude-flow/cli/mcp-tools/business-pod+ */++import { readFileSync, existsSync } from 'node:fs';+import { resolve, isAbsolute } from 'node:path';++import type { MCPTool } from './types.js';+import {+ validatePodTemplate,+ PodTemplateValidationError,+ KNOWN_AGENT_TYPES,+} from '../business-pods/pod-schema.js';+import {+ selectAgentBackend,+ CLOUD_BUDGET_THRESHOLD_USD,+ type BackendDecision,+} from '../business-pods/domain-affinity-policy.js';++/**+ * Load a pod template from either an in-memory object or a JSON-file path.+ * Returns either the parsed (unvalidated) JSON or an `error` shape suitable+ * for direct return from an MCP handler.+ */+function loadTemplate(+ input: { podTemplate?: unknown; podTemplatePath?: unknown },+): { ok: true; raw: unknown } | { ok: false; error: string; path: string } {+ if (input.podTemplate !== undefined && input.podTemplate !== null) {+ if (typeof input.podTemplate !== 'object' || Array.isArray(input.podTemplate)) {+ return { ok: false, error: 'podTemplate must be a JSON object', path: '/podTemplate' };+ }+ return { ok: true, raw: input.podTemplate };+ }+ if (typeof input.podTemplatePath === 'string' && input.podTemplatePath.length > 0) {+ const abs = isAbsolute(input.podTemplatePath)+ ? input.podTemplatePath+ : resolve(process.cwd(), input.podTemplatePath);+ if (!existsSync(abs)) {+ return { ok: false, error: `pod template file not found: ${abs}`, path: '/podTemplatePath' };+ }+ try {+ const raw = JSON.parse(readFileSync(abs, 'utf-8'));+ return { ok: true, raw };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ return { ok: false, error: `failed to parse pod template JSON: ${msg}`, path: '/podTemplatePath' };+ }+ }+ return {+ ok: false,+ error: 'either podTemplate (object) or podTemplatePath (string) must be provided',+ path: '/',+ };+}++export const businessPodTools: MCPTool[] = [+ {+ name: 'business_pod_validate',+ description: 'ADR-164 Phase 2 β Validate a business-pod template JSON against the schema in ADR-164 Β§3.3 (name, agents[], allowedMcpTools, bench, piiPolicy, budgets, cronSchedule, auditReadView, reservationExpiryMs bounded by ADR-164.1 Β§3.2). Use when a /loop driver or CI workflow needs to pre-flight a pod template before pod-tick.mjs reaches it β surfacing validation as JSON keeps the optional-dep degraded path clean. Hand-parsing the JSON in the caller is wrong because it skips the JSON-pointer error path and the reservationExpiryMs [5000, 300000] ms bound check that ADR-164.1 mandates. Pair with business_pod_validate -> pod-tick.mjs in the sales-pod smoke contract.',+ category: 'business-pods',+ tags: ['business-pods', 'pod-template', 'validation', 'adr-164', 'adr-164.1'],+ inputSchema: {+ type: 'object',+ properties: {+ podTemplate: {+ type: 'object',+ description: 'The pod template object to validate. Must conform to the PodTemplate interface from ADR-164 Β§3.3.',+ },+ },+ required: ['podTemplate'],+ },+ handler: async (input) => {+ if (typeof input.podTemplate !== 'object' || input.podTemplate === null) {+ return {+ success: false,+ valid: false,+ error: 'podTemplate must be a JSON object',+ path: '/',+ };+ }+ try {+ const template = validatePodTemplate(input.podTemplate);+ // Lightweight agent-type sanity check β surface unknown types as a+ // warning rather than a hard failure so operators can prototype with+ // not-yet-registered roles. pod-tick.mjs enforces the hard check.+ const unknownAgents = template.agents+ .map((a) => a.agentType)+ .filter((t) => !(KNOWN_AGENT_TYPES as readonly string[]).includes(t));+ return {+ success: true,+ valid: true,+ template,+ warnings: unknownAgents.length > 0+ ? [`unknown agent types (pod-tick.mjs will reject): ${unknownAgents.join(', ')}`]+ : [],+ };+ } catch (err) {+ if (err instanceof PodTemplateValidationError) {+ return {+ success: false,+ valid: false,+ error: err.message,+ path: err.path,+ };+ }+ throw err;+ }+ },+ },+ {+ name: 'business_pod_route_backend',+ description: 'ADR-164 Phase 3 β Compute the domain-affinity routing decision for a business pod per ADR-164 Β§3.4 and return {backend, reason}. The three backends are local-stdio (preferLocalExecution=true), cloud-managed (preferLocalExecution=false AND budgetUsdMonthly >= 50), and remote-peer (everything else β small-budget non-local pods route through a federation peer node). Use when a /loop driver, @metaharness/router policy hook, or operator CLI needs the structural routing pick BEFORE the cost-optimal KRR step β surfacing this as an MCP tool keeps the rule auditable from the pod template alone and lets non-TS callers reach it. Re-implementing the rule in the caller is wrong because it forks the Β§3.4 source-of-truth and skips the {success,valid,error,path} envelope shape callers already rely on from business_pod_validate. Pair with business_pod_validate when pre-flighting a template, since this tool also runs full schema validation and degrades to the same error shape on malformed input. Threshold lives in CLOUD_BUDGET_THRESHOLD_USD in domain-affinity-policy.ts β keep that constant and this description aligned.',+ category: 'business-pods',+ tags: ['business-pods', 'pod-template', 'routing', 'domain-affinity', 'adr-164'],+ inputSchema: {+ type: 'object',+ properties: {+ podTemplate: {+ type: 'object',+ description: 'In-memory pod template object. One of podTemplate or podTemplatePath is required.',+ },+ podTemplatePath: {+ type: 'string',+ description: 'Absolute or cwd-relative path to a pod template JSON file. One of podTemplate or podTemplatePath is required.',+ },+ },+ },+ handler: async (input) => {+ const loaded = loadTemplate(input);+ if (!loaded.ok) {+ return {+ success: false,+ valid: false,+ error: loaded.error,+ path: loaded.path,+ };+ }++ let template;+ try {+ template = validatePodTemplate(loaded.raw);+ } catch (err) {+ if (err instanceof PodTemplateValidationError) {+ return {+ success: false,+ valid: false,+ error: err.message,+ path: err.path,+ };+ }+ throw err;+ }++ const decision: BackendDecision = selectAgentBackend(template);+ return {+ success: true,+ valid: true,+ backend: decision.backend,+ reason: decision.reason,+ pod: {+ name: template.name,+ preferLocalExecution: template.preferLocalExecution,+ budgetUsdMonthly: template.budgetUsdMonthly,+ },+ };+ },+ },+];diff --git a/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.tsnew file mode 100644index 0000000000..cc8a5833dc--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts@@ -0,0 +1,356 @@+/**+ * http_fetch MCP tool β ADR-164 Β§5.1.8.+ *+ * The Operations business pod (templates/ops.json) references `http_fetch` as+ * an allowed MCP tool for the synthetic-endpoint availability bench (probe+ * 200/500 from a configured URL, escalate to #ops on 500-rate spikes).+ * Phase 3 left this as a TODO; Phase 4 ships the tool with secure-by-default+ * gating per the Β§5.1.8 contract: URL allowlist (no file://, ftp://, no+ * RFC-1918 / loopback unless explicitly enabled), header sanitization (no+ * auth pass-through unless explicitly enabled), hard timeout via+ * AbortController, response truncation, default User-Agent.+ *+ * Architectural constraints (load-bearing):+ * - DEFAULT-REFUSES private addresses + loopback (CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 opt-in)+ * - DEFAULT-REFUSES Authorization / Cookie / X-Auth-* (CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1 opt-in)+ * - hard timeout 30s default, 60s ceiling+ * - response truncated to 256KB default, 1MB ceiling+ * - no redirects auto-followed beyond fetch's default; status reported as-is+ *+ * @module @claude-flow/cli/mcp-tools/http-fetch+ */++import type { MCPTool } from './types.js';++const DEFAULT_TIMEOUT_MS = 30_000;+const MAX_TIMEOUT_MS = 60_000;+const DEFAULT_MAX_RESPONSE_BYTES = 256 * 1024; // 256 KB+const MAX_RESPONSE_BYTES = 1024 * 1024; // 1 MB+const DEFAULT_USER_AGENT = 'ruflo-http-fetch/1.0';++const FORBIDDEN_HEADER_PREFIXES = ['x-auth-', 'x-api-key'] as const;+const FORBIDDEN_HEADERS_EXACT = ['authorization', 'cookie', 'set-cookie', 'proxy-authorization'] as const;++export class HttpFetchValidationError extends Error {+ constructor(message: string, public readonly code: string) {+ super(message);+ this.name = 'HttpFetchValidationError';+ }+}++/**+ * Decide whether the URL is permitted under the default secure-by-default+ * allowlist. Block file://, ftp://, RFC-1918 private addresses, loopback,+ * link-local β unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 is set.+ */+export function validateUrl(rawUrl: string): URL {+ let parsed: URL;+ try {+ parsed = new URL(rawUrl);+ } catch {+ throw new HttpFetchValidationError(`invalid URL: ${rawUrl}`, 'INVALID_URL');+ }+ const proto = parsed.protocol.toLowerCase();+ if (proto !== 'http:' && proto !== 'https:') {+ throw new HttpFetchValidationError(+ `protocol ${parsed.protocol} not allowed (only http: and https:)`,+ 'FORBIDDEN_PROTOCOL',+ );+ }+ const host = parsed.hostname.toLowerCase();+ const allowPrivate = process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE === '1';+ if (!allowPrivate && isPrivateOrLoopback(host)) {+ throw new HttpFetchValidationError(+ `host ${host} is loopback/private/link-local; set CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1 to override`,+ 'PRIVATE_ADDRESS',+ );+ }+ return parsed;+}++function isPrivateOrLoopback(host: string): boolean {+ if (host === 'localhost' || host === 'localhost.localdomain') return true;+ // IPv6 loopback+ if (host === '::1' || host === '[::1]') return true;+ // IPv4 numeric checks+ const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);+ if (m) {+ const a = Number(m[1]);+ const b = Number(m[2]);+ if (a === 0) return true; // 0.0.0.0/8+ if (a === 127) return true; // loopback+ if (a === 10) return true; // RFC1918+ if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918+ if (a === 192 && b === 168) return true; // RFC1918+ if (a === 169 && b === 254) return true; // link-local+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT+ return false;+ }+ // IPv6 bracketed addresses and other special forms β be conservative and+ // accept only public-looking literals. Reject obvious private/local forms.+ if (host.startsWith('fc') || host.startsWith('fd')) return true; // fc00::/7 ULA+ if (host.startsWith('fe80:')) return true; // link-local+ return false;+}++export function validateHeaders(headers: Record<string, string>): Record<string, string> {+ const allowAuth = process.env.CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH === '1';+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(headers)) {+ const lower = key.toLowerCase();+ if (!allowAuth) {+ if ((FORBIDDEN_HEADERS_EXACT as readonly string[]).includes(lower)) {+ throw new HttpFetchValidationError(+ `header "${key}" is not allowed without CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1`,+ 'FORBIDDEN_HEADER',+ );+ }+ if (FORBIDDEN_HEADER_PREFIXES.some((p) => lower.startsWith(p))) {+ throw new HttpFetchValidationError(+ `header "${key}" is not allowed without CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1`,+ 'FORBIDDEN_HEADER',+ );+ }+ }+ if (typeof value !== 'string') {+ throw new HttpFetchValidationError(+ `header "${key}" must be a string`,+ 'INVALID_HEADER_VALUE',+ );+ }+ out[key] = value;+ }+ return out;+}++function clampNumber(raw: unknown, defaultValue: number, max: number): number {+ if (raw === undefined || raw === null) return defaultValue;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) return defaultValue;+ return Math.min(Math.floor(n), max);+}++export interface HttpFetchResult {+ success: boolean;+ status: number;+ statusText: string;+ headers: Record<string, string>;+ body: string;+ bodyTruncated: boolean;+ bytesRead: number;+ durationMs: number;+ url: string;+ method: string;+ error?: string;+ errorCode?: string;+}++/**+ * Pure execution path so tests can call it without going through the MCP+ * dispatcher. Returns a result object (does not throw on validation failure+ * β it returns success: false with an errorCode).+ */+export async function httpFetchExecute(input: Record<string, unknown>): Promise<HttpFetchResult> {+ const startedAt = Date.now();+ const url = String(input.url ?? '');+ const method = String(input.method ?? 'GET').toUpperCase();+ if (!['GET', 'POST', 'HEAD'].includes(method)) {+ return {+ success: false,+ status: 0,+ statusText: '',+ headers: {},+ body: '',+ bodyTruncated: false,+ bytesRead: 0,+ durationMs: Date.now() - startedAt,+ url,+ method,+ error: `method ${method} not allowed (GET, POST, HEAD only)`,+ errorCode: 'INVALID_METHOD',+ };+ }++ let parsed: URL;+ try {+ parsed = validateUrl(url);+ } catch (e) {+ const err = e as HttpFetchValidationError;+ return {+ success: false,+ status: 0,+ statusText: '',+ headers: {},+ body: '',+ bodyTruncated: false,+ bytesRead: 0,+ durationMs: Date.now() - startedAt,+ url,+ method,+ error: err.message,+ errorCode: err.code ?? 'VALIDATION_ERROR',+ };+ }++ let headers: Record<string, string>;+ try {+ const raw = (input.headers ?? {}) as Record<string, string>;+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ throw new HttpFetchValidationError('headers must be an object', 'INVALID_HEADERS');+ }+ headers = validateHeaders(raw);+ } catch (e) {+ const err = e as HttpFetchValidationError;+ return {+ success: false,+ status: 0,+ statusText: '',+ headers: {},+ body: '',+ bodyTruncated: false,+ bytesRead: 0,+ durationMs: Date.now() - startedAt,+ url,+ method,+ error: err.message,+ errorCode: err.code ?? 'VALIDATION_ERROR',+ };+ }++ // Default UA if not set+ const hasUA = Object.keys(headers).some((k) => k.toLowerCase() === 'user-agent');+ if (!hasUA) headers['User-Agent'] = DEFAULT_USER_AGENT;++ const timeoutMs = clampNumber(input.timeoutMs, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);+ const maxResponseBytes = clampNumber(+ input.maxResponseBytes,+ DEFAULT_MAX_RESPONSE_BYTES,+ MAX_RESPONSE_BYTES,+ );+ const body = input.body !== undefined ? String(input.body) : undefined;++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);++ try {+ const response = await fetch(parsed.toString(), {+ method,+ headers,+ body: method === 'GET' || method === 'HEAD' ? undefined : body,+ signal: controller.signal,+ // Keep redirect default ('follow') β caller sees final status/url.+ });++ // Drain the body with byte budget. Use array-buffer first to bound size+ // deterministically before decoding to UTF-8.+ const reader = response.body?.getReader();+ let bytesRead = 0;+ let bodyTruncated = false;+ const chunks: Uint8Array[] = [];+ if (reader) {+ // eslint-disable-next-line no-constant-condition+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ if (value) {+ if (bytesRead + value.byteLength > maxResponseBytes) {+ const remaining = Math.max(0, maxResponseBytes - bytesRead);+ if (remaining > 0) chunks.push(value.slice(0, remaining));+ bytesRead += remaining;+ bodyTruncated = true;+ try { await reader.cancel('body-truncated'); } catch { /* ignore */ }+ break;+ }+ chunks.push(value);+ bytesRead += value.byteLength;+ }+ }+ }+ const combined = new Uint8Array(bytesRead);+ let offset = 0;+ for (const c of chunks) {+ combined.set(c, offset);+ offset += c.byteLength;+ }+ const decoder = new TextDecoder('utf-8', { fatal: false });+ const bodyText = decoder.decode(combined);++ const outHeaders: Record<string, string> = {};+ response.headers.forEach((v, k) => { outHeaders[k] = v; });++ return {+ success: true,+ status: response.status,+ statusText: response.statusText,+ headers: outHeaders,+ body: bodyText,+ bodyTruncated,+ bytesRead,+ durationMs: Date.now() - startedAt,+ url: parsed.toString(),+ method,+ };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ const aborted = msg.includes('aborted') || (e as { name?: string } | undefined)?.name === 'AbortError';+ return {+ success: false,+ status: 0,+ statusText: '',+ headers: {},+ body: '',+ bodyTruncated: false,+ bytesRead: 0,+ durationMs: Date.now() - startedAt,+ url: parsed.toString(),+ method,+ error: aborted ? `request aborted after ${timeoutMs}ms timeout` : msg,+ errorCode: aborted ? 'TIMEOUT' : 'FETCH_ERROR',+ };+ } finally {+ clearTimeout(timer);+ }+}++export const httpFetchTools: MCPTool[] = [+ {+ name: 'http_fetch',+ description: 'ADR-164 Β§5.1.8 β HTTP probe primitive for business-pod ops benches (synthetic 200/500 endpoint checks, third-party status pages). Default-secure: blocks file://, ftp://, RFC-1918 / loopback / link-local hosts unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE=1, and rejects Authorization / Cookie / X-Auth-* headers unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1. Hard 30s timeout (60s ceiling), response truncated to 256 KB (1 MB ceiling), default User-Agent ruflo-http-fetch/1.0. Use when a pod or smoke contract needs a guarded HTTP probe β calling Node fetch() directly is wrong because it skips the URL allowlist and header sanitization that ADR-164 mandates for autopilot mode. Pair with the ops-pod bench in plugins/ruflo-business-pods/templates/ops.json (the Β§4.4 synthetic-endpoint test).',+ category: 'business-pods',+ tags: ['business-pods', 'http', 'fetch', 'adr-164', 'security', 'ops-pod'],+ inputSchema: {+ type: 'object',+ properties: {+ url: {+ type: 'string',+ description: 'Absolute http:// or https:// URL. file://, ftp://, RFC-1918 / loopback / link-local blocked by default.',+ },+ method: {+ type: 'string',+ enum: ['GET', 'POST', 'HEAD'],+ description: 'HTTP method. Defaults to GET.',+ },+ timeoutMs: {+ type: 'number',+ description: 'Hard timeout in milliseconds. Default 30000, max 60000.',+ },+ maxResponseBytes: {+ type: 'number',+ description: 'Max body bytes to read before truncation. Default 262144 (256 KB), max 1048576 (1 MB).',+ },+ headers: {+ type: 'object',+ description: 'Extra request headers. Authorization / Cookie / X-Auth-* blocked unless CLAUDE_FLOW_HTTP_FETCH_ALLOW_AUTH=1.',+ },+ body: {+ type: 'string',+ description: 'Request body for POST. Ignored for GET / HEAD.',+ },+ },+ required: ['url'],+ },+ handler: async (input) => {+ return await httpFetchExecute(input);+ },+ },+];diff --git a/v3/@claude-flow/cli/src/mcp-tools/index.ts b/v3/@claude-flow/cli/src/mcp-tools/index.tsindex cc35536ecd..baf42a0971 100644--- a/v3/@claude-flow/cli/src/mcp-tools/index.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/index.ts@@ -31,3 +31,9 @@ export { metaharnessTools } from './metaharness-tools.js';export { testgenTools } from './testgen-tools.js';// agenticow@~0.2.3 β Copy-On-Write memory branching (162-byte branches)export { agenticowTools } from './agenticow-tools.js';+// ADR-164 β AgentBBS federated business-domain BBS rooms (Phase 1)+export { agentbbsTools } from './agentbbs-tools.js';+// ADR-164 Phase 2 β Business-pod template validation+export { businessPodTools } from './business-pod-tools.js';+// ADR-164 Phase 4 Β§5.1.8 β http_fetch (secure-by-default HTTP probe)+export { httpFetchTools } from './http-fetch-tools.js';diff --git a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/trust-evaluator.test.ts b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/trust-evaluator.test.tsindex 41b60d1c56..2f1a8e2864 100644--- a/v3/@claude-flow/plugin-agent-federation/__tests__/unit/trust-evaluator.test.ts+++ b/v3/@claude-flow/plugin-agent-federation/__tests__/unit/trust-evaluator.test.ts@@ -412,4 +412,62 @@ describe('TrustEvaluator', () => {expect(called).toBe(true);});});++ // -------------------------------------------------------------------------+ // bootstrapElevate β ADR-164 Β§3.5.4 founder-bootstrap escape hatch+ // -------------------------------------------------------------------------+ describe('bootstrapElevate', () => {+ it('throws on empty reason', () => {+ const node = makeNode(TrustLevel.VERIFIED);+ expect(() => evaluator.bootstrapElevate(node, TrustLevel.TRUSTED, '')).toThrow(/non-empty reason/);+ expect(() => evaluator.bootstrapElevate(node, TrustLevel.TRUSTED, ' ')).toThrow(/non-empty reason/);+ });++ it('bypasses minInteractions to jump VERIFIED β TRUSTED in a single call', () => {+ const node = makeNode(TrustLevel.VERIFIED, 'fresh-peer');+ // Organic upgrade VERIFIEDβATTESTED requires scoreβ₯0.7 AND minInteractions=50.+ // ATTESTEDβTRUSTED requires scoreβ₯0.85 AND minInteractions=500. The+ // bootstrap path must skip both thresholds.+ const entry = evaluator.bootstrapElevate(node, TrustLevel.TRUSTED, 'Day-1 #exec autopilot bring-up');+ expect(entry.tag).toBe('bootstrap_elevation');+ expect(entry.nodeId).toBe('fresh-peer');+ expect(entry.previousLevel).toBe(TrustLevel.VERIFIED);+ expect(entry.newLevel).toBe(TrustLevel.TRUSTED);+ expect(entry.reason).toBe('Day-1 #exec autopilot bring-up');+ expect(entry.operatorBypass).toBe(true);+ expect(node.trustLevel).toBe(TrustLevel.TRUSTED);+ });++ it('emits onTrustChange callback so downstream code can react', () => {+ let observed: { nodeId: string; previous: TrustLevel; next: TrustLevel } | null = null;+ const evaluatorWithCb = new TrustEvaluator({+ onTrustChange: (nodeId, result) => {+ observed = {+ nodeId,+ previous: result.previousLevel,+ next: result.newLevel,+ };+ },+ });+ const node = makeNode(TrustLevel.UNTRUSTED, 'cb-node');+ const entry = evaluatorWithCb.bootstrapElevate(node, TrustLevel.TRUSTED, 'manual elevate for smoke test');+ expect(entry).toBeDefined();+ expect(observed).not.toBeNull();+ expect(observed!.nodeId).toBe('cb-node');+ expect(observed!.previous).toBe(TrustLevel.UNTRUSTED);+ expect(observed!.next).toBe(TrustLevel.TRUSTED);+ });++ it('rejects out-of-range trust levels', () => {+ const node = makeNode(TrustLevel.VERIFIED);+ expect(() => evaluator.bootstrapElevate(node, TrustLevel.UNTRUSTED, 'x')).toThrow(/VERIFIED..PRIVILEGED/);+ expect(() => evaluator.bootstrapElevate(node, 99 as TrustLevel, 'x')).toThrow(/VERIFIED..PRIVILEGED/);+ });++ it('audit entry timestamp is an ISO-8601 string', () => {+ const node = makeNode(TrustLevel.VERIFIED);+ const entry = evaluator.bootstrapElevate(node, TrustLevel.ATTESTED, 'iso check');+ expect(entry.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);+ });+ });});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 364fe5e19f..beff85d505 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@@ -11,7 +11,7 @@ import { HandshakeService } from '../domain/services/handshake-service.js';import { RoutingService, type RoutingResult } from '../domain/services/routing-service.js';import { AuditService } from '../domain/services/audit-service.js';import { PIIPipelineService } from '../domain/services/pii-pipeline-service.js';-import { TrustEvaluator, type ImmediateDowngradeReason } from './trust-evaluator.js';+import { TrustEvaluator, type ImmediateDowngradeReason, type BootstrapElevationAuditEntry } from './trust-evaluator.js';import { PolicyEngine } from './policy-engine.js';import {type Budget,@@ -549,6 +549,43 @@ export class FederationCoordinator {if (tasks.length > 0) await Promise.all(tasks);}+ /**+ * Founder-bootstrap trust elevation (ADR-164 Β§3.5.4 β operator escape hatch+ * used in the autopilot Day-1 scenario where a freshly-joined BBS peer+ * needs TRUSTED before organic minInteractions thresholds can accrue).+ *+ * Refuses if the target node is not a registered federation peer (returns+ * null). On success, writes a `trust_level_changed` audit entry tagged+ * `bootstrap_elevation` with the operator-supplied reason, and returns+ * the audit entry so the CLI / caller can print it to stdout.+ */+ async bootstrapElevatePeer(+ nodeId: string,+ newLevel: TrustLevel,+ reason: string,+ ): Promise<BootstrapElevationAuditEntry | null> {+ this.ensureInitialized();+ const peer = this.discovery.getPeer(nodeId);+ if (!peer) return null;++ const entry = this.trustEvaluator.bootstrapElevate(peer, newLevel, reason);++ await this.audit.log('trust_level_changed', {+ targetNodeId: nodeId,+ trustLevel: newLevel,+ metadata: {+ tag: 'bootstrap_elevation',+ previousLevel: entry.previousLevel,+ newLevel: entry.newLevel,+ reason: entry.reason,+ operatorBypass: true,+ timestamp: entry.timestamp,+ },+ });++ return entry;+ }+/*** Operator-initiated reactivate. Used after an integrator-supplied* health probe confirms a SUSPENDED peer is healthy, OR as andiff --git a/v3/@claude-flow/plugin-agent-federation/src/application/trust-evaluator.ts b/v3/@claude-flow/plugin-agent-federation/src/application/trust-evaluator.tsindex ee24d50be6..04d261edca 100644--- a/v3/@claude-flow/plugin-agent-federation/src/application/trust-evaluator.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/application/trust-evaluator.ts@@ -27,6 +27,22 @@ export interface TrustEvaluatorDeps {onTrustChange?: (nodeId: string, result: TrustTransitionResult) => void;}+/**+ * Audit record emitted by `bootstrapElevate`. Captures the bypass intent,+ * the operator-supplied reason, and the before/after trust levels so that+ * downstream audit consumers can flag bootstrap elevations distinctly from+ * organic trust transitions. See ADR-164 Β§3.5.4.+ */+export interface BootstrapElevationAuditEntry {+ readonly tag: 'bootstrap_elevation';+ readonly nodeId: string;+ readonly previousLevel: TrustLevel;+ readonly newLevel: TrustLevel;+ readonly reason: string;+ readonly timestamp: string;+ readonly operatorBypass: true;+}+export interface ThreatWindow {readonly detections: Date[];readonly windowMs: number;@@ -146,6 +162,62 @@ export class TrustEvaluator {return result;}+ /**+ * Founder-bootstrap trust elevation (ADR-164 Β§3.5.4).+ *+ * Bypasses the organic trust-accrual thresholds (minInteractions: 500 for+ * 2β3, etc.) so a freshly-joined BBS peer can be hand-promoted to+ * TRUSTED on Day 1, before its interaction count has accrued. This is an+ * operator escape hatch β every invocation MUST be recorded as a special+ * `bootstrap_elevation` audit entry so it is distinguishable from organic+ * upgrades. `reason` MUST be a non-empty operator-supplied string.+ *+ * The caller is responsible for refusing to invoke this method when the+ * target node is not a registered federation peer; this function trusts+ * its inputs and only performs the elevation + audit construction.+ *+ * @returns audit entry tagged `bootstrap_elevation` ready to be persisted.+ */+ bootstrapElevate(+ node: FederationNode,+ newLevel: TrustLevel,+ reason: string,+ ): BootstrapElevationAuditEntry {+ if (typeof reason !== 'string' || reason.trim().length === 0) {+ throw new Error('bootstrapElevate requires a non-empty reason');+ }+ if (+ newLevel !== TrustLevel.VERIFIED &&+ newLevel !== TrustLevel.ATTESTED &&+ newLevel !== TrustLevel.TRUSTED &&+ newLevel !== TrustLevel.PRIVILEGED+ ) {+ throw new Error(`bootstrapElevate target level must be VERIFIED..PRIVILEGED, got ${newLevel}`);+ }+ const previousLevel = node.trustLevel;+ node.updateTrustLevel(newLevel);++ const result: TrustTransitionResult = {+ previousLevel,+ newLevel,+ score: 0,+ components: { successRate: 0, uptime: 0, threatPenalty: 0, dataIntegrityScore: 0 },+ reason: `Bootstrap elevation: ${reason}`,+ requiresHumanApproval: false,+ };+ this.deps.onTrustChange?.(node.nodeId, result);++ return {+ tag: 'bootstrap_elevation',+ nodeId: node.nodeId,+ previousLevel,+ newLevel,+ reason: reason.trim(),+ timestamp: new Date().toISOString(),+ operatorBypass: true,+ };+ }+recordThreatDetection(nodeId: string): boolean {const now = new Date();const detections = this.threatWindows.get(nodeId) ?? [];diff --git a/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts b/v3/@claude-flow/plugin-agent-federation/src/cli-commands.tsindex ca19bef1ef..6ca9294041 100644--- a/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/cli-commands.ts@@ -157,6 +157,103 @@ export function createCliCommands(}},},+ {+ name: 'federation trust elevate',+ description:+ 'ADR-164 Β§3.5.4 β Founder-bootstrap trust elevation escape hatch. ' ++ 'Hand-promote a registered BBS peer past the organic minInteractions ' ++ 'threshold (e.g. 500 for ATTESTEDβTRUSTED) so #exec / #finance pods can ' ++ 'reach the share-context capability on Day 1. Refuses if the target ' ++ 'is not a registered federation peer. Every invocation writes a ' ++ '`trust_level_changed` audit entry tagged `bootstrap_elevation`.',+ arguments: [{ name: 'node-id', description: 'BBS / federation node id to elevate', required: true }],+ options: [+ {+ name: 'to',+ description: 'Target trust level (VERIFIED, ATTESTED, TRUSTED, PRIVILEGED, or numeric 1-4)',+ type: 'string',+ required: true,+ },+ {+ name: 'reason',+ description: 'Operator-supplied reason β appears verbatim in the audit log',+ type: 'string',+ required: true,+ },+ {+ name: 'audit',+ description: 'MANDATORY β print the resulting audit-log entry to stdout',+ type: 'boolean',+ default: false,+ },+ ],+ handler: async (args) => {+ const coordinator = requireCoordinator(getCoordinator);+ const nodeId = (args._?.[0] ?? '') as string;+ if (!nodeId) {+ console.error('node-id is required');+ process.exitCode = 1;+ return;+ }++ const rawTo = args['to'];+ const reason = args['reason'];+ const auditFlag = args['audit'];++ if (typeof reason !== 'string' || reason.trim().length === 0) {+ console.error('--reason is required and must be a non-empty string');+ process.exitCode = 1;+ return;+ }+ if (auditFlag !== true && auditFlag !== 'true') {+ console.error(+ '--audit is mandatory for bootstrap elevation (ADR-164 Β§3.5.4). ' ++ 'Pass --audit to acknowledge the audit-log emission.',+ );+ process.exitCode = 1;+ return;+ }++ let target: TrustLevel | null = null;+ const toStr = String(rawTo).trim().toUpperCase();+ switch (toStr) {+ case 'VERIFIED': case '1': target = TrustLevel.VERIFIED; break;+ case 'ATTESTED': case '2': target = TrustLevel.ATTESTED; break;+ case 'TRUSTED': case '3': target = TrustLevel.TRUSTED; break;+ case 'PRIVILEGED': case '4': target = TrustLevel.PRIVILEGED; break;+ }+ if (target === null) {+ console.error(+ `--to value "${rawTo}" not recognized. ` ++ `Use VERIFIED, ATTESTED, TRUSTED, PRIVILEGED, or numeric 1-4.`,+ );+ process.exitCode = 1;+ return;+ }++ const entry = await coordinator.bootstrapElevatePeer(nodeId, target, reason);+ if (entry === null) {+ console.error(+ `Node "${nodeId}" is not a registered federation peer. ` ++ `Run "ruflo-federation peers add <endpoint>" first.`,+ );+ process.exitCode = 1;+ return;+ }++ // --audit is mandatory; always print the entry to stdout.+ const human =+ `[BOOTSTRAP-ELEVATION] ${entry.timestamp}\n` ++ ` nodeId: ${entry.nodeId}\n` ++ ` previousLevel: ${getTrustLevelLabel(entry.previousLevel)} (${entry.previousLevel})\n` ++ ` newLevel: ${getTrustLevelLabel(entry.newLevel)} (${entry.newLevel})\n` ++ ` reason: ${entry.reason}\n` ++ ` operatorBypass: ${entry.operatorBypass}\n` ++ ` tag: ${entry.tag}`;+ console.log(human);+ console.log(JSON.stringify(entry));+ },+ },{name: 'federation trust',description: 'View or modify trust level for a specific node',diff --git a/v3/docs/adr/ADR-164-agentbbs-business-autopilot.md b/v3/docs/adr/ADR-164-agentbbs-business-autopilot.mdnew file mode 100644index 0000000000..12344aa4b8--- /dev/null+++ b/v3/docs/adr/ADR-164-agentbbs-business-autopilot.md@@ -0,0 +1,1445 @@+# ADR-164 β AgentBBS Federated Business-Management Autopilot++**Status**: Draft+**Date**: 2026-06-29+**Authors**: claude (drafted with rUv)+**Related**:+- ADR-097 (federation budget circuit breaker)+- ADR-110 (production spend reporter)+- ADR-111 (WG mesh transport)+- ADR-115 (managed agents cloud backend)+- ADR-150 (metaharness integration β the optional-dep playbook this ADR mirrors)+- ADR-001 (deep-integration philosophy β build as extension, not parallel implementation)+- PR #2500 (agenticow v3.15.0 ship β precedent for the optional-dep onboarding pattern)+**External references**:+- `[email protected]` (npm launcher) / Rust workspace β [`ruvnet/agentbbs`](https://github.com/ruvnet/agentbbs) β mature Rust workspace: 13 crates (`agentbbs`, `agentbbs-arena`, `agentbbs-core`, `agentbbs-federation`, `agentbbs-mcp`, `agentbbs-tui`, `agentbbs-web`, `agentbbs-wasm`, plus `late-cli`, `late-core`, `late-nethack`, `late-ssh`, `late-web`), 30+ release tags (latest seen: `v0.34.9-nethack`), 7 GitHub Actions workflows (`agentbbs.yml`, `build.yml`, `ci.yml`, `deploy.yml`, `deploy_cli.yml`, `deploy_infra.yml`, `deploy_nethack.yml`), existing MCP server at `crates/agentbbs-mcp/` (`server.rs`, `client.rs`, `transport.rs`, `lib.rs` + `tests/mcp.rs`), existing federation crate at `crates/agentbbs-federation/`, postgres-backed integration tests, Docker + docker-compose + monitoring stack, `deny.toml` (cargo-deny supply-chain scans), `.gitguardian.yaml` (secret scanning), FSL-1.1-Apache-2.0 license (converts to Apache-2.0 after 2 years); same author ([email protected])+- `@claude-flow/plugin-agent-federation` β `v3/@claude-flow/plugin-agent-federation/src/`++---++## 1. Context++### 1.1 Business-owner problem statement++A business owner who deploys ruflo today can run AI agents against discrete tasks. What they cannot do is hand over *operational continuity* to those agents. Sales pipelines go untouched between sessions. Finance reconciliation waits for a human to ask for it. Marketing copy drifts without review. Support tickets queue unreplied.++The gap is not capability β ruflo's agents can already do each of these things when prompted. The gap is **perpetual, observable, overrideable automation with a cockpit the owner can actually sit in**. They need:++1. **Perpetual operation**: agents running Sales / Marketing / Finance / Ops / Support / HR continuously, not just when the owner types a prompt.+2. **A cockpit**: a live feed of what every agent is doing, organized by business function, with a clear override path.+3. **Domain boundary enforcement**: the Finance pod and the Sales pod should not cross-contaminate each other's context. Financial data should not leave the local node. Outreach tasks can tolerate cloud Managed Agents.+4. **Cost visibility**: the CFO needs a kill switch. Each business domain should have a monthly spend cap that cuts off agent execution when hit β not a soft warning, a hard stop.++### 1.2 The three-system intersection++This ADR sits at the intersection of three existing components:++| System | What it provides | Gap |+|--------|-----------------|-----|+| ruflo federation (ADR-097, ADR-111) | Trust-scored peer connections, PII pipeline, budget hop enforcement, WG mesh transport | No concept of "business domain"; federation is agent-to-agent, not role-to-domain-to-human |+| Managed Agents (ADR-115) | Cloud agent execution with SSE event streaming | No persistent room concept; sessions are ephemeral |+| agentbbs (npm launcher v0.1.0; Rust workspace v0.34.9-nethack) | BBS-style web UI + TUI + SSH front door for human-agent interaction, organized into "rooms"; existing `crates/agentbbs-mcp/` MCP server with server/client/transport layers + integration test suite; existing `crates/agentbbs-federation/` crate; Docker + monitoring stack; postgres-backed CI; 7 CI workflows | Typed federation-envelope compatibility with ruflo's wire format is unverified; `agentbbs-mcp` tool interface needs explicit compat check against our `MCPTool` interface; FSL-1.1-Apache-2.0 license (converts to Apache-2.0 after 2 years) has integration implications for ruflo's MIT distribution; `cargo` required at first run (Rust compilation); npm launcher version vs. Rust workspace version are independent versioning tracks |++The proposal is to wire these three together: federation provides the trust + PII + budget primitives; Managed Agents provides cloud-scale execution for appropriate workloads; agentbbs provides the human-facing cockpit.++### 1.3 Why agentbbs specifically++agentbbs is authored by the same maintainer (rUv), follows the same ADR convention, and is explicitly framed as an interaction layer for agent systems. It provides a BBS (bulletin board system) metaphor β rooms, posts, subscriptions β that maps naturally onto business functions. The SSH front door is significant: agents that cannot run a local MCP server can still participate by speaking SSH.++Critically, the npm package `[email protected]` is a thin launcher only. The actual project is a mature Rust workspace tracked under `ruvnet/agentbbs` with 30+ release tags (latest: `v0.34.9-nethack`), a working CI pipeline including rustfmt, clippy, and postgres-backed integration tests, and two directly relevant crates:++- **`crates/agentbbs-mcp/`** β an existing MCP server implementation (`server.rs`, `client.rs`, `transport.rs`, `lib.rs`) with its own integration test (`tests/mcp.rs`). Before writing any new MCP plumbing, this integration must verify whether `agentbbs-mcp` already exposes compatible tool endpoints that ruflo's `MCPTool` interface can consume directly. If so, Phase 1 and Phase 2 integration costs drop significantly.++- **`crates/agentbbs-federation/`** β an existing federation crate. Before specifying "new upstream changes" for federation envelope handling (Section 5.2), this crate must be surveyed to determine which capabilities already exist. It may already accept typed payloads that are close to ruflo's `FederationEnvelope` wire format.++The project also ships `deny.toml` (cargo-deny supply-chain scanning) and `.gitguardian.yaml` (secret scanning), which are hygiene signals consistent with a production-tracked codebase. Docker, docker-compose, and a monitoring stack are present, indicating the project has been deployed rather than only prototyped.++The integration risks are therefore not about project maturity in the general sense. The specific risks are: (a) the npm launcher version track and the Rust workspace version track are independently versioned β the integration must pin against the Rust workspace tag, not the npm package semver; (b) the FSL-1.1-Apache-2.0 license converts to Apache-2.0 after 2 years, which is compatible with ruflo's MIT distribution for most commercial contexts but requires legal review before embedding agentbbs binaries in a ruflo distribution; (c) `cargo` must be present on the operator's machine for the Rust binary to build at first run; (d) the `agentbbs-mcp` server's tool interface needs explicit compatibility verification against ruflo's `MCPTool` interface before Phase 2. See Section 9.1 for the rewritten risk register.++This ADR treats agentbbs the same way ADR-150 treated `[email protected]` in terms of the integration pattern: `optionalDependency`, graceful-degraded paths, smoke contract on day one, and deeper phases gated behind measured evidence. It does NOT treat agentbbs as an unproven project β the Rust workspace evidence justifies confidence in its foundational architecture.++---++## 2. Decision++**Adopt agentbbs as a special-tier federation peer (BBS-as-peer model) and scaffold business-domain pods as a new plugin (`ruflo-bbs-federation` + `ruflo-business-pods`), following the optional-dep integration pattern established by ADR-150 and exercised by the agenticow PR #2500.**++Concretely:++1. **BBS rooms are federation peers.** Each room (`#sales`, `#marketing`, `#finance`, `#ops`, `#support`, `#hr`, `#exec`) is registered as a named federation peer via four new MCP tools: `federation_bbs_register`, `federation_bbs_publish`, `federation_bbs_watch`, `federation_bbs_human_join`. These wrap the existing `FederationCoordinator` API without changing the wire format.++2. **Domain pods are the unit of execution.** A pod is a named group of specialized agents serving one BBS room, with a defined bench, schedule, PII policy, and budget cap. Pods are defined in a new plugin, `ruflo-business-pods`, as typed JSON templates.++3. **Routing uses `@metaharness/router` policy extended with domain-affinity rules.** Sensitive workloads (finance, HR) prefer local stdio execution. High-throughput workloads (marketing outreach, support triage) prefer cloud Managed Agents. The policy is a small additive layer on the existing neural router.++4. **Budget circuit breakers are per-room.** The existing `federation-budget.ts` `enforceBudget` mechanism is used without modification; the BBS plugin configures a per-room `maxUsd` that maps to the CFO kill-switch requirement.++5. **agentbbs goes in `optionalDependencies`.** Ruflo must remain fully operational with agentbbs removed. The smoke contract (`plugins/ruflo-bbs-federation/scripts/smoke.sh`) must pass without agentbbs present by running in degraded mode.++### 2.1 What we are NOT doing in this ADR++- Forking or modifying agentbbs's core architecture. We are building an integration layer, not taking ownership of the upstream project.+- Mandating CRDT semantics for BBS rooms. CRDT is out of scope for agentbbs v0.1.0; we rely on the federation envelope's `hmacSignature` for ordering, and accept eventual consistency with human-visible timestamps.+- Replacing ruflo's existing federation with a BBS-centric model. BBS rooms are *one kind* of federation peer; all existing peer types continue to work unchanged.+- Claiming cost or performance numbers for the business autopilot. Agentbbs has no published benchmark; cost projections in Section 8 are estimates based on current API pricing, not measured workloads.++---++## 3. Architecture++### 3.1 System diagram++```+ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β HUMAN LAYER β+ β β+ β Business owner β+ β β β+ β βΌ β+ β agentbbs web UI / TUI / SSH β+ β (rooms: #sales #marketing #finance #ops #support #hr #exec) β+ ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ+ β HTTP / WebSocket / SSH+ β (typed federation envelopes in post body)+ ββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ+ β ruflo-bbs-federation plugin β+ β β+ β federation_bbs_register βββΊ FederationCoordinator.joinPeer() β+ β federation_bbs_publish βββΊ FederationCoordinator.sendMessage() β+ β federation_bbs_watch βββΊ inbound-dispatcher.ts subscription β+ β federation_bbs_human_join ββΊ HandshakeService + single-use token β+ β β+ β PII pipeline (pii-pipeline-service.ts) applied per room policy β+ β Budget enforcement (federation-budget.ts enforceBudget) per room β+ β Audit log (audit-service.ts) β business-owner read view β+ ββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β FederationEnvelope (typed, HMAC-signed, PII-scanned)+ β+ ββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β ruflo node (local or remote via WG mesh) β+ β β+ β βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββββ β+ β β #sales pod β β #finance pod β β #marketing pod β β+ β β lead-gen β β reconcile-agent β β copy-drafter β β+ β β crm-sync β β budget-watcher β β campaign-analyst β β+ β β outreach β β tax-classifier β β seo-scout β β+ β β pipeline-analystβ β β β β β+ β ββββββββββ¬βββββββββ ββββββββββ¬ββββββββββ ββββββββββ¬βββββββββββ β+ β β local stdio MCP β local stdio MCP β β+ β β β (finance: local-only) β β+ β β β β+ β ββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββΌββββββββββββ β+ β β @metaharness/router (domain-affinity policy) β β+ β β ββ local: finance, hr, ops (sensitive) β β+ β β ββ cloud: sales, marketing, support (high throughput) β β+ β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+ β β β+ β ββββββββββΌββββββββββββββββββ β+ β β Managed Agents (ADR-115) β β+ β β cloud execution pool β β+ β βββββββββββββββββββββββββββββ β+ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++### 3.2 The four new MCP tools++All four tools live in `plugins/ruflo-bbs-federation/scripts/` (skill-shelled) and additionally as typed MCP handlers in `plugins/ruflo-bbs-federation/mcp-tools.ts` (mirroring the `ruflo-metaharness` pattern). They wrap β never bypass β the existing `FederationCoordinator`.++When agentbbs is not installed, each tool returns a structured degraded response `{ degraded: true, reason: "agentbbs not installed" }` and exits with status 0 (non-fatal). This is the mandatory graceful-degradation contract.++#### 3.2.1 `federation_bbs_register`++Register a BBS room as a named federation peer. Idempotent: re-registering the same room updates its policy without creating a duplicate peer.++```typescript+inputSchema: {+ type: 'object',+ properties: {+ roomId: {+ type: 'string',+ description: 'BBS room identifier, e.g. "sales", "finance". Used as the federation nodeId.',+ },+ bbsEndpoint: {+ type: 'string',+ description: 'WebSocket or HTTP endpoint of the agentbbs server for this room.',+ },+ domainPod: {+ type: 'string',+ description: 'Name of the ruflo-business-pods template that serves this room.',+ },+ piiPolicy: {+ type: 'string',+ enum: ['soc2', 'gdpr', 'hipaa', 'permissive'],+ description: 'Compliance mode for PII scanning on all envelopes in/out of this room.',+ },+ budgetUsdMonthly: {+ type: 'number',+ description: 'Monthly USD hard cap for this room. 0 means unlimited (not recommended for finance).',+ },+ preferLocal: {+ type: 'boolean',+ description: 'If true, @metaharness/router policy routes this room\'s tasks to local stdio agents first.',+ default: false,+ },+ },+ required: ['roomId', 'bbsEndpoint', 'domainPod', 'piiPolicy'],+}++// Graceful degradation (agentbbs not installed):+// Returns { degraded: true, reason: "[email protected] not installed", roomId }+// Does NOT throw. Logs a warn to audit-service.ts.+//+// Implementation notes:+// Calls FederationCoordinator.joinPeer(bbsEndpoint) with the room's trust+// tier pre-set to TrustLevel.ATTESTED (rooms are operator-registered, not+// auto-discovered, so they start one tier above VERIFIED).+// Stores the room policy in a new BbsRoomRegistry (in-memory, persisted to+// ruflo memory namespace 'bbs-rooms').+```++#### 3.2.2 `federation_bbs_publish`++Publish a domain event from a pod agent to its BBS room. Wraps `federation_send` with room-specific budget enforcement and PII pipeline application.++```typescript+inputSchema: {+ type: 'object',+ properties: {+ roomId: {+ type: 'string',+ description: 'Target BBS room.',+ },+ eventKind: {+ type: 'string',+ enum: [+ 'pod-status', // periodic heartbeat from a pod+ 'task-result', // agent completed a task+ 'alert', // pod detected an anomaly or threshold breach+ 'human-override-ack', // pod acknowledged a human redirect+ 'bench-result', // periodic bench score for the domain+ ],+ description: 'Typed event kind β controls how the BBS web UI renders this post.',+ },+ payload: {+ type: 'object',+ description: 'Event-specific payload. Must be JSON-serializable.',+ },+ podAgentId: {+ type: 'string',+ description: 'The agent within the pod that produced this event.',+ },+ budgetHopCount: {+ type: 'number',+ description: 'How many federation hops this message has already traveled (0 on origin).',+ default: 0,+ },+ },+ required: ['roomId', 'eventKind', 'payload', 'podAgentId'],+}++// Implementation notes:+// Wraps FederationCoordinator.sendMessage() with:+// messageType: 'context-share' (existing FederationMessageType)+// payload: { eventKind, payload, podAgentId, ts: new Date().toISOString() }+// budget: { maxUsd: room.budgetUsdRemaining }+// PII pipeline runs per room.piiPolicy before the envelope is signed.+// Spend is reported via federation_report_spend after send completes.+// On BBS endpoint unavailable: falls back to ruflo memory store under+// namespace 'bbs-room-<roomId>-offline-queue' for retry on reconnect.+```++#### 3.2.3 `federation_bbs_watch`++Subscribe to events from a BBS room. Registers an inbound-dispatcher subscription so pod agents receive human overrides and new tasks posted by the business owner. Long-lived; survives pod restarts via a re-registration on startup.++```typescript+inputSchema: {+ type: 'object',+ properties: {+ roomId: {+ type: 'string',+ description: 'BBS room to watch.',+ },+ podAgentId: {+ type: 'string',+ description: 'Agent that should receive incoming events from this room.',+ },+ eventKinds: {+ type: 'array',+ items: {+ type: 'string',+ enum: ['human-override', 'new-task', 'shutdown-request', 'policy-update'],+ },+ description: 'Filter: only deliver these event kinds. Omit to receive all.',+ },+ sinceTs: {+ type: 'string',+ description: 'ISO 8601 timestamp. Replay missed events since this time on connect.',+ },+ },+ required: ['roomId', 'podAgentId'],+}++// Implementation notes:+// Calls inbound-dispatcher.ts registerSubscription(roomId, podAgentId, filter).+// The inbound-dispatcher (v3/@claude-flow/plugin-agent-federation/src/application/+// inbound-dispatcher.ts) does not yet implement subscriptions β this is a required+// upstream change (see Section 6.1.3).+// On agentbbs not installed: registers a no-op subscription, returns degraded flag.+// sinceTs replay requires agentbbs to have a durable event log (see Section 10).+```++#### 3.2.4 `federation_bbs_human_join`++Authenticate a human business owner into a BBS room via a single-use token signed by the local federation keypair. The token is scoped to the room and expires after first use or 15 minutes, whichever comes first.++```typescript+inputSchema: {+ type: 'object',+ properties: {+ roomId: {+ type: 'string',+ description: 'The room to join.',+ },+ humanIdentity: {+ type: 'string',+ description: 'Email or identifier for the human. Used for audit log attribution only.',+ },+ expirySeconds: {+ type: 'number',+ description: 'Token lifetime in seconds. Max 900 (15 min). Default 300.',+ default: 300,+ },+ accessLevel: {+ type: 'string',+ enum: ['read-only', 'override', 'admin'],+ description: 'Permissions within the room. "override" allows redirecting running tasks. "admin" allows shutdown and policy changes.',+ default: 'override',+ },+ },+ required: ['roomId', 'humanIdentity'],+}++// Token shape:+// { roomId, humanIdentity, accessLevel, issuedAt, expiresAt, nonce, signature }+// Signed with the node's Ed25519 keypair (same key used by plugin.ts for+// federation handshakes β @noble/ed25519 via ed.sign()).+// Token is handed to the human out-of-band (printed to stdout or returned+// in the MCP tool result). The human presents it to the agentbbs SSH/web+// front door on connect.+//+// Two-phase authentication model:+//+// Phase A β Handshake (token is single-use):+// The 15-minute Ed25519 token is un-replayable. It is consumed by a+// SINGLE USE to open a WebSocket or SSH channel. Once the channel is+// opened, the token is invalidated immediately: the agentbbs server+// records the JTI (nonce) so that any replay of the same token against+// a new connection fails with 401. The token MUST NOT be persisted by+// the client or used for any subsequent request.+//+// Phase B β Session (channel is long-lived):+// Once the Phase A handshake succeeds, the open channel remains active+// until one of three conditions occurs:+// (i) The user explicitly closes the connection.+// (ii) An idle timeout fires (default: 30 minutes of no inbound or+// outbound traffic on the channel; configurable via the BBS+// server's session policy).+// (iii) The BBS node restarts (channel is torn down; client must+// perform a new Phase A handshake to reconnect).+// During Phase B, NO re-validation of the token occurs. The channel+// is already authenticated. Long-running streams (e.g., `subscribe+// #sales` via SSH β see Section 5.2.5) are Phase B sessions: the SSH+// session stays open for the duration of the stream WITHOUT re-checking+// the token mid-stream. Requiring mid-stream re-validation would break+// the streaming contract.+//+// Re-authentication:+// After a channel closes (any of the three conditions above), a new+// call to federation_bbs_human_join is required to obtain a fresh+// single-use token before reconnecting.+//+// Graceful degradation: token is generated locally even if agentbbs is+// unreachable. The human can present it later when BBS reconnects.+```++### 3.3 Pod template schema++A pod template is a typed JSON object stored in `plugins/ruflo-business-pods/templates/<domain>.json`. The schema:++```typescript+interface BusinessPodTemplate {+ /** Canonical name, e.g. "sales", "finance". Must match the BBS roomId. */+ name: string;++ /** Display name for the BBS web UI. */+ displayName: string;++ /** BBS room this pod serves. */+ roomId: string;++ /** Ordered list of agent roles in the pod. */+ agents: Array<{+ role: string; // e.g. "lead-gen-agent"+ agentType: string; // must be a known ruflo agent type+ description: string;+ preferLocal: boolean; // if true, @metaharness/router routes here first+ }>;++ /** MCP tools the pod agents may call. Allowlist β not a blocklist. */+ allowedMcpTools: string[];++ /** Bench definition for the domain's Darwin /loop. */+ bench: {+ name: string;+ description: string;+ successCriteria: string[];+ scheduleHours: number; // how often to run the bench loop+ };++ /** PII compliance mode applied to all envelopes in/out of this room. */+ piiPolicy: 'soc2' | 'gdpr' | 'hipaa' | 'permissive';++ /** Monthly USD hard cap (0 = unlimited). */+ budgetUsdMonthly: number;++ /** Suggested starting budget per run, for individual task cost tracking. */+ budgetUsdPerRun: number;++ /** If true, @metaharness/router domain-affinity policy routes to local first. */+ preferLocalExecution: boolean;++ /** Default cron schedule for the perpetual /loop (POSIX cron syntax). */+ cronSchedule: string;++ /**+ * Metadata for the compliance audit log.+ * Determines which audit events are written in business-owner-readable form.+ */+ auditReadView: {+ includedEventTypes: string[];+ retentionDays: number;+ };+}+```++### 3.4 `@metaharness/router` domain-affinity policy extension++The existing neural router in `v3/@claude-flow/cli/src/intelligence/neural-router.ts` accepts a `PolicyEngine` (from `v3/@claude-flow/plugin-agent-federation/src/application/policy-engine.ts`). The BBS plugin adds a `DomainAffinityPolicy` layer that the router checks before the KRR cost-optimal decision:++```typescript+// Pseudocode β new file:+// plugins/ruflo-bbs-federation/src/domain-affinity-policy.ts++interface DomainAffinityPolicy {+ evaluate(task: RoutingTask, room: BbsRoom): RoutingHint;+}++type RoutingHint =+ | { preference: 'local'; reason: string }+ | { preference: 'cloud'; reason: string }+ | { preference: 'any'; reason: string };++// Reference implementation:+function evaluateDomainAffinity(task, room): RoutingHint {+ if (room.preferLocalExecution) {+ return { preference: 'local', reason: `domain=${room.name} configured preferLocalExecution` };+ }+ if (room.piiPolicy === 'hipaa' || room.piiPolicy === 'gdpr') {+ return { preference: 'local', reason: `domain=${room.name} piiPolicy=${room.piiPolicy} requires local` };+ }+ // High-throughput rooms that tolerate cloud:+ if (['marketing', 'support'].includes(room.name)) {+ return { preference: 'cloud', reason: `domain=${room.name} favors cloud for throughput` };+ }+ return { preference: 'any', reason: 'no affinity constraint' };+}+```++This policy is injected as an optional constructor argument on the neural router; the router calls it before KRR if the BBS plugin is loaded, and skips it otherwise. No change to the router's core logic.++### 3.5 Trust model for BBS rooms++BBS rooms are operator-registered peers (humans with admin access issued the token). They start at `TrustLevel.ATTESTED` (level 2), which grants `send`, `receive`, `query-redacted`, and `share-context` capabilities per the existing `CAPABILITY_GATES` in `v3/@claude-flow/plugin-agent-federation/src/domain/entities/trust-level.ts`.++Human messages arriving via the BBS room inherit the room's trust level. An `accessLevel: 'admin'` human token elevates the interaction to `TrustLevel.TRUSTED` (level 3) for the duration of the session β never higher, even with an admin token, because `TrustLevel.PRIVILEGED` (level 4, which grants `remote-spawn`) requires `minInteractions: 5000` in `TRUST_TRANSITION_THRESHOLDS`.++Override messages from humans are enveloped in the standard `FederationEnvelope` with `messageType: 'task-assignment'` (an existing `FederationMessageType`). The receiving pod agent checks the token signature before acting on the override. Unsigned or expired tokens are rejected by the `HandshakeService` before they reach the pod.++#### 3.5.4 Founder-bootstrap trust elevation++The organic trust accrual path (`minInteractions: 500` to reach `TRUSTED`, `minInteractions: 5000` for `PRIVILEGED`) means the `#exec` cross-pod synthesizer cannot operate at full capability on Day 1. In practice, the operator who registers the BBS rooms knows they are legitimate. An escape hatch is required to unblock production deployments without waiting for organic accrual.++**CLI command** (new subcommand under `ruflo federation`):++```bash+ruflo federation trust elevate <bbs-node-id> \+ --to TRUSTED \+ --reason "<human-readable justification>" \+ --audit+```++Constraints:+- `--reason` is **mandatory** and stored verbatim in the audit log. The command rejects invocations that omit it.+- `--audit` is **mandatory** and prints the audit-log entry to stdout immediately after writing it, so the operator can record it externally before proceeding.+- The elevation bypasses the `TRUST_TRANSITION_THRESHOLDS` gate entirely but MUST write a special audit entry tagged `type: 'bootstrap_elevation'` to `AuditService`. This entry includes `nodeId`, `elevatedTo`, `reason`, `operatorIdentity` (from the session token), and `timestamp`.+- The command only elevates to `TRUSTED` (level 3). It cannot be used to reach `PRIVILEGED` (level 4) β `--to PRIVILEGED` is rejected.++**Implementation wire point**: add a new method to `application/trust-evaluator.ts`:++```typescript+/**+ * Operator escape hatch β bypasses TRUST_TRANSITION_THRESHOLDS for registered+ * BBS room nodes. Writes a 'bootstrap_elevation' audit entry.+ * Requires: reason is non-empty string; audit flag triggers stdout print.+ */+async bootstrapElevate(+ nodeId: string,+ toLevel: TrustLevel.TRUSTED, // only TRUSTED is permitted+ reason: string,+ audit: boolean+): Promise<void>;+```++The CLI subcommand calls `bootstrapElevate` and exits non-zero if `reason` is empty or `audit` is false.++**Security caveat**: Production deployments SHOULD require multi-party sign-off before invoking this command (e.g., two operators, one acting as auditor who records the stdout output). Phase 1 may ship with a single-operator escape hatch; enforcing multi-party sign-off is a **Phase 5 hardening** item. The reason-and-audit gate provides a papertrail even for single-operator Phase 1 deployments.++---++## 4. Domain pod templates++Each template below is the canonical definition for that business function. The `cronSchedule` uses the pod's Darwin /loop for perpetual operation; the `bench` defines the success criteria for each cycle. These are starting points β operators are expected to tune agent composition and bench criteria for their business.++### 4.1 Sales pod++```json+{+ "name": "sales",+ "displayName": "Sales",+ "roomId": "sales",+ "agents": [+ { "role": "lead-gen-agent", "agentType": "researcher", "description": "Discovers and qualifies inbound leads", "preferLocal": false },+ { "role": "crm-sync-agent", "agentType": "backend-dev", "description": "Syncs pipeline state to CRM via webhook", "preferLocal": false },+ { "role": "outreach-drafter", "agentType": "api-docs", "description": "Drafts outreach emails for review", "preferLocal": false },+ { "role": "pipeline-analyst", "agentType": "perf-analyzer", "description": "Monitors pipeline velocity and flags stalls", "preferLocal": false }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch"],+ "bench": {+ "name": "sales-pipeline-bench",+ "description": "Measures pipeline movement per cycle",+ "successCriteria": [+ "At least 1 new lead qualified per 24h cycle",+ "CRM sync error rate < 5%",+ "No outreach draft older than 48h pending in queue"+ ],+ "scheduleHours": 6+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 50,+ "budgetUsdPerRun": 0.50,+ "preferLocalExecution": false,+ "cronSchedule": "0 */6 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ }+}+```++### 4.2 Marketing pod++```json+{+ "name": "marketing",+ "displayName": "Marketing",+ "roomId": "marketing",+ "agents": [+ { "role": "copy-drafter", "agentType": "api-docs", "description": "Drafts blog posts and ad copy", "preferLocal": false },+ { "role": "campaign-analyst", "agentType": "perf-analyzer", "description": "Tracks campaign metrics against targets", "preferLocal": false },+ { "role": "seo-scout", "agentType": "researcher", "description": "Identifies SEO opportunities", "preferLocal": false }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch"],+ "bench": {+ "name": "marketing-output-bench",+ "description": "Measures content production rate and campaign accuracy",+ "successCriteria": [+ "At least 1 draft piece of content per 24h cycle",+ "Campaign metric delta reported within 12h of cycle start",+ "No SEO queue older than 72h"+ ],+ "scheduleHours": 12+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 40,+ "budgetUsdPerRun": 0.30,+ "preferLocalExecution": false,+ "cronSchedule": "0 */12 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ }+}+```++### 4.3 Finance pod++Finance is the most sensitive domain. All execution is local. PII policy is GDPR (tightest available). The pod runs on a daily schedule rather than sub-daily to reduce noise.++```json+{+ "name": "finance",+ "displayName": "Finance",+ "roomId": "finance",+ "agents": [+ { "role": "reconcile-agent", "agentType": "database-specialist", "description": "Reconciles transactions against ledger", "preferLocal": true },+ { "role": "budget-watcher", "agentType": "perf-analyzer", "description": "Monitors spend against monthly budgets", "preferLocal": true },+ { "role": "tax-classifier", "agentType": "code-analyzer", "description": "Classifies transactions by tax category", "preferLocal": true }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch"],+ "bench": {+ "name": "finance-accuracy-bench",+ "description": "Measures reconciliation accuracy per cycle",+ "successCriteria": [+ "Reconciliation error rate < 0.1% of transactions",+ "All transactions classified within 24h",+ "No budget over-run alerts older than 4h unacknowledged"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "gdpr",+ "budgetUsdMonthly": 20,+ "budgetUsdPerRun": 0.10,+ "preferLocalExecution": true,+ "cronSchedule": "0 6 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result", "pod-status"],+ "retentionDays": 365+ }+}+```++### 4.4 Ops pod++Ops covers infrastructure monitoring, deployment readiness, and internal tooling health. Execution is mixed: local for infrastructure reads, cloud for high-throughput log analysis.++```json+{+ "name": "ops",+ "displayName": "Operations",+ "roomId": "ops",+ "agents": [+ { "role": "infra-monitor", "agentType": "perf-analyzer", "description": "Monitors service health and uptime", "preferLocal": true },+ { "role": "deploy-scout", "agentType": "cicd-engineer", "description": "Tracks deployment pipeline state", "preferLocal": false },+ { "role": "incident-responder","agentType": "security-auditor", "description": "Triages and escalates incidents to #exec", "preferLocal": false }+ ],+ "allowedMcpTools": [+ "memory_store", "memory_search",+ "federation_bbs_publish", "federation_bbs_watch", "federation_send",+ "aidefence_analyze", "aidefence_scan", "aidefence_stats",+ "terminal_execute",+ "http_fetch",+ "agent_execute"+ ],+ "_allowedMcpTools_notes": [+ "aidefence_* β alerting and threat-detection signals from the AIDefence subsystem",+ "terminal_execute β shell execution for ops scripts (e.g. health-check probes, log scrapes)",+ "http_fetch β external HTTP endpoint monitoring (see Β§5.1.8 for contract; Phase 2 prerequisite)",+ "agent_execute β delegates to cloud Managed Agents with AWS/GCP/Azure SDK access for cloud-infra ops",+ "Cloud-provider MCP servers (e.g. aws-mcp, gcp-mcp) are deployment-specific; NOT bundled. Must be registered per-installation via `ruflo mcp config add`."+ ],+ "bench": {+ "name": "ops-availability-bench",+ "description": "Measures service availability and incident response lag",+ "successCriteria": [+ "No unacknowledged P1 alert older than 15 min",+ "Deployment pipeline green or escalated within 30 min",+ "Infra health check at least every 4h",+ "HTTP endpoint monitor: probe a synthetic endpoint returning 200 OK 90% / 500 10% of the time; pod must detect the 500 rate and post an alert to #ops within 60 seconds"+ ],+ "scheduleHours": 4+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 30,+ "budgetUsdPerRun": 0.20,+ "preferLocalExecution": false,+ "cronSchedule": "0 */4 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 90+ }+}+```++### 4.5 Support pod++Support handles ticket triage, response drafting, and customer escalation routing. High-throughput, tolerates cloud execution, SOC2 PII policy.++```json+{+ "name": "support",+ "displayName": "Customer Support",+ "roomId": "support",+ "agents": [+ { "role": "ticket-triager", "agentType": "researcher", "description": "Classifies and prioritises incoming tickets", "preferLocal": false },+ { "role": "response-drafter", "agentType": "api-docs", "description": "Drafts first-response replies for review", "preferLocal": false },+ { "role": "escalation-router", "agentType": "task-orchestrator", "description": "Routes escalations to #ops or #exec", "preferLocal": false }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch", "federation_send"],+ "bench": {+ "name": "support-response-bench",+ "description": "Measures first-response time and classification accuracy",+ "successCriteria": [+ "First-response draft within 2h of ticket open",+ "Classification accuracy > 90% (spot-checked by human weekly)",+ "Escalations routed within 30 min of P1 classification"+ ],+ "scheduleHours": 2+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 60,+ "budgetUsdPerRun": 0.25,+ "preferLocalExecution": false,+ "cronSchedule": "0 */2 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 180+ }+}+```++### 4.6 HR pod++HR handles onboarding checklists, policy document retrieval, and leave tracking. All execution is local. GDPR policy. Runs daily.++```json+{+ "name": "hr",+ "displayName": "Human Resources",+ "roomId": "hr",+ "agents": [+ { "role": "onboarding-agent", "agentType": "planner", "description": "Tracks onboarding checklist progress per employee", "preferLocal": true },+ { "role": "policy-retriever", "agentType": "researcher", "description": "Answers policy queries from employees", "preferLocal": true },+ { "role": "leave-tracker", "agentType": "database-specialist","description": "Reconciles leave requests against policy", "preferLocal": true }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch"],+ "bench": {+ "name": "hr-compliance-bench",+ "description": "Measures policy query coverage and onboarding accuracy",+ "successCriteria": [+ "No onboarding step older than 48h without status update",+ "All leave requests classified within 24h",+ "Policy query response latency < 5 min"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "gdpr",+ "budgetUsdMonthly": 15,+ "budgetUsdPerRun": 0.05,+ "preferLocalExecution": true,+ "cronSchedule": "0 8 * * 1-5",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result"],+ "retentionDays": 365+ }+}+```++### 4.7 Exec (cross-cutting) pod++The `#exec` room is the cross-cutting coordination layer. It receives escalations from all other pods and presents a unified executive dashboard. The exec pod does not initiate work β it synthesizes and escalates.++```json+{+ "name": "exec",+ "displayName": "Executive",+ "roomId": "exec",+ "agents": [+ { "role": "cross-pod-synthesizer", "agentType": "task-orchestrator", "description": "Aggregates status from all pods and produces executive summary", "preferLocal": false },+ { "role": "risk-sentinel", "agentType": "security-auditor", "description": "Monitors cross-domain risk signals and escalates to human", "preferLocal": false }+ ],+ "allowedMcpTools": ["memory_store", "memory_search", "federation_bbs_publish", "federation_bbs_watch", "federation_send", "federation_peers", "federation_status"],+ "bench": {+ "name": "exec-dashboard-bench",+ "description": "Measures summary quality and escalation timeliness",+ "successCriteria": [+ "Executive summary produced at least every 24h",+ "All P1 escalations from sub-pods acknowledged in #exec within 15 min",+ "No cross-domain risk signal older than 1h unreviewed"+ ],+ "scheduleHours": 24+ },+ "piiPolicy": "soc2",+ "budgetUsdMonthly": 25,+ "budgetUsdPerRun": 0.40,+ "preferLocalExecution": false,+ "cronSchedule": "0 7 * * *",+ "auditReadView": {+ "includedEventTypes": ["task-result", "alert", "bench-result", "pod-status", "human-override-ack"],+ "retentionDays": 365+ }+}+```++---++## 5. Upstream changes required++### 5.1 In ruflo (this repository)++#### 5.1.1 New plugin: `plugins/ruflo-bbs-federation/`++Standard ruflo plugin structure (mirrors `plugins/ruflo-metaharness/`):++```+plugins/ruflo-bbs-federation/+βββ plugin.json # name, version, optionalDependencies: { "agentbbs": "^0.1.0" }+βββ scripts/+β βββ smoke.sh # smoke contract β must pass with agentbbs absent+β βββ register-rooms.mjs # CLI helper: register all rooms from a config file+βββ skills/+β βββ bbs-register/SKILL.md+β βββ bbs-publish/SKILL.md+β βββ bbs-watch/SKILL.md+β βββ bbs-human-join/SKILL.md+βββ src/+β βββ mcp-tools.ts # the four tools from Section 3.2+β βββ bbs-room-registry.ts # in-memory + persisted room config store+β βββ domain-affinity-policy.ts # @metaharness/router extension from Section 3.4+βββ agents/+ βββ bbs-coordinator.md # agent definition: orchestrates pod lifecycle+```++`plugin.json` must declare `agentbbs` in `optionalDependencies`, not `dependencies`. The CI workflow `no-bbs-smoke.yml` must assert that `npm install --ignore-optional` followed by `scripts/smoke.sh` exits 0.++#### 5.1.2 New plugin: `plugins/ruflo-business-pods/`++```+plugins/ruflo-business-pods/+βββ plugin.json+βββ templates/+β βββ sales.json+β βββ marketing.json+β βββ finance.json+β βββ ops.json+β βββ support.json+β βββ hr.json+β βββ exec.json+βββ scripts/+β βββ smoke.sh+β βββ init-pods.mjs # scaffold a pod from a template into the running ruflo node+βββ skills/+β βββ business-pods/SKILL.md+βββ src/+ βββ pod-template-loader.ts # validates and loads templates against the schema in Section 3.3+```++#### 5.1.3 Extension to `v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts`++The `inbound-dispatcher.ts` file currently contains an `InboundDispatcher` stub. The `federation_bbs_watch` tool requires a subscription registration API:++```typescript+// Add to InboundDispatcher class:+registerSubscription(+ sourceNodeId: string,+ targetAgentId: string,+ filter?: { eventKinds?: string[] }+): SubscriptionHandle;++deregisterSubscription(handle: SubscriptionHandle): void;+```++The subscription system delivers incoming `FederationEnvelope` messages to the registered agent. This is a required change, not an optional one β `federation_bbs_watch` is a no-op without it.++**File to modify**: `v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts`++#### 5.1.4 Extension to `v3/@claude-flow/plugin-agent-federation/src/domain/services/pii-pipeline-service.ts`++The PII pipeline currently applies a single global policy. Per-room PII modes require the pipeline to accept a policy config at call time rather than construction time:++```typescript+// Current signature (inferred from pii-pipeline-service.ts):+class PIIPipelineService {+ constructor(config: PIIPolicyConfig) { ... }+ transform(text: string, trustLevel: TrustLevel): PIITransformResult { ... }+}++// Required extension:+class PIIPipelineService {+ constructor(defaultConfig: PIIPolicyConfig) { ... }+ transform(+ text: string,+ trustLevel: TrustLevel,+ overrideConfig?: Partial<PIIPolicyConfig>+ ): PIITransformResult { ... }+}+```++The three compliance modes map to `PIIPolicyConfig` overrides:++| Compliance mode | `defaultAction` | Key overrides |+|-----------------|-----------------|---------------|+| `soc2` | `redact` | api_key β block; github_token β block |+| `gdpr` | `hash` | name β hash; email β hash; address β hash; phone β hash |+| `hipaa` | `block` | name β block; ssn β block; address β block; all PII β block by default |+| `permissive` | `pass` | no overrides |++**File to modify**: `v3/@claude-flow/plugin-agent-federation/src/domain/services/pii-pipeline-service.ts`+**File to modify**: `v3/@claude-flow/plugin-agent-federation/src/plugin.ts` (pass overrideConfig through to `FederationCoordinator.sendMessage`)++#### 5.1.5 Per-room spend cap in ADR-097 budget circuit breaker++The existing `enforceBudget` in `v3/@claude-flow/plugin-agent-federation/src/domain/value-objects/federation-budget.ts` accepts a `Budget` with `maxUsd` per call. The BBS plugin needs a per-room running balance that accumulates across the month and cuts off when the cap is hit.++This is a new `BbsRoomBudgetTracker` (not a change to `federation-budget.ts`, which is correct as a per-call primitive):++```typescript+// New file: plugins/ruflo-bbs-federation/src/bbs-room-budget-tracker.ts+interface BbsRoomBudgetTracker {+ /** Returns remaining USD for the room this month. Returns 0 if cap exceeded. */+ getRemainingUsd(roomId: string): Promise<number>;+ /** Records spend for this room. Persists to 'bbs-budget-<roomId>' namespace. */+ recordSpend(roomId: string, usdSpent: number): Promise<void>;+ /** Reset at the start of each billing month (called by the monthly cron). */+ resetMonthly(roomId: string): Promise<void>;+}+```++`federation_bbs_publish` calls `getRemainingUsd` before calling `sendMessage`; if the result is 0 it returns `{ blocked: true, reason: 'MONTHLY_BUDGET_EXCEEDED' }` without spending a token.++**File to create**: `plugins/ruflo-bbs-federation/src/bbs-room-budget-tracker.ts`++#### 5.1.6 Audit log business-owner read view++`v3/@claude-flow/plugin-agent-federation/src/domain/services/audit-service.ts` currently supports `query({ eventType, severity, since, limit })`. The BBS plugin needs a filtered view restricted to events a business owner can read (no internal trust-score mutations, no cryptographic details):++```typescript+// Add to audit-service.ts:+queryBusinessOwnerView(params: {+ roomId: string;+ since?: Date;+ limit?: number;+}): Promise<BusinessOwnerAuditEvent[]>;++interface BusinessOwnerAuditEvent {+ ts: string;+ roomId: string;+ eventKind: string;+ podAgentId: string;+ summary: string; // human-readable, PII-redacted+ outcome: 'success' | 'failure' | 'alert';+}+```++**File to modify**: `v3/@claude-flow/plugin-agent-federation/src/domain/services/audit-service.ts`++#### 5.1.8 New MCP tool: `http_fetch` (Phase 2 prerequisite)++The Ops pod requires the ability to probe external HTTP endpoints for availability monitoring. This tool does not exist in ruflo today and must be created.++**Minimal contract**:++```typescript+// New tool in plugins/ruflo-bbs-federation/src/mcp-tools.ts (or a shared http plugin)+{+ name: 'http_fetch',+ description: 'Perform a monitored HTTP GET/POST against an external endpoint. Subject to allowlist, timeout, and response-size constraints.',+ inputSchema: {+ type: 'object',+ properties: {+ url: {+ type: 'string',+ description: 'Target URL. Must match at least one pattern in the configured URL allowlist.',+ },+ method: {+ type: 'string',+ enum: ['GET', 'POST', 'HEAD'],+ default: 'GET',+ description: 'HTTP method.',+ },+ timeoutMs: {+ type: 'number',+ description: 'Request timeout in milliseconds. Default 5000. Max 30000.',+ default: 5000,+ },+ headers: {+ type: 'object',+ description: 'Additional headers. Auth headers (Authorization, Cookie, X-Api-Key) are BLOCKED unless the URL is on the explicit auth-header allowlist.',+ additionalProperties: { type: 'string' },+ },+ },+ required: ['url'],+ },+}+```++**Security constraints** (all enforced server-side, not by caller):+1. **URL allowlist**: the operator configures a list of URL patterns (e.g. `["https://status.myservice.com/*", "https://api.monitoring.example.com/health"]`). Requests to unlisted URLs are rejected with `403 URL_NOT_ALLOWLISTED`.+2. **Timeout cap**: maximum 30 seconds. Requests exceeding the cap are killed and return `{ error: 'TIMEOUT' }`.+3. **Response-size cap**: maximum 256 KB of response body. Larger responses are truncated at the cap; a `truncated: true` field is added to the result.+4. **No auth-header pass-through**: `Authorization`, `Cookie`, and `X-Api-Key` headers are stripped from all requests unless the URL is explicitly on a separate `authAllowedUrls` list (empty by default). This prevents the Ops pod from inadvertently leaking credentials to external endpoints.+5. **Audit logging**: every `http_fetch` call is logged to `AuditService` with URL, method, response status, latency, and caller agent ID.++**Phase gate**: `http_fetch` is a **Phase 2 prerequisite** for the Ops pod. Phase 1 can ship the stub (returns `{ degraded: true, reason: "http_fetch not yet implemented" }`). The ops bench scenario (Β§4.4) cannot complete until Phase 2 ships the full implementation.++#### 5.1.9 Optional dependency wiring in root package.json and ruflo wrapper++`agentbbs` must be added to `optionalDependencies` in:+- `/Users/cohen/Projects/ruflo/package.json` (root umbrella)+- `/Users/cohen/Projects/ruflo/ruflo/package.json` (ruflo wrapper β same lesson as metaharness in #2112: root overrides do not propagate to the published ruflo wrapper)++The graceful-degradation guard pattern (same as `plugins/ruflo-metaharness/src/*.ts`):++```typescript+let agentbbs: typeof import('agentbbs') | null = null;+try {+ agentbbs = await import('agentbbs');+} catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw e;+ // degraded mode β log warn, return { degraded: true } from all tools+}+```++### 5.2 In agentbbs upstream β survey findings (`ruvnet/agentbbs` @ ca3c6e0, 2026-06-29)++The agentbbs project is a mature Rust workspace with 30+ release tags. The Phase 1 survey of `crates/agentbbs-federation/` + `crates/agentbbs-mcp/` (commit `ca3c6e0` on `main`) resolved each compatibility check below. The survey is now concrete: each sub-section names the existing primitive ruflo will adapt to, or the genuine gap that needs an upstream PR.++A symmetric regression guard β [`ruvnet/AgentBBS#3`](https://github.com/ruvnet/AgentBBS/pull/3) β was opened against agentbbs and asserts on every PR + nightly cron that the four MCP tool names, four `FederationPayload` variants, and three `RufloAdapter` subcommand names this section depends on continue to exist. Drift becomes a failed nightly workflow within 24h of the upstream change landing.++Requests for upstream changes go to the agentbbs maintainer (same author, ruv). Each sub-section closes with a definite "no upstream PR needed for Phase 1" or "file issue X" β the survey replaces all earlier "VERIFY FIRST" hedges.++#### 5.2.1 Federation-envelope message kind compatibility++**Already covered by `crates/agentbbs-federation/src/envelope.rs::FederationPayload`.**++The enum is `#[serde(tag = "type", rename_all = "snake_case")]` with four variants:++```rust+pub enum FederationPayload {+ AnnounceBoard(Board),+ ReplicateMessage(Message),+ PeerHello { node: AgentId, protocol: String },+ Ack { id: String },+}+```++Each envelope is sealed by `FederationEnvelope::seal()` over deterministic canonical bytes signed with the sending node's Ed25519 key. `FederationEnvelope::open()` re-derives those bytes and verifies the signature; tampered or forged envelopes are rejected with `Error::BadSignature` (validated by `forged_node_id_rejected` + `tampered_payload_rejected` in `lib.rs` tests).++**Ruflo's adapter strategy for Phase 1 β Phase 3**:+- `federation_bbs_publish` β wraps the typed pod event inside a `ReplicateMessage(Message)` where `MessageBody.subject` carries the ruflo `msgType` discriminator (`pod-status` / `task-result` / `alert` / `human-override-ack` / `bench-result`) and `MessageBody.body` is the JSON-serialized typed payload.+- `federation_bbs_register` β drives `AnnounceBoard(Board)`; the agentbbs `Board` struct already round-trips through the PII scrubber in `Federator::announce_board()` (egress strips PII from `description` via `strip_pii`).+- The `hmacSignature` field in ruflo's `FederationEnvelope` shape is replaced by agentbbs's Ed25519-over-canonical-bytes signature on the outer `FederationEnvelope`. Stronger than HMAC; no behavior change needed in ruflo's Phase 1 layer β the agentbbs side computes + validates the signature.+- `piiScanResult` is **not** stored alongside the payload by agentbbs (PII is scrubbed and discarded). For ruflo's audit trail requirement, the `piiScanResult` must be persisted in ruflo's local `AuditService` (already the canonical record per Β§6.2) *before* the envelope is dispatched to agentbbs.++**No upstream PR required for Phase 1.** A possible Phase 3 enhancement: if richer routing per typed event becomes valuable, propose a `RufloEvent { envelope_id, msg_type, payload }` variant. Filed as a follow-up β not blocking.++#### 5.2.2 MCP tool registration shape++**Already covered by `crates/agentbbs-mcp/src/server.rs` β but as a static surface, not a dynamic registry.**++The MCP server exposes exactly four tools, registered as a hardcoded JSON array in `McpServer::tools_list()`: `list_boards`, `read_board`, `post_message`, `search_memory`. Dispatch in `tools_call()` is a hardcoded `match name { ... }` β there is no plugin/handler-registration hook.++Ruflo's `federation_bbs_register` / `federation_bbs_publish` / `federation_bbs_watch` / `federation_bbs_human_join` are **ruflo-owned MCP tools** that live in ruflo's MCP server, not in agentbbs's. The Phase 2 wire-up calls into agentbbs via one of two paths:++- (A) Spawn `agentbbs mcp` as a subprocess and drive its stdio JSON-RPC pipe β `federation_bbs_publish` becomes `tools/call name=post_message`, `federation_bbs_watch` becomes repeated `tools/call name=read_board`, `federation_bbs_register` becomes a board-creation call via the agentbbs CLI (no MCP tool for board creation β see gap below).+- (B) Depend on the agentbbs Rust crates directly via a native binding (heavier, deferred to Phase 4+).++**Phase 1**: ruflo's `agentbbsBin` argument is documented as "Reserved for Phase 2 wire-up; ignored in Phase 1". Phase 1 implements the ruflo-side MCP tool surface only; the spawned subprocess wiring lands in Phase 2.++**Genuine gap (filed as follow-up issue, not blocking Phase 1)**: `agentbbs-mcp` does not currently expose a `create_board` tool β board creation only happens via the direct `Bbs::create_board()` Rust API or via `agentbbs ssh` admin commands. For ruflo's `federation_bbs_register` to map cleanly to MCP, either (i) ruflo's Phase 2 register implementation drives `agentbbs federate β¦` CLI subcommands rather than MCP, or (ii) upstream adds `create_board` to the four-tool MCP surface. Filed as gap #1 below.++**No upstream PR required for Phase 1.** The web UI rendering concern previously documented here is moved to Phase 4 and re-scoped β `agentbbs-web` is out of scope until ruflo's pods publish enough events to make per-message-type rendering worthwhile.++#### 5.2.3 Subscription / streaming for `federation_bbs_watch`++**Genuinely missing β but matches ruflo's Phase 1 polling design.**++`crates/agentbbs-mcp/src/server.rs::initialize()` returns `capabilities.resources.subscribe = false`. The transport (`crates/agentbbs-mcp/src/transport.rs::serve_stdio`) is strict newline-delimited JSON-RPC request/response; there is no server-initiated push frame.++This matches ruflo's `federation_bbs_watch` Phase 1 contract verbatim: the tool description says *"Phase 1 is polling β Phase 4 layers streaming on the same surface."* The Phase 2 implementation will repeatedly call `tools/call name=read_board` with the agentbbs-side message ordering (`Message.id` is content-addressed and `Store::list_messages` returns ordered) and filter by ruflo's monotonic `sinceEnvelopeId`.++**Phase 4 gap (filed as follow-up issue, not blocking Phase 1)**: a streaming-subscribe path. Two design options for upstream:+- (A) Add `resources/subscribe` per the MCP spec β the server pushes `notifications/resources/updated` frames; ruflo consumes them in a long-poll loop.+- (B) Add an `agentbbs ssh subscribe #room` CLI subcommand that streams envelope JSON to stdout (the agentbbs project's SSH-first ethos suggests this is the more natural extension). Filed as gap #2 below.++**Durability and retention** were previously bundled into this sub-section; they're now their own concern in Β§5.2.5.++**No upstream PR required for Phase 1.**++#### 5.2.4 Integration seam β `RufloAdapter` already exists (other direction)++**Surprise finding: agentbbs already drives `npx ruflo federation` via `crates/agentbbs-federation/src/adapter.rs::RufloAdapter`.**++The adapter wraps a `CommandRunner` trait (production `TokioCommandRunner`, test `FakeCommandRunner`) and shells out to:++```+npx ruflo federation init+npx ruflo federation join <addr>+npx ruflo federation status+```++This means the integration direction agentbbs anticipated is: **agentbbs β ruflo as the federation control plane**. Ruflo's ADR-164 goes the *opposite* direction: ruflo β agentbbs as the room/event substrate. Both can coexist (asymmetric driving β ruflo manages federation peers, agentbbs publishes room events).++**Implications for ruflo**:+- Ruflo's CLI must keep `npx ruflo federation {init,join,status}` alive as a stable surface. Renaming or removing these breaks the agentbbs side silently. The regression guard at [`ruvnet/AgentBBS#3`](https://github.com/ruvnet/AgentBBS/pull/3) catches this β its third static-contract check greps for these exact subcommands in `adapter.rs` and fires if either side drifts.+- `RufloAdapter` is the seam through which agentbbs can use ruflo's memory/federation layer. Ruflo's Phase 2 wire-up will likely add a *reciprocal* `AgentBbsAdapter` (in ruflo) that drives `agentbbs federate` / `agentbbs mcp` from the ruflo side β mirroring the symmetric pattern.+- Ed25519 authentication (the previous "keypair handshake" concern) is **already implemented** in the envelope layer (Β§5.2.1). The `federation_bbs_human_join` single-use token validation is a ruflo-side concern (token minting + JTI replay protection), not an agentbbs concern β agentbbs just stores the signed envelopes.++**No upstream PR required for Phase 1.** Reciprocal `AgentBbsAdapter` is a ruflo Phase 2 deliverable (Β§5.1, not Β§5.2).++#### 5.2.5 Durable event retention and `sinceTs` replay++**Partial β postgres backend exists, but `agentbbs mcp` default uses in-memory store.**++`agentbbs.yml` + `ci.yml` both spin up `postgres:18-alpine` as a service container, confirming there is at least one postgres-backed `Store` impl somewhere in the workspace (likely under `agentbbs-web` or `agentbbs-gcp`). However, the integration tests in `crates/agentbbs-mcp/tests/mcp.rs` build the server with `MemoryStore`, and the `agentbbs` umbrella binary's `Command::Mcp` path in `crates/agentbbs/src/main.rs` does not surface a `--store postgres://...` flag in the public CLI usage (`agentbbs mcp` takes no documented store args).++**Implications for ruflo's `federation_bbs_watch` `sinceTs` replay**:+- Phase 1 + 2 ruflo's `federation_bbs_watch` polls the most-recent window (no `sinceTs` durability requirement β the ruflo-side `AuditService` is the canonical record per Β§6.2; agentbbs is the display projection).+- Phase 3+ (cross-session replay after BBS reconnect) requires durable agentbbs storage. The `sinceTs` query API needs to be exposed via `agentbbs mcp` as either a tool argument or a separate tool. Filed as gap #3 below.++**No upstream PR required for Phase 1/2.** Gap #3 is a Phase 3 prerequisite.++#### 5.2.6 Existing CI regression coverage and the gap this ADR fills++**No existing test exercises the agentbbs β ruflo integration end-to-end.**++`agentbbs.yml` runs fmt + clippy + nextest + cargo-deny over the agentbbs workspace. `agentbbs-federation`'s `ruflo_adapter_shells_npx` test uses `FakeCommandRunner` β it asserts the *intended* `npx ruflo federation β¦` invocations are emitted, but never spawns the real published `ruflo` CLI. Symmetric story for ruflo's side (Phase 1 doesn't shell out to agentbbs at all).++So the integration is currently held together by convention, not by a test. The regression guard at [`ruvnet/AgentBBS#3`](https://github.com/ruvnet/AgentBBS/pull/3) closes the gap with three contract-grep checks plus a live `agentbbs mcp` stdio roundtrip:++1. `agentbbs-mcp/src/server.rs` still registers `list_boards`, `read_board`, `post_message`, `search_memory`+2. `agentbbs-federation/src/envelope.rs::FederationPayload` still has `AnnounceBoard`, `ReplicateMessage`, `PeerHello`, `Ack`+3. `agentbbs-federation/src/adapter.rs` still shells out to `npx ruflo federation {init,join,status}`++Per-room authorization (the original concern in this sub-section) is deferred β agentbbs's current model uses a global `Caps` permission set per MCP-server connection (`Role::Sysop`, `Role::Member`, `Role::Guest` in `crates/agentbbs-core/src/caps.rs`), not per-room ACLs. Each ruflo pod will get its own `(roomId, Caps)` binding by spawning a separate `agentbbs mcp` subprocess per room with the room's Caps β a process-level isolation pattern that doesn't require any upstream change. Filed as gap #4 below if multi-room-per-subprocess ever becomes a requirement.++**No upstream PR required for Phase 1/2.**++---++#### Genuine gaps (filed as follow-up issues against `ruvnet/agentbbs`)++| # | Gap | Phase blocked | Severity |+|---|-----|--------------|----------|+| 1 | No `create_board` MCP tool β board creation is Rust-API or SSH-admin only | 2 | Low (workaround: ruflo's Phase 2 `federation_bbs_register` calls `agentbbs federate` CLI) |+| 2 | No subscription / push frame in MCP β `resources.subscribe = false` hardcoded | 4 | Low (Phase 1-3 polling is by design) |+| 3 | `agentbbs mcp` default uses `MemoryStore`; no documented `--store postgres://...` flag despite postgres being in CI | 3 | Medium (durable replay deferred) |+| 4 | `Caps` is per-connection, not per-room | 5+ | Low (workaround: process-per-room) |++Draft bodies for these issues are kept in the Phase 1 hand-off ticket and will be filed against `ruvnet/agentbbs` once Phase 1 lands.++---++## 6. Security and compliance++### 6.1 Per-room PII policy++Each room has an immutable PII policy set at registration time by `federation_bbs_register`. The PII pipeline applies this policy to every outbound envelope before HMAC signing (in `FederationCoordinator.sendMessage`) and to every inbound envelope on arrival (in the inbound dispatcher). The policy cannot be downgraded at runtime without re-registering the room (which requires an `admin`-level human token and is logged in the audit trail).++Policy escalation (tightening) is always allowed; relaxation requires admin + explicit reason logged.++### 6.2 Audit trail flow++```+Pod agent produces event+ β federation_bbs_publish called+ β PII pipeline applied (compliance mode per room)+ β FederationEnvelope created + HMAC signed+ β FederationCoordinator.sendMessage() dispatches to BBS room+ β AuditService.log() records the event (full envelope, not just summary)+ β BusinessOwnerAuditEvent projected (PII-stripped summary for #exec display)+ β BBS room post stored (hmacSignature preserved)+```++The canonical audit record is in `AuditService` (local, durable). The BBS post is a display projection. If the BBS is unavailable, audit records still accumulate locally and are replayed when the BBS reconnects.++### 6.3 Pod kill switch++The business owner (or CFO, for finance) can stop a pod in three ways, in order of severity:++1. **Pause one task**: post a `human-override` message to the room via the BBS UI. The pod's override-handler agent (registered via `federation_bbs_watch`) receives this and sends a `{ type: "shutdown_request" }` message to the running task agent via `SendMessage`.++2. **Suspend the pod's federation peer**: call `federation_evict` (existing MCP tool, `mcp-tools.ts` line 267β291) with the room's `nodeId`. All subsequent `federation_bbs_publish` calls from the pod short-circuit with `PEER_EVICTED`.++3. **Monthly budget cap exhausted**: the `BbsRoomBudgetTracker` (Section 5.1.5) blocks `federation_bbs_publish` automatically when `getRemainingUsd` returns 0. This is the CFO kill switch β no human action required.++All three paths are logged in `AuditService` with `severity: 'critical'` and are visible in the business-owner read view.++### 6.4 HIPAA / SOC2 / GDPR modes per pod++| Room | Default mode | Rationale |+|------|-------------|-----------|+| sales | SOC2 | Customer data (emails, company names) in outreach; not health data |+| marketing | SOC2 | Campaign data, not health data |+| finance | GDPR | Financial records require GDPR-level PII hashing in EU contexts |+| ops | SOC2 | Infrastructure metadata; minimal PII risk |+| support | SOC2 | Customer tickets may contain email, name |+| hr | GDPR | Employee data (name, address, leave records) is squarely GDPR |+| exec | SOC2 | Aggregated summaries; PII already stripped by upstream pods |++A healthcare operator would override `support` and `hr` to HIPAA. The pod template `piiPolicy` field is the single configuration point; changing it triggers a re-registration of the room (audit-logged, requires admin token).++---++## 7. Performance and cost++**No performance benchmarks exist for agentbbs v0.1.0.** The numbers below are estimates based on current Anthropic API pricing and observed ruflo agent token usage from existing sessions.++### 7.1 Per-pod estimated monthly cost++| Pod | Cycles/month | Tokens/cycle est. | Model | Est. USD/month |+|-----|-------------|-------------------|-------|----------------|+| sales | 120 (6h) | ~4,000 input + 1,000 output | Sonnet | ~$7 |+| marketing | 60 (12h) | ~3,000 input + 1,500 output | Sonnet | ~$4 |+| finance | 30 (24h) | ~2,000 input + 500 output | Haiku (local) | ~$0.50 |+| ops | 180 (4h) | ~1,500 input + 500 output | Haiku | ~$1 |+| support | 360 (2h) | ~2,500 input + 1,000 output | Haiku/Sonnet mix | ~$10 |+| hr | 22 (weekdays 24h) | ~1,500 input + 300 output | Haiku | ~$0.25 |+| exec | 30 (24h) | ~5,000 input + 2,000 output | Sonnet | ~$5 |++**Total estimated: ~$28/month for a full 7-pod deployment.** This is a rough estimate, not a measured number. Actual costs depend on prompt design, bench iteration depth, and which tasks surface during perpetual operation. Operators should set `budgetUsdMonthly` conservatively for the first month and raise based on observed spend.++### 7.2 Budget accounting for BBS publish++A single `federation_bbs_publish` call dispatches one `federation_send` which counts as one hop in the budget circuit breaker. The BBS room is modeled as a zero-cost relay (it stores the message but doesn't run an LLM). Spend is attributed to the originating pod agent, not to the BBS room, by `federation_report_spend`.++For accounting purposes, one BBS publish = one spend event in the `federation-spend` memory namespace (key: `fed-spend-<roomId>-<ts>`). The cost-tracker plugin (`plugins/ruflo-cost-tracker/scripts/federation.mjs`) already aggregates these; no change needed there.++### 7.3 Budget circuit breaker hardening++> **Atomicity design lives in ADR-164.1; this section summarises the requirements only.** ADR-164.1 (the companion atomic budget-tracker ADR, being written in parallel) specifies the full concurrency design. See Β§9.5 for the associated risk entry which forwards to ADR-164.1.++The existing `enforceBudget` function in `federation-budget.ts` is synchronous and cannot be raced by two concurrent send calls (documented in the file's security invariants comment at line 7). The per-room monthly tracker (`BbsRoomBudgetTracker`) is an async read-then-write which *can* be raced. ADR-164.1 must satisfy the following four requirements:++1. **Atomic reserve-and-commit**: spending must use a reserve-then-commit protocol. A call to `federation_bbs_publish` must atomically reserve the estimated spend (preventing concurrent calls from both seeing non-zero balance) and commit the actual spend only after the underlying `sendMessage` call returns success. If `sendMessage` fails, the reserved amount is released.++2. **Write-side serialization**: no read-then-write windows are permitted for the per-room balance. Either a database-level row lock (for postgres backends) or a process-level serialization primitive (e.g., a Mutex per roomId in-memory, backed by a CAS operation in the persistence layer) must ensure that two concurrent publishes cannot both pass a nearly-exhausted budget.++3. **Explicit expiry semantics for unconfirmed reservations**: if a reserve succeeds but the publisher crashes before committing, the reserved amount must expire after a configurable timeout (default: 60 seconds) and return to the available balance. ADR-164.1 must define the expiry mechanism and its interaction with the monthly reset cron.++4. **Audit-log integration**: every reserve, commit, and release operation must write a `federation_spend` event to `AuditService`. The event type must be distinguishable (`reserve`, `commit`, `release-success`, `release-expiry`) so the audit trail accurately reflects the lifecycle of each spend unit.++---++## 8. Rollout plan++The agenticow integration (PR #2500, v3.15.0) established the pattern: optional-dep wiring first, smoke contract on day one, measured evidence before deeper phases. This ADR follows the same playbook.++### Phase 1: Federation BBS MCP tools + smoke contract (target: 1 MINOR release)++Deliverables:+- `plugins/ruflo-bbs-federation/` scaffold with the four MCP tools from Section 3.2+- Graceful-degraded behavior when agentbbs is not installed (all tools return `{ degraded: true }`)+- `plugins/ruflo-bbs-federation/scripts/smoke.sh` passing with and without agentbbs+- `agentbbs` in `optionalDependencies` of root and ruflo wrapper `package.json`+- CI workflow `no-bbs-smoke.yml` asserting the absent-agentbbs path+- `inbound-dispatcher.ts` subscription stub (returns no-op handle, does not deliver events yet)++What is NOT in Phase 1:+- Working `federation_bbs_watch` delivery (stub only)+- Per-room budget tracker+- Domain-affinity policy extension+- Any business pod templates++Exit criteria: `scripts/smoke.sh` exits 0 with and without agentbbs installed. Fleet meta-smoke shows ruflo-bbs-federation green. No regressions in existing federation tests.++Semver: MINOR (additive plugin, no breaking changes).++### Phase 2: One pod end-to-end (sales), local + remote peer++Deliverables:+- `plugins/ruflo-business-pods/` with the sales pod template (`templates/sales.json`)+- `pod-template-loader.ts` with JSON schema validation+- Working `federation_bbs_watch` delivery via `inbound-dispatcher.ts` subscription API (Section 5.1.3 change landed)+- Per-room budget tracker (`bbs-room-budget-tracker.ts`) with monthly reset cron+- Sales pod running end-to-end against a local agentbbs instance (manual verification)+- Per-room PII pipeline override (Section 5.1.4 change to `pii-pipeline-service.ts` landed)++Exit criteria: Sales pod bench cycle completes and publishes a `bench-result` event to the BBS room. Human override (test harness) redirects a running task and pod acknowledges. Budget cap blocks further publishes when exceeded.++Semver: MINOR.++### Phase 3: All pods + cloud Managed Agent routing++Deliverables:+- All six remaining pod templates (marketing, finance, ops, support, hr, exec)+- Domain-affinity policy wired into `@metaharness/router` (Section 3.4)+- Marketing and support pods routing outbound tasks to Managed Agents (ADR-115 `managed_agent_*` tools)+- Finance and HR pods asserting local-only execution in bench tests+- Per-pod spend tracking visible in `ruflo cost` dashboard+- Upstream agentbbs changes confirmed shipped: typed envelope kind + durable log + token validation (Section 5.2 items 1, 3, 4)++Exit criteria: All seven pods running concurrently. Exec pod producing daily summary. No pod exceeds its `budgetUsdMonthly` in a test run. Finance pod tasks route to local stdio exclusively.++Semver: MINOR (all additive).++### Phase 4: Human override semantics + BBS web UI polish++Deliverables:+- Full human override lifecycle: post β parse β redirect/shutdown β acknowledge β audit log+- agentbbs web UI renders `federation-envelope` post kinds with domain components (Section 5.2.2)+- SSH "room subscribe" streaming available (Section 5.2.5)+- Per-room access controls enforced by agentbbs (Section 5.2.6)+- `federation_bbs_human_join` token validation working end-to-end via agentbbs auth (Section 5.2.4)+- Business-owner audit read view surfaced in BBS UI++Exit criteria: Business owner (manual test) can watch all seven rooms, post an override to #sales, see it acknowledged by the pod, and inspect the audit trail β all without touching a terminal.++Semver: MINOR (additive UI / override semantics).++### Phase 5: Business-owner GA++Deliverables:+- Measured cost-per-domain numbers (real runs, not estimates) added to CLAUDE.md+- `ruflo doctor --component bbs-federation` reporting agentbbs version, registered rooms, pod health+- Published agentbbs integration documentation+- Migration guide for operators who want to add custom pod templates+- `ruflo metaharness oia-audit` extended to include BBS-specific compliance checks++Exit criteria: Full 7-pod deployment running for β₯30 days in a real business environment with measured costs and zero cost runaway incidents. Business-owner GA announcement.++---++## 9. Open questions and risks++### 9.1 Real integration risks for the agentbbs Rust workspace++The previous version of this ADR mis-stated agentbbs as "v0.1.0, 16 hours old, no test suite." That was incorrect β the npm launcher is v0.1.0 but the Rust workspace is mature (30+ release tags, postgres-backed CI, 13 crates including `agentbbs-mcp` and `agentbbs-federation`). The actual risks are different:++**Risk 9.1.a β npm launcher version vs. Rust workspace version drift**: The npm package `[email protected]` and the Rust workspace (currently at `v0.34.9-nethack`) are independently versioned. The integration must pin against the Rust workspace tag for compatibility purposes. If a future npm release silently picks up an incompatible Rust binary, the BBS cockpit may break without a semver signal. Mitigation: pin the Rust binary version explicitly in `plugin.json` and add a Phase 1 smoke check that asserts the binary version reported by `agentbbs --version` matches the pinned value.++**Risk 9.1.b β FSL-1.1-Apache-2.0 license implications**: The Functional Source License converts to Apache-2.0 after 2 years. In the current FSL period, ruflo (MIT) may distribute agentbbs as an `optionalDependency` for use by operators, but embedding agentbbs binaries in a ruflo distribution that is itself sold as a product may require explicit FSL compliance review. Mitigation: legal review before Phase 3. Phase 1 and Phase 2 are unaffected (operator installs agentbbs separately; ruflo does not bundle it).++**Risk 9.1.c β `cargo` required at first run**: The Rust workspace compiles from source on the operator's machine unless a pre-built binary is available. Operators without `cargo` in their PATH will see a compilation failure, not a graceful-degradation response. Mitigation: the `no-bbs-smoke.yml` CI workflow must test the absent-agentbbs path (graceful degradation), not only the present-agentbbs path. Document the `cargo` requirement prominently in `plugins/ruflo-bbs-federation/README.md`. Phase 3+ may consider shipping a pre-built binary via npm for common platforms.++**Risk 9.1.d β `agentbbs-mcp` compatibility with ruflo's `MCPTool` interface**: The existing `crates/agentbbs-mcp/src/server.rs` implements an MCP server, but its tool interface shape (JSON-RPC envelope, tool name conventions, parameter types) has not been verified against ruflo's `MCPTool` interface. If there is a mismatch (e.g., different `inputSchema` conventions or different transport handshake), the four BBS MCP tools in Β§3.2 may need an adapter layer. Mitigation: Phase 1 deliverable includes a documented compatibility matrix produced by reading `crates/agentbbs-mcp/src/server.rs` against ruflo's `MCPTool` type definition. Incompatibilities are resolved in Phase 1 (adapter shim) before Phase 2 proceeds.++### 9.2 Persistence semantics of agentbbs BBS rooms++It is not clear whether agentbbs stores posts durably or keeps them in memory. If BBS state is ephemeral, the `sinceTs` replay in `federation_bbs_watch` will not work across BBS restarts, and the business-owner audit read view will show gaps. The federation audit log (`audit-service.ts`) is the canonical source and does not depend on BBS persistence β but the BBS as a display layer will be unreliable until this is confirmed and documented.++**Action before Phase 2**: open an issue in `ruvnet/agentbbs` requesting confirmation of persistence semantics and a documented retention API.++### 9.3 Concurrent-edit / CRDT problem++When multiple pod agents publish to the same BBS room concurrently, and a human posts an override simultaneously, the ordering of events is not guaranteed. The federation envelope carries an `hmacSignature` over a deterministic payload (including `timestamp` and `nonce`), but there is no vector clock or CRDT layer to resolve conflicts. For most business autopilot scenarios this is acceptable (last-write-wins per field is fine for a daily summary; ordering only matters for overrides). For override messages specifically, the pod agent should apply the most recent human override by `timestamp` and discard earlier ones.++This is a known design limitation, documented here for future consideration. CRDT adoption is out of scope for this ADR.++### 9.4 Trust elevation path for new BBS rooms++The trust model (Section 3.5) starts BBS rooms at `TrustLevel.ATTESTED`. There is no automated path to `TrustLevel.TRUSTED` without `minInteractions: 500` (per `TRUST_TRANSITION_THRESHOLDS` in `trust-level.ts` line 17). An operator who wants a room at TRUSTED must either wait for 500 interactions or implement an out-of-band attestation mechanism. This is by design β trust is earned, not configured β but operators should be aware that the full `collaborative-task` and `share-context` capabilities are not available at room registration time.++**No action required**: the current trust model is correct. This is a documentation note.++### 9.5 LLM cost runaway risk on perpetual operation++The perpetual-loop pattern (`cronSchedule` + Darwin /loop) means agents run indefinitely. A buggy bench that never terminates, or an agent that calls expensive models in a tight loop, can exhaust a monthly budget in hours. The `BbsRoomBudgetTracker` (Section 5.1.5) is the primary defense, but it has an async race condition (Section 7.3) that could allow brief overshoot.++**See ADR-164.1 Β§3 for the resolved concurrency design** (atomic reserve-and-commit, write-side serialization, expiry semantics, audit-log integration). The race condition risk is considered resolved by ADR-164.1; this section tracks the remaining operational risks.++Mitigation requirements for Phase 2 before GA:+1. Hardened tests for the `BbsRoomBudgetTracker` race, verifying the ADR-164.1 design: two concurrent publishes against a budget of $0.01 must not both succeed. These tests must be green before Phase 2 exit criteria are declared met.+2. A daily `federation_report_spend` rollup for each room, alerting to `#exec` if the trailing 7-day spend rate implies monthly cap breach before month end.+3. An emergency `federation_evict` shortcut in the BBS UI for the business owner (do not require terminal access to stop a runaway pod).++### 9.6 agentbbs API surface may change between v0.1.0 and v0.2.0++Given that the metaharness project moved from `0.1.0 β 0.1.11` in ~23 hours (noted in ADR-150 context), agentbbs may similarly iterate fast. The integration layer must avoid deep coupling to agentbbs internals. The four MCP tools must only depend on the agentbbs HTTP/WebSocket endpoint and authentication API β not on internal agentbbs modules.++If agentbbs introduces a breaking API change before Phase 3, the graceful-degraded path ensures ruflo continues operating; only the BBS cockpit goes dark until the adapter is updated.++### 9.7 No benchmark for BBS round-trip latency++`federation_bbs_publish` dispatches a `federation_send` and waits for acknowledgment from the BBS. We do not know the round-trip latency of agentbbs v0.1.0. If it is high (>500ms per publish), the perpetual loop for high-frequency pods (ops: every 4h, support: every 2h) will not be materially affected, but real-time human override delivery could feel sluggish.++**Action before Phase 4**: benchmark BBS round-trip latency under realistic load and document it alongside the smoke contract results.++---++## 10. Alternatives considered and rejected++### 10.1 BBS-as-transport (rejected)++One option was to replace the federation's WebSocket/QUIC transport with agentbbs's SSH/HTTP endpoints entirely β making BBS the transport layer, not a peer.++Rejected because: (a) federation transport is intentionally pluggable (ADR-104, ADR-120) but abstracting BBS at the transport level would couple every federation feature to agentbbs availability; (b) the mandatory graceful-degradation invariant (ruflo operational without agentbbs) is much harder to satisfy at the transport layer than at the peer layer; (c) BBS-as-transport would prevent federation from using WG mesh (ADR-111) for high-security peers, which finance and HR require.++### 10.2 BBS-as-surface-only (rejected)++Another option was to treat agentbbs as a pure display layer β a read-only dashboard that subscribes to ruflo memory events but has no write path back to agents.++Rejected because: it eliminates the human override path, which is the central safety mechanism for a perpetual business autopilot. A business owner who cannot stop a running agent from the cockpit is not in control. The override path requires a write channel from the BBS to the pod.++### 10.3 Build our own business cockpit UI from scratch (rejected)++Building a ruflo-native business cockpit was considered. It would eliminate the dependency on an unproven v0.1.0 project.++Rejected because: (a) a BBS-style interaction paradigm is a good fit for the "rooms by business function" model and agentbbs already provides it; (b) the integration effort is substantially less than building a UI from scratch; (c) agentbbs is first-party (same author) and can be coordinated with; (d) the graceful-degradation requirement means ruflo does not *depend* on agentbbs β if agentbbs fails to mature, the federation primitives built here remain useful without the BBS cockpit.++### 10.4 Use Slack instead of agentbbs (rejected)++Slack has a mature API, proven persistence, and a UI every business owner already uses.++Rejected for the short term because: (a) Slack is a third-party SaaS with per-seat pricing that adds external dependency for what should be self-hosted; (b) Slack's API does not natively support typed federation envelopes β we would need an adapter layer of similar complexity to what we're building for agentbbs; (c) the SSH front door in agentbbs is a meaningful capability for headless agent participation that Slack does not provide. A `ruflo-slack-federation` plugin following this same ADR pattern is a viable future alternative if agentbbs proves immature.++---++## 11. References++| Reference | What it contributes to this ADR |+|-----------|--------------------------------|+| ADR-097 (federation budget circuit breaker) | `enforceBudget`, `validateBudget`, `BudgetEnforcement` primitives used unchanged; per-room monthly tracker is additive |+| ADR-110 (production spend reporter) | `SpendReporter` + `MemorySpendReporter` pattern; `BbsRoomBudgetTracker` follows the same storage-agnostic interface |+| ADR-111 (WG mesh transport) | Finance and HR pods must route over WG mesh when using remote ruflo peers |+| ADR-115 (managed agents cloud backend) | Sales, marketing, and support pods delegate high-throughput tasks to Managed Agents via `managed_agent_*` MCP tools |+| ADR-150 (metaharness integration surfaces) | Defines the optional-dep integration pattern this ADR mirrors: optionalDependencies, graceful-degradation, smoke contract, CI gate |+| ADR-001 (deep-integration philosophy) | Build as an extension of existing primitives (federation, router, audit), not a parallel system |+| PR #2500 (agenticow v3.15.0) | Precedent for the optional-dep integration onboarding: optional dep wiring + smoke contract + measured findings before deeper phases |+| `v3/@claude-flow/plugin-agent-federation/src/mcp-tools.ts` | All 14 existing federation MCP tools; the four new BBS tools wrap these, not replace them |+| `v3/@claude-flow/plugin-agent-federation/src/domain/entities/federation-envelope.ts` | `FederationMessageType` union β `'context-share'` and `'task-assignment'` are the message types used by BBS room events |+| `v3/@claude-flow/plugin-agent-federation/src/domain/entities/trust-level.ts` | `TrustLevel` enum + `CAPABILITY_GATES` + `TRUST_TRANSITION_THRESHOLDS` β BBS rooms start at ATTESTED (level 2) |+| `v3/@claude-flow/plugin-agent-federation/src/domain/services/pii-pipeline-service.ts` | `PIIPolicyConfig`, `PIIAction`, `PIIType` β extended with per-call override in Section 5.1.4 |+| `v3/@claude-flow/plugin-agent-federation/src/domain/value-objects/federation-budget.ts` | `DEFAULT_MAX_HOPS=8`, `enforceBudget` security invariants β used as-is; per-room monthly cap is a separate layer |+| `v3/@claude-flow/plugin-agent-federation/src/application/spend-reporter.ts` | `FederationSpendEvent`, `MemorySpendReporter` β BBS publish reports spend through this interface |+| `v3/@claude-flow/plugin-agent-federation/src/application/inbound-dispatcher.ts` | Requires subscription API (Section 5.1.3) β current file is a stub |+| `plugins/ruflo-metaharness/scripts/smoke.sh` | Reference implementation for the smoke contract pattern |+| `docs/agenticow/findings.md` | Example of the measured-evidence approach before deeper integration phases |++---++## Appendix A: Decisions made autonomously where the brief was ambiguous++The brief described the trust model as "how BBS rooms get trust tier scoring" without specifying the starting tier. This ADR assigned `TrustLevel.ATTESTED` (level 2) because: (a) rooms are operator-registered, not auto-discovered, which is materially more trustworthy than a cold join; (b) VERIFIED (level 1) would not allow `share-context` which is needed for the exec pod's cross-pod synthesis; (c) TRUSTED (level 3) requires 500 interactions by the existing threshold logic and cannot be granted at registration time without modifying trust-level.ts in a way this ADR does not propose.++The brief said "Finance pod prefers local." This ADR extended that to HR as well, because HR handles employee personal data (names, addresses, leave records) which maps to GDPR-level sensitivity on the same reasoning as financial records. The brief listed HR as a separate pod but did not specify its routing preference.++The brief described the budget circuit breaker "per-room spend caps" but did not specify whether the cap is per-call or monthly. This ADR chose monthly because: (a) the CFO mental model is a monthly budget, not a per-API-call limit; (b) the existing `enforceBudget` already handles per-call limits; (c) a monthly tracker is the additive layer needed, not a modification to the existing mechanism.++The brief said "agenticow was shipped today via PR #2500 / v3.15.0." This ADR references it as the precedent for optional-dep onboarding pattern. The actual PR content was not read directly, but the agenticow findings file (`docs/agenticow/findings.md`) confirms the measured-evidence approach used there.++---++### Peer review corrections (2026-06-29) β resolved in this edit++The following corrections were applied during peer review of this ADR. Each is marked with the section(s) it affected.++**Correction PR-1 β Agentbbs maturity assessment rewrite** (affects Β§External references header, Β§1.2 table, Β§1.3, Β§5.2, Β§9.1)++The initial draft characterized agentbbs as "v0.1.0, 16 hours old, no test suite, unproven." This was incorrect. The npm package `[email protected]` is a thin launcher; the actual project is a mature Rust workspace at `github.com/ruvnet/agentbbs` with 13 crates, 30+ release tags (latest: `v0.34.9-nethack`), 7 GitHub Actions CI workflows, postgres-backed integration tests, existing `crates/agentbbs-mcp/` MCP server, existing `crates/agentbbs-federation/` federation crate, Docker stack, `deny.toml`, and `.gitguardian.yaml`. All passages asserting immaturity were replaced with accurate language. Β§5.2 was restructured from "changes needed" to "verify-first" β each sub-section now surveys the existing crate before specifying any upstream PR. Β§9.1 was rewritten with the four real integration risks: (a) npm launcher / Rust workspace version drift, (b) FSL license implications, (c) `cargo` required at first run, (d) `agentbbs-mcp` interface compatibility. Status: **resolved** β all affected passages updated in this edit.++**Correction PR-2 β Atomic budget tracker forward-reference to ADR-164.1** (affects Β§7.3, Β§9.5)++Β§7.3 previously described the async race condition in `BbsRoomBudgetTracker` and flagged it as an open risk. Per review, the atomicity design is being specified in a companion ADR-164.1 (written in parallel). Β§7.3 was rewritten to: (a) declare "atomicity design lives in ADR-164.1; this section summarises requirements only," (b) enumerate the four requirements ADR-164.1 must satisfy (atomic reserve-and-commit, write-side serialization, explicit expiry semantics for unconfirmed reservations, audit-log integration for every reserve/commit/release), and (c) not attempt to resolve the concurrency design itself. Β§9.5 was updated to forward to "ADR-164.1 Β§3 for the resolved concurrency design." Status: **resolved** β Β§7.3 and Β§9.5 updated in this edit. ADR-164.1 must be authored to satisfy the four requirements listed in Β§7.3.++**Correction PR-3 β Trust elevation escape hatch Β§3.5.4** (affects Β§3.5)++The organic trust accrual path (`minInteractions: 500` for `TRUSTED`) blocks the `#exec` cross-pod synthesizer from operating at full capability on Day 1. A founder-bootstrap escape hatch was added as Β§3.5.4. Specifies: new CLI subcommand `ruflo federation trust elevate <bbs-node-id> --to TRUSTED --reason "<text>" --audit`; `--reason` and `--audit` are mandatory; audit entry is tagged `bootstrap_elevation`; elevation is capped at `TRUSTED` (level 3); multi-party sign-off is a Phase 5 hardening item; Phase 1 ships with single-operator escape hatch; wire point is a new `bootstrapElevate()` method on `application/trust-evaluator.ts`. Status: **resolved** β Β§3.5.4 added in this edit.++**Correction PR-4 β Token expiry vs. long-lived streams (two-phase auth)** (affects Β§3.2.4)++Β§3.2.4 previously described the 15-minute Ed25519 token as the session mechanism without distinguishing handshake from session. Per review, the token must be single-use for the handshake (Phase A) and the resulting channel must be long-lived without mid-stream re-validation (Phase B). Β§3.2.4 was rewritten with explicit Phase A / Phase B language: Phase A consumes the token on first use (JTI/nonce recorded, replay rejected); Phase B keeps the channel open until explicit close, idle timeout (default 30 min), or BBS restart β no mid-stream re-auth. The SSH "room subscribe" long-running stream is explicitly called out as a Phase B session that must not re-validate mid-stream. Status: **resolved** β Β§3.2.4 updated in this edit.++**Correction PR-5 β Ops pod tooling expansion** (affects Β§4.4, Β§5.1)++The Ops pod's `allowedMcpTools` was insufficient for real ops work. Updated to include: `aidefence_*` (threat detection signals), `terminal_execute` (ops script execution), `http_fetch` (external endpoint monitoring β NEW tool, Phase 2 prerequisite), `agent_execute` (delegation to cloud Managed Agents with AWS/GCP/Azure SDK), and a note that cloud-provider MCP servers are deployment-specific and not bundled. A new Β§5.1.8 was added specifying the `http_fetch` tool's minimal contract: URL allowlist, 30s timeout cap, 256 KB response-size cap, no auth-header pass-through without explicit `authAllowedUrls` entry, audit logging on every call. Phase gate: Phase 2 prerequisite; Phase 1 ships a stub. The ops bench was updated with a concrete scenario: monitor a synthetic HTTP endpoint returning 200 OK 90% / 500 10% of the time; pod must detect the 500 rate and post an alert to `#ops` within 60 seconds. Status: **resolved** β Β§4.4 and Β§5.1.8 updated in this edit. `http_fetch` tool must be implemented before Phase 2 ops bench can pass.diff --git a/v3/docs/adr/ADR-164.1-budget-tracker-atomicity.md b/v3/docs/adr/ADR-164.1-budget-tracker-atomicity.mdnew file mode 100644index 0000000000..f0b030aeee--- /dev/null+++ b/v3/docs/adr/ADR-164.1-budget-tracker-atomicity.md@@ -0,0 +1,775 @@+# ADR-164.1 β BbsRoomBudgetTracker: Atomic Reserve-and-Commit Design++**ID**: ADR-164.1+**Status**: Draft+**Date**: 2026-06-29+**Authors**: claude (drafted with rUv)+**Companion to**: ADR-164 (AgentBBS Federated Business-Management Autopilot)+**Related**:+- ADR-097 (federation budget circuit breaker β per-call primitive this ADR layers over)+- ADR-145 (plugin supply-chain integrity and memory namespace governance β audit log foundation)+- better-sqlite3 documentation (WAL mode + `BEGIN IMMEDIATE` semantics)++---++## 1. Problem Statement++### 1.1 The race window++ADR-164 Β§5.1.5 introduces `BbsRoomBudgetTracker` with the following interface:++```typescript+getRemainingUsd(roomId: string): Promise<number>+recordSpend(roomId: string, usdSpent: number): Promise<void>+```++`federation_bbs_publish` calls `getRemainingUsd` and, if the result is greater than zero, proceeds to call `sendMessage` (which incurs cost), then calls `recordSpend`. This is a classic read-then-write pattern. Two concurrent callers can both read a remaining balance above zero, both pass the gate, and collectively spend more than the monthly cap.++### 1.2 Concrete example++Room `#sales` has a monthly cap of $1.00. Committed spend so far this month: $0.95. Remaining: $0.05.++Ten concurrent calls to `federation_bbs_publish` each estimate a cost of $0.05:++```+T0 caller-1 getRemainingUsd("sales") β 0.05 (passes gate)+T0 caller-2 getRemainingUsd("sales") β 0.05 (passes gate β reads same committed total)+T0 caller-3 getRemainingUsd("sales") β 0.05 (passes gate)+ ...+T0 caller-10 getRemainingUsd("sales") β 0.05 (passes gate)++T1 all 10 send messages, each spending $0.05+T2 all 10 call recordSpend("sales", 0.05)+T3 committed total = $0.95 + $0.50 = $1.45 β $0.45 over cap+```++In autopilot mode with a Finance pod running overnight, this race can accumulate into a multi-hundred-dollar surprise bill before the morning review window.++### 1.3 Why the existing `enforceBudget` doesn't solve this++`enforceBudget` in `v3/@claude-flow/plugin-agent-federation/src/domain/value-objects/federation-budget.ts` is a correct, synchronous, per-call primitive. It runs check-then-decrement with no awaits inside a single call. What it does NOT do is maintain a persistent monthly ledger. It is per-envelope, not per-room-per-month. The `BbsRoomBudgetTracker` fills that gap, but its naive implementation creates the race described above.++---++## 2. Decision++Use an **atomic reserve-and-commit token bucket** backed by better-sqlite3 in WAL mode.++SQLite's write-side serialization β specifically `BEGIN IMMEDIATE`, which acquires the write lock before any read β eliminates the race window. No compare-and-swap loops. No advisory locks. No file-system flocks. The SQLite write lock IS the serialization primitive.++The design has three operations:++1. **`reserve()`** β Before calling `sendMessage`, a caller atomically checks budget availability AND inserts a reservation row in a single `BEGIN IMMEDIATE` transaction. If budget would be exceeded, the transaction rolls back with `BUDGET_EXCEEDED`.+2. **`commit()`** β After `sendMessage` returns the actual cost, the caller commits the reservation with the real amount.+3. **`release()`** β If the caller decides not to proceed (or if the call fails before incurring cost), the reservation is released, returning budget to the pool immediately.++This three-phase contract replaces the two-phase read-then-write in the original design.++---++## 3. Data Model++### 3.1 Schema++The tracker maintains two tables in a dedicated SQLite file at `data/bbs-budget.db` (configurable via `CLAUDE_FLOW_BBS_BUDGET_DB`). The file is distinct from the main AgentDB store to avoid write contention on the higher-volume pattern/memory tables.++```sql+-- WAL mode MUST be set once on database open, before any transactions.+PRAGMA journal_mode = WAL;+PRAGMA synchronous = NORMAL; -- safe with WAL; fsync only on checkpoint++-- One row per registered BBS room. The _lock_bump column exists solely as+-- a write target for BEGIN IMMEDIATE serialization (see Section 5).+CREATE TABLE IF NOT EXISTS bbs_budget_rooms (+ room_id TEXT NOT NULL PRIMARY KEY,+ monthly_cap_usd REAL NOT NULL CHECK (monthly_cap_usd >= 0),+ billing_month TEXT NOT NULL, -- 'YYYY-MM', resets on month boundary+ _lock_bump INTEGER NOT NULL DEFAULT 0+);++-- One row per reservation lifecycle.+CREATE TABLE IF NOT EXISTS bbs_budget_reservations (+ reservation_id TEXT NOT NULL PRIMARY KEY, -- UUID v7 (sortable timestamp prefix)+ room_id TEXT NOT NULL REFERENCES bbs_budget_rooms(room_id),+ caller_node_id TEXT NOT NULL, -- federation node-id of the spending agent+ estimated_usd REAL NOT NULL CHECK (estimated_usd >= 0),+ actual_usd REAL, -- NULL until commit+ state TEXT NOT NULL+ CHECK (state IN ('reserved','committed','released','expired','committed_post_expiry')),+ reserved_at INTEGER NOT NULL, -- unix milliseconds+ expires_at INTEGER NOT NULL, -- reserved_at + 60_000 by default+ committed_at INTEGER, -- unix ms, NULL until commit+ audit_envelope_id TEXT NOT NULL -- FK to federation_spend audit entry+);++-- Covering index for the monthly window query in reserve().+CREATE INDEX IF NOT EXISTS idx_reservations_room_month+ ON bbs_budget_reservations (room_id, reserved_at);++-- Index for the expiry sweeper.+CREATE INDEX IF NOT EXISTS idx_reservations_expiry+ ON bbs_budget_reservations (state, expires_at)+ WHERE state = 'reserved';+```++### 3.2 Field notes++**`reservation_id` β UUID v7**: UUID v7 encodes a millisecond-precision timestamp prefix in the first 48 bits, making rows naturally sorted by creation time without a separate `ORDER BY reserved_at` clause on most queries. This is a purely aesthetic win; correctness does not depend on UUID v7 specifically. Any opaque unique string suffices.++**`_lock_bump`**: This column exists as a belt-and-suspenders mechanism alongside `BEGIN IMMEDIATE`. **Peer-review clarification (2026-06-29)**: serialization is *primarily* provided by `BEGIN IMMEDIATE` itself β which natively acquires a `RESERVED` lock on the entire SQLite database file the moment it executes, causing any concurrent `BEGIN IMMEDIATE` or write to block or throw `SQLITE_BUSY`. The `_lock_bump` UPDATE is an explicit write inside the transaction making the lock acquisition visible in code-review and any query-log analysis; it also defends against a future SQLite version changing `BEGIN IMMEDIATE` semantics. The increment value is never read by application logic β it's a write target by intent.++**`expires_at`**: Default is `reserved_at + 60_000` (60 seconds). The default is appropriate for standard cloud LLM calls (sub-30s typical). For pods that run **local, large, quantized models** (e.g. Finance pod doing multi-step reconciliation), a single task can legitimately take 2-3 minutes β the 60s default would cause every commit to land post-expiry and trigger `COMMIT_AFTER_EXPIRY` warnings (mathematically correct, but operationally noisy). To accommodate, the pod template loader (per ADR-164 Β§3.3) MUST honour an optional `reservationExpiryMs` field in the pod's JSON template, clamped to **[5_000, 300_000]** (5 sec floor to defang trivially-tiny windows; 5 min ceiling to defang unbounded-runaway). When unset, `CLAUDE_FLOW_BBS_RESERVATION_EXPIRY_MS` is used; when that is unset, the 60_000 default applies. The hard ceiling means even a misconfigured local pod cannot exceed 5 minutes per reservation, bounding the worst-case post-expiry-commit window.++**`audit_envelope_id`**: Every reservation must be paired with a `federation_spend` audit entry before insertion. The audit write and the reservation insert share the same outer transaction (see Section 6), so they are atomically linked. A JOIN on `bbs_budget_reservations.audit_envelope_id` reconstructs full spend history without a separate query.++---++## 4. API++### 4.1 TypeScript signatures++File: `plugins/ruflo-bbs-federation/src/bbs-room-budget-tracker.ts`++```typescript+/**+ * Atomically reserve budget before calling sendMessage.+ *+ * If successful, returns a reservationId the caller MUST pass to commit()+ * or release() when the downstream call finishes.+ *+ * On BUDGET_EXCEEDED the reservation is not created; the caller must abort+ * the send and return { blocked: true, reason: 'MONTHLY_BUDGET_EXCEEDED' }+ * to federation_bbs_publish.+ */+reserve(+ roomId: string,+ callerId: string,+ estimatedUsd: number+): Promise<+ | { ok: true; reservationId: string; remainingAfterReserve: number }+ | { ok: false; error: 'BUDGET_EXCEEDED' | 'ROOM_NOT_FOUND' }+>;++/**+ * Commit the reservation with the actual cost returned by sendMessage.+ *+ * actualUsd may be greater than estimatedUsd (overrun); see Section 8.3.+ * The reservation transitions from 'reserved' to 'committed'. Once+ * committed, the row is permanent β it cannot be released.+ */+commit(+ reservationId: string,+ actualUsd: number+): Promise<+ // ok-and-clean: reservation was live when commit landed+ | { ok: true; committed: true; finalRemaining: number }+ // ok-but-late: reservation had already expired when commit landed, but+ // the actual API spend was REAL and is now recorded against the budget.+ // Callers / audit dashboards should highlight this. See Β§5.3 Expired Commit+ // Leak fix (peer review 2026-06-29).+ | { ok: true; warned: 'COMMIT_AFTER_EXPIRY'; finalRemaining: number }+ | { ok: false; error: 'NOT_FOUND' | 'ALREADY_FINALIZED' }+>;++/**+ * Release the reservation if the send was not attempted or failed before+ * incurring cost. Transitions 'reserved' β 'released'. Released reservations+ * free their estimated_usd immediately (they are excluded from the window+ * query on the next reserve() call).+ *+ * Calling release() on a committed or already-released reservation is an+ * error; it indicates a caller bug.+ */+release(+ reservationId: string+): Promise<+ | { ok: true; released: true }+ | { ok: false; error: 'NOT_FOUND' | 'ALREADY_FINALIZED' }+>;+```++---++## 5. The Reserve Transaction (Load-Bearing Detail)++### 5.1 Why `BEGIN IMMEDIATE` is mandatory++SQLite has three transaction modes:++| Mode | Write-lock acquired | Risk |+|------|---------------------|------|+| `BEGIN` (deferred) | On first write | Two readers both pass the gate before either writes |+| `BEGIN IMMEDIATE` | Immediately on BEGIN | Only one caller holds the write lock; all others block |+| `BEGIN EXCLUSIVE` | Full database lock | Correct but blocks all readers; overkill here |++The race in Section 1.2 exists precisely because deferred mode allows two readers to execute the "check committed + reserved total" SELECT before either performs the INSERT. `BEGIN IMMEDIATE` closes this window: the write lock is acquired atomically with the transaction start, so the second caller blocks at its own `BEGIN IMMEDIATE` until the first commits or rolls back.++### 5.2 Pseudocode for `reserve()`++```+function reserve(roomId, callerId, estimatedUsd):++ auditEnvelopeId = generateAuditEntry(roomId, callerId, estimatedUsd)+ // ^-- audit write runs BEFORE the budget transaction starts.+ // If the audit write fails, we throw immediately: no budget state changes.+ // (Audit + budget must be atomic; see Section 6.)++ BEGIN IMMEDIATE;++ -- Step 1: Touch the room header row.+ -- This is the serialization primitive. SQLite grants the write lock+ -- to exactly one connection at a time. All other BEGIN IMMEDIATE+ -- callers block here until we commit or rollback.+ UPDATE bbs_budget_rooms+ SET _lock_bump = _lock_bump + 1+ WHERE room_id = roomId;++ -- Step 1b: If no rows updated, the room doesn't exist.+ IF rows_changed == 0 THEN+ ROLLBACK;+ RETURN { ok: false, error: 'ROOM_NOT_FOUND' };+ END IF;++ -- Step 2: Fetch room's monthly cap and verify billing month.+ SELECT monthly_cap_usd, billing_month+ FROM bbs_budget_rooms+ WHERE room_id = roomId;+ -- If billing_month != current YYYY-MM, reset (see Section 7.3).++ -- Step 3: Compute current financial position within this month.+ -- committed_total = sum of actual_usd for committed rows this month+ -- reserved_total = sum of estimated_usd for live reserved rows this month+ -- "live" = state='reserved' AND expires_at > now()+ -- "this month" = reserved_at >= start_of_billing_month (unix ms)+ SELECT+ COALESCE(SUM(CASE WHEN state = 'committed' THEN actual_usd ELSE 0 END), 0)+ AS committed_total,+ COALESCE(SUM(CASE WHEN state = 'reserved' AND expires_at > now_ms+ THEN estimated_usd ELSE 0 END), 0)+ AS reserved_total+ FROM bbs_budget_reservations+ WHERE room_id = roomId+ AND reserved_at >= billing_month_start_ms;++ -- Step 4: Gate check.+ projected = committed_total + reserved_total + estimatedUsd;+ IF projected > monthly_cap_usd THEN+ ROLLBACK;+ RETURN { ok: false, error: 'BUDGET_EXCEEDED' };+ END IF;++ -- Step 5: Insert the reservation.+ now_ms = Date.now();+ expiry = now_ms + RESERVATION_EXPIRY_MS; // default 60_000+ reservId = uuidv7();++ INSERT INTO bbs_budget_reservations+ (reservation_id, room_id, caller_node_id, estimated_usd,+ actual_usd, state, reserved_at, expires_at, committed_at,+ audit_envelope_id)+ VALUES+ (reservId, roomId, callerId, estimatedUsd,+ NULL, 'reserved', now_ms, expiry, NULL,+ auditEnvelopeId);++ COMMIT;++ remaining = monthly_cap_usd - (committed_total + reserved_total + estimatedUsd);+ RETURN { ok: true, reservationId: reservId, remainingAfterReserve: remaining };+```++### 5.3 Pseudocode for `commit()`++```+function commit(reservationId, actualUsd):++ BEGIN IMMEDIATE;++ SELECT state, room_id, estimated_usd, reserved_at, expires_at+ FROM bbs_budget_reservations+ WHERE reservation_id = reservationId;++ IF no row THEN+ ROLLBACK; RETURN { ok: false, error: 'NOT_FOUND' };+ END IF;++ IF state IN ('committed', 'released', 'expired') THEN+ ROLLBACK; RETURN { ok: false, error: 'ALREADY_FINALIZED' };+ END IF;++ IF expires_at <= Date.now() THEN+ -- Reservation expired before the caller committed.+ -- *** PEER-REVIEW FIX (2026-06-29): never let a real API spend escape the ledger. ***+ -- Previously: marked 'expired' and returned ok:false. This created the+ -- "Expired Commit Leak" β the API was actually called (spend incurred)+ -- but the budget tracker recorded nothing, so the monthly cap could be+ -- silently bypassed by any slow-LLM loop.+ -- Now: accept the spend, transition state to 'committed_post_expiry',+ -- record actual_usd, AND emit an alert envelope to the exec room.+ UPDATE bbs_budget_reservations+ SET state = 'committed_post_expiry',+ actual_usd = actualUsd,+ committed_at = Date.now()+ WHERE reservation_id = reservationId;+ -- The spend-reporter MUST emit a `reservation.committed_post_expiry`+ -- audit event in the same transaction (see Β§6.1 atomicity requirement).+ -- The federation-breaker-service treats this event as a budget consumer+ -- β cumulative spend still includes it for circuit-breaker math.+ COMMIT;+ RETURN { ok: true, warned: 'COMMIT_AFTER_EXPIRY', finalRemaining: <recomputed> };+ END IF;++ -- On overrun (actualUsd > estimatedUsd), we charge the room the+ -- actual amount regardless. See Section 8.3.+ UPDATE bbs_budget_reservations+ SET state = 'committed',+ actual_usd = actualUsd,+ committed_at = Date.now()+ WHERE reservation_id = reservationId;++ -- Re-compute remaining after commit (for the return value).+ SELECT monthly_cap_usd FROM bbs_budget_rooms WHERE room_id = room_id;+ SELECT COALESCE(SUM(actual_usd), 0) AS committed_total+ FROM bbs_budget_reservations+ WHERE room_id = room_id AND state = 'committed'+ AND reserved_at >= billing_month_start_ms;+ SELECT COALESCE(SUM(estimated_usd), 0) AS live_reserved_total+ FROM bbs_budget_reservations+ WHERE room_id = room_id AND state = 'reserved'+ AND expires_at > Date.now()+ AND reserved_at >= billing_month_start_ms;++ COMMIT;++ finalRemaining = monthly_cap_usd - (committed_total + live_reserved_total);+ RETURN { ok: true, committed: true, finalRemaining };+```++### 5.4 Pseudocode for `release()`++```+function release(reservationId):++ BEGIN IMMEDIATE;++ SELECT state FROM bbs_budget_reservations+ WHERE reservation_id = reservationId;++ IF no row THEN+ ROLLBACK; RETURN { ok: false, error: 'NOT_FOUND' };+ END IF;++ IF state IN ('committed', 'released', 'expired') THEN+ ROLLBACK; RETURN { ok: false, error: 'ALREADY_FINALIZED' };+ END IF;++ UPDATE bbs_budget_reservations+ SET state = 'released'+ WHERE reservation_id = reservationId;++ COMMIT;++ RETURN { ok: true, released: true };+```++---++## 6. Audit Log Integration++### 6.1 Atomicity requirement++Budget state and audit state must be kept in sync. A reservation that has no corresponding audit entry creates an unexplained gap in the spend history. An audit entry with no reservation row means the budget was potentially spent without being gated.++The sequencing is:++1. **Write audit entry first** (via `spend-reporter.ts β ProductionFederationSpendReporter`). This targets the `federation-spend` namespace, key `fed-spend-<roomId>-<ts>`, as specified by `DEFAULT_FEDERATION_SPEND_NAMESPACE` in `v3/@claude-flow/plugin-agent-federation/src/application/spend-reporter.ts`.+2. **Capture the returned key as `audit_envelope_id`**.+3. **Open `BEGIN IMMEDIATE` and insert the reservation row** referencing `audit_envelope_id`.++If step 1 fails (memory backend error), throw immediately β no reservation is created. If step 3 fails (budget exceeded, database locked, etc.), the audit entry is orphaned but the budget is NOT charged. Orphaned audit entries with no matching reservation_id are a diagnostic signal, not a correctness violation; they will be caught by the audit reconciliation job (out of scope for Phase 1-3).++### 6.2 Overrun entries++When `commit()` is called with `actualUsd > estimatedUsd`, a second audit event is written before the commit transaction:++```typescript+// emit a reservation_overrun audit entry via spend-reporter.ts+await spendReporter.reportSpend({+ peerId: roomId,+ taskId: reservationId,+ tokensUsed: 0,+ usdSpent: actualUsd - estimatedUsd,+ ts: new Date().toISOString(),+ success: true,+ // custom field consumed by ruflo-cost-tracker:+ eventKind: 'reservation_overrun',+});+```++This allows the `FederationBreakerService` (in `v3/@claude-flow/plugin-agent-federation/src/application/federation-breaker-service.ts`) to detect spend anomalies via its rolling sample buffer. If cumulative spend for the room crosses the 24h cap threshold (`dailySpendCapUsd`, default $5.00), the breaker can trip the room. See ADR-097 Β§Phase 2 for the breaker trip logic.++### 6.3 Cross-reference: ADR-097 Β§audit-log++The `federation_spend` events emitted here are consumed by `[email protected]` (ADR-097 Phase 3). The `audit_envelope_id` on each reservation row provides a direct JOIN path:++```sql+SELECT r.reservation_id, r.state, r.actual_usd, a.ts, a.peerId+FROM bbs_budget_reservations r+JOIN federation_spend_events a+ ON a.key = 'fed-spend-' || r.room_id || '-' || r.audit_envelope_id+WHERE r.room_id = 'finance'+ORDER BY r.reserved_at DESC+LIMIT 100;+```++Full month history for a room is reconstructable from this JOIN alone.++---++## 7. Expiry Handling++### 7.1 The sweeper++A background sweeper runs every 5 seconds (configurable via `CLAUDE_FLOW_BBS_SWEEP_INTERVAL_MS`). It transitions expired reservations from `reserved` to `expired`:++```typescript+// Runs on setInterval, not BEGIN IMMEDIATE β this is intentionally deferred.+async function sweepExpiredReservations(db: Database): Promise<number> {+ const now = Date.now();+ const result = db+ .prepare(`+ UPDATE bbs_budget_reservations+ SET state = 'expired'+ WHERE state = 'reserved'+ AND expires_at < ?+ `)+ .run(now);+ return result.changes;+}+```++Note this uses a regular `BEGIN DEFERRED` (the default for a single prepared statement). The sweeper does not compete with reserve()/commit() for correctness because:+- reserve() already excludes expired rows from its window query (`expires_at > now_ms`).+- The sweeper merely formalizes the state; it does not change what reserve() would observe.++### 7.2 Phantom debt (intentional safety bias)++Reservations in state `reserved` where `expires_at <= now()` are excluded from the window query in `reserve()`. This means their `estimated_usd` is NOT counted against the room's remaining budget from the perspective of new reservations.++However, expired-but-unswepped rows remain in state `reserved` until the sweeper runs. The sweeper may lag by up to `SWEEP_INTERVAL_MS` (default 5 seconds). During this window, the rows are already excluded from the gate check (since `expires_at <= now()`), so they do not block new reservations.++The intentional safety bias is: **expired reservations that have not been swept yet do NOT free up budget, but they also do NOT block new reservations.** This means a room can briefly have committed + reserved + expired totals that exceed the cap on paper, but new callers will correctly see available budget once the expiry timestamp passes.++If the sweeper crashes permanently (e.g., the process exits), expired rows accumulate indefinitely. They are excluded from gate checks, so correctness is maintained, but storage grows. The sweeper health is reported by `npx ruflo doctor --component bbs-budget`.++### 7.3 Monthly billing reset++On the first `reserve()` call after a month boundary, the tracker detects `billing_month != current-YYYY-MM` and runs a reset inside the same `BEGIN IMMEDIATE` transaction before the gate check:++```sql+UPDATE bbs_budget_rooms+ SET billing_month = ?, _lock_bump = _lock_bump + 1+ WHERE room_id = ?;+```++Old reservation rows from the previous month are NOT deleted on reset. They are retained for audit purposes until the retention policy purges them (configurable `retentionDays` per ADR-145 Β§namespace-governance). The window query is naturally scoped to `reserved_at >= billing_month_start_ms`, so old rows are ignored without deletion.++---++## 8. Open Questions++### 8.1 Expired commit handling β RESOLVED (peer review 2026-06-29)++**Original concern**: if a caller takes longer than `RESERVATION_EXPIRY_MS` to commit (slow model, network timeout), its reservations expire mid-flight. The first draft rejected the late commit with `EXPIRED`, meaning the actual API cost was incurred but the budget tracker showed nothing β a silent budget bypass (the "Expired Commit Leak").++**Resolution**: `commit()` on an expired reservation now ACCEPTS the spend, transitions state to `committed_post_expiry`, records `actual_usd` against the room's budget, returns `{ ok: true, warned: 'COMMIT_AFTER_EXPIRY', finalRemaining }`, AND emits a high-priority `reservation.committed_post_expiry` audit envelope to the room and (when configured) to `#exec`. This guarantees that every real API spend is reflected in the monthly cap math, even when execution windows are violated. The warning is the observability signal β repeated `COMMIT_AFTER_EXPIRY` for the same pod is a clear instruction to increase `reservationExpiryMs` for that pod template (or to investigate why the pod's calls are exceeding their expected window). See Β§3.2 `expires_at` field notes for per-pod tuning, Β§5.3 for the commit-path SQL, and Β§4.1 for the discriminated return shape.++A residual mitigation also applies: the per-pod `reservationExpiryMs` ceiling of 300_000 ms (5 minutes) bounds the worst-case window during which a single reservation can sit pre-commit, regardless of agent stall depth.++### 8.2 Commit with actualUsd > estimatedUsd (overrun)++Default behaviour: charge the room the actual amount AND emit a `reservation_overrun` audit entry. The breaker may trip if cumulative overruns move total spend past the `dailySpendCapUsd` threshold in `FederationBreakerService`.++An alternative β fail the commit β was considered and rejected. A failed commit would mean the API call completed successfully but the cost is unrecorded, which is worse for budget accuracy than charging the overrun.++### 8.3 Cross-pod budget pooling++Out of scope for this ADR. The Phase 1-3 model is independent per-pod per-room per-month ledgers. If a business eventually wants a shared budget pool (e.g., the `#exec` room borrows from the `#sales` room's unused balance), the data model supports it via a future `bbs_budget_pool` table, but the implementation is Phase 4. Do not design for it now.++---++## 9. Concurrency Test Plan++All five tests are implementable in vitest using the existing better-sqlite3 setup (the `agentdb-tools.ts` file in `v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts` demonstrates the project's standard better-sqlite3 integration pattern).++### Test 1: 100 concurrent reserves, $1.00 cap++```+Setup: register room "sales-test" with monthly_cap_usd = 1.00+ set billing_month = current YYYY-MM++Action: fire 100 concurrent Promise calls:+ reserve("sales-test", "caller-N", 0.05)+ where N = 0..99, all fired in parallel via Promise.all()++Assert:+ - exactly 20 reservations have state 'reserved'+ - exactly 80 calls returned { ok: false, error: 'BUDGET_EXCEEDED' }+ - SELECT SUM(estimated_usd) FROM bbs_budget_reservations+ WHERE room_id = 'sales-test' AND state = 'reserved'+ = 1.00 (not 1.00 + epsilon, not 0.95)+ - no row with state 'committed' or 'released'+```++### Test 2: Block, then release, then allow 20 of 50++```+Setup: register room "sales-test2" with monthly_cap_usd = 1.00++Step A: reserve("sales-test2", "initial", 0.50)+ β reservationIdA++Step B: fire 50 concurrent reserve("sales-test2", "caller-N", 0.05)+ Promise.all of 50 calls++Assert step B: all 50 return BUDGET_EXCEEDED+ (0.50 reserved + 0.50 requested > 1.00)++Step C: release(reservationIdA)++Step D: fire another 50 concurrent reserve("sales-test2", "caller-N", 0.05)++Assert step D:+ - exactly 10 succeed (0.50 freed, 10 Γ $0.05 = $0.50)+ - exactly 40 return BUDGET_EXCEEDED+```++### Test 3: Reservation expiry frees budget for next caller++```+Setup: register room "hr-test" with monthly_cap_usd = 0.10+ set RESERVATION_EXPIRY_MS = 100 (100ms for test speed)++Step A: reserve("hr-test", "agent-1", 0.10)+ β reservationId (state: 'reserved')++Step B: reserve("hr-test", "agent-2", 0.05)+ β assert BUDGET_EXCEEDED (reservation still live)++Step C: wait 150ms (expiry passes)+ run sweepExpiredReservations() manually++Step D: reserve("hr-test", "agent-2", 0.05)+ β assert ok: true, state 'reserved'+ (expired row excluded from gate check)+```++### Test 4: Crash mid-reserve (transaction atomicity)++```+Setup: use better-sqlite3 in-process (no separate process needed)+ intercept the COMMIT step by throwing after the INSERT+ and before db.exec('COMMIT')++Action: call reserve("ops-test", "agent", 0.05)+ β throws mid-transaction++Assert:+ - db.prepare('SELECT * FROM bbs_budget_reservations').all() returns []+ (transaction was rolled back; no orphan row)+ - bbs_budget_rooms._lock_bump is unchanged from pre-test value+ (write was rolled back with the transaction)+```++Note: better-sqlite3's synchronous API means "mid-transaction crash" is modelled by an exception thrown between `db.prepare('BEGIN IMMEDIATE').run()` and `db.prepare('COMMIT').run()`. The database automatically rolls back any transaction that was not committed before the connection is closed or an exception propagates.++### Test 5: Clock skew backward 30 seconds++```+Setup: register room "finance-test" with monthly_cap_usd = 0.50+ set RESERVATION_EXPIRY_MS = 60_000++Step A: reserve at t=1000 (Date.now() = 1000)+ β reservation expires_at = 61_000++Step B: simulate clock jump: Date.now() = 1000 - 30_000 = -29_000+ (wrap in a clock-override fixture)++Step C: run sweepExpiredReservations()+ β WHERE expires_at < -29_000 β no rows match (61_000 is not < -29_000)+ Assert: reservation is NOT swept, state remains 'reserved'++Step D: call commit(reservationId, 0.05) at clock=-29_000+ β expires_at (61_000) > Date.now() (-29_000): not expired+ Assert: commit succeeds++This test validates that a clock moving backward does not revive an expired+reservation. The expires_at column stores the wall-clock instant of expiry+as an absolute unix-ms value; it does not store a relative duration.+A backward jump makes all unexpired reservations appear to have more time+remaining, not less. Expired reservations (expires_at already in the past)+cannot be moved back to 'reserved' because the sweeper only writes+'expired' β it never writes 'reserved'.+```++### Test 6: COMMIT_AFTER_EXPIRY captures the real spend++**Added by peer review 2026-06-29 β verifies the Β§8.1 Expired Commit Leak fix.**++```+Setup: room with monthly_cap_usd = $1.00, reservationExpiryMs = 100++Step A: reserve($0.30) β reservationId, expires_at = now + 100ms+Step B: wait 200ms (the reservation is now expired but not yet committed+ nor swept; this simulates a slow LLM call)+Step C: assert sweeper has NOT yet committed_post_expiry (window query+ excludes it, but state is still 'reserved' or just transitioned+ to 'expired' by sweeper β either is acceptable)+Step D: call commit(reservationId, 0.30)+ Assert: returns { ok: true, warned: 'COMMIT_AFTER_EXPIRY',+ finalRemaining: 0.70 }+ Assert: room's cumulative committed spend now includes the $0.30+ Assert: audit log contains a `reservation.committed_post_expiry`+ envelope referencing reservationId++Step E: reserve($0.70) β succeeds (since remaining is exactly 0.70)+Step F: reserve($0.01) β BUDGET_EXCEEDED (room is fully spent β the+ post-expiry commit counted)+```++This test is the load-bearing proof that the Expired Commit Leak is closed:+the late commit MUST charge the room and MUST be visible in subsequent gate+checks. Failing this test means the Β§8.1 fix has regressed.+```++---++## 10. Failure Modes++### 10.1 SQLite `database is locked` under contention++WAL mode greatly reduces lock contention compared to journal mode because readers and the writer operate on different regions. However, if `BEGIN IMMEDIATE` cannot acquire the write lock within SQLite's default busy timeout (default: 0ms β fails immediately), the caller receives `SQLITE_BUSY`.++The tracker applies exponential backoff on `SQLITE_BUSY`:++```typescript+const BACKOFF_SCHEDULE_MS = [10, 50, 250] as const;++async function withRetry<T>(fn: () => T): Promise<T> {+ for (let attempt = 0; attempt < BACKOFF_SCHEDULE_MS.length; attempt++) {+ try {+ return fn(); // synchronous better-sqlite3 call+ } catch (err: unknown) {+ if (!isSqliteBusy(err) || attempt === BACKOFF_SCHEDULE_MS.length - 1) {+ throw err;+ }+ await sleep(BACKOFF_SCHEDULE_MS[attempt]);+ }+ }+ throw new Error('unreachable');+}+```++Three retries (10ms / 50ms / 250ms) cover transient lock spikes. If all three fail, the error propagates to `federation_bbs_publish`, which returns `{ blocked: true, reason: 'DATABASE_BUSY' }` rather than attempting the send. This is fail-closed: a busy database does not permit unbudgeted sends.++Setting `db.pragma('busy_timeout = 500')` on connection open (as a complement to WAL mode) is also recommended β this lets SQLite spin internally for up to 500ms before surfacing `SQLITE_BUSY` to Node, reducing the frequency of application-level retries without changing the correctness guarantee.++### 10.2 Database file corruption++If the WAL file or the main database file is corrupt (detected on first `db.prepare()` or on explicit `PRAGMA integrity_check`), the tracker fails closed: all `reserve()` calls return `{ ok: false, error: 'DATABASE_UNAVAILABLE' }`. All `federation_bbs_publish` calls return `{ blocked: true, reason: 'BUDGET_DATABASE_UNAVAILABLE' }`.++Recovery requires operator intervention:+1. Stop all pods for the affected node.+2. Delete or rename `data/bbs-budget.db`, `data/bbs-budget.db-wal`, `data/bbs-budget.db-shm`.+3. Re-run `npx ruflo doctor --fix --component bbs-budget` to recreate the schema.+4. Restart pods. The new database starts with zero committed spend, so the room may temporarily accept more spend than its cap before historical spends are re-accounted. This is a known limitation of Phase 1-3; a reconciliation import from the audit log is deferred to Phase 4.++### 10.3 Audit log write failure before reserve()++If the `reportSpend()` call to `spend-reporter.ts` throws before the `BEGIN IMMEDIATE` transaction starts, the entire `reserve()` call throws. No reservation is created. The caller receives an error and must abort the send. This is the correct fail-closed behaviour: if we cannot audit the spend, we do not permit it.++---++## 11. Performance Bound++### 11.1 Target++p99 latency for `reserve()` under N=50 concurrent callers on a Mac mini-class host (Apple M-series, NVMe SSD): less than 5ms.++### 11.2 Rationale++WAL mode eliminates reader-writer contention. `BEGIN IMMEDIATE` serializes writers, so N concurrent callers are serialized into a queue. Each queue slot is:+- One `UPDATE bbs_budget_rooms` (by primary key β index seek, ~0.1ms)+- One `SELECT` with a covering index on `(room_id, reserved_at)` (~0.2ms)+- One `INSERT` (append to WAL, ~0.3ms)+- WAL write + fsync at checkpoint cadence (amortized, not per-transaction with `PRAGMA synchronous = NORMAL`)++Estimated per-transaction time in-process: ~0.5β1ms. At N=50 serial queue depth, expected tail: ~50ms for the last caller. However, in practice N=50 concurrent HTTP handlers will not all land simultaneously β they arrive with microsecond jitter that disaggregates the queue significantly. Load testing using the pattern in `scripts/bench-agenticow.mjs` should be run in CI to validate the 5ms target.++### 11.3 Throughput ceiling and non-goal++SQLite write serialization means the throughput ceiling for `reserve()` is approximately 1000 calls/second on this hardware (1ms per write Γ single-writer at a time). This is sufficient for Phase 1-3: a business autopilot across 7 pods, each firing at most one send per few seconds.++If pod density ever requires more than ~500 reserves/second per node, the correct resolution is **partitioned databases per-pod** (one `data/bbs-budget-<podName>.db` file per pod, rather than one shared file). This preserves the SQLite serialization guarantee within each pod while eliminating cross-pod contention.++Replacing SQLite with a distributed store (Redis, Postgres, Spanner) is explicitly a non-goal for Phase 1-3. It introduces network latency, operational complexity, and a new failure mode (network partition). The agentbbs model is single-node-first; distributed budget pooling is Phase 4.++---++## 12. Migration++### 12.1 Current state++At the time this ADR is written, `BbsRoomBudgetTracker` is specified in ADR-164 Β§5.1.5 but not yet implemented. There is no existing atomic or non-atomic implementation to migrate FROM.++However, to permit incremental rollout (and to guard against regressions if this design has unforeseen issues), the implementation follows a three-step feature-flag pattern:++### 12.2 Step A: Schema-only migration++Ship a no-op migration that creates `bbs_budget_rooms` and `bbs_budget_reservations` tables in `data/bbs-budget.db`. This migration runs on node startup if the file does not exist. No application logic changes. The existing (to-be-written) non-atomic tracker remains the code path.++### 12.3 Step B: Ship behind feature flag++Implement the atomic tracker as `AtomicBbsRoomBudgetTracker`. The tracker factory reads `CLAUDE_FLOW_BBS_ATOMIC_BUDGET`:++```typescript+export function createBudgetTracker(+ db: Database,+ spendReporter: SpendReporter+): BbsRoomBudgetTracker {+ if (process.env.CLAUDE_FLOW_BBS_ATOMIC_BUDGET === '1') {+ return new AtomicBbsRoomBudgetTracker(db, spendReporter);+ }+ // Fallback to the non-atomic implementation while the flag is off.+ return new NaiveBbsRoomBudgetTracker(db, spendReporter);+}+```++The flag defaults to `'0'` (disabled).++### 12.4 Step C: Flip the default++After 1 week of operation at a production site with `CLAUDE_FLOW_BBS_ATOMIC_BUDGET=1` showing zero budget-exceeded incidents attributable to the tracker, flip the default to `'1'` and deprecate the naive implementation. Remove `NaiveBbsRoomBudgetTracker` in the next minor version.++---++## 13. Code Anchoring++The following ruflo source files are the primary anchor points for implementing this ADR:++| File | Role |+|------|------|+| `v3/@claude-flow/plugin-agent-federation/src/application/spend-reporter.ts` | Emits `federation_spend` events; `ProductionFederationSpendReporter.reportSpend()` is called before `BEGIN IMMEDIATE` |+| `v3/@claude-flow/plugin-agent-federation/src/domain/value-objects/federation-budget.ts` | Per-call `enforceBudget` primitive β this ADR does NOT modify this file; the atomic tracker layers above it |+| `v3/@claude-flow/plugin-agent-federation/src/application/federation-breaker-service.ts` | Consumes `federation_spend` events from the cost-tracker; an overrun audit entry can trip the room's daily cap |+| `v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts` | Demonstrates the project-standard better-sqlite3 setup: WAL mode, `pragma synchronous`, `prepare().run()` pattern |+| `plugins/ruflo-bbs-federation/src/bbs-room-budget-tracker.ts` | New file β the `AtomicBbsRoomBudgetTracker` class implementing this ADR's design |++---++## 14. References++- **ADR-164** β AgentBBS Federated Business-Management Autopilot (parent ADR; Β§5.1.5 specifies the `BbsRoomBudgetTracker` interface this ADR replaces with an atomic version)+- **ADR-097** β Federation Budget Circuit Breaker (Β§Phase 2: `FederationBreakerService`; Β§Phase 3: `spend-reporter.ts` consumer contract; Β§audit-log: `federation-spend` namespace layout)+- **ADR-145** β Plugin Supply-Chain Integrity and Memory Namespace Governance (audit log namespace retention, namespace ownership rules)+- **better-sqlite3 documentation** β `BEGIN IMMEDIATE` semantics, WAL mode configuration, `busy_timeout` pragma, synchronous-NORMAL safety guaranteediff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 6a008c2721..f1587e5fa0 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -185,6 +185,9 @@ importers:'@ruvector/tiny-dancer':specifier: ^0.1.22version: 0.1.22+ agentbbs:+ specifier: ~0.1.0+ version: 0.1.0agentdb:specifier: ^3.0.0-alpha.17version: 3.0.0-alpha.17(@types/[email protected])([email protected])@@ -6948,6 +6951,14 @@ packages:requiresBuild: truedev: false+ resolution: {integrity: sha512-XOEjlgdObklxnZdA0yS6pAcKId99SsFwH5ZF5qNByWs6VsTht1oxjbuFhuapGV7fNnQ6Y2XLq0GbtZ7t+sQMbw==}+ engines: {node: '>=18'}+ hasBin: true+ requiresBuild: true+ dev: false+ optional: true+resolution: {integrity: sha512-OO/hwO+MYtqsgz+6CyrY2BCjcgRWGv5Ob7nFupNEt7m1ZchIArCwvBAcJgFMFNFqWxH6AN2ThiQKBmfXboBkPg==}engines: {node: '>=18.0.0'}