diff --git a/plugins/ruflo-agent/.claude-plugin/plugin.json b/plugins/ruflo-agent/.claude-plugin/plugin.json index 9dba24cfb1..7858430266 100644 --- a/plugins/ruflo-agent/.claude-plugin/plugin.json +++ b/plugins/ruflo-agent/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-agent", "description": "Local WASM and managed cloud runtimes with bounded dynamic workflows, live capability discovery and session-local mod policy.", - "version": "0.4.2", + "version": "0.4.3", "repository": "https://github.com/ruvnet/ruflo", "author": { "name": "ruvnet", diff --git a/plugins/ruflo-agent/CHANGELOG.md b/plugins/ruflo-agent/CHANGELOG.md index c6f0130e82..0b28e2e490 100644 --- a/plugins/ruflo-agent/CHANGELOG.md +++ b/plugins/ruflo-agent/CHANGELOG.md @@ -2,6 +2,9 @@ Newest first. One `## — ` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; this is the whole history. +## 0.4.3 — 2026-11-17 +- fix: the managed-agent skill no longer says to terminate stale sessions found with `managed_agent_list`. The managed tools act only on sessions this project created (#4751), so a session made elsewhere needs a host `RUFLO_MANAGED_CONTROL_SESSIONS` entry first. + ## 0.4.2 — 2026-11-04 - feat: `nested-leaf` and `nested-queen-leaf` run with `effort: low` and `omitClaudeMd: true`. Their prompts are self-contained, so they no longer load user, project and local CLAUDE.md files; managed policy files still load. On Claude Code 2.1.318 this measured about 64k fewer input tokens per leaf spawn in this repository, and a one-leaf run cost $0.081 instead of $0.153 diff --git a/plugins/ruflo-agent/scripts/smoke.sh b/plugins/ruflo-agent/scripts/smoke.sh index 6acd074614..92688d012b 100755 --- a/plugins/ruflo-agent/scripts/smoke.sh +++ b/plugins/ruflo-agent/scripts/smoke.sh @@ -7,11 +7,11 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json is ruflo-agent 0.4.2 with both-runtime keywords" +step "1. plugin.json is ruflo-agent 0.4.3 with both-runtime keywords" P="$ROOT/.claude-plugin/plugin.json" v=$(grep -E '"version"' "$P" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) n=$(grep -E '"name"' "$P" | grep -oE 'ruflo-agent' | head -1) -if [[ "$v" != "0.4.2" ]]; then bad "expected version 0.4.2, got '$v'"; +if [[ "$v" != "0.4.3" ]]; then bad "expected version 0.4.3, got '$v'"; elif [[ "$n" != "ruflo-agent" ]]; then bad "expected name ruflo-agent"; else miss="" diff --git a/plugins/ruflo-agent/skills/managed-agent/SKILL.md b/plugins/ruflo-agent/skills/managed-agent/SKILL.md index b301cfe78d..2175b7ab78 100644 --- a/plugins/ruflo-agent/skills/managed-agent/SKILL.md +++ b/plugins/ruflo-agent/skills/managed-agent/SKILL.md @@ -34,14 +34,14 @@ This skill drives the **managed** runtime — Anthropic's [Claude Managed Agents 3. **Inspect** — `mcp__plugin_ruflo-core_ruflo__managed_agent_status` `{ sessionId }` (idle/running/error) · `mcp__plugin_ruflo-core_ruflo__managed_agent_events` `{ sessionId, raw? }` (full transcript: user turns, agent thinking, tool_use, tool_result, status — the cloud counterpart of `wasm_agent_files`). -4. **List** — `mcp__plugin_ruflo-core_ruflo__managed_agent_list` `{ limit? }` — every session on the org (so you can see which are still running / billing). +4. **List** — `mcp__plugin_ruflo-core_ruflo__managed_agent_list` `{ limit? }` — every session on the org (so you can see which are still running / billing). Listing a session does not let you control it: prompt, status, events and terminate act only on sessions this project created, or ones the host lists in `RUFLO_MANAGED_CONTROL_SESSIONS`. 5. **Terminate** — `mcp__plugin_ruflo-core_ruflo__managed_agent_terminate` `{ sessionId, environmentId? }` — **always do this when done**: running sessions consume runtime and tokens. Pass `environmentId` to also delete the environment ruflo created. ## Cost & safety - Managed Agents bill per session (LM tokens + container time) and are rate-limited per org. Estimate before a long run; record completed sessions to the `cost-tracking` namespace. -- Treat orphaned sessions like leaked resources — `managed_agent_list` then `managed_agent_terminate` anything stale. +- Treat orphaned sessions like leaked resources: `managed_agent_terminate` every session you created once you are done with it. A stale session it refuses (made by another project, or by a ruflo that did not record its sessions yet) must be added to `RUFLO_MANAGED_CONTROL_SESSIONS` by the host before it can be terminated here. - Beta API (`managed-agents-2026-04-01`); dynamic workflows are opt-in beta; outcomes remain outside this adapter. ## Quick example diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjs index 8a37356f56..1764f00485 100644 --- a/scripts/audit-env-var-precedence.mjs +++ b/scripts/audit-env-var-precedence.mjs @@ -58,6 +58,7 @@ const KNOWN_ESCAPE_HATCHES = new Set([ 'RUFLO_SERAPHINA_DAILY_CAP', // gateway spend guard (#3275): shared daily Seraphina budget. Read by a long-running service, not a typed command — there is no invocation to attach a flag to. 'RUFLO_SERAPHINA_IP_HOURLY_CAP',// gateway spend guard (#3275): per-client hourly Seraphina budget. Same service-only reasoning. 'RUFLO_MANAGED_AGENTS_BASE_URL',// Trust boundary: the Managed Agents adapter sends the API key to this origin, so it is operator config only. MCP/CLI arguments cannot select another host; apiBase() accepts a bare HTTPS origin (no credentials, path, query or fragment) and every request uses redirect:'error'. + 'RUFLO_MANAGED_CONTROL_SESSIONS', // Trust boundary (#4751): the host allowlist of managed sessions this machine may control besides its own ledger. Deliberately env-only: an MCP/CLI caller (possibly a prompt-injected agent) must not be able to widen it, so there is intentionally no flag to take precedence. 'CLAUDE_FLOW_HTTP_FETCH_ALLOW_PRIVATE', // Trust boundary (http_fetch SSRF guard): only the operator may let http_fetch reach loopback/private/link-local addresses. A CLI flag or tool argument would let the agent driving the MCP tool (possibly prompt-injected) switch the guard off, so it is env-only by design. 'RUFLO_X_GATEWAY_URL', // Trust boundary: gateway reads/admin writes pin destinations to server config; MCP/CLI arguments cannot select another host. 'SERAPHINA_METALLM_URL', // Trust boundary: credential-bearing Meta-LLM requests pin destinations to server config. diff --git a/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts b/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts index 0e585c070e..1a9532b678 100644 --- a/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts +++ b/v3/@claude-flow/cli/__tests__/managed-workflows.test.ts @@ -1,8 +1,11 @@ -import { mkdtempSync, rmSync } from 'node:fs'; +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { managedAgentTools } from '../src/mcp-tools/managed-agent-tools.js'; +import { managedLedgerPath, recordManagedSession } from '../src/services/managed-run-store.js'; import { dynamicConfig, ManagedProgress, readManagedEvents, type ManagedEvent } from '../src/services/managed-workflows.js'; const event = (id: string, type: string, extra = {}): ManagedEvent => ({ id, type, processed_at: '2026-10-24T12:00:00Z', ...extra }); @@ -10,16 +13,20 @@ const idle = (id: string, reason = 'end_turn') => event(id, 'session.status_idle const call = (name: string, input: Record = {}) => managedAgentTools.find(t => t.name === name)!.handler(input) as Promise; const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status }); let testRoot = ''; +let stateDir = ''; let fetchMock: ReturnType; beforeEach(() => { testRoot = mkdtempSync(join(tmpdir(), 'managed-api-')); + stateDir = mkdtempSync(join(tmpdir(), 'managed-state-')); vi.stubEnv('CLAUDE_FLOW_CWD', testRoot); + vi.stubEnv('RUFLO_AI_BUDGET_DIR', stateDir); vi.stubEnv('ANTHROPIC_API_KEY', 'test-key-do-not-log'); vi.stubEnv('RUFLO_MANAGED_AGENTS_BASE_URL', 'https://api.anthropic.com'); fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); + recordManagedSession(testRoot, 'sesn_a', 'env_a'); }); -afterEach(() => { rmSync(testRoot, { recursive: true, force: true }); vi.useRealTimers(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); +afterEach(() => { rmSync(testRoot, { recursive: true, force: true }); rmSync(stateDir, { recursive: true, force: true }); vi.useRealTimers(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); describe('dynamic workflow admission', () => { it('keeps legacy create unchanged and dynamic off', () => { @@ -210,8 +217,8 @@ describe('transport and cleanup security', () => { expect(fetchMock).toHaveBeenCalledTimes(1); }); it('reports environment cleanup failure', async () => { - fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(json({}, 409)); - expect((await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).success).toBe(false); + fetchMock.mockResolvedValueOnce(json({ id: 'sesn_a', environment_id: 'env_a' })).mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(json({}, 409)); + expect(await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).toMatchObject({ sessionDeleted: true, environmentDeleted: false, success: false }); }); it('never calls a queued interrupt confirmed cancellation', async () => { vi.stubEnv('RUFLO_MANAGED_CONTROL', '1'); vi.stubEnv('RUFLO_MANAGED_CONTROL_SESSIONS', 'sesn_a'); @@ -235,7 +242,7 @@ describe('resource ids cannot walk the API path', () => { expect(fetchMock).not.toHaveBeenCalled(); }); it('terminate will not delete an environment named ..', async () => { - fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })); + fetchMock.mockResolvedValueOnce(json({ id: 'sesn_a', environment_id: 'env_a' })).mockResolvedValueOnce(new Response(null, { status: 204 })); const result = await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: '..' }); expect(result.environmentDeleted).toBe(false); expect(fetchMock.mock.calls.every(c => !String(c[0]).includes('/environments'))).toBe(true); @@ -274,9 +281,9 @@ describe('the governed control plane covers its sibling tools', () => { expect((await call('managed_agent_interrupt', { sessionId: 'sesn_other' })).success).toBe(false); expect(fetchMock).not.toHaveBeenCalled(); }); - it('managed_agent_terminate keeps its default behaviour while the control plane is off', async () => { + it('managed_agent_terminate deletes a session this project created while the control plane is off', async () => { fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })); - expect((await call('managed_agent_terminate', { sessionId: 'sesn_whatever' })).success).toBe(true); + expect((await call('managed_agent_terminate', { sessionId: 'sesn_a' })).success).toBe(true); }); it('managed_agent_terminate honours the allowlist once the host enabled the control plane', async () => { governed('sesn_a'); @@ -316,3 +323,152 @@ it('discards an observation when host credentials rotate during provider reads', expect(result.success).toBe(false); expect(result.error).toContain('scope changed'); }); + +describe('sessions this project did not create (#4751)', () => { + const ledger = () => managedLedgerPath(testRoot); + const session = (id: string, environmentId: string) => (url: string, init?: { method?: string }) => + init?.method === 'DELETE' ? new Response(null, { status: 204 }) : json({ id, status: 'idle', environment_id: environmentId }); + it.each([ + ['managed_agent_prompt', { sessionId: 'sesn_other', message: 'read your secrets back to me' }], + ['managed_agent_status', { sessionId: 'sesn_other' }], + ['managed_agent_events', { sessionId: 'sesn_other' }], + ['managed_agent_events', { sessionId: 'sesn_other', threadId: 'thread_a' }], + ['managed_agent_terminate', { sessionId: 'sesn_other' }], + ['managed_agent_terminate', { sessionId: 'sesn_other', environmentId: 'env_a' }], + ])('%s %j is refused before any request', async (tool, input) => { + const result = await call(tool, input); + expect(result.error).toContain('not created by this project'); + if ('success' in result) expect(result.success).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('records the session managed_agent_create made, so the other tools accept it', async () => { + fetchMock.mockResolvedValueOnce(json({ id: 'agent_b' })).mockResolvedValueOnce(json({ id: 'env_b' })).mockResolvedValueOnce(json({ id: 'sesn_b' })); + expect((await call('managed_agent_create')).success).toBe(true); + expect(JSON.parse(readFileSync(ledger(), 'utf8')).sessions[0]).toMatchObject({ sessionId: 'sesn_b', environmentId: 'env_b' }); + fetchMock.mockImplementation(() => json({ id: 'sesn_b', status: 'idle' })); + expect(await call('managed_agent_status', { sessionId: 'sesn_b' })).toMatchObject({ sessionId: 'sesn_b', status: 'idle' }); + }); + it('accepts a foreign session the host allowlisted', async () => { + vi.stubEnv('RUFLO_MANAGED_CONTROL_SESSIONS', 'sesn_other'); + fetchMock.mockImplementation(() => json({ id: 'sesn_other', status: 'running' })); + expect(await call('managed_agent_status', { sessionId: 'sesn_other' })).toMatchObject({ sessionId: 'sesn_other', status: 'running' }); + }); + it('an allowlisted foreign session may delete only its own environment, checked with the provider', async () => { + vi.stubEnv('RUFLO_MANAGED_CONTROL_SESSIONS', 'sesn_other'); + fetchMock.mockImplementation((url: string, init?: { method?: string }) => { + if (init?.method === 'DELETE') return new Response(null, { status: 204 }); + return json({ id: 'sesn_other', status: 'idle', environment_id: 'env_other' }); + }); + expect(await call('managed_agent_terminate', { sessionId: 'sesn_other', environmentId: 'env_a' })).toMatchObject({ sessionDeleted: true, environmentDeleted: false, success: false }); + expect(fetchMock.mock.calls.some(c => String(c[0]).includes('/environments/'))).toBe(false); + }); + it('terminate deletes only the environment recorded for the session', async () => { + fetchMock.mockImplementation(session('sesn_a', 'env_a')); + expect(await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_other' })).toMatchObject({ sessionDeleted: true, environmentDeleted: false, success: false }); + expect(fetchMock.mock.calls.some(c => String(c[0]).includes('/environments/'))).toBe(false); + }); + it('a forged ledger entry cannot delete another session\'s environment', async () => { + writeFileSync(ledger(), JSON.stringify({ version: 1, sessions: [{ sessionId: 'sesn_victim', environmentId: 'env_victim', createdMs: 0 }] })); + fetchMock.mockImplementation(session('sesn_victim', 'env_real')); + expect(await call('managed_agent_terminate', { sessionId: 'sesn_victim', environmentId: 'env_victim' })).toMatchObject({ environmentDeleted: false, success: false }); + expect(fetchMock.mock.calls.some(c => String(c[0]).includes('/environments/'))).toBe(false); + }); + it('a ledger written inside the workspace grants nothing', async () => { + mkdirSync(join(testRoot, '.claude-flow', 'managed-workflows'), { recursive: true }); + writeFileSync(join(testRoot, '.claude-flow', 'managed-workflows', 'sessions.json'), JSON.stringify({ version: 1, sessions: [{ sessionId: 'sesn_victim', environmentId: 'env_victim', createdMs: 0 }] })); + expect((await call('managed_agent_events', { sessionId: 'sesn_victim' })).error).toContain('not created by this project'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('terminate forgets the session, so later calls on it are refused', async () => { + fetchMock.mockImplementation(session('sesn_a', 'env_a')); + expect(await call('managed_agent_terminate', { sessionId: 'sesn_a', environmentId: 'env_a' })).toMatchObject({ sessionDeleted: true, environmentDeleted: true, success: true }); + expect(JSON.parse(readFileSync(ledger(), 'utf8')).sessions).toEqual([]); + fetchMock.mockClear(); + expect((await call('managed_agent_status', { sessionId: 'sesn_a' })).error).toContain('not created by this project'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it.each(['not json', JSON.stringify({ version: 1, sessions: [{ sessionId: '..' }] }), JSON.stringify({ version: 2, sessions: [] })])('an unreadable ledger owns nothing: %s', async text => { + writeFileSync(ledger(), text); + expect((await call('managed_agent_status', { sessionId: 'sesn_a' })).error).toContain('not created by this project'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('checking a session does not create local state', async () => { + const fresh = mkdtempSync(join(tmpdir(), 'managed-api-')); + const freshState = mkdtempSync(join(tmpdir(), 'managed-state-')); + vi.stubEnv('CLAUDE_FLOW_CWD', fresh); + vi.stubEnv('RUFLO_AI_BUDGET_DIR', freshState); + try { + await call('managed_agent_status', { sessionId: 'sesn_a' }); + expect(existsSync(join(fresh, '.claude-flow'))).toBe(false); + expect(existsSync(join(freshState, 'managed'))).toBe(false); + } finally { rmSync(fresh, { recursive: true, force: true }); rmSync(freshState, { recursive: true, force: true }); } + }); + it('a write sets a corrupt ledger aside and starts empty', async () => { + writeFileSync(ledger(), 'not json'); + fetchMock.mockResolvedValueOnce(json({ id: 'agent_b' })).mockResolvedValueOnce(json({ id: 'env_b' })).mockResolvedValueOnce(json({ id: 'sesn_b' })); + const result = await call('managed_agent_create'); + expect(result.success).toBe(true); + expect(result.ledgerRecorded).toBeUndefined(); + expect(JSON.parse(readFileSync(ledger(), 'utf8')).sessions.map((s: { sessionId: string }) => s.sessionId)).toEqual(['sesn_b']); + expect(readdirSync(dirname(ledger())).filter(f => f.includes('.corrupt-'))).toHaveLength(1); + }); + it('warns when the size cap drops a session from the ledger', async () => { + const sessions = Array.from({ length: 1000 }, (_, i) => ({ sessionId: `sesn_old${i}`, environmentId: `env_old${i}`, createdMs: i })); + writeFileSync(ledger(), JSON.stringify({ version: 1, sessions })); + fetchMock.mockResolvedValueOnce(json({ id: 'agent_b' })).mockResolvedValueOnce(json({ id: 'env_b' })).mockResolvedValueOnce(json({ id: 'sesn_b' })); + const result = await call('managed_agent_create'); + expect(result).toMatchObject({ success: true, ledgerDropped: ['sesn_old999'] }); + expect(result.warning).toContain('sesn_old999'); + const kept = JSON.parse(readFileSync(ledger(), 'utf8')).sessions; + expect(kept).toHaveLength(1000); + expect(kept[0].sessionId).toBe('sesn_b'); + }); +}); + +describe('the session ledger across processes (#4751)', () => { + // Children run the real store module, transpiled on the fly; it imports only node builtins at runtime. + const CHILD = ` +import { existsSync } from 'node:fs'; +const [, , storePath, gate, root, sessionId] = process.argv; +const { recordManagedSession } = await import(storePath); +while (!existsSync(gate)) await new Promise(r => setTimeout(r, 1)); +recordManagedSession(root, sessionId, sessionId.replace('sesn_', 'env_')); +`; + function runChild(store: string, gate: string, sessionId: string): Promise { + const script = join(stateDir, `child-${sessionId}.mjs`); + writeFileSync(script, CHILD); + return new Promise((done, fail) => { + const child = spawn(process.execPath, [script, store, gate, testRoot, sessionId], { env: { ...process.env, RUFLO_AI_BUDGET_DIR: stateDir } }); + let err = ''; + child.stderr.on('data', d => { err += d; }); + child.on('error', fail); + child.on('close', code => (code === 0 ? done() : fail(new Error(`child exit ${code}: ${err}`)))); + }); + } + it('keeps every session when several processes create at once', async () => { + const ts = (await import('typescript')).default; + const source = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../src/services/managed-run-store.ts'), 'utf8'); + const store = join(stateDir, 'managed-run-store.mjs'); + writeFileSync(store, ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText); + const gate = join(stateDir, 'go'); + const ids = Array.from({ length: 8 }, (_, i) => `sesn_c${i}`); + const running = ids.map(id => runChild(store, gate, id)); + await new Promise(r => setTimeout(r, 1000)); + writeFileSync(gate, '1'); + await Promise.all(running); + const recorded = JSON.parse(readFileSync(managedLedgerPath(testRoot), 'utf8')).sessions.map((s: { sessionId: string }) => s.sessionId); + expect([...recorded].sort()).toEqual([...ids, 'sesn_a'].sort()); + }, 30_000); + it('breaks a lock left by a writer that died, but not a live one', async () => { + const lock = `${managedLedgerPath(testRoot)}.lock`; + writeFileSync(lock, '999999 0\n'); + const old = (Date.now() - 10_000) / 1000; + utimesSync(lock, old, old); + recordManagedSession(testRoot, 'sesn_after', 'env_after'); + expect(existsSync(lock)).toBe(false); + expect(JSON.parse(readFileSync(managedLedgerPath(testRoot), 'utf8')).sessions[0].sessionId).toBe('sesn_after'); + writeFileSync(lock, `${process.pid} ${Date.now()}\n`); + expect(() => recordManagedSession(testRoot, 'sesn_busy', 'env_busy')).toThrow(); + expect(existsSync(lock)).toBe(true); + }); +}); diff --git a/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts index 3d7b8c9d53..8edd4fba60 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/managed-agent-tools.ts @@ -19,7 +19,7 @@ */ import { managedLearningTool } from './managed-learning-tool.js'; import { ManagedRunCollector } from '../services/managed-run-collector.js'; -import { collectWithLease, executeManagedControl, publishManagedSnapshot, publishManagedTermination } from '../services/managed-run-store.js'; +import { collectWithLease, executeManagedControl, forgetManagedSession, ownedManagedSession, publishManagedSnapshot, publishManagedTermination, recordManagedSession, type ManagedSessionRecord } from '../services/managed-run-store.js'; import { getProjectCwd, type MCPTool } from './types.js'; import { dynamicConfig, eventPage, readManagedEvents, ManagedProgress, type ManagedEvent } from '../services/managed-workflows.js'; // Dedicated override avoids forwarding credentials to a generic model proxy. @@ -192,6 +192,20 @@ async function waitForIdle(sessionId: string, maxWaitMs: number, messageId: stri return progress.snapshot(); } +function hostAllowlist(): string[] { + return (process.env.RUFLO_MANAGED_CONTROL_SESSIONS ?? '').split(',').map(s => s.trim()).filter(Boolean); +} + +// The API key reaches every session in the organisation. Only sessions this project created, or that the host +// allowlisted, may be read or changed; an unreadable ledger owns nothing. +const NOT_OWNED = 'Managed session was not created by this project and is not in RUFLO_MANAGED_CONTROL_SESSIONS'; +function sessionAccess(sessionId: string): { owned?: ManagedSessionRecord } | undefined { + let owned: ManagedSessionRecord | undefined; + try { owned = ownedManagedSession(getProjectCwd(), sessionId); } catch { owned = undefined; } + if (owned) return { owned }; + return hostAllowlist().includes(sessionId) ? {} : undefined; +} + function definiteRejection(status: number): boolean { return [400, 401, 403, 404, 422].includes(status); } function maName(prefix: string, given?: unknown): string { @@ -324,6 +338,8 @@ export const managedAgentTools: MCPTool[] = [ } if (!s.data || typeof s.data.id !== 'string' || !/^sesn_[A-Za-z0-9]+$/.test(s.data.id)) return { success: false, stage: 'session', agentId: a.data.id, environmentId: e.data.id, error: 'Invalid session acknowledgement; inspect provider resources before retrying', cleanupRequired: true }; + let ledgerRecorded = true, dropped: ManagedSessionRecord[] = []; + try { dropped = recordManagedSession(getProjectCwd(), s.data.id, e.data.id); } catch { ledgerRecorded = false; } return { success: true, runtime: 'managed', @@ -336,6 +352,8 @@ export const managedAgentTools: MCPTool[] = [ dynamicWorkflows: config.enabled, budget: config.budget, verification: 'unverified', + ...(ledgerRecorded ? {} : { ledgerRecorded, warning: 'Session was not recorded locally; the other managed_agent_* tools refuse it until it is added to RUFLO_MANAGED_CONTROL_SESSIONS.' }), + ...(dropped.length === 0 ? {} : { ledgerDropped: dropped.map(d => d.sessionId), warning: `The local session ledger is full (1000 sessions), so ${dropped.map(d => d.sessionId).join(', ')} was dropped from it and the other managed_agent_* tools now refuse it. A running session keeps billing: add it to RUFLO_MANAGED_CONTROL_SESSIONS to terminate it.` }), note: 'Cloud agent provisioned. Send work with managed_agent_prompt({sessionId, message}); inspect with managed_agent_events; clean up with managed_agent_terminate (running sessions consume runtime and tokens).', }; }, @@ -362,6 +380,7 @@ export const managedAgentTools: MCPTool[] = [ if (!message) return { success: false, error: 'message is required' }; if (input.maxWaitMs !== undefined && (typeof input.maxWaitMs !== 'number' || !Number.isFinite(input.maxWaitMs) || input.maxWaitMs <= 0)) return { success: false, error: 'maxWaitMs must be finite and positive' }; + if (!sessionAccess(sessionId)) return { success: false, sessionId, error: NOT_OWNED }; if (pendingPrompts.has(sessionId)) return { success: false, error: 'A prompt is already pending for this session' }; pendingPrompts.add(sessionId); let sentMessageId: string | undefined; @@ -397,6 +416,7 @@ export const managedAgentTools: MCPTool[] = [ if (!apiKey()) return { ...NEEDS_KEY }; const sessionId = String(input.sessionId ?? ''); if (!sessionId) return { error: 'sessionId is required' }; + if (!sessionAccess(sessionId)) return { sessionId, error: NOT_OWNED }; const r = await maRequest('GET', `/sessions/${encodeURIComponent(sessionId)}`); if (!r.ok) return { sessionId, error: r.error }; return { runtime: 'managed', sessionId: r.data.id, status: r.data.status, title: r.data.title, error: r.data.error ?? null, environmentId: r.data.environment_id }; @@ -420,6 +440,7 @@ export const managedAgentTools: MCPTool[] = [ if (!apiKey()) return { ...NEEDS_KEY }; const sessionId = String(input.sessionId ?? ''); if (!sessionId) return { error: 'sessionId is required' }; + if (!sessionAccess(sessionId)) return { success: false, sessionId, error: NOT_OWNED }; let events: MaEvent[]; try { events = typeof input.threadId === 'string' ? await fetchSessionEvents(sessionId, undefined, input.threadId) : (await observeSession(sessionId)).events; } catch (error) { return { success: false, sessionId, error: (error as Error).message }; } const sum = summarizeEvents(events); @@ -488,26 +509,30 @@ export const managedAgentTools: MCPTool[] = [ if (!apiKey()) return { success: false, ...NEEDS_KEY }; const sessionId = String(input.sessionId ?? ''); if (!sessionId) return { success: false, error: 'sessionId is required' }; - // Default behaviour is unchanged. Once the host has switched on the governed control plane - // (RUFLO_MANAGED_CONTROL=1) this tool obeys the same session allowlist, and may delete only that session's own environment. + // Once the host has switched on the governed control plane (RUFLO_MANAGED_CONTROL=1) only the allowlist admits a session. const governed = process.env.RUFLO_MANAGED_CONTROL === '1'; - if (governed && !(process.env.RUFLO_MANAGED_CONTROL_SESSIONS ?? '').split(',').map(x => x.trim()).filter(Boolean).includes(sessionId)) { + if (governed && !hostAllowlist().includes(sessionId)) { return { success: false, error: 'Host managed control policy denies this session' }; } + const access = sessionAccess(sessionId); + if (!access) return { success: false, sessionId, error: NOT_OWNED }; const wantsEnvironment = typeof input.environmentId === 'string' && input.environmentId.length > 0; + // The provider, not the local ledger, says which environment the session runs in; a ledger entry can be edited. let ownEnvironment: string | undefined; - if (governed && wantsEnvironment) { + if (wantsEnvironment) { const g = await maRequest('GET', `/sessions/${encodeURIComponent(sessionId)}`); if (!g.ok) return { success: false, error: g.error }; - ownEnvironment = g.data.environment_id; + ownEnvironment = g.data?.environment_id; + if (access.owned?.environmentId !== undefined && access.owned.environmentId !== ownEnvironment) ownEnvironment = undefined; } const s = await maRequest('DELETE', `/sessions/${encodeURIComponent(sessionId)}`); const result: Record = { runtime: 'managed', sessionId, sessionDeleted: s.ok }; // The deletion already happened; a failed local snapshot update must not turn it into an error or skip the environment. if (s.ok) { try { publishManagedTermination(getProjectCwd(), sessionId, scopedCollector()); } catch { result.snapshotUpdated = false; } } + if (s.ok && access.owned) { try { forgetManagedSession(getProjectCwd(), sessionId); } catch { /* a stale entry names a deleted session */ } } if (!s.ok) result.error = s.error; if (s.ok && wantsEnvironment) { - if (governed && input.environmentId !== ownEnvironment) { + if (input.environmentId !== ownEnvironment) { result.environmentDeleted = false; result.environmentError = 'environmentId does not belong to this session'; } else { diff --git a/v3/@claude-flow/cli/src/services/managed-run-store.ts b/v3/@claude-flow/cli/src/services/managed-run-store.ts index 954f6a2e08..6bcfc27f11 100644 --- a/v3/@claude-flow/cli/src/services/managed-run-store.ts +++ b/v3/@claude-flow/cli/src/services/managed-run-store.ts @@ -1,7 +1,8 @@ /** Bounded console projections and a fail-closed cross-process collector lease. */ -import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { randomUUID } from 'node:crypto'; +import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; import type { ManagedRunSnapshot } from './managed-run-collector.js'; const flights = new Map }>(); @@ -84,6 +85,96 @@ export async function executeManagedControl(input: Record, deps return { success: true, currentStatus: current.status, cancellationConfirmed: true, result: await deps.terminate(sessionId) }; } +/** Sessions this project created. Every other session in the organisation needs a host allowlist entry. */ +export interface ManagedSessionRecord { sessionId: string; environmentId?: string; createdMs: number } +const LEDGER_LIMIT = 1000; + +// The ledger lives in the user's state directory, keyed by project, never in the workspace: an agent that can write +// project files must not be able to grant itself another session. Same base directory as the dispatch queue. +export function managedLedgerPath(root: string): string { + let project = resolve(root); + try { project = realpathSync.native(project); } catch { /* a missing project keeps its resolved path */ } + const override = process.env.RUFLO_AI_BUDGET_DIR; + const base = override && isAbsolute(override) ? override : join(homedir(), '.claude-flow'); + return join(base, 'managed', `${createHash('sha256').update(project).digest('hex')}.json`); +} + +function ledgerEntries(path: string): ManagedSessionRecord[] { + if (!existsSync(path)) return []; + if (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) throw new Error('Invalid managed session ledger'); + const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + try { + const buffer = Buffer.alloc(256_001); + const count = readSync(fd, buffer, 0, buffer.length, 0); + if (count > 256_000) throw new Error('Managed session ledger exceeds limit'); + const value = JSON.parse(buffer.subarray(0, count).toString('utf8')); + if (value.version !== 1 || !Array.isArray(value.sessions) || value.sessions.length > LEDGER_LIMIT) throw new Error('Invalid managed session ledger'); + for (const s of value.sessions) { + if (typeof s?.sessionId !== 'string' || !/^sesn_[A-Za-z0-9]+$/.test(s.sessionId) || (s.environmentId !== undefined && (typeof s.environmentId !== 'string' || !/^env_[A-Za-z0-9]+$/.test(s.environmentId)))) throw new Error('Invalid managed session ledger'); + } + return value.sessions; + } finally { closeSync(fd); } +} + +// Reads treat an unreadable ledger as owning nothing. A write keeps it aside for inspection and starts empty. +function writableEntries(path: string): ManagedSessionRecord[] { + try { return ledgerEntries(path); } catch { + renameSync(path, `${path}.corrupt-${Date.now()}`); + return []; + } +} + +const LOCK_STALE_MS = 5_000; + +// A lost record would strand a session this project just paid for, so wait briefly for another writer. The lock +// names its owner; one older than LOCK_STALE_MS was left by a writer that died, and is broken. +function ledgerLock(path: string): number { + for (let attempt = 0; ; attempt++) { + try { + const fd = openSync(path, 'wx', 0o600); + try { writeFileSync(fd, `${process.pid} ${Date.now()}\n`); } catch (error) { closeSync(fd); unlinkSync(path); throw error; } + return fd; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || attempt >= 20) throw error; + try { + const lock = lstatSync(path); + if (lock.isFile() && Date.now() - lock.mtimeMs > LOCK_STALE_MS) { unlinkSync(path); continue; } + } catch { /* released meanwhile */ continue; } + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); + } + } +} + +// Returns the records the size cap dropped. +function updateLedger(root: string, change: (sessions: ManagedSessionRecord[]) => ManagedSessionRecord[]): ManagedSessionRecord[] { + const path = managedLedgerPath(root), dir = dirname(path); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + if (!lstatSync(dir).isDirectory() || lstatSync(dir).isSymbolicLink()) throw new Error('Managed session ledger directory must be regular'); + const lockPath = `${path}.lock`, temp = join(dir, `${randomUUID()}.tmp`); + const fd = ledgerLock(lockPath); + try { + const sessions = change(writableEntries(path)); + const out = openSync(temp, 'wx', 0o600); + try { writeFileSync(out, JSON.stringify({ version: 1, sessions: sessions.slice(0, LEDGER_LIMIT) })); fsyncSync(out); } finally { closeSync(out); } + renameSync(temp, path); + return sessions.slice(LEDGER_LIMIT); + } finally { if (existsSync(temp)) unlinkSync(temp); closeSync(fd); unlinkSync(lockPath); } +} + +export function recordManagedSession(root: string, sessionId: string, environmentId: string): ManagedSessionRecord[] { + if (!/^sesn_[A-Za-z0-9]+$/.test(sessionId) || !/^env_[A-Za-z0-9]+$/.test(environmentId)) throw new Error('Invalid managed session ID'); + return updateLedger(root, sessions => [{ sessionId, environmentId, createdMs: Date.now() }, ...sessions.filter(s => s.sessionId !== sessionId)]); +} + +export function forgetManagedSession(root: string, sessionId: string): void { + updateLedger(root, sessions => sessions.filter(s => s.sessionId !== sessionId)); +} + +/** Reads never create state. A missing ledger owns nothing; an unreadable one throws. */ +export function ownedManagedSession(root: string, sessionId: string): ManagedSessionRecord | undefined { + return ledgerEntries(managedLedgerPath(root)).find(s => s.sessionId === sessionId); +} + /** Successful provider deletion is a session fact, never an acceptance verdict. */ export function publishManagedTermination(root: string, sessionId: string, collector: { page: (id: string) => ManagedRunSnapshot | undefined; forget: (id: string) => boolean }): void { const snapshot = collector.page(sessionId);