"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/cross-agent-learning/index.ts
var cross_agent_learning_exports = {};
__export(cross_agent_learning_exports, {
  CapabilityEmergenceDetector: () => CapabilityEmergenceDetector,
  ContextualPatternExtractor: () => ContextualPatternExtractor,
  ErrorAggregator: () => ErrorAggregator,
  ErrorClassifier: () => ErrorClassifier,
  FixProposer: () => FixProposer,
  FixRecommender: () => FixRecommender,
  ImprovementRolloutOrchestrator: () => ImprovementRolloutOrchestrator,
  InMemoryCustomerSharingPolicyStore: () => InMemoryCustomerSharingPolicyStore,
  InMemoryEmergencePatternStore: () => InMemoryEmergencePatternStore,
  InMemoryErrorEventStore: () => InMemoryErrorEventStore,
  InMemoryErrorSignatureStore: () => InMemoryErrorSignatureStore,
  InMemoryFixProposalStore: () => InMemoryFixProposalStore,
  InMemoryRolloutStore: () => InMemoryRolloutStore,
  LearningMind: () => LearningMind,
  LearningSharer: () => LearningSharer,
  OptInPolicyEnforcer: () => OptInPolicyEnforcer,
  PromptUpdateRecommender: () => PromptUpdateRecommender,
  SkillRecommendationEngine: () => SkillRecommendationEngine,
  SubAgentErrorCapture: () => SubAgentErrorCapture,
  normalizePattern: () => normalizePattern
});
module.exports = __toCommonJS(cross_agent_learning_exports);

// src/cross-agent-learning/error-classifier.ts
var ErrorClassifier = class {
  /**
   * Classifies a single error event by matching message + detail text against
   * known patterns. Returns category and severity; never throws.
   */
  classify(event) {
    const msg = event.message.toLowerCase();
    const detail = stringify(event.detail).toLowerCase();
    const src = (event.sourceComponent ?? "").toLowerCase();
    const combined = `${msg} ${detail} ${src}`;
    return matchSchema(combined) ?? matchConfig(combined) ?? matchToolBug(combined) ?? matchPromptIssue(combined) ?? matchModelLimitation(combined) ?? matchTransient(combined) ?? { category: "transient", severity: "low" };
  }
  classifyAll(events) {
    return events.map((e) => this.classify(e));
  }
};
function matchSchema(text) {
  if (text.includes("schema") || text.includes("zod") || text.includes("validation") || text.includes("parse error") || text.includes("invalid type") || text.includes("required field")) {
    return { category: "schema", severity: "high" };
  }
  return null;
}
function matchConfig(text) {
  if (text.includes("api key") || text.includes("unauthorized") || text.includes("authentication") || text.includes("missing env") || text.includes("config") || text.includes(" 401") || text.includes(" 403") || text.includes("forbidden")) {
    return { category: "config", severity: "high" };
  }
  return null;
}
function matchToolBug(text) {
  if (text.includes("tool") && (text.includes("failed") || text.includes("error") || text.includes("threw")) || text.includes("tool execution") || text.includes("tool_use") || text.includes("mcp error")) {
    return { category: "tool-bug", severity: "medium" };
  }
  return null;
}
function matchPromptIssue(text) {
  if (text.includes("context length") || text.includes("max_tokens") || text.includes("token limit") || text.includes("prompt too long") || text.includes("overloaded") || text.includes("system prompt")) {
    return { category: "prompt-issue", severity: "medium" };
  }
  return null;
}
function matchModelLimitation(text) {
  if (text.includes("model") && (text.includes("not support") || text.includes("capability") || text.includes("cannot") || text.includes("unable to")) || text.includes("model_error") || text.includes("not available")) {
    return { category: "model-limitation", severity: "medium" };
  }
  return null;
}
function matchTransient(text) {
  if (text.includes("rate limit") || text.includes("429") || text.includes("timeout") || text.includes("econnreset") || text.includes("econnrefused") || text.includes("network error") || text.includes(" 502") || text.includes(" 503") || text.includes(" 529") || text.includes("overloaded") || text.includes("retrying")) {
    return { category: "transient", severity: "low" };
  }
  return null;
}
function stringify(value) {
  if (value === null || value === void 0) return "";
  if (typeof value === "string") return value;
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
}

// src/cross-agent-learning/error-aggregator.ts
var import_crypto = require("crypto");
var ErrorAggregator = class {
  constructor(eventStore, signatureStore, classifier, options = {}) {
    this.eventStore = eventStore;
    this.signatureStore = signatureStore;
    this.classifier = classifier;
    this.minOccurrencesForSurface = options.minOccurrencesForSurface ?? 3;
  }
  eventStore;
  signatureStore;
  classifier;
  minOccurrencesForSurface;
  /**
   * Ingests a single ErrorEvent, classifies it, and upserts the corresponding
   * ErrorSignature. Returns the updated (or newly created) signature.
   */
  async ingest(event) {
    const classification = event.category ? { category: event.category, severity: event.severity ?? "low" } : this.classifier.classify(event);
    const classified = {
      ...event,
      category: classification.category,
      severity: classification.severity
    };
    const pattern = normalizePattern(event.message);
    const existing = await this.signatureStore.getByPattern(pattern);
    const now = /* @__PURE__ */ new Date();
    let deploymentCount = 1;
    let operatorCount = 1;
    if (existing) {
      const pastEvents = await this.eventStore.listBySignature(existing.id, 1e3);
      const deployments = new Set(pastEvents.map((e) => e.deploymentId));
      deployments.add(event.deploymentId);
      deploymentCount = deployments.size;
      const operators = new Set(pastEvents.map((e) => e.operatorId));
      operators.add(event.operatorId);
      operatorCount = operators.size;
    }
    const updated = {
      id: existing?.id ?? (0, import_crypto.randomUUID)(),
      pattern,
      category: classification.category,
      severity: classification.severity,
      sourceComponent: event.sourceComponent ?? existing?.sourceComponent,
      occurrenceCount: (existing?.occurrenceCount ?? 0) + 1,
      deploymentCount,
      operatorCount,
      firstSeenAt: existing?.firstSeenAt ?? now,
      lastSeenAt: now
    };
    const signature = await this.signatureStore.upsert(updated);
    await this.eventStore.append({ ...classified, signatureId: signature.id });
    return signature;
  }
  /**
   * Ingests multiple events in sequence. Returns all updated signatures.
   * Useful for batch backfill from an existing error log.
   */
  async ingestBatch(events) {
    const signatures = [];
    for (const event of events) {
      signatures.push(await this.ingest(event));
    }
    return signatures;
  }
  /** Returns the most frequent error signatures above the surface threshold. */
  async listTopErrors() {
    return this.signatureStore.listByFrequency(this.minOccurrencesForSurface);
  }
};
function normalizePattern(message) {
  return message.replace(
    /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,
    "<uuid>"
  ).replace(/\b\d{4}-\d{2}-\d{2}T[\d:.Z+-]+/g, "<timestamp>").replace(/["'][^"']{20,}["']/g, "<string>").replace(/\b0x[0-9a-f]+\b/gi, "<hex>").replace(/\b\d+\b/g, "<n>").replace(/\s+/g, " ").trim().slice(0, 250);
}

// src/cross-agent-learning/fix-proposer.ts
var FixProposer = class {
  constructor(anthropic, signatureStore, eventStore, proposalStore, options = {}) {
    this.anthropic = anthropic;
    this.signatureStore = signatureStore;
    this.eventStore = eventStore;
    this.proposalStore = proposalStore;
    this.model = options.model ?? "claude-haiku-4-5-20251001";
    this.maxTokens = options.maxTokens ?? 1024;
    this.minOccurrences = options.minOccurrencesForProposal ?? 5;
  }
  anthropic;
  signatureStore;
  eventStore;
  proposalStore;
  model;
  maxTokens;
  minOccurrences;
  /**
   * Scans all signatures above the recurrence threshold and drafts fix proposals
   * for those that don't yet have a pending or approved proposal.
   * Returns the newly created proposals.
   */
  async proposeFixesForTopErrors() {
    const signatures = await this.signatureStore.listByFrequency(
      this.minOccurrences
    );
    const proposals = [];
    for (const sig of signatures) {
      const existing = await this.proposalStore.listBySignature(sig.id);
      const hasActive = existing.some(
        (p) => p.status === "DRAFT" || p.status === "APPROVED"
      );
      if (hasActive) continue;
      const examples = await this.eventStore.listBySignature(sig.id, 3);
      proposals.push(await this.draftProposal(sig, examples));
    }
    return proposals;
  }
  /**
   * Drafts a fix proposal for a specific signature, using up to `examples` for
   * context. Returns the stored FixProposal in DRAFT status.
   */
  async draftProposal(sig, examples) {
    const { summary, proposedChange } = await this.callClaude(sig, examples);
    return this.proposalStore.create({
      signatureId: sig.id,
      summary,
      proposedChange,
      requiresApproval: true,
      status: "DRAFT",
      confidence: computeConfidence(sig)
    });
  }
  async callClaude(sig, examples) {
    const exampleText = examples.map(
      (e) => `- [${e.deploymentId}] ${e.message}` + (e.conversationContext ? `
  Context: ${e.conversationContext}` : "")
    ).join("\n");
    const prompt = `You are a senior AI systems engineer reviewing recurring errors in a multi-tenant AI agent platform.

## Error Signature
Category: ${sig.category}
Severity: ${sig.severity}
Occurrences: ${sig.occurrenceCount} across ${sig.deploymentCount} deployments, ${sig.operatorCount} operators
Pattern: ${sig.pattern}
Source component: ${sig.sourceComponent ?? "unknown"}

## Example Occurrences
${exampleText || "(none available)"}

## Task
Produce two outputs separated by the delimiter "---CHANGE---":

**Part 1 \u2014 Summary (1\u20132 sentences)**
What is causing this error and what class of fix resolves it?

**Part 2 \u2014 Proposed Change (Markdown)**
Concrete, actionable fix description. May be a config change, prompt update, code pattern correction, retry strategy, or documentation update. Be specific about what to change and where. Note any ambiguity.

Respond with Part 1, then the literal line "---CHANGE---", then Part 2. No preamble.`;
    const response = await this.anthropic.messages.create({
      model: this.model,
      max_tokens: this.maxTokens,
      messages: [{ role: "user", content: prompt }]
    });
    const firstBlock = response.content[0];
    const raw = firstBlock !== void 0 && firstBlock.type === "text" ? firstBlock.text : "";
    const delimiter = "---CHANGE---";
    const idx = raw.indexOf(delimiter);
    if (idx === -1) {
      return {
        summary: `Recurring ${sig.category} error: ${sig.pattern.slice(0, 100)}`,
        proposedChange: raw.trim()
      };
    }
    return {
      summary: raw.slice(0, idx).trim(),
      proposedChange: raw.slice(idx + delimiter.length).trim()
    };
  }
};
function computeConfidence(sig) {
  const occurrenceFactor = Math.min(sig.occurrenceCount / 50, 1);
  const deploymentFactor = Math.min(sig.deploymentCount / 5, 1);
  return Math.round((occurrenceFactor * 0.6 + deploymentFactor * 0.4) * 100) / 100;
}

// src/cross-agent-learning/capability-emergence-detector.ts
var CapabilityEmergenceDetector = class {
  constructor(anthropic, patternStore, options = {}) {
    this.anthropic = anthropic;
    this.patternStore = patternStore;
    this.model = options.model ?? "claude-sonnet-4-6";
    this.maxTokens = options.maxTokens ?? 2048;
    this.minDeployments = options.minDeploymentsForPattern ?? 2;
    this.batchSize = options.excerptBatchSize ?? 20;
  }
  anthropic;
  patternStore;
  model;
  maxTokens;
  minDeployments;
  batchSize;
  /**
   * Analyses a batch of conversation excerpts for unmet capability signals.
   * Clusters signals into CapabilityEmergencePatterns, merges with existing
   * patterns, and returns all affected patterns (new + updated).
   */
  async analyzeConversations(excerpts) {
    if (excerpts.length === 0) return [];
    const allSignals = [];
    for (let i = 0; i < excerpts.length; i += this.batchSize) {
      const batch = excerpts.slice(i, i + this.batchSize);
      const signals = await this.extractSignals(batch);
      allSignals.push(...signals);
    }
    if (allSignals.length === 0) return [];
    const deploymentToOperator = new Map(
      excerpts.map((e) => [e.deploymentId, e.operatorId])
    );
    const clusters = clusterSignals(allSignals, deploymentToOperator);
    const saved = [];
    for (const cluster of clusters) {
      if (cluster.deploymentCount < this.minDeployments) continue;
      const existing = await this.findSimilarPattern(cluster.capabilityLabel);
      if (existing) {
        const merged = await this.patternStore.update(existing.id, {
          eventCount: existing.eventCount + cluster.eventCount,
          deploymentCount: Math.max(
            existing.deploymentCount,
            cluster.deploymentCount
          ),
          operatorCount: Math.max(
            existing.operatorCount,
            cluster.operatorCount
          ),
          evidenceExcerpts: [
            ...existing.evidenceExcerpts,
            ...cluster.evidenceExcerpts
          ].slice(0, 10),
          confidence: computePatternConfidence(
            existing.eventCount + cluster.eventCount,
            Math.max(existing.deploymentCount, cluster.deploymentCount)
          ),
          lastUpdatedAt: /* @__PURE__ */ new Date()
        });
        saved.push(merged);
      } else {
        const created = await this.patternStore.create({
          capabilityLabel: cluster.capabilityLabel,
          evidenceExcerpts: cluster.evidenceExcerpts.slice(0, 10),
          deploymentCount: cluster.deploymentCount,
          operatorCount: cluster.operatorCount,
          eventCount: cluster.eventCount,
          confidence: computePatternConfidence(
            cluster.eventCount,
            cluster.deploymentCount
          ),
          status: "DETECTED"
        });
        saved.push(created);
      }
    }
    return saved;
  }
  async extractSignals(excerpts) {
    const excerptText = excerpts.map(
      (e) => `[deployment:${e.deploymentId}] ${e.userMessage}` + (e.agentResponse ? `
Agent: ${e.agentResponse.slice(0, 300)}` : "")
    ).join("\n\n---\n\n");
    const prompt = `You are analysing conversation excerpts from AI agent deployments to detect unmet capability needs.

Look for user messages where the agent:
- Was unable to do something the user requested
- Said "I can't" / "I don't have access to" / "I'm not able to" / "that's not something I can"
- Gave a partial answer that clearly didn't address the full user need
- Misunderstood the same type of request more than once

Return a JSON array (no markdown fences) of objects with shape:
{ "capabilitySignal": string, "deploymentId": string, "excerpt": string }

Where "capabilitySignal" is a 3\u20138 word label describing the missing capability.
Return [] if none detected.

## Conversation excerpts
${excerptText}`;
    const response = await this.anthropic.messages.create({
      model: this.model,
      max_tokens: this.maxTokens,
      messages: [{ role: "user", content: prompt }]
    });
    const firstBlock = response.content[0];
    const raw = firstBlock !== void 0 && firstBlock.type === "text" ? firstBlock.text : "[]";
    try {
      const parsed = JSON.parse(raw);
      if (!Array.isArray(parsed)) return [];
      return parsed;
    } catch {
      return [];
    }
  }
  async findSimilarPattern(label) {
    const patterns = await this.patternStore.listByConfidence(0);
    const normalized = label.toLowerCase();
    return patterns.find((p) => {
      const existing = p.capabilityLabel.toLowerCase();
      return existing.includes(normalized) || normalized.includes(existing);
    }) ?? null;
  }
};
function clusterSignals(signals, deploymentToOperator) {
  const clusterMap = /* @__PURE__ */ new Map();
  for (const sig of signals) {
    const key = sig.capabilitySignal.toLowerCase().replace(/\s+/g, " ").trim();
    if (!clusterMap.has(key)) {
      clusterMap.set(key, {
        deployments: /* @__PURE__ */ new Set(),
        operators: /* @__PURE__ */ new Set(),
        excerpts: [],
        count: 0
      });
    }
    const cluster = clusterMap.get(key);
    cluster.deployments.add(sig.deploymentId);
    const operatorId = deploymentToOperator.get(sig.deploymentId);
    if (operatorId) cluster.operators.add(operatorId);
    if (sig.excerpt) cluster.excerpts.push(sig.excerpt);
    cluster.count++;
  }
  return Array.from(clusterMap.entries()).map(([label, data]) => ({
    capabilityLabel: label,
    evidenceExcerpts: data.excerpts,
    deploymentCount: data.deployments.size,
    operatorCount: data.operators.size,
    eventCount: data.count
  }));
}
function computePatternConfidence(eventCount, deploymentCount) {
  const eventFactor = Math.min(eventCount / 20, 1);
  const deploymentFactor = Math.min(deploymentCount / 5, 1);
  return Math.round((eventFactor * 0.5 + deploymentFactor * 0.5) * 100) / 100;
}

// src/cross-agent-learning/skill-recommendation-engine.ts
var import_crypto2 = require("crypto");
var SkillRecommendationEngine = class {
  constructor(patternStore, anthropic, options = {}) {
    this.patternStore = patternStore;
    this.anthropic = anthropic;
    this.model = options.model ?? "claude-haiku-4-5-20251001";
    this.minConfidence = options.minConfidence ?? 0.3;
  }
  patternStore;
  anthropic;
  model;
  minConfidence;
  /**
   * Generates and ranks SkillRecommendations from detected emergence patterns.
   * Results are sorted by demand score, highest first.
   *
   * If an Anthropic client was provided, Claude derives the skill name,
   * rationale, and suggested module path. Otherwise, the pattern label is
   * used directly — useful for testing without API access.
   */
  async generateRecommendations() {
    const patterns = await this.patternStore.listByConfidence(this.minConfidence);
    const eligible = patterns.filter(
      (p) => p.status === "DETECTED" || p.status === "PROPOSED"
    );
    const recommendations = await Promise.all(
      eligible.map(async (pattern) => {
        const demandScore = computeDemandScore(pattern);
        const spec = await this.deriveSkillSpec(pattern);
        return {
          id: (0, import_crypto2.randomUUID)(),
          patternId: pattern.id,
          skillName: spec.skillName,
          rationale: spec.rationale,
          demandScore,
          suggestedModulePath: spec.suggestedModulePath,
          rankedAt: /* @__PURE__ */ new Date()
        };
      })
    );
    recommendations.sort((a, b) => b.demandScore - a.demandScore);
    return recommendations;
  }
  async deriveSkillSpec(pattern) {
    if (!this.anthropic) {
      return {
        skillName: pattern.capabilityLabel,
        rationale: `${pattern.deploymentCount} deployments, ${pattern.operatorCount} operators requesting: ${pattern.capabilityLabel}`
      };
    }
    const excerptText = pattern.evidenceExcerpts.slice(0, 5).join("\n- ");
    const prompt = `You are designing new capabilities for an AI agent framework (agent-kit).

The following unmet capability need has been detected across ${pattern.deploymentCount} deployments and ${pattern.operatorCount} operators:

**Pattern:** ${pattern.capabilityLabel}
**Evidence excerpts:**
- ${excerptText}

Produce three fields as JSON (no markdown fences):
{
  "skillName": "3\u20136 word skill name, kebab-case, suitable for a module path",
  "rationale": "1\u20132 sentences explaining what this skill does and why the demand signal is strong",
  "suggestedModulePath": "src/<module-name>/ (under the agent-kit src/ tree)"
}`;
    const response = await this.anthropic.messages.create({
      model: this.model,
      max_tokens: 256,
      messages: [{ role: "user", content: prompt }]
    });
    const firstBlock = response.content[0];
    const raw = firstBlock !== void 0 && firstBlock.type === "text" ? firstBlock.text : "{}";
    try {
      const parsed = JSON.parse(raw);
      return {
        skillName: parsed.skillName ?? pattern.capabilityLabel,
        rationale: parsed.rationale ?? `${pattern.deploymentCount} deployments requesting: ${pattern.capabilityLabel}`,
        suggestedModulePath: parsed.suggestedModulePath
      };
    } catch {
      return {
        skillName: pattern.capabilityLabel,
        rationale: `${pattern.deploymentCount} deployments requesting: ${pattern.capabilityLabel}`
      };
    }
  }
};
function computeDemandScore(pattern) {
  return Math.round(
    pattern.eventCount * pattern.deploymentCount * pattern.confidence * 100
  ) / 100;
}

// src/cross-agent-learning/improvement-rollout-orchestrator.ts
var ImprovementRolloutOrchestrator = class {
  constructor(rolloutStore, fixProposalStore, patternStore) {
    this.rolloutStore = rolloutStore;
    this.fixProposalStore = fixProposalStore;
    this.patternStore = patternStore;
  }
  rolloutStore;
  fixProposalStore;
  patternStore;
  /**
   * Initiates a staged rollout for an approved FixProposal.
   * Throws if the proposal is not in APPROVED status.
   */
  async initiateFixRollout(proposalId, allDeploymentIds, options = {}) {
    const proposal = await this.fixProposalStore.get(proposalId);
    if (!proposal) throw new Error(`FixProposal not found: ${proposalId}`);
    if (proposal.status !== "APPROVED") {
      throw new Error(
        `FixProposal ${proposalId} is not approved (status: ${proposal.status})`
      );
    }
    const rollout = await this.createRollout(
      proposalId,
      "fix",
      allDeploymentIds,
      options
    );
    await this.fixProposalStore.update(proposalId, { status: "DEPLOYED" });
    return rollout;
  }
  /**
   * Initiates a staged rollout for an approved CapabilityEmergencePattern.
   * Throws if the pattern is not in APPROVED status.
   */
  async initiateCapabilityRollout(patternId, allDeploymentIds, options = {}) {
    const pattern = await this.patternStore.get(patternId);
    if (!pattern) throw new Error(`EmergencePattern not found: ${patternId}`);
    if (pattern.status !== "APPROVED") {
      throw new Error(
        `EmergencePattern ${patternId} is not approved (status: ${pattern.status})`
      );
    }
    const rollout = await this.createRollout(
      patternId,
      "capability",
      allDeploymentIds,
      options
    );
    await this.patternStore.update(patternId, { status: "SHIPPED" });
    return rollout;
  }
  /**
   * Marks the current in-progress stage as COMPLETED (attaching telemetry)
   * and starts the next stage. If all stages complete, sets overallStatus to
   * COMPLETED.
   *
   * Callers are expected to pass telemetrySummary as evidence that the stage
   * was successful before advancing.
   */
  async advanceStage(rolloutId, telemetrySummary) {
    const rollout = await this.rolloutStore.get(rolloutId);
    if (!rollout) throw new Error(`Rollout not found: ${rolloutId}`);
    const inProgressIndex = rollout.stages.findIndex(
      (s) => s.status === "IN_PROGRESS"
    );
    if (inProgressIndex === -1) {
      throw new Error(
        `No stage in progress for rollout ${rolloutId}. Current status: ${rollout.overallStatus}`
      );
    }
    const now = /* @__PURE__ */ new Date();
    const updatedStages = rollout.stages.map((s, i) => {
      if (i === inProgressIndex) {
        return { ...s, status: "COMPLETED", completedAt: now, telemetrySummary };
      }
      if (i === inProgressIndex + 1) {
        return { ...s, status: "IN_PROGRESS", startedAt: now };
      }
      return s;
    });
    const allComplete = updatedStages.every((s) => s.status === "COMPLETED");
    return this.rolloutStore.update(rolloutId, {
      stages: updatedStages,
      overallStatus: allComplete ? "COMPLETED" : "IN_PROGRESS",
      updatedAt: now
    });
  }
  /** Pauses an in-progress rollout. Resume by calling advanceStage again. */
  async pauseRollout(rolloutId) {
    return this.rolloutStore.update(rolloutId, {
      overallStatus: "PAUSED",
      updatedAt: /* @__PURE__ */ new Date()
    });
  }
  async listActiveRollouts() {
    return this.rolloutStore.listActive();
  }
  async createRollout(improvementId, improvementType, allDeploymentIds, options) {
    const stages = options.targetStages ?? [
      "dev",
      "staging",
      "prod"
    ];
    const [devIds, stagingIds, prodIds] = partitionDeployments(
      allDeploymentIds,
      stages
    );
    const now = /* @__PURE__ */ new Date();
    const stageRecords = stages.map((stage, i) => ({
      stage,
      status: i === 0 ? "IN_PROGRESS" : "PENDING",
      targetDeploymentIds: stage === "dev" ? devIds : stage === "staging" ? stagingIds : prodIds,
      startedAt: i === 0 ? now : void 0
    }));
    return this.rolloutStore.create({
      improvementId,
      improvementType,
      stages: stageRecords,
      overallStatus: "IN_PROGRESS"
    });
  }
};
function partitionDeployments(ids, stages) {
  if (stages.length === 1) return [ids, [], []];
  if (stages.length === 2) {
    const split = Math.max(1, Math.ceil(ids.length * 0.2));
    return [ids.slice(0, split), ids.slice(split), []];
  }
  const devCount = Math.max(1, Math.ceil(ids.length * 0.1));
  const stagingCount = Math.max(1, Math.ceil(ids.length * 0.3));
  return [
    ids.slice(0, devCount),
    ids.slice(devCount, devCount + stagingCount),
    ids.slice(devCount + stagingCount)
  ];
}

// src/cross-agent-learning/memory-stores.ts
var import_crypto3 = require("crypto");
var InMemoryErrorEventStore = class {
  events = [];
  async append(event) {
    this.events.push(event);
  }
  async listBySignature(signatureId, limit = 100) {
    return this.events.filter((e) => e.signatureId === signatureId).slice(-limit);
  }
  async listRecent(deploymentId, since) {
    return this.events.filter(
      (e) => e.deploymentId === deploymentId && e.occurredAt.getTime() >= since.getTime()
    );
  }
};
var InMemoryErrorSignatureStore = class {
  sigs = /* @__PURE__ */ new Map();
  async get(id) {
    return this.sigs.get(id) ?? null;
  }
  async getByPattern(pattern) {
    return Array.from(this.sigs.values()).find((s) => s.pattern === pattern) ?? null;
  }
  async upsert(sig) {
    this.sigs.set(sig.id, sig);
    return sig;
  }
  async listByFrequency(minOccurrences = 1) {
    return Array.from(this.sigs.values()).filter((s) => s.occurrenceCount >= minOccurrences).sort((a, b) => b.occurrenceCount - a.occurrenceCount);
  }
};
var InMemoryFixProposalStore = class {
  proposals = /* @__PURE__ */ new Map();
  async create(proposal) {
    const record = {
      ...proposal,
      id: (0, import_crypto3.randomUUID)(),
      draftedAt: /* @__PURE__ */ new Date()
    };
    this.proposals.set(record.id, record);
    return record;
  }
  async get(id) {
    return this.proposals.get(id) ?? null;
  }
  async update(id, patch) {
    const existing = this.proposals.get(id);
    if (!existing) throw new Error(`FixProposal not found: ${id}`);
    const updated = { ...existing, ...patch };
    this.proposals.set(id, updated);
    return updated;
  }
  async listPending() {
    return Array.from(this.proposals.values()).filter(
      (p) => p.status === "DRAFT"
    );
  }
  async listBySignature(signatureId) {
    return Array.from(this.proposals.values()).filter(
      (p) => p.signatureId === signatureId
    );
  }
};
var InMemoryEmergencePatternStore = class {
  patterns = /* @__PURE__ */ new Map();
  async create(pattern) {
    const now = /* @__PURE__ */ new Date();
    const record = {
      ...pattern,
      id: (0, import_crypto3.randomUUID)(),
      detectedAt: now,
      lastUpdatedAt: now
    };
    this.patterns.set(record.id, record);
    return record;
  }
  async get(id) {
    return this.patterns.get(id) ?? null;
  }
  async update(id, patch) {
    const existing = this.patterns.get(id);
    if (!existing) throw new Error(`EmergencePattern not found: ${id}`);
    const updated = { ...existing, ...patch, lastUpdatedAt: /* @__PURE__ */ new Date() };
    this.patterns.set(id, updated);
    return updated;
  }
  async listByConfidence(minConfidence = 0) {
    return Array.from(this.patterns.values()).filter((p) => p.confidence >= minConfidence).sort((a, b) => b.confidence - a.confidence);
  }
};
var InMemoryRolloutStore = class {
  rollouts = /* @__PURE__ */ new Map();
  async create(rollout) {
    const now = /* @__PURE__ */ new Date();
    const record = {
      ...rollout,
      id: (0, import_crypto3.randomUUID)(),
      createdAt: now,
      updatedAt: now
    };
    this.rollouts.set(record.id, record);
    return record;
  }
  async get(id) {
    return this.rollouts.get(id) ?? null;
  }
  async update(id, patch) {
    const existing = this.rollouts.get(id);
    if (!existing) throw new Error(`ImprovementRollout not found: ${id}`);
    const updated = { ...existing, ...patch, updatedAt: /* @__PURE__ */ new Date() };
    this.rollouts.set(id, updated);
    return updated;
  }
  async listActive() {
    return Array.from(this.rollouts.values()).filter(
      (r) => r.overallStatus === "IN_PROGRESS" || r.overallStatus === "PAUSED"
    );
  }
};

// src/cross-agent-learning/aggregators/error-aggregator.ts
var import_crypto4 = require("crypto");
var SubAgentErrorCapture = class {
  constructor(aggregator, options = {}) {
    this.aggregator = aggregator;
    this.defaultTimeoutMs = options.defaultTimeoutMs ?? 3e4;
  }
  aggregator;
  defaultTimeoutMs;
  /** Wrap a tool call. Captures and re-throws on failure. */
  async captureToolCall(ctx, fn) {
    try {
      return await fn();
    } catch (err) {
      await this.record(ctx, "tool_call", err);
      throw err;
    }
  }
  /**
   * Wrap a call with a hard timeout. If the operation runs longer than
   * `timeoutMs`, captures a "timeout" event and rejects. The underlying
   * promise is not cancelled — callers must implement that themselves.
   */
  async captureWithTimeout(ctx, fn, timeoutMs) {
    const ms = timeoutMs ?? this.defaultTimeoutMs;
    let timer;
    try {
      return await Promise.race([
        fn(),
        new Promise((_, reject) => {
          timer = setTimeout(() => {
            const err = new Error(`Operation timed out after ${ms}ms`);
            reject(err);
          }, ms);
        })
      ]);
    } catch (err) {
      if (err instanceof Error && /timed out after \d+ms/.test(err.message)) {
        await this.record(ctx, "timeout", err);
      } else {
        await this.record(ctx, "tool_call", err);
      }
      throw err;
    } finally {
      if (timer) clearTimeout(timer);
    }
  }
  /** Explicit capture entry point for malformed input failures. */
  async captureMalformedInput(ctx, message, detail) {
    return this.record(ctx, "malformed_input", message, detail);
  }
  /** Explicit capture entry point for retry-exhaustion failures. */
  async captureRetryExhaustion(ctx, attempts, lastError) {
    const message = errorMessage(lastError);
    return this.record(
      ctx,
      "retry_exhaustion",
      `Retry exhausted after ${attempts} attempts: ${message}`,
      lastError
    );
  }
  async record(ctx, kind, errOrMessage, explicitDetail) {
    const message = typeof errOrMessage === "string" ? errOrMessage : errorMessage(errOrMessage);
    const detail = explicitDetail !== void 0 ? explicitDetail : errorDetail(errOrMessage);
    const now = /* @__PURE__ */ new Date();
    const event = {
      id: (0, import_crypto4.randomUUID)(),
      operatorId: ctx.operatorId,
      deploymentId: ctx.deploymentId,
      agentId: ctx.agentId,
      message: `[${kind}] ${message}`,
      occurredAt: now,
      receivedAt: now,
      ...ctx.sourceComponent ? { sourceComponent: ctx.sourceComponent } : {},
      ...ctx.conversationContext ? { conversationContext: ctx.conversationContext } : {},
      ...detail !== void 0 ? { detail } : {}
    };
    return this.aggregator.ingest(event);
  }
};
function errorMessage(err) {
  if (err instanceof Error) return err.message;
  if (typeof err === "string") return err;
  try {
    return JSON.stringify(err);
  } catch {
    return String(err);
  }
}
function errorDetail(err) {
  if (err instanceof Error) {
    return { name: err.name, stack: err.stack };
  }
  return err;
}

// src/cross-agent-learning/aggregators/pattern-extractor.ts
var import_crypto5 = require("crypto");
var ContextualPatternExtractor = class {
  constructor(signatureStore, eventStore, options = {}) {
    this.signatureStore = signatureStore;
    this.eventStore = eventStore;
    this.minEvidence = options.minEvidenceCount ?? 3;
    this.minShare = options.minConditionShare ?? 0.6;
  }
  signatureStore;
  eventStore;
  minEvidence;
  minShare;
  /**
   * Sweeps all signatures and produces a contextual pattern per signature
   * whose events share a discriminating condition. Returns the list of new
   * patterns — callers persist them as they see fit.
   */
  async extractPatterns() {
    const signatures = await this.signatureStore.listByFrequency(
      this.minEvidence
    );
    const out = [];
    for (const sig of signatures) {
      const events = await this.eventStore.listBySignature(sig.id, 200);
      const pattern = this.buildPattern(sig, events);
      if (pattern) out.push(pattern);
    }
    return out;
  }
  /** Build a contextual pattern for a single signature, or null if too weak. */
  buildPattern(sig, events) {
    if (events.length < this.minEvidence) return null;
    const conditions = extractDiscriminatingConditions(
      events,
      this.minShare
    );
    if (conditions.length === 0) return null;
    const agents = /* @__PURE__ */ new Set();
    const deployments = /* @__PURE__ */ new Set();
    for (const e of events) {
      agents.add(e.agentId);
      deployments.add(e.deploymentId);
    }
    const confidence = computeConfidence2(events.length, conditions.length);
    const label = buildLabel(sig, Array.from(agents), conditions);
    return {
      id: (0, import_crypto5.randomUUID)(),
      signatureId: sig.id,
      label,
      conditions,
      affectedAgents: Array.from(agents),
      affectedDeployments: Array.from(deployments),
      evidenceCount: events.length,
      confidence,
      detectedAt: /* @__PURE__ */ new Date()
    };
  }
};
function extractDiscriminatingConditions(events, minShare) {
  const counters = /* @__PURE__ */ new Map();
  for (const e of events) {
    const text = `${e.conversationContext ?? ""} ${e.message}`;
    for (const cond of conditionsForText(text)) {
      const key = `${cond.kind}:${cond.value}`;
      const existing = counters.get(key);
      if (existing) {
        existing.hits++;
      } else {
        counters.set(key, { hits: 1, condition: cond });
      }
    }
  }
  const threshold = Math.max(1, Math.ceil(events.length * minShare));
  return Array.from(counters.values()).filter((c) => c.hits >= threshold).sort((a, b) => b.hits - a.hits).slice(0, 5).map((c) => c.condition);
}
var EMOJI_RE = new RegExp("\\p{Extended_Pictographic}", "u");
var NON_ASCII_RE = /[^\x00-\x7F]/;
var KEYWORD_HINTS = [
  "calendar",
  "attachment",
  "image",
  "voice",
  "video",
  "draft",
  "reply",
  "forward",
  "schedule",
  "invoice",
  "approval"
];
function conditionsForText(text) {
  const out = [];
  if (text.length === 0) return out;
  if (EMOJI_RE.test(text)) {
    out.push({ kind: "contains_emoji", value: "true" });
  }
  if (NON_ASCII_RE.test(text)) {
    out.push({ kind: "non_ascii_chars", value: "true" });
  }
  out.push({
    kind: "message_length_bucket",
    value: bucketLength(text.length)
  });
  if (/attachment|attached|attach\.|file:|\.pdf|\.png|\.jpg/i.test(text)) {
    out.push({ kind: "attachment_present", value: "true" });
  }
  const subjectMatch = /subject[:=]\s*(.{0,200})/i.exec(text);
  if (subjectMatch?.[1]) {
    out.push({
      kind: "subject_length_bucket",
      value: bucketLength(subjectMatch[1].trim().length)
    });
  }
  for (const kw of KEYWORD_HINTS) {
    if (text.toLowerCase().includes(kw)) {
      out.push({ kind: "keyword", value: kw });
    }
  }
  return out;
}
function bucketLength(n) {
  if (n < 20) return "<20";
  if (n < 80) return "20-79";
  if (n < 200) return "80-199";
  if (n < 500) return "200-499";
  return ">=500";
}
function computeConfidence2(evidenceCount, conditionCount) {
  const evidenceFactor = Math.min(evidenceCount / 20, 1);
  const conditionFactor = Math.min(conditionCount / 3, 1);
  return Math.round((evidenceFactor * 0.6 + conditionFactor * 0.4) * 100) / 100;
}
function buildLabel(sig, agents, conditions) {
  const agentLabel = agents.length === 1 ? agents[0] : `${agents.length} agents`;
  const tool = sig.sourceComponent ?? "operation";
  const condLabel = conditions.map((c) => `${c.kind}=${c.value}`).join(" AND ");
  return `${agentLabel}'s ${tool} fails when ${condLabel}`;
}

// src/cross-agent-learning/recommenders/fix-recommender.ts
var import_crypto6 = require("crypto");
var FixRecommender = class {
  constructor(signatureStore, options = {}) {
    this.signatureStore = signatureStore;
    this.minConfidence = options.minPatternConfidence ?? 0.3;
  }
  signatureStore;
  minConfidence;
  /** Generate a fix recommendation for a single contextual pattern. */
  async recommend(pattern) {
    if (pattern.confidence < this.minConfidence) return null;
    const sig = await this.signatureStore.get(pattern.signatureId);
    if (!sig) return null;
    const { strategy, rationale, suggestedConfig } = deriveStrategy(
      sig,
      pattern
    );
    return {
      id: (0, import_crypto6.randomUUID)(),
      patternId: pattern.id,
      signatureId: pattern.signatureId,
      strategy,
      rationale,
      ...suggestedConfig ? { suggestedConfig } : {},
      confidence: pattern.confidence,
      requiresApproval: true,
      recommendedAt: /* @__PURE__ */ new Date()
    };
  }
  /** Bulk variant — skips patterns below the confidence threshold. */
  async recommendAll(patterns) {
    const out = [];
    for (const p of patterns) {
      const rec = await this.recommend(p);
      if (rec) out.push(rec);
    }
    return out;
  }
};
function deriveStrategy(sig, pattern) {
  if (sig.category === "transient") {
    return {
      strategy: "retry_strategy",
      rationale: "Transient errors recurring under a stable condition \u2014 tune retry budget + backoff.",
      suggestedConfig: {
        maxAttempts: 5,
        initialDelayMs: 500,
        backoff: "exponential",
        jitter: true
      }
    };
  }
  if (sig.category === "config") {
    return {
      strategy: "config_change",
      rationale: "Authentication or configuration error pattern \u2014 requires environment or credential update."
    };
  }
  if (sig.category === "schema") {
    const containsExoticChars = pattern.conditions.some(
      (c) => c.kind === "contains_emoji" || c.kind === "non_ascii_chars"
    );
    if (containsExoticChars) {
      return {
        strategy: "input_sanitisation",
        rationale: "Schema/validation failures correlate with non-ASCII or emoji input \u2014 normalise before tool call.",
        suggestedConfig: {
          normaliseEmoji: true,
          normaliseUnicode: "NFKC",
          stripControlChars: true
        }
      };
    }
    return {
      strategy: "validation_guard",
      rationale: "Schema failures recur under a stable input shape \u2014 add pre-tool validation guard."
    };
  }
  if (sig.category === "tool-bug") {
    return {
      strategy: "alternative_tool_path",
      rationale: "Tool-bug pattern \u2014 route the failing call to an alternative tool or graceful degradation path."
    };
  }
  if (sig.category === "prompt-issue") {
    return {
      strategy: "prompt_update",
      rationale: "Prompt-rooted error \u2014 update the agent's system prompt to address the misunderstanding."
    };
  }
  return {
    strategy: "alternative_tool_path",
    rationale: "Model-limitation pattern \u2014 degrade to an alternative tool or simpler reasoning path."
  };
}

// src/cross-agent-learning/recommenders/prompt-update-recommender.ts
var import_crypto7 = require("crypto");
var PromptUpdateRecommender = class {
  constructor(anthropic, signatureStore, eventStore, options = {}) {
    this.anthropic = anthropic;
    this.signatureStore = signatureStore;
    this.eventStore = eventStore;
    this.model = options.model ?? "claude-haiku-4-5-20251001";
    this.maxTokens = options.maxTokens ?? 768;
    this.minEvidence = options.minEvidenceCount ?? 3;
  }
  anthropic;
  signatureStore;
  eventStore;
  model;
  maxTokens;
  minEvidence;
  /**
   * Draft a prompt-update recommendation for a contextual pattern.
   * Returns null if the pattern doesn't look prompt-rooted, the signature
   * is missing, or evidence is insufficient.
   */
  async recommend(pattern) {
    if (pattern.evidenceCount < this.minEvidence) return null;
    const sig = await this.signatureStore.get(pattern.signatureId);
    if (!sig) return null;
    if (!isPromptRooted(sig.category)) return null;
    const agentId = pattern.affectedAgents[0];
    if (!agentId) return null;
    const events = await this.eventStore.listBySignature(pattern.signatureId, 5);
    const { summary, suggestedPromptDelta } = await this.callClaude(
      pattern,
      events,
      agentId
    );
    return {
      id: (0, import_crypto7.randomUUID)(),
      patternId: pattern.id,
      agentId,
      summary,
      suggestedPromptDelta,
      confidence: pattern.confidence,
      requiresApproval: true,
      draftedAt: /* @__PURE__ */ new Date()
    };
  }
  async callClaude(pattern, events, agentId) {
    const evidenceText = events.map((e) => `- ${e.conversationContext ?? "(no context)"} \u2192 ${e.message}`).join("\n");
    const conditionText = pattern.conditions.map((c) => `${c.kind}=${c.value}`).join(", ");
    const prompt = `You review recurring failure patterns in an AI agent platform and suggest prompt updates.

## Agent
${agentId}

## Pattern
${pattern.label}

## Conditions correlated with failure
${conditionText || "(none extracted)"}

## Evidence (up to 5 events)
${evidenceText || "(none available)"}

## Task
Produce two outputs separated by the literal line "---DELTA---":

**Part 1 \u2014 Summary (1 sentence)**
What is the agent misunderstanding?

**Part 2 \u2014 Suggested prompt delta (Markdown)**
Concrete addition or rewording for the agent's system prompt. 2\u20135 sentences. Address the misunderstanding directly. Do not include unrelated tone or formatting changes.

Respond with Part 1, then "---DELTA---", then Part 2. No preamble.`;
    const response = await this.anthropic.messages.create({
      model: this.model,
      max_tokens: this.maxTokens,
      messages: [{ role: "user", content: prompt }]
    });
    const firstBlock = response.content[0];
    const raw = firstBlock !== void 0 && firstBlock.type === "text" ? firstBlock.text : "";
    const delimiter = "---DELTA---";
    const idx = raw.indexOf(delimiter);
    if (idx === -1) {
      return {
        summary: `Prompt rooted in misunderstanding: ${pattern.label}`,
        suggestedPromptDelta: raw.trim()
      };
    }
    return {
      summary: raw.slice(0, idx).trim(),
      suggestedPromptDelta: raw.slice(idx + delimiter.length).trim()
    };
  }
};
function isPromptRooted(category) {
  return category === "prompt-issue" || category === "model-limitation";
}

// src/cross-agent-learning/sharers/opt-in-policy.ts
var InMemoryCustomerSharingPolicyStore = class {
  policies = /* @__PURE__ */ new Map();
  async get(customerId) {
    return this.policies.get(customerId) ?? null;
  }
  async upsert(policy) {
    this.policies.set(policy.customerId, policy);
    return policy;
  }
  async list() {
    return Array.from(this.policies.values());
  }
};
var OptInPolicyEnforcer = class {
  constructor(store) {
    this.store = store;
  }
  store;
  /**
   * Returns true when `customerId` has agreed to contribute the given
   * category to the fleet. Default (no policy stored) is false — opt-in.
   */
  async canShare(customerId, category) {
    const policy = await this.store.get(customerId);
    if (!policy) return false;
    return policy.shareCategories.includes(category);
  }
  /**
   * Returns true when `customerId` has agreed to receive learnings of the
   * given category from the fleet. Default is false — opt-in.
   */
  async canConsume(customerId, category) {
    const policy = await this.store.get(customerId);
    if (!policy) return false;
    return policy.consumeCategories.includes(category);
  }
  /** Convenience: returns customers that have opted in to a given share/consume. */
  async listShareSubscribers(category) {
    const all = await this.store.list();
    return all.filter((p) => p.shareCategories.includes(category)).map((p) => p.customerId);
  }
  async listConsumeSubscribers(category) {
    const all = await this.store.list();
    return all.filter((p) => p.consumeCategories.includes(category)).map((p) => p.customerId);
  }
};

// src/cross-agent-learning/sharers/learning-sharer.ts
var import_crypto8 = require("crypto");
var LearningSharer = class {
  constructor(policy, options = {}) {
    this.policy = policy;
    this.salt = options.originHashSalt ?? "DEFAULT_UNSAFE_SALT_REPLACE_ME";
  }
  policy;
  salt;
  /**
   * Anonymise an ErrorSignature for cross-customer sharing.
   * Returns null when the origin customer has not opted in to share errors.
   */
  async shareErrorSignature(originCustomerId, sig) {
    if (!await this.policy.canShare(originCustomerId, "errors")) {
      return null;
    }
    return {
      category: "errors",
      originHash: this.hash(originCustomerId),
      payload: {
        kind: "error_signature",
        pattern: sig.pattern,
        categoryHint: sig.category,
        occurrenceCount: sig.occurrenceCount,
        deploymentCount: sig.deploymentCount
      },
      sharedAt: /* @__PURE__ */ new Date()
    };
  }
  /** Anonymise a FixRecommendation. */
  async shareFixRecommendation(originCustomerId, rec) {
    if (!await this.policy.canShare(originCustomerId, "fixes")) {
      return null;
    }
    return {
      category: "fixes",
      originHash: this.hash(originCustomerId),
      payload: {
        kind: "fix_recommendation",
        strategy: rec.strategy,
        rationale: rec.rationale,
        ...rec.suggestedConfig ? { suggestedConfig: rec.suggestedConfig } : {}
      },
      sharedAt: /* @__PURE__ */ new Date()
    };
  }
  /**
   * Anonymise a CapabilityEmergencePattern. Evidence excerpts are stripped
   * — only the capability label and aggregate counts survive.
   */
  async shareCapabilityEmergence(originCustomerId, pattern) {
    if (!await this.policy.canShare(originCustomerId, "capabilities")) {
      return null;
    }
    return {
      category: "capabilities",
      originHash: this.hash(originCustomerId),
      payload: {
        kind: "capability_emergence",
        capabilityLabel: pattern.capabilityLabel,
        deploymentCount: pattern.deploymentCount,
        eventCount: pattern.eventCount
      },
      sharedAt: /* @__PURE__ */ new Date()
    };
  }
  /**
   * Distribute a batch of anonymised learnings to all customers opted in to
   * the given category. Returns a delivery map: customerId → number of
   * learnings the consumer accepted (gated by their consume policy).
   */
  async distribute(category, learnings, deliver) {
    const consumers = await this.policy.listConsumeSubscribers(category);
    const results = {};
    for (const customerId of consumers) {
      let count = 0;
      for (const l of learnings) {
        if (l.originHash === this.hash(customerId)) continue;
        await deliver(customerId, l);
        count++;
      }
      results[customerId] = count;
    }
    return results;
  }
  /** Expose the hash function for testing the round-trip cleanly. */
  hash(customerId) {
    return (0, import_crypto8.createHash)("sha256").update(`${this.salt}:${customerId}`).digest("hex");
  }
};

// src/cross-agent-learning/sub-agent/learning-mind.ts
var import_crypto9 = require("crypto");
var LearningMind = class {
  constructor(config) {
    this.config = config;
    this.extractor = new ContextualPatternExtractor(
      config.signatureStore,
      config.eventStore,
      config.extractorOptions ?? {}
    );
    this.fixRecommender = new FixRecommender(
      config.signatureStore,
      config.recommenderOptions ?? {}
    );
    if (config.promptUpdateRecommender) {
      this.promptRecommender = config.promptUpdateRecommender;
    }
    if (config.sharer) this.sharer = config.sharer;
    if (config.originCustomerId) this.originCustomerId = config.originCustomerId;
    this.minSurfaceConfidence = config.minSurfaceConfidence ?? 0.5;
  }
  config;
  extractor;
  fixRecommender;
  promptRecommender;
  sharer;
  originCustomerId;
  minSurfaceConfidence;
  /** Full sweep — extract patterns, recommend fixes, surface, optionally share. */
  async sweep(now = /* @__PURE__ */ new Date()) {
    const patterns = await this.extractor.extractPatterns();
    const fixRecommendations = await this.fixRecommender.recommendAll(patterns);
    const promptUpdates = [];
    if (this.promptRecommender) {
      for (const pattern of patterns) {
        const rec = await this.promptRecommender.recommend(pattern);
        if (rec) promptUpdates.push(rec);
      }
    }
    const candidateEvents = this.toCandidateEvents(
      patterns,
      fixRecommendations,
      promptUpdates,
      now
    );
    const anonymised = await this.anonymise(
      patterns,
      fixRecommendations
    );
    return {
      patterns,
      fixRecommendations,
      promptUpdates,
      candidateEvents,
      anonymised
    };
  }
  /** Convert the latest recommendations into CandidateEvents for F0.10. */
  surfaceHighImpactFixes(fixes, patterns, now = /* @__PURE__ */ new Date()) {
    const patternsById = new Map(patterns.map((p) => [p.id, p]));
    return fixes.filter((f) => f.confidence >= this.minSurfaceConfidence).map((fix) => {
      const pattern = patternsById.get(fix.patternId);
      return makeCandidateEvent(fix, pattern, now);
    });
  }
  toCandidateEvents(patterns, fixes, promptUpdates, now) {
    const patternsById = new Map(patterns.map((p) => [p.id, p]));
    const fixEvents = fixes.filter((f) => f.confidence >= this.minSurfaceConfidence).map((fix) => makeCandidateEvent(fix, patternsById.get(fix.patternId), now));
    const promptEvents = promptUpdates.filter((p) => p.confidence >= this.minSurfaceConfidence).map(
      (p) => makePromptCandidateEvent(p, patternsById.get(p.patternId), now)
    );
    return [...fixEvents, ...promptEvents];
  }
  async anonymise(patterns, fixes) {
    if (!this.sharer || !this.originCustomerId) return [];
    const out = [];
    for (const fix of fixes) {
      const a = await this.sharer.shareFixRecommendation(
        this.originCustomerId,
        fix
      );
      if (a) out.push(a);
    }
    for (const pattern of patterns) {
      const sig = await this.config.signatureStore.get(pattern.signatureId);
      if (!sig) continue;
      const a = await this.sharer.shareErrorSignature(
        this.originCustomerId,
        sig
      );
      if (a) out.push(a);
    }
    return out;
  }
};
function makeCandidateEvent(fix, pattern, now) {
  const label = pattern?.label ?? "Recurring error pattern";
  return {
    id: (0, import_crypto9.randomUUID)(),
    sourceName: "tech",
    payload: {
      title: `Fix recommended: ${fix.strategy}`,
      summary: `${label}. Recommended strategy: ${fix.strategy}. ${fix.rationale}`,
      baseRelevance: clamp01(0.4 + fix.confidence * 0.6),
      kind: "cross_agent_fix_recommendation",
      recommendationId: fix.id,
      strategy: fix.strategy,
      requiresApproval: true
    },
    occurredAt: now
  };
}
function makePromptCandidateEvent(rec, pattern, now) {
  const label = pattern?.label ?? "Agent misunderstanding pattern";
  return {
    id: (0, import_crypto9.randomUUID)(),
    sourceName: "tech",
    payload: {
      title: `Prompt update suggested for ${rec.agentId}`,
      summary: `${label}. ${rec.summary}`,
      baseRelevance: clamp01(0.4 + rec.confidence * 0.6),
      kind: "cross_agent_prompt_update",
      recommendationId: rec.id,
      agentId: rec.agentId,
      requiresApproval: true
    },
    occurredAt: now
  };
}
function clamp01(n) {
  if (n < 0) return 0;
  if (n > 1) return 1;
  return n;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CapabilityEmergenceDetector,
  ContextualPatternExtractor,
  ErrorAggregator,
  ErrorClassifier,
  FixProposer,
  FixRecommender,
  ImprovementRolloutOrchestrator,
  InMemoryCustomerSharingPolicyStore,
  InMemoryEmergencePatternStore,
  InMemoryErrorEventStore,
  InMemoryErrorSignatureStore,
  InMemoryFixProposalStore,
  InMemoryRolloutStore,
  LearningMind,
  LearningSharer,
  OptInPolicyEnforcer,
  PromptUpdateRecommender,
  SkillRecommendationEngine,
  SubAgentErrorCapture,
  normalizePattern
});
//# sourceMappingURL=index.js.map