import { g as getBrainAccessor } from './memory-accessor2-BzlgmY-Z.js';
import { randomBytes } from 'node:crypto';
import './memory-schema-Bi7cChwo.js';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './chunk-DDP5xfzh.js';
import 'node:module';
import './paths-2M_UxD_H.js';
import 'node:fs';
import 'node:path';
import 'node:os';
import 'node:events';
import 'node:diagnostics_channel';
import 'fs';
import 'events';
import 'util';
import 'path';
import 'assert';
import 'worker_threads';
import 'module';
import 'node:url';
import 'url';
import 'buffer';
import 'node:child_process';
import 'node:process';
import 'node:async_hooks';
import './unique-constraint-BM-Apx1H.js';
import './sqlite-Dsbe0wec.js';
import './dual-scope-db-ATrwq0LH.js';
import './conduit-Ca_OFWR_.js';
import './agent-registry-BtE5uhMO.js';
import './nexus-sqlite2-DgTuv9BQ.js';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'constants';
import 'stream';

//#region ../core/dist/agents/execution-learning.js
/**
* Agent Execution Learning — Agent dimension BRAIN integration.
*
* Tracks which agent types succeed or fail on which task types, logs agent
* decisions to brain_decisions with structured context, provides queries to
* retrieve agent performance history, and implements basic self-healing by
* recording failure patterns as brain_observations and surfacing healing
* suggestions when the same failure pattern recurs.
*
* This module bridges the agent registry (tasks.db) with the cognitive
* memory layer (brain.db) without introducing circular dependencies:
* - Tasks.db agent tables: agent_instances, agent_error_log (agent-schema.ts)
* - Brain.db tables: brain_decisions, brain_patterns, brain_observations
*
* All brain.db writes are best-effort — failures are silently swallowed so
* agent lifecycle events never fail due to a brain.db write error.
*
* @module agents/execution-learning
* @task T034
* @epic T029
*/
/** Generate a unique brain_decisions ID with `AGT-` prefix. */
function generateDecisionId() {
	return `AGT-${randomBytes(5).toString("hex")}`;
}
/** Generate a unique brain_patterns ID with `P-agt-` prefix. */
function generatePatternId() {
	return `P-agt-${randomBytes(4).toString("hex")}`;
}
/** Generate a unique brain_observations ID with `O-agt-` prefix. */
function generateObservationId() {
	return `O-agt-${randomBytes(4).toString("hex")}`;
}
/** Normalised ISO timestamp in SQLite-friendly format (space separator). */
function nowSql() {
	return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
}
/**
* Internal implementation that accepts a pre-constructed accessor.
* Separated for testability without touching the real file system.
*
* @internal
*/
async function _recordAgentExecutionWithAccessor(event, brain) {
	const id = generateDecisionId();
	const outcomeMap = {
		success: "success",
		failure: "failure",
		partial: "mixed"
	};
	const decisionText = `Agent type "${event.agentType}" ${event.outcome === "success" ? "successfully completed" : `failed (${event.errorType ?? "unknown"}) on`} task ${event.taskId} (type: ${event.taskType})`;
	const rationale = [
		`Agent: ${event.agentId}`,
		`Task type: ${event.taskType}`,
		`Outcome: ${event.outcome}`,
		event.taskLabels?.length ? `Labels: ${event.taskLabels.join(", ")}` : null,
		event.errorMessage ? `Error: ${event.errorMessage}` : null,
		event.durationMs != null ? `Duration: ${event.durationMs}ms` : null
	].filter(Boolean).join(" | ");
	const alternativesJson = JSON.stringify({
		agentId: event.agentId,
		agentType: event.agentType,
		taskType: event.taskType,
		taskLabels: event.taskLabels ?? [],
		errorType: event.errorType ?? null,
		durationMs: event.durationMs ?? null,
		sessionId: event.sessionId ?? null
	});
	return await brain.addDecision({
		id,
		type: "tactical",
		decision: decisionText,
		rationale,
		confidence: event.outcome === "success" ? "high" : event.outcome === "partial" ? "medium" : "low",
		outcome: outcomeMap[event.outcome],
		alternativesJson,
		contextTaskId: event.taskId,
		contextEpicId: null,
		contextPhase: null,
		createdAt: nowSql(),
		updatedAt: null,
		decisionCategory: "agent_dispatch"
	});
}
/**
* Internal implementation with injected accessor.
*
* @internal
*/
async function _recordFailurePatternWithAccessor(event, brain) {
	const errorType = event.errorType ?? "unknown";
	const patternText = `Agent type "${event.agentType}" fails on task type "${event.taskType}" with ${errorType} error`;
	const contextText = `Failure pattern detected: ${event.agentType} agent encountering ${errorType} errors on ${event.taskType} tasks`;
	const match = (await brain.findPatterns({
		type: "failure",
		limit: 200
	})).find((p) => p.pattern === patternText);
	if (match) {
		const newFrequency = match.frequency + 1;
		const suggestion = buildHealingSuggestion(event.agentType, event.taskType, errorType, newFrequency);
		await brain.updatePattern(match.id, {
			frequency: newFrequency,
			successRate: 0,
			mitigation: suggestion
		});
		return {
			...match,
			frequency: newFrequency,
			successRate: 0,
			mitigation: suggestion
		};
	}
	const id = generatePatternId();
	const now = nowSql();
	const suggestion = buildHealingSuggestion(event.agentType, event.taskType, errorType, 1);
	return brain.addPattern({
		id,
		type: "failure",
		pattern: patternText,
		context: contextText,
		frequency: 1,
		successRate: 0,
		impact: "medium",
		antiPattern: `${event.agentType} assigned to ${event.taskType} task with ${errorType} error risk`,
		mitigation: suggestion,
		examplesJson: JSON.stringify([event.taskId]),
		extractedAt: now,
		updatedAt: null
	});
}
/**
* Internal implementation with injected accessor.
*
* @internal
*/
async function _storeHealingStrategyWithAccessor(event, strategy, brain) {
	const id = generateObservationId();
	const now = nowSql();
	return brain.addObservation({
		id,
		type: "change",
		title: `Healing strategy: ${event.agentType} on ${event.taskType}`,
		subtitle: `Error type: ${event.errorType ?? "unknown"}`,
		narrative: strategy,
		factsJson: JSON.stringify([
			`Agent: ${event.agentType}`,
			`Task type: ${event.taskType}`,
			`Error: ${event.errorMessage ?? "unspecified"}`,
			`Suggested action: ${strategy}`
		]),
		conceptsJson: JSON.stringify([
			"self-healing",
			"agent-execution",
			event.agentType,
			event.taskType
		]),
		project: null,
		filesReadJson: null,
		filesModifiedJson: null,
		sourceSessionId: event.sessionId ?? null,
		sourceType: "agent",
		contentHash: null,
		discoveryTokens: null,
		createdAt: now,
		updatedAt: null
	});
}
/**
* Internal implementation with injected accessor.
*
* @internal
*/
async function _getSelfHealingSuggestionsWithAccessor(agentType, taskType, brain) {
	const patterns = await brain.findPatterns({
		type: "failure",
		limit: 200
	});
	const prefix = `Agent type "${agentType}" fails on task type "${taskType}"`;
	return patterns.filter((p) => p.pattern.startsWith(prefix) && p.mitigation).map((p) => ({
		patternId: p.id,
		failurePattern: p.pattern,
		frequency: p.frequency,
		suggestion: p.mitigation,
		confidence: Math.min(.3 + p.frequency * .1, .9)
	})).sort((a, b) => b.frequency - a.frequency);
}
/**
* Full agent lifecycle event processor.
*
* Convenience function that:
* 1. Records the execution event to brain_decisions
* 2. On failure: records/updates the failure pattern in brain_patterns
* 3. On failure with frequency ≥ 3: stores a healing strategy observation
*
* Returns a structured result with the recorded IDs and any healing
* suggestions that now apply.
*
* All operations are best-effort — the call never throws.
*
* @param event - The execution event
* @param cwd - Working directory
*/
async function processAgentLifecycleEvent(event, cwd) {
	const result = {
		decisionId: null,
		patternId: null,
		observationId: null,
		healingSuggestions: []
	};
	try {
		const brain = await getBrainAccessor(cwd);
		const decision = await _recordAgentExecutionWithAccessor(event, brain);
		if (decision) result.decisionId = decision.id;
		if (event.outcome === "failure") {
			const pattern = await _recordFailurePatternWithAccessor(event, brain);
			if (pattern) {
				result.patternId = pattern.id;
				if (pattern.frequency >= 3 && pattern.mitigation) {
					const obs = await _storeHealingStrategyWithAccessor(event, pattern.mitigation, brain);
					if (obs) result.observationId = obs.id;
				}
			}
		}
		if (event.outcome !== "success") result.healingSuggestions = await _getSelfHealingSuggestionsWithAccessor(event.agentType, event.taskType, brain);
	} catch {}
	return result;
}
/**
* Build a human-readable healing mitigation string for a failure pattern.
*/
function buildHealingSuggestion(agentType, taskType, errorType, frequency) {
	if (errorType === "retriable") return `Retry with exponential backoff. Consider switching to a different ${agentType} agent instance if failures exceed threshold (seen ${frequency}x).`;
	if (errorType === "permanent") return `Reassign task to a different agent type — ${agentType} has a permanent failure on ${taskType} tasks. Check permissions, inputs, and dependencies (seen ${frequency}x).`;
	if (frequency >= 5) return `High-frequency unknown failure (${frequency}x): escalate to orchestrator for manual investigation of ${agentType} on ${taskType} tasks.`;
	return `Unknown failure for ${agentType} on ${taskType} tasks (${frequency}x). Check agent logs, retry with fresh context, or reassign to a different agent type.`;
}

export { processAgentLifecycleEvent };
//# sourceMappingURL=execution-learning-D7yNT9EV.js.map
