π 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(swarm): SubagentPermissionDelegate β --with-permissions preset (#2768)
ruv46b33cb763fd
diff --git a/v3/@claude-flow/cli/src/commands/swarm.ts b/v3/@claude-flow/cli/src/commands/swarm.tsindex 2222080d78..8b8a370a3b 100644--- a/v3/@claude-flow/cli/src/commands/swarm.ts+++ b/v3/@claude-flow/cli/src/commands/swarm.ts@@ -284,12 +284,23 @@ const initCommand: Command = {description: 'Enable V3 15-agent hierarchical mesh mode',type: 'boolean',default: false- }+ },+ {+ // #2768 β dream-cycle SubagentPermissionDelegate. Ships a per-role+ // capability manifest to `.swarm/permissions.jsonl` + an append-only+ // audit trail. Task-tool prompts can consult the manifest; ruflo+ // does NOT enforce at the syscall boundary (Claude Code owns that).+ name: 'with-permissions',+ description: 'Ship workspace-scoped permission manifest (preset: strict|standard|permissive) β dream-cycle #2768',+ type: 'string',+ choices: ['strict', 'standard', 'permissive'],+ },],action: async (ctx: CommandContext): Promise<CommandResult> => {let topology = ctx.flags.topology as string;const maxAgents = ctx.flags.maxAgents as number || 15;const v3Mode = ctx.flags.v3Mode as boolean;+ const withPermissions = ctx.flags.withPermissions as string | undefined;// V3 mode enables hierarchical-mesh hybridif (v3Mode) {@@ -381,6 +392,7 @@ const initCommand: Command = {maxAgents: result.config.maxAgents,strategy: ctx.flags.strategy || 'development',v3Mode,+ permissions: withPermissions ?? null,initializedAt: result.initializedAt,status: 'ready'}, null, 2));@@ -388,6 +400,35 @@ const initCommand: Command = {// Ignore errors writing state file}+ // #2768 β write the permission manifest + seed the audit trail.+ // Optional: only fires when --with-permissions was passed. Missing+ // module or failed I/O is non-critical; we log a dim warning and+ // continue so a broken permission layer never blocks swarm init.+ if (withPermissions) {+ try {+ const [{ resolvePreset }, { writeGrants, appendAuditEvent }] = await Promise.all([+ import('../permission/permission-set.js'),+ import('../permission/permission-audit.js'),+ ]);+ const sets = resolvePreset(withPermissions);+ writeGrants(sets, swarmDir);+ for (const set of sets) {+ appendAuditEvent({+ agentId: 'swarm-init',+ role: set.role,+ event: 'granted',+ capability: `preset:${withPermissions}`,+ swarmId: result.swarmId,+ reason: `Initial grant from swarm init --with-permissions ${withPermissions}`,+ }, swarmDir);+ }+ output.writeln(output.dim(` Wrote permission manifest (preset: ${withPermissions}, ${sets.length} roles) β .swarm/permissions.jsonl`));+ output.writeln(output.dim(` Audit trail seeded β .swarm/permission-audit.jsonl`));+ } catch (err) {+ output.writeln(output.dim(` β permission manifest skipped: ${err instanceof Error ? err.message : String(err)}`));+ }+ }+if (ctx.flags.format === 'json') {output.printJson(result);}diff --git a/v3/@claude-flow/cli/src/permission/permission-audit.ts b/v3/@claude-flow/cli/src/permission/permission-audit.tsnew file mode 100644index 0000000000..ba9e82034f--- /dev/null+++ b/v3/@claude-flow/cli/src/permission/permission-audit.ts@@ -0,0 +1,109 @@+/**+ * Append-only permission audit log for swarm subagents (dream-cycle #2768).+ *+ * Every grant / check / deny / revoke event is written to+ * `.swarm/permission-audit.jsonl` β one JSON object per line, no rewrites,+ * no deletes. Persistence follows the same discipline as ruflo's other+ * append-only ledgers (routing-outcomes, funnel-events) so downstream+ * readers can tail without truncation risk.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import { randomBytes } from 'node:crypto';++/** A single permission-audit event. */+export interface AuditEvent {+ /** ISO-8601 timestamp. */+ timestamp: string;+ /** Opaque agent identifier β matches Task tool `name:` or a swarm-assigned slot id. */+ agentId: string;+ /** Symbolic role β matches PermissionSet.role. */+ role: string;+ /** Event class. */+ event: 'granted' | 'checked' | 'denied' | 'revoked';+ /** Free-form capability descriptor (`tool:Bash`, `path:src/**`, `net:api.github.com`). */+ capability: string;+ /** Optional swarm-scope identifier. */+ swarmId?: string;+ /** Optional human-readable reason. */+ reason?: string;+ /** Auto-generated event id for correlation. */+ eventId: string;+}++/** Resolve `.swarm/permission-audit.jsonl` under the given (or cwd's) swarm dir. */+export function auditLogPath(swarmDir?: string): string {+ const dir = swarmDir ?? path.join(process.cwd(), '.swarm');+ return path.join(dir, 'permission-audit.jsonl');+}++/** Resolve `.swarm/permissions.jsonl` β the current-grants manifest. */+export function grantsPath(swarmDir?: string): string {+ const dir = swarmDir ?? path.join(process.cwd(), '.swarm');+ return path.join(dir, 'permissions.jsonl');+}++function ensureDirFor(filePath: string): void {+ const dir = path.dirname(filePath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+}++/** Append a single audit event. Never throws β failures are non-critical. */+export function appendAuditEvent(event: Omit<AuditEvent, 'eventId' | 'timestamp'>, swarmDir?: string): void {+ const full: AuditEvent = {+ ...event,+ timestamp: new Date().toISOString(),+ eventId: `evt-${Date.now()}-${randomBytes(4).toString('hex')}`,+ };+ try {+ const p = auditLogPath(swarmDir);+ ensureDirFor(p);+ fs.appendFileSync(p, JSON.stringify(full) + '\n', 'utf-8');+ } catch {+ /* audit log unavailable β non-critical, don't crash the caller */+ }+}++/** Read every audit event. Used by review tooling. */+export function readAuditLog(swarmDir?: string): AuditEvent[] {+ const p = auditLogPath(swarmDir);+ if (!fs.existsSync(p)) return [];+ const raw = fs.readFileSync(p, 'utf-8');+ return raw+ .split('\n')+ .filter((line) => line.length > 0)+ .map((line) => {+ try {+ return JSON.parse(line) as AuditEvent;+ } catch {+ return null;+ }+ })+ .filter((e): e is AuditEvent => e !== null);+}++/** Write the current grants manifest (overwrites) β one line per role. */+export function writeGrants(grants: unknown[], swarmDir?: string): void {+ const p = grantsPath(swarmDir);+ ensureDirFor(p);+ fs.writeFileSync(p, grants.map((g) => JSON.stringify(g)).join('\n') + '\n', 'utf-8');+}++/** Read the current grants manifest. */+export function readGrants(swarmDir?: string): unknown[] {+ const p = grantsPath(swarmDir);+ if (!fs.existsSync(p)) return [];+ const raw = fs.readFileSync(p, 'utf-8');+ return raw+ .split('\n')+ .filter((line) => line.length > 0)+ .map((line) => {+ try {+ return JSON.parse(line);+ } catch {+ return null;+ }+ })+ .filter((g) => g !== null);+}diff --git a/v3/@claude-flow/cli/src/permission/permission-set.ts b/v3/@claude-flow/cli/src/permission/permission-set.tsnew file mode 100644index 0000000000..408c573eb8--- /dev/null+++ b/v3/@claude-flow/cli/src/permission/permission-set.ts@@ -0,0 +1,164 @@+/**+ * Workspace-scoped permission model for swarm subagents (dream-cycle #2768,+ * ClawArena finding: privilege granting is the #1 orchestration bottleneck,+ * no LLM > 50% workspace-permission precision as team lead).+ *+ * SCOPE (honest): this is a METADATA + AUDIT layer, not a runtime sandbox.+ * Claude Code's Task tool owns the actual subprocess sandbox; ruflo cannot+ * enforce at the syscall boundary. What we CAN do:+ * 1. Publish a per-role capability manifest that Task-tool prompts can+ * consult ("your workspace-scoped tools are X, Y, Z; you may not use W").+ * 2. Record every grant/check/deny/revoke to an append-only audit trail+ * so the swarm has a reviewable permission history.+ *+ * That is enough to close the "permission-hygiene" half of the ClawArena+ * finding β the "50% precision as team lead" number is about the LLM's+ * decision QUALITY, which no runtime layer fixes.+ */++import type { PathValidator } from '@claude-flow/security';++/** A single agent role's capability envelope. */+export interface PermissionSet {+ /** Symbolic role name β matches ruflo agent-type names (coder, tester, reviewer, β¦). */+ role: string;+ /** Tools this role MAY use. Empty array = deny-all-tools. */+ allowedTools: string[];+ /** Tools this role MUST NOT use (evaluated after allow β deny wins). */+ deniedTools: string[];+ /** Glob patterns this role MAY read/write, relative to swarm cwd. */+ allowedPaths: string[];+ /** Glob patterns this role MUST NOT touch (deny wins). */+ deniedPaths: string[];+ /** Exact-host allowlist for outbound network. Empty = deny-all-network. */+ allowedNetworkHosts: string[];+ /** Human-readable note explaining the intent of this envelope. */+ notes?: string;+}++/** Built-in presets, ordered narrow β wide. Each preset ships per-role sets. */+export const PRESETS: Record<'strict' | 'standard' | 'permissive', PermissionSet[]> = {+ /**+ * strict β read-only file access, no network, no bash. Suitable for+ * research / review / planning agents. Denies every destructive surface.+ */+ strict: [+ {+ role: 'researcher',+ allowedTools: ['Read', 'Grep', 'Glob'],+ deniedTools: ['Bash', 'Edit', 'Write', 'NotebookEdit'],+ allowedPaths: ['**/*'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem'],+ allowedNetworkHosts: [],+ notes: 'Read-only research role; no filesystem writes, no network, no shell.',+ },+ {+ role: 'reviewer',+ allowedTools: ['Read', 'Grep', 'Glob'],+ deniedTools: ['Bash', 'Edit', 'Write', 'NotebookEdit'],+ allowedPaths: ['**/*'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem'],+ allowedNetworkHosts: [],+ notes: 'Read-only code review; findings emitted via return message, not filesystem writes.',+ },+ {+ role: 'planner',+ allowedTools: ['Read', 'Grep', 'Glob'],+ deniedTools: ['Bash', 'Edit', 'Write', 'NotebookEdit'],+ allowedPaths: ['**/*'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem'],+ allowedNetworkHosts: [],+ notes: 'Read-only planning; produces plan text, no side effects.',+ },+ ],++ /**+ * standard β the default. Read + edit under cwd, no bash, allowlisted+ * network hosts for common dev workflows (github, npm registry, docs).+ * Suitable for implementation agents doing bounded file changes.+ */+ standard: [+ {+ role: 'coder',+ allowedTools: ['Read', 'Grep', 'Glob', 'Edit', 'Write', 'NotebookEdit'],+ deniedTools: ['Bash'],+ allowedPaths: ['src/**', 'tests/**', '__tests__/**', 'lib/**', 'plugins/**', 'v3/**', 'docs/**', 'CHANGELOG.md', 'package.json'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem', '**/.git/**', '**/node_modules/**'],+ allowedNetworkHosts: ['api.github.com', 'registry.npmjs.org', 'docs.rs', 'crates.io'],+ notes: 'Bounded code writer; edits under source directories, no shell, allowlist network.',+ },+ {+ role: 'tester',+ allowedTools: ['Read', 'Grep', 'Glob', 'Edit', 'Write'],+ deniedTools: ['Bash', 'NotebookEdit'],+ allowedPaths: ['tests/**', '__tests__/**', '**/*.test.*', '**/*.spec.*'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem'],+ allowedNetworkHosts: [],+ notes: 'Tests-only writer; scope pinned to test directories and .test/.spec files.',+ },+ {+ role: 'reviewer',+ allowedTools: ['Read', 'Grep', 'Glob'],+ deniedTools: ['Bash', 'Edit', 'Write', 'NotebookEdit'],+ allowedPaths: ['**/*'],+ deniedPaths: ['**/.env', '**/.env.*', '**/secrets/**', '**/*.key', '**/*.pem'],+ allowedNetworkHosts: [],+ notes: 'Read-only reviewer; identical to strict-reviewer.',+ },+ ],++ /**+ * permissive β the pre-#2768 baseline. Full toolset, no path fencing.+ * Kept for compatibility so users can opt back in explicitly. NOT a+ * good default β the entire point of this feature is that the LLM's+ * unaided permission decisions land under 50% precision.+ */+ permissive: [+ {+ role: '*',+ allowedTools: ['*'],+ deniedTools: [],+ allowedPaths: ['**/*'],+ deniedPaths: [],+ allowedNetworkHosts: ['*'],+ notes: 'No restriction. Kept for opt-in compatibility; see #2768 for why this is not the default.',+ },+ ],+};++export type PresetName = keyof typeof PRESETS;++/**+ * Resolve a preset name to its per-role sets. Throws on unknown preset β+ * fail loud so a typo doesn't silently degrade to permissive.+ */+export function resolvePreset(name: string): PermissionSet[] {+ if (!(name in PRESETS)) {+ const valid = Object.keys(PRESETS).join(', ');+ throw new Error(`Unknown permissions preset: ${name}. Valid presets: ${valid}`);+ }+ return PRESETS[name as PresetName];+}++/**+ * Sanity-check a permission set: role name shape, no null entries.+ * Path validation is deferred to the enforcement side (PathValidator)+ * so this module has no @claude-flow/security runtime dep beyond a+ * type-only import.+ */+export function validatePermissionSet(set: PermissionSet, _validator?: PathValidator): string[] {+ const errors: string[] = [];+ if (!set.role || typeof set.role !== 'string') errors.push('role must be a non-empty string');+ const arrays: [keyof PermissionSet, unknown][] = [+ ['allowedTools', set.allowedTools],+ ['deniedTools', set.deniedTools],+ ['allowedPaths', set.allowedPaths],+ ['deniedPaths', set.deniedPaths],+ ['allowedNetworkHosts', set.allowedNetworkHosts],+ ];+ for (const [key, val] of arrays) {+ if (!Array.isArray(val)) errors.push(`${String(key)} must be an array`);+ else if ((val as unknown[]).some((v) => typeof v !== 'string')) errors.push(`${String(key)} must contain only strings`);+ }+ return errors;+}