🌊 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: add capability algebra and evolution pipeline
Claude4d68d8b47ada
diff --git a/v3/@claude-flow/guidance/src/capabilities.ts b/v3/@claude-flow/guidance/src/capabilities.tsnew file mode 100644index 0000000000..ddb47b3f4b--- /dev/null+++ b/v3/@claude-flow/guidance/src/capabilities.ts@@ -0,0 +1,639 @@+/**+ * Capability Algebra+ *+ * All permissions become typed objects that can be composed, restricted,+ * delegated, revoked, and reasoned about. Supports delegation chains,+ * attestations, constraint evaluation, and set-theoretic composition+ * (intersection for actions, union for constraints).+ *+ * @module @claude-flow/guidance/capabilities+ */++import { randomUUID } from 'node:crypto';++// ============================================================================+// Types+// ============================================================================++/**+ * Scope categories for capabilities+ */+export type CapabilityScope = 'tool' | 'memory' | 'network' | 'file' | 'model' | 'system';++/**+ * Constraint applied to a capability+ */+export interface CapabilityConstraint {+ /** Constraint type */+ type: 'rate-limit' | 'budget' | 'time-window' | 'condition' | 'scope-restriction';+ /** Type-specific parameters */+ params: Record<string, unknown>;+}++/**+ * Cryptographic attestation for a capability+ */+export interface Attestation {+ /** ID of the attesting agent or authority */+ attesterId: string;+ /** When the attestation was made (ms since epoch) */+ attestedAt: number;+ /** Claim being attested (e.g., "agent passed security audit") */+ claim: string;+ /** Optional evidence supporting the claim */+ evidence: string | null;+ /** Signature over the claim (hex-encoded) */+ signature: string;+}++/**+ * A typed permission object representing a granted capability+ */+export interface Capability {+ /** Unique capability identifier (UUID) */+ id: string;+ /** Scope category */+ scope: CapabilityScope;+ /** Target resource (tool name, namespace, path pattern, etc.) */+ resource: string;+ /** Allowed actions (e.g., 'read', 'write', 'execute', 'delete') */+ actions: string[];+ /** Active constraints on this capability */+ constraints: CapabilityConstraint[];+ /** Agent or authority that granted this capability */+ grantedBy: string;+ /** Agent this capability is granted to */+ grantedTo: string;+ /** When the capability was granted (ms since epoch) */+ grantedAt: number;+ /** When the capability expires, or null for no expiry */+ expiresAt: number | null;+ /** Whether this capability can be delegated to sub-agents */+ delegatable: boolean;+ /** Whether this capability has been revoked */+ revoked: boolean;+ /** When the capability was revoked, or null if not revoked */+ revokedAt: number | null;+ /** Attestations attached to this capability */+ attestations: Attestation[];+ /** Parent capability ID for delegation chains, or null for root grants */+ parentCapabilityId: string | null;+}++/**+ * Result of evaluating a capability check+ */+export interface CapabilityCheckResult {+ /** Whether the requested action is allowed */+ allowed: boolean;+ /** Capabilities that matched the check criteria */+ capabilities: Capability[];+ /** Human-readable reason for the decision */+ reason: string;+ /** Active constraints that applied during evaluation */+ constraints: CapabilityConstraint[];+}++// ============================================================================+// Capability Algebra+// ============================================================================++/**+ * Capability Algebra+ *+ * Manages the lifecycle of typed capabilities: granting, restricting,+ * delegating, revoking, attesting, checking, and composing permissions.+ * All mutations produce new capability objects; the original is never+ * modified in place (except for revocation which is a state change).+ */+export class CapabilityAlgebra {+ /** All capabilities indexed by ID */+ private readonly capabilities: Map<string, Capability> = new Map();+ /** Index: agentId -> set of capability IDs */+ private readonly agentIndex: Map<string, Set<string>> = new Map();+ /** Index: parentCapabilityId -> set of child capability IDs */+ private readonly delegationIndex: Map<string, Set<string>> = new Map();++ // =========================================================================+ // Public API+ // =========================================================================++ /**+ * Grant a new root capability.+ *+ * Creates a capability with no parent (it is a root grant from an+ * authority to an agent).+ */+ grant(params: {+ scope: CapabilityScope;+ resource: string;+ actions: string[];+ grantedBy: string;+ grantedTo: string;+ constraints?: CapabilityConstraint[];+ expiresAt?: number | null;+ delegatable?: boolean;+ }): Capability {+ const capability: Capability = {+ id: randomUUID(),+ scope: params.scope,+ resource: params.resource,+ actions: [...params.actions],+ constraints: params.constraints ? [...params.constraints] : [],+ grantedBy: params.grantedBy,+ grantedTo: params.grantedTo,+ grantedAt: Date.now(),+ expiresAt: params.expiresAt ?? null,+ delegatable: params.delegatable ?? false,+ revoked: false,+ revokedAt: null,+ attestations: [],+ parentCapabilityId: null,+ };++ this.store(capability);+ return capability;+ }++ /**+ * Restrict a capability, producing a new capability with tighter constraints.+ *+ * Restrictions can only narrow permissions, never widen them:+ * - Actions can only be removed, never added+ * - Constraints can only be added, never removed+ * - Expiry can only be shortened, never extended+ * - Delegatable can only be set to false, never promoted to true+ */+ restrict(capability: Capability, restrictions: Partial<Capability>): Capability {+ const restricted: Capability = {+ ...capability,+ id: randomUUID(),+ grantedAt: Date.now(),+ attestations: [],+ parentCapabilityId: capability.id,+ };++ // Actions: only allow narrowing (intersection with original)+ if (restrictions.actions) {+ const originalSet = new Set(capability.actions);+ restricted.actions = restrictions.actions.filter(a => originalSet.has(a));+ }++ // Constraints: only allow adding more (union)+ if (restrictions.constraints) {+ restricted.constraints = [+ ...capability.constraints,+ ...restrictions.constraints,+ ];+ }++ // Expiry: only allow shortening (pick earlier)+ if (restrictions.expiresAt !== undefined) {+ if (restrictions.expiresAt !== null) {+ if (capability.expiresAt === null) {+ restricted.expiresAt = restrictions.expiresAt;+ } else {+ restricted.expiresAt = Math.min(capability.expiresAt, restrictions.expiresAt);+ }+ }+ // If restriction tries to set null (no expiry) but original has expiry, keep original+ }++ // Delegatable: can only be downgraded to false+ if (restrictions.delegatable !== undefined) {+ if (!restrictions.delegatable) {+ restricted.delegatable = false;+ }+ // Cannot promote to delegatable if original is not+ }++ this.store(restricted);+ return restricted;+ }++ /**+ * Delegate a capability to another agent.+ *+ * Creates a child capability with the new grantedTo agent. The parent+ * capability must have delegatable=true. Optional further restrictions+ * can be applied during delegation.+ *+ * @throws Error if the capability is not delegatable+ */+ delegate(+ capability: Capability,+ toAgentId: string,+ restrictions?: Partial<Capability>,+ ): Capability {+ if (!capability.delegatable) {+ throw new Error(+ `Capability ${capability.id} is not delegatable`+ );+ }++ if (capability.revoked) {+ throw new Error(+ `Cannot delegate revoked capability ${capability.id}`+ );+ }++ if (capability.expiresAt !== null && capability.expiresAt <= Date.now()) {+ throw new Error(+ `Cannot delegate expired capability ${capability.id}`+ );+ }++ const delegated: Capability = {+ ...capability,+ id: randomUUID(),+ grantedBy: capability.grantedTo,+ grantedTo: toAgentId,+ grantedAt: Date.now(),+ attestations: [],+ parentCapabilityId: capability.id,+ };++ // Apply optional further restrictions+ if (restrictions?.actions) {+ const originalSet = new Set(capability.actions);+ delegated.actions = restrictions.actions.filter(a => originalSet.has(a));+ }++ if (restrictions?.constraints) {+ delegated.constraints = [+ ...capability.constraints,+ ...restrictions.constraints,+ ];+ }++ if (restrictions?.expiresAt !== undefined && restrictions.expiresAt !== null) {+ if (capability.expiresAt === null) {+ delegated.expiresAt = restrictions.expiresAt;+ } else {+ delegated.expiresAt = Math.min(capability.expiresAt, restrictions.expiresAt);+ }+ }++ if (restrictions?.delegatable === false) {+ delegated.delegatable = false;+ }++ this.store(delegated);++ // Track delegation relationship+ const children = this.delegationIndex.get(capability.id) ?? new Set();+ children.add(delegated.id);+ this.delegationIndex.set(capability.id, children);++ return delegated;+ }++ /**+ * Expire a capability immediately by setting expiresAt to now.+ */+ expire(capabilityId: string): void {+ const capability = this.capabilities.get(capabilityId);+ if (!capability) return;+ capability.expiresAt = Date.now();+ }++ /**+ * Revoke a capability and cascade revocation to all delegated children.+ */+ revoke(capabilityId: string, _reason?: string): void {+ const capability = this.capabilities.get(capabilityId);+ if (!capability) return;++ capability.revoked = true;+ capability.revokedAt = Date.now();++ this.cascadeRevoke(capabilityId);+ }++ /**+ * Add an attestation to a capability.+ */+ attest(+ capabilityId: string,+ attestation: Omit<Attestation, 'attestedAt'>,+ ): void {+ const capability = this.capabilities.get(capabilityId);+ if (!capability) return;++ capability.attestations.push({+ ...attestation,+ attestedAt: Date.now(),+ });+ }++ /**+ * Check whether an agent is allowed to perform an action on a resource.+ *+ * Finds all non-revoked, non-expired capabilities for the agent that+ * match the requested scope and resource, checks if the requested action+ * is allowed, and verifies all constraints are satisfied.+ */+ check(+ agentId: string,+ scope: CapabilityScope,+ resource: string,+ action: string,+ context?: Record<string, unknown>,+ ): CapabilityCheckResult {+ const agentCapIds = this.agentIndex.get(agentId);+ if (!agentCapIds || agentCapIds.size === 0) {+ return {+ allowed: false,+ capabilities: [],+ reason: `No capabilities found for agent "${agentId}"`,+ constraints: [],+ };+ }++ const now = Date.now();+ const matchingCapabilities: Capability[] = [];+ const activeConstraints: CapabilityConstraint[] = [];++ for (const capId of agentCapIds) {+ const cap = this.capabilities.get(capId);+ if (!cap) continue;++ // Skip revoked+ if (cap.revoked) continue;++ // Skip expired+ if (cap.expiresAt !== null && cap.expiresAt <= now) continue;++ // Match scope and resource+ if (cap.scope !== scope) continue;+ if (cap.resource !== resource && cap.resource !== '*') continue;++ // Check action+ if (!cap.actions.includes(action) && !cap.actions.includes('*')) continue;++ // Check constraints+ if (!this.satisfiesConstraints(cap, context)) continue;++ matchingCapabilities.push(cap);+ activeConstraints.push(...cap.constraints);+ }++ if (matchingCapabilities.length === 0) {+ return {+ allowed: false,+ capabilities: [],+ reason: `No matching capability for agent "${agentId}" to "${action}" on ${scope}:${resource}`,+ constraints: [],+ };+ }++ return {+ allowed: true,+ capabilities: matchingCapabilities,+ reason: `Allowed by ${matchingCapabilities.length} capability(ies)`,+ constraints: activeConstraints,+ };+ }++ /**+ * Get all capabilities granted to a specific agent.+ */+ getCapabilities(agentId: string): Capability[] {+ const capIds = this.agentIndex.get(agentId);+ if (!capIds) return [];++ const result: Capability[] = [];+ for (const id of capIds) {+ const cap = this.capabilities.get(id);+ if (cap) result.push(cap);+ }+ return result;+ }++ /**+ * Get a capability by ID.+ */+ getCapability(id: string): Capability | undefined {+ return this.capabilities.get(id);+ }++ /**+ * Get the full delegation chain from root to the given capability.+ *+ * Returns an array ordered from the root ancestor to the given capability.+ */+ getDelegationChain(capabilityId: string): Capability[] {+ const chain: Capability[] = [];+ let current = this.capabilities.get(capabilityId);++ while (current) {+ chain.unshift(current);+ if (current.parentCapabilityId === null) break;+ current = this.capabilities.get(current.parentCapabilityId);+ }++ return chain;+ }++ /**+ * Compose two capabilities via intersection.+ *+ * - Actions = intersection of both action sets+ * - Constraints = union of both constraint sets+ * - Expiry = the tighter (earlier) of the two+ * - Delegatable = true only if both are delegatable+ * - Scope and resource must match; throws if they differ+ *+ * @throws Error if scope or resource do not match+ */+ compose(cap1: Capability, cap2: Capability): Capability {+ if (cap1.scope !== cap2.scope) {+ throw new Error(+ `Cannot compose capabilities with different scopes: "${cap1.scope}" vs "${cap2.scope}"`+ );+ }+ if (cap1.resource !== cap2.resource) {+ throw new Error(+ `Cannot compose capabilities with different resources: "${cap1.resource}" vs "${cap2.resource}"`+ );+ }++ // Actions: intersection+ const actionSet1 = new Set(cap1.actions);+ const intersectedActions = cap2.actions.filter(a => actionSet1.has(a));++ // Constraints: union+ const combinedConstraints = [...cap1.constraints, ...cap2.constraints];++ // Expiry: tightest+ let expiresAt: number | null = null;+ if (cap1.expiresAt !== null && cap2.expiresAt !== null) {+ expiresAt = Math.min(cap1.expiresAt, cap2.expiresAt);+ } else if (cap1.expiresAt !== null) {+ expiresAt = cap1.expiresAt;+ } else if (cap2.expiresAt !== null) {+ expiresAt = cap2.expiresAt;+ }++ const composed: Capability = {+ id: randomUUID(),+ scope: cap1.scope,+ resource: cap1.resource,+ actions: intersectedActions,+ constraints: combinedConstraints,+ grantedBy: cap1.grantedBy,+ grantedTo: cap1.grantedTo,+ grantedAt: Date.now(),+ expiresAt,+ delegatable: cap1.delegatable && cap2.delegatable,+ revoked: false,+ revokedAt: null,+ attestations: [],+ parentCapabilityId: null,+ };++ this.store(composed);+ return composed;+ }++ /**+ * Check if inner's permission set is a subset of outer's.+ *+ * Returns true if:+ * - inner.scope === outer.scope+ * - inner.resource === outer.resource+ * - Every action in inner is present in outer+ * - inner.expiresAt is <= outer.expiresAt (or outer has no expiry)+ */+ isSubset(inner: Capability, outer: Capability): boolean {+ if (inner.scope !== outer.scope) return false;+ if (inner.resource !== outer.resource) return false;++ const outerActions = new Set(outer.actions);+ for (const action of inner.actions) {+ if (!outerActions.has(action)) return false;+ }++ // Expiry: inner must expire no later than outer (or outer has no expiry)+ if (outer.expiresAt !== null) {+ if (inner.expiresAt === null) return false; // inner never expires but outer does+ if (inner.expiresAt > outer.expiresAt) return false;+ }++ return true;+ }++ // =========================================================================+ // Private Methods+ // =========================================================================++ /**+ * Evaluate whether all constraints on a capability are satisfied.+ */+ private satisfiesConstraints(+ capability: Capability,+ context?: Record<string, unknown>,+ ): boolean {+ for (const constraint of capability.constraints) {+ switch (constraint.type) {+ case 'time-window': {+ const now = Date.now();+ const start = constraint.params['start'] as number | undefined;+ const end = constraint.params['end'] as number | undefined;+ if (start !== undefined && now < start) return false;+ if (end !== undefined && now > end) return false;+ break;+ }+ case 'rate-limit': {+ // Rate-limit constraints are informational; enforcement is external.+ // If context provides current usage, check it.+ if (context) {+ const max = constraint.params['max'] as number | undefined;+ const current = context['currentUsage'] as number | undefined;+ if (max !== undefined && current !== undefined && current >= max) {+ return false;+ }+ }+ break;+ }+ case 'budget': {+ if (context) {+ const limit = constraint.params['limit'] as number | undefined;+ const used = context['budgetUsed'] as number | undefined;+ if (limit !== undefined && used !== undefined && used >= limit) {+ return false;+ }+ }+ break;+ }+ case 'condition': {+ // Condition constraints require a truthy context value at the specified key+ const key = constraint.params['key'] as string | undefined;+ const expectedValue = constraint.params['value'];+ if (key && context) {+ if (expectedValue !== undefined) {+ if (context[key] !== expectedValue) return false;+ } else {+ if (!context[key]) return false;+ }+ }+ break;+ }+ case 'scope-restriction': {+ // Scope restrictions limit to specific sub-resources+ const allowedPattern = constraint.params['pattern'] as string | undefined;+ if (allowedPattern && context) {+ const targetResource = context['targetResource'] as string | undefined;+ if (targetResource && !targetResource.startsWith(allowedPattern)) {+ return false;+ }+ }+ break;+ }+ }+ }++ return true;+ }++ /**+ * Cascade revocation to all delegated children of a capability.+ */+ private cascadeRevoke(capabilityId: string): void {+ const children = this.delegationIndex.get(capabilityId);+ if (!children) return;++ const now = Date.now();+ for (const childId of children) {+ const child = this.capabilities.get(childId);+ if (child && !child.revoked) {+ child.revoked = true;+ child.revokedAt = now;+ // Recurse into grandchildren+ this.cascadeRevoke(childId);+ }+ }+ }++ /**+ * Store a capability and update indices.+ */+ private store(capability: Capability): void {+ this.capabilities.set(capability.id, capability);++ const agentCaps = this.agentIndex.get(capability.grantedTo) ?? new Set();+ agentCaps.add(capability.id);+ this.agentIndex.set(capability.grantedTo, agentCaps);+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create a CapabilityAlgebra instance+ */+export function createCapabilityAlgebra(): CapabilityAlgebra {+ return new CapabilityAlgebra();+}diff --git a/v3/@claude-flow/guidance/src/evolution.ts b/v3/@claude-flow/guidance/src/evolution.tsnew file mode 100644index 0000000000..bbe20b0230--- /dev/null+++ b/v3/@claude-flow/guidance/src/evolution.ts@@ -0,0 +1,797 @@+/**+ * Evolution Pipeline+ *+ * Every change to prompts, policies, tools, and code becomes a signed change+ * proposal that goes through simulation, replay comparison, and staged rollout.+ *+ * Pipeline stages:+ * 1. Propose - Create a signed ChangeProposal+ * 2. Simulate - Replay golden traces with baseline vs candidate config+ * 3. Compare - Approve or reject based on divergence threshold+ * 4. Stage - Create a staged rollout plan (canary -> partial -> full)+ * 5. Advance - Progress through stages with metric gates+ * 6. Promote / Rollback - Apply permanently or revert+ *+ * @module @claude-flow/guidance/evolution+ */++import { createHash, createHmac, randomUUID } from 'node:crypto';++// ============================================================================+// Types+// ============================================================================++/**+ * The kind of change being proposed.+ */+export type ChangeProposalKind =+ | 'rule-modify'+ | 'rule-add'+ | 'rule-remove'+ | 'rule-promote'+ | 'policy-update'+ | 'tool-config'+ | 'budget-adjust';++/**+ * Lifecycle status of a change proposal.+ */+export type ProposalStatus =+ | 'draft'+ | 'signed'+ | 'simulating'+ | 'compared'+ | 'staged'+ | 'promoted'+ | 'rolled-back'+ | 'rejected';++/**+ * Risk assessment attached to a proposal.+ */+export interface RiskAssessment {+ level: 'low' | 'medium' | 'high';+ factors: string[];+}++/**+ * A signed change proposal describing a modification to the guidance system.+ */+export interface ChangeProposal {+ /** Unique identifier (UUID) */+ proposalId: string;+ /** What kind of change this is */+ kind: ChangeProposalKind;+ /** Short human-readable title */+ title: string;+ /** Longer description of the change */+ description: string;+ /** Agent or human ID that authored the proposal */+ author: string;+ /** Dot-path or identifier of what is being changed */+ targetPath: string;+ /** Before/after snapshot of the change */+ diff: { before: unknown; after: unknown };+ /** Why this change is being proposed */+ rationale: string;+ /** Risk assessment for the change */+ riskAssessment: RiskAssessment;+ /** HMAC-SHA256 signature of the proposal content */+ signature: string;+ /** Epoch ms when the proposal was created */+ createdAt: number;+ /** Current lifecycle status */+ status: ProposalStatus;+}++/**+ * A single decision point where baseline and candidate diverged.+ */+export interface DecisionDiff {+ /** Sequence number in the trace */+ seq: number;+ /** What the baseline decided */+ baseline: unknown;+ /** What the candidate decided */+ candidate: unknown;+ /** How severe the divergence is */+ severity: 'low' | 'medium' | 'high';+}++/**+ * Result of simulating a proposal against golden traces.+ */+export interface SimulationResult {+ /** Proposal that was simulated */+ proposalId: string;+ /** Hash of the trace produced by baseline config */+ baselineTraceHash: string;+ /** Hash of the trace produced by candidate config */+ candidateTraceHash: string;+ /** 0-1 score: 0 = identical, 1 = completely different */+ divergenceScore: number;+ /** Individual decision points where behaviour diverged */+ decisionDiffs: DecisionDiff[];+ /** Side-by-side metric comparison */+ metricsComparison: {+ baseline: Record<string, number>;+ candidate: Record<string, number>;+ };+ /** Whether the simulation passed acceptance criteria */+ passed: boolean;+ /** Human-readable reason for the verdict */+ reason: string;+}++/**+ * A single stage in a staged rollout.+ */+export interface RolloutStage {+ /** Stage name (e.g. 'canary', 'partial', 'full') */+ name: string;+ /** Percentage of traffic/agents this stage covers (0-100) */+ percentage: number;+ /** How long this stage should run before advancing (ms) */+ durationMs: number;+ /** Observed metrics during this stage */+ metrics: Record<string, number>;+ /** Maximum acceptable divergence before auto-rollback */+ divergenceThreshold: number;+ /** null = not evaluated yet, true = passed, false = failed */+ passed: boolean | null;+ /** Epoch ms when the stage started (null if not started) */+ startedAt: number | null;+ /** Epoch ms when the stage completed (null if not completed) */+ completedAt: number | null;+}++/**+ * A staged rollout plan for a change proposal.+ */+export interface StagedRollout {+ /** Unique rollout identifier */+ rolloutId: string;+ /** The proposal being rolled out */+ proposalId: string;+ /** Ordered stages (canary -> partial -> full) */+ stages: RolloutStage[];+ /** Index of the current stage (0-based) */+ currentStage: number;+ /** Overall rollout status */+ status: 'in-progress' | 'completed' | 'rolled-back';+ /** Epoch ms when the rollout started */+ startedAt: number;+ /** Epoch ms when the rollout completed (null if still running) */+ completedAt: number | null;+}++/**+ * History entry combining proposal, optional simulation, optional rollout,+ * and final outcome.+ */+export interface EvolutionHistoryEntry {+ proposal: ChangeProposal;+ simulation?: SimulationResult;+ rollout?: StagedRollout;+ outcome: ProposalStatus;+}++/**+ * Evaluator function for simulation: given a golden trace and a config variant,+ * produce a trace hash and metrics.+ */+export type TraceEvaluator = (+ trace: unknown,+ config: 'baseline' | 'candidate',+) => { traceHash: string; metrics: Record<string, number>; decisions: unknown[] };++// ============================================================================+// Configuration+// ============================================================================++export interface EvolutionPipelineConfig {+ /** HMAC signing key for proposals */+ signingKey?: string;+ /** Maximum divergence score (0-1) to approve a change */+ maxDivergence?: number;+ /** Default rollout stages */+ stages?: RolloutStage[];+}++const DEFAULT_SIGNING_KEY = 'claude-flow-evolution-default-key';+const DEFAULT_MAX_DIVERGENCE = 0.3;++const DEFAULT_STAGES: RolloutStage[] = [+ {+ name: 'canary',+ percentage: 5,+ durationMs: 60_000,+ metrics: {},+ divergenceThreshold: 0.2,+ passed: null,+ startedAt: null,+ completedAt: null,+ },+ {+ name: 'partial',+ percentage: 50,+ durationMs: 300_000,+ metrics: {},+ divergenceThreshold: 0.25,+ passed: null,+ startedAt: null,+ completedAt: null,+ },+ {+ name: 'full',+ percentage: 100,+ durationMs: 600_000,+ metrics: {},+ divergenceThreshold: 0.3,+ passed: null,+ startedAt: null,+ completedAt: null,+ },+];++// ============================================================================+// EvolutionPipeline+// ============================================================================++/**+ * The Evolution Pipeline manages the lifecycle of change proposals through+ * signing, simulation, comparison, staged rollout, and promotion or rollback.+ */+export class EvolutionPipeline {+ private readonly signingKey: string;+ private readonly maxDivergence: number;+ private readonly defaultStages: RolloutStage[];++ private proposals = new Map<string, ChangeProposal>();+ private simulations = new Map<string, SimulationResult>();+ private rollouts = new Map<string, StagedRollout>();++ constructor(config: EvolutionPipelineConfig = {}) {+ this.signingKey = config.signingKey ?? DEFAULT_SIGNING_KEY;+ this.maxDivergence = config.maxDivergence ?? DEFAULT_MAX_DIVERGENCE;+ this.defaultStages = config.stages ?? DEFAULT_STAGES;+ }++ // ==========================================================================+ // Propose+ // ==========================================================================++ /**+ * Create and sign a new change proposal.+ */+ propose(params: {+ kind: ChangeProposalKind;+ title: string;+ description: string;+ author: string;+ targetPath: string;+ diff: { before: unknown; after: unknown };+ rationale: string;+ riskAssessment: RiskAssessment;+ }): ChangeProposal {+ const proposalId = randomUUID();+ const createdAt = Date.now();++ const proposal: ChangeProposal = {+ proposalId,+ kind: params.kind,+ title: params.title,+ description: params.description,+ author: params.author,+ targetPath: params.targetPath,+ diff: params.diff,+ rationale: params.rationale,+ riskAssessment: params.riskAssessment,+ signature: '', // placeholder, signed below+ createdAt,+ status: 'draft',+ };++ proposal.signature = this.signProposal(proposal);+ proposal.status = 'signed';++ this.proposals.set(proposalId, proposal);+ return proposal;+ }++ // ==========================================================================+ // Simulate+ // ==========================================================================++ /**+ * Run golden traces through both baseline and candidate configs to measure+ * divergence. The evaluator is called once per golden trace per config.+ */+ simulate(+ proposalId: string,+ goldenTraces: unknown[],+ evaluator: TraceEvaluator,+ ): SimulationResult {+ const proposal = this.proposals.get(proposalId);+ if (!proposal) {+ throw new Error(`Proposal not found: ${proposalId}`);+ }++ proposal.status = 'simulating';++ // Evaluate each trace against both configs+ const baselineResults = goldenTraces.map(t => evaluator(t, 'baseline'));+ const candidateResults = goldenTraces.map(t => evaluator(t, 'candidate'));++ // Compute composite trace hashes+ const baselineTraceHash = this.hashTraceResults(baselineResults.map(r => r.traceHash));+ const candidateTraceHash = this.hashTraceResults(candidateResults.map(r => r.traceHash));++ // Compute decision diffs+ const decisionDiffs: DecisionDiff[] = [];+ for (let i = 0; i < goldenTraces.length; i++) {+ const bDecisions = baselineResults[i].decisions;+ const cDecisions = candidateResults[i].decisions;+ const maxLen = Math.max(bDecisions.length, cDecisions.length);++ for (let seq = 0; seq < maxLen; seq++) {+ const bVal = seq < bDecisions.length ? bDecisions[seq] : undefined;+ const cVal = seq < cDecisions.length ? cDecisions[seq] : undefined;++ if (JSON.stringify(bVal) !== JSON.stringify(cVal)) {+ decisionDiffs.push({+ seq,+ baseline: bVal,+ candidate: cVal,+ severity: this.classifyDiffSeverity(bVal, cVal),+ });+ }+ }+ }++ // Aggregate metrics+ const baselineMetrics = this.aggregateMetrics(baselineResults.map(r => r.metrics));+ const candidateMetrics = this.aggregateMetrics(candidateResults.map(r => r.metrics));++ // Compute divergence score (0-1)+ const divergenceScore = this.computeDivergenceScore(+ baselineTraceHash,+ candidateTraceHash,+ decisionDiffs,+ goldenTraces.length,+ );++ const passed = divergenceScore <= this.maxDivergence;+ const reason = passed+ ? `Divergence ${divergenceScore.toFixed(3)} is within threshold ${this.maxDivergence}`+ : `Divergence ${divergenceScore.toFixed(3)} exceeds threshold ${this.maxDivergence}`;++ const result: SimulationResult = {+ proposalId,+ baselineTraceHash,+ candidateTraceHash,+ divergenceScore,+ decisionDiffs,+ metricsComparison: {+ baseline: baselineMetrics,+ candidate: candidateMetrics,+ },+ passed,+ reason,+ };++ this.simulations.set(proposalId, result);+ return result;+ }++ // ==========================================================================+ // Compare+ // ==========================================================================++ /**+ * Compare a simulation result against acceptance criteria.+ *+ * Checks:+ * 1. Divergence is below threshold+ * 2. No regression in key metrics (candidate >= baseline)+ */+ compare(+ proposalId: string,+ simulationResult: SimulationResult,+ ): { approved: boolean; reason: string } {+ const proposal = this.proposals.get(proposalId);+ if (!proposal) {+ throw new Error(`Proposal not found: ${proposalId}`);+ }++ // Check divergence threshold+ if (simulationResult.divergenceScore > this.maxDivergence) {+ proposal.status = 'rejected';+ return {+ approved: false,+ reason: `Divergence ${simulationResult.divergenceScore.toFixed(3)} exceeds threshold ${this.maxDivergence}`,+ };+ }++ // Check for metric regressions+ const { baseline, candidate } = simulationResult.metricsComparison;+ const regressions: string[] = [];++ for (const key of Object.keys(baseline)) {+ if (candidate[key] !== undefined && candidate[key] < baseline[key]) {+ const pctDrop = ((baseline[key] - candidate[key]) / Math.max(baseline[key], 1)) * 100;+ // Only flag significant regressions (> 5%)+ if (pctDrop > 5) {+ regressions.push(`${key} regressed by ${pctDrop.toFixed(1)}%`);+ }+ }+ }++ if (regressions.length > 0) {+ proposal.status = 'rejected';+ return {+ approved: false,+ reason: `Metric regressions detected: ${regressions.join('; ')}`,+ };+ }++ proposal.status = 'compared';+ return {+ approved: true,+ reason: `Divergence ${simulationResult.divergenceScore.toFixed(3)} within threshold, no metric regressions`,+ };+ }++ // ==========================================================================+ // Stage+ // ==========================================================================++ /**+ * Create a staged rollout plan for a proposal.+ */+ stage(proposalId: string): StagedRollout {+ const proposal = this.proposals.get(proposalId);+ if (!proposal) {+ throw new Error(`Proposal not found: ${proposalId}`);+ }++ const now = Date.now();++ // Deep-clone default stages so each rollout has independent state+ const stages: RolloutStage[] = this.defaultStages.map(s => ({+ ...s,+ metrics: { ...s.metrics },+ passed: null,+ startedAt: null,+ completedAt: null,+ }));++ // Start the first stage immediately+ stages[0].startedAt = now;++ const rollout: StagedRollout = {+ rolloutId: randomUUID(),+ proposalId,+ stages,+ currentStage: 0,+ status: 'in-progress',+ startedAt: now,+ completedAt: null,+ };++ proposal.status = 'staged';+ this.rollouts.set(rollout.rolloutId, rollout);+ return rollout;+ }++ // ==========================================================================+ // Advance Stage+ // ==========================================================================++ /**+ * Advance to the next rollout stage or auto-rollback.+ *+ * If `stageMetrics.divergence` exceeds the current stage's threshold,+ * the rollout is automatically rolled back.+ */+ advanceStage(+ rolloutId: string,+ stageMetrics: Record<string, number>,+ ): { advanced: boolean; rolledBack: boolean; reason: string } {+ const rollout = this.rollouts.get(rolloutId);+ if (!rollout) {+ throw new Error(`Rollout not found: ${rolloutId}`);+ }++ if (rollout.status !== 'in-progress') {+ return {+ advanced: false,+ rolledBack: false,+ reason: `Rollout is ${rollout.status}, not in-progress`,+ };+ }++ const current = rollout.stages[rollout.currentStage];+ const now = Date.now();++ // Record metrics on the current stage+ current.metrics = { ...stageMetrics };++ // Check divergence against threshold+ const divergence = stageMetrics.divergence ?? 0;+ if (divergence > current.divergenceThreshold) {+ // Auto-rollback+ current.passed = false;+ current.completedAt = now;+ this.rollback(rolloutId, `Stage "${current.name}" divergence ${divergence.toFixed(3)} exceeded threshold ${current.divergenceThreshold}`);+ return {+ advanced: false,+ rolledBack: true,+ reason: `Auto-rollback: divergence ${divergence.toFixed(3)} exceeded threshold ${current.divergenceThreshold} at stage "${current.name}"`,+ };+ }++ // Current stage passed+ current.passed = true;+ current.completedAt = now;++ // Check if there are more stages+ if (rollout.currentStage < rollout.stages.length - 1) {+ rollout.currentStage += 1;+ rollout.stages[rollout.currentStage].startedAt = now;+ return {+ advanced: true,+ rolledBack: false,+ reason: `Advanced to stage "${rollout.stages[rollout.currentStage].name}"`,+ };+ }++ // All stages complete - auto-promote+ rollout.status = 'completed';+ rollout.completedAt = now;+ const proposal = this.proposals.get(rollout.proposalId);+ if (proposal) {+ proposal.status = 'promoted';+ }++ return {+ advanced: true,+ rolledBack: false,+ reason: 'All stages completed successfully; proposal promoted',+ };+ }++ // ==========================================================================+ // Rollback+ // ==========================================================================++ /**+ * Roll back a staged rollout.+ */+ rollback(rolloutId: string, reason: string): void {+ const rollout = this.rollouts.get(rolloutId);+ if (!rollout) {+ throw new Error(`Rollout not found: ${rolloutId}`);+ }++ rollout.status = 'rolled-back';+ rollout.completedAt = Date.now();++ const proposal = this.proposals.get(rollout.proposalId);+ if (proposal) {+ proposal.status = 'rolled-back';+ }+ }++ // ==========================================================================+ // Promote+ // ==========================================================================++ /**+ * Promote a rollout, permanently applying the change.+ */+ promote(rolloutId: string): void {+ const rollout = this.rollouts.get(rolloutId);+ if (!rollout) {+ throw new Error(`Rollout not found: ${rolloutId}`);+ }++ rollout.status = 'completed';+ rollout.completedAt = Date.now();++ const proposal = this.proposals.get(rollout.proposalId);+ if (proposal) {+ proposal.status = 'promoted';+ }+ }++ // ==========================================================================+ // Queries+ // ==========================================================================++ /**+ * Get a proposal by ID.+ */+ getProposal(id: string): ChangeProposal | undefined {+ return this.proposals.get(id);+ }++ /**+ * Get all proposals, optionally filtered by status.+ */+ getProposals(status?: ProposalStatus): ChangeProposal[] {+ const all = Array.from(this.proposals.values());+ if (status === undefined) {+ return all;+ }+ return all.filter(p => p.status === status);+ }++ /**+ * Get a rollout by ID.+ */+ getRollout(id: string): StagedRollout | undefined {+ return this.rollouts.get(id);+ }++ /**+ * Get the full evolution history across all proposals.+ */+ getHistory(): EvolutionHistoryEntry[] {+ return Array.from(this.proposals.values()).map(proposal => ({+ proposal,+ simulation: this.simulations.get(proposal.proposalId),+ rollout: this.findRolloutByProposal(proposal.proposalId),+ outcome: proposal.status,+ }));+ }++ // ==========================================================================+ // Private Helpers+ // ==========================================================================++ /**+ * Produce an HMAC-SHA256 signature for a proposal.+ *+ * The signature covers every field except `signature` and `status`.+ */+ private signProposal(proposal: ChangeProposal): string {+ const body = {+ proposalId: proposal.proposalId,+ kind: proposal.kind,+ title: proposal.title,+ description: proposal.description,+ author: proposal.author,+ targetPath: proposal.targetPath,+ diff: proposal.diff,+ rationale: proposal.rationale,+ riskAssessment: proposal.riskAssessment,+ createdAt: proposal.createdAt,+ };+ const payload = JSON.stringify(body);+ return createHmac('sha256', this.signingKey).update(payload).digest('hex');+ }++ /**+ * Compute a composite hash from an array of trace hashes.+ */+ private hashTraceResults(traceHashes: string[]): string {+ const payload = traceHashes.join(':');+ return createHash('sha256').update(payload).digest('hex');+ }++ /**+ * Classify how severe a single decision diff is.+ */+ private classifyDiffSeverity(+ baseline: unknown,+ candidate: unknown,+ ): 'low' | 'medium' | 'high' {+ // If one is undefined (extra/missing decision), it is high+ if (baseline === undefined || candidate === undefined) {+ return 'high';+ }++ const bStr = JSON.stringify(baseline);+ const cStr = JSON.stringify(candidate);++ // Very different lengths suggest structural changes+ if (Math.abs(bStr.length - cStr.length) > bStr.length * 0.5) {+ return 'high';+ }++ // Moderate difference+ if (bStr.length > 0 && Math.abs(bStr.length - cStr.length) > bStr.length * 0.2) {+ return 'medium';+ }++ return 'low';+ }++ /**+ * Compute an overall divergence score (0-1).+ */+ private computeDivergenceScore(+ baselineHash: string,+ candidateHash: string,+ diffs: DecisionDiff[],+ traceCount: number,+ ): number {+ // If hashes are identical, divergence = 0+ if (baselineHash === candidateHash) {+ return 0;+ }++ // If there are no golden traces, treat as fully divergent+ if (traceCount === 0) {+ return 1;+ }++ // Weight diffs by severity+ const severityWeights: Record<string, number> = {+ low: 0.1,+ medium: 0.4,+ high: 1.0,+ };++ const totalWeight = diffs.reduce(+ (sum, d) => sum + (severityWeights[d.severity] ?? 0.5),+ 0,+ );++ // Normalize: max possible weight is traceCount * maxDecisionsPerTrace+ // Use a heuristic cap to keep score in [0, 1]+ const maxExpected = traceCount * 5; // assume ~5 decisions per trace at max weight+ const raw = totalWeight / Math.max(maxExpected, 1);++ return Math.min(1, Math.max(0, raw));+ }++ /**+ * Aggregate an array of metric records into averages.+ */+ private aggregateMetrics(records: Record<string, number>[]): Record<string, number> {+ if (records.length === 0) return {};++ const sums: Record<string, number> = {};+ const counts: Record<string, number> = {};++ for (const record of records) {+ for (const [key, value] of Object.entries(record)) {+ sums[key] = (sums[key] ?? 0) + value;+ counts[key] = (counts[key] ?? 0) + 1;+ }+ }++ const result: Record<string, number> = {};+ for (const key of Object.keys(sums)) {+ result[key] = sums[key] / counts[key];+ }+ return result;+ }++ /**+ * Find the rollout associated with a proposal.+ */+ private findRolloutByProposal(proposalId: string): StagedRollout | undefined {+ for (const rollout of this.rollouts.values()) {+ if (rollout.proposalId === proposalId) {+ return rollout;+ }+ }+ return undefined;+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create an EvolutionPipeline instance.+ */+export function createEvolutionPipeline(+ config?: EvolutionPipelineConfig,+): EvolutionPipeline {+ return new EvolutionPipeline(config);+}diff --git a/v3/@claude-flow/guidance/tests/capabilities.test.ts b/v3/@claude-flow/guidance/tests/capabilities.test.tsnew file mode 100644index 0000000000..f7cb2ec14e--- /dev/null+++ b/v3/@claude-flow/guidance/tests/capabilities.test.ts@@ -0,0 +1,861 @@+/**+ * Tests for Capability Algebra+ */+import { describe, it, expect, beforeEach } from 'vitest';+import {+ CapabilityAlgebra,+ createCapabilityAlgebra,+ type Capability,+ type CapabilityScope,+ type CapabilityConstraint,+} from '../src/capabilities.js';++// ============================================================================+// Test Helpers+// ============================================================================++let algebra: CapabilityAlgebra;++function grantBasic(overrides: {+ scope?: CapabilityScope;+ resource?: string;+ actions?: string[];+ grantedBy?: string;+ grantedTo?: string;+ constraints?: CapabilityConstraint[];+ expiresAt?: number | null;+ delegatable?: boolean;+} = {}): Capability {+ return algebra.grant({+ scope: overrides.scope ?? 'tool',+ resource: overrides.resource ?? 'bash',+ actions: overrides.actions ?? ['execute'],+ grantedBy: overrides.grantedBy ?? 'authority-1',+ grantedTo: overrides.grantedTo ?? 'agent-1',+ constraints: overrides.constraints,+ expiresAt: overrides.expiresAt,+ delegatable: overrides.delegatable,+ });+}++// ============================================================================+// Grant Tests+// ============================================================================++describe('CapabilityAlgebra', () => {+ beforeEach(() => {+ algebra = new CapabilityAlgebra();+ });++ describe('grant', () => {+ it('should create a capability with correct fields', () => {+ const cap = algebra.grant({+ scope: 'tool',+ resource: 'bash',+ actions: ['execute', 'read'],+ grantedBy: 'authority-1',+ grantedTo: 'agent-1',+ constraints: [{ type: 'rate-limit', params: { max: 10 } }],+ expiresAt: Date.now() + 60_000,+ delegatable: true,+ });++ expect(cap.id).toBeTruthy();+ expect(cap.scope).toBe('tool');+ expect(cap.resource).toBe('bash');+ expect(cap.actions).toEqual(['execute', 'read']);+ expect(cap.constraints).toHaveLength(1);+ expect(cap.constraints[0].type).toBe('rate-limit');+ expect(cap.grantedBy).toBe('authority-1');+ expect(cap.grantedTo).toBe('agent-1');+ expect(cap.grantedAt).toBeLessThanOrEqual(Date.now());+ expect(cap.expiresAt).toBeGreaterThan(Date.now());+ expect(cap.delegatable).toBe(true);+ expect(cap.revoked).toBe(false);+ expect(cap.revokedAt).toBeNull();+ expect(cap.attestations).toEqual([]);+ expect(cap.parentCapabilityId).toBeNull();+ });++ it('should default to non-delegatable with no expiry and no constraints', () => {+ const cap = algebra.grant({+ scope: 'memory',+ resource: 'shared',+ actions: ['read'],+ grantedBy: 'auth',+ grantedTo: 'agent',+ });++ expect(cap.delegatable).toBe(false);+ expect(cap.expiresAt).toBeNull();+ expect(cap.constraints).toEqual([]);+ });++ it('should store the capability and make it retrievable', () => {+ const cap = grantBasic();+ const retrieved = algebra.getCapability(cap.id);++ expect(retrieved).toBeDefined();+ expect(retrieved!.id).toBe(cap.id);+ });++ it('should index the capability by agent', () => {+ grantBasic({ grantedTo: 'agent-A' });+ grantBasic({ grantedTo: 'agent-A', resource: 'edit' });+ grantBasic({ grantedTo: 'agent-B' });++ expect(algebra.getCapabilities('agent-A')).toHaveLength(2);+ expect(algebra.getCapabilities('agent-B')).toHaveLength(1);+ expect(algebra.getCapabilities('agent-C')).toHaveLength(0);+ });+ });++ // ============================================================================+ // Restrict Tests+ // ============================================================================++ describe('restrict', () => {+ it('should create a new capability with tighter actions', () => {+ const original = grantBasic({ actions: ['read', 'write', 'delete'] });+ const restricted = algebra.restrict(original, { actions: ['read', 'write'] });++ expect(restricted.id).not.toBe(original.id);+ expect(restricted.actions).toEqual(['read', 'write']);+ expect(restricted.parentCapabilityId).toBe(original.id);+ });++ it('should never loosen actions (cannot add actions not in original)', () => {+ const original = grantBasic({ actions: ['read'] });+ const restricted = algebra.restrict(original, { actions: ['read', 'write', 'delete'] });++ // Only 'read' should survive since original only has 'read'+ expect(restricted.actions).toEqual(['read']);+ });++ it('should union constraints (only add, never remove)', () => {+ const original = grantBasic({+ constraints: [{ type: 'rate-limit', params: { max: 10 } }],+ });+ const restricted = algebra.restrict(original, {+ constraints: [{ type: 'budget', params: { limit: 100 } }],+ });++ expect(restricted.constraints).toHaveLength(2);+ expect(restricted.constraints[0].type).toBe('rate-limit');+ expect(restricted.constraints[1].type).toBe('budget');+ });++ it('should never extend expiry', () => {+ const futureExpiry = Date.now() + 60_000;+ const farFutureExpiry = Date.now() + 120_000;++ const original = grantBasic({ expiresAt: futureExpiry });+ const restricted = algebra.restrict(original, { expiresAt: farFutureExpiry });++ // Should keep the original (tighter) expiry+ expect(restricted.expiresAt).toBe(futureExpiry);+ });++ it('should allow shortening expiry', () => {+ const futureExpiry = Date.now() + 60_000;+ const soonerExpiry = Date.now() + 30_000;++ const original = grantBasic({ expiresAt: futureExpiry });+ const restricted = algebra.restrict(original, { expiresAt: soonerExpiry });++ expect(restricted.expiresAt).toBe(soonerExpiry);+ });++ it('should set expiry when original has no expiry', () => {+ const original = grantBasic({ expiresAt: null });+ const newExpiry = Date.now() + 30_000;+ const restricted = algebra.restrict(original, { expiresAt: newExpiry });++ expect(restricted.expiresAt).toBe(newExpiry);+ });++ it('should not promote delegatable from false to true', () => {+ const original = grantBasic({ delegatable: false });+ const restricted = algebra.restrict(original, { delegatable: true });++ // Cannot promote; original stays false+ expect(restricted.delegatable).toBe(false);+ });++ it('should allow downgrading delegatable from true to false', () => {+ const original = grantBasic({ delegatable: true });+ const restricted = algebra.restrict(original, { delegatable: false });++ expect(restricted.delegatable).toBe(false);+ });+ });++ // ============================================================================+ // Delegate Tests+ // ============================================================================++ describe('delegate', () => {+ it('should create a child capability with parentCapabilityId', () => {+ const parent = grantBasic({ delegatable: true, grantedTo: 'agent-A' });+ const child = algebra.delegate(parent, 'agent-B');++ expect(child.parentCapabilityId).toBe(parent.id);+ expect(child.grantedTo).toBe('agent-B');+ expect(child.grantedBy).toBe('agent-A');+ expect(child.id).not.toBe(parent.id);+ });++ it('should fail when capability is not delegatable', () => {+ const nonDelegatable = grantBasic({ delegatable: false });++ expect(() => algebra.delegate(nonDelegatable, 'agent-B')).toThrow(+ /not delegatable/+ );+ });++ it('should fail when capability is revoked', () => {+ const cap = grantBasic({ delegatable: true });+ algebra.revoke(cap.id);++ expect(() => algebra.delegate(cap, 'agent-B')).toThrow(+ /revoked/+ );+ });++ it('should fail when capability is expired', () => {+ const cap = grantBasic({ delegatable: true, expiresAt: Date.now() - 1_000 });++ expect(() => algebra.delegate(cap, 'agent-B')).toThrow(+ /expired/+ );+ });++ it('should apply further restrictions during delegation', () => {+ const parent = grantBasic({+ delegatable: true,+ actions: ['read', 'write', 'delete'],+ });++ const child = algebra.delegate(parent, 'agent-B', {+ actions: ['read'],+ delegatable: false,+ });++ expect(child.actions).toEqual(['read']);+ expect(child.delegatable).toBe(false);+ });++ it('should inherit scope and resource from parent', () => {+ const parent = grantBasic({+ delegatable: true,+ scope: 'file',+ resource: '/src/**',+ });++ const child = algebra.delegate(parent, 'agent-B');++ expect(child.scope).toBe('file');+ expect(child.resource).toBe('/src/**');+ });++ it('should add delegated constraints on top of parent constraints', () => {+ const parent = grantBasic({+ delegatable: true,+ constraints: [{ type: 'rate-limit', params: { max: 100 } }],+ });++ const child = algebra.delegate(parent, 'agent-B', {+ constraints: [{ type: 'budget', params: { limit: 50 } }],+ });++ expect(child.constraints).toHaveLength(2);+ });+ });++ // ============================================================================+ // Expire Tests+ // ============================================================================++ describe('expire', () => {+ it('should set expiresAt to now', () => {+ const cap = grantBasic({ expiresAt: Date.now() + 60_000 });+ const before = Date.now();++ algebra.expire(cap.id);++ const updated = algebra.getCapability(cap.id)!;+ expect(updated.expiresAt).toBeGreaterThanOrEqual(before);+ expect(updated.expiresAt).toBeLessThanOrEqual(Date.now());+ });++ it('should cause subsequent checks to deny access', () => {+ const cap = grantBasic({ grantedTo: 'agent-1' });++ // Before expiry, should be allowed+ const resultBefore = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(resultBefore.allowed).toBe(true);++ // Expire and check again+ algebra.expire(cap.id);++ const resultAfter = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(resultAfter.allowed).toBe(false);+ });++ it('should be a no-op for unknown capability IDs', () => {+ // Should not throw+ algebra.expire('nonexistent-id');+ });+ });++ // ============================================================================+ // Revoke Tests+ // ============================================================================++ describe('revoke', () => {+ it('should mark capability as revoked', () => {+ const cap = grantBasic();+ algebra.revoke(cap.id);++ const updated = algebra.getCapability(cap.id)!;+ expect(updated.revoked).toBe(true);+ expect(updated.revokedAt).toBeLessThanOrEqual(Date.now());+ });++ it('should cascade revocation to all delegated children', () => {+ const root = grantBasic({ delegatable: true, grantedTo: 'agent-A' });+ const child = algebra.delegate(root, 'agent-B');+ const grandchild = algebra.delegate(child, 'agent-C');++ algebra.revoke(root.id);++ expect(algebra.getCapability(root.id)!.revoked).toBe(true);+ expect(algebra.getCapability(child.id)!.revoked).toBe(true);+ expect(algebra.getCapability(grandchild.id)!.revoked).toBe(true);+ });++ it('should deny access after revocation', () => {+ grantBasic({ grantedTo: 'agent-1' });++ const beforeRevoke = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(beforeRevoke.allowed).toBe(true);++ const caps = algebra.getCapabilities('agent-1');+ algebra.revoke(caps[0].id);++ const afterRevoke = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(afterRevoke.allowed).toBe(false);+ });++ it('should be a no-op for unknown capability IDs', () => {+ algebra.revoke('nonexistent-id');+ });++ it('should not affect sibling capabilities', () => {+ const root = grantBasic({ delegatable: true, grantedTo: 'agent-A' });+ const child1 = algebra.delegate(root, 'agent-B');+ const child2 = algebra.delegate(root, 'agent-C');++ algebra.revoke(child1.id);++ expect(algebra.getCapability(child1.id)!.revoked).toBe(true);+ expect(algebra.getCapability(child2.id)!.revoked).toBe(false);+ expect(algebra.getCapability(root.id)!.revoked).toBe(false);+ });+ });++ // ============================================================================+ // Attest Tests+ // ============================================================================++ describe('attest', () => {+ it('should add an attestation with timestamp', () => {+ const cap = grantBasic();+ const before = Date.now();++ algebra.attest(cap.id, {+ attesterId: 'auditor-1',+ claim: 'Passed security review',+ evidence: 'audit-report-2026-01.pdf',+ signature: 'abc123hex',+ });++ const updated = algebra.getCapability(cap.id)!;+ expect(updated.attestations).toHaveLength(1);+ expect(updated.attestations[0].attesterId).toBe('auditor-1');+ expect(updated.attestations[0].claim).toBe('Passed security review');+ expect(updated.attestations[0].evidence).toBe('audit-report-2026-01.pdf');+ expect(updated.attestations[0].signature).toBe('abc123hex');+ expect(updated.attestations[0].attestedAt).toBeGreaterThanOrEqual(before);+ });++ it('should support multiple attestations', () => {+ const cap = grantBasic();++ algebra.attest(cap.id, {+ attesterId: 'auditor-1',+ claim: 'Claim A',+ evidence: null,+ signature: 'sig1',+ });+ algebra.attest(cap.id, {+ attesterId: 'auditor-2',+ claim: 'Claim B',+ evidence: null,+ signature: 'sig2',+ });++ const updated = algebra.getCapability(cap.id)!;+ expect(updated.attestations).toHaveLength(2);+ });++ it('should be a no-op for unknown capability IDs', () => {+ algebra.attest('nonexistent', {+ attesterId: 'x',+ claim: 'test',+ evidence: null,+ signature: 'sig',+ });+ // No throw+ });+ });++ // ============================================================================+ // Check Tests+ // ============================================================================++ describe('check', () => {+ it('should allow when a matching capability exists', () => {+ grantBasic({+ scope: 'tool',+ resource: 'bash',+ actions: ['execute'],+ grantedTo: 'agent-1',+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');++ expect(result.allowed).toBe(true);+ expect(result.capabilities).toHaveLength(1);+ expect(result.reason).toContain('Allowed');+ });++ it('should deny when no capability exists for the agent', () => {+ const result = algebra.check('unknown-agent', 'tool', 'bash', 'execute');++ expect(result.allowed).toBe(false);+ expect(result.capabilities).toHaveLength(0);+ expect(result.reason).toContain('No capabilities');+ });++ it('should deny when the action is not in the capability', () => {+ grantBasic({+ scope: 'tool',+ resource: 'bash',+ actions: ['read'],+ grantedTo: 'agent-1',+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');++ expect(result.allowed).toBe(false);+ });++ it('should deny when the scope does not match', () => {+ grantBasic({+ scope: 'file',+ resource: 'bash',+ actions: ['execute'],+ grantedTo: 'agent-1',+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should deny when the resource does not match', () => {+ grantBasic({+ scope: 'tool',+ resource: 'edit',+ actions: ['execute'],+ grantedTo: 'agent-1',+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should respect expiry', () => {+ grantBasic({+ scope: 'tool',+ resource: 'bash',+ actions: ['execute'],+ grantedTo: 'agent-1',+ expiresAt: Date.now() - 1_000, // Already expired+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should respect revocation', () => {+ const cap = grantBasic({+ scope: 'tool',+ resource: 'bash',+ actions: ['execute'],+ grantedTo: 'agent-1',+ });++ algebra.revoke(cap.id);++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should collect active constraints in result', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [+ { type: 'rate-limit', params: { max: 10 } },+ { type: 'budget', params: { limit: 100 } },+ ],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');++ expect(result.allowed).toBe(true);+ expect(result.constraints).toHaveLength(2);+ });++ it('should deny when rate-limit constraint is exceeded via context', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{ type: 'rate-limit', params: { max: 5 } }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute', {+ currentUsage: 5,+ });++ expect(result.allowed).toBe(false);+ });++ it('should deny when budget constraint is exceeded via context', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{ type: 'budget', params: { limit: 100 } }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute', {+ budgetUsed: 100,+ });++ expect(result.allowed).toBe(false);+ });++ it('should match multiple capabilities and return all', () => {+ grantBasic({+ grantedTo: 'agent-1',+ scope: 'tool',+ resource: 'bash',+ actions: ['execute'],+ });+ grantBasic({+ grantedTo: 'agent-1',+ scope: 'tool',+ resource: 'bash',+ actions: ['execute', 'read'],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');++ expect(result.allowed).toBe(true);+ expect(result.capabilities).toHaveLength(2);+ });+ });++ // ============================================================================+ // Compose Tests+ // ============================================================================++ describe('compose', () => {+ it('should intersect actions', () => {+ const cap1 = grantBasic({ actions: ['read', 'write', 'delete'] });+ const cap2 = grantBasic({ actions: ['read', 'write', 'execute'] });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.actions).toEqual(['read', 'write']);+ });++ it('should union constraints', () => {+ const cap1 = grantBasic({+ constraints: [{ type: 'rate-limit', params: { max: 10 } }],+ });+ const cap2 = grantBasic({+ constraints: [{ type: 'budget', params: { limit: 50 } }],+ });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.constraints).toHaveLength(2);+ expect(composed.constraints[0].type).toBe('rate-limit');+ expect(composed.constraints[1].type).toBe('budget');+ });++ it('should pick the tightest expiry when both have expiry', () => {+ const sooner = Date.now() + 30_000;+ const later = Date.now() + 60_000;++ const cap1 = grantBasic({ expiresAt: sooner });+ const cap2 = grantBasic({ expiresAt: later });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.expiresAt).toBe(sooner);+ });++ it('should use the non-null expiry when one has no expiry', () => {+ const expiry = Date.now() + 30_000;++ const cap1 = grantBasic({ expiresAt: expiry });+ const cap2 = grantBasic({ expiresAt: null });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.expiresAt).toBe(expiry);+ });++ it('should result in null expiry when both have no expiry', () => {+ const cap1 = grantBasic({ expiresAt: null });+ const cap2 = grantBasic({ expiresAt: null });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.expiresAt).toBeNull();+ });++ it('should be delegatable only if both are delegatable', () => {+ const cap1 = grantBasic({ delegatable: true });+ const cap2 = grantBasic({ delegatable: false });++ const composed = algebra.compose(cap1, cap2);++ expect(composed.delegatable).toBe(false);+ });++ it('should throw when scopes differ', () => {+ const cap1 = grantBasic({ scope: 'tool' });+ const cap2 = grantBasic({ scope: 'file' });++ expect(() => algebra.compose(cap1, cap2)).toThrow(/different scopes/);+ });++ it('should throw when resources differ', () => {+ const cap1 = grantBasic({ resource: 'bash' });+ const cap2 = grantBasic({ resource: 'edit' });++ expect(() => algebra.compose(cap1, cap2)).toThrow(/different resources/);+ });+ });++ // ============================================================================+ // isSubset Tests+ // ============================================================================++ describe('isSubset', () => {+ it('should return true when inner is a strict subset', () => {+ const outer = grantBasic({ actions: ['read', 'write', 'delete'] });+ const inner = grantBasic({ actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(true);+ });++ it('should return true when inner equals outer', () => {+ const outer = grantBasic({ actions: ['read', 'write'] });+ const inner = grantBasic({ actions: ['read', 'write'] });++ expect(algebra.isSubset(inner, outer)).toBe(true);+ });++ it('should return false when inner has actions not in outer', () => {+ const outer = grantBasic({ actions: ['read'] });+ const inner = grantBasic({ actions: ['read', 'write'] });++ expect(algebra.isSubset(inner, outer)).toBe(false);+ });++ it('should return false when scopes differ', () => {+ const outer = grantBasic({ scope: 'tool', actions: ['read'] });+ const inner = grantBasic({ scope: 'file', actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(false);+ });++ it('should return false when resources differ', () => {+ const outer = grantBasic({ resource: 'bash', actions: ['read'] });+ const inner = grantBasic({ resource: 'edit', actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(false);+ });++ it('should return false when inner never expires but outer does', () => {+ const outer = grantBasic({ expiresAt: Date.now() + 60_000, actions: ['read'] });+ const inner = grantBasic({ expiresAt: null, actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(false);+ });++ it('should return false when inner expires after outer', () => {+ const outer = grantBasic({ expiresAt: Date.now() + 30_000, actions: ['read'] });+ const inner = grantBasic({ expiresAt: Date.now() + 60_000, actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(false);+ });++ it('should return true when inner expires before outer', () => {+ const outer = grantBasic({ expiresAt: Date.now() + 60_000, actions: ['read'] });+ const inner = grantBasic({ expiresAt: Date.now() + 30_000, actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(true);+ });++ it('should return true when outer has no expiry', () => {+ const outer = grantBasic({ expiresAt: null, actions: ['read'] });+ const inner = grantBasic({ expiresAt: Date.now() + 30_000, actions: ['read'] });++ expect(algebra.isSubset(inner, outer)).toBe(true);+ });+ });++ // ============================================================================+ // getDelegationChain Tests+ // ============================================================================++ describe('getDelegationChain', () => {+ it('should return a single-element chain for root capabilities', () => {+ const root = grantBasic();+ const chain = algebra.getDelegationChain(root.id);++ expect(chain).toHaveLength(1);+ expect(chain[0].id).toBe(root.id);+ });++ it('should return the full chain from root to leaf', () => {+ const root = grantBasic({ delegatable: true, grantedTo: 'A' });+ const child = algebra.delegate(root, 'B');+ const grandchild = algebra.delegate(child, 'C');++ const chain = algebra.getDelegationChain(grandchild.id);++ expect(chain).toHaveLength(3);+ expect(chain[0].id).toBe(root.id);+ expect(chain[1].id).toBe(child.id);+ expect(chain[2].id).toBe(grandchild.id);+ });++ it('should return empty for unknown capability IDs', () => {+ const chain = algebra.getDelegationChain('nonexistent');+ expect(chain).toHaveLength(0);+ });++ it('should work for intermediate nodes in the chain', () => {+ const root = grantBasic({ delegatable: true, grantedTo: 'A' });+ const child = algebra.delegate(root, 'B');+ algebra.delegate(child, 'C');++ const chain = algebra.getDelegationChain(child.id);++ expect(chain).toHaveLength(2);+ expect(chain[0].id).toBe(root.id);+ expect(chain[1].id).toBe(child.id);+ });+ });++ // ============================================================================+ // Factory Function Tests+ // ============================================================================++ describe('createCapabilityAlgebra', () => {+ it('should create a fresh CapabilityAlgebra instance', () => {+ const instance = createCapabilityAlgebra();+ expect(instance).toBeInstanceOf(CapabilityAlgebra);+ expect(instance.getCapabilities('any')).toEqual([]);+ });+ });++ // ============================================================================+ // Constraint Evaluation Tests+ // ============================================================================++ describe('constraint evaluation via check', () => {+ it('should deny when time-window start is in the future', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{+ type: 'time-window',+ params: { start: Date.now() + 60_000 },+ }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should deny when time-window end is in the past', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{+ type: 'time-window',+ params: { end: Date.now() - 60_000 },+ }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(false);+ });++ it('should allow when within time-window', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{+ type: 'time-window',+ params: { start: Date.now() - 60_000, end: Date.now() + 60_000 },+ }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute');+ expect(result.allowed).toBe(true);+ });++ it('should deny when condition context key does not match expected value', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{+ type: 'condition',+ params: { key: 'environment', value: 'production' },+ }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute', {+ environment: 'development',+ });+ expect(result.allowed).toBe(false);+ });++ it('should allow when condition context matches', () => {+ grantBasic({+ grantedTo: 'agent-1',+ constraints: [{+ type: 'condition',+ params: { key: 'environment', value: 'production' },+ }],+ });++ const result = algebra.check('agent-1', 'tool', 'bash', 'execute', {+ environment: 'production',+ });+ expect(result.allowed).toBe(true);+ });+ });+});