🌊 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 wave 1 guidance primitives - proof, gateway, memory-gate, coherence, hooks, persistence
Clauded43d6e1b22e6
diff --git a/v3/@claude-flow/guidance/package.json b/v3/@claude-flow/guidance/package.jsonindex 4b0b795ac4..d1b1189a59 100644--- a/v3/@claude-flow/guidance/package.json+++ b/v3/@claude-flow/guidance/package.json@@ -22,6 +22,10 @@"types": "./dist/gates.d.ts","import": "./dist/gates.js"},+ "./hooks": {+ "types": "./dist/hooks.d.ts",+ "import": "./dist/hooks.js"+ },"./ledger": {"types": "./dist/ledger.d.ts","import": "./dist/ledger.js"@@ -33,6 +37,14 @@"./headless": {"types": "./dist/headless.d.ts","import": "./dist/headless.js"+ },+ "./persistence": {+ "types": "./dist/persistence.d.ts",+ "import": "./dist/persistence.js"+ },+ "./gateway": {+ "types": "./dist/gateway.d.ts",+ "import": "./dist/gateway.js"}},"files": [diff --git a/v3/@claude-flow/guidance/src/coherence.ts b/v3/@claude-flow/guidance/src/coherence.tsnew file mode 100644index 0000000000..4a02bf72b5--- /dev/null+++ b/v3/@claude-flow/guidance/src/coherence.ts@@ -0,0 +1,534 @@+/**+ * Coherence Scheduler & Economic Governor+ *+ * Detects drift in agent behavior and enforces resource budgets.+ *+ * CoherenceScheduler:+ * - Computes a coherence score from violation rate, rework, and intent drift+ * - Maps scores to privilege levels (full, restricted, read-only, suspended)+ * - Tracks score history and provides human-readable recommendations+ *+ * EconomicGovernor:+ * - Tracks token usage, tool calls, storage, and time+ * - Checks budgets and emits alerts when thresholds are crossed+ * - Estimates remaining capacity and costs+ *+ * @module @claude-flow/guidance/coherence+ */++import type { RunEvent, OptimizationMetrics } from './types.js';++// ============================================================================+// Coherence Types+// ============================================================================++/**+ * Coherence score computed from recent run metrics and events+ */+export interface CoherenceScore {+ /** Overall coherence (0-1, 1 = perfectly coherent) */+ overall: number;+ /** Violation component (0-1, lower violations = higher score) */+ violationComponent: number;+ /** Rework component (0-1, lower rework = higher score) */+ reworkComponent: number;+ /** Drift component (0-1, consistent intents = higher score) */+ driftComponent: number;+ /** Timestamp when this score was computed */+ timestamp: number;+ /** Number of events evaluated in the window */+ windowSize: number;+}++/**+ * Thresholds for privilege level determination+ */+export interface CoherenceThresholds {+ /** Below this overall score the agent is restricted to read-only */+ readOnlyThreshold: number;+ /** Below this overall score warnings are emitted */+ warningThreshold: number;+ /** Above this overall score the agent has full privileges */+ healthyThreshold: number;+ /** Above this overall score privilege escalation is allowed */+ privilegeEscalationThreshold: number;+}++/**+ * Privilege level derived from a coherence score+ */+export type PrivilegeLevel = 'full' | 'restricted' | 'read-only' | 'suspended';++// ============================================================================+// Economic Types+// ============================================================================++/**+ * Budget usage breakdown across all tracked dimensions+ */+export interface BudgetUsage {+ tokens: { used: number; limit: number; percentage: number };+ toolCalls: { used: number; limit: number; percentage: number };+ storage: { usedBytes: number; limitBytes: number; percentage: number };+ time: { usedMs: number; limitMs: number; percentage: number };+ cost: { totalUsd: number; limitUsd: number; percentage: number };+}++// ============================================================================+// Default Configurations+// ============================================================================++const DEFAULT_THRESHOLDS: CoherenceThresholds = {+ readOnlyThreshold: 0.3,+ warningThreshold: 0.5,+ healthyThreshold: 0.7,+ privilegeEscalationThreshold: 0.9,+};++const DEFAULT_ECONOMIC_CONFIG = {+ tokenLimit: 1_000_000,+ toolCallLimit: 10_000,+ storageLimit: 1_073_741_824, // 1 GiB+ timeLimit: 3_600_000, // 1 hour+ costPerToken: 0.000003, // $3 per million tokens+ costPerToolCall: 0.0001,+ costLimit: 10, // $10 USD+};++// ============================================================================+// Coherence Scheduler+// ============================================================================++export interface CoherenceSchedulerConfig {+ thresholds?: Partial<CoherenceThresholds>;+ windowSize?: number;+ checkIntervalMs?: number;+}++/**+ * Computes coherence scores from run metrics and events, determines privilege+ * levels, and provides recommendations when drift is detected.+ */+export class CoherenceScheduler {+ private readonly thresholds: CoherenceThresholds;+ private readonly windowSize: number;+ private readonly checkIntervalMs: number;+ private readonly scoreHistory: CoherenceScore[] = [];+ private static readonly MAX_HISTORY = 100;++ constructor(config: CoherenceSchedulerConfig = {}) {+ this.thresholds = { ...DEFAULT_THRESHOLDS, ...config.thresholds };+ this.windowSize = config.windowSize ?? 20;+ this.checkIntervalMs = config.checkIntervalMs ?? 30_000;+ }++ /**+ * Compute a coherence score from optimization metrics and recent events.+ *+ * Components:+ * - violationComponent: 1 - (violationRate / 10) clamped to [0, 1]+ * - reworkComponent: 1 - (reworkLines / 100) clamped to [0, 1]+ * - driftComponent: intent consistency (fewer unique intents relative to window = higher)+ * - overall: weighted average (0.4 * violation + 0.3 * rework + 0.3 * drift)+ */+ computeCoherence(+ metrics: OptimizationMetrics,+ recentEvents: RunEvent[],+ ): CoherenceScore {+ const window = recentEvents.slice(-this.windowSize);+ const windowLen = window.length;++ // Violation component: fewer violations per 10 tasks = better+ const violationComponent = clamp(1 - metrics.violationRate / 10, 0, 1);++ // Rework component: fewer rework lines on average = better+ const reworkComponent = clamp(1 - metrics.reworkLines / 100, 0, 1);++ // Drift component: consistent intents = better+ // A single unique intent across N events means perfect consistency+ let driftComponent: number;+ if (windowLen === 0) {+ driftComponent = 1; // No events, assume no drift+ } else {+ const uniqueIntents = new Set(window.map(e => e.intent)).size;+ // 1 unique intent / N events = score 1; N unique / N events = score approaches 0+ driftComponent = clamp(1 - (uniqueIntents - 1) / Math.max(windowLen - 1, 1), 0, 1);+ }++ const overall =+ 0.4 * violationComponent ++ 0.3 * reworkComponent ++ 0.3 * driftComponent;++ const score: CoherenceScore = {+ overall,+ violationComponent,+ reworkComponent,+ driftComponent,+ timestamp: Date.now(),+ windowSize: windowLen,+ };++ this.scoreHistory.push(score);+ if (this.scoreHistory.length > CoherenceScheduler.MAX_HISTORY) {+ this.scoreHistory.shift();+ }++ return score;+ }++ /**+ * Determine the privilege level from a coherence score.+ *+ * - overall >= healthyThreshold (0.7): 'full'+ * - overall >= warningThreshold (0.5): 'restricted'+ * - overall >= readOnlyThreshold (0.3): 'read-only'+ * - below readOnlyThreshold: 'suspended'+ */+ getPrivilegeLevel(score: CoherenceScore): PrivilegeLevel {+ if (score.overall >= this.thresholds.healthyThreshold) {+ return 'full';+ }+ if (score.overall >= this.thresholds.warningThreshold) {+ return 'restricted';+ }+ if (score.overall >= this.thresholds.readOnlyThreshold) {+ return 'read-only';+ }+ return 'suspended';+ }++ /**+ * Return the last 100 coherence scores (most recent last).+ */+ getScoreHistory(): CoherenceScore[] {+ return [...this.scoreHistory];+ }++ /**+ * Whether the score indicates healthy coherence.+ */+ isHealthy(score: CoherenceScore): boolean {+ return score.overall >= this.thresholds.healthyThreshold;+ }++ /**+ * Whether the score indicates drift (below warning threshold).+ */+ isDrifting(score: CoherenceScore): boolean {+ return score.overall < this.thresholds.warningThreshold;+ }++ /**+ * Whether the score warrants restricting agent actions.+ */+ shouldRestrict(score: CoherenceScore): boolean {+ return score.overall < this.thresholds.warningThreshold;+ }++ /**+ * Produce a human-readable recommendation based on the coherence score.+ */+ getRecommendation(score: CoherenceScore): string {+ const level = this.getPrivilegeLevel(score);+ const parts: string[] = [];++ switch (level) {+ case 'full':+ parts.push(+ `Coherence is healthy at ${(score.overall * 100).toFixed(1)}%.`,+ );+ if (score.overall >= this.thresholds.privilegeEscalationThreshold) {+ parts.push('Privilege escalation is permitted.');+ }+ break;++ case 'restricted':+ parts.push(+ `Coherence is degraded at ${(score.overall * 100).toFixed(1)}%. Agent privileges are restricted.`,+ );+ break;++ case 'read-only':+ parts.push(+ `Coherence is critically low at ${(score.overall * 100).toFixed(1)}%. Agent is limited to read-only operations.`,+ );+ break;++ case 'suspended':+ parts.push(+ `Coherence has collapsed to ${(score.overall * 100).toFixed(1)}%. Agent operations are suspended.`,+ );+ break;+ }++ // Add component-specific advice+ if (score.violationComponent < 0.5) {+ parts.push(+ `High violation rate detected (component: ${(score.violationComponent * 100).toFixed(0)}%). Review and strengthen enforcement gates.`,+ );+ }+ if (score.reworkComponent < 0.5) {+ parts.push(+ `Excessive rework detected (component: ${(score.reworkComponent * 100).toFixed(0)}%). Consider more prescriptive guidance or smaller task scopes.`,+ );+ }+ if (score.driftComponent < 0.5) {+ parts.push(+ `Intent drift detected (component: ${(score.driftComponent * 100).toFixed(0)}%). Agent is switching between too many task types. Focus on a single objective.`,+ );+ }++ return parts.join(' ');+ }++ /**+ * Get the configured check interval in milliseconds.+ */+ get interval(): number {+ return this.checkIntervalMs;+ }++ /**+ * Get the configured thresholds.+ */+ getThresholds(): CoherenceThresholds {+ return { ...this.thresholds };+ }+}++// ============================================================================+// Economic Governor+// ============================================================================++export interface EconomicGovernorConfig {+ tokenLimit?: number;+ toolCallLimit?: number;+ storageLimit?: number;+ timeLimit?: number;+ costPerToken?: number;+ costPerToolCall?: number;+ costLimit?: number;+}++interface ToolCallRecord {+ toolName: string;+ durationMs: number;+ timestamp: number;+}++/**+ * Tracks resource consumption (tokens, tool calls, storage, time, cost)+ * and enforces budget limits with alerts.+ */+export class EconomicGovernor {+ private readonly config: Required<EconomicGovernorConfig>;+ private tokensUsed = 0;+ private toolCallsUsed = 0;+ private storageUsed = 0;+ private readonly toolCallLog: ToolCallRecord[] = [];+ private readonly startTime: number;+ private periodStart: number;++ private static readonly ALERT_THRESHOLDS = [0.75, 0.9, 0.95, 1.0];++ constructor(config: EconomicGovernorConfig = {}) {+ this.config = {+ tokenLimit: config.tokenLimit ?? DEFAULT_ECONOMIC_CONFIG.tokenLimit,+ toolCallLimit: config.toolCallLimit ?? DEFAULT_ECONOMIC_CONFIG.toolCallLimit,+ storageLimit: config.storageLimit ?? DEFAULT_ECONOMIC_CONFIG.storageLimit,+ timeLimit: config.timeLimit ?? DEFAULT_ECONOMIC_CONFIG.timeLimit,+ costPerToken: config.costPerToken ?? DEFAULT_ECONOMIC_CONFIG.costPerToken,+ costPerToolCall: config.costPerToolCall ?? DEFAULT_ECONOMIC_CONFIG.costPerToolCall,+ costLimit: config.costLimit ?? DEFAULT_ECONOMIC_CONFIG.costLimit,+ };++ this.startTime = Date.now();+ this.periodStart = Date.now();+ }++ /**+ * Record token consumption.+ */+ recordTokenUsage(count: number): void {+ this.tokensUsed += count;+ }++ /**+ * Record a tool call with its name and duration.+ */+ recordToolCall(toolName: string, durationMs: number): void {+ this.toolCallsUsed++;+ this.toolCallLog.push({+ toolName,+ durationMs,+ timestamp: Date.now(),+ });+ }++ /**+ * Record storage usage in bytes.+ */+ recordStorageUsage(bytes: number): void {+ this.storageUsed += bytes;+ }++ /**+ * Check whether current usage is within budget limits.+ * Returns a summary with alerts for any limits that are near or exceeded.+ */+ checkBudget(): { withinBudget: boolean; usage: BudgetUsage; alerts: string[] } {+ const usage = this.getUsageSummary();+ const alerts: string[] = [];++ // Check each dimension against alert thresholds+ const dimensions: Array<{ name: string; percentage: number }> = [+ { name: 'tokens', percentage: usage.tokens.percentage },+ { name: 'tool calls', percentage: usage.toolCalls.percentage },+ { name: 'storage', percentage: usage.storage.percentage },+ { name: 'time', percentage: usage.time.percentage },+ { name: 'cost', percentage: usage.cost.percentage },+ ];++ let withinBudget = true;++ for (const dim of dimensions) {+ if (dim.percentage >= 100) {+ alerts.push(`BUDGET EXCEEDED: ${dim.name} at ${dim.percentage.toFixed(1)}% of limit`);+ withinBudget = false;+ } else if (dim.percentage >= 95) {+ alerts.push(`CRITICAL: ${dim.name} at ${dim.percentage.toFixed(1)}% of limit`);+ } else if (dim.percentage >= 90) {+ alerts.push(`WARNING: ${dim.name} at ${dim.percentage.toFixed(1)}% of limit`);+ } else if (dim.percentage >= 75) {+ alerts.push(`NOTICE: ${dim.name} at ${dim.percentage.toFixed(1)}% of limit`);+ }+ }++ return { withinBudget, usage, alerts };+ }++ /**+ * Get a full usage summary across all tracked dimensions.+ */+ getUsageSummary(): BudgetUsage {+ const elapsedMs = Date.now() - this.periodStart;+ const costEstimate = this.getCostEstimate();++ return {+ tokens: {+ used: this.tokensUsed,+ limit: this.config.tokenLimit,+ percentage: safePercentage(this.tokensUsed, this.config.tokenLimit),+ },+ toolCalls: {+ used: this.toolCallsUsed,+ limit: this.config.toolCallLimit,+ percentage: safePercentage(this.toolCallsUsed, this.config.toolCallLimit),+ },+ storage: {+ usedBytes: this.storageUsed,+ limitBytes: this.config.storageLimit,+ percentage: safePercentage(this.storageUsed, this.config.storageLimit),+ },+ time: {+ usedMs: elapsedMs,+ limitMs: this.config.timeLimit,+ percentage: safePercentage(elapsedMs, this.config.timeLimit),+ },+ cost: {+ totalUsd: costEstimate.totalCost,+ limitUsd: this.config.costLimit,+ percentage: safePercentage(costEstimate.totalCost, this.config.costLimit),+ },+ };+ }++ /**+ * Reset all counters for a new billing/tracking period.+ */+ resetPeriod(): void {+ this.tokensUsed = 0;+ this.toolCallsUsed = 0;+ this.storageUsed = 0;+ this.toolCallLog.length = 0;+ this.periodStart = Date.now();+ }++ /**+ * Estimate remaining capacity before hitting limits.+ */+ estimateRemainingCapacity(): {+ tokensRemaining: number;+ callsRemaining: number;+ timeRemainingMs: number;+ } {+ const elapsedMs = Date.now() - this.periodStart;++ return {+ tokensRemaining: Math.max(0, this.config.tokenLimit - this.tokensUsed),+ callsRemaining: Math.max(0, this.config.toolCallLimit - this.toolCallsUsed),+ timeRemainingMs: Math.max(0, this.config.timeLimit - elapsedMs),+ };+ }++ /**+ * Compute a cost estimate with a breakdown by category.+ */+ getCostEstimate(): { totalCost: number; breakdown: Record<string, number> } {+ const tokenCost = this.tokensUsed * this.config.costPerToken;+ const toolCallCost = this.toolCallsUsed * this.config.costPerToolCall;++ const breakdown: Record<string, number> = {+ tokens: tokenCost,+ toolCalls: toolCallCost,+ };++ return {+ totalCost: tokenCost + toolCallCost,+ breakdown,+ };+ }++ /**+ * Get the raw tool call log.+ */+ getToolCallLog(): ReadonlyArray<ToolCallRecord> {+ return this.toolCallLog;+ }+}++// ============================================================================+// Factory Functions+// ============================================================================++/**+ * Create a CoherenceScheduler with optional configuration.+ */+export function createCoherenceScheduler(+ config?: CoherenceSchedulerConfig,+): CoherenceScheduler {+ return new CoherenceScheduler(config);+}++/**+ * Create an EconomicGovernor with optional configuration.+ */+export function createEconomicGovernor(+ config?: EconomicGovernorConfig,+): EconomicGovernor {+ return new EconomicGovernor(config);+}++// ============================================================================+// Helpers+// ============================================================================++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++function safePercentage(used: number, limit: number): number {+ if (limit <= 0) return 0;+ return (used / limit) * 100;+}diff --git a/v3/@claude-flow/guidance/src/gateway.ts b/v3/@claude-flow/guidance/src/gateway.tsnew file mode 100644index 0000000000..6032c702e7--- /dev/null+++ b/v3/@claude-flow/guidance/src/gateway.ts@@ -0,0 +1,607 @@+/**+ * Deterministic Tool Gateway+ *+ * Extends EnforcementGates with idempotency, schema validation,+ * and budget metering. Every tool call passes through a deterministic+ * pipeline: idempotency check -> schema validation -> budget check ->+ * enforcement gates -> allow/deny.+ *+ * @module @claude-flow/guidance/gateway+ */++import { createHash } from 'node:crypto';+import { EnforcementGates } from './gates.js';+import type { GateConfig } from './types.js';++// ============================================================================+// Types+// ============================================================================++/**+ * Schema definition for a tool's parameters+ */+export interface ToolSchema {+ /** Tool name this schema applies to */+ toolName: string;+ /** Parameters that must be present */+ requiredParams: string[];+ /** Parameters that may be present */+ optionalParams: string[];+ /** Expected type for each parameter */+ paramTypes: Record<string, 'string' | 'number' | 'boolean' | 'object' | 'array'>;+ /** Maximum total serialized size of all parameters in bytes */+ maxParamSize: number;+ /** Optional whitelist of allowed values per parameter */+ allowedValues?: Record<string, unknown[]>;+}++/**+ * Multi-dimensional budget tracking+ */+export interface Budget {+ tokenBudget: { used: number; limit: number };+ toolCallBudget: { used: number; limit: number };+ storageBudget: { usedBytes: number; limitBytes: number };+ timeBudget: { usedMs: number; limitMs: number };+ costBudget: { usedUsd: number; limitUsd: number };+}++/**+ * Record of a previous tool call for idempotency+ */+export interface IdempotencyRecord {+ /** SHA-256 of tool name + sorted params */+ key: string;+ /** Tool that was called */+ toolName: string;+ /** Hash of the parameters */+ paramsHash: string;+ /** Cached result from the call */+ result: unknown;+ /** When the call was recorded */+ timestamp: number;+ /** Time-to-live in milliseconds */+ ttlMs: number;+}++/**+ * Decision returned by the gateway for each tool call evaluation+ */+export interface GatewayDecision {+ /** Whether the call is allowed */+ allowed: boolean;+ /** Human-readable reason for the decision */+ reason: string;+ /** Which gate produced the decision (or 'none' if allowed) */+ gate: string;+ /** Evidence of what was checked */+ evidence: Record<string, unknown>;+ /** Whether an idempotency cache hit occurred */+ idempotencyHit: boolean;+ /** Cached result if idempotency hit */+ cachedResult?: unknown;+ /** Remaining budget after this decision */+ budgetRemaining?: Budget;+}++// ============================================================================+// Default Budget+// ============================================================================++const DEFAULT_BUDGET: Budget = {+ tokenBudget: { used: 0, limit: Infinity },+ toolCallBudget: { used: 0, limit: Infinity },+ storageBudget: { usedBytes: 0, limitBytes: Infinity },+ timeBudget: { usedMs: 0, limitMs: Infinity },+ costBudget: { usedUsd: 0, limitUsd: Infinity },+};++// ============================================================================+// Gateway Configuration+// ============================================================================++export interface ToolGatewayConfig {+ /** Tool schemas for validation */+ schemas?: ToolSchema[];+ /** Budget limits (partial; defaults to Infinity for unset dimensions) */+ budget?: Partial<Budget>;+ /** Default TTL for idempotency records in milliseconds */+ idempotencyTtlMs?: number;+ /** If true, evidence must be non-empty for allow decisions */+ requireEvidence?: boolean;+ /** Gate configuration passed through to EnforcementGates */+ gateConfig?: Partial<GateConfig>;+}++// ============================================================================+// Deterministic Tool Gateway+// ============================================================================++export class DeterministicToolGateway {+ private readonly gates: EnforcementGates;+ private readonly schemas: Map<string, ToolSchema>;+ private budget: Budget;+ private readonly idempotencyTtlMs: number;+ private readonly requireEvidence: boolean;+ private readonly idempotencyCache: Map<string, IdempotencyRecord> = new Map();++ constructor(config: ToolGatewayConfig = {}) {+ this.gates = new EnforcementGates(config.gateConfig);++ // Index schemas by tool name+ this.schemas = new Map();+ if (config.schemas) {+ for (const schema of config.schemas) {+ this.schemas.set(schema.toolName, schema);+ }+ }++ // Merge partial budget with defaults+ this.budget = this.mergeBudget(config.budget);+ this.idempotencyTtlMs = config.idempotencyTtlMs ?? 300_000; // 5 minutes default+ this.requireEvidence = config.requireEvidence ?? false;+ }++ // =========================================================================+ // Public API+ // =========================================================================++ /**+ * Evaluate whether a tool call should be allowed.+ *+ * Pipeline:+ * 1. Check idempotency cache+ * 2. Validate params against schema+ * 3. Check budget+ * 4. Run EnforcementGates checks+ * 5. Return decision with remaining budget+ */+ evaluate(+ toolName: string,+ params: Record<string, unknown>,+ context?: Record<string, unknown>,+ ): GatewayDecision {+ const evidence: Record<string, unknown> = {};++ // Step 1: Idempotency check+ this.cleanExpiredIdempotency();+ const idempotencyKey = this.getIdempotencyKey(toolName, params);+ const cached = this.idempotencyCache.get(idempotencyKey);++ if (cached) {+ return {+ allowed: true,+ reason: 'Idempotency cache hit; returning cached result',+ gate: 'idempotency',+ evidence: { idempotencyKey, cachedAt: cached.timestamp },+ idempotencyHit: true,+ cachedResult: cached.result,+ budgetRemaining: this.cloneBudget(),+ };+ }++ evidence.idempotencyKey = idempotencyKey;+ evidence.idempotencyHit = false;++ // Step 2: Schema validation+ const schemaResult = this.validateSchema(toolName, params);+ evidence.schemaValidation = schemaResult;++ if (!schemaResult.valid) {+ return {+ allowed: false,+ reason: `Schema validation failed: ${schemaResult.errors.join('; ')}`,+ gate: 'schema-validation',+ evidence,+ idempotencyHit: false,+ };+ }++ // Step 3: Budget check+ const budgetStatus = this.checkBudget();+ evidence.budgetStatus = budgetStatus;++ if (!budgetStatus.withinBudget) {+ const exceeded = this.findExceededBudgets();+ return {+ allowed: false,+ reason: `Budget exceeded: ${exceeded.join(', ')}`,+ gate: 'budget',+ evidence,+ idempotencyHit: false,+ budgetRemaining: this.cloneBudget(),+ };+ }++ // Step 4: EnforcementGates checks+ const gateResults = this.gates.evaluateToolUse(toolName, params);+ evidence.gateResults = gateResults;++ if (gateResults.length > 0) {+ const aggregated = this.gates.aggregateDecision(gateResults);++ if (aggregated === 'block') {+ const blockResult = gateResults.find(r => r.decision === 'block')!;+ return {+ allowed: false,+ reason: blockResult.reason,+ gate: `enforcement:${blockResult.gateName}`,+ evidence,+ idempotencyHit: false,+ budgetRemaining: this.cloneBudget(),+ };+ }++ if (aggregated === 'require-confirmation') {+ const confirmResult = gateResults.find(r => r.decision === 'require-confirmation')!;+ return {+ allowed: false,+ reason: confirmResult.reason,+ gate: `enforcement:${confirmResult.gateName}`,+ evidence,+ idempotencyHit: false,+ budgetRemaining: this.cloneBudget(),+ };+ }++ // 'warn' still allows, but note it in evidence+ evidence.warnings = gateResults+ .filter(r => r.decision === 'warn')+ .map(r => r.reason);+ }++ // Also run command-level checks if context provides a command string+ if (context?.command && typeof context.command === 'string') {+ const commandResults = this.gates.evaluateCommand(context.command);+ evidence.commandGateResults = commandResults;++ if (commandResults.length > 0) {+ const aggregated = this.gates.aggregateDecision(commandResults);+ if (aggregated === 'block' || aggregated === 'require-confirmation') {+ const worst = commandResults.find(+ r => r.decision === aggregated,+ )!;+ return {+ allowed: false,+ reason: worst.reason,+ gate: `enforcement:${worst.gateName}`,+ evidence,+ idempotencyHit: false,+ budgetRemaining: this.cloneBudget(),+ };+ }+ }+ }++ // Step 5: Allow+ return {+ allowed: true,+ reason: 'All gates passed',+ gate: 'none',+ evidence,+ idempotencyHit: false,+ budgetRemaining: this.cloneBudget(),+ };+ }++ /**+ * Record a completed tool call.+ * Updates budgets and stores the result in the idempotency cache.+ */+ recordCall(+ toolName: string,+ params: Record<string, unknown>,+ result: unknown,+ durationMs: number,+ tokenCount?: number,+ ): void {+ // Update budgets+ this.budget.toolCallBudget.used += 1;+ this.budget.timeBudget.usedMs += durationMs;++ if (tokenCount !== undefined) {+ this.budget.tokenBudget.used += tokenCount;+ }++ // Estimate storage from serialized result+ const serialized = JSON.stringify(result) ?? '';+ this.budget.storageBudget.usedBytes += Buffer.byteLength(serialized, 'utf-8');++ // Estimate cost: simple heuristic based on tokens+ if (tokenCount !== undefined) {+ // Rough estimate: $0.003 per 1K tokens (configurable in production)+ this.budget.costBudget.usedUsd += (tokenCount / 1000) * 0.003;+ }++ // Store in idempotency cache+ const key = this.getIdempotencyKey(toolName, params);+ const paramsHash = this.computeParamsHash(params);++ this.idempotencyCache.set(key, {+ key,+ toolName,+ paramsHash,+ result,+ timestamp: Date.now(),+ ttlMs: this.idempotencyTtlMs,+ });+ }++ /**+ * Validate tool parameters against the registered schema.+ * Returns valid:true if no schema is registered for the tool.+ */+ validateSchema(+ toolName: string,+ params: Record<string, unknown>,+ ): { valid: boolean; errors: string[] } {+ const schema = this.schemas.get(toolName);++ if (!schema) {+ // No schema registered; pass through+ return { valid: true, errors: [] };+ }++ const errors: string[] = [];++ // Check required params+ for (const required of schema.requiredParams) {+ if (!(required in params) || params[required] === undefined) {+ errors.push(`Missing required parameter: "${required}"`);+ }+ }++ // Check for unknown params+ const knownParams = new Set([...schema.requiredParams, ...schema.optionalParams]);+ for (const key of Object.keys(params)) {+ if (!knownParams.has(key)) {+ errors.push(`Unknown parameter: "${key}"`);+ }+ }++ // Check param types+ for (const [key, expectedType] of Object.entries(schema.paramTypes)) {+ if (!(key in params) || params[key] === undefined) continue;++ const value = params[key];+ const actualType = this.getParamType(value);++ if (actualType !== expectedType) {+ errors.push(+ `Parameter "${key}" expected type "${expectedType}" but got "${actualType}"`,+ );+ }+ }++ // Check param size+ const serialized = JSON.stringify(params);+ const sizeBytes = Buffer.byteLength(serialized, 'utf-8');+ if (sizeBytes > schema.maxParamSize) {+ errors.push(+ `Parameters size ${sizeBytes} bytes exceeds limit of ${schema.maxParamSize} bytes`,+ );+ }++ // Check allowed values+ if (schema.allowedValues) {+ for (const [key, allowed] of Object.entries(schema.allowedValues)) {+ if (!(key in params) || params[key] === undefined) continue;++ const value = params[key];+ const isAllowed = allowed.some(+ a => JSON.stringify(a) === JSON.stringify(value),+ );++ if (!isAllowed) {+ errors.push(+ `Parameter "${key}" value ${JSON.stringify(value)} is not in the allowed values list`,+ );+ }+ }+ }++ return { valid: errors.length === 0, errors };+ }++ /**+ * Check whether all budget dimensions are within limits.+ */+ checkBudget(): { withinBudget: boolean; budgetStatus: Budget } {+ const b = this.budget;++ const withinBudget =+ b.tokenBudget.used <= b.tokenBudget.limit &&+ b.toolCallBudget.used <= b.toolCallBudget.limit &&+ b.storageBudget.usedBytes <= b.storageBudget.limitBytes &&+ b.timeBudget.usedMs <= b.timeBudget.limitMs &&+ b.costBudget.usedUsd <= b.costBudget.limitUsd;++ return { withinBudget, budgetStatus: this.cloneBudget() };+ }++ /**+ * Compute a deterministic idempotency key from tool name and params.+ * Uses SHA-256 of `toolName:sortedParamsJSON`.+ */+ getIdempotencyKey(toolName: string, params: Record<string, unknown>): string {+ return this.computeIdempotencyKey(toolName, params);+ }++ /**+ * Reset all budget counters to zero.+ */+ resetBudget(): void {+ this.budget.tokenBudget.used = 0;+ this.budget.toolCallBudget.used = 0;+ this.budget.storageBudget.usedBytes = 0;+ this.budget.timeBudget.usedMs = 0;+ this.budget.costBudget.usedUsd = 0;+ }++ /**+ * Get a snapshot of the current budget.+ */+ getBudget(): Budget {+ return this.cloneBudget();+ }++ /**+ * Get all idempotency records (including expired ones not yet cleaned).+ */+ getCallHistory(): IdempotencyRecord[] {+ return Array.from(this.idempotencyCache.values());+ }++ /**+ * Access the underlying EnforcementGates instance.+ */+ getGates(): EnforcementGates {+ return this.gates;+ }++ // =========================================================================+ // Private helpers+ // =========================================================================++ /**+ * Remove expired idempotency records.+ */+ private cleanExpiredIdempotency(): void {+ const now = Date.now();+ for (const [key, record] of this.idempotencyCache) {+ if (now - record.timestamp > record.ttlMs) {+ this.idempotencyCache.delete(key);+ }+ }+ }++ /**+ * Compute a deterministic SHA-256 key from tool name and sorted params.+ */+ private computeIdempotencyKey(+ toolName: string,+ params: Record<string, unknown>,+ ): string {+ const sortedParams = this.sortObject(params);+ const input = `${toolName}:${JSON.stringify(sortedParams)}`;+ return createHash('sha256').update(input).digest('hex');+ }++ /**+ * Compute a SHA-256 hash of params only (for the IdempotencyRecord).+ */+ private computeParamsHash(params: Record<string, unknown>): string {+ const sortedParams = this.sortObject(params);+ return createHash('sha256').update(JSON.stringify(sortedParams)).digest('hex');+ }++ /**+ * Recursively sort object keys for deterministic serialization.+ */+ private sortObject(obj: unknown): unknown {+ if (obj === null || obj === undefined) return obj;+ if (Array.isArray(obj)) return obj.map(item => this.sortObject(item));+ if (typeof obj === 'object') {+ const sorted: Record<string, unknown> = {};+ for (const key of Object.keys(obj as Record<string, unknown>).sort()) {+ sorted[key] = this.sortObject((obj as Record<string, unknown>)[key]);+ }+ return sorted;+ }+ return obj;+ }++ /**+ * Determine the type string for a parameter value.+ */+ private getParamType(value: unknown): string {+ if (Array.isArray(value)) return 'array';+ if (value === null) return 'object';+ return typeof value;+ }++ /**+ * Create a deep clone of the current budget.+ */+ private cloneBudget(): Budget {+ return {+ tokenBudget: { ...this.budget.tokenBudget },+ toolCallBudget: { ...this.budget.toolCallBudget },+ storageBudget: { ...this.budget.storageBudget },+ timeBudget: { ...this.budget.timeBudget },+ costBudget: { ...this.budget.costBudget },+ };+ }++ /**+ * Merge a partial budget config with defaults.+ */+ private mergeBudget(partial?: Partial<Budget>): Budget {+ if (!partial) return this.cloneDefaultBudget();++ return {+ tokenBudget: partial.tokenBudget+ ? { ...DEFAULT_BUDGET.tokenBudget, ...partial.tokenBudget }+ : { ...DEFAULT_BUDGET.tokenBudget },+ toolCallBudget: partial.toolCallBudget+ ? { ...DEFAULT_BUDGET.toolCallBudget, ...partial.toolCallBudget }+ : { ...DEFAULT_BUDGET.toolCallBudget },+ storageBudget: partial.storageBudget+ ? { ...DEFAULT_BUDGET.storageBudget, ...partial.storageBudget }+ : { ...DEFAULT_BUDGET.storageBudget },+ timeBudget: partial.timeBudget+ ? { ...DEFAULT_BUDGET.timeBudget, ...partial.timeBudget }+ : { ...DEFAULT_BUDGET.timeBudget },+ costBudget: partial.costBudget+ ? { ...DEFAULT_BUDGET.costBudget, ...partial.costBudget }+ : { ...DEFAULT_BUDGET.costBudget },+ };+ }++ private cloneDefaultBudget(): Budget {+ return {+ tokenBudget: { ...DEFAULT_BUDGET.tokenBudget },+ toolCallBudget: { ...DEFAULT_BUDGET.toolCallBudget },+ storageBudget: { ...DEFAULT_BUDGET.storageBudget },+ timeBudget: { ...DEFAULT_BUDGET.timeBudget },+ costBudget: { ...DEFAULT_BUDGET.costBudget },+ };+ }++ /**+ * Find which budget dimensions have been exceeded.+ */+ private findExceededBudgets(): string[] {+ const exceeded: string[] = [];+ const b = this.budget;++ if (b.tokenBudget.used > b.tokenBudget.limit) {+ exceeded.push(`tokens (${b.tokenBudget.used}/${b.tokenBudget.limit})`);+ }+ if (b.toolCallBudget.used > b.toolCallBudget.limit) {+ exceeded.push(`tool calls (${b.toolCallBudget.used}/${b.toolCallBudget.limit})`);+ }+ if (b.storageBudget.usedBytes > b.storageBudget.limitBytes) {+ exceeded.push(`storage (${b.storageBudget.usedBytes}/${b.storageBudget.limitBytes} bytes)`);+ }+ if (b.timeBudget.usedMs > b.timeBudget.limitMs) {+ exceeded.push(`time (${b.timeBudget.usedMs}/${b.timeBudget.limitMs} ms)`);+ }+ if (b.costBudget.usedUsd > b.costBudget.limitUsd) {+ exceeded.push(`cost ($${b.costBudget.usedUsd.toFixed(4)}/$${b.costBudget.limitUsd.toFixed(4)})`);+ }++ return exceeded;+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create a DeterministicToolGateway instance+ */+export function createToolGateway(config?: ToolGatewayConfig): DeterministicToolGateway {+ return new DeterministicToolGateway(config);+}diff --git a/v3/@claude-flow/guidance/src/hooks.ts b/v3/@claude-flow/guidance/src/hooks.tsnew file mode 100644index 0000000000..323a8f017e--- /dev/null+++ b/v3/@claude-flow/guidance/src/hooks.ts@@ -0,0 +1,465 @@+/**+ * Guidance Hook Integration Layer+ *+ * Wires the EnforcementGates and ShardRetriever into the Claude Flow V3+ * hook lifecycle. Each guidance concern is registered as a hook that+ * participates in the standard HookRegistry event flow.+ *+ * Hook mappings:+ * PreCommand -> EnforcementGates.evaluateCommand() (destructive ops + secrets)+ * PreToolUse -> EnforcementGates.evaluateToolUse() (tool allowlist + secrets)+ * PreEdit -> EnforcementGates.evaluateEdit() (diff size + secrets)+ * PreTask -> ShardRetriever.retrieve() (inject relevant shards)+ * PostTask -> RunLedger.finalizeEvent() (record run completion)+ *+ * @module @claude-flow/guidance/hooks+ */++import type {+ HookContext,+ HookResult,+ HookRegistrationOptions,+} from '@claude-flow/hooks';++import {+ HookEvent,+ HookPriority,+} from '@claude-flow/hooks';++import type { HookRegistry } from '@claude-flow/hooks';++import type { EnforcementGates } from './gates.js';+import type { ShardRetriever } from './retriever.js';+import type { RunLedger } from './ledger.js';+import type {+ GateResult,+ GateDecision,+ RunEvent,+ RetrievalResult,+} from './types.js';++// ============================================================================+// Gate-Result -> Hook-Result Mapping+// ============================================================================++/**+ * Convert an array of GateResults into a single HookResult.+ *+ * Severity ordering: block > require-confirmation > warn > allow.+ * The most restrictive decision drives the hook outcome.+ */+function gateResultsToHookResult(gateResults: GateResult[]): HookResult {+ if (gateResults.length === 0) {+ return { success: true };+ }++ const severityOrder: Record<GateDecision, number> = {+ block: 3,+ 'require-confirmation': 2,+ warn: 1,+ allow: 0,+ };++ // Sort by severity descending to find the most restrictive+ const sorted = [...gateResults].sort(+ (a, b) => severityOrder[b.decision] - severityOrder[a.decision],+ );++ const worst = sorted[0];++ // Collect all warnings and reasons+ const allWarnings: string[] = [];+ const allReasons: string[] = [];++ for (const result of gateResults) {+ allReasons.push(`[${result.gateName}] ${result.reason}`);+ if (result.remediation) {+ allWarnings.push(`[${result.gateName}] ${result.remediation}`);+ }+ }++ switch (worst.decision) {+ case 'block':+ return {+ success: false,+ abort: true,+ error: allReasons.join(' | '),+ message: allReasons.join('\n'),+ warnings: allWarnings.length > 0 ? allWarnings : undefined,+ data: {+ gateDecision: 'block',+ gateResults: gateResults.map(r => ({+ gate: r.gateName,+ decision: r.decision,+ reason: r.reason,+ })),+ },+ };++ case 'require-confirmation':+ return {+ success: false,+ abort: true,+ message: allReasons.join('\n'),+ warnings: allWarnings.length > 0 ? allWarnings : undefined,+ data: {+ gateDecision: 'require-confirmation',+ gateResults: gateResults.map(r => ({+ gate: r.gateName,+ decision: r.decision,+ reason: r.reason,+ })),+ },+ };++ case 'warn':+ return {+ success: true,+ message: allReasons.join('\n'),+ warnings: allWarnings.length > 0 ? allWarnings : allReasons,+ data: {+ gateDecision: 'warn',+ gateResults: gateResults.map(r => ({+ gate: r.gateName,+ decision: r.decision,+ reason: r.reason,+ })),+ },+ };++ default:+ return { success: true };+ }+}++// ============================================================================+// Guidance Hook Provider+// ============================================================================++/**+ * Provides guidance enforcement hooks for the V3 hook system.+ *+ * Registers hooks on a HookRegistry that wire each lifecycle event+ * (PreCommand, PreToolUse, PreEdit, PreTask, PostTask) to the+ * appropriate guidance subsystem (gates, retriever, ledger).+ */+export class GuidanceHookProvider {+ private gates: EnforcementGates;+ private retriever: ShardRetriever;+ private ledger: RunLedger;++ /** IDs of hooks registered by this provider, for cleanup */+ private hookIds: string[] = [];++ /** Active run events keyed by task ID, for PostTask finalization */+ private activeRuns = new Map<string, RunEvent>();++ constructor(+ gates: EnforcementGates,+ retriever: ShardRetriever,+ ledger: RunLedger,+ ) {+ this.gates = gates;+ this.retriever = retriever;+ this.ledger = ledger;+ }++ /**+ * Register all guidance hooks on the given registry.+ *+ * Returns the array of generated hook IDs for tracking.+ */+ registerAll(registry: HookRegistry): string[] {+ this.hookIds = [];++ // 1. PreCommand -> gate enforcement (Critical priority)+ this.hookIds.push(+ registry.register(+ HookEvent.PreCommand,+ (ctx: HookContext) => this.handlePreCommand(ctx),+ HookPriority.Critical,+ {+ name: 'guidance-gate-pre-command',+ description: 'Evaluates commands for destructive ops and secrets',+ },+ ),+ );++ // 2. PreToolUse -> gate enforcement (Critical priority)+ this.hookIds.push(+ registry.register(+ HookEvent.PreToolUse,+ (ctx: HookContext) => this.handlePreToolUse(ctx),+ HookPriority.Critical,+ {+ name: 'guidance-gate-pre-tool-use',+ description: 'Evaluates tool usage against allowlist and checks for secrets',+ },+ ),+ );++ // 3. PreEdit -> gate enforcement (High priority)+ this.hookIds.push(+ registry.register(+ HookEvent.PreEdit,+ (ctx: HookContext) => this.handlePreEdit(ctx),+ HookPriority.High,+ {+ name: 'guidance-gate-pre-edit',+ description: 'Evaluates file edits for diff size and secrets',+ },+ ),+ );++ // 4. PreTask -> shard retrieval (Normal priority)+ this.hookIds.push(+ registry.register(+ HookEvent.PreTask,+ (ctx: HookContext) => this.handlePreTask(ctx),+ HookPriority.Normal,+ {+ name: 'guidance-retriever-pre-task',+ description: 'Retrieves relevant guidance shards at task start',+ },+ ),+ );++ // 5. PostTask -> ledger finalization (Normal priority)+ this.hookIds.push(+ registry.register(+ HookEvent.PostTask,+ (ctx: HookContext) => this.handlePostTask(ctx),+ HookPriority.Normal,+ {+ name: 'guidance-ledger-post-task',+ description: 'Finalizes the run event in the ledger on task completion',+ },+ ),+ );++ return [...this.hookIds];+ }++ /**+ * Unregister all hooks previously registered by this provider.+ */+ unregisterAll(registry: HookRegistry): void {+ for (const id of this.hookIds) {+ registry.unregister(id);+ }+ this.hookIds = [];+ }++ /**+ * Get the IDs of all registered hooks.+ */+ getHookIds(): string[] {+ return [...this.hookIds];+ }++ /**+ * Get the active run event for a given task ID (if any).+ */+ getActiveRun(taskId: string): RunEvent | undefined {+ return this.activeRuns.get(taskId);+ }++ // ==========================================================================+ // Hook Handlers+ // ==========================================================================++ /**+ * PreCommand handler: evaluate command through destructive ops and secrets gates.+ */+ private handlePreCommand(ctx: HookContext): HookResult {+ const command = ctx.command?.raw;+ if (!command) {+ return { success: true };+ }++ const gateResults = this.gates.evaluateCommand(command);+ return gateResultsToHookResult(gateResults);+ }++ /**+ * PreToolUse handler: evaluate tool usage against allowlist and check params for secrets.+ */+ private handlePreToolUse(ctx: HookContext): HookResult {+ const toolName = ctx.tool?.name;+ if (!toolName) {+ return { success: true };+ }++ const params = ctx.tool?.parameters ?? {};+ const gateResults = this.gates.evaluateToolUse(toolName, params);+ return gateResultsToHookResult(gateResults);+ }++ /**+ * PreEdit handler: evaluate file edit for diff size and secrets.+ *+ * Extracts the file path from context. The content to scan comes from+ * metadata.content or is synthesized from available context. The diff+ * line count defaults to metadata.diffLines or 0.+ */+ private handlePreEdit(ctx: HookContext): HookResult {+ const filePath = ctx.file?.path;+ if (!filePath) {+ return { success: true };+ }++ const content = (ctx.metadata?.content as string) ?? '';+ const diffLines = (ctx.metadata?.diffLines as number) ?? 0;++ const gateResults = this.gates.evaluateEdit(filePath, content, diffLines);+ return gateResultsToHookResult(gateResults);+ }++ /**+ * PreTask handler: classify intent and retrieve relevant guidance shards.+ *+ * Creates a new RunEvent in the active runs map for PostTask finalization.+ * Returns the retrieved policy text and shards as hook data.+ */+ private async handlePreTask(ctx: HookContext): Promise<HookResult> {+ const taskId = ctx.task?.id;+ const taskDescription = ctx.task?.description;++ if (!taskId || !taskDescription) {+ return { success: true };+ }++ try {+ // Classify intent+ const { intent, confidence } = this.retriever.classifyIntent(taskDescription);++ // Retrieve relevant shards+ let retrievalResult: RetrievalResult | null = null;+ try {+ retrievalResult = await this.retriever.retrieve({+ taskDescription,+ intent,+ });+ } catch {+ // Retriever may not have a loaded bundle -- degrade gracefully+ }++ // Create a run event for ledger tracking+ const guidanceHash = retrievalResult?.constitution?.hash ?? 'unknown';+ const runEvent = this.ledger.createEvent(taskId, intent, guidanceHash);++ if (retrievalResult) {+ runEvent.retrievedRuleIds = retrievalResult.shards.map(+ s => s.shard.rule.id,+ );+ }++ this.activeRuns.set(taskId, runEvent);++ return {+ success: true,+ message: retrievalResult+ ? `Retrieved ${retrievalResult.shards.length} guidance shard(s) for intent "${intent}" (confidence: ${(confidence * 100).toFixed(0)}%)`+ : `Classified intent as "${intent}" (confidence: ${(confidence * 100).toFixed(0)}%). No policy bundle loaded.`,+ data: {+ intent,+ confidence,+ policyText: retrievalResult?.policyText ?? null,+ shardCount: retrievalResult?.shards.length ?? 0,+ contradictionsResolved: retrievalResult?.contradictionsResolved ?? 0,+ retrievalLatencyMs: retrievalResult?.latencyMs ?? 0,+ },+ };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ message: 'Failed to retrieve guidance shards for task',+ };+ }+ }++ /**+ * PostTask handler: finalize the run event in the ledger.+ *+ * Looks up the active run by task ID, populates completion metadata,+ * and calls ledger.finalizeEvent().+ */+ private handlePostTask(ctx: HookContext): HookResult {+ const taskId = ctx.task?.id;+ if (!taskId) {+ return { success: true };+ }++ const runEvent = this.activeRuns.get(taskId);+ if (!runEvent) {+ return {+ success: true,+ message: `No active run event found for task "${taskId}". Skipping finalization.`,+ };+ }++ try {+ // Populate additional metadata from context if available+ if (ctx.task?.status) {+ runEvent.outcomeAccepted = ctx.task.status === 'completed';+ }++ if (ctx.metadata?.toolsUsed && Array.isArray(ctx.metadata.toolsUsed)) {+ runEvent.toolsUsed = ctx.metadata.toolsUsed as string[];+ }++ if (ctx.metadata?.filesTouched && Array.isArray(ctx.metadata.filesTouched)) {+ runEvent.filesTouched = ctx.metadata.filesTouched as string[];+ }++ // Finalize the event in the ledger+ this.ledger.finalizeEvent(runEvent);+ this.activeRuns.delete(taskId);++ return {+ success: true,+ message: `Run event finalized for task "${taskId}" (duration: ${runEvent.durationMs}ms)`,+ data: {+ eventId: runEvent.eventId,+ taskId: runEvent.taskId,+ intent: runEvent.intent,+ durationMs: runEvent.durationMs,+ violationCount: runEvent.violations.length,+ },+ };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ message: `Failed to finalize run event for task "${taskId}"`,+ };+ }+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create a GuidanceHookProvider and optionally register it on a registry.+ *+ * @param gates - The enforcement gates instance+ * @param retriever - The shard retriever instance+ * @param ledger - The run ledger instance+ * @param registry - Optional registry to auto-register on+ * @returns The provider and (if registry was given) the hook IDs+ */+export function createGuidanceHooks(+ gates: EnforcementGates,+ retriever: ShardRetriever,+ ledger: RunLedger,+ registry?: HookRegistry,+): { provider: GuidanceHookProvider; hookIds: string[] } {+ const provider = new GuidanceHookProvider(gates, retriever, ledger);+ const hookIds = registry ? provider.registerAll(registry) : [];+ return { provider, hookIds };+}++export { gateResultsToHookResult };diff --git a/v3/@claude-flow/guidance/src/index.ts b/v3/@claude-flow/guidance/src/index.tsindex 8a0ac26f26..04e5efba11 100644--- a/v3/@claude-flow/guidance/src/index.ts+++ b/v3/@claude-flow/guidance/src/index.ts@@ -33,6 +33,7 @@ import { EnforcementGates, createGates } from './gates.js';import { RunLedger, createLedger } from './ledger.js';import { OptimizerLoop, createOptimizer } from './optimizer.js';import { HeadlessRunner, createHeadlessRunner } from './headless.js';+import { DeterministicToolGateway, createToolGateway } from './gateway.js';// Re-export all typesexport type {@@ -73,6 +74,11 @@ export type { CompilerConfig } from './compiler.js';export { ShardRetriever, createRetriever, HashEmbeddingProvider } from './retriever.js';export type { IEmbeddingProvider } from './retriever.js';export { EnforcementGates, createGates } from './gates.js';+export {+ GuidanceHookProvider,+ createGuidanceHooks,+ gateResultsToHookResult,+} from './hooks.js';export {RunLedger,createLedger,@@ -85,6 +91,13 @@ export {export type { IEvaluator } from './ledger.js';export { OptimizerLoop, createOptimizer } from './optimizer.js';export type { OptimizerConfig } from './optimizer.js';+export {+ PersistentLedger,+ EventStore,+ createPersistentLedger,+ createEventStore,+} from './persistence.js';+export type { PersistenceConfig, StorageStats } from './persistence.js';export {HeadlessRunner,createHeadlessRunner,@@ -99,6 +112,14 @@ export type {SuiteRunSummary,ICommandExecutor,} from './headless.js';+export { DeterministicToolGateway, createToolGateway } from './gateway.js';+export type {+ ToolSchema,+ Budget,+ IdempotencyRecord,+ GatewayDecision,+ ToolGatewayConfig,+} from './gateway.js';import type {PolicyBundle,diff --git a/v3/@claude-flow/guidance/src/memory-gate.ts b/v3/@claude-flow/guidance/src/memory-gate.tsnew file mode 100644index 0000000000..0c04d6c587--- /dev/null+++ b/v3/@claude-flow/guidance/src/memory-gate.ts@@ -0,0 +1,584 @@+/**+ * Memory Write Gating System+ *+ * Adds authority scope, TTL, decay, and contradiction tracking+ * to memory operations. Ensures that only authorized agents can+ * write to specific namespaces, enforces rate limits, and detects+ * contradictions between memory entries.+ *+ * @module @claude-flow/guidance/memory-gate+ */++import { createHash } from 'node:crypto';++// ============================================================================+// Types+// ============================================================================++/**+ * Authority definition for a memory-writing agent+ */+export interface MemoryAuthority {+ /** Agent identifier */+ agentId: string;+ /** Role in the hierarchy */+ role: 'queen' | 'coordinator' | 'worker' | 'observer';+ /** Namespaces this agent is allowed to write to */+ namespaces: string[];+ /** Maximum writes allowed per minute */+ maxWritesPerMinute: number;+ /** Whether this agent can delete entries */+ canDelete: boolean;+ /** Whether this agent can overwrite existing entries */+ canOverwrite: boolean;+ /** Trust level from 0 (untrusted) to 1 (fully trusted) */+ trustLevel: number;+}++/**+ * A gated memory entry with metadata for TTL, decay, lineage, and contradictions+ */+export interface MemoryEntry {+ /** Entry key */+ key: string;+ /** Namespace the entry belongs to */+ namespace: string;+ /** The stored value */+ value: unknown;+ /** SHA-256 hash of the serialized value */+ valueHash: string;+ /** Authority that created/last wrote this entry */+ authority: MemoryAuthority;+ /** Timestamp when the entry was created (ms since epoch) */+ createdAt: number;+ /** Timestamp of the last update (ms since epoch) */+ updatedAt: number;+ /** Time-to-live in milliseconds, or null for no expiry */+ ttlMs: number | null;+ /** Decay rate from 0 (no decay) to 1 (immediate decay) */+ decayRate: number;+ /** Confidence score from 0 to 1, decays over time */+ confidence: number;+ /** Lineage tracking for provenance */+ lineage: {+ parentKey?: string;+ derivedFrom?: string[];+ operation: string;+ };+ /** Detected contradictions with other entries */+ contradictions: Array<{+ entryKey: string;+ description: string;+ resolvedAt?: number;+ }>;+}++/**+ * Result of evaluating a write request+ */+export interface WriteDecision {+ /** Whether the write is allowed */+ allowed: boolean;+ /** Human-readable reason for the decision */+ reason: string;+ /** Contradictions detected with existing entries */+ contradictions: Array<{ existingKey: string; description: string }>;+ /** Authority check result */+ authorityCheck: {+ passed: boolean;+ requiredRole: string;+ actualRole: string;+ };+ /** Rate limit check result */+ rateCheck: {+ passed: boolean;+ writesInWindow: number;+ limit: number;+ };+ /** Overwrite permission check result */+ overwriteCheck: {+ isOverwrite: boolean;+ allowed: boolean;+ };+}++/**+ * Configuration for the MemoryWriteGate+ */+export interface MemoryWriteGateConfig {+ /** Pre-registered authorities */+ authorities?: MemoryAuthority[];+ /** Similarity threshold for contradiction detection (0-1) */+ contradictionThreshold?: number;+ /** Default TTL for new entries in ms (null = no expiry) */+ defaultTtlMs?: number;+ /** Default decay rate for new entries (0-1) */+ defaultDecayRate?: number;+ /** Whether to run contradiction detection on writes */+ enableContradictionTracking?: boolean;+}++// ============================================================================+// Role Hierarchy+// ============================================================================++/** Role hierarchy levels (higher = more authority) */+const ROLE_HIERARCHY: Record<MemoryAuthority['role'], number> = {+ queen: 4,+ coordinator: 3,+ worker: 2,+ observer: 1,+};++/**+ * Minimum role required to write to any namespace+ */+const MINIMUM_WRITE_ROLE: MemoryAuthority['role'] = 'worker';++// ============================================================================+// Contradiction Detection Patterns+// ============================================================================++const CONTRADICTION_PATTERNS: Array<{+ positive: RegExp;+ negative: RegExp;+ description: string;+}> = [+ {+ positive: /\bmust\b/i,+ negative: /\bnever\b|\bdo not\b|\bavoid\b/i,+ description: 'Conflicting obligation: "must" vs negation',+ },+ {+ positive: /\balways\b/i,+ negative: /\bnever\b|\bdon't\b|\bdo not\b/i,+ description: 'Conflicting frequency: "always" vs "never"',+ },+ {+ positive: /\brequire\b/i,+ negative: /\bforbid\b|\bprohibit\b/i,+ description: 'Conflicting policy: "require" vs "forbid"',+ },+ {+ positive: /\benable\b/i,+ negative: /\bdisable\b/i,+ description: 'Conflicting state: "enable" vs "disable"',+ },+ {+ positive: /\btrue\b/i,+ negative: /\bfalse\b/i,+ description: 'Conflicting boolean: "true" vs "false"',+ },+];++// ============================================================================+// Utility Functions+// ============================================================================++/**+ * Compute SHA-256 hash of a value+ */+function computeValueHash(value: unknown): string {+ const serialized = JSON.stringify(value);+ return createHash('sha256').update(serialized).digest('hex');+}++/**+ * Stringify a value for contradiction detection+ */+function stringifyForComparison(value: unknown): string {+ if (typeof value === 'string') return value;+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++// ============================================================================+// MemoryWriteGate+// ============================================================================++/**+ * Memory Write Gate+ *+ * Controls write access to the memory system by enforcing:+ * - Authority checks (namespace access, role hierarchy)+ * - Rate limiting (sliding window per agent)+ * - Overwrite permissions+ * - Contradiction detection against existing entries+ * - TTL and confidence decay tracking+ */+export class MemoryWriteGate {+ private authorities: Map<string, MemoryAuthority> = new Map();+ private writeTimestamps: Map<string, number[]> = new Map();+ private contradictionThreshold: number;+ private defaultTtlMs: number | null;+ private defaultDecayRate: number;+ private enableContradictionTracking: boolean;+ private contradictionResolutions: Map<string, string> = new Map();++ constructor(config: MemoryWriteGateConfig = {}) {+ this.contradictionThreshold = config.contradictionThreshold ?? 0.5;+ this.defaultTtlMs = config.defaultTtlMs ?? null;+ this.defaultDecayRate = config.defaultDecayRate ?? 0;+ this.enableContradictionTracking = config.enableContradictionTracking ?? true;++ if (config.authorities) {+ for (const authority of config.authorities) {+ this.authorities.set(authority.agentId, authority);+ }+ }+ }++ /**+ * Evaluate whether a write operation should be allowed.+ *+ * Steps:+ * 1. Check authority (namespace allowed, role sufficient)+ * 2. Check rate limit+ * 3. Check overwrite permission+ * 4. Detect contradictions against existing entries+ * 5. Return decision+ */+ evaluateWrite(+ authority: MemoryAuthority,+ key: string,+ namespace: string,+ value: unknown,+ existingEntries?: MemoryEntry[]+ ): WriteDecision {+ const reasons: string[] = [];+ let allowed = true;++ // Step 1: Authority check+ const authorityCheck = this.checkAuthority(authority, namespace);+ if (!authorityCheck.passed) {+ allowed = false;+ reasons.push(+ `Authority check failed: role "${authority.role}" insufficient or namespace "${namespace}" not allowed`+ );+ }++ // Step 2: Rate limit check+ const rateCheck = this.checkRateLimit(authority);+ if (!rateCheck.passed) {+ allowed = false;+ reasons.push(+ `Rate limit exceeded: ${rateCheck.writesInWindow}/${rateCheck.limit} writes in window`+ );+ }++ // Step 3: Overwrite check+ const isOverwrite = existingEntries+ ? existingEntries.some((e) => e.key === key && e.namespace === namespace)+ : false;+ const overwriteCheck = {+ isOverwrite,+ allowed: isOverwrite ? authority.canOverwrite : true,+ };+ if (isOverwrite && !authority.canOverwrite) {+ allowed = false;+ reasons.push('Overwrite not permitted for this authority');+ }++ // Step 4: Contradiction detection+ let contradictions: Array<{ existingKey: string; description: string }> = [];+ if (+ this.enableContradictionTracking &&+ existingEntries &&+ existingEntries.length > 0+ ) {+ const raw = this.detectContradictions(value, existingEntries);+ contradictions = raw.map((c) => ({+ existingKey: c.entryKey,+ description: c.description,+ }));+ }++ // Step 5: Record write timestamp if allowed+ if (allowed) {+ this.recordWrite(authority.agentId);+ }++ const reason = allowed+ ? 'Write allowed'+ : reasons.join('; ');++ return {+ allowed,+ reason,+ contradictions,+ authorityCheck,+ rateCheck,+ overwriteCheck,+ };+ }++ /**+ * Register a new authority or update an existing one+ */+ registerAuthority(authority: MemoryAuthority): void {+ this.authorities.set(authority.agentId, authority);+ }++ /**+ * Compute the current confidence for an entry based on decay over time.+ *+ * Uses exponential decay: confidence = initialConfidence * e^(-decayRate * ageHours)+ * where ageHours is (now - updatedAt) / 3600000+ */+ computeConfidence(entry: MemoryEntry): number {+ if (entry.decayRate === 0) return entry.confidence;+ if (entry.decayRate >= 1) return 0;++ const now = Date.now();+ const ageMs = now - entry.updatedAt;+ const ageHours = ageMs / 3_600_000;++ const decayed = entry.confidence * Math.exp(-entry.decayRate * ageHours);+ return Math.max(0, Math.min(1, decayed));+ }++ /**+ * Get all entries whose TTL has been exceeded+ */+ getExpiredEntries(entries: MemoryEntry[]): MemoryEntry[] {+ const now = Date.now();+ return entries.filter((entry) => {+ if (entry.ttlMs === null) return false;+ return now - entry.createdAt > entry.ttlMs;+ });+ }++ /**+ * Get entries whose decayed confidence has dropped below a threshold+ */+ getDecayedEntries(entries: MemoryEntry[], threshold: number): MemoryEntry[] {+ return entries.filter((entry) => {+ const currentConfidence = this.computeConfidence(entry);+ return currentConfidence < threshold;+ });+ }++ /**+ * Detect contradictions between a new value and existing entries.+ *+ * Uses string-based pattern matching to find conflicting statements+ * (must vs never, always vs never, require vs forbid, etc.)+ */+ detectContradictions(+ newValue: unknown,+ existingEntries: MemoryEntry[]+ ): Array<{ entryKey: string; description: string }> {+ const newText = stringifyForComparison(newValue);+ const contradictions: Array<{ entryKey: string; description: string }> = [];++ for (const entry of existingEntries) {+ const existingText = stringifyForComparison(entry.value);++ for (const pattern of CONTRADICTION_PATTERNS) {+ const newMatchesPositive =+ pattern.positive.test(newText) && pattern.negative.test(existingText);+ const newMatchesNegative =+ pattern.negative.test(newText) && pattern.positive.test(existingText);++ if (newMatchesPositive || newMatchesNegative) {+ contradictions.push({+ entryKey: entry.key,+ description: pattern.description,+ });+ break; // Only report the first contradiction per entry+ }+ }+ }++ return contradictions;+ }++ /**+ * Mark a contradiction as resolved+ */+ resolveContradiction(entryKey: string, resolution: string): void {+ this.contradictionResolutions.set(entryKey, resolution);+ }++ /**+ * Get the authority for an agent by ID+ */+ getAuthorityFor(agentId: string): MemoryAuthority | undefined {+ return this.authorities.get(agentId);+ }++ /**+ * Get the current rate limit status for an agent+ */+ getRateLimitStatus(agentId: string): {+ writesInWindow: number;+ limit: number;+ resetAt: number;+ } {+ const authority = this.authorities.get(agentId);+ const limit = authority?.maxWritesPerMinute ?? 0;+ const now = Date.now();+ const windowMs = 60_000;+ const windowStart = now - windowMs;++ const timestamps = this.writeTimestamps.get(agentId) ?? [];+ const recentWrites = timestamps.filter((t) => t > windowStart);++ // Find the earliest write in the window to compute reset time+ const resetAt =+ recentWrites.length > 0+ ? recentWrites[0] + windowMs+ : now;++ return {+ writesInWindow: recentWrites.length,+ limit,+ resetAt,+ };+ }++ // ===== Accessors =====++ /** Get the default TTL in ms */+ getDefaultTtlMs(): number | null {+ return this.defaultTtlMs;+ }++ /** Get the default decay rate */+ getDefaultDecayRate(): number {+ return this.defaultDecayRate;+ }++ /** Check if contradiction tracking is enabled */+ isContradictionTrackingEnabled(): boolean {+ return this.enableContradictionTracking;+ }++ /** Get the contradiction resolution for an entry key */+ getContradictionResolution(entryKey: string): string | undefined {+ return this.contradictionResolutions.get(entryKey);+ }++ // ===== Private Methods =====++ /**+ * Check whether an authority is allowed to write to a namespace+ */+ private checkAuthority(+ authority: MemoryAuthority,+ namespace: string+ ): { passed: boolean; requiredRole: string; actualRole: string } {+ const roleLevel = ROLE_HIERARCHY[authority.role];+ const minimumLevel = ROLE_HIERARCHY[MINIMUM_WRITE_ROLE];++ // Role check: must be at least 'worker' level+ if (roleLevel < minimumLevel) {+ return {+ passed: false,+ requiredRole: MINIMUM_WRITE_ROLE,+ actualRole: authority.role,+ };+ }++ // Namespace check: must be in allowed list, or queen can write anywhere+ if (authority.role !== 'queen' && !authority.namespaces.includes(namespace)) {+ return {+ passed: false,+ requiredRole: MINIMUM_WRITE_ROLE,+ actualRole: authority.role,+ };+ }++ return {+ passed: true,+ requiredRole: MINIMUM_WRITE_ROLE,+ actualRole: authority.role,+ };+ }++ /**+ * Check rate limit using a sliding window of write timestamps+ */+ private checkRateLimit(authority: MemoryAuthority): {+ passed: boolean;+ writesInWindow: number;+ limit: number;+ } {+ const now = Date.now();+ const windowMs = 60_000;+ const windowStart = now - windowMs;++ const timestamps = this.writeTimestamps.get(authority.agentId) ?? [];+ // Prune old timestamps outside the window+ const recentWrites = timestamps.filter((t) => t > windowStart);+ this.writeTimestamps.set(authority.agentId, recentWrites);++ return {+ passed: recentWrites.length < authority.maxWritesPerMinute,+ writesInWindow: recentWrites.length,+ limit: authority.maxWritesPerMinute,+ };+ }++ /**+ * Record a write timestamp for an agent+ */+ private recordWrite(agentId: string): void {+ const timestamps = this.writeTimestamps.get(agentId) ?? [];+ timestamps.push(Date.now());+ this.writeTimestamps.set(agentId, timestamps);+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create a MemoryWriteGate instance with optional configuration+ */+export function createMemoryWriteGate(+ config?: MemoryWriteGateConfig+): MemoryWriteGate {+ return new MemoryWriteGate(config);+}++// ============================================================================+// Helper: Create a MemoryEntry+// ============================================================================++/**+ * Create a new MemoryEntry with defaults applied+ */+export function createMemoryEntry(+ key: string,+ namespace: string,+ value: unknown,+ authority: MemoryAuthority,+ options: {+ ttlMs?: number | null;+ decayRate?: number;+ confidence?: number;+ lineage?: MemoryEntry['lineage'];+ } = {}+): MemoryEntry {+ const now = Date.now();+ return {+ key,+ namespace,+ value,+ valueHash: computeValueHash(value),+ authority,+ createdAt: now,+ updatedAt: now,+ ttlMs: options.ttlMs ?? null,+ decayRate: options.decayRate ?? 0,+ confidence: options.confidence ?? 1,+ lineage: options.lineage ?? { operation: 'create' },+ contradictions: [],+ };+}diff --git a/v3/@claude-flow/guidance/src/persistence.ts b/v3/@claude-flow/guidance/src/persistence.tsnew file mode 100644index 0000000000..bc3ff7db7f--- /dev/null+++ b/v3/@claude-flow/guidance/src/persistence.ts@@ -0,0 +1,556 @@+/**+ * Ledger Persistence Layer+ *+ * Connects the in-memory RunLedger to durable file-based storage using+ * newline-delimited JSON (NDJSON). Provides append-only event logging,+ * compaction, and lock-based concurrent access prevention.+ *+ * Storage layout:+ * {storagePath}/events.ndjson - Newline-delimited JSON events+ * {storagePath}/index.json - Metadata index (counts, timestamps, task IDs)+ * {storagePath}/.lock - Lock file for concurrent access prevention+ *+ * @module @claude-flow/guidance/persistence+ */++import { mkdir, readFile, writeFile, appendFile, stat, unlink, rename } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { RunLedger } from './ledger.js';+import type { RunEvent } from './types.js';++// ============================================================================+// Types+// ============================================================================++/**+ * Configuration for the persistent ledger+ */+export interface PersistenceConfig {+ /** Directory path for storage files (default: '.claude-flow/guidance') */+ storagePath: string;+ /** Maximum events to keep; oldest evicted on compact (default: 10000) */+ maxEvents: number;+ /** How often to compact/vacuum in milliseconds (default: 1 hour) */+ compactIntervalMs: number;+ /** Enable write-ahead logging style (flush after each write) (default: true) */+ enableWAL: boolean;+}++/**+ * Storage statistics+ */+export interface StorageStats {+ /** Total number of stored events */+ eventCount: number;+ /** Storage size in bytes */+ storageSizeBytes: number;+ /** Timestamp of the oldest event (null if empty) */+ oldestEvent: number | null;+ /** Timestamp of the newest event (null if empty) */+ newestEvent: number | null;+}++/**+ * Index file structure for quick metadata lookups+ */+interface StorageIndex {+ /** Number of events in the NDJSON file */+ eventCount: number;+ /** Oldest event timestamp */+ oldestTimestamp: number | null;+ /** Newest event timestamp */+ newestTimestamp: number | null;+ /** Set of unique task IDs */+ taskIds: string[];+}++// ============================================================================+// Default Configuration+// ============================================================================++const DEFAULT_PERSISTENCE_CONFIG: PersistenceConfig = {+ storagePath: '.claude-flow/guidance',+ maxEvents: 10_000,+ compactIntervalMs: 60 * 60 * 1000, // 1 hour+ enableWAL: true,+};++// Lock file stale threshold: 30 seconds+const LOCK_STALE_MS = 30_000;++// ============================================================================+// EventStore (Internal)+// ============================================================================++/**+ * Low-level NDJSON-based event storage.+ *+ * Handles file I/O, append-only writes, range reads, compaction,+ * and lock-based concurrent access prevention.+ */+export class EventStore {+ private readonly eventsPath: string;+ private readonly indexPath: string;+ private readonly lockPath: string;+ private readonly baseDir: string;+ private lockHolder: string | null = null;++ constructor(storagePath: string) {+ this.baseDir = storagePath;+ this.eventsPath = join(storagePath, 'events.ndjson');+ this.indexPath = join(storagePath, 'index.json');+ this.lockPath = join(storagePath, '.lock');+ }++ /**+ * Append a single event to the NDJSON file and update the index.+ */+ async append(event: RunEvent): Promise<void> {+ await this.ensureDirectory();+ const line = JSON.stringify(event) + '\n';+ await appendFile(this.eventsPath, line, 'utf-8');+ await this.updateIndex(event);+ }++ /**+ * Read and parse all events from storage.+ */+ async readAll(): Promise<RunEvent[]> {+ if (!existsSync(this.eventsPath)) {+ return [];+ }++ const content = await readFile(this.eventsPath, 'utf-8');+ return this.parseNdjson(content);+ }++ /**+ * Read events within a time range [startTime, endTime].+ */+ async readRange(startTime: number, endTime: number): Promise<RunEvent[]> {+ const all = await this.readAll();+ return all.filter(e => e.timestamp >= startTime && e.timestamp <= endTime);+ }++ /**+ * Compact the event store to keep at most `maxEvents` events.+ * Oldest events are evicted first. Rewrites the NDJSON file atomically.+ *+ * @returns The number of evicted events.+ */+ async compact(maxEvents: number): Promise<number> {+ const events = await this.readAll();++ if (events.length <= maxEvents) {+ return 0;+ }++ // Sort by timestamp ascending, keep the newest maxEvents+ events.sort((a, b) => a.timestamp - b.timestamp);+ const evicted = events.length - maxEvents;+ const kept = events.slice(evicted);++ // Atomic rewrite: write to temp file, then rename+ await this.ensureDirectory();+ const tempPath = join(this.baseDir, `events.tmp.${randomUUID()}.ndjson`);+ const content = kept.map(e => JSON.stringify(e)).join('\n') + (kept.length > 0 ? '\n' : '');+ await writeFile(tempPath, content, 'utf-8');+ await rename(tempPath, this.eventsPath);++ // Rebuild index from kept events+ await this.rebuildIndex(kept);++ return evicted;+ }++ /**+ * Get storage statistics.+ */+ async getStats(): Promise<StorageStats> {+ const index = await this.readIndex();+ let storageSizeBytes = 0;++ if (existsSync(this.eventsPath)) {+ const fileStat = await stat(this.eventsPath);+ storageSizeBytes = fileStat.size;+ }++ if (existsSync(this.indexPath)) {+ const indexStat = await stat(this.indexPath);+ storageSizeBytes += indexStat.size;+ }++ return {+ eventCount: index.eventCount,+ storageSizeBytes,+ oldestEvent: index.oldestTimestamp,+ newestEvent: index.newestTimestamp,+ };+ }++ /**+ * Acquire a file-based lock for concurrent access prevention.+ * Throws if the lock is already held by another process.+ */+ async acquireLock(): Promise<void> {+ await this.ensureDirectory();++ // Check for stale locks+ if (existsSync(this.lockPath)) {+ try {+ const lockContent = await readFile(this.lockPath, 'utf-8');+ const lockData = JSON.parse(lockContent);+ const age = Date.now() - lockData.timestamp;++ if (age < LOCK_STALE_MS) {+ throw new Error(+ `Storage is locked by another process (holder: ${lockData.holder}, age: ${age}ms). ` ++ `Lock file: ${this.lockPath}`+ );+ }+ // Stale lock, remove it+ await unlink(this.lockPath);+ } catch (err) {+ if (err instanceof Error && err.message.startsWith('Storage is locked')) {+ throw err;+ }+ // Corrupted lock file, remove it+ try { await unlink(this.lockPath); } catch { /* ignore */ }+ }+ }++ const holder = randomUUID();+ const lockData = { holder, timestamp: Date.now(), pid: process.pid };+ await writeFile(this.lockPath, JSON.stringify(lockData), 'utf-8');+ this.lockHolder = holder;+ }++ /**+ * Release the file-based lock.+ */+ async releaseLock(): Promise<void> {+ if (existsSync(this.lockPath)) {+ try {+ const lockContent = await readFile(this.lockPath, 'utf-8');+ const lockData = JSON.parse(lockContent);++ // Only release if we own the lock+ if (this.lockHolder && lockData.holder === this.lockHolder) {+ await unlink(this.lockPath);+ }+ } catch {+ // Best-effort removal+ try { await unlink(this.lockPath); } catch { /* ignore */ }+ }+ }+ this.lockHolder = null;+ }++ /**+ * Remove all storage files (events, index, lock).+ */+ async destroy(): Promise<void> {+ for (const filePath of [this.eventsPath, this.indexPath, this.lockPath]) {+ if (existsSync(filePath)) {+ try { await unlink(filePath); } catch { /* ignore */ }+ }+ }+ }++ // ===== Private helpers =====++ /**+ * Ensure the storage directory exists.+ */+ private async ensureDirectory(): Promise<void> {+ if (!existsSync(this.baseDir)) {+ await mkdir(this.baseDir, { recursive: true });+ }+ }++ /**+ * Parse an NDJSON string into RunEvent array, skipping blank/invalid lines.+ */+ private parseNdjson(content: string): RunEvent[] {+ const events: RunEvent[] = [];+ const lines = content.split('\n');++ for (const line of lines) {+ const trimmed = line.trim();+ if (trimmed.length === 0) continue;++ try {+ events.push(JSON.parse(trimmed) as RunEvent);+ } catch {+ // Skip malformed lines+ }+ }++ return events;+ }++ /**+ * Read the index file, returning a default if it does not exist.+ */+ private async readIndex(): Promise<StorageIndex> {+ if (!existsSync(this.indexPath)) {+ return { eventCount: 0, oldestTimestamp: null, newestTimestamp: null, taskIds: [] };+ }++ try {+ const content = await readFile(this.indexPath, 'utf-8');+ return JSON.parse(content) as StorageIndex;+ } catch {+ return { eventCount: 0, oldestTimestamp: null, newestTimestamp: null, taskIds: [] };+ }+ }++ /**+ * Update the index with a new event.+ */+ private async updateIndex(event: RunEvent): Promise<void> {+ const index = await this.readIndex();++ index.eventCount++;+ if (index.oldestTimestamp === null || event.timestamp < index.oldestTimestamp) {+ index.oldestTimestamp = event.timestamp;+ }+ if (index.newestTimestamp === null || event.timestamp > index.newestTimestamp) {+ index.newestTimestamp = event.timestamp;+ }+ if (!index.taskIds.includes(event.taskId)) {+ index.taskIds.push(event.taskId);+ }++ await writeFile(this.indexPath, JSON.stringify(index, null, 2), 'utf-8');+ }++ /**+ * Rebuild the index from a given set of events.+ */+ private async rebuildIndex(events: RunEvent[]): Promise<void> {+ const taskIdSet = new Set<string>();+ let oldest: number | null = null;+ let newest: number | null = null;++ for (const event of events) {+ taskIdSet.add(event.taskId);+ if (oldest === null || event.timestamp < oldest) {+ oldest = event.timestamp;+ }+ if (newest === null || event.timestamp > newest) {+ newest = event.timestamp;+ }+ }++ const index: StorageIndex = {+ eventCount: events.length,+ oldestTimestamp: oldest,+ newestTimestamp: newest,+ taskIds: Array.from(taskIdSet),+ };++ await this.ensureDirectory();+ await writeFile(this.indexPath, JSON.stringify(index, null, 2), 'utf-8');+ }+}++// ============================================================================+// PersistentLedger+// ============================================================================++/**+ * A RunLedger subclass that persists events to NDJSON file storage.+ *+ * Extends the in-memory RunLedger with:+ * - Automatic persistence on logEvent()+ * - Load from storage on init via importEvents()+ * - Explicit save()/load() for bulk operations+ * - Compaction to enforce maxEvents limit+ * - Storage statistics+ * - Automatic periodic compaction via interval timer+ */+export class PersistentLedger extends RunLedger {+ private readonly config: PersistenceConfig;+ private readonly store: EventStore;+ private compactTimer: ReturnType<typeof setInterval> | null = null;+ private initialized = false;++ constructor(config?: Partial<PersistenceConfig>) {+ super();+ this.config = { ...DEFAULT_PERSISTENCE_CONFIG, ...config };+ this.store = new EventStore(this.config.storagePath);+ }++ /**+ * Initialize the persistent ledger: load existing events from storage+ * and start the compaction timer.+ */+ async init(): Promise<void> {+ if (this.initialized) return;++ await this.load();+ this.startCompactTimer();+ this.initialized = true;+ }++ /**+ * Override logEvent to also persist the event to storage.+ */+ override logEvent(event: RunEvent | Omit<RunEvent, 'eventId'>): RunEvent {+ const logged = super.logEvent(event);++ // Fire-and-forget persist. If enableWAL is true, we await in a microtask+ // to minimize the chance of data loss without blocking the caller.+ if (this.config.enableWAL) {+ // Use a void promise to avoid unhandled rejection+ void this.store.append(logged).catch(() => {+ // Silently swallow persistence errors to not break the caller.+ // In production you would log this.+ });+ }++ return logged;+ }++ /**+ * Override importEvents to also persist imported events to storage.+ */+ override importEvents(events: RunEvent[]): void {+ super.importEvents(events);++ // Persist each imported event+ void (async () => {+ for (const event of events) {+ try {+ await this.store.append(event);+ } catch {+ // Silently continue+ }+ }+ })();+ }++ /**+ * Flush all in-memory events to storage, replacing the storage contents.+ * This performs a full rewrite of the NDJSON file.+ */+ async save(): Promise<void> {+ const events = this.exportEvents();++ await this.store.acquireLock();+ try {+ // Compact rewrite: write all events, then rebuild index+ await this.store.compact(Infinity); // Clear the file by compacting with no limit first+ // Now write all current in-memory events+ for (const event of events) {+ await this.store.append(event);+ }+ } finally {+ await this.store.releaseLock();+ }+ }++ /**+ * Restore events from storage into memory.+ * Clears the in-memory ledger first, then loads all stored events.+ */+ async load(): Promise<void> {+ const events = await this.store.readAll();+ this.clear();+ if (events.length > 0) {+ super.importEvents(events);+ }+ }++ /**+ * Compact the storage to keep at most maxEvents events.+ * Also updates the in-memory ledger to match.+ *+ * @returns The number of evicted events.+ */+ async compact(): Promise<number> {+ await this.store.acquireLock();+ try {+ const evicted = await this.store.compact(this.config.maxEvents);++ if (evicted > 0) {+ // Reload in-memory state from the compacted storage+ const events = await this.store.readAll();+ this.clear();+ if (events.length > 0) {+ super.importEvents(events);+ }+ }++ return evicted;+ } finally {+ await this.store.releaseLock();+ }+ }++ /**+ * Get storage statistics.+ */+ async getStorageStats(): Promise<StorageStats> {+ return this.store.getStats();+ }++ /**+ * Clean up resources (stop compaction timer, release locks, etc.).+ */+ async destroy(): Promise<void> {+ this.stopCompactTimer();+ await this.store.releaseLock();+ }++ /**+ * Get the underlying EventStore (for advanced use / testing).+ */+ getEventStore(): EventStore {+ return this.store;+ }++ // ===== Private =====++ private startCompactTimer(): void {+ if (this.config.compactIntervalMs > 0) {+ this.compactTimer = setInterval(() => {+ void this.compact().catch(() => { /* ignore timer errors */ });+ }, this.config.compactIntervalMs);++ // Unref the timer so it doesn't keep the process alive+ if (this.compactTimer && typeof this.compactTimer === 'object' && 'unref' in this.compactTimer) {+ this.compactTimer.unref();+ }+ }+ }++ private stopCompactTimer(): void {+ if (this.compactTimer !== null) {+ clearInterval(this.compactTimer);+ this.compactTimer = null;+ }+ }+}++// ============================================================================+// Factory Functions+// ============================================================================++/**+ * Create a PersistentLedger instance. Call `init()` after creation to load+ * existing events from storage.+ */+export function createPersistentLedger(config?: Partial<PersistenceConfig>): PersistentLedger {+ return new PersistentLedger(config);+}++/**+ * Create an EventStore instance for direct low-level storage access.+ */+export function createEventStore(path: string): EventStore {+ return new EventStore(path);+}diff --git a/v3/@claude-flow/guidance/src/proof.ts b/v3/@claude-flow/guidance/src/proof.tsnew file mode 100644index 0000000000..b14a70bb03--- /dev/null+++ b/v3/@claude-flow/guidance/src/proof.ts@@ -0,0 +1,364 @@+/**+ * Proof Envelope - Cryptographic Evidence Trail+ *+ * Makes every run auditable and tamper-evident by producing a hash-chained,+ * HMAC-signed envelope for each RunEvent. Each envelope captures:+ *+ * - SHA-256 content hash of the run event+ * - Hash chain linking to the previous envelope (genesis = '0' x 64)+ * - Individual tool call hashes+ * - Memory lineage (reads/writes with value hashes)+ * - HMAC-SHA256 signature over the entire envelope body+ *+ * @module @claude-flow/guidance/proof+ */++import { createHash, createHmac, randomUUID } from 'node:crypto';+import type { RunEvent } from './types.js';++// ============================================================================+// Types+// ============================================================================++/**+ * Record of a single tool invocation with its parameters and result.+ */+export interface ToolCallRecord {+ /** Unique call identifier */+ callId: string;+ /** Name of the tool invoked */+ toolName: string;+ /** Parameters passed to the tool */+ params: Record<string, unknown>;+ /** Result returned by the tool */+ result: unknown;+ /** Timestamp of the call (epoch ms) */+ timestamp: number;+ /** Duration of the call in milliseconds */+ durationMs: number;+}++/**+ * Record of a memory read, write, or delete operation.+ */+export interface MemoryOperation {+ /** Memory key */+ key: string;+ /** Memory namespace */+ namespace: string;+ /** Type of operation */+ operation: 'read' | 'write' | 'delete';+ /** SHA-256 hash of the value */+ valueHash: string;+ /** Timestamp of the operation (epoch ms) */+ timestamp: number;+}++/**+ * Entry in the memory lineage array stored inside a ProofEnvelope.+ */+export interface MemoryLineageEntry {+ key: string;+ namespace: string;+ operation: 'read' | 'write' | 'delete';+ hash: string;+}++/**+ * Metadata attached to every proof envelope.+ */+export interface ProofEnvelopeMetadata {+ agentId: string;+ sessionId: string;+ parentEnvelopeId?: string;+}++/**+ * A cryptographically signed, hash-chained proof envelope.+ */+export interface ProofEnvelope {+ /** Unique envelope identifier */+ envelopeId: string;+ /** Reference to the RunEvent this envelope covers */+ runEventId: string;+ /** ISO 8601 timestamp of envelope creation */+ timestamp: string;+ /** SHA-256 hash of the full RunEvent */+ contentHash: string;+ /** Hash of the previous envelope in the chain (genesis = '0'.repeat(64)) */+ previousHash: string;+ /** Map of tool call ID to SHA-256(toolName + params + result) */+ toolCallHashes: Record<string, string>;+ /** SHA-256 hash of the policy bundle used */+ guidanceHash: string;+ /** Lineage of memory operations during the run */+ memoryLineage: MemoryLineageEntry[];+ /** HMAC-SHA256 signature of the envelope content */+ signature: string;+ /** Contextual metadata */+ metadata: ProofEnvelopeMetadata;+}++/**+ * Serializable chain representation for export/import.+ */+export interface SerializedProofChain {+ envelopes: ProofEnvelope[];+ createdAt: string;+ version: number;+}++// ============================================================================+// Constants+// ============================================================================++const GENESIS_HASH = '0'.repeat(64);+const DEFAULT_SIGNING_KEY = 'claude-flow-guidance-default-key';+const SERIALIZATION_VERSION = 1;++// ============================================================================+// ProofChain+// ============================================================================++/**+ * A tamper-evident, hash-chained sequence of ProofEnvelopes.+ *+ * Each envelope links to the previous one via `previousHash`, forming+ * a blockchain-like structure. Every envelope is HMAC-signed so any+ * modification to the chain can be detected.+ */+export class ProofChain {+ private envelopes: ProofEnvelope[] = [];+ private readonly signingKey: string;++ constructor(signingKey: string = DEFAULT_SIGNING_KEY) {+ this.signingKey = signingKey;+ }++ /**+ * Append a new ProofEnvelope to the chain.+ *+ * @param runEvent - The RunEvent to wrap+ * @param toolCalls - Tool call records from the run+ * @param memoryOps - Memory operations from the run+ * @param metadata - Optional metadata overrides+ * @returns The newly created and signed ProofEnvelope+ */+ append(+ runEvent: RunEvent,+ toolCalls: ToolCallRecord[] = [],+ memoryOps: MemoryOperation[] = [],+ metadata?: Partial<ProofEnvelopeMetadata>,+ ): ProofEnvelope {+ const previousHash = this.envelopes.length > 0+ ? this.envelopes[this.envelopes.length - 1].contentHash+ : GENESIS_HASH;++ const contentHash = this.computeContentHash(runEvent);++ const toolCallHashes: Record<string, string> = {};+ for (const call of toolCalls) {+ toolCallHashes[call.callId] = this.computeToolCallHash(call);+ }++ const memoryLineage: MemoryLineageEntry[] = memoryOps.map(op => ({+ key: op.key,+ namespace: op.namespace,+ operation: op.operation,+ hash: op.valueHash,+ }));++ const envelope: ProofEnvelope = {+ envelopeId: randomUUID(),+ runEventId: runEvent.eventId,+ timestamp: new Date().toISOString(),+ contentHash,+ previousHash,+ toolCallHashes,+ guidanceHash: runEvent.guidanceHash,+ memoryLineage,+ signature: '', // placeholder; signed below+ metadata: {+ agentId: metadata?.agentId ?? 'unknown',+ sessionId: metadata?.sessionId ?? runEvent.sessionId ?? 'unknown',+ parentEnvelopeId: metadata?.parentEnvelopeId,+ },+ };++ envelope.signature = this.signEnvelope(envelope);+ this.envelopes.push(envelope);++ return envelope;+ }++ /**+ * Verify a single envelope's HMAC signature and hash chain link.+ *+ * @returns true if the signature is valid and the previousHash is correct+ */+ verify(envelope: ProofEnvelope): boolean {+ // Verify HMAC signature+ const expectedSignature = this.signEnvelope(envelope);+ if (envelope.signature !== expectedSignature) {+ return false;+ }++ // Verify hash chain linkage+ const index = this.envelopes.findIndex(e => e.envelopeId === envelope.envelopeId);+ if (index === -1) {+ // Envelope not in this chain; verify signature only+ return true;+ }++ if (index === 0) {+ return envelope.previousHash === GENESIS_HASH;+ }++ return envelope.previousHash === this.envelopes[index - 1].contentHash;+ }++ /**+ * Verify the entire chain from genesis to tip.+ *+ * Checks that every envelope:+ * 1. Has a valid HMAC signature+ * 2. Links correctly to the previous envelope's contentHash+ *+ * @returns true if the full chain is intact+ */+ verifyChain(): boolean {+ if (this.envelopes.length === 0) {+ return true;+ }++ for (let i = 0; i < this.envelopes.length; i++) {+ const envelope = this.envelopes[i];++ // Verify signature+ const expectedSignature = this.signEnvelope(envelope);+ if (envelope.signature !== expectedSignature) {+ return false;+ }++ // Verify hash chain+ if (i === 0) {+ if (envelope.previousHash !== GENESIS_HASH) {+ return false;+ }+ } else {+ if (envelope.previousHash !== this.envelopes[i - 1].contentHash) {+ return false;+ }+ }+ }++ return true;+ }++ /**+ * Retrieve an envelope by its ID.+ */+ getEnvelope(id: string): ProofEnvelope | undefined {+ return this.envelopes.find(e => e.envelopeId === id);+ }++ /**+ * Get the most recent envelope in the chain.+ */+ getChainTip(): ProofEnvelope | undefined {+ return this.envelopes.length > 0+ ? this.envelopes[this.envelopes.length - 1]+ : undefined;+ }++ /**+ * Get the number of envelopes in the chain.+ */+ getChainLength(): number {+ return this.envelopes.length;+ }++ /**+ * Export the chain as a serializable object.+ */+ export(): SerializedProofChain {+ return {+ envelopes: this.envelopes.map(e => ({ ...e })),+ createdAt: new Date().toISOString(),+ version: SERIALIZATION_VERSION,+ };+ }++ /**+ * Restore the chain from a previously exported object.+ *+ * Replaces the current chain contents entirely.+ */+ import(data: SerializedProofChain): void {+ if (data.version !== SERIALIZATION_VERSION) {+ throw new Error(+ `Unsupported proof chain version: ${data.version} (expected ${SERIALIZATION_VERSION})`,+ );+ }+ this.envelopes = data.envelopes.map(e => ({ ...e }));+ }++ // ===========================================================================+ // Private helpers+ // ===========================================================================++ /**+ * Compute the SHA-256 content hash of a RunEvent.+ */+ private computeContentHash(event: RunEvent): string {+ const payload = JSON.stringify(event, Object.keys(event).sort());+ return createHash('sha256').update(payload).digest('hex');+ }++ /**+ * Compute the SHA-256 hash of a single tool call.+ *+ * Hash = SHA-256(toolName + JSON(params) + JSON(result))+ */+ private computeToolCallHash(call: ToolCallRecord): string {+ const payload = call.toolName+ + JSON.stringify(call.params)+ + JSON.stringify(call.result);+ return createHash('sha256').update(payload).digest('hex');+ }++ /**+ * Produce the HMAC-SHA256 signature for an envelope.+ *+ * The signature covers every field except `signature` itself.+ */+ private signEnvelope(envelope: ProofEnvelope): string {+ const body = {+ envelopeId: envelope.envelopeId,+ runEventId: envelope.runEventId,+ timestamp: envelope.timestamp,+ contentHash: envelope.contentHash,+ previousHash: envelope.previousHash,+ toolCallHashes: envelope.toolCallHashes,+ guidanceHash: envelope.guidanceHash,+ memoryLineage: envelope.memoryLineage,+ metadata: envelope.metadata,+ };+ const payload = JSON.stringify(body);+ return createHmac('sha256', this.signingKey).update(payload).digest('hex');+ }+}++// ============================================================================+// Factory+// ============================================================================++/**+ * Create a new ProofChain instance.+ *+ * @param config - Optional configuration. `signingKey` sets the HMAC key.+ * @returns A fresh ProofChain+ */+export function createProofChain(config?: { signingKey?: string }): ProofChain {+ return new ProofChain(config?.signingKey);+}diff --git a/v3/@claude-flow/guidance/tests/coherence.test.ts b/v3/@claude-flow/guidance/tests/coherence.test.tsnew file mode 100644index 0000000000..075d280255--- /dev/null+++ b/v3/@claude-flow/guidance/tests/coherence.test.ts@@ -0,0 +1,732 @@+/**+ * Tests for the Coherence Scheduler & Economic Governor+ */+import { describe, it, expect, beforeEach } from 'vitest';+import {+ CoherenceScheduler,+ EconomicGovernor,+ createCoherenceScheduler,+ createEconomicGovernor,+} from '../src/coherence.js';+import type { CoherenceScore } from '../src/coherence.js';+import type { RunEvent, OptimizationMetrics, TaskIntent } from '../src/types.js';++// ============================================================================+// Test Helpers+// ============================================================================++function createMockEvent(overrides: Partial<RunEvent> = {}): RunEvent {+ return {+ eventId: `evt-${Math.random().toString(36).slice(2)}`,+ taskId: `task-${Math.random().toString(36).slice(2)}`,+ guidanceHash: 'abc123',+ retrievedRuleIds: ['R001', 'R002'],+ toolsUsed: ['Read', 'Edit'],+ filesTouched: ['src/main.ts'],+ diffSummary: { linesAdded: 50, linesRemoved: 10, filesChanged: 1 },+ testResults: { ran: true, passed: 10, failed: 0, skipped: 0 },+ violations: [],+ outcomeAccepted: true,+ reworkLines: 5,+ intent: 'feature',+ timestamp: Date.now(),+ durationMs: 5000,+ ...overrides,+ };+}++function createMockMetrics(overrides: Partial<OptimizationMetrics> = {}): OptimizationMetrics {+ return {+ violationRate: 0,+ selfCorrectionRate: 1,+ reworkLines: 0,+ clarifyingQuestions: 0,+ taskCount: 10,+ ...overrides,+ };+}++// ============================================================================+// CoherenceScheduler Tests+// ============================================================================++describe('CoherenceScheduler', () => {+ let scheduler: CoherenceScheduler;++ beforeEach(() => {+ scheduler = new CoherenceScheduler();+ });++ describe('computeCoherence', () => {+ it('should compute a healthy score with clean metrics and consistent events', () => {+ const metrics = createMockMetrics({+ violationRate: 0,+ reworkLines: 0,+ });++ // All events have the same intent+ const events = Array.from({ length: 10 }, () =>+ createMockEvent({ intent: 'feature' }),+ );++ const score = scheduler.computeCoherence(metrics, events);++ expect(score.overall).toBeGreaterThanOrEqual(0.7);+ expect(score.violationComponent).toBe(1);+ expect(score.reworkComponent).toBe(1);+ expect(score.driftComponent).toBe(1);+ expect(score.overall).toBe(1);+ expect(score.windowSize).toBe(10);+ expect(score.timestamp).toBeGreaterThan(0);+ });++ it('should compute a degraded score with moderate violations and rework', () => {+ const metrics = createMockMetrics({+ violationRate: 5, // 5 violations per 10 tasks+ reworkLines: 50, // 50 rework lines on average+ });++ const events = Array.from({ length: 10 }, () =>+ createMockEvent({ intent: 'feature' }),+ );++ const score = scheduler.computeCoherence(metrics, events);++ // violationComponent: 1 - (5/10) = 0.5+ expect(score.violationComponent).toBe(0.5);+ // reworkComponent: 1 - (50/100) = 0.5+ expect(score.reworkComponent).toBe(0.5);+ // driftComponent: all same intent = 1+ expect(score.driftComponent).toBe(1);+ // overall: 0.4*0.5 + 0.3*0.5 + 0.3*1 = 0.2 + 0.15 + 0.3 = 0.65+ expect(score.overall).toBeCloseTo(0.65, 5);+ });++ it('should compute a critical score with high violations, rework, and drift', () => {+ const metrics = createMockMetrics({+ violationRate: 10, // max+ reworkLines: 100, // max+ });++ // Every event has a different intent+ const intents: TaskIntent[] = [+ 'bug-fix', 'feature', 'refactor', 'security',+ 'performance', 'testing', 'docs', 'deployment',+ 'architecture', 'debug',+ ];+ const events = intents.map(intent => createMockEvent({ intent }));++ const score = scheduler.computeCoherence(metrics, events);++ // violationComponent: 1 - (10/10) = 0, clamped to 0+ expect(score.violationComponent).toBe(0);+ // reworkComponent: 1 - (100/100) = 0, clamped to 0+ expect(score.reworkComponent).toBe(0);+ // driftComponent: 10 unique / 10 events = 1 - (10-1)/(10-1) = 0+ expect(score.driftComponent).toBe(0);+ // overall: 0+ expect(score.overall).toBe(0);+ });++ it('should clamp violation rate above 10 to 0', () => {+ const metrics = createMockMetrics({ violationRate: 20 });+ const events = [createMockEvent()];++ const score = scheduler.computeCoherence(metrics, events);+ expect(score.violationComponent).toBe(0);+ });++ it('should clamp rework lines above 100 to 0', () => {+ const metrics = createMockMetrics({ reworkLines: 200 });+ const events = [createMockEvent()];++ const score = scheduler.computeCoherence(metrics, events);+ expect(score.reworkComponent).toBe(0);+ });++ it('should handle empty events with drift component 1', () => {+ const metrics = createMockMetrics();+ const score = scheduler.computeCoherence(metrics, []);++ expect(score.driftComponent).toBe(1);+ expect(score.windowSize).toBe(0);+ });++ it('should respect custom window size', () => {+ const customScheduler = new CoherenceScheduler({ windowSize: 5 });+ const metrics = createMockMetrics();+ const events = Array.from({ length: 20 }, () => createMockEvent());++ const score = customScheduler.computeCoherence(metrics, events);+ expect(score.windowSize).toBe(5);+ });++ it('should add scores to history', () => {+ const metrics = createMockMetrics();+ const events = [createMockEvent()];++ scheduler.computeCoherence(metrics, events);+ scheduler.computeCoherence(metrics, events);+ scheduler.computeCoherence(metrics, events);++ expect(scheduler.getScoreHistory()).toHaveLength(3);+ });+ });++ describe('getPrivilegeLevel', () => {+ it('should return "full" for healthy scores', () => {+ const score: CoherenceScore = {+ overall: 0.85,+ violationComponent: 0.9,+ reworkComponent: 0.8,+ driftComponent: 0.85,+ timestamp: Date.now(),+ windowSize: 10,+ };+ expect(scheduler.getPrivilegeLevel(score)).toBe('full');+ });++ it('should return "full" at exactly the healthy threshold', () => {+ const score: CoherenceScore = {+ overall: 0.7,+ violationComponent: 0.7,+ reworkComponent: 0.7,+ driftComponent: 0.7,+ timestamp: Date.now(),+ windowSize: 10,+ };+ expect(scheduler.getPrivilegeLevel(score)).toBe('full');+ });++ it('should return "restricted" between warning and healthy thresholds', () => {+ const score: CoherenceScore = {+ overall: 0.6,+ violationComponent: 0.6,+ reworkComponent: 0.6,+ driftComponent: 0.6,+ timestamp: Date.now(),+ windowSize: 10,+ };+ expect(scheduler.getPrivilegeLevel(score)).toBe('restricted');+ });++ it('should return "read-only" between read-only and warning thresholds', () => {+ const score: CoherenceScore = {+ overall: 0.4,+ violationComponent: 0.4,+ reworkComponent: 0.4,+ driftComponent: 0.4,+ timestamp: Date.now(),+ windowSize: 10,+ };+ expect(scheduler.getPrivilegeLevel(score)).toBe('read-only');+ });++ it('should return "suspended" below read-only threshold', () => {+ const score: CoherenceScore = {+ overall: 0.2,+ violationComponent: 0.2,+ reworkComponent: 0.2,+ driftComponent: 0.2,+ timestamp: Date.now(),+ windowSize: 10,+ };+ expect(scheduler.getPrivilegeLevel(score)).toBe('suspended');+ });++ it('should use custom thresholds', () => {+ const custom = new CoherenceScheduler({+ thresholds: {+ readOnlyThreshold: 0.2,+ warningThreshold: 0.4,+ healthyThreshold: 0.6,+ },+ });++ const score: CoherenceScore = {+ overall: 0.5,+ violationComponent: 0.5,+ reworkComponent: 0.5,+ driftComponent: 0.5,+ timestamp: Date.now(),+ windowSize: 10,+ };++ // 0.5 is between warning (0.4) and healthy (0.6) with custom thresholds+ expect(custom.getPrivilegeLevel(score)).toBe('restricted');+ });+ });++ describe('drift detection', () => {+ it('should detect drift when score is below warning threshold', () => {+ const driftingScore: CoherenceScore = {+ overall: 0.3,+ violationComponent: 0.2,+ reworkComponent: 0.3,+ driftComponent: 0.4,+ timestamp: Date.now(),+ windowSize: 10,+ };++ expect(scheduler.isDrifting(driftingScore)).toBe(true);+ });++ it('should not detect drift when score is healthy', () => {+ const healthyScore: CoherenceScore = {+ overall: 0.8,+ violationComponent: 0.9,+ reworkComponent: 0.8,+ driftComponent: 0.7,+ timestamp: Date.now(),+ windowSize: 10,+ };++ expect(scheduler.isDrifting(healthyScore)).toBe(false);+ });++ it('should not detect drift at exactly the warning threshold', () => {+ const borderlineScore: CoherenceScore = {+ overall: 0.5,+ violationComponent: 0.5,+ reworkComponent: 0.5,+ driftComponent: 0.5,+ timestamp: Date.now(),+ windowSize: 10,+ };++ expect(scheduler.isDrifting(borderlineScore)).toBe(false);+ });++ it('should measure intent drift from diverse events', () => {+ const metrics = createMockMetrics();+ const intents: TaskIntent[] = [+ 'bug-fix', 'feature', 'refactor', 'security', 'performance',+ ];+ const events = intents.map(intent => createMockEvent({ intent }));++ const score = scheduler.computeCoherence(metrics, events);++ // 5 unique intents out of 5 events: drift = 1 - (5-1)/(5-1) = 0+ expect(score.driftComponent).toBe(0);+ });+ });++ describe('isHealthy', () => {+ it('should return true for scores at or above healthy threshold', () => {+ expect(scheduler.isHealthy({ overall: 0.7 } as CoherenceScore)).toBe(true);+ expect(scheduler.isHealthy({ overall: 1.0 } as CoherenceScore)).toBe(true);+ });++ it('should return false for scores below healthy threshold', () => {+ expect(scheduler.isHealthy({ overall: 0.69 } as CoherenceScore)).toBe(false);+ expect(scheduler.isHealthy({ overall: 0.0 } as CoherenceScore)).toBe(false);+ });+ });++ describe('shouldRestrict', () => {+ it('should restrict when below warning threshold', () => {+ expect(scheduler.shouldRestrict({ overall: 0.49 } as CoherenceScore)).toBe(true);+ });++ it('should not restrict at or above warning threshold', () => {+ expect(scheduler.shouldRestrict({ overall: 0.5 } as CoherenceScore)).toBe(false);+ expect(scheduler.shouldRestrict({ overall: 0.9 } as CoherenceScore)).toBe(false);+ });+ });++ describe('getRecommendation', () => {+ it('should include escalation note for very high scores', () => {+ const score: CoherenceScore = {+ overall: 0.95,+ violationComponent: 0.95,+ reworkComponent: 0.95,+ driftComponent: 0.95,+ timestamp: Date.now(),+ windowSize: 10,+ };++ const rec = scheduler.getRecommendation(score);+ expect(rec).toContain('healthy');+ expect(rec).toContain('escalation');+ });++ it('should warn about violations when violation component is low', () => {+ const score: CoherenceScore = {+ overall: 0.65,+ violationComponent: 0.3,+ reworkComponent: 0.8,+ driftComponent: 0.85,+ timestamp: Date.now(),+ windowSize: 10,+ };++ const rec = scheduler.getRecommendation(score);+ expect(rec).toContain('violation');+ expect(rec).toContain('enforcement');+ });++ it('should warn about rework when rework component is low', () => {+ const score: CoherenceScore = {+ overall: 0.55,+ violationComponent: 0.8,+ reworkComponent: 0.3,+ driftComponent: 0.55,+ timestamp: Date.now(),+ windowSize: 10,+ };++ const rec = scheduler.getRecommendation(score);+ expect(rec).toContain('rework');+ });++ it('should warn about drift when drift component is low', () => {+ const score: CoherenceScore = {+ overall: 0.55,+ violationComponent: 0.8,+ reworkComponent: 0.8,+ driftComponent: 0.3,+ timestamp: Date.now(),+ windowSize: 10,+ };++ const rec = scheduler.getRecommendation(score);+ expect(rec).toContain('drift');+ });++ it('should mention suspension for very low scores', () => {+ const score: CoherenceScore = {+ overall: 0.1,+ violationComponent: 0.1,+ reworkComponent: 0.1,+ driftComponent: 0.1,+ timestamp: Date.now(),+ windowSize: 10,+ };++ const rec = scheduler.getRecommendation(score);+ expect(rec).toContain('suspended');+ });+ });++ describe('score history', () => {+ it('should cap history at 100 entries', () => {+ const metrics = createMockMetrics();+ const events = [createMockEvent()];++ for (let i = 0; i < 120; i++) {+ scheduler.computeCoherence(metrics, events);+ }++ expect(scheduler.getScoreHistory()).toHaveLength(100);+ });++ it('should preserve most recent scores when capped', () => {+ const events = [createMockEvent()];++ // First 50 with high violation rate+ for (let i = 0; i < 50; i++) {+ scheduler.computeCoherence(+ createMockMetrics({ violationRate: 8 }),+ events,+ );+ }++ // Next 70 with zero violation rate+ for (let i = 0; i < 70; i++) {+ scheduler.computeCoherence(+ createMockMetrics({ violationRate: 0 }),+ events,+ );+ }++ const history = scheduler.getScoreHistory();+ expect(history).toHaveLength(100);+ // The most recent entries should all have violationComponent = 1+ const last = history[history.length - 1];+ expect(last.violationComponent).toBe(1);+ });+ });++ describe('factory function', () => {+ it('should create a scheduler via createCoherenceScheduler', () => {+ const s = createCoherenceScheduler({ windowSize: 50 });+ expect(s).toBeInstanceOf(CoherenceScheduler);+ });++ it('should create a scheduler with defaults', () => {+ const s = createCoherenceScheduler();+ expect(s).toBeInstanceOf(CoherenceScheduler);+ });+ });+});++// ============================================================================+// EconomicGovernor Tests+// ============================================================================++describe('EconomicGovernor', () => {+ let governor: EconomicGovernor;++ beforeEach(() => {+ governor = new EconomicGovernor({+ tokenLimit: 10_000,+ toolCallLimit: 100,+ storageLimit: 1_000_000,+ timeLimit: 60_000, // 1 minute+ costPerToken: 0.00001,+ costPerToolCall: 0.001,+ costLimit: 1.0,+ });+ });++ describe('recordTokenUsage', () => {+ it('should accumulate token usage', () => {+ governor.recordTokenUsage(500);+ governor.recordTokenUsage(300);++ const usage = governor.getUsageSummary();+ expect(usage.tokens.used).toBe(800);+ expect(usage.tokens.limit).toBe(10_000);+ expect(usage.tokens.percentage).toBeCloseTo(8.0, 1);+ });+ });++ describe('recordToolCall', () => {+ it('should track tool calls', () => {+ governor.recordToolCall('Edit', 150);+ governor.recordToolCall('Read', 50);+ governor.recordToolCall('Bash', 1200);++ const usage = governor.getUsageSummary();+ expect(usage.toolCalls.used).toBe(3);+ expect(usage.toolCalls.limit).toBe(100);+ expect(usage.toolCalls.percentage).toBeCloseTo(3.0, 1);+ });+ });++ describe('recordStorageUsage', () => {+ it('should accumulate storage bytes', () => {+ governor.recordStorageUsage(50_000);+ governor.recordStorageUsage(25_000);++ const usage = governor.getUsageSummary();+ expect(usage.storage.usedBytes).toBe(75_000);+ expect(usage.storage.limitBytes).toBe(1_000_000);+ expect(usage.storage.percentage).toBeCloseTo(7.5, 1);+ });+ });++ describe('checkBudget', () => {+ it('should report within budget when usage is low', () => {+ governor.recordTokenUsage(100);+ governor.recordToolCall('Edit', 50);++ const result = governor.checkBudget();+ expect(result.withinBudget).toBe(true);+ expect(result.alerts).toHaveLength(0);+ });++ it('should emit NOTICE alert at 75% usage', () => {+ governor.recordTokenUsage(7_500); // 75% of 10,000++ const result = governor.checkBudget();+ expect(result.withinBudget).toBe(true);+ expect(result.alerts.some(a => a.includes('NOTICE') && a.includes('tokens'))).toBe(true);+ });++ it('should emit WARNING alert at 90% usage', () => {+ governor.recordTokenUsage(9_000); // 90%++ const result = governor.checkBudget();+ expect(result.withinBudget).toBe(true);+ expect(result.alerts.some(a => a.includes('WARNING') && a.includes('tokens'))).toBe(true);+ });++ it('should emit CRITICAL alert at 95% usage', () => {+ governor.recordTokenUsage(9_500); // 95%++ const result = governor.checkBudget();+ expect(result.withinBudget).toBe(true);+ expect(result.alerts.some(a => a.includes('CRITICAL') && a.includes('tokens'))).toBe(true);+ });++ it('should report budget exceeded at 100%', () => {+ governor.recordTokenUsage(10_001); // Over limit++ const result = governor.checkBudget();+ expect(result.withinBudget).toBe(false);+ expect(result.alerts.some(a => a.includes('BUDGET EXCEEDED') && a.includes('tokens'))).toBe(true);+ });++ it('should generate alerts for multiple dimensions simultaneously', () => {+ governor.recordTokenUsage(9_000); // 90% tokens+ for (let i = 0; i < 95; i++) {+ governor.recordToolCall('Edit', 10); // 95% tool calls+ }++ const result = governor.checkBudget();+ expect(result.alerts.length).toBeGreaterThanOrEqual(2);+ });+ });++ describe('budget alerts', () => {+ it('should include cost alerts when cost exceeds thresholds', () => {+ // costPerToken = 0.00001, costLimit = 1.0+ // Need 75,000 tokens for 75% cost threshold ($0.75)+ governor.recordTokenUsage(75_000);++ const result = governor.checkBudget();+ expect(result.alerts.some(a => a.includes('cost'))).toBe(true);+ });+ });++ describe('getCostEstimate', () => {+ it('should compute cost from token usage', () => {+ governor.recordTokenUsage(1_000); // 1000 * 0.00001 = $0.01++ const estimate = governor.getCostEstimate();+ expect(estimate.totalCost).toBeCloseTo(0.01, 5);+ expect(estimate.breakdown.tokens).toBeCloseTo(0.01, 5);+ });++ it('should compute cost from tool call usage', () => {+ governor.recordToolCall('Edit', 100); // 1 * 0.001 = $0.001++ const estimate = governor.getCostEstimate();+ expect(estimate.breakdown.toolCalls).toBeCloseTo(0.001, 5);+ });++ it('should sum token and tool call costs', () => {+ governor.recordTokenUsage(1_000); // $0.01+ governor.recordToolCall('Edit', 100); // $0.001++ const estimate = governor.getCostEstimate();+ expect(estimate.totalCost).toBeCloseTo(0.011, 5);+ });++ it('should report zero cost with no usage', () => {+ const estimate = governor.getCostEstimate();+ expect(estimate.totalCost).toBe(0);+ expect(estimate.breakdown.tokens).toBe(0);+ expect(estimate.breakdown.toolCalls).toBe(0);+ });+ });++ describe('estimateRemainingCapacity', () => {+ it('should show full capacity at start', () => {+ const remaining = governor.estimateRemainingCapacity();+ expect(remaining.tokensRemaining).toBe(10_000);+ expect(remaining.callsRemaining).toBe(100);+ expect(remaining.timeRemainingMs).toBeLessThanOrEqual(60_000);+ expect(remaining.timeRemainingMs).toBeGreaterThan(59_000);+ });++ it('should decrease remaining tokens after usage', () => {+ governor.recordTokenUsage(4_000);++ const remaining = governor.estimateRemainingCapacity();+ expect(remaining.tokensRemaining).toBe(6_000);+ });++ it('should decrease remaining calls after usage', () => {+ for (let i = 0; i < 30; i++) {+ governor.recordToolCall('Edit', 10);+ }++ const remaining = governor.estimateRemainingCapacity();+ expect(remaining.callsRemaining).toBe(70);+ });++ it('should not go below zero', () => {+ governor.recordTokenUsage(20_000); // way over limit++ const remaining = governor.estimateRemainingCapacity();+ expect(remaining.tokensRemaining).toBe(0);+ });+ });++ describe('resetPeriod', () => {+ it('should reset all counters', () => {+ governor.recordTokenUsage(5_000);+ governor.recordToolCall('Edit', 100);+ governor.recordStorageUsage(500_000);++ governor.resetPeriod();++ const usage = governor.getUsageSummary();+ expect(usage.tokens.used).toBe(0);+ expect(usage.toolCalls.used).toBe(0);+ expect(usage.storage.usedBytes).toBe(0);+ });++ it('should reset cost estimate to zero', () => {+ governor.recordTokenUsage(5_000);+ governor.recordToolCall('Edit', 100);++ governor.resetPeriod();++ const estimate = governor.getCostEstimate();+ expect(estimate.totalCost).toBe(0);+ });++ it('should reset time tracking', () => {+ governor.resetPeriod();++ const usage = governor.getUsageSummary();+ // Time should be near zero since we just reset+ expect(usage.time.usedMs).toBeLessThan(100);+ });++ it('should allow budget to pass again after reset', () => {+ governor.recordTokenUsage(10_001); // Over limit+ expect(governor.checkBudget().withinBudget).toBe(false);++ governor.resetPeriod();+ expect(governor.checkBudget().withinBudget).toBe(true);+ });+ });++ describe('factory function', () => {+ it('should create a governor via createEconomicGovernor', () => {+ const g = createEconomicGovernor({ tokenLimit: 50_000 });+ expect(g).toBeInstanceOf(EconomicGovernor);+ });++ it('should create a governor with defaults', () => {+ const g = createEconomicGovernor();+ expect(g).toBeInstanceOf(EconomicGovernor);++ // Default token limit is 1,000,000+ const usage = g.getUsageSummary();+ expect(usage.tokens.limit).toBe(1_000_000);+ });+ });++ describe('getUsageSummary', () => {+ it('should return complete usage breakdown', () => {+ governor.recordTokenUsage(2_000);+ governor.recordToolCall('Edit', 50);+ governor.recordStorageUsage(100_000);++ const usage = governor.getUsageSummary();++ expect(usage.tokens.used).toBe(2_000);+ expect(usage.tokens.limit).toBe(10_000);+ expect(usage.tokens.percentage).toBeCloseTo(20.0, 1);++ expect(usage.toolCalls.used).toBe(1);+ expect(usage.toolCalls.limit).toBe(100);+ expect(usage.toolCalls.percentage).toBeCloseTo(1.0, 1);++ expect(usage.storage.usedBytes).toBe(100_000);+ expect(usage.storage.limitBytes).toBe(1_000_000);+ expect(usage.storage.percentage).toBeCloseTo(10.0, 1);++ expect(usage.time.limitMs).toBe(60_000);+ expect(usage.time.usedMs).toBeGreaterThanOrEqual(0);++ expect(usage.cost.totalUsd).toBeGreaterThan(0);+ expect(usage.cost.limitUsd).toBe(1.0);+ });+ });+});diff --git a/v3/@claude-flow/guidance/tests/gateway.test.ts b/v3/@claude-flow/guidance/tests/gateway.test.tsnew file mode 100644index 0000000000..679fbb6756--- /dev/null+++ b/v3/@claude-flow/guidance/tests/gateway.test.ts@@ -0,0 +1,650 @@+/**+ * Tests for DeterministicToolGateway+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import {+ DeterministicToolGateway,+ createToolGateway,+} from '../src/gateway.js';+import type {+ ToolSchema,+ Budget,+ GatewayDecision,+} from '../src/gateway.js';++// ============================================================================+// Test Helpers+// ============================================================================++function makeSchema(overrides: Partial<ToolSchema> = {}): ToolSchema {+ return {+ toolName: 'TestTool',+ requiredParams: ['input'],+ optionalParams: ['verbose'],+ paramTypes: { input: 'string', verbose: 'boolean' },+ maxParamSize: 1024,+ ...overrides,+ };+}++function makeBudget(overrides: Partial<Budget> = {}): Budget {+ return {+ tokenBudget: { used: 0, limit: 1000 },+ toolCallBudget: { used: 0, limit: 50 },+ storageBudget: { usedBytes: 0, limitBytes: 1_000_000 },+ timeBudget: { usedMs: 0, limitMs: 60_000 },+ costBudget: { usedUsd: 0, limitUsd: 1.0 },+ ...overrides,+ };+}++// ============================================================================+// Idempotency Tests+// ============================================================================++describe('DeterministicToolGateway - Idempotency', () => {+ let gateway: DeterministicToolGateway;++ beforeEach(() => {+ gateway = new DeterministicToolGateway({+ idempotencyTtlMs: 5000,+ });+ });++ it('should return cached result for identical tool calls', () => {+ const params = { input: 'hello' };++ // First call: evaluate + record+ const firstDecision = gateway.evaluate('TestTool', params);+ expect(firstDecision.allowed).toBe(true);+ expect(firstDecision.idempotencyHit).toBe(false);++ gateway.recordCall('TestTool', params, { output: 'world' }, 100);++ // Second call: should hit cache+ const secondDecision = gateway.evaluate('TestTool', params);+ expect(secondDecision.allowed).toBe(true);+ expect(secondDecision.idempotencyHit).toBe(true);+ expect(secondDecision.cachedResult).toEqual({ output: 'world' });+ });++ it('should not return cached result for different params', () => {+ gateway.recordCall('TestTool', { input: 'a' }, { result: 1 }, 50);++ const decision = gateway.evaluate('TestTool', { input: 'b' });+ expect(decision.idempotencyHit).toBe(false);+ expect(decision.cachedResult).toBeUndefined();+ });++ it('should not return cached result for different tool names', () => {+ gateway.recordCall('ToolA', { input: 'x' }, { result: 1 }, 50);++ const decision = gateway.evaluate('ToolB', { input: 'x' });+ expect(decision.idempotencyHit).toBe(false);+ });++ it('should expire idempotency records after TTL', () => {+ const gateway = new DeterministicToolGateway({+ idempotencyTtlMs: 100,+ });++ gateway.recordCall('TestTool', { input: 'x' }, { result: 1 }, 10);++ // Manually manipulate timestamp to simulate expiration+ const history = gateway.getCallHistory();+ expect(history.length).toBe(1);++ // Alter timestamp to be in the past+ history[0].timestamp = Date.now() - 200;++ // Evaluate should not return cached (record is expired)+ const decision = gateway.evaluate('TestTool', { input: 'x' });+ expect(decision.idempotencyHit).toBe(false);+ });++ it('should list all call history', () => {+ gateway.recordCall('Tool1', { a: 1 }, 'result1', 10);+ gateway.recordCall('Tool2', { b: 2 }, 'result2', 20);+ gateway.recordCall('Tool3', { c: 3 }, 'result3', 30);++ const history = gateway.getCallHistory();+ expect(history.length).toBe(3);+ expect(history.map(h => h.toolName)).toEqual(['Tool1', 'Tool2', 'Tool3']);+ });+});++// ============================================================================+// Idempotency Key Determinism Tests+// ============================================================================++describe('DeterministicToolGateway - Idempotency Key Determinism', () => {+ let gateway: DeterministicToolGateway;++ beforeEach(() => {+ gateway = new DeterministicToolGateway();+ });++ it('should produce the same key for identical inputs', () => {+ const key1 = gateway.getIdempotencyKey('Tool', { a: 1, b: 2 });+ const key2 = gateway.getIdempotencyKey('Tool', { a: 1, b: 2 });+ expect(key1).toBe(key2);+ });++ it('should produce the same key regardless of param order', () => {+ const key1 = gateway.getIdempotencyKey('Tool', { b: 2, a: 1 });+ const key2 = gateway.getIdempotencyKey('Tool', { a: 1, b: 2 });+ expect(key1).toBe(key2);+ });++ it('should produce different keys for different tool names', () => {+ const key1 = gateway.getIdempotencyKey('ToolA', { x: 1 });+ const key2 = gateway.getIdempotencyKey('ToolB', { x: 1 });+ expect(key1).not.toBe(key2);+ });++ it('should produce different keys for different param values', () => {+ const key1 = gateway.getIdempotencyKey('Tool', { x: 1 });+ const key2 = gateway.getIdempotencyKey('Tool', { x: 2 });+ expect(key1).not.toBe(key2);+ });++ it('should produce a 64-character hex string (SHA-256)', () => {+ const key = gateway.getIdempotencyKey('Tool', { foo: 'bar' });+ expect(key).toMatch(/^[a-f0-9]{64}$/);+ });++ it('should handle nested objects deterministically', () => {+ const key1 = gateway.getIdempotencyKey('Tool', {+ nested: { z: 3, a: 1 },+ top: 'value',+ });+ const key2 = gateway.getIdempotencyKey('Tool', {+ top: 'value',+ nested: { a: 1, z: 3 },+ });+ expect(key1).toBe(key2);+ });+});++// ============================================================================+// Schema Validation Tests+// ============================================================================++describe('DeterministicToolGateway - Schema Validation', () => {+ let gateway: DeterministicToolGateway;++ beforeEach(() => {+ gateway = new DeterministicToolGateway({+ schemas: [+ makeSchema(),+ makeSchema({+ toolName: 'TypedTool',+ requiredParams: ['count', 'name', 'enabled'],+ optionalParams: ['tags'],+ paramTypes: {+ count: 'number',+ name: 'string',+ enabled: 'boolean',+ tags: 'array',+ },+ maxParamSize: 512,+ allowedValues: {+ name: ['alice', 'bob', 'charlie'],+ },+ }),+ ],+ });+ });++ it('should accept valid params matching schema', () => {+ const result = gateway.validateSchema('TestTool', {+ input: 'hello',+ verbose: true,+ });+ expect(result.valid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should reject missing required params', () => {+ const result = gateway.validateSchema('TestTool', { verbose: true });+ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Missing required parameter: "input"');+ });++ it('should reject unknown params', () => {+ const result = gateway.validateSchema('TestTool', {+ input: 'hello',+ unknown: 'bad',+ });+ expect(result.valid).toBe(false);+ expect(result.errors).toContain('Unknown parameter: "unknown"');+ });++ it('should reject wrong param types', () => {+ const result = gateway.validateSchema('TestTool', {+ input: 42, // should be string+ });+ expect(result.valid).toBe(false);+ expect(result.errors.some(e => e.includes('"input"') && e.includes('string'))).toBe(true);+ });++ it('should reject params exceeding max size', () => {+ const result = gateway.validateSchema('TestTool', {+ input: 'x'.repeat(2000),+ });+ expect(result.valid).toBe(false);+ expect(result.errors.some(e => e.includes('exceeds limit'))).toBe(true);+ });++ it('should reject values not in allowed list', () => {+ const result = gateway.validateSchema('TypedTool', {+ count: 1,+ name: 'eve', // not in ['alice', 'bob', 'charlie']+ enabled: true,+ });+ expect(result.valid).toBe(false);+ expect(result.errors.some(e => e.includes('"name"') && e.includes('allowed values'))).toBe(true);+ });++ it('should accept values in allowed list', () => {+ const result = gateway.validateSchema('TypedTool', {+ count: 1,+ name: 'alice',+ enabled: true,+ });+ expect(result.valid).toBe(true);+ });++ it('should pass through tools without a registered schema', () => {+ const result = gateway.validateSchema('UnknownTool', { anything: 'goes' });+ expect(result.valid).toBe(true);+ expect(result.errors).toHaveLength(0);+ });++ it('should detect array type correctly', () => {+ const result = gateway.validateSchema('TypedTool', {+ count: 1,+ name: 'alice',+ enabled: true,+ tags: ['a', 'b'],+ });+ expect(result.valid).toBe(true);+ });++ it('should reject array when string is expected', () => {+ const result = gateway.validateSchema('TestTool', {+ input: ['not', 'a', 'string'],+ });+ expect(result.valid).toBe(false);+ expect(result.errors.some(e => e.includes('"input"'))).toBe(true);+ });++ it('should block invalid params through evaluate pipeline', () => {+ const decision = gateway.evaluate('TestTool', { verbose: true });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('schema-validation');+ });+});++// ============================================================================+// Budget Enforcement Tests+// ============================================================================++describe('DeterministicToolGateway - Budget Enforcement', () => {+ it('should allow calls within budget', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget(),+ });++ const decision = gateway.evaluate('TestTool', { input: 'ok' });+ expect(decision.allowed).toBe(true);+ expect(decision.budgetRemaining).toBeDefined();+ });++ it('should block when tool call budget is exceeded', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ toolCallBudget: { used: 51, limit: 50 },+ }),+ });++ const decision = gateway.evaluate('TestTool', { input: 'blocked' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ expect(decision.reason).toContain('Budget exceeded');+ });++ it('should block when token budget is exceeded', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ tokenBudget: { used: 1001, limit: 1000 },+ }),+ });++ const decision = gateway.evaluate('TestTool', { input: 'blocked' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ });++ it('should block when time budget is exceeded', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ timeBudget: { usedMs: 61_000, limitMs: 60_000 },+ }),+ });++ const decision = gateway.evaluate('TestTool', { input: 'blocked' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ expect(decision.reason).toContain('time');+ });++ it('should block when cost budget is exceeded', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ costBudget: { usedUsd: 1.5, limitUsd: 1.0 },+ }),+ });++ const decision = gateway.evaluate('TestTool', { input: 'blocked' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ expect(decision.reason).toContain('cost');+ });++ it('should block when storage budget is exceeded', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ storageBudget: { usedBytes: 2_000_000, limitBytes: 1_000_000 },+ }),+ });++ const decision = gateway.evaluate('TestTool', { input: 'blocked' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ expect(decision.reason).toContain('storage');+ });++ it('should use infinite limits when no budget is specified', () => {+ const gateway = new DeterministicToolGateway();++ const { withinBudget } = gateway.checkBudget();+ expect(withinBudget).toBe(true);+ });+});++// ============================================================================+// Budget Metering Tests+// ============================================================================++describe('DeterministicToolGateway - Budget Metering', () => {+ let gateway: DeterministicToolGateway;++ beforeEach(() => {+ gateway = new DeterministicToolGateway({+ budget: makeBudget(),+ });+ });++ it('should increment tool call count on recordCall', () => {+ gateway.recordCall('Tool', { a: 1 }, 'result', 100);+ const budget = gateway.getBudget();+ expect(budget.toolCallBudget.used).toBe(1);+ });++ it('should accumulate time on recordCall', () => {+ gateway.recordCall('Tool', { a: 1 }, 'r1', 100);+ gateway.recordCall('Tool', { a: 2 }, 'r2', 200);+ const budget = gateway.getBudget();+ expect(budget.timeBudget.usedMs).toBe(300);+ });++ it('should accumulate tokens when provided', () => {+ gateway.recordCall('Tool', { a: 1 }, 'r1', 50, 100);+ gateway.recordCall('Tool', { a: 2 }, 'r2', 50, 200);+ const budget = gateway.getBudget();+ expect(budget.tokenBudget.used).toBe(300);+ });++ it('should not alter token budget when tokenCount is omitted', () => {+ gateway.recordCall('Tool', { a: 1 }, 'r1', 50);+ const budget = gateway.getBudget();+ expect(budget.tokenBudget.used).toBe(0);+ });++ it('should accumulate storage from result size', () => {+ gateway.recordCall('Tool', { a: 1 }, { big: 'x'.repeat(500) }, 10);+ const budget = gateway.getBudget();+ expect(budget.storageBudget.usedBytes).toBeGreaterThan(500);+ });++ it('should estimate cost based on tokens', () => {+ gateway.recordCall('Tool', { a: 1 }, 'result', 100, 1000);+ const budget = gateway.getBudget();+ // 1000 tokens * $0.003/1K = $0.003+ expect(budget.costBudget.usedUsd).toBeCloseTo(0.003, 4);+ });++ it('should reset budget to zero', () => {+ gateway.recordCall('Tool', { a: 1 }, 'r', 100, 500);+ gateway.resetBudget();++ const budget = gateway.getBudget();+ expect(budget.tokenBudget.used).toBe(0);+ expect(budget.toolCallBudget.used).toBe(0);+ expect(budget.storageBudget.usedBytes).toBe(0);+ expect(budget.timeBudget.usedMs).toBe(0);+ expect(budget.costBudget.usedUsd).toBe(0);+ });++ it('should preserve limits after reset', () => {+ gateway.recordCall('Tool', { a: 1 }, 'r', 100, 500);+ gateway.resetBudget();++ const budget = gateway.getBudget();+ expect(budget.tokenBudget.limit).toBe(1000);+ expect(budget.toolCallBudget.limit).toBe(50);+ });++ it('should block after budget is exhausted through metering', () => {+ const tightGateway = new DeterministicToolGateway({+ budget: makeBudget({+ toolCallBudget: { used: 0, limit: 2 },+ }),+ });++ tightGateway.recordCall('T', { a: 1 }, 'r1', 10);+ tightGateway.recordCall('T', { a: 2 }, 'r2', 10);+ tightGateway.recordCall('T', { a: 3 }, 'r3', 10);++ const decision = tightGateway.evaluate('T', { a: 4 });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ });+});++// ============================================================================+// EnforcementGates Integration Tests+// ============================================================================++describe('DeterministicToolGateway - EnforcementGates Integration', () => {+ it('should block destructive commands through context', () => {+ const gateway = new DeterministicToolGateway();++ const decision = gateway.evaluate(+ 'Bash',+ { command: 'rm -rf /' },+ { command: 'rm -rf /' },+ );+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toContain('enforcement');+ });++ it('should block tools not in allowlist', () => {+ const gateway = new DeterministicToolGateway({+ gateConfig: {+ toolAllowlist: true,+ allowedTools: ['Read', 'Write'],+ },+ });++ const decision = gateway.evaluate('Bash', { command: 'ls' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toContain('enforcement:tool-allowlist');+ });++ it('should allow tools in the allowlist', () => {+ const gateway = new DeterministicToolGateway({+ gateConfig: {+ toolAllowlist: true,+ allowedTools: ['Read', 'Write'],+ },+ });++ const decision = gateway.evaluate('Read', { path: '/tmp/file.txt' });+ expect(decision.allowed).toBe(true);+ });++ it('should detect secrets in tool params', () => {+ const gateway = new DeterministicToolGateway();++ const decision = gateway.evaluate('Write', {+ content: 'api_key = "sk-supersecretkey1234567890abcdef"',+ });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toContain('enforcement:secrets');+ });++ it('should allow clean tool params', () => {+ const gateway = new DeterministicToolGateway();++ const decision = gateway.evaluate('Write', {+ content: 'const greeting = "hello world"',+ });+ expect(decision.allowed).toBe(true);+ });++ it('should run schema validation before gates', () => {+ const gateway = new DeterministicToolGateway({+ schemas: [makeSchema()],+ });++ // Missing required param should fail at schema, not gates+ const decision = gateway.evaluate('TestTool', {});+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('schema-validation');+ });++ it('should run budget check before gates', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ toolCallBudget: { used: 100, limit: 50 },+ }),+ gateConfig: {+ toolAllowlist: true,+ allowedTools: ['Read'],+ },+ });++ // Budget exceeded should fail before tool allowlist check+ const decision = gateway.evaluate('Bash', { command: 'ls' });+ expect(decision.allowed).toBe(false);+ expect(decision.gate).toBe('budget');+ });+});++// ============================================================================+// Factory Function Tests+// ============================================================================++describe('createToolGateway', () => {+ it('should create a gateway with default config', () => {+ const gateway = createToolGateway();+ expect(gateway).toBeInstanceOf(DeterministicToolGateway);+ });++ it('should create a gateway with custom config', () => {+ const gateway = createToolGateway({+ schemas: [makeSchema()],+ budget: makeBudget(),+ idempotencyTtlMs: 10_000,+ });+ expect(gateway).toBeInstanceOf(DeterministicToolGateway);++ const budget = gateway.getBudget();+ expect(budget.tokenBudget.limit).toBe(1000);+ });++ it('should return a fully functional gateway', () => {+ const gateway = createToolGateway({+ schemas: [makeSchema()],+ });++ const decision = gateway.evaluate('TestTool', { input: 'valid' });+ expect(decision.allowed).toBe(true);+ expect(decision.idempotencyHit).toBe(false);+ expect(decision.gate).toBe('none');+ });+});++// ============================================================================+// Edge Cases+// ============================================================================++describe('DeterministicToolGateway - Edge Cases', () => {+ it('should handle empty params', () => {+ const gateway = new DeterministicToolGateway();+ const decision = gateway.evaluate('Tool', {});+ expect(decision.allowed).toBe(true);+ });++ it('should handle null-like param values', () => {+ const gateway = new DeterministicToolGateway();+ const decision = gateway.evaluate('Tool', { a: null, b: undefined });+ expect(decision.allowed).toBe(true);+ });++ it('should produce consistent keys with undefined values', () => {+ const gateway = new DeterministicToolGateway();+ // JSON.stringify drops undefined values, so these should match+ const key1 = gateway.getIdempotencyKey('Tool', { a: 1 });+ const key2 = gateway.getIdempotencyKey('Tool', { a: 1, b: undefined });+ expect(key1).toBe(key2);+ });++ it('should return budget remaining on allow', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget(),+ });++ const decision = gateway.evaluate('Tool', { x: 1 });+ expect(decision.allowed).toBe(true);+ expect(decision.budgetRemaining).toBeDefined();+ expect(decision.budgetRemaining!.tokenBudget.limit).toBe(1000);+ });++ it('should return budget remaining on budget rejection', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget({+ toolCallBudget: { used: 100, limit: 50 },+ }),+ });++ const decision = gateway.evaluate('Tool', { x: 1 });+ expect(decision.allowed).toBe(false);+ expect(decision.budgetRemaining).toBeDefined();+ expect(decision.budgetRemaining!.toolCallBudget.used).toBe(100);+ });++ it('should not mutate the budget through getBudget', () => {+ const gateway = new DeterministicToolGateway({+ budget: makeBudget(),+ });++ const budget1 = gateway.getBudget();+ budget1.tokenBudget.used = 999;++ const budget2 = gateway.getBudget();+ expect(budget2.tokenBudget.used).toBe(0);+ });+});diff --git a/v3/@claude-flow/guidance/tests/hooks.test.ts b/v3/@claude-flow/guidance/tests/hooks.test.tsnew file mode 100644index 0000000000..b2bd863c12--- /dev/null+++ b/v3/@claude-flow/guidance/tests/hooks.test.ts@@ -0,0 +1,707 @@+/**+ * Tests for Guidance Hook Integration Layer+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { GuidanceHookProvider, createGuidanceHooks, gateResultsToHookResult } from '../src/hooks.js';+import { EnforcementGates } from '../src/gates.js';+import { ShardRetriever, HashEmbeddingProvider } from '../src/retriever.js';+import { RunLedger } from '../src/ledger.js';+import { HookRegistry } from '@claude-flow/hooks';+import { HookEvent, HookPriority } from '@claude-flow/hooks';+import type { HookContext, HookResult } from '@claude-flow/hooks';+import type { GateResult, RunEvent, PolicyBundle } from '../src/types.js';++// ============================================================================+// Helpers+// ============================================================================++function makeHookContext(overrides: Partial<HookContext> = {}): HookContext {+ return {+ event: HookEvent.PreCommand,+ timestamp: new Date(),+ ...overrides,+ };+}++function makePolicyBundle(): PolicyBundle {+ return {+ constitution: {+ rules: [+ {+ id: 'R001',+ text: 'Never commit secrets',+ riskClass: 'critical',+ toolClasses: ['all'],+ intents: ['security'],+ repoScopes: ['**/*'],+ domains: ['security'],+ priority: 100,+ source: 'root',+ isConstitution: true,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ text: '# Constitution\n\n- Never commit secrets',+ hash: 'test-hash-001',+ },+ shards: [+ {+ rule: {+ id: 'R002',+ text: 'Always run tests before committing',+ riskClass: 'high',+ toolClasses: ['bash'],+ intents: ['testing', 'feature'],+ repoScopes: ['**/*'],+ domains: ['testing'],+ priority: 80,+ source: 'root',+ isConstitution: false,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ compactText: 'Run tests before committing code changes.',+ },+ {+ rule: {+ id: 'R003',+ text: 'Use staged commits for large changes',+ riskClass: 'medium',+ toolClasses: ['edit'],+ intents: ['feature', 'refactor'],+ repoScopes: ['**/*'],+ domains: ['architecture'],+ priority: 50,+ source: 'root',+ isConstitution: false,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ compactText: 'Break large changes into staged commits.',+ },+ ],+ manifest: {+ rules: [],+ compiledAt: Date.now(),+ sourceHashes: {},+ totalRules: 3,+ constitutionRules: 1,+ shardRules: 2,+ },+ };+}++// ============================================================================+// gateResultsToHookResult+// ============================================================================++describe('gateResultsToHookResult', () => {+ it('should return success for empty gate results', () => {+ const result = gateResultsToHookResult([]);+ expect(result.success).toBe(true);+ expect(result.abort).toBeUndefined();+ });++ it('should map block decision to abort', () => {+ const gateResults: GateResult[] = [+ {+ decision: 'block',+ gateName: 'secrets',+ reason: 'Secret detected',+ triggeredRules: ['R001'],+ remediation: 'Remove the secret',+ },+ ];++ const result = gateResultsToHookResult(gateResults);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ expect(result.error).toContain('Secret detected');+ });++ it('should map require-confirmation to abort', () => {+ const gateResults: GateResult[] = [+ {+ decision: 'require-confirmation',+ gateName: 'destructive-ops',+ reason: 'Destructive op detected',+ triggeredRules: [],+ remediation: 'Confirm the operation',+ },+ ];++ const result = gateResultsToHookResult(gateResults);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ expect(result.data).toBeDefined();+ expect((result.data as Record<string, unknown>).gateDecision).toBe('require-confirmation');+ });++ it('should map warn to success with warnings', () => {+ const gateResults: GateResult[] = [+ {+ decision: 'warn',+ gateName: 'diff-size',+ reason: 'Large diff detected',+ triggeredRules: [],+ remediation: 'Stage incrementally',+ },+ ];++ const result = gateResultsToHookResult(gateResults);+ expect(result.success).toBe(true);+ expect(result.abort).toBeUndefined();+ expect(result.warnings).toBeDefined();+ expect(result.warnings!.length).toBeGreaterThan(0);+ });++ it('should pick the most restrictive decision among mixed results', () => {+ const gateResults: GateResult[] = [+ { decision: 'warn', gateName: 'diff-size', reason: 'Large', triggeredRules: [] },+ { decision: 'block', gateName: 'secrets', reason: 'Secret', triggeredRules: [] },+ ];++ const result = gateResultsToHookResult(gateResults);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ expect((result.data as Record<string, unknown>).gateDecision).toBe('block');+ });+});++// ============================================================================+// GuidanceHookProvider - Registration+// ============================================================================++describe('GuidanceHookProvider', () => {+ let gates: EnforcementGates;+ let retriever: ShardRetriever;+ let ledger: RunLedger;+ let registry: HookRegistry;+ let provider: GuidanceHookProvider;++ beforeEach(async () => {+ gates = new EnforcementGates();+ retriever = new ShardRetriever(new HashEmbeddingProvider());+ ledger = new RunLedger();+ registry = new HookRegistry();+ provider = new GuidanceHookProvider(gates, retriever, ledger);++ // Load a bundle so the retriever is functional+ await retriever.loadBundle(makePolicyBundle());+ });++ describe('registerAll', () => {+ it('should register 5 hooks on the registry', () => {+ const ids = provider.registerAll(registry);+ expect(ids).toHaveLength(5);+ expect(registry.size).toBe(5);+ });++ it('should register a hook for PreCommand', () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ expect(hooks.length).toBeGreaterThanOrEqual(1);+ const guidanceHook = hooks.find(h => h.name === 'guidance-gate-pre-command');+ expect(guidanceHook).toBeDefined();+ expect(guidanceHook!.priority).toBe(HookPriority.Critical);+ });++ it('should register a hook for PreToolUse', () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreToolUse);+ const guidanceHook = hooks.find(h => h.name === 'guidance-gate-pre-tool-use');+ expect(guidanceHook).toBeDefined();+ expect(guidanceHook!.priority).toBe(HookPriority.Critical);+ });++ it('should register a hook for PreEdit at High priority', () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreEdit);+ const guidanceHook = hooks.find(h => h.name === 'guidance-gate-pre-edit');+ expect(guidanceHook).toBeDefined();+ expect(guidanceHook!.priority).toBe(HookPriority.High);+ });++ it('should register a hook for PreTask at Normal priority', () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const guidanceHook = hooks.find(h => h.name === 'guidance-retriever-pre-task');+ expect(guidanceHook).toBeDefined();+ expect(guidanceHook!.priority).toBe(HookPriority.Normal);+ });++ it('should register a hook for PostTask at Normal priority', () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PostTask);+ const guidanceHook = hooks.find(h => h.name === 'guidance-ledger-post-task');+ expect(guidanceHook).toBeDefined();+ expect(guidanceHook!.priority).toBe(HookPriority.Normal);+ });+ });++ describe('unregisterAll', () => {+ it('should remove all registered hooks from the registry', () => {+ provider.registerAll(registry);+ expect(registry.size).toBe(5);++ provider.unregisterAll(registry);+ expect(registry.size).toBe(0);+ expect(provider.getHookIds()).toHaveLength(0);+ });+ });++ // ==========================================================================+ // PreCommand hook+ // ==========================================================================++ describe('PreCommand hook', () => {+ it('should block destructive commands', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-command')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreCommand,+ command: { raw: 'rm -rf /' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ expect(result.message).toContain('Destructive operation');+ });++ it('should block git push --force', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-command')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreCommand,+ command: { raw: 'git push origin main --force' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ });++ it('should detect secrets in commands', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-command')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreCommand,+ command: { raw: 'export API_KEY="sk-abc123456789012345678901234567890"' },+ });++ const result = await handler(ctx);+ // Secrets gate fires with 'block'+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ });++ it('should allow safe commands', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-command')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreCommand,+ command: { raw: 'git status' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });++ it('should succeed when no command is provided', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreCommand);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-command')!.handler;++ const ctx = makeHookContext({ event: HookEvent.PreCommand });+ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });+ });++ // ==========================================================================+ // PreToolUse hook+ // ==========================================================================++ describe('PreToolUse hook', () => {+ it('should block non-allowlisted tools when allowlist is enabled', async () => {+ const restrictedGates = new EnforcementGates({+ toolAllowlist: true,+ allowedTools: ['Read', 'Write'],+ });+ const restrictedProvider = new GuidanceHookProvider(restrictedGates, retriever, ledger);+ restrictedProvider.registerAll(registry);++ const hooks = registry.getForEvent(HookEvent.PreToolUse);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-tool-use')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreToolUse,+ tool: { name: 'Bash', parameters: {} },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ });++ it('should detect secrets in tool parameters', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreToolUse);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-tool-use')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreToolUse,+ tool: {+ name: 'Write',+ parameters: {+ content: 'password = "superSecretPassword123"',+ },+ },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ });++ it('should allow safe tool use', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreToolUse);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-tool-use')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreToolUse,+ tool: { name: 'Read', parameters: { path: '/src/main.ts' } },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });++ it('should succeed when no tool info is provided', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreToolUse);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-tool-use')!.handler;++ const ctx = makeHookContext({ event: HookEvent.PreToolUse });+ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });+ });++ // ==========================================================================+ // PreEdit hook+ // ==========================================================================++ describe('PreEdit hook', () => {+ it('should detect secrets in edit content', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreEdit);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-edit')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreEdit,+ file: { path: '/src/config.ts', operation: 'modify' },+ metadata: {+ content: 'const token = "ghp_abcdefghijklmnopqrstuvwxyz1234567890"',+ diffLines: 5,+ },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(false);+ expect(result.abort).toBe(true);+ });++ it('should warn on large diffs', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreEdit);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-edit')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreEdit,+ file: { path: '/src/main.ts', operation: 'modify' },+ metadata: {+ content: 'const foo = "bar"',+ diffLines: 500,+ },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ expect(result.warnings).toBeDefined();+ expect(result.warnings!.length).toBeGreaterThan(0);+ });++ it('should allow clean small edits', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreEdit);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-edit')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreEdit,+ file: { path: '/src/utils.ts', operation: 'modify' },+ metadata: {+ content: 'export const VERSION = "1.0.0"',+ diffLines: 1,+ },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });++ it('should succeed when no file info is provided', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreEdit);+ const handler = hooks.find(h => h.name === 'guidance-gate-pre-edit')!.handler;++ const ctx = makeHookContext({ event: HookEvent.PreEdit });+ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });+ });++ // ==========================================================================+ // PreTask hook+ // ==========================================================================++ describe('PreTask hook', () => {+ it('should retrieve shards and classify intent', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-001', description: 'Fix the authentication bug in login flow' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ expect(result.data).toBeDefined();+ expect((result.data as Record<string, unknown>).intent).toBeDefined();+ expect((result.data as Record<string, unknown>).shardCount).toBeDefined();+ });++ it('should classify intent as bug-fix for bug descriptions', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-002', description: 'Fix broken error handling' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ expect((result.data as Record<string, unknown>).intent).toBe('bug-fix');+ });++ it('should classify intent as security for security descriptions', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-003', description: 'Fix XSS vulnerability in input sanitization' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ expect((result.data as Record<string, unknown>).intent).toBe('security');+ });++ it('should create an active run event for the task', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-004', description: 'Add new feature for user profiles' },+ });++ await handler(ctx);+ const activeRun = provider.getActiveRun('task-004');+ expect(activeRun).toBeDefined();+ expect(activeRun!.taskId).toBe('task-004');+ });++ it('should succeed when task info is missing', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PreTask);+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({ event: HookEvent.PreTask });+ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });++ it('should gracefully handle retriever without a loaded bundle', async () => {+ const emptyRetriever = new ShardRetriever(new HashEmbeddingProvider());+ const emptyProvider = new GuidanceHookProvider(gates, emptyRetriever, ledger);+ emptyProvider.registerAll(registry);++ const hooks = registry.getForEvent(HookEvent.PreTask);+ // Get the one from emptyProvider (last registered for this event)+ const handler = hooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-005', description: 'Implement caching layer' },+ });++ const result = await handler(ctx);+ // Should succeed despite retriever not having a bundle+ expect(result.success).toBe(true);+ });+ });++ // ==========================================================================+ // PostTask hook+ // ==========================================================================++ describe('PostTask hook', () => {+ it('should finalize a previously created run event', async () => {+ provider.registerAll(registry);++ // First trigger PreTask to create the run event+ const preTaskHooks = registry.getForEvent(HookEvent.PreTask);+ const preTaskHandler = preTaskHooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;+ await preTaskHandler(makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-010', description: 'Add user dashboard feature' },+ }));++ // Confirm the run event exists+ expect(provider.getActiveRun('task-010')).toBeDefined();++ // Now trigger PostTask+ const postTaskHooks = registry.getForEvent(HookEvent.PostTask);+ const postTaskHandler = postTaskHooks.find(h => h.name === 'guidance-ledger-post-task')!.handler;+ const result = await postTaskHandler(makeHookContext({+ event: HookEvent.PostTask,+ task: { id: 'task-010', description: 'Add user dashboard feature', status: 'completed' },+ }));++ expect(result.success).toBe(true);+ expect(result.data).toBeDefined();+ expect((result.data as Record<string, unknown>).taskId).toBe('task-010');++ // Active run should be cleaned up+ expect(provider.getActiveRun('task-010')).toBeUndefined();+ });++ it('should record the event in the ledger', async () => {+ provider.registerAll(registry);++ const initialCount = ledger.eventCount;++ // Create run via PreTask+ const preTaskHooks = registry.getForEvent(HookEvent.PreTask);+ const preTaskHandler = preTaskHooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;+ await preTaskHandler(makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-011', description: 'Refactor database module' },+ }));++ // Finalize via PostTask+ const postTaskHooks = registry.getForEvent(HookEvent.PostTask);+ const postTaskHandler = postTaskHooks.find(h => h.name === 'guidance-ledger-post-task')!.handler;+ await postTaskHandler(makeHookContext({+ event: HookEvent.PostTask,+ task: { id: 'task-011', description: 'Refactor database module', status: 'completed' },+ }));++ expect(ledger.eventCount).toBe(initialCount + 1);+ });++ it('should handle PostTask without a matching PreTask gracefully', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PostTask);+ const handler = hooks.find(h => h.name === 'guidance-ledger-post-task')!.handler;++ const ctx = makeHookContext({+ event: HookEvent.PostTask,+ task: { id: 'task-unknown', description: 'Unknown task' },+ });++ const result = await handler(ctx);+ expect(result.success).toBe(true);+ expect(result.message).toContain('No active run event');+ });++ it('should succeed when no task info is provided', async () => {+ provider.registerAll(registry);+ const hooks = registry.getForEvent(HookEvent.PostTask);+ const handler = hooks.find(h => h.name === 'guidance-ledger-post-task')!.handler;++ const ctx = makeHookContext({ event: HookEvent.PostTask });+ const result = await handler(ctx);+ expect(result.success).toBe(true);+ });++ it('should populate metadata from context', async () => {+ provider.registerAll(registry);++ // Create run via PreTask+ const preTaskHooks = registry.getForEvent(HookEvent.PreTask);+ const preTaskHandler = preTaskHooks.find(h => h.name === 'guidance-retriever-pre-task')!.handler;+ await preTaskHandler(makeHookContext({+ event: HookEvent.PreTask,+ task: { id: 'task-012', description: 'Add feature with tools' },+ }));++ // Finalize via PostTask with metadata+ const postTaskHooks = registry.getForEvent(HookEvent.PostTask);+ const postTaskHandler = postTaskHooks.find(h => h.name === 'guidance-ledger-post-task')!.handler;+ await postTaskHandler(makeHookContext({+ event: HookEvent.PostTask,+ task: { id: 'task-012', description: 'Add feature with tools', status: 'completed' },+ metadata: {+ toolsUsed: ['Edit', 'Bash'],+ filesTouched: ['/src/main.ts', '/tests/main.test.ts'],+ },+ }));++ // Verify the event was stored with the metadata+ const events = ledger.getEventsByTask('task-012');+ expect(events.length).toBe(1);+ expect(events[0].toolsUsed).toEqual(['Edit', 'Bash']);+ expect(events[0].filesTouched).toEqual(['/src/main.ts', '/tests/main.test.ts']);+ expect(events[0].outcomeAccepted).toBe(true);+ });+ });++ // ==========================================================================+ // createGuidanceHooks factory+ // ==========================================================================++ describe('createGuidanceHooks', () => {+ it('should create a provider without registering when no registry given', () => {+ const result = createGuidanceHooks(gates, retriever, ledger);+ expect(result.provider).toBeInstanceOf(GuidanceHookProvider);+ expect(result.hookIds).toHaveLength(0);+ });++ it('should create and register when registry is given', () => {+ const result = createGuidanceHooks(gates, retriever, ledger, registry);+ expect(result.provider).toBeInstanceOf(GuidanceHookProvider);+ expect(result.hookIds).toHaveLength(5);+ expect(registry.size).toBe(5);+ });+ });+});diff --git a/v3/@claude-flow/guidance/tests/memory-gate.test.ts b/v3/@claude-flow/guidance/tests/memory-gate.test.tsnew file mode 100644index 0000000000..6357c5330a--- /dev/null+++ b/v3/@claude-flow/guidance/tests/memory-gate.test.ts@@ -0,0 +1,747 @@+/**+ * Tests for Memory Write Gating System+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import {+ MemoryWriteGate,+ createMemoryWriteGate,+ createMemoryEntry,+ type MemoryAuthority,+ type MemoryEntry,+} from '../src/memory-gate.js';++// ============================================================================+// Test Helpers+// ============================================================================++function makeAuthority(overrides: Partial<MemoryAuthority> = {}): MemoryAuthority {+ return {+ agentId: 'agent-1',+ role: 'worker',+ namespaces: ['default', 'shared'],+ maxWritesPerMinute: 60,+ canDelete: false,+ canOverwrite: true,+ trustLevel: 0.8,+ ...overrides,+ };+}++function makeEntry(overrides: Partial<MemoryEntry> = {}): MemoryEntry {+ const authority = makeAuthority();+ return {+ key: 'test-key',+ namespace: 'default',+ value: 'test value',+ valueHash: 'abc123',+ authority,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ ttlMs: null,+ decayRate: 0,+ confidence: 1,+ lineage: { operation: 'create' },+ contradictions: [],+ ...overrides,+ };+}++// ============================================================================+// Authority Check Tests+// ============================================================================++describe('MemoryWriteGate', () => {+ let gate: MemoryWriteGate;++ beforeEach(() => {+ gate = new MemoryWriteGate();+ });++ describe('authority checks', () => {+ it('should allow a worker to write to an allowed namespace', () => {+ const authority = makeAuthority({ role: 'worker', namespaces: ['default'] });+ const decision = gate.evaluateWrite(authority, 'key1', 'default', 'value');++ expect(decision.allowed).toBe(true);+ expect(decision.authorityCheck.passed).toBe(true);+ expect(decision.authorityCheck.actualRole).toBe('worker');+ });++ it('should block a worker writing to a disallowed namespace', () => {+ const authority = makeAuthority({ role: 'worker', namespaces: ['default'] });+ const decision = gate.evaluateWrite(authority, 'key1', 'restricted', 'value');++ expect(decision.allowed).toBe(false);+ expect(decision.authorityCheck.passed).toBe(false);+ });++ it('should block an observer from writing', () => {+ const authority = makeAuthority({ role: 'observer', namespaces: ['default'] });+ const decision = gate.evaluateWrite(authority, 'key1', 'default', 'value');++ expect(decision.allowed).toBe(false);+ expect(decision.authorityCheck.passed).toBe(false);+ expect(decision.authorityCheck.requiredRole).toBe('worker');+ expect(decision.authorityCheck.actualRole).toBe('observer');+ });++ it('should allow a queen to write to any namespace', () => {+ const authority = makeAuthority({ role: 'queen', namespaces: [] });+ const decision = gate.evaluateWrite(authority, 'key1', 'any-namespace', 'value');++ expect(decision.allowed).toBe(true);+ expect(decision.authorityCheck.passed).toBe(true);+ });++ it('should allow a coordinator to write to allowed namespaces', () => {+ const authority = makeAuthority({+ role: 'coordinator',+ namespaces: ['coordination', 'shared'],+ });+ const decision = gate.evaluateWrite(authority, 'key1', 'coordination', 'value');++ expect(decision.allowed).toBe(true);+ expect(decision.authorityCheck.passed).toBe(true);+ });++ it('should block a coordinator writing to disallowed namespace', () => {+ const authority = makeAuthority({+ role: 'coordinator',+ namespaces: ['coordination'],+ });+ const decision = gate.evaluateWrite(authority, 'key1', 'private', 'value');++ expect(decision.allowed).toBe(false);+ expect(decision.authorityCheck.passed).toBe(false);+ });+ });++ // ============================================================================+ // Rate Limiting Tests+ // ============================================================================++ describe('rate limiting', () => {+ it('should allow writes within the rate limit', () => {+ const authority = makeAuthority({ maxWritesPerMinute: 5 });++ for (let i = 0; i < 5; i++) {+ const decision = gate.evaluateWrite(authority, `key-${i}`, 'default', 'value');+ expect(decision.allowed).toBe(true);+ expect(decision.rateCheck.passed).toBe(true);+ }+ });++ it('should block writes exceeding the rate limit', () => {+ const authority = makeAuthority({ maxWritesPerMinute: 3 });++ // Use up the rate limit+ for (let i = 0; i < 3; i++) {+ gate.evaluateWrite(authority, `key-${i}`, 'default', 'value');+ }++ // This should be blocked+ const decision = gate.evaluateWrite(authority, 'key-extra', 'default', 'value');+ expect(decision.allowed).toBe(false);+ expect(decision.rateCheck.passed).toBe(false);+ expect(decision.rateCheck.writesInWindow).toBe(3);+ expect(decision.rateCheck.limit).toBe(3);+ });++ it('should track rate limits per agent independently', () => {+ const authority1 = makeAuthority({ agentId: 'agent-1', maxWritesPerMinute: 2 });+ const authority2 = makeAuthority({ agentId: 'agent-2', maxWritesPerMinute: 2 });++ // Fill up agent-1's limit+ gate.evaluateWrite(authority1, 'key1', 'default', 'value');+ gate.evaluateWrite(authority1, 'key2', 'default', 'value');++ // agent-2 should still be allowed+ const decision = gate.evaluateWrite(authority2, 'key3', 'default', 'value');+ expect(decision.allowed).toBe(true);++ // agent-1 should be blocked+ const blocked = gate.evaluateWrite(authority1, 'key4', 'default', 'value');+ expect(blocked.allowed).toBe(false);+ });++ it('should report rate limit status', () => {+ const authority = makeAuthority({ agentId: 'rate-agent', maxWritesPerMinute: 10 });+ gate.registerAuthority(authority);++ gate.evaluateWrite(authority, 'k1', 'default', 'v');+ gate.evaluateWrite(authority, 'k2', 'default', 'v');++ const status = gate.getRateLimitStatus('rate-agent');+ expect(status.writesInWindow).toBe(2);+ expect(status.limit).toBe(10);+ expect(status.resetAt).toBeGreaterThan(Date.now() - 1000);+ });+ });++ // ============================================================================+ // Overwrite Permission Tests+ // ============================================================================++ describe('overwrite permissions', () => {+ it('should allow overwrite when authority has canOverwrite', () => {+ const authority = makeAuthority({ canOverwrite: true });+ const existing = makeEntry({ key: 'shared-key', namespace: 'default' });++ const decision = gate.evaluateWrite(+ authority,+ 'shared-key',+ 'default',+ 'new value',+ [existing]+ );++ expect(decision.allowed).toBe(true);+ expect(decision.overwriteCheck.isOverwrite).toBe(true);+ expect(decision.overwriteCheck.allowed).toBe(true);+ });++ it('should block overwrite when authority lacks canOverwrite', () => {+ const authority = makeAuthority({ canOverwrite: false });+ const existing = makeEntry({ key: 'shared-key', namespace: 'default' });++ const decision = gate.evaluateWrite(+ authority,+ 'shared-key',+ 'default',+ 'new value',+ [existing]+ );++ expect(decision.allowed).toBe(false);+ expect(decision.overwriteCheck.isOverwrite).toBe(true);+ expect(decision.overwriteCheck.allowed).toBe(false);+ expect(decision.reason).toContain('Overwrite not permitted');+ });++ it('should not flag as overwrite when key does not exist', () => {+ const authority = makeAuthority({ canOverwrite: false });+ const existing = makeEntry({ key: 'other-key', namespace: 'default' });++ const decision = gate.evaluateWrite(+ authority,+ 'new-key',+ 'default',+ 'value',+ [existing]+ );++ expect(decision.overwriteCheck.isOverwrite).toBe(false);+ expect(decision.overwriteCheck.allowed).toBe(true);+ });++ it('should not flag as overwrite when existing entries is empty', () => {+ const authority = makeAuthority({ canOverwrite: false });++ const decision = gate.evaluateWrite(authority, 'key', 'default', 'value', []);++ expect(decision.overwriteCheck.isOverwrite).toBe(false);+ expect(decision.overwriteCheck.allowed).toBe(true);+ });+ });++ // ============================================================================+ // Contradiction Detection Tests+ // ============================================================================++ describe('contradiction detection', () => {+ it('should detect "must" vs "never" contradictions', () => {+ const existing = makeEntry({+ key: 'rule-1',+ value: 'You must always validate inputs',+ });++ const contradictions = gate.detectContradictions(+ 'You should never validate inputs',+ [existing]+ );++ expect(contradictions.length).toBeGreaterThan(0);+ expect(contradictions[0].entryKey).toBe('rule-1');+ });++ it('should detect "always" vs "never" contradictions', () => {+ const existing = makeEntry({+ key: 'rule-2',+ value: 'Always use encryption for data at rest',+ });++ const contradictions = gate.detectContradictions(+ 'Never use encryption for temporary files',+ [existing]+ );++ expect(contradictions.length).toBeGreaterThan(0);+ });++ it('should detect "require" vs "forbid" contradictions', () => {+ const existing = makeEntry({+ key: 'rule-3',+ value: 'We require two-factor authentication',+ });++ const contradictions = gate.detectContradictions(+ 'We forbid two-factor authentication for API keys',+ [existing]+ );++ expect(contradictions.length).toBeGreaterThan(0);+ expect(contradictions[0].description).toContain('require');+ });++ it('should detect "enable" vs "disable" contradictions', () => {+ const existing = makeEntry({+ key: 'config-1',+ value: 'Enable debug logging in production',+ });++ const contradictions = gate.detectContradictions(+ 'Disable debug logging everywhere',+ [existing]+ );++ expect(contradictions.length).toBeGreaterThan(0);+ });++ it('should return empty when no contradictions exist', () => {+ const existing = makeEntry({+ key: 'fact-1',+ value: 'The server runs on port 3000',+ });++ const contradictions = gate.detectContradictions(+ 'The database runs on port 5432',+ [existing]+ );++ expect(contradictions.length).toBe(0);+ });++ it('should include contradictions in write decision', () => {+ const authority = makeAuthority();+ const existing = makeEntry({+ key: 'policy-1',+ namespace: 'default',+ value: 'You must use TypeScript for all new code',+ });++ const decision = gate.evaluateWrite(+ authority,+ 'policy-2',+ 'default',+ 'You should never use TypeScript',+ [existing]+ );++ expect(decision.contradictions.length).toBeGreaterThan(0);+ expect(decision.contradictions[0].existingKey).toBe('policy-1');+ });++ it('should not detect contradictions when tracking is disabled', () => {+ const gateNoTracking = new MemoryWriteGate({+ enableContradictionTracking: false,+ });+ const authority = makeAuthority();+ const existing = makeEntry({+ key: 'rule-x',+ namespace: 'default',+ value: 'You must always do X',+ });++ const decision = gateNoTracking.evaluateWrite(+ authority,+ 'rule-y',+ 'default',+ 'You should never do X',+ [existing]+ );++ expect(decision.contradictions.length).toBe(0);+ });++ it('should detect contradictions across multiple existing entries', () => {+ const entries = [+ makeEntry({ key: 'r1', value: 'Always use strict mode' }),+ makeEntry({ key: 'r2', value: 'Require code reviews' }),+ makeEntry({ key: 'r3', value: 'The sky is blue' }),+ ];++ const contradictions = gate.detectContradictions(+ "Don't use strict mode and forbid code reviews",+ entries+ );++ expect(contradictions.length).toBe(2);+ const keys = contradictions.map((c) => c.entryKey);+ expect(keys).toContain('r1');+ expect(keys).toContain('r2');+ });+ });++ // ============================================================================+ // TTL Expiry Tests+ // ============================================================================++ describe('TTL expiry', () => {+ it('should identify expired entries', () => {+ const now = Date.now();+ const entries = [+ makeEntry({ key: 'expired', createdAt: now - 10_000, ttlMs: 5_000 }),+ makeEntry({ key: 'still-valid', createdAt: now - 1_000, ttlMs: 5_000 }),+ makeEntry({ key: 'no-ttl', createdAt: now - 100_000, ttlMs: null }),+ ];++ const expired = gate.getExpiredEntries(entries);++ expect(expired.length).toBe(1);+ expect(expired[0].key).toBe('expired');+ });++ it('should return empty when no entries are expired', () => {+ const now = Date.now();+ const entries = [+ makeEntry({ key: 'valid-1', createdAt: now, ttlMs: 60_000 }),+ makeEntry({ key: 'valid-2', createdAt: now, ttlMs: null }),+ ];++ const expired = gate.getExpiredEntries(entries);+ expect(expired.length).toBe(0);+ });++ it('should handle all entries expired', () => {+ const now = Date.now();+ const entries = [+ makeEntry({ key: 'old-1', createdAt: now - 20_000, ttlMs: 1_000 }),+ makeEntry({ key: 'old-2', createdAt: now - 30_000, ttlMs: 1_000 }),+ ];++ const expired = gate.getExpiredEntries(entries);+ expect(expired.length).toBe(2);+ });+ });++ // ============================================================================+ // Confidence Decay Tests+ // ============================================================================++ describe('confidence decay', () => {+ it('should return full confidence when decayRate is 0', () => {+ const entry = makeEntry({+ confidence: 0.9,+ decayRate: 0,+ updatedAt: Date.now() - 3_600_000, // 1 hour ago+ });++ const confidence = gate.computeConfidence(entry);+ expect(confidence).toBe(0.9);+ });++ it('should return 0 confidence when decayRate is 1', () => {+ const entry = makeEntry({+ confidence: 1,+ decayRate: 1,+ updatedAt: Date.now() - 1_000, // 1 second ago+ });++ const confidence = gate.computeConfidence(entry);+ expect(confidence).toBe(0);+ });++ it('should decay confidence over time', () => {+ const oneHourAgo = Date.now() - 3_600_000;+ const entry = makeEntry({+ confidence: 1.0,+ decayRate: 0.5,+ updatedAt: oneHourAgo,+ });++ const confidence = gate.computeConfidence(entry);++ // After 1 hour with decayRate 0.5: 1.0 * e^(-0.5 * 1) ~ 0.6065+ expect(confidence).toBeGreaterThan(0.5);+ expect(confidence).toBeLessThan(0.7);+ });++ it('should return near-full confidence for very recent entries', () => {+ const entry = makeEntry({+ confidence: 1.0,+ decayRate: 0.1,+ updatedAt: Date.now() - 100, // 100ms ago+ });++ const confidence = gate.computeConfidence(entry);+ expect(confidence).toBeGreaterThan(0.99);+ });++ it('should identify decayed entries below threshold', () => {+ const twoHoursAgo = Date.now() - 7_200_000;+ const entries = [+ makeEntry({+ key: 'fresh',+ confidence: 1.0,+ decayRate: 0.1,+ updatedAt: Date.now(),+ }),+ makeEntry({+ key: 'decayed',+ confidence: 1.0,+ decayRate: 2.0,+ updatedAt: twoHoursAgo,+ }),+ makeEntry({+ key: 'no-decay',+ confidence: 0.5,+ decayRate: 0,+ updatedAt: twoHoursAgo,+ }),+ ];++ const decayed = gate.getDecayedEntries(entries, 0.3);++ expect(decayed.length).toBe(1);+ expect(decayed[0].key).toBe('decayed');+ });+ });++ // ============================================================================+ // Lineage Tracking Tests+ // ============================================================================++ describe('lineage tracking', () => {+ it('should create entries with lineage via createMemoryEntry', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('derived-key', 'default', 'derived value', authority, {+ lineage: {+ parentKey: 'parent-key',+ derivedFrom: ['source-1', 'source-2'],+ operation: 'merge',+ },+ });++ expect(entry.lineage.parentKey).toBe('parent-key');+ expect(entry.lineage.derivedFrom).toEqual(['source-1', 'source-2']);+ expect(entry.lineage.operation).toBe('merge');+ });++ it('should default lineage operation to "create"', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('new-key', 'default', 'value', authority);++ expect(entry.lineage.operation).toBe('create');+ expect(entry.lineage.parentKey).toBeUndefined();+ expect(entry.lineage.derivedFrom).toBeUndefined();+ });++ it('should preserve lineage through entry creation', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('key', 'ns', { data: 123 }, authority, {+ lineage: {+ derivedFrom: ['a', 'b', 'c'],+ operation: 'aggregate',+ },+ });++ expect(entry.lineage.derivedFrom).toHaveLength(3);+ expect(entry.lineage.operation).toBe('aggregate');+ });+ });++ // ============================================================================+ // Factory Function Tests+ // ============================================================================++ describe('createMemoryWriteGate', () => {+ it('should create a gate with default config', () => {+ const gate = createMemoryWriteGate();+ expect(gate).toBeInstanceOf(MemoryWriteGate);+ expect(gate.isContradictionTrackingEnabled()).toBe(true);+ });++ it('should create a gate with custom config', () => {+ const authority = makeAuthority({ agentId: 'pre-reg' });+ const gate = createMemoryWriteGate({+ authorities: [authority],+ contradictionThreshold: 0.8,+ defaultTtlMs: 30_000,+ defaultDecayRate: 0.1,+ enableContradictionTracking: false,+ });++ expect(gate.isContradictionTrackingEnabled()).toBe(false);+ expect(gate.getDefaultTtlMs()).toBe(30_000);+ expect(gate.getDefaultDecayRate()).toBe(0.1);+ expect(gate.getAuthorityFor('pre-reg')).toBeDefined();+ });+ });++ // ============================================================================+ // Authority Registration Tests+ // ============================================================================++ describe('registerAuthority', () => {+ it('should register and retrieve an authority', () => {+ const authority = makeAuthority({ agentId: 'new-agent' });+ gate.registerAuthority(authority);++ const retrieved = gate.getAuthorityFor('new-agent');+ expect(retrieved).toBeDefined();+ expect(retrieved!.agentId).toBe('new-agent');+ expect(retrieved!.role).toBe('worker');+ });++ it('should update an existing authority', () => {+ const authority1 = makeAuthority({ agentId: 'agent-x', role: 'worker' });+ gate.registerAuthority(authority1);++ const authority2 = makeAuthority({ agentId: 'agent-x', role: 'coordinator' });+ gate.registerAuthority(authority2);++ const retrieved = gate.getAuthorityFor('agent-x');+ expect(retrieved!.role).toBe('coordinator');+ });++ it('should return undefined for unknown agent', () => {+ const retrieved = gate.getAuthorityFor('nonexistent');+ expect(retrieved).toBeUndefined();+ });+ });++ // ============================================================================+ // Contradiction Resolution Tests+ // ============================================================================++ describe('resolveContradiction', () => {+ it('should store and retrieve a resolution', () => {+ gate.resolveContradiction('entry-1', 'Resolved by promoting entry-1 as authoritative');++ const resolution = gate.getContradictionResolution('entry-1');+ expect(resolution).toBe('Resolved by promoting entry-1 as authoritative');+ });++ it('should return undefined for unresolved contradictions', () => {+ const resolution = gate.getContradictionResolution('unresolved-key');+ expect(resolution).toBeUndefined();+ });+ });++ // ============================================================================+ // createMemoryEntry Helper Tests+ // ============================================================================++ describe('createMemoryEntry', () => {+ it('should create an entry with computed value hash', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('k', 'ns', { hello: 'world' }, authority);++ expect(entry.key).toBe('k');+ expect(entry.namespace).toBe('ns');+ expect(entry.value).toEqual({ hello: 'world' });+ expect(entry.valueHash).toBeTruthy();+ expect(entry.valueHash.length).toBe(64); // SHA-256 hex length+ });++ it('should apply TTL and decay options', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('k', 'ns', 'v', authority, {+ ttlMs: 60_000,+ decayRate: 0.3,+ confidence: 0.75,+ });++ expect(entry.ttlMs).toBe(60_000);+ expect(entry.decayRate).toBe(0.3);+ expect(entry.confidence).toBe(0.75);+ });++ it('should default to no TTL, no decay, full confidence', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('k', 'ns', 'v', authority);++ expect(entry.ttlMs).toBeNull();+ expect(entry.decayRate).toBe(0);+ expect(entry.confidence).toBe(1);+ });++ it('should set timestamps close to now', () => {+ const before = Date.now();+ const authority = makeAuthority();+ const entry = createMemoryEntry('k', 'ns', 'v', authority);+ const after = Date.now();++ expect(entry.createdAt).toBeGreaterThanOrEqual(before);+ expect(entry.createdAt).toBeLessThanOrEqual(after);+ expect(entry.updatedAt).toBe(entry.createdAt);+ });++ it('should initialize with empty contradictions', () => {+ const authority = makeAuthority();+ const entry = createMemoryEntry('k', 'ns', 'v', authority);++ expect(entry.contradictions).toEqual([]);+ });++ it('should produce different hashes for different values', () => {+ const authority = makeAuthority();+ const entry1 = createMemoryEntry('k', 'ns', 'value-a', authority);+ const entry2 = createMemoryEntry('k', 'ns', 'value-b', authority);++ expect(entry1.valueHash).not.toBe(entry2.valueHash);+ });+ });++ // ============================================================================+ // Combined Scenarios+ // ============================================================================++ describe('combined write evaluation', () => {+ it('should report multiple failure reasons', () => {+ // Observer trying to overwrite in a wrong namespace+ const authority = makeAuthority({+ role: 'observer',+ namespaces: ['other'],+ canOverwrite: false,+ });+ const existing = makeEntry({ key: 'target', namespace: 'default' });++ const decision = gate.evaluateWrite(+ authority,+ 'target',+ 'default',+ 'new value',+ [existing]+ );++ expect(decision.allowed).toBe(false);+ expect(decision.authorityCheck.passed).toBe(false);+ // The reason should contain failure info+ expect(decision.reason).toContain('Authority check failed');+ });++ it('should allow a fully authorized write with no contradictions', () => {+ const authority = makeAuthority({+ role: 'queen',+ canOverwrite: true,+ maxWritesPerMinute: 100,+ });++ const decision = gate.evaluateWrite(+ authority,+ 'new-fact',+ 'knowledge',+ 'The earth orbits the sun',+ []+ );++ expect(decision.allowed).toBe(true);+ expect(decision.reason).toBe('Write allowed');+ expect(decision.contradictions.length).toBe(0);+ expect(decision.authorityCheck.passed).toBe(true);+ expect(decision.rateCheck.passed).toBe(true);+ expect(decision.overwriteCheck.isOverwrite).toBe(false);+ });+ });+});diff --git a/v3/@claude-flow/guidance/tests/persistence.test.ts b/v3/@claude-flow/guidance/tests/persistence.test.tsnew file mode 100644index 0000000000..5d3503be7f--- /dev/null+++ b/v3/@claude-flow/guidance/tests/persistence.test.ts@@ -0,0 +1,614 @@+/**+ * Tests for Ledger Persistence Layer+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, readFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import {+ PersistentLedger,+ EventStore,+ createPersistentLedger,+ createEventStore,+} from '../src/persistence.js';+import { RunLedger } from '../src/ledger.js';+import type { RunEvent, Violation } from '../src/types.js';++// ============================================================================+// Helpers+// ============================================================================++function createMockEvent(overrides: Partial<RunEvent> = {}): RunEvent {+ return {+ eventId: `evt-${Math.random().toString(36).slice(2, 10)}`,+ taskId: 'task-1',+ guidanceHash: 'abc123',+ retrievedRuleIds: ['R001', 'R002'],+ toolsUsed: ['Read', 'Edit'],+ filesTouched: ['src/main.ts'],+ diffSummary: { linesAdded: 50, linesRemoved: 10, filesChanged: 1 },+ testResults: { ran: true, passed: 10, failed: 0, skipped: 0 },+ violations: [],+ outcomeAccepted: true,+ reworkLines: 5,+ intent: 'feature',+ timestamp: Date.now(),+ durationMs: 3000,+ ...overrides,+ };+}++/**+ * Small delay to allow fire-and-forget async writes to complete.+ */+function tick(ms = 50): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}++// ============================================================================+// EventStore tests+// ============================================================================++describe('EventStore', () => {+ let tempDir: string;+ let store: EventStore;++ beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'guidance-eventstore-'));+ store = createEventStore(tempDir);+ });++ afterEach(async () => {+ await store.releaseLock();+ await rm(tempDir, { recursive: true, force: true });+ });++ describe('directory creation', () => {+ it('should create the storage directory if it does not exist', async () => {+ const nestedDir = join(tempDir, 'nested', 'deep', 'dir');+ const nestedStore = createEventStore(nestedDir);++ const event = createMockEvent();+ await nestedStore.append(event);++ expect(existsSync(nestedDir)).toBe(true);+ const events = await nestedStore.readAll();+ expect(events).toHaveLength(1);+ });+ });++ describe('append and read', () => {+ it('should append an event and read it back', async () => {+ const event = createMockEvent({ taskId: 'task-42' });+ await store.append(event);++ const events = await store.readAll();+ expect(events).toHaveLength(1);+ expect(events[0].taskId).toBe('task-42');+ expect(events[0].eventId).toBe(event.eventId);+ });++ it('should append multiple events preserving order', async () => {+ const e1 = createMockEvent({ taskId: 'task-1', timestamp: 1000 });+ const e2 = createMockEvent({ taskId: 'task-2', timestamp: 2000 });+ const e3 = createMockEvent({ taskId: 'task-3', timestamp: 3000 });++ await store.append(e1);+ await store.append(e2);+ await store.append(e3);++ const events = await store.readAll();+ expect(events).toHaveLength(3);+ expect(events[0].taskId).toBe('task-1');+ expect(events[1].taskId).toBe('task-2');+ expect(events[2].taskId).toBe('task-3');+ });++ it('should return empty array when no events file exists', async () => {+ const events = await store.readAll();+ expect(events).toEqual([]);+ });++ it('should store events as valid NDJSON', async () => {+ const e1 = createMockEvent({ taskId: 'task-a' });+ const e2 = createMockEvent({ taskId: 'task-b' });+ await store.append(e1);+ await store.append(e2);++ const raw = await readFile(join(tempDir, 'events.ndjson'), 'utf-8');+ const lines = raw.trim().split('\n');+ expect(lines).toHaveLength(2);++ // Each line should be valid JSON+ for (const line of lines) {+ expect(() => JSON.parse(line)).not.toThrow();+ }+ });++ it('should skip malformed lines gracefully', async () => {+ const { writeFile: wf } = await import('node:fs/promises');+ const eventsPath = join(tempDir, 'events.ndjson');+ const validEvent = createMockEvent({ taskId: 'valid-task' });+ const content = JSON.stringify(validEvent) + '\n' + 'not-json\n' + '\n';+ await wf(eventsPath, content, 'utf-8');++ const events = await store.readAll();+ expect(events).toHaveLength(1);+ expect(events[0].taskId).toBe('valid-task');+ });+ });++ describe('readRange', () => {+ it('should return events within the specified time range', async () => {+ await store.append(createMockEvent({ taskId: 't1', timestamp: 1000 }));+ await store.append(createMockEvent({ taskId: 't2', timestamp: 2000 }));+ await store.append(createMockEvent({ taskId: 't3', timestamp: 3000 }));+ await store.append(createMockEvent({ taskId: 't4', timestamp: 4000 }));++ const events = await store.readRange(1500, 3500);+ expect(events).toHaveLength(2);+ expect(events.map(e => e.taskId)).toEqual(['t2', 't3']);+ });++ it('should return empty array when no events match range', async () => {+ await store.append(createMockEvent({ timestamp: 1000 }));+ const events = await store.readRange(5000, 6000);+ expect(events).toEqual([]);+ });+ });++ describe('compact', () => {+ it('should evict oldest events when exceeding maxEvents', async () => {+ // Append 10 events with ascending timestamps+ for (let i = 0; i < 10; i++) {+ await store.append(createMockEvent({+ taskId: `task-${i}`,+ timestamp: 1000 + i * 100,+ }));+ }++ const evicted = await store.compact(5);+ expect(evicted).toBe(5);++ const remaining = await store.readAll();+ expect(remaining).toHaveLength(5);+ // The 5 newest (task-5 through task-9) should remain+ expect(remaining[0].taskId).toBe('task-5');+ expect(remaining[4].taskId).toBe('task-9');+ });++ it('should return 0 when no compaction needed', async () => {+ await store.append(createMockEvent());+ await store.append(createMockEvent());++ const evicted = await store.compact(10);+ expect(evicted).toBe(0);+ });++ it('should update the index after compaction', async () => {+ for (let i = 0; i < 5; i++) {+ await store.append(createMockEvent({+ taskId: `task-${i}`,+ timestamp: 1000 + i * 100,+ }));+ }++ await store.compact(2);++ const stats = await store.getStats();+ expect(stats.eventCount).toBe(2);+ expect(stats.oldestEvent).toBe(1300); // task-3+ expect(stats.newestEvent).toBe(1400); // task-4+ });+ });++ describe('getStats', () => {+ it('should return zero stats for empty store', async () => {+ const stats = await store.getStats();+ expect(stats.eventCount).toBe(0);+ expect(stats.storageSizeBytes).toBe(0);+ expect(stats.oldestEvent).toBeNull();+ expect(stats.newestEvent).toBeNull();+ });++ it('should return correct stats after appending events', async () => {+ await store.append(createMockEvent({ timestamp: 1000 }));+ await store.append(createMockEvent({ timestamp: 3000 }));+ await store.append(createMockEvent({ timestamp: 2000 }));++ const stats = await store.getStats();+ expect(stats.eventCount).toBe(3);+ expect(stats.storageSizeBytes).toBeGreaterThan(0);+ expect(stats.oldestEvent).toBe(1000);+ expect(stats.newestEvent).toBe(3000);+ });+ });++ describe('lock file', () => {+ it('should acquire and release lock successfully', async () => {+ await store.acquireLock();+ expect(existsSync(join(tempDir, '.lock'))).toBe(true);++ await store.releaseLock();+ expect(existsSync(join(tempDir, '.lock'))).toBe(false);+ });++ it('should reject concurrent lock acquisition', async () => {+ await store.acquireLock();++ const store2 = createEventStore(tempDir);+ await expect(store2.acquireLock()).rejects.toThrow(/locked/i);++ await store.releaseLock();+ });++ it('should handle stale lock by removing it', async () => {+ // Write a stale lock file (timestamp far in the past)+ const { writeFile: wf } = await import('node:fs/promises');+ const lockData = { holder: 'old-holder', timestamp: Date.now() - 60_000, pid: 99999 };+ await wf(join(tempDir, '.lock'), JSON.stringify(lockData), 'utf-8');++ // Should succeed because the lock is stale+ await store.acquireLock();+ expect(existsSync(join(tempDir, '.lock'))).toBe(true);++ await store.releaseLock();+ });++ it('should only release lock owned by the same holder', async () => {+ await store.acquireLock();++ // A different store instance should not be able to release our lock+ const store2 = createEventStore(tempDir);+ await store2.releaseLock();++ // Lock should still exist since store2 did not own it+ // (store2 has null lockHolder so the holder check will fail, but+ // the fallback best-effort removal may remove it anyway)+ // Release with the actual owner+ await store.releaseLock();+ });++ it('should succeed when releasing without holding a lock', async () => {+ // Should not throw+ await store.releaseLock();+ });+ });++ describe('destroy', () => {+ it('should remove all storage files', async () => {+ await store.append(createMockEvent());+ await store.acquireLock();+ await store.releaseLock();++ // index.json and events.ndjson should exist+ expect(existsSync(join(tempDir, 'events.ndjson'))).toBe(true);+ expect(existsSync(join(tempDir, 'index.json'))).toBe(true);++ await store.destroy();++ expect(existsSync(join(tempDir, 'events.ndjson'))).toBe(false);+ expect(existsSync(join(tempDir, 'index.json'))).toBe(false);+ });+ });+});++// ============================================================================+// PersistentLedger tests+// ============================================================================++describe('PersistentLedger', () => {+ let tempDir: string;+ let ledger: PersistentLedger;++ beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'guidance-persist-'));+ ledger = createPersistentLedger({+ storagePath: tempDir,+ maxEvents: 100,+ compactIntervalMs: 0, // disable auto-compact in tests+ enableWAL: true,+ });+ });++ afterEach(async () => {+ await ledger.destroy();+ await rm(tempDir, { recursive: true, force: true });+ });++ describe('event persistence (log -> save -> load roundtrip)', () => {+ it('should persist events across save/load cycles', async () => {+ ledger.logEvent(createMockEvent({ taskId: 'task-a' }));+ ledger.logEvent(createMockEvent({ taskId: 'task-b' }));++ // Allow async writes to flush+ await tick();++ // Save explicitly+ await ledger.save();++ // Create a fresh ledger pointing to the same storage+ const ledger2 = createPersistentLedger({+ storagePath: tempDir,+ compactIntervalMs: 0,+ });++ await ledger2.load();+ expect(ledger2.eventCount).toBe(2);++ const events = ledger2.getEvents();+ const taskIds = events.map(e => e.taskId);+ expect(taskIds).toContain('task-a');+ expect(taskIds).toContain('task-b');++ await ledger2.destroy();+ });++ it('should persist full event structure accurately', async () => {+ const violations: Violation[] = [+ { ruleId: 'R001', description: 'test violation', severity: 'high', autoCorrected: true },+ ];+ const original = createMockEvent({+ taskId: 'precise-task',+ guidanceHash: 'hash-xyz',+ retrievedRuleIds: ['R001', 'R003'],+ toolsUsed: ['Read', 'Bash', 'Edit'],+ filesTouched: ['src/a.ts', 'src/b.ts'],+ diffSummary: { linesAdded: 100, linesRemoved: 20, filesChanged: 3 },+ testResults: { ran: true, passed: 15, failed: 1, skipped: 2 },+ violations,+ outcomeAccepted: false,+ reworkLines: 42,+ intent: 'refactor',+ timestamp: 1700000000000,+ durationMs: 12345,+ });++ ledger.logEvent(original);+ await tick();+ await ledger.save();++ const ledger2 = createPersistentLedger({ storagePath: tempDir, compactIntervalMs: 0 });+ await ledger2.load();++ const loaded = ledger2.getEvents();+ expect(loaded).toHaveLength(1);++ const evt = loaded[0];+ expect(evt.taskId).toBe('precise-task');+ expect(evt.guidanceHash).toBe('hash-xyz');+ expect(evt.retrievedRuleIds).toEqual(['R001', 'R003']);+ expect(evt.toolsUsed).toEqual(['Read', 'Bash', 'Edit']);+ expect(evt.filesTouched).toEqual(['src/a.ts', 'src/b.ts']);+ expect(evt.diffSummary).toEqual({ linesAdded: 100, linesRemoved: 20, filesChanged: 3 });+ expect(evt.testResults).toEqual({ ran: true, passed: 15, failed: 1, skipped: 2 });+ expect(evt.violations).toHaveLength(1);+ expect(evt.violations[0].ruleId).toBe('R001');+ expect(evt.violations[0].autoCorrected).toBe(true);+ expect(evt.outcomeAccepted).toBe(false);+ expect(evt.reworkLines).toBe(42);+ expect(evt.intent).toBe('refactor');+ expect(evt.timestamp).toBe(1700000000000);+ expect(evt.durationMs).toBe(12345);++ await ledger2.destroy();+ });+ });++ describe('init()', () => {+ it('should load existing events from storage on init', async () => {+ // Write events directly to storage+ const store = createEventStore(tempDir);+ await store.append(createMockEvent({ taskId: 'preexisting-1' }));+ await store.append(createMockEvent({ taskId: 'preexisting-2' }));++ const freshLedger = createPersistentLedger({+ storagePath: tempDir,+ compactIntervalMs: 0,+ });+ await freshLedger.init();++ expect(freshLedger.eventCount).toBe(2);+ const events = freshLedger.getEvents();+ expect(events.map(e => e.taskId)).toContain('preexisting-1');++ await freshLedger.destroy();+ });++ it('should be idempotent', async () => {+ const store = createEventStore(tempDir);+ await store.append(createMockEvent({ taskId: 't1' }));++ await ledger.init();+ await ledger.init(); // second call should be a no-op++ expect(ledger.eventCount).toBe(1);+ });+ });++ describe('logEvent with WAL', () => {+ it('should persist events to storage via fire-and-forget write', async () => {+ ledger.logEvent(createMockEvent({ taskId: 'wal-task' }));++ // Allow async WAL write to complete+ await tick();++ // Read directly from the store to confirm persistence+ const store = createEventStore(tempDir);+ const events = await store.readAll();+ expect(events).toHaveLength(1);+ expect(events[0].taskId).toBe('wal-task');+ });+ });++ describe('compaction', () => {+ it('should evict oldest events and keep maxEvents', async () => {+ const compactLedger = createPersistentLedger({+ storagePath: tempDir,+ maxEvents: 3,+ compactIntervalMs: 0,+ });++ // Log 6 events with increasing timestamps+ for (let i = 0; i < 6; i++) {+ compactLedger.logEvent(createMockEvent({+ taskId: `task-${i}`,+ timestamp: 1000 + i * 100,+ }));+ }+ await tick();+ await compactLedger.save();++ const evicted = await compactLedger.compact();+ expect(evicted).toBe(3);+ expect(compactLedger.eventCount).toBe(3);++ // Should keep the 3 newest: task-3, task-4, task-5+ const events = compactLedger.getEvents();+ const taskIds = events.map(e => e.taskId);+ expect(taskIds).toContain('task-3');+ expect(taskIds).toContain('task-4');+ expect(taskIds).toContain('task-5');+ expect(taskIds).not.toContain('task-0');+ expect(taskIds).not.toContain('task-1');++ await compactLedger.destroy();+ });++ it('should return 0 when no compaction is needed', async () => {+ ledger.logEvent(createMockEvent());+ await tick();+ await ledger.save();++ const evicted = await ledger.compact();+ expect(evicted).toBe(0);+ });+ });++ describe('storage stats', () => {+ it('should return correct stats', async () => {+ ledger.logEvent(createMockEvent({ timestamp: 5000 }));+ ledger.logEvent(createMockEvent({ timestamp: 2000 }));+ ledger.logEvent(createMockEvent({ timestamp: 8000 }));+ await tick();+ await ledger.save();++ const stats = await ledger.getStorageStats();+ expect(stats.eventCount).toBe(3);+ expect(stats.storageSizeBytes).toBeGreaterThan(0);+ expect(stats.oldestEvent).toBe(2000);+ expect(stats.newestEvent).toBe(8000);+ });++ it('should return zero stats for empty ledger', async () => {+ const stats = await ledger.getStorageStats();+ expect(stats.eventCount).toBe(0);+ expect(stats.oldestEvent).toBeNull();+ expect(stats.newestEvent).toBeNull();+ });+ });++ describe('import/export compatibility with base RunLedger', () => {+ it('should export events compatible with base RunLedger.importEvents()', async () => {+ ledger.logEvent(createMockEvent({ taskId: 'compat-1' }));+ ledger.logEvent(createMockEvent({ taskId: 'compat-2' }));+ await tick();++ const exported = ledger.exportEvents();++ const baseLedger = new RunLedger();+ baseLedger.importEvents(exported);++ expect(baseLedger.eventCount).toBe(2);+ const taskIds = baseLedger.getEvents().map(e => e.taskId);+ expect(taskIds).toContain('compat-1');+ expect(taskIds).toContain('compat-2');+ });++ it('should import events from base RunLedger.exportEvents()', async () => {+ const baseLedger = new RunLedger();+ baseLedger.logEvent(createMockEvent({ taskId: 'base-1' }));+ baseLedger.logEvent(createMockEvent({ taskId: 'base-2' }));++ const exported = baseLedger.exportEvents();+ ledger.importEvents(exported);+ await tick();++ expect(ledger.eventCount).toBe(2);++ // Also verify it was persisted+ await ledger.save();+ const ledger2 = createPersistentLedger({ storagePath: tempDir, compactIntervalMs: 0 });+ await ledger2.load();+ expect(ledger2.eventCount).toBe(2);++ await ledger2.destroy();+ });++ it('should support metrics computation after load', async () => {+ const violations: Violation[] = [+ { ruleId: 'R001', description: 'v', severity: 'medium', autoCorrected: false },+ ];+ ledger.logEvent(createMockEvent({ violations, reworkLines: 20 }));+ ledger.logEvent(createMockEvent({ reworkLines: 10 }));+ await tick();+ await ledger.save();++ const ledger2 = createPersistentLedger({ storagePath: tempDir, compactIntervalMs: 0 });+ await ledger2.load();++ const metrics = ledger2.computeMetrics();+ expect(metrics.taskCount).toBe(2);+ expect(metrics.violationRate).toBe(5); // 1 violation / 2 tasks * 10+ expect(metrics.reworkLines).toBe(15); // avg of 20 and 10++ await ledger2.destroy();+ });+ });++ describe('destroy', () => {+ it('should clean up resources without removing storage files', async () => {+ ledger.logEvent(createMockEvent());+ await tick();+ await ledger.save();++ await ledger.destroy();++ // Storage files should still exist (destroy only cleans up runtime resources)+ expect(existsSync(join(tempDir, 'events.ndjson'))).toBe(true);+ });+ });+});++// ============================================================================+// Factory function tests+// ============================================================================++describe('Factory functions', () => {+ let tempDir: string;++ beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'guidance-factory-'));+ });++ afterEach(async () => {+ await rm(tempDir, { recursive: true, force: true });+ });++ it('createPersistentLedger should create a PersistentLedger instance', () => {+ const ledger = createPersistentLedger({ storagePath: tempDir, compactIntervalMs: 0 });+ expect(ledger).toBeInstanceOf(PersistentLedger);+ expect(ledger).toBeInstanceOf(RunLedger);+ });++ it('createEventStore should create an EventStore instance', () => {+ const store = createEventStore(tempDir);+ expect(store).toBeInstanceOf(EventStore);+ });++ it('createPersistentLedger with defaults should use default config', () => {+ const ledger = createPersistentLedger();+ expect(ledger).toBeInstanceOf(PersistentLedger);+ });+});diff --git a/v3/@claude-flow/guidance/tests/proof.test.ts b/v3/@claude-flow/guidance/tests/proof.test.tsnew file mode 100644index 0000000000..f43f9c470a--- /dev/null+++ b/v3/@claude-flow/guidance/tests/proof.test.ts@@ -0,0 +1,576 @@+/**+ * Tests for the Proof Envelope system+ */+import { describe, it, expect, beforeEach } from 'vitest';+import {+ ProofChain,+ createProofChain,+} from '../src/proof.js';+import type {+ ProofEnvelope,+ ToolCallRecord,+ MemoryOperation,+} from '../src/proof.js';+import type { RunEvent } from '../src/types.js';++// ============================================================================+// Helpers+// ============================================================================++function createMockEvent(overrides: Partial<RunEvent> = {}): RunEvent {+ return {+ eventId: `evt-${Math.random().toString(36).slice(2, 8)}`,+ taskId: 'task-1',+ guidanceHash: 'abc123',+ retrievedRuleIds: ['R001', 'R002'],+ toolsUsed: ['Read', 'Edit', 'Bash'],+ filesTouched: ['src/main.ts', 'src/utils.ts'],+ diffSummary: { linesAdded: 50, linesRemoved: 10, filesChanged: 2 },+ testResults: { ran: true, passed: 10, failed: 0, skipped: 1 },+ violations: [],+ outcomeAccepted: true,+ reworkLines: 5,+ intent: 'feature',+ timestamp: Date.now(),+ durationMs: 5000,+ sessionId: 'session-1',+ ...overrides,+ };+}++function createMockToolCall(overrides: Partial<ToolCallRecord> = {}): ToolCallRecord {+ return {+ callId: `call-${Math.random().toString(36).slice(2, 8)}`,+ toolName: 'Edit',+ params: { file_path: '/src/main.ts', old_string: 'foo', new_string: 'bar' },+ result: { success: true },+ timestamp: Date.now(),+ durationMs: 120,+ ...overrides,+ };+}++function createMockMemoryOp(overrides: Partial<MemoryOperation> = {}): MemoryOperation {+ return {+ key: 'agent/status',+ namespace: 'coordination',+ operation: 'write',+ valueHash: 'a'.repeat(64),+ timestamp: Date.now(),+ ...overrides,+ };+}++// ============================================================================+// Tests+// ============================================================================++describe('ProofChain', () => {+ let chain: ProofChain;++ beforeEach(() => {+ chain = createProofChain({ signingKey: 'test-secret-key' });+ });++ // --------------------------------------------------------------------------+ // Genesis envelope+ // --------------------------------------------------------------------------++ describe('genesis envelope', () => {+ it('should create the first envelope with previousHash of all zeros', () => {+ const event = createMockEvent();+ const envelope = chain.append(event);++ expect(envelope.previousHash).toBe('0'.repeat(64));+ });++ it('should set the runEventId to the event ID', () => {+ const event = createMockEvent({ eventId: 'evt-genesis' });+ const envelope = chain.append(event);++ expect(envelope.runEventId).toBe('evt-genesis');+ });++ it('should have a valid ISO 8601 timestamp', () => {+ const event = createMockEvent();+ const envelope = chain.append(event);++ expect(() => new Date(envelope.timestamp)).not.toThrow();+ expect(new Date(envelope.timestamp).toISOString()).toBe(envelope.timestamp);+ });++ it('should have a non-empty content hash', () => {+ const event = createMockEvent();+ const envelope = chain.append(event);++ expect(envelope.contentHash).toMatch(/^[a-f0-9]{64}$/);+ });++ it('should have a non-empty HMAC signature', () => {+ const event = createMockEvent();+ const envelope = chain.append(event);++ expect(envelope.signature).toMatch(/^[a-f0-9]{64}$/);+ });++ it('should produce a unique envelope ID', () => {+ const event = createMockEvent();+ const e1 = chain.append(event);+ const e2 = chain.append(createMockEvent());++ expect(e1.envelopeId).not.toBe(e2.envelopeId);+ });+ });++ // --------------------------------------------------------------------------+ // Hash chaining+ // --------------------------------------------------------------------------++ describe('hash chaining', () => {+ it('should link the second envelope to the first via contentHash', () => {+ const first = chain.append(createMockEvent());+ const second = chain.append(createMockEvent());++ expect(second.previousHash).toBe(first.contentHash);+ });++ it('should form a valid chain across multiple envelopes', () => {+ const envelopes: ProofEnvelope[] = [];+ for (let i = 0; i < 5; i++) {+ envelopes.push(chain.append(createMockEvent()));+ }++ expect(envelopes[0].previousHash).toBe('0'.repeat(64));+ for (let i = 1; i < envelopes.length; i++) {+ expect(envelopes[i].previousHash).toBe(envelopes[i - 1].contentHash);+ }+ });++ it('should produce different content hashes for different events', () => {+ const e1 = chain.append(createMockEvent({ taskId: 'task-a', reworkLines: 0 }));+ const e2 = chain.append(createMockEvent({ taskId: 'task-b', reworkLines: 99 }));++ expect(e1.contentHash).not.toBe(e2.contentHash);+ });+ });++ // --------------------------------------------------------------------------+ // Signature verification+ // --------------------------------------------------------------------------++ describe('signature verification', () => {+ it('should verify a valid envelope', () => {+ const envelope = chain.append(createMockEvent());++ expect(chain.verify(envelope)).toBe(true);+ });++ it('should reject an envelope with a tampered contentHash', () => {+ const envelope = chain.append(createMockEvent());++ // Tamper with the content hash+ const tampered: ProofEnvelope = { ...envelope, contentHash: 'f'.repeat(64) };++ expect(chain.verify(tampered)).toBe(false);+ });++ it('should reject an envelope with a tampered guidanceHash', () => {+ const envelope = chain.append(createMockEvent());++ const tampered: ProofEnvelope = { ...envelope, guidanceHash: 'tampered' };++ expect(chain.verify(tampered)).toBe(false);+ });++ it('should reject an envelope with a tampered metadata field', () => {+ const envelope = chain.append(createMockEvent(), [], [], {+ agentId: 'agent-1',+ sessionId: 'session-1',+ });++ const tampered: ProofEnvelope = {+ ...envelope,+ metadata: { ...envelope.metadata, agentId: 'attacker' },+ };++ expect(chain.verify(tampered)).toBe(false);+ });++ it('should reject an envelope signed with a different key', () => {+ const otherChain = createProofChain({ signingKey: 'other-key' });+ const event = createMockEvent();+ const envelope = otherChain.append(event);++ // Verify with the original chain (different key)+ expect(chain.verify(envelope)).toBe(false);+ });+ });++ // --------------------------------------------------------------------------+ // Full chain verification+ // --------------------------------------------------------------------------++ describe('chain verification', () => {+ it('should verify an empty chain', () => {+ expect(chain.verifyChain()).toBe(true);+ });++ it('should verify a single-envelope chain', () => {+ chain.append(createMockEvent());++ expect(chain.verifyChain()).toBe(true);+ });++ it('should verify a multi-envelope chain', () => {+ for (let i = 0; i < 10; i++) {+ chain.append(createMockEvent());+ }++ expect(chain.verifyChain()).toBe(true);+ });++ it('should detect a broken chain when an envelope signature is tampered', () => {+ chain.append(createMockEvent());+ chain.append(createMockEvent());+ chain.append(createMockEvent());++ // Export, tamper, and reimport+ const serialized = chain.export();+ serialized.envelopes[1].signature = 'bad'.repeat(21) + 'b';++ const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });+ tamperedChain.import(serialized);++ expect(tamperedChain.verifyChain()).toBe(false);+ });++ it('should detect a broken chain when previousHash is tampered', () => {+ chain.append(createMockEvent());+ chain.append(createMockEvent());++ const serialized = chain.export();+ // Tamper with the second envelope's previousHash+ serialized.envelopes[1] = {+ ...serialized.envelopes[1],+ previousHash: 'f'.repeat(64),+ };+ // Re-sign would be needed, but since we tampered the field the+ // signature itself will also fail, which is the desired behavior.++ const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });+ tamperedChain.import(serialized);++ expect(tamperedChain.verifyChain()).toBe(false);+ });++ it('should detect a chain with a wrong genesis hash', () => {+ chain.append(createMockEvent());++ const serialized = chain.export();+ serialized.envelopes[0] = {+ ...serialized.envelopes[0],+ previousHash: 'a'.repeat(64),+ };++ const tamperedChain = createProofChain({ signingKey: 'test-secret-key' });+ tamperedChain.import(serialized);++ expect(tamperedChain.verifyChain()).toBe(false);+ });+ });++ // --------------------------------------------------------------------------+ // Tool call hashing+ // --------------------------------------------------------------------------++ describe('tool call hashing', () => {+ it('should include tool call hashes in the envelope', () => {+ const call1 = createMockToolCall({ callId: 'c1', toolName: 'Read' });+ const call2 = createMockToolCall({ callId: 'c2', toolName: 'Edit' });++ const envelope = chain.append(createMockEvent(), [call1, call2]);++ expect(Object.keys(envelope.toolCallHashes)).toHaveLength(2);+ expect(envelope.toolCallHashes['c1']).toMatch(/^[a-f0-9]{64}$/);+ expect(envelope.toolCallHashes['c2']).toMatch(/^[a-f0-9]{64}$/);+ });++ it('should produce different hashes for different tool calls', () => {+ const call1 = createMockToolCall({+ callId: 'c1',+ toolName: 'Read',+ params: { file: 'a.ts' },+ result: 'content-a',+ });+ const call2 = createMockToolCall({+ callId: 'c2',+ toolName: 'Read',+ params: { file: 'b.ts' },+ result: 'content-b',+ });++ const envelope = chain.append(createMockEvent(), [call1, call2]);++ expect(envelope.toolCallHashes['c1']).not.toBe(envelope.toolCallHashes['c2']);+ });++ it('should produce the same hash for identical tool calls', () => {+ const sharedParams = { file: 'same.ts' };+ const sharedResult = { ok: true };+ const call1 = createMockToolCall({+ callId: 'c1',+ toolName: 'Read',+ params: sharedParams,+ result: sharedResult,+ });+ const call2 = createMockToolCall({+ callId: 'c2',+ toolName: 'Read',+ params: sharedParams,+ result: sharedResult,+ });++ const envelope = chain.append(createMockEvent(), [call1, call2]);++ // Same tool name + params + result => same hash+ expect(envelope.toolCallHashes['c1']).toBe(envelope.toolCallHashes['c2']);+ });++ it('should handle empty tool calls', () => {+ const envelope = chain.append(createMockEvent(), []);++ expect(Object.keys(envelope.toolCallHashes)).toHaveLength(0);+ });+ });++ // --------------------------------------------------------------------------+ // Memory lineage tracking+ // --------------------------------------------------------------------------++ describe('memory lineage tracking', () => {+ it('should include memory operations in the envelope', () => {+ const ops: MemoryOperation[] = [+ createMockMemoryOp({ key: 'status', namespace: 'agent', operation: 'write' }),+ createMockMemoryOp({ key: 'config', namespace: 'system', operation: 'read' }),+ ];++ const envelope = chain.append(createMockEvent(), [], ops);++ expect(envelope.memoryLineage).toHaveLength(2);+ expect(envelope.memoryLineage[0]).toEqual({+ key: 'status',+ namespace: 'agent',+ operation: 'write',+ hash: 'a'.repeat(64),+ });+ expect(envelope.memoryLineage[1]).toEqual({+ key: 'config',+ namespace: 'system',+ operation: 'read',+ hash: 'a'.repeat(64),+ });+ });++ it('should handle all operation types', () => {+ const ops: MemoryOperation[] = [+ createMockMemoryOp({ operation: 'read', valueHash: 'r'.repeat(64) }),+ createMockMemoryOp({ operation: 'write', valueHash: 'w'.repeat(64) }),+ createMockMemoryOp({ operation: 'delete', valueHash: 'd'.repeat(64) }),+ ];++ const envelope = chain.append(createMockEvent(), [], ops);++ expect(envelope.memoryLineage[0].operation).toBe('read');+ expect(envelope.memoryLineage[0].hash).toBe('r'.repeat(64));+ expect(envelope.memoryLineage[1].operation).toBe('write');+ expect(envelope.memoryLineage[1].hash).toBe('w'.repeat(64));+ expect(envelope.memoryLineage[2].operation).toBe('delete');+ expect(envelope.memoryLineage[2].hash).toBe('d'.repeat(64));+ });++ it('should handle empty memory operations', () => {+ const envelope = chain.append(createMockEvent(), [], []);++ expect(envelope.memoryLineage).toHaveLength(0);+ });+ });++ // --------------------------------------------------------------------------+ // Export / Import roundtrip+ // --------------------------------------------------------------------------++ describe('export and import', () => {+ it('should roundtrip a chain through export/import', () => {+ chain.append(createMockEvent({ taskId: 'task-1' }));+ chain.append(createMockEvent({ taskId: 'task-2' }));+ chain.append(createMockEvent({ taskId: 'task-3' }));++ const exported = chain.export();+ expect(exported.envelopes).toHaveLength(3);+ expect(exported.version).toBe(1);+ expect(exported.createdAt).toBeTruthy();++ const restored = createProofChain({ signingKey: 'test-secret-key' });+ restored.import(exported);++ expect(restored.getChainLength()).toBe(3);+ expect(restored.verifyChain()).toBe(true);+ });++ it('should preserve envelope contents through roundtrip', () => {+ const toolCalls = [createMockToolCall({ callId: 'tc-1' })];+ const memOps = [createMockMemoryOp({ key: 'k1', namespace: 'ns1' })];++ const original = chain.append(+ createMockEvent({ eventId: 'evt-rt' }),+ toolCalls,+ memOps,+ { agentId: 'agent-a', sessionId: 'sess-a' },+ );++ const exported = chain.export();+ const restored = createProofChain({ signingKey: 'test-secret-key' });+ restored.import(exported);++ const reimported = restored.getEnvelope(original.envelopeId);+ expect(reimported).toBeDefined();+ expect(reimported!.runEventId).toBe('evt-rt');+ expect(reimported!.toolCallHashes['tc-1']).toBe(original.toolCallHashes['tc-1']);+ expect(reimported!.memoryLineage).toEqual(original.memoryLineage);+ expect(reimported!.metadata.agentId).toBe('agent-a');+ expect(reimported!.signature).toBe(original.signature);+ });++ it('should reject imports with an unsupported version', () => {+ const bad: any = { envelopes: [], createdAt: new Date().toISOString(), version: 999 };++ expect(() => chain.import(bad)).toThrow(/Unsupported proof chain version/);+ });++ it('should replace existing chain on import', () => {+ chain.append(createMockEvent());+ chain.append(createMockEvent());+ expect(chain.getChainLength()).toBe(2);++ const other = createProofChain({ signingKey: 'test-secret-key' });+ other.append(createMockEvent());+ const exported = other.export();++ chain.import(exported);+ expect(chain.getChainLength()).toBe(1);+ });+ });++ // --------------------------------------------------------------------------+ // Retrieval helpers+ // --------------------------------------------------------------------------++ describe('retrieval helpers', () => {+ it('getEnvelope should return undefined for unknown ID', () => {+ expect(chain.getEnvelope('nonexistent')).toBeUndefined();+ });++ it('getEnvelope should find an envelope by ID', () => {+ const envelope = chain.append(createMockEvent());+ const found = chain.getEnvelope(envelope.envelopeId);++ expect(found).toBeDefined();+ expect(found!.envelopeId).toBe(envelope.envelopeId);+ });++ it('getChainTip should return undefined for empty chain', () => {+ expect(chain.getChainTip()).toBeUndefined();+ });++ it('getChainTip should return the latest envelope', () => {+ chain.append(createMockEvent({ taskId: 'first' }));+ const last = chain.append(createMockEvent({ taskId: 'last' }));++ expect(chain.getChainTip()?.envelopeId).toBe(last.envelopeId);+ });++ it('getChainLength should return zero for empty chain', () => {+ expect(chain.getChainLength()).toBe(0);+ });++ it('getChainLength should count all envelopes', () => {+ chain.append(createMockEvent());+ chain.append(createMockEvent());+ chain.append(createMockEvent());++ expect(chain.getChainLength()).toBe(3);+ });+ });++ // --------------------------------------------------------------------------+ // Factory function+ // --------------------------------------------------------------------------++ describe('createProofChain factory', () => {+ it('should create a ProofChain with default key', () => {+ const defaultChain = createProofChain();+ const envelope = defaultChain.append(createMockEvent());++ expect(envelope.signature).toMatch(/^[a-f0-9]{64}$/);+ expect(defaultChain.verify(envelope)).toBe(true);+ });++ it('should create a ProofChain with a custom signing key', () => {+ const customChain = createProofChain({ signingKey: 'my-custom-key' });+ const envelope = customChain.append(createMockEvent());++ expect(customChain.verify(envelope)).toBe(true);++ // A chain with a different key should not verify the same envelope+ const otherChain = createProofChain({ signingKey: 'different-key' });+ expect(otherChain.verify(envelope)).toBe(false);+ });+ });++ // --------------------------------------------------------------------------+ // Guidance hash propagation+ // --------------------------------------------------------------------------++ describe('guidance hash', () => {+ it('should capture the guidanceHash from the RunEvent', () => {+ const event = createMockEvent({ guidanceHash: 'policy-sha256-hash' });+ const envelope = chain.append(event);++ expect(envelope.guidanceHash).toBe('policy-sha256-hash');+ });+ });++ // --------------------------------------------------------------------------+ // Metadata+ // --------------------------------------------------------------------------++ describe('metadata', () => {+ it('should use provided metadata', () => {+ const envelope = chain.append(createMockEvent(), [], [], {+ agentId: 'coder-1',+ sessionId: 'sess-42',+ parentEnvelopeId: 'parent-env-1',+ });++ expect(envelope.metadata.agentId).toBe('coder-1');+ expect(envelope.metadata.sessionId).toBe('sess-42');+ expect(envelope.metadata.parentEnvelopeId).toBe('parent-env-1');+ });++ it('should default to unknown agent and event sessionId', () => {+ const event = createMockEvent({ sessionId: 'from-event' });+ const envelope = chain.append(event);++ expect(envelope.metadata.agentId).toBe('unknown');+ expect(envelope.metadata.sessionId).toBe('from-event');+ });++ it('should default sessionId to unknown when event has none', () => {+ const event = createMockEvent();+ delete (event as any).sessionId;+ const envelope = chain.append(event);++ expect(envelope.metadata.sessionId).toBe('unknown');+ });+ });+});