// ../core/src/codeTrail/types.ts
var CODE_TRAIL_SCHEMA_VERSION = 1;
var CODE_TRAIL_READ_MODEL_VERSION = 1;
var CODE_TRAIL_MODEL_VERSION = "code-trail-v1";
// ../core/src/codeTrail/selectors.ts
var CODE_TRAIL_NO_AUTHORITY_BOUNDARY = Object.freeze({
  reportOnly: true,
  noAuthority: true,
  grantsApplyAuthority: false,
  grantsCanonAuthority: false,
  grantsProviderAuthority: false,
  grantsNetworkAuthority: false,
  grantsFilesystemEditAuthority: false,
  grantsExecutionAuthority: false
});
var PHASE_SORT_ORDER = {
  context: 0,
  planning: 1,
  execution: 2,
  review: 3,
  evidence: 4,
  truth: 5,
  import: 6,
  observation: 7
};
var SAFE_METADATA_KEYS = new Set([
  "artifactRefs",
  "cursor",
  "branch",
  "cloudConsentStatus",
  "cloudIndexStatus",
  "cloudWorkspaceStatus",
  "commit",
  "consentTier",
  "diagnosticCount",
  "dirtyState",
  "durationMs",
  "duplicateDiagnosticsCount",
  "errorCode",
  "errorCodes",
  "fileCount",
  "generatedAt",
  "graphId",
  "hasErrors",
  "importId",
  "kind",
  "nodeId",
  "readinessStatus",
  "reasonCode",
  "reasonCodes",
  "receiptRefs",
  "receiptKind",
  "requestId",
  "resultState",
  "revision",
  "revisionCounter",
  "runId",
  "selectedRefCount",
  "selectedRefs",
  "sourceKind",
  "sourceWatermark",
  "status",
  "patchStatus",
  "proofStatus",
  "tags",
  "tokenCount",
  "tokenEstimate",
  "trailHash",
  "warningCount",
  "warnings",
  "watermark"
]);
var SAFE_METADATA_KEY_PATTERNS = [/Count$/, /Counts$/, /Hash$/, /Id$/, /Ids$/, /Ms$/, /Ref$/, /Refs$/];
var MAX_METADATA_STRING_LENGTH = 512;
var MAX_METADATA_ARRAY_LENGTH = 50;
function clamp(value, min, max) {
  if (Number.isNaN(value))
    return min;
  return Math.min(max, Math.max(min, value));
}
function codeTrailNoAuthorityBoundary() {
  return { ...CODE_TRAIL_NO_AUTHORITY_BOUNDARY };
}
function uniqueCodeTrailStrings(values) {
  const seen = new Set;
  const result = [];
  for (const value of values) {
    const trimmed = value?.trim();
    if (!trimmed || seen.has(trimmed))
      continue;
    seen.add(trimmed);
    result.push(trimmed);
  }
  return result;
}
function buildCodeTrailRefStableKey(args) {
  return args.repoId ? `${args.kind}:${args.repoId}:${args.id}` : `${args.kind}:${args.id}`;
}
function buildCodeTrailSourceKey(args) {
  return `source:${args.sourceKind}:${args.stableKey}`;
}
function isDeterministicCodeTrailRef(ref) {
  if (!ref)
    return false;
  return Boolean(ref.id.trim() && ref.stableKey.trim() && ref.sourceKey.trim());
}
function sanitizeCodeTrailMetadata(metadata) {
  if (!metadata)
    return;
  const output = {};
  for (const [key, value] of Object.entries(metadata)) {
    const trimmedKey = key.trim();
    if (!trimmedKey || !isSafeMetadataKey(trimmedKey))
      continue;
    if (isSafeMetadataPrimitive(value)) {
      output[trimmedKey] = value;
      continue;
    }
    if (Array.isArray(value) && value.length <= MAX_METADATA_ARRAY_LENGTH && value.every(isSafeMetadataPrimitive)) {
      output[trimmedKey] = value;
    }
  }
  return Object.keys(output).length > 0 ? output : undefined;
}
function admitSource(candidate) {
  const key = candidate.key?.trim();
  const kind = candidate.kind;
  if (!key || !kind)
    return null;
  return {
    key,
    kind,
    ref: isDeterministicCodeTrailRef(candidate.ref) ? sanitizeRef(candidate.ref) : undefined,
    label: candidate.label,
    observedAt: candidate.observedAt,
    confidence: candidate.confidence === undefined ? undefined : clamp(candidate.confidence, 0, 1),
    watermark: candidate.watermark
  };
}
function admitCodeTrailGap(candidate) {
  const sourceKey = candidate.sourceKey?.trim();
  if (!sourceKey)
    return null;
  const stableKey = candidate.stableKey?.trim() || `gap:${sourceKey}:${candidate.kind ?? "source_unavailable"}`;
  return {
    schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    kind: candidate.kind ?? "source_unavailable",
    severity: candidate.severity ?? "info",
    title: candidate.title?.trim() || "Trail source gap",
    detail: candidate.detail,
    sourceKey,
    ref: isDeterministicCodeTrailRef(candidate.ref) ? sanitizeRef(candidate.ref) : undefined
  };
}
function admitEntry(candidate) {
  if (!isDeterministicCodeTrailRef(candidate.primaryRef))
    return null;
  const primaryRef = sanitizeRef(candidate.primaryRef);
  const sourceKey = candidate.sourceKey?.trim() || primaryRef.sourceKey;
  if (!sourceKey)
    return null;
  const sourceRefs = uniqueRefs([primaryRef, ...candidate.sourceRefs ?? []]);
  const inputRefs = uniqueRefs(candidate.inputRefs ?? []);
  const outputRefs = uniqueRefs(candidate.outputRefs ?? []);
  const evidenceRefs = uniqueRefs(candidate.evidenceRefs ?? []);
  const receiptRefs = uniqueRefs(candidate.receiptRefs ?? []);
  const relatedRefs = uniqueRefs(candidate.relatedRefs ?? []);
  const stableKey = candidate.stableKey?.trim() || `entry:${candidate.entryKind ?? "observation"}:${primaryRef.stableKey}`;
  const metadata = sanitizeCodeTrailMetadata(candidate.metadata);
  return {
    schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    sourceKey,
    sourceKeys: uniqueCodeTrailStrings([
      sourceKey,
      ...candidate.sourceKeys ?? [],
      primaryRef.sourceKey,
      ...sourceRefs.map((ref) => ref.sourceKey),
      ...inputRefs.map((ref) => ref.sourceKey),
      ...outputRefs.map((ref) => ref.sourceKey),
      ...evidenceRefs.map((ref) => ref.sourceKey),
      ...receiptRefs.map((ref) => ref.sourceKey),
      ...relatedRefs.map((ref) => ref.sourceKey)
    ]),
    entryKind: candidate.entryKind ?? "observation",
    phase: candidate.phase ?? "observation",
    status: candidate.status ?? "observed",
    sourceStatus: candidate.sourceStatus,
    title: candidate.title,
    summary: candidate.summary,
    primaryRef,
    sourceRefs,
    inputRefs,
    outputRefs,
    evidenceRefs,
    receiptRefs,
    relatedRefs,
    reasonCodes: uniqueCodeTrailStrings(candidate.reasonCodes ?? []),
    createdAt: candidate.createdAt,
    updatedAt: candidate.updatedAt,
    startedAt: candidate.startedAt,
    completedAt: candidate.completedAt,
    metadata,
    authorityBoundary: codeTrailNoAuthorityBoundary()
  };
}
function admitLink(candidate) {
  if (!isDeterministicCodeTrailRef(candidate.sourceRef))
    return null;
  if (!isDeterministicCodeTrailRef(candidate.targetRef))
    return null;
  const sourceRef = sanitizeRef(candidate.sourceRef);
  const targetRef = sanitizeRef(candidate.targetRef);
  const sourceKeys = uniqueCodeTrailStrings([
    ...candidate.sourceKeys ?? [],
    sourceRef.sourceKey,
    targetRef.sourceKey
  ]);
  if (sourceKeys.length === 0)
    return null;
  const stableKey = candidate.stableKey?.trim() || `link:${candidate.kind ?? "references"}:${sourceRef.stableKey}:${targetRef.stableKey}`;
  const metadata = sanitizeCodeTrailMetadata(candidate.metadata);
  return {
    schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    kind: candidate.kind ?? "references",
    sourceRef,
    targetRef,
    sourceKeys,
    reasonCodes: uniqueCodeTrailStrings(candidate.reasonCodes ?? []),
    metadata
  };
}
function normalizeCodeTrailProjection(candidate) {
  const entries = dedupeCodeTrailEntries(sortCodeTrailEntries((candidate.entries ?? []).map(admitEntry).filter(isPresent)));
  const links = dedupeCodeTrailLinks(sortCodeTrailLinks((candidate.links ?? []).map(admitLink).filter(isPresent)));
  const sources = dedupeSources((candidate.sources ?? []).map(admitSource).filter(isPresent));
  const gaps = dedupeGaps((candidate.gaps ?? []).map(admitCodeTrailGap).filter(isPresent));
  const reasonCodes = uniqueCodeTrailStrings([
    ...candidate.summary?.reasonCodes ?? [],
    ...entries.flatMap((entry) => entry.reasonCodes)
  ]);
  return {
    schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
    readModelVersion: CODE_TRAIL_READ_MODEL_VERSION,
    modelVersion: CODE_TRAIL_MODEL_VERSION,
    projectId: candidate.projectId,
    generatedAt: candidate.generatedAt ?? 0,
    scope: {
      projectId: candidate.scope?.projectId ?? candidate.projectId,
      repoId: candidate.scope?.repoId,
      repoName: candidate.scope?.repoName,
      sessionId: candidate.scope?.sessionId,
      workroomRunId: candidate.scope?.workroomRunId,
      patchRunId: candidate.scope?.patchRunId,
      editSessionId: candidate.scope?.editSessionId,
      editSessionRowId: candidate.scope?.editSessionRowId,
      truthCandidateId: candidate.scope?.truthCandidateId,
      capabilityRunId: candidate.scope?.capabilityRunId,
      importId: candidate.scope?.importId,
      trailHash: candidate.scope?.trailHash,
      sourceMcpRequestId: candidate.scope?.sourceMcpRequestId,
      sourceMcpRunId: candidate.scope?.sourceMcpRunId,
      sourceRunId: candidate.scope?.sourceRunId,
      receiptId: candidate.scope?.receiptId,
      artifactId: candidate.scope?.artifactId,
      codeMarketSnapshotId: candidate.scope?.codeMarketSnapshotId,
      mcpContextRunId: candidate.scope?.mcpContextRunId,
      prSnapshotId: candidate.scope?.prSnapshotId,
      reviewRoomId: candidate.scope?.reviewRoomId,
      storyId: candidate.scope?.storyId,
      filePath: candidate.scope?.filePath,
      surface: candidate.scope?.surface,
      sourceMode: candidate.scope?.sourceMode
    },
    summary: {
      title: candidate.summary?.title?.trim() || "Code Trail",
      detail: candidate.summary?.detail,
      entryCount: entries.length,
      linkCount: links.length,
      statusCounts: countStatuses(entries),
      reasonCodes
    },
    entries,
    links,
    sources,
    gaps,
    sourceWatermarks: dedupeBySourceKey(candidate.sourceWatermarks ?? []),
    truncation: dedupeBySourceKey(candidate.truncation ?? []),
    authorityBoundary: codeTrailNoAuthorityBoundary()
  };
}
function sortCodeTrailEntries(entries) {
  return [...entries].sort((a, b) => {
    const timeDelta = entrySortTime(b) - entrySortTime(a);
    if (timeDelta !== 0)
      return timeDelta;
    const phaseDelta = PHASE_SORT_ORDER[a.phase] - PHASE_SORT_ORDER[b.phase];
    if (phaseDelta !== 0)
      return phaseDelta;
    return a.stableKey.localeCompare(b.stableKey);
  });
}
function sortCodeTrailLinks(links) {
  return [...links].sort((a, b) => {
    const sourceDelta = a.sourceRef.stableKey.localeCompare(b.sourceRef.stableKey);
    if (sourceDelta !== 0)
      return sourceDelta;
    const targetDelta = a.targetRef.stableKey.localeCompare(b.targetRef.stableKey);
    if (targetDelta !== 0)
      return targetDelta;
    return a.stableKey.localeCompare(b.stableKey);
  });
}
function dedupeCodeTrailEntries(entries) {
  const byStableKey = new Map;
  for (const entry of entries) {
    const existing = byStableKey.get(entry.stableKey);
    if (!existing || entrySortTime(entry) >= entrySortTime(existing)) {
      byStableKey.set(entry.stableKey, entry);
    }
  }
  return sortCodeTrailEntries([...byStableKey.values()]);
}
function dedupeCodeTrailLinks(links) {
  const seen = new Set;
  const output = [];
  for (const link of links) {
    const key = link.stableKey;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(link);
  }
  return sortCodeTrailLinks(output);
}
function getCodeTrailEntryById(trail, id) {
  return (trail.entries ?? []).find((entry) => entry.id === id || entry.stableKey === id);
}
function getCodeTrailEntriesForRef(trail, refStableKey) {
  return (trail.entries ?? []).filter((entry) => [
    entry.primaryRef,
    ...entry.sourceRefs,
    ...entry.inputRefs,
    ...entry.outputRefs,
    ...entry.evidenceRefs,
    ...entry.receiptRefs,
    ...entry.relatedRefs
  ].some((ref) => ref.stableKey === refStableKey || ref.id === refStableKey));
}
function sanitizeRef(ref) {
  return {
    ...ref,
    id: ref.id.trim(),
    stableKey: ref.stableKey.trim(),
    sourceKey: ref.sourceKey.trim(),
    metadata: sanitizeCodeTrailMetadata(ref.metadata)
  };
}
function uniqueRefs(refs) {
  const seen = new Set;
  const output = [];
  for (const ref of refs) {
    if (!isDeterministicCodeTrailRef(ref))
      continue;
    const sanitized = sanitizeRef(ref);
    const key = `${sanitized.kind}:${sanitized.stableKey}:${sanitized.sourceKey}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(sanitized);
  }
  return output;
}
function isSafeMetadataPrimitive(value) {
  if (value === null || typeof value === "boolean")
    return true;
  if (typeof value === "number")
    return Number.isFinite(value);
  if (typeof value === "string")
    return value.length <= MAX_METADATA_STRING_LENGTH;
  return false;
}
function isSafeMetadataKey(key) {
  return SAFE_METADATA_KEYS.has(key) || SAFE_METADATA_KEY_PATTERNS.some((pattern) => pattern.test(key));
}
function entrySortTime(entry) {
  return entry.updatedAt ?? entry.completedAt ?? entry.startedAt ?? entry.createdAt ?? 0;
}
function countStatuses(entries) {
  const counts = {};
  for (const entry of entries) {
    counts[entry.status] = (counts[entry.status] ?? 0) + 1;
  }
  return counts;
}
function dedupeSources(sources) {
  const seen = new Set;
  const output = [];
  for (const source of sources) {
    if (seen.has(source.key))
      continue;
    seen.add(source.key);
    output.push(source);
  }
  return output.sort((a, b) => a.key.localeCompare(b.key));
}
function dedupeGaps(gaps) {
  const seen = new Set;
  const output = [];
  for (const gap of gaps) {
    if (seen.has(gap.stableKey))
      continue;
    seen.add(gap.stableKey);
    output.push(gap);
  }
  return output.sort((a, b) => a.stableKey.localeCompare(b.stableKey));
}
function dedupeBySourceKey(items) {
  const seen = new Set;
  const output = [];
  for (const item of items) {
    const sourceKey = item.sourceKey.trim();
    if (!sourceKey || seen.has(sourceKey))
      continue;
    seen.add(sourceKey);
    output.push({ ...item, sourceKey });
  }
  return output.sort((a, b) => a.sourceKey.localeCompare(b.sourceKey));
}
function isPresent(value) {
  return value !== null && value !== undefined;
}
// ../core/src/codeMarket/types.ts
var CODE_MARKET_SCHEMA_VERSION = 1;
var CODE_MARKET_READ_MODEL_VERSION = 1;
var CODE_MARKET_MODEL_VERSION = "code-market-v1";
// ../core/src/codeMarket/selectors.ts
var NON_ADMITTING_AUTHORITIES = new Set(["llm_label", "ready_code_insight", "title"]);
var NON_ADMITTING_REF_KINDS = new Set(["llm_label", "title"]);
function clamp2(value, min, max) {
  if (Number.isNaN(value))
    return min;
  return Math.min(max, Math.max(min, value));
}
function unique(values) {
  const seen = new Set;
  const result = [];
  for (const value of values) {
    const trimmed = value?.trim();
    if (!trimmed || seen.has(trimmed))
      continue;
    seen.add(trimmed);
    result.push(trimmed);
  }
  return result;
}
function isDeterministicCodeMarketRef(ref) {
  if (!ref)
    return false;
  if (!ref.id.trim() || !ref.stableKey.trim() || !ref.sourceKey.trim())
    return false;
  if (NON_ADMITTING_AUTHORITIES.has(ref.authority))
    return false;
  if (NON_ADMITTING_REF_KINDS.has(ref.kind))
    return false;
  return true;
}
function normalizeSelection(candidate) {
  const filePaths = unique(candidate?.filePaths ?? []);
  const nodeIds = unique(candidate?.nodeIds ?? []);
  const moduleIds = unique(candidate?.moduleIds ?? []);
  const entityIds = unique(candidate?.entityIds ?? []);
  return {
    source: candidate?.source ?? "code_market",
    repoId: candidate?.repoId,
    filePaths,
    nodeIds,
    moduleIds,
    entityIds,
    selectedItems: candidate?.selectedItems ?? [],
    previewFilePaths: candidate?.previewFilePaths ?? filePaths.slice(0, 12),
    label: candidate?.label ?? "Code Context selection",
    warnings: candidate?.warnings ?? [],
    workingSetItem: candidate?.workingSetItem
  };
}
function admitGap(candidate) {
  const sourceKey = candidate.sourceKey?.trim();
  if (!sourceKey)
    return null;
  const stableKey = candidate.stableKey?.trim() || `gap:${sourceKey}:${candidate.kind ?? "source_unavailable"}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    kind: candidate.kind ?? "source_unavailable",
    severity: candidate.severity ?? "info",
    title: candidate.title?.trim() || "Source gap",
    detail: candidate.detail,
    sourceKey,
    ref: candidate.ref
  };
}
function admitRelationship(candidate) {
  if (!isDeterministicCodeMarketRef(candidate.sourceRef))
    return null;
  if (!isDeterministicCodeMarketRef(candidate.targetRef))
    return null;
  const sourceKeys = unique([
    ...candidate.sourceKeys ?? [],
    candidate.sourceRef.sourceKey,
    candidate.targetRef.sourceKey
  ]);
  if (sourceKeys.length === 0)
    return null;
  const stableKey = candidate.stableKey?.trim() || `relationship:${candidate.kind ?? "relates_to"}:${candidate.sourceRef.stableKey}:${candidate.targetRef.stableKey}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    kind: candidate.kind ?? "relates_to",
    sourceRef: candidate.sourceRef,
    targetRef: candidate.targetRef,
    sourceKeys,
    label: candidate.label,
    strength: clamp2(candidate.strength ?? 0.5, 0, 1),
    reasonCodes: unique(candidate.reasonCodes ?? [])
  };
}
function admitAction(candidate) {
  const mode = candidate.mode;
  const state = candidate.state ?? "enabled";
  const refs = candidate.refs ?? [];
  const reasonCodes = unique(candidate.reasonCodes ?? []);
  const sourceKeys = unique([...candidate.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]);
  const stableKey = candidate.stableKey?.trim() || candidate.id?.trim();
  const id = candidate.id?.trim() || stableKey;
  const label = candidate.label?.trim();
  if (!stableKey || !id || !label)
    return null;
  const base = {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id,
    stableKey,
    label,
    shortLabel: candidate.shortLabel,
    description: candidate.description,
    sourceKeys,
    refs,
    reasonCodes,
    sortPriority: candidate.sortPriority ?? 0
  };
  if (state === "disabled") {
    if (mode !== "disabled")
      return null;
    const disabledReason = candidate.disabledReason?.trim();
    if (!disabledReason || reasonCodes.length === 0)
      return null;
    return { ...base, state: "disabled", mode: "disabled", disabledReason };
  }
  if (sourceKeys.length === 0)
    return null;
  if (mode === "rheiAction" && candidate.rheiAction) {
    return { ...base, state: "enabled", mode: "rheiAction", rheiAction: candidate.rheiAction };
  }
  if (mode === "localOnly" && candidate.localOnly) {
    return { ...base, state: "enabled", mode: "localOnly", localOnly: candidate.localOnly };
  }
  return null;
}
function admitWorkCluster(candidate) {
  const sourceKey = candidate.sourceKey?.trim();
  if (!sourceKey)
    return null;
  const changedRefs = (candidate.changedRefs ?? []).filter(isDeterministicCodeMarketRef);
  const relatedRefs = (candidate.relatedRefs ?? []).filter(isDeterministicCodeMarketRef);
  const sourceRefs = (candidate.sourceRefs ?? []).filter(isDeterministicCodeMarketRef);
  const evidenceRefs = (candidate.evidenceRefs ?? []).filter(isDeterministicCodeMarketRef);
  const receiptRefs = (candidate.receiptRefs ?? []).filter(isDeterministicCodeMarketRef);
  const identityRefs = uniqueRefs2([
    ...changedRefs,
    ...sourceRefs,
    ...evidenceRefs,
    ...receiptRefs,
    ...relatedRefs
  ]);
  if (identityRefs.length === 0)
    return null;
  const sourceKeys = unique([
    sourceKey,
    ...candidate.sourceKeys ?? [],
    ...identityRefs.map((ref) => ref.sourceKey)
  ]);
  const stableKey = candidate.stableKey?.trim() || `work-cluster:${sourceKey}`;
  const title = candidate.title?.trim() || identityRefs[0]?.label || "Code Context work cluster";
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    sourceKey,
    sourceKeys,
    title,
    summary: candidate.summary,
    status: candidate.status ?? "observed",
    completion: candidate.completion ?? "unknown",
    changedRefs,
    relatedRefs,
    sourceRefs,
    evidenceRefs,
    receiptRefs,
    tileIds: unique(candidate.tileIds ?? []),
    relationshipIds: unique(candidate.relationshipIds ?? []),
    reasonCodes: unique(candidate.reasonCodes ?? []),
    confidence: clamp2(candidate.confidence ?? 0.5, 0, 1),
    updatedAt: candidate.updatedAt ?? 0,
    selection: candidate.selection ? normalizeSelection(candidate.selection) : undefined,
    metadata: candidate.metadata
  };
}
function admitTile(candidate) {
  const refs = candidate.refs ?? [];
  const primaryRef = refs.find(isDeterministicCodeMarketRef);
  if (!primaryRef)
    return null;
  const title = candidate.title?.trim();
  if (!title)
    return null;
  const sourceKeys = unique([...candidate.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]);
  if (sourceKeys.length === 0)
    return null;
  const stableKey = candidate.stableKey?.trim() || `tile:${primaryRef.stableKey}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    kind: candidate.kind ?? "module",
    title,
    subtitle: candidate.subtitle,
    state: candidate.state ?? "unknown",
    confidence: clamp2(candidate.confidence ?? 0.5, 0, 1),
    controlWeight: candidate.controlWeight ?? 0,
    primaryRef,
    refs,
    sourceKeys,
    reasonCodes: unique(candidate.reasonCodes ?? []),
    selection: normalizeSelection(candidate.selection),
    gaps: candidate.gaps ?? [],
    actions: candidate.actions ?? [],
    metadata: candidate.metadata
  };
}
function admitSector(candidate) {
  const stableKey = candidate.stableKey?.trim() || candidate.id?.trim();
  const title = candidate.title?.trim();
  const sourceKeys = unique(candidate.sourceKeys ?? []);
  if (!stableKey || !title || sourceKeys.length === 0)
    return null;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    id: candidate.id?.trim() || stableKey,
    stableKey,
    title,
    sourceKeys,
    tileIds: unique(candidate.tileIds ?? []),
    sortOrder: candidate.sortOrder ?? 0
  };
}
function uniqueRefs2(refs) {
  const seen = new Set;
  const output = [];
  for (const ref of refs) {
    const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(ref);
  }
  return output;
}
// ../core/src/agentFactoryRouting.ts
var AGENT_FACTORY_TEMPLATE_IDS = [
  "habit_coach",
  "wellness_coach",
  "learning_coach",
  "hobby_project_agent",
  "creative_partner",
  "personal_ops_agent",
  "project_agent",
  "codebase_agent",
  "project_review_agent"
];
var AGENT_FACTORY_SOURCES = [
  "natural_language",
  "template",
  "pulse_signal",
  "widget_promotion",
  "context_lens",
  "canvas_cli",
  "slash_command"
];
var TEMPLATE_ID_SET = new Set(AGENT_FACTORY_TEMPLATE_IDS);
var SOURCE_SET = new Set(AGENT_FACTORY_SOURCES);
// ../core/src/briefs/types.ts
var BRIEF_COMMAND_DESCRIPTORS_V1 = {
  open: {
    command: "open",
    label: "Open",
    description: "Open this item as a reference.",
    recordsPositiveEvidence: true
  },
  ask_with_this: {
    command: "ask_with_this",
    label: "Ask with this",
    description: "Use this item as context for an Ask Rhei turn.",
    recordsPositiveEvidence: true
  },
  ask_with_brief: {
    command: "ask_with_brief",
    label: "Ask with Brief",
    description: "Use the full brief as context for an Ask Rhei turn.",
    recordsPositiveEvidence: true
  },
  pin: {
    command: "pin",
    label: "Pin",
    description: "Save this item for the current work without promoting it to canonical truth.",
    defaultScope: "current_working_set",
    correctionTool: true,
    recordsPositiveEvidence: true
  },
  hide_for_me: {
    command: "hide_for_me",
    label: "Hide",
    description: "Hide this item for your ranking only.",
    defaultScope: "personal_ranking",
    correctionTool: true
  },
  why_this_appears: {
    command: "why_this_appears",
    label: "Why this appears",
    description: "Show evidence and reasoning for this item."
  },
  not_useful_here: {
    command: "not_useful_here",
    label: "Not useful here",
    description: "Downrank this item for the current working context only.",
    defaultScope: "current_working_set",
    correctionTool: true
  },
  not_related: {
    command: "not_related",
    label: "Not related",
    description: "Mark this soft connection as not related at the project level.",
    defaultScope: "project_connection",
    correctionTool: true,
    requiresConnection: true
  },
  wrong: {
    command: "wrong",
    label: "Wrong",
    description: "Flag this soft connection as wrong for review.",
    defaultScope: "project_connection",
    correctionTool: true,
    requiresConnection: true
  },
  request_review: {
    command: "request_review",
    label: "Review relationship",
    description: "Open a governed review request without mutating canonical truth.",
    defaultScope: "project_connection",
    governanceOnly: true,
    requiresConnection: true
  }
};
var BRIEF_COMMAND_LABELS_V1 = Object.fromEntries(Object.entries(BRIEF_COMMAND_DESCRIPTORS_V1).map(([command, descriptor]) => [command, descriptor.label]));
var BRIEF_COMMAND_DEFAULT_SCOPES_V1 = Object.fromEntries(Object.entries(BRIEF_COMMAND_DESCRIPTORS_V1).filter(([, descriptor]) => Boolean(descriptor.defaultScope)).map(([command, descriptor]) => [command, descriptor.defaultScope]));

// ../core/src/contextRouting/graphExecutionMode.ts
var GRAPH_EXECUTION_MODES = [
  "convex_local",
  "connected_work_shallow",
  "memgraph_depth3",
  "memgraph_depth5",
  "memgraph_depth5_plus_lite_llm"
];
// ../core/src/contextRouting/plannerHandoffGraphAdvisory.ts
var VALID_SOURCES = new Set([
  "local_code_context",
  "code_market",
  "mcp_input",
  "task_brief",
  "workroom_context_receipt",
  "connected_work_packet",
  "plan_contract",
  "external"
]);
var VALID_BASES = new Set([
  "graph_routing_policy_v1",
  "explicit_metadata",
  "default_no_live"
]);
var VALID_EVIDENCE_QUALITY = new Set(["none", "weak", "usable", "strong"]);
var VALID_GRAPH_NOISE_RISK = new Set(["unknown", "low", "medium", "high"]);
var VALID_MODES = new Set(GRAPH_EXECUTION_MODES);
// ../core/src/contextRouting/surfacePolicies.ts
var CONNECTED_SURFACE_KINDS_V1 = [
  "primary_code",
  "targeted_tests",
  "user_docs",
  "config_policy",
  "package_exports",
  "runtime_enforcement",
  "schema_persistence",
  "ui_surface",
  "design_system_or_shared_component",
  "usage_sites",
  "visual_snapshot_or_story",
  "native_counterpart",
  "receipt_audit",
  "eval_report",
  "migration_notes",
  "provider_gateway",
  "agent_handoff"
];
var COMMON_CODE_EVIDENCE = [
  "primary_edit_file",
  "context_slice",
  "source_ref",
  "evidence_ref"
];
var COMMON_SUPPORT_EVIDENCE = [
  "context_slice",
  "affected_test",
  "affected_doc",
  "config_file",
  "source_ref",
  "evidence_ref",
  "receipt_ref"
];
function required(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
  return { surfaceKind, level: "required", minEvidenceCount, evidenceTypes, rationale };
}
function optional(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
  return { surfaceKind, level: "optional", minEvidenceCount, evidenceTypes, rationale };
}
var CONNECTED_SURFACE_POLICIES_V1 = {
  shared_abstraction: {
    version: 1,
    changeShape: "shared_abstraction",
    label: "Shared abstraction",
    description: "Reusable code contracts need implementation, public contract/docs, and regression tests in the same bounded packet.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Shared behavior changes need targeted regression tests."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Public behavior should stay aligned with user-facing docs."),
      optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Export/type surfaces often carry shared abstraction contracts."),
      optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Runtime guards and helpers can constrain shared behavior."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing receipts or reports help confirm prior behavior.")
    ]
  },
  ui_behavior: {
    version: 1,
    changeShape: "ui_behavior",
    label: "UI behavior",
    description: "UI behavior packets need render code and visible surface context, with tests/docs when available.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary render/state code must be represented."),
      required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
      optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "UI regression tests are useful when present."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Trail/receipt display surfaces should remain auditable."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-visible behavior may need docs or copy updates.")
    ]
  },
  ui_reuse_or_design_system: {
    version: 1,
    changeShape: "ui_reuse_or_design_system",
    label: "UI reuse or design system",
    description: "Reusable UI/design-system opportunities need shared component context, usage sites, package exports, and visible UI surfaces in the same bounded packet.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
      required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
      required("design_system_or_shared_component", 1, COMMON_SUPPORT_EVIDENCE, "The shared UI primitive or design-system component must be represented."),
      required("usage_sites", 1, COMMON_SUPPORT_EVIDENCE, "Representative call sites must show how the reusable behavior is consumed."),
      required("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Package export surfaces must expose or bound the reusable UI contract."),
      optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Reusable UI behavior should have targeted regression tests when available."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Shared UI behavior may need docs or usage guidance."),
      optional("visual_snapshot_or_story", 1, COMMON_SUPPORT_EVIDENCE, "Visual snapshots or stories help validate reusable UI behavior."),
      optional("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes can bound adoption across usage sites."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing reports or receipts help confirm prior UI behavior.")
    ]
  },
  execution_safety: {
    version: 1,
    changeShape: "execution_safety",
    label: "Execution safety",
    description: "Safety-sensitive changes need implementation, enforcement, tests, and audit/receipt surfaces.",
    recommendedEscalation: "memgraph_depth5",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "high",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Safety behavior must include the primary implementation."),
      required("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Policy/enforcement code must be represented."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Safety changes require targeted regression tests."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Environment/config policy can change safety behavior."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipt and audit surfaces support post-run proof."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Operator docs should reflect safety policy."),
      optional("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "User-facing callbacks or flows can be affected by safety policy.")
    ]
  },
  provider_integration: {
    version: 1,
    changeShape: "provider_integration",
    label: "Provider integration",
    description: "Provider-routing changes need gateway/provider code, call-path code, docs, and targeted tests.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Provider integration must include primary call-path code."),
      required("provider_gateway", 1, COMMON_SUPPORT_EVIDENCE, "Gateway/provider routing surfaces must be present."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Provider fallback behavior needs targeted tests."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Provider integration contracts are user-facing."),
      optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Exported provider contracts should be checked."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Provider options/config can control routing."),
      optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Retry/error wrappers enforce provider behavior.")
    ]
  },
  agent_handoff: {
    version: 1,
    changeShape: "agent_handoff",
    label: "Agent handoff",
    description: "Agent handoff work needs handoff contracts, docs/work packets, and preferably tests/eval reports.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("agent_handoff", 1, COMMON_SUPPORT_EVIDENCE, "The handoff contract or work packet must be represented."),
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary handoff implementation/contract code must be present."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Agent-facing docs or markdown guidance must be present."),
      optional("eval_report", 1, COMMON_SUPPORT_EVIDENCE, "Eval reports help validate handoff usefulness."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipts can prove agent handoff lineage."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Handoff contracts should have targeted tests when available.")
    ]
  },
  docs_or_migration: {
    version: 1,
    changeShape: "docs_or_migration",
    label: "Docs or migration",
    description: "Documentation/migration work needs user docs and migration notes, with code/tests when applicable.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-facing docs must be represented."),
      required("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes or planning docs must be represented."),
      optional("primary_code", 1, COMMON_CODE_EVIDENCE, "Related implementation code can anchor docs changes."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Tests can validate migration guidance."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Migration/config policy may be relevant.")
    ]
  }
};
// ../core/src/contextRouting/semanticSelectionSignals.ts
var CONNECTED_SURFACE_KIND_SET = new Set(CONNECTED_SURFACE_KINDS_V1);
// ../core/src/contextRouting/semanticGraphRouting.ts
var PUBLIC_SURFACES = new Set(["package_exports", "user_docs"]);
var CRITICAL_SURFACES = new Set([
  "runtime_enforcement",
  "config_policy",
  "schema_persistence",
  "receipt_audit"
]);
var TOKEN_VALUE_NAMESPACES = new Set(["focus_lens", "audience", "intent", "tag", "feature_label", "risk", "context_packet"]);
// ../core/src/codeMarket/evidenceRefinement.ts
var SUPPORTED_KINDS = new Set([
  "command_diagnostic",
  "validation_result",
  "diff_packet",
  "pr_review_comment",
  "session_trace",
  "service_intelligence",
  "impact_prediction",
  "proof_plan",
  "stream_diagnostics",
  "ci_log",
  "review_diff",
  "session_validation",
  "agent_result",
  "run_summary"
]);
// ../core/src/contextLens/relationshipTaxonomy.ts
var CONNECTION_RELATIONSHIP_TYPE_REGISTRY = {
  related_to: { direction: "symmetric", riskLevel: "low" },
  knows: { direction: "symmetric", riskLevel: "low" },
  mentions: { direction: "symmetric", riskLevel: "low" },
  references: { direction: "symmetric", riskLevel: "low" },
  contradicts: { direction: "symmetric", riskLevel: "high" },
  owns: { direction: "directed", riskLevel: "medium" },
  owned_by: { direction: "directed", riskLevel: "medium" },
  depends_on: { direction: "directed", riskLevel: "medium" },
  implements: { direction: "directed", riskLevel: "medium" },
  documents: { direction: "directed", riskLevel: "medium" },
  calls: { direction: "directed", riskLevel: "medium" },
  imports: { direction: "directed", riskLevel: "medium" },
  affects: { direction: "directed", riskLevel: "medium" },
  affected_by: { direction: "directed", riskLevel: "medium" },
  uses: { direction: "directed", riskLevel: "medium" },
  uses_context: { direction: "directed", riskLevel: "medium" },
  supports: { direction: "directed", riskLevel: "medium" },
  tested_by: { direction: "directed", riskLevel: "medium" },
  covers: { direction: "directed", riskLevel: "medium" },
  verifies: { direction: "directed", riskLevel: "medium" },
  deploys: { direction: "directed", riskLevel: "medium" },
  configures: { direction: "directed", riskLevel: "medium" },
  publishes_to: { direction: "directed", riskLevel: "medium" },
  subscribes_to: { direction: "directed", riskLevel: "medium" },
  reads_from: { direction: "directed", riskLevel: "medium" },
  observes: { direction: "directed", riskLevel: "medium" },
  authenticates: { direction: "directed", riskLevel: "high" },
  authorizes: { direction: "directed", riskLevel: "high" },
  supersedes: { direction: "directed", riskLevel: "high" },
  source_of_truth_for: { direction: "directed", riskLevel: "high" },
  replaces: { direction: "directed", riskLevel: "high" },
  blocks: { direction: "directed", riskLevel: "high" },
  blocked_by: { direction: "directed", riskLevel: "high" },
  writes_to: { direction: "directed", riskLevel: "medium" },
  stores_in: { direction: "directed", riskLevel: "medium" },
  policy_for: { direction: "directed", riskLevel: "high" }
};
var CONNECTION_RELATIONSHIP_TYPES = Object.keys(CONNECTION_RELATIONSHIP_TYPE_REGISTRY);

// ../core/src/contextLens/serviceConnections.ts
var SERVICE_CONNECTION_IDENTITY_SCOPES = ["logical_service", "deployment_environment"];
var SERVICE_CONNECTION_LIFECYCLE_STATES = [
  "hint",
  "candidate",
  "verified",
  "stale",
  "rejected",
  "retracted"
];
var SERVICE_CONNECTION_OBSERVATION_STATUSES = [
  "present",
  "absent_in_latest_scan",
  "changed",
  "unknown"
];
var SERVICE_CONNECTION_SENSITIVITY_LEVELS = ["public", "internal", "sensitive", "secret"];
var SERVICE_CONNECTION_RELATIONSHIP_TYPES = [
  "publishes_to",
  "subscribes_to",
  "writes_to",
  "stores_in",
  "reads_from",
  "observes",
  "blocked_by"
];
var SERVICE_CONNECTION_ENDPOINT_KINDS = ["service", "resource"];
var SERVICE_CONNECTION_SURFACE_KINDS = [
  "api",
  "queue",
  "topic",
  "stream",
  "datastore",
  "cache",
  "object_store",
  "observability_sink",
  "config",
  "secret",
  "feature_flag",
  "runtime",
  "external_service",
  "unknown"
];
var SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS = [
  "code_static",
  "config_static",
  "runtime_receipt",
  "manual_report",
  "semantic_advisory"
];
var SERVICE_CONNECTION_EVIDENCE_TIERS = [
  "explicit_user_action",
  "accepted_truth_candidate",
  "deterministic_code_edge",
  "receipt_backed",
  "explicit_source_language",
  "repeated_reference",
  "llm_classification",
  "co_mention",
  "vector_similarity"
];
var SERVICE_CONNECTION_CANDIDATE_KINDS = [
  "http_api",
  "database",
  "auth_provider",
  "provider_client",
  "object_store",
  "queue_topic",
  "cache",
  "secret_config",
  "observability_sink",
  "runtime_owner",
  "test_proof",
  "doc_proof",
  "unknown_service_surface"
];
var SERVICE_CONNECTION_DIRECTION_HINTS = [
  "inbound_api",
  "outbound_provider",
  "reads_secret",
  "reads_datastore",
  "writes_datastore",
  "publishes_queue",
  "consumes_queue",
  "reads_cache",
  "writes_cache",
  "emits_telemetry",
  "owns_runtime",
  "proves_with_test",
  "documents",
  "unknown"
];
var SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS = [
  "path_only",
  "import_backed",
  "call_backed",
  "env_backed",
  "schema_backed",
  "test_backed",
  "doc_backed",
  "mixed_backed"
];
var SERVICE_CONNECTION_RELATIONSHIP_TYPE_SET = new Set(SERVICE_CONNECTION_RELATIONSHIP_TYPES);
var SERVICE_CONNECTION_ENDPOINT_KIND_SET = new Set(SERVICE_CONNECTION_ENDPOINT_KINDS);
var SERVICE_CONNECTION_SURFACE_KIND_SET = new Set(SERVICE_CONNECTION_SURFACE_KINDS);
var SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND_SET = new Set(SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS);
var SERVICE_CONNECTION_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_EVIDENCE_TIERS);
var SERVICE_CONNECTION_CANDIDATE_KIND_SET = new Set(SERVICE_CONNECTION_CANDIDATE_KINDS);
var SERVICE_CONNECTION_DIRECTION_HINT_SET = new Set(SERVICE_CONNECTION_DIRECTION_HINTS);
var SERVICE_CONNECTION_STATIC_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS);
var SERVICE_CONNECTION_IDENTITY_SCOPE_SET = new Set(SERVICE_CONNECTION_IDENTITY_SCOPES);
var SERVICE_CONNECTION_LIFECYCLE_STATE_SET = new Set(SERVICE_CONNECTION_LIFECYCLE_STATES);
var SERVICE_CONNECTION_CONNECTED_WORK_STATE_SET = new Set([
  "observed",
  "usable_hint",
  "high_confidence_hint",
  "review_candidate",
  "canonical",
  "dismissed",
  "stale",
  "conflicted",
  "invalidated"
]);
var SERVICE_CONNECTION_OBSERVATION_STATUS_SET = new Set(SERVICE_CONNECTION_OBSERVATION_STATUSES);
var SERVICE_CONNECTION_SENSITIVITY_LEVEL_SET = new Set(SERVICE_CONNECTION_SENSITIVITY_LEVELS);

// ../core/src/codeMarket/localContextForGoal/contracts.ts
var ROUTE_SLOT_GENERIC_TERMS = new Set(["route", "routing", "slot", "rerank", "retrieval", "graph", "memgraph", "seed", "confidence", "exact", "evidence", "implementation"]);
var TOOL_COMPARISON_TERMS = new Set([
  "actionability",
  "absence",
  "compare",
  "comparison",
  "criterion",
  "criteria",
  "deepness",
  "evaluate",
  "exactness",
  "mcp",
  "oracle",
  "output",
  "outputs",
  "product",
  "proof",
  "repoprompt",
  "safety",
  "score",
  "scores",
  "selection",
  "selector",
  "speed",
  "tokens",
  "usefulness"
]);
var TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES = [
  "apps/web/src/components/code-workroom/useCodeWorkroomState.ts",
  "apps/web/src/components/code-workroom/types.ts",
  "apps/web/src/components/code-workroom/CodeWorkroomView.tsx"
];
var TEAM_BRIDGE_RELATED_UI_SURFACE_FILES = [
  "apps/web/src/components/canvas/Canvas.tsx",
  "apps/web/src/components/code-workroom/index.ts",
  "apps/web/src/components/canvas/ExpoCanvas.tsx",
  "packages/canvas/src/Canvas.tsx"
];
var TEAM_BRIDGE_NEXT_SLICE_FILES = [
  ...TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES,
  "apps/web/src/components/canvas/Canvas.tsx"
];
var TEAM_BRIDGE_UI_PATH_HINTS = [
  ...TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES,
  ...TEAM_BRIDGE_RELATED_UI_SURFACE_FILES
].map((path) => path.toLowerCase());
var TEAM_BRIDGE_PRODUCT_EXACT_PATHS = [
  "convex/code_layer/teambridge.ts",
  ...TEAM_BRIDGE_UI_PATH_HINTS
];
var TEAM_BRIDGE_BACKEND_SYMBOL_HINTS = new Set([
  "buildTeamBridgeSessionState",
  "getTeamBridgeSessionState",
  "getTeamBridgeSessionStateInternal",
  "startTeamBridgeFromHandoffInternal",
  "runCodeAgentChildBridgeInternal",
  "recordToolTelemetryInternal"
]);
var DOC_EXTENSIONS = new Set([".md", ".mdx"]);
var CODE_EXTENSIONS = new Set([
  ".cjs",
  ".css",
  ".cts",
  ".dart",
  ".go",
  ".java",
  ".js",
  ".jsx",
  ".json",
  ".kt",
  ".md",
  ".mdx",
  ".mjs",
  ".mts",
  ".php",
  ".py",
  ".pyi",
  ".rb",
  ".rs",
  ".sh",
  ".sql",
  ".swift",
  ".toml",
  ".ts",
  ".tsx",
  ".yaml",
  ".yml"
]);
var STOP_WORDS = new Set([
  "about",
  "after",
  "add",
  "adding",
  "advisory",
  "agent",
  "and",
  "build",
  "building",
  "can",
  "code",
  "context",
  "debugging",
  "files",
  "for",
  "from",
  "get",
  "goal",
  "have",
  "how",
  "improve",
  "into",
  "local",
  "make",
  "next",
  "only",
  "path",
  "paths",
  "plan",
  "report",
  "repo",
  "rhei",
  "safe",
  "then",
  "that",
  "the",
  "this",
  "tool",
  "use",
  "while",
  "with"
]);
// ../core/src/codeMarket/workImpactOverlay.ts
function codeMarketWorkClusterToWorkImpactOverlayV1(args) {
  const cluster = args.cluster;
  const generatedAt = args.generatedAt ?? cluster.updatedAt;
  const sourceKind = args.sourceKind ?? sourceKindFromCluster(cluster);
  const sourceRefs = uniqueRefs3(cluster.sourceRefs.length > 0 ? cluster.sourceRefs : cluster.receiptRefs);
  const sourceKey = cluster.sourceKey;
  const nodes = [];
  const edges = [];
  const sourceNode = overlayNode({
    role: "source",
    kind: "source",
    id: cluster.sourceKey,
    label: cluster.title,
    refs: sourceRefs,
    sourceKeys: cluster.sourceKeys,
    reasonCodes: unique(["source:work_cluster", ...cluster.reasonCodes]),
    metadata: cluster.metadata
  });
  nodes.push(sourceNode);
  for (const ref of cluster.changedRefs) {
    const node = overlayNode({ role: "scope", kind: "changed_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["scope:changed_ref"] });
    nodes.push(node);
    edges.push(overlayEdge({ kind: "touches", fromNodeId: sourceNode.nodeId, toNodeId: node.nodeId, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["source:touches_changed_ref"] }));
  }
  for (const ref of cluster.relatedRefs) {
    nodes.push(overlayNode({ role: "impact", kind: "impacted_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["impact:related_ref"] }));
  }
  for (const ref of cluster.evidenceRefs) {
    const node = overlayNode({ role: "evidence", kind: "evidence_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], evidenceRefs: [ref], reasonCodes: ["evidence:work_cluster_ref"] });
    nodes.push(node);
    evidencePush(nodes, edges, node, cluster.changedRefs, sourceKey);
  }
  for (const ref of cluster.receiptRefs) {
    const node = overlayNode({ role: "evidence", kind: "receipt_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], receiptRefs: [ref], reasonCodes: ["evidence:receipt_ref"] });
    nodes.push(node);
    evidencePush(nodes, edges, node, cluster.changedRefs, sourceKey);
  }
  const overlayId = stableId("work-impact-overlay", [sourceKind, cluster.stableKey]);
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    kind: "code_market_work_impact_overlay",
    overlayId,
    stableKey: overlayId,
    source: {
      kind: sourceKind,
      sourceId: cluster.sourceKey,
      label: cluster.title,
      generatedFrom: "CodeMarketWorkClusterV1",
      refs: sourceRefs,
      sourceKeys: cluster.sourceKeys
    },
    scope: {
      repoId: stringValue(cluster.selection?.repoId),
      surface: surfaceFromSourceKind(sourceKind),
      filePaths: unique(cluster.changedRefs.map((ref) => ref.path)),
      changedRefs: cluster.changedRefs,
      impactedRefs: cluster.relatedRefs,
      relatedRefs: cluster.relatedRefs,
      sourceRefs,
      evidenceRefs: cluster.evidenceRefs,
      receiptRefs: cluster.receiptRefs
    },
    status: {
      state: overlayStatusFromClusterStatus(cluster.status),
      clusterStatus: cluster.status,
      completion: cluster.completion,
      updatedAt: generatedAt,
      reasonCodes: unique([`cluster_status:${cluster.status}`, `completion:${cluster.completion}`])
    },
    nodes: dedupeNodes(nodes),
    edges: dedupeEdges(edges),
    evidence: dedupeEvidence([
      ...cluster.evidenceRefs.map((ref) => overlayEvidence({ kind: "evidence_ref", status: "used", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["evidence:work_cluster_ref"], observedAt: generatedAt })),
      ...cluster.receiptRefs.map((ref) => overlayEvidence({ kind: "receipt_ref", status: "used", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["evidence:receipt_ref"], observedAt: generatedAt }))
    ]),
    blockerNodeIds: [],
    proofNodeIds: [],
    impactNodeIds: unique(nodes.filter((node) => node.role === "impact").map((node) => node.nodeId)),
    workClusterIds: [cluster.id],
    reasonCodes: unique(["work_impact_overlay", `source:${sourceKind}`, ...cluster.reasonCodes]),
    generatedAt,
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true,
    metadata: {
      ...cluster.metadata ?? {},
      sourceClusterId: cluster.id,
      sourceClusterStableKey: cluster.stableKey,
      sourceTileIds: cluster.tileIds,
      sourceRelationshipIds: cluster.relationshipIds,
      sourceSelection: cluster.selection,
      sourceSummary: cluster.summary,
      sourceConfidence: cluster.confidence
    }
  };
}
function overlayNode(args) {
  const refs = uniqueRefs3([...args.ref ? [args.ref] : [], ...args.refs ?? []]);
  const stableKey = `work-impact-node:${args.kind}:${stableHash(args.id)}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    nodeId: stableKey,
    stableKey,
    role: args.role,
    kind: args.kind,
    label: args.label,
    status: args.status,
    ref: args.ref,
    refs,
    filePaths: unique([...args.filePaths ?? [], ...refs.map((ref) => ref.path)]),
    sourceKeys: unique([...args.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]),
    evidenceRefs: uniqueRefs3(args.evidenceRefs ?? []),
    receiptRefs: uniqueRefs3(args.receiptRefs ?? []),
    reasonCodes: unique(args.reasonCodes ?? []),
    metadata: args.metadata
  };
}
function overlayEdge(args) {
  const stableKey = `work-impact-edge:${args.kind}:${stableHash(`${args.fromNodeId}->${args.toNodeId}`)}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    edgeId: stableKey,
    stableKey,
    kind: args.kind,
    fromNodeId: args.fromNodeId,
    toNodeId: args.toNodeId,
    refs: uniqueRefs3(args.refs ?? []),
    sourceKeys: unique([...args.sourceKeys ?? [], ...(args.refs ?? []).map((ref) => ref.sourceKey)]),
    reasonCodes: unique(args.reasonCodes ?? []),
    label: args.label,
    metadata: args.metadata
  };
}
function overlayEvidence(args) {
  const stableKey = `work-impact-evidence:${args.kind}:${stableHash(args.id)}`;
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    evidenceId: stableKey,
    stableKey,
    kind: args.kind,
    status: args.status,
    label: args.label,
    refs: uniqueRefs3(args.refs ?? []),
    sourceKeys: unique([...args.sourceKeys ?? [], ...(args.refs ?? []).map((ref) => ref.sourceKey)]),
    reasonCodes: unique(args.reasonCodes ?? []),
    observedAt: args.observedAt,
    metadata: args.metadata
  };
}
function evidencePush(_nodes, edges, evidenceNode, changedRefs, sourceKey) {
  for (const changedRef of changedRefs) {
    const changedNodeId = `work-impact-node:changed_ref:${stableHash(changedRef.stableKey)}`;
    edges.push(overlayEdge({ kind: "evidences", fromNodeId: evidenceNode.nodeId, toNodeId: changedNodeId, refs: [changedRef, ...evidenceNode.refs], sourceKeys: [sourceKey, changedRef.sourceKey], reasonCodes: ["evidence:work_cluster_ref"] }));
  }
}
function sourceKindFromCluster(cluster) {
  const source = stringValue((cluster.metadata ?? {})["source"]);
  if (isWorkImpactSourceKind(source))
    return source;
  return "code_market";
}
function isWorkImpactSourceKind(value) {
  return value === "pr_review" || value === "agent_edit_session" || value === "trail_story" || value === "mcp_context" || value === "repo_intelligence" || value === "code_trail" || value === "code_market";
}
function surfaceFromSourceKind(sourceKind) {
  if (sourceKind === "pr_review")
    return "pr_review";
  if (sourceKind === "agent_edit_session")
    return "agent_edit_session";
  if (sourceKind === "mcp_context")
    return "mcp_context";
  if (sourceKind === "repo_intelligence")
    return "repo_intelligence";
  if (sourceKind === "trail_story" || sourceKind === "code_trail")
    return "trail_story";
  return "code_map";
}
function overlayStatusFromClusterStatus(status) {
  if (status === "in_progress" || status === "forming")
    return "in_progress";
  if (status === "ready_review")
    return "needs_review";
  if (status === "applied")
    return "applied";
  if (status === "stale")
    return "stale";
  return "observed";
}
function uniqueRefs3(refs) {
  const seen = new Set;
  const output = [];
  for (const ref of refs) {
    if (!ref?.id?.trim())
      continue;
    const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(ref);
  }
  return output;
}
function dedupeNodes(nodes) {
  const seen = new Set;
  const output = [];
  for (const node of nodes) {
    if (seen.has(node.stableKey))
      continue;
    seen.add(node.stableKey);
    output.push(node);
  }
  return output;
}
function dedupeEdges(edges) {
  const seen = new Set;
  const output = [];
  for (const edge of edges) {
    if (seen.has(edge.stableKey))
      continue;
    seen.add(edge.stableKey);
    output.push(edge);
  }
  return output;
}
function dedupeEvidence(evidence) {
  const seen = new Set;
  const output = [];
  for (const item of evidence) {
    if (seen.has(item.stableKey))
      continue;
    seen.add(item.stableKey);
    output.push(item);
  }
  return output;
}
function isString(value) {
  return typeof value === "string" && value.trim().length > 0;
}
function stringValue(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function stableId(prefix, parts) {
  return `${prefix}:${stableHash(parts.filter(isString).join("|"))}`;
}
function stableHash(input) {
  let hash = 2166136261;
  for (let index = 0;index < input.length; index += 1) {
    hash ^= input.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0");
}

// ../core/src/codeMarket/localContextForGoal/exactFileSelection.ts
var CONTINUATION_WORK_MEMORY_TERMS = new Set(["continue", "continuing", "current", "resume", "resuming", "next", "now", "focus", "work", "working"]);
// ../core/src/codeMarket/fixtures.ts
var CODE_MARKET_FIXTURE_GENERATED_AT = 1779000000000;
var CODE_MARKET_FIXTURE_PROJECT_ID = "project_code_market_fixture";
var CODE_MARKET_FIXTURE_REPO_ID = "repo_rhei_fixture";
var CODE_MARKET_FIXTURE_MODULE_ID = "module:packages/core/src/codeMarket";
var codeMarketFixtureScope = {
  projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
  repoId: CODE_MARKET_FIXTURE_REPO_ID,
  repoName: "rhei",
  surface: "pulse",
  groupBy: "directory",
  moduleDepth: 2,
  pathPrefix: "packages/core/src/codeMarket",
  focusedModuleId: CODE_MARKET_FIXTURE_MODULE_ID,
  selectedModuleIds: [CODE_MARKET_FIXTURE_MODULE_ID],
  codeScopeId: "code_scope_code_market_fixture",
  workingSetSnapshotHash: "working-set:fixture:v1",
  canvasSurfaceId: "canvas-surface:code-market-fixture",
  chatThreadId: "thread:code-market-fixture"
};
var codeMarketFixtureRepoRef = {
  kind: "repository",
  id: CODE_MARKET_FIXTURE_REPO_ID,
  stableKey: `repo:${CODE_MARKET_FIXTURE_REPO_ID}`,
  sourceKey: "source:code-index:repo:rhei",
  authority: "code_index",
  label: "rhei"
};
var codeMarketFixtureModuleRef = {
  kind: "module",
  id: CODE_MARKET_FIXTURE_MODULE_ID,
  stableKey: `module:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket`,
  sourceKey: "source:code-index:module:packages/core/src/codeMarket",
  authority: "code_index",
  label: "Code Context core",
  path: "packages/core/src/codeMarket"
};
var codeMarketFixtureFileRef = {
  kind: "file",
  id: "file:packages/core/src/codeMarket/selectors.ts",
  stableKey: `file:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket/selectors.ts`,
  sourceKey: "source:code-index:file:packages/core/src/codeMarket/selectors.ts",
  authority: "code_index",
  label: "selectors.ts",
  path: "packages/core/src/codeMarket/selectors.ts"
};
var codeMarketFixtureNodeRef = {
  kind: "code_node",
  id: "node:packages/core/src/codeMarket/selectors.ts#admitTile",
  stableKey: `node:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket/selectors.ts#admitTile`,
  sourceKey: "source:code-index:node:admitTile",
  authority: "code_index",
  label: "admitTile",
  path: "packages/core/src/codeMarket/selectors.ts"
};
var codeMarketFixtureEdgeRef = {
  kind: "code_edge",
  id: "edge:fixtures-to-selectors",
  stableKey: `edge:${CODE_MARKET_FIXTURE_REPO_ID}:fixtures.ts->selectors.ts`,
  sourceKey: "source:code-edge:fixtures-to-selectors",
  authority: "code_edge",
  label: "fixtures imports selectors"
};
var codeMarketFixturePulseSignalRef = {
  kind: "pulse_signal",
  id: "pulse_signal:code-market-contract-change",
  stableKey: "pulse_signal:code-market-contract-change",
  sourceKey: "source:pulse-signal:code-market-contract-change",
  authority: "pulse_signal",
  label: "Code Context contract changed",
  metadata: { groupKey: "code-market-contract-change" }
};
var codeMarketFixtureReceiptRef = {
  kind: "receipt",
  id: "receipt:code-market-contract-context",
  stableKey: "receipt:code-market-contract-context",
  sourceKey: "source:receipt:code-market-contract-context",
  authority: "receipt",
  label: "Context receipt ready"
};
var codeMarketFixtureSources = [
  {
    key: codeMarketFixtureRepoRef.sourceKey,
    kind: "code_index",
    ref: codeMarketFixtureRepoRef,
    label: "Repository index",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 3000,
    confidence: 0.98,
    watermark: "repo-index:v1"
  },
  {
    key: codeMarketFixtureModuleRef.sourceKey,
    kind: "code_index",
    ref: codeMarketFixtureModuleRef,
    label: "Module index",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 2000,
    confidence: 0.96,
    watermark: "module-index:v1"
  },
  {
    key: codeMarketFixtureFileRef.sourceKey,
    kind: "code_index",
    ref: codeMarketFixtureFileRef,
    label: "File index",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 1500,
    confidence: 0.95,
    watermark: "file-index:v1"
  },
  {
    key: codeMarketFixtureEdgeRef.sourceKey,
    kind: "code_edge",
    ref: codeMarketFixtureEdgeRef,
    label: "Code edge index",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 1000,
    confidence: 0.9,
    watermark: "edge-index:v1"
  },
  {
    key: codeMarketFixturePulseSignalRef.sourceKey,
    kind: "pulse_signal",
    ref: codeMarketFixturePulseSignalRef,
    label: "Pulse changed-work signal",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 750,
    confidence: 0.88,
    watermark: "pulse-signal:v1"
  },
  {
    key: codeMarketFixtureReceiptRef.sourceKey,
    kind: "receipt",
    ref: codeMarketFixtureReceiptRef,
    label: "Context receipt",
    observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 500,
    confidence: 0.84,
    watermark: "receipt:v1"
  }
];
var codeMarketFixtureSelection = {
  source: "code_market",
  repoId: CODE_MARKET_FIXTURE_REPO_ID,
  filePaths: [
    "packages/core/src/codeMarket/types.ts",
    "packages/core/src/codeMarket/selectors.ts",
    "packages/core/src/codeMarket/fixtures.ts"
  ],
  nodeIds: [codeMarketFixtureNodeRef.id],
  moduleIds: [CODE_MARKET_FIXTURE_MODULE_ID],
  entityIds: ["entity:code-market-contract"],
  selectedItems: [
    {
      kind: "module",
      moduleId: CODE_MARKET_FIXTURE_MODULE_ID,
      path: "packages/core/src/codeMarket",
      label: "Code Context core",
      fileCount: 3,
      nodeCount: 1
    }
  ],
  previewFilePaths: ["packages/core/src/codeMarket/types.ts", "packages/core/src/codeMarket/selectors.ts"],
  label: "Code Context: core contract",
  warnings: []
};
var codeMarketFixtureRheiAction = {
  schemaVersion: 1,
  actionModelVersion: 1,
  id: "rhei-action:code-market:start-workroom",
  dedupeKey: "rhei-action:code-market:start-workroom",
  label: "Open in Workroom",
  shortLabel: "Workroom",
  description: "Open this Code Context selection in the code workroom.",
  verb: "start_workroom",
  sourceSurface: "pulse",
  targetRef: {
    kind: "code_node",
    id: codeMarketFixtureNodeRef.id,
    label: codeMarketFixtureNodeRef.label,
    projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
    metadata: { repoId: CODE_MARKET_FIXTURE_REPO_ID }
  },
  executionPath: "workroom",
  requiredAuthority: "code_workroom",
  policyState: "enabled",
  reasonCodes: ["code_market_fixture_action"],
  evidenceRefs: [
    {
      kind: "code_file",
      id: codeMarketFixtureFileRef.id,
      label: codeMarketFixtureFileRef.label
    }
  ],
  sourceRefs: [{ kind: "code_index", id: codeMarketFixtureModuleRef.id, label: codeMarketFixtureModuleRef.label }],
  receiptRefs: [],
  privacyBoundary: "project",
  visibility: "shared_project",
  projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
  authority: {
    required: "code_workroom",
    executionPath: "workroom",
    authorityRef: {
      kind: "repository",
      id: CODE_MARKET_FIXTURE_REPO_ID,
      label: "rhei",
      projectId: CODE_MARKET_FIXTURE_PROJECT_ID
    }
  },
  policy: {
    state: "enabled",
    requiresConfirmation: false,
    requiresTruthGate: false,
    reasonCodes: ["code_market_fixture_action"]
  },
  refs: {
    target: {
      kind: "code_node",
      id: codeMarketFixtureNodeRef.id,
      label: codeMarketFixtureNodeRef.label,
      projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
      metadata: { repoId: CODE_MARKET_FIXTURE_REPO_ID }
    },
    evidenceRefs: [
      {
        kind: "code_file",
        id: codeMarketFixtureFileRef.id,
        label: codeMarketFixtureFileRef.label
      }
    ],
    sourceRefs: [{ kind: "code_index", id: codeMarketFixtureModuleRef.id, label: codeMarketFixtureModuleRef.label }],
    receiptRefs: [],
    sourceSignalIds: []
  },
  audit: {
    resolverVersion: "agentos-actions-v1",
    schemaVersion: 1,
    actionModelVersion: 1,
    sourceSurface: "pulse",
    groupKey: "code-market-fixture",
    generatedAt: CODE_MARKET_FIXTURE_GENERATED_AT
  },
  deterministic: {
    id: "rhei-action:code-market:start-workroom",
    dedupeKey: "rhei-action:code-market:start-workroom"
  },
  metadata: { codeMarketTileId: "tile:code-market-core" },
  sortPriority: 10
};
function required2(value, name) {
  if (!value)
    throw new Error(`Invalid Code Context fixture ${name}`);
  return value;
}
function createCodeMarketFixtureSnapshot() {
  const gap = required2(admitGap({
    id: "gap:readiness:partial-receipts",
    stableKey: "gap:readiness:partial-receipts",
    kind: "index_warming",
    severity: "info",
    title: "Receipt overlay is warming",
    detail: "The core contract can render before optional receipt overlays finish.",
    sourceKey: codeMarketFixtureRepoRef.sourceKey,
    ref: codeMarketFixtureRepoRef
  }), "gap");
  const actions = [
    required2(admitAction({
      id: "action:code-market:open-workroom",
      stableKey: "action:code-market:open-workroom",
      label: "Open in Workroom",
      shortLabel: "Workroom",
      state: "enabled",
      mode: "rheiAction",
      rheiAction: codeMarketFixtureRheiAction,
      sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
      refs: [codeMarketFixtureModuleRef, codeMarketFixtureNodeRef],
      reasonCodes: ["selection_has_code_scope"],
      sortPriority: 10
    }), "rhei action"),
    required2(admitAction({
      id: "action:code-market:pin-layout",
      stableKey: "action:code-market:pin-layout",
      label: "Pin layout",
      shortLabel: "Pin",
      state: "enabled",
      mode: "localOnly",
      localOnly: { kind: "pin_layout", targetTileId: "tile:code-market-core" },
      sourceKeys: ["source:local-state:code-market-controls"],
      refs: [codeMarketFixtureModuleRef],
      reasonCodes: ["client_local_surface_control"],
      sortPriority: 20
    }), "local action"),
    required2(admitAction({
      id: "action:code-market:assign-agent",
      stableKey: "action:code-market:assign-agent",
      label: "Assign agent",
      shortLabel: "Assign",
      state: "disabled",
      mode: "disabled",
      disabledReason: "Agent assignment authority is not available in the core contract slice.",
      sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
      refs: [codeMarketFixtureModuleRef],
      reasonCodes: ["missing_assignment_authority"],
      sortPriority: 30
    }), "disabled action")
  ];
  const tile = required2(admitTile({
    id: "tile:code-market-core",
    stableKey: "tile:repo_rhei_fixture:packages/core/src/codeMarket",
    kind: "module",
    title: "Code Context core contract",
    subtitle: "Shared DTOs, selectors, fixture, and action invariants",
    state: "review_needed",
    confidence: 0.92,
    controlWeight: 7.25,
    refs: [codeMarketFixtureModuleRef, codeMarketFixtureFileRef, codeMarketFixtureNodeRef],
    sourceKeys: [codeMarketFixtureRepoRef.sourceKey],
    reasonCodes: ["deterministic_module_ref", "selection_has_file_and_node_payload"],
    selection: codeMarketFixtureSelection,
    gaps: [gap],
    actions,
    metadata: { fixture: true }
  }), "tile");
  const relationship = required2(admitRelationship({
    id: "relationship:fixtures-import-selectors",
    stableKey: codeMarketFixtureEdgeRef.stableKey,
    kind: "imports",
    sourceRef: codeMarketFixtureFileRef,
    targetRef: codeMarketFixtureNodeRef,
    sourceKeys: [codeMarketFixtureEdgeRef.sourceKey],
    label: "Fixture exercises selector admission",
    strength: 0.86,
    reasonCodes: ["source_backed_code_edge"]
  }), "relationship");
  const workCluster = required2(admitWorkCluster({
    id: "work-cluster:code-market-contract-change",
    stableKey: "work-cluster:repo_rhei_fixture:code-market-contract-change",
    sourceKey: codeMarketFixturePulseSignalRef.sourceKey,
    sourceKeys: [codeMarketFixtureModuleRef.sourceKey, codeMarketFixtureReceiptRef.sourceKey],
    title: "Code Context contract work cluster",
    summary: "Changed core Code Context contract files are grouped for review and handoff.",
    status: "ready_review",
    completion: "partial",
    changedRefs: [codeMarketFixtureFileRef],
    relatedRefs: [codeMarketFixtureModuleRef, codeMarketFixtureNodeRef],
    sourceRefs: [codeMarketFixturePulseSignalRef, codeMarketFixtureModuleRef],
    evidenceRefs: [codeMarketFixtureFileRef, codeMarketFixtureNodeRef],
    receiptRefs: [codeMarketFixtureReceiptRef],
    tileIds: [tile.id],
    relationshipIds: [relationship.id],
    reasonCodes: ["source_backed_changed_work", "selection_has_file_and_node_payload"],
    confidence: 0.88,
    updatedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 250,
    selection: codeMarketFixtureSelection,
    metadata: { fixture: true }
  }), "work cluster");
  const sector = required2(admitSector({
    id: "sector:code-market-contract",
    stableKey: "sector:code-market-contract",
    title: "Contract surface",
    sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
    tileIds: [tile.id],
    sortOrder: 1
  }), "sector");
  const gaps = [gap];
  const tiles = [tile];
  const workClusters = [workCluster];
  return {
    schemaVersion: CODE_MARKET_SCHEMA_VERSION,
    readModelVersion: CODE_MARKET_READ_MODEL_VERSION,
    modelVersion: CODE_MARKET_MODEL_VERSION,
    projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
    generatedAt: CODE_MARKET_FIXTURE_GENERATED_AT,
    scope: codeMarketFixtureScope,
    readiness: {
      state: "partial",
      title: "Code Context fixture is source-backed",
      detail: "Core contract is ready; optional overlays are represented as gaps.",
      reasonCodes: ["fixture_partial_overlay"]
    },
    sectors: [sector],
    tiles,
    workClusters,
    relationships: [relationship],
    gaps,
    sources: codeMarketFixtureSources,
    selections: [codeMarketFixtureSelection],
    sourceWatermarks: codeMarketFixtureSources.map((source) => ({
      sourceKey: source.key,
      kind: source.kind,
      complete: true,
      updatedAt: source.observedAt,
      cursor: source.watermark
    })),
    truncation: [
      {
        sourceKey: codeMarketFixtureModuleRef.sourceKey,
        limit: 50,
        returned: 1,
        truncated: false
      }
    ]
  };
}
var codeMarketFixtureSnapshot = createCodeMarketFixtureSnapshot();
// ../core/src/codeTrail/codeMarketAdapter.ts
var REF_KIND_MAP = {
  repository: "repository",
  file: "file",
  code_node: "code_node",
  context_receipt: "receipt",
  sync_receipt: "receipt",
  plan_contract: "plan_contract",
  session: "code_session",
  code_workroom_run: "code_workroom_run",
  code_patch_run: "code_patch_run",
  agent_edit_session: "agent_edit_session",
  code_write_proposal: "local_state",
  evidence_job: "evidence_job",
  truth_candidate: "truth_candidate",
  mcp_context_run: "local_state",
  mcp_run_graph: "local_state",
  trail_import: "local_state",
  code_change_story: "code_change_story",
  pr_snapshot: "pr_snapshot",
  review_room: "review_room",
  capability_run: "local_state"
};
var REF_AUTHORITY_MAP = {
  repository: "code_index",
  file: "code_index",
  code_node: "code_index",
  receipt: "receipt",
  plan_contract: "plan_contract",
  code_session: "code_session",
  code_workroom_run: "code_workroom_run",
  code_patch_run: "code_patch_run",
  agent_edit_session: "agent_edit_session",
  evidence_job: "evidence_job",
  truth_candidate: "truth_candidate",
  pr_snapshot: "pr_review",
  review_room: "pr_review",
  code_change_story: "trail_story",
  local_state: "local_only"
};
var SOURCE_KIND_MAP = {
  workroom_ledger: "code_session",
  code_context_receipt: "receipt",
  sync_receipt: "receipt",
  plan_contract: "plan_contract",
  workroom_run: "code_workroom_run",
  workroom_event: "code_workroom_run",
  patch_run: "code_patch_run",
  patch_file_diff: "code_patch_run",
  evidence_job: "evidence_job",
  truth_candidate: "truth_candidate",
  agent_edit_session: "agent_edit_session",
  code_write_proposal: "agent_edit_session",
  capability_run: "capability_run",
  trail_import: "local_state",
  local_mcp_context_run: "local_state",
  local_mcp_run_graph: "local_state",
  code_story: "trail_story",
  pr_review: "pr_review",
  code_market: "local_state"
};
var GAP_KIND_MAP = {
  source_unavailable: "source_unavailable",
  missing_source_row: "source_unavailable",
  permission_filtered: "permission_filtered",
  truncated_source: "truncated_source",
  unresolved_reference: "source_unavailable",
  local_history_unavailable: "source_unavailable",
  diff_unavailable: "source_unavailable"
};
var WORKROOM_LEDGER_ENTRY_KINDS = new Set([
  "workroom_run",
  "context_receipt",
  "plan_contract",
  "patch_run",
  "evidence_job",
  "truth_candidate"
]);
var LIFECYCLE_WORK_ENTRY_KINDS = new Set([
  "context_receipt",
  "validation_receipt",
  "diagnostic_edit_trace",
  "agent_edit_session",
  "observation"
]);
function codeTrailStatusToCodeMarketWorkClusterStatus(status) {
  if (["queued", "running", "waiting"].includes(status))
    return "in_progress";
  if (["ready", "review_needed", "blocked", "failed"].includes(status))
    return "ready_review";
  if (["succeeded", "completed", "approved", "canonical"].includes(status))
    return "applied";
  if (["aborted", "superseded", "rejected"].includes(status))
    return "stale";
  return "observed";
}
function codeTrailEntryToCodeMarketCompletion(entry) {
  if (entry.entryKind === "truth_candidate" && ["approved", "canonical"].includes(entry.status)) {
    return "done_by_review";
  }
  if (["context_receipt", "workroom_run"].includes(entry.entryKind) && ["ready", "succeeded", "completed"].includes(entry.status)) {
    return "done_by_receipt";
  }
  if (entry.entryKind === "patch_run" && ["succeeded", "completed", "approved"].includes(entry.status)) {
    return "likely_done";
  }
  if (["queued", "running", "waiting", "ready", "review_needed"].includes(entry.status)) {
    return "partial";
  }
  return "unknown";
}
function codeTrailRefToCodeMarketRef(ref) {
  const kind = REF_KIND_MAP[ref.kind] ?? "local_state";
  return {
    kind,
    id: ref.id,
    stableKey: ref.stableKey,
    sourceKey: ref.sourceKey,
    authority: REF_AUTHORITY_MAP[kind] ?? "local_only",
    label: ref.label,
    path: ref.path,
    href: ref.href,
    metadata: ref.metadata
  };
}
function codeTrailSourceToCodeMarketSource(source) {
  return {
    key: source.key,
    kind: SOURCE_KIND_MAP[source.kind] ?? "local_state",
    ref: source.ref ? codeTrailRefToCodeMarketRef(source.ref) : undefined,
    label: source.label,
    observedAt: source.observedAt,
    confidence: source.confidence,
    watermark: source.watermark
  };
}
function codeTrailGapToCodeMarketGap(gap) {
  return admitGap({
    id: `gap:code-trail:${gap.id}`,
    stableKey: `gap:code-trail:${gap.stableKey}`,
    kind: GAP_KIND_MAP[gap.kind] ?? "source_unavailable",
    severity: gap.severity,
    title: gap.title,
    detail: gap.detail,
    sourceKey: gap.sourceKey,
    ref: gap.ref ? codeTrailRefToCodeMarketRef(gap.ref) : undefined
  });
}
function codeTrailEntriesToCodeMarketWorkImpactOverlays(entries) {
  return codeTrailEntriesToCodeMarketWorkClusters(entries).map((cluster) => codeMarketWorkClusterToWorkImpactOverlayV1({
    cluster,
    sourceKind: cluster.reasonCodes.some((code) => code.includes("pr_review")) ? "pr_review" : "code_trail",
    generatedAt: cluster.updatedAt
  }));
}
function codeTrailEntriesToCodeMarketWorkClusters(entries) {
  const groups = buildWorkroomGroupMaps(entries);
  const drafts = new Map;
  for (const entry of entries) {
    if (!WORKROOM_LEDGER_ENTRY_KINDS.has(entry.entryKind) && !isLifecycleWorkEntry(entry))
      continue;
    const sourceKey = codeTrailEntryClusterSourceKey(entry, groups);
    upsertDraft(drafts, entryToDraft(entry, sourceKey));
  }
  return Array.from(drafts.values()).map((draft) => admitWorkCluster({
    id: `work-cluster:${draft.sourceKey}`,
    stableKey: `work-cluster:${draft.sourceKey}`,
    sourceKey: draft.sourceKey,
    sourceKeys: draft.sourceKeys,
    title: draft.title,
    summary: draft.summary,
    status: draft.status,
    completion: draft.completion,
    changedRefs: draft.changedRefs,
    relatedRefs: draft.relatedRefs,
    sourceRefs: draft.sourceRefs,
    evidenceRefs: draft.evidenceRefs,
    receiptRefs: draft.receiptRefs,
    reasonCodes: draft.reasonCodes,
    confidence: draft.confidence,
    updatedAt: draft.updatedAt,
    metadata: draft.metadata
  })).filter((cluster) => cluster !== null);
}
function isLifecycleWorkEntry(entry) {
  return LIFECYCLE_WORK_ENTRY_KINDS.has(entry.entryKind) && entry.reasonCodes.some((code) => code.startsWith("goal_lifecycle:"));
}
function buildWorkroomGroupMaps(entries) {
  const receiptToGroup = new Map;
  const planToGroup = new Map;
  const patchToGroup = new Map;
  const truthToGroup = new Map;
  const workroomRunToGroup = new Map;
  for (const entry of entries) {
    if (entry.primaryRef.kind === "session") {
      workroomRunToGroup.set(entry.primaryRef.id, codeSessionClusterSourceKey(entry.primaryRef.id));
    }
    if (entry.primaryRef.kind === "code_workroom_run") {
      const sessionRef = entry.inputRefs.find((ref) => ref.kind === "session");
      workroomRunToGroup.set(entry.primaryRef.id, sessionRef ? codeSessionClusterSourceKey(sessionRef.id) : codeWorkroomRunClusterSourceKey(entry.primaryRef.id));
    }
  }
  for (const entry of entries) {
    if (entry.entryKind !== "context_receipt")
      continue;
    const sessionRef = entry.inputRefs.find((ref) => ref.kind === "session");
    if (sessionRef)
      receiptToGroup.set(entry.primaryRef.id, codeSessionClusterSourceKey(sessionRef.id));
  }
  for (const entry of entries) {
    if (entry.entryKind !== "plan_contract")
      continue;
    const receiptRef = entry.inputRefs.find((ref) => ref.kind === "context_receipt") ?? entry.receiptRefs.find((ref) => ref.kind === "context_receipt");
    if (receiptRef && receiptToGroup.has(receiptRef.id))
      planToGroup.set(entry.primaryRef.id, receiptToGroup.get(receiptRef.id));
  }
  for (const entry of entries) {
    if (entry.entryKind !== "patch_run")
      continue;
    const sessionId = metadataString(entry.metadata, "workroomSessionId");
    const workroomRunRef = entry.inputRefs.find((ref) => ref.kind === "code_workroom_run");
    const planRef = entry.inputRefs.find((ref) => ref.kind === "plan_contract");
    const group = sessionId ? codeSessionClusterSourceKey(sessionId) : workroomRunRef && workroomRunToGroup.has(workroomRunRef.id) ? workroomRunToGroup.get(workroomRunRef.id) : planRef && planToGroup.has(planRef.id) ? planToGroup.get(planRef.id) : codePatchRunClusterSourceKey(entry.primaryRef.id);
    if (group)
      patchToGroup.set(entry.primaryRef.id, group);
  }
  for (const entry of entries) {
    if (entry.entryKind !== "truth_candidate")
      continue;
    const patchRef = entry.inputRefs.find((ref) => ref.kind === "code_patch_run") ?? entry.relatedRefs.find((ref) => ref.kind === "code_patch_run");
    if (patchRef && patchToGroup.has(patchRef.id))
      truthToGroup.set(entry.primaryRef.id, patchToGroup.get(patchRef.id));
  }
  return { receiptToGroup, planToGroup, patchToGroup, truthToGroup, workroomRunToGroup };
}
function codeTrailEntryClusterSourceKey(entry, groups) {
  if (entry.primaryRef.kind === "session")
    return codeSessionClusterSourceKey(entry.primaryRef.id);
  if (entry.primaryRef.kind === "code_workroom_run")
    return groups.workroomRunToGroup.get(entry.primaryRef.id) ?? codeWorkroomRunClusterSourceKey(entry.primaryRef.id);
  if (entry.entryKind === "context_receipt")
    return groups.receiptToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
  if (entry.entryKind === "plan_contract")
    return groups.planToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
  if (entry.entryKind === "patch_run")
    return groups.patchToGroup.get(entry.primaryRef.id) ?? codePatchRunClusterSourceKey(entry.primaryRef.id);
  if (entry.entryKind === "truth_candidate")
    return groups.truthToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
  if (entry.entryKind === "evidence_job") {
    const patchRef = entry.inputRefs.find((ref) => ref.kind === "code_patch_run");
    if (patchRef && groups.patchToGroup.has(patchRef.id))
      return groups.patchToGroup.get(patchRef.id);
    const truthRef = entry.inputRefs.find((ref) => ref.kind === "truth_candidate");
    if (truthRef && groups.truthToGroup.has(truthRef.id))
      return groups.truthToGroup.get(truthRef.id);
    const workroomRunRef = entry.inputRefs.find((ref) => ref.kind === "code_workroom_run");
    if (workroomRunRef && groups.workroomRunToGroup.has(workroomRunRef.id))
      return groups.workroomRunToGroup.get(workroomRunRef.id);
  }
  return entry.sourceKey;
}
function entryToDraft(entry, sourceKey) {
  const sourceRefs = uniqueRefs5([entry.primaryRef, ...entry.sourceRefs].map(codeTrailRefToCodeMarketRef));
  const changedRefs = uniqueRefs5(entry.outputRefs.map(codeTrailRefToCodeMarketRef));
  const relatedRefs = uniqueRefs5([...entry.relatedRefs, ...entry.inputRefs].map(codeTrailRefToCodeMarketRef));
  const evidenceRefs = uniqueRefs5([
    ...entry.entryKind === "truth_candidate" || entry.entryKind === "evidence_job" ? [entry.primaryRef] : [],
    ...entry.evidenceRefs
  ].map(codeTrailRefToCodeMarketRef));
  const receiptRefs = uniqueRefs5([
    ...entry.entryKind === "context_receipt" ? [entry.primaryRef] : [],
    ...entry.receiptRefs
  ].map(codeTrailRefToCodeMarketRef));
  return {
    sourceKey,
    title: entry.title ?? entry.primaryRef.label ?? "Code Trail entry",
    summary: entry.summary,
    status: codeTrailStatusToCodeMarketWorkClusterStatus(entry.status),
    completion: codeTrailEntryToCodeMarketCompletion(entry),
    changedRefs,
    relatedRefs,
    sourceRefs,
    evidenceRefs,
    receiptRefs,
    sourceKeys: unique([sourceKey, ...entry.sourceKeys, ...sourceRefs.map((ref) => ref.sourceKey), ...changedRefs.map((ref) => ref.sourceKey), ...evidenceRefs.map((ref) => ref.sourceKey), ...receiptRefs.map((ref) => ref.sourceKey)]),
    reasonCodes: unique(["code_trail_work_cluster", ...entry.reasonCodes]),
    confidence: 0.8,
    updatedAt: entry.updatedAt ?? entry.completedAt ?? entry.startedAt ?? entry.createdAt ?? 0,
    metadata: {
      source: "code_trail",
      trailEntryIds: [entry.id],
      trailStableKeys: [entry.stableKey],
      trailPhases: [entry.phase]
    }
  };
}
function upsertDraft(drafts, next) {
  const current = drafts.get(next.sourceKey);
  if (!current) {
    drafts.set(next.sourceKey, next);
    return;
  }
  drafts.set(next.sourceKey, {
    ...current,
    title: preferredTitle(current, next),
    summary: current.summary ?? next.summary,
    status: strongerStatus(current.status, next.status),
    completion: strongerCompletion(current.completion, next.completion),
    changedRefs: uniqueRefs5([...current.changedRefs, ...next.changedRefs]),
    relatedRefs: uniqueRefs5([...current.relatedRefs, ...next.relatedRefs]),
    sourceRefs: uniqueRefs5([...current.sourceRefs, ...next.sourceRefs]),
    evidenceRefs: uniqueRefs5([...current.evidenceRefs, ...next.evidenceRefs]),
    receiptRefs: uniqueRefs5([...current.receiptRefs, ...next.receiptRefs]),
    sourceKeys: unique([...current.sourceKeys, ...next.sourceKeys]),
    reasonCodes: unique([...current.reasonCodes, ...next.reasonCodes]),
    confidence: Math.max(current.confidence, next.confidence),
    updatedAt: Math.max(current.updatedAt, next.updatedAt),
    metadata: {
      ...current.metadata,
      ...next.metadata,
      trailEntryIds: unique([...asStringArray(current.metadata["trailEntryIds"]), ...asStringArray(next.metadata["trailEntryIds"])]),
      trailStableKeys: unique([...asStringArray(current.metadata["trailStableKeys"]), ...asStringArray(next.metadata["trailStableKeys"])]),
      trailPhases: unique([...asStringArray(current.metadata["trailPhases"]), ...asStringArray(next.metadata["trailPhases"])])
    }
  });
}
function preferredTitle(current, next) {
  if (next.reasonCodes.some((code) => code.includes("patch_run")) && !current.reasonCodes.some((code) => code.includes("patch_run")))
    return next.title;
  return current.title || next.title;
}
function strongerStatus(a, b) {
  const order = ["observed", "forming", "in_progress", "ready_review", "applied", "stale"];
  return order.indexOf(b) > order.indexOf(a) ? b : a;
}
function strongerCompletion(a, b) {
  const order = ["unknown", "partial", "likely_done", "done_by_receipt", "done_by_review"];
  return order.indexOf(b) > order.indexOf(a) ? b : a;
}
function uniqueRefs5(refs) {
  const seen = new Set;
  const output = [];
  for (const ref of refs) {
    const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(ref);
  }
  return output;
}
function metadataString(metadata, key) {
  const value = metadata?.[key];
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function asStringArray(value) {
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function codeSessionClusterSourceKey(sessionId) {
  return `source:code_session:${cleanPart(sessionId)}`;
}
function codeWorkroomRunClusterSourceKey(runId) {
  return `source:code_workroom_run:${cleanPart(runId)}`;
}
function codePatchRunClusterSourceKey(patchRunId) {
  return `source:code_patch_run:${cleanPart(patchRunId)}`;
}
function cleanPart(value) {
  return String(value ?? "").trim().replace(/\s+/g, "-").replace(/[^a-zA-Z0-9._:/#-]/g, "_");
}
// ../core/src/codeTrail/receiptTargets.ts
function buildCodeTrailReceiptTargetV1(args) {
  const refs = normalizeRefs([
    ...args.refs ?? [],
    args.sourceKind && args.sourceId ? { kind: args.sourceKind, id: args.sourceId } : undefined
  ]);
  const explicitHref = firstSafeTrailHref([
    args.href,
    ...refs.map((ref) => ref.href),
    stringFromMetadata(args.metadata, "href"),
    stringFromMetadata(args.metadata, "route"),
    stringFromMetadata(args.metadata, "deepLink")
  ]);
  const params = explicitHref ? paramsFromHref(explicitHref) : new URLSearchParams;
  const projectId = cleanString2(args.projectId) ?? params.get("projectId") ?? projectIdFromRefs(refs);
  if (!projectId)
    return null;
  setParam(params, "projectId", projectId, true);
  setParam(params, "repoId", cleanString2(args.repoId));
  for (const ref of refs) {
    mapRefToTrailParams(params, ref);
  }
  const targetKind = args.targetKind ?? inferTargetKind(refs, explicitHref);
  const scope = buildScopeFromParams(params, targetKind);
  return {
    schemaVersion: 1,
    kind: "code_trail_receipt_target",
    targetKind,
    href: `/trail?${params.toString()}`,
    scope,
    params: Object.fromEntries(params.entries()),
    refs,
    fanout: buildFanout(params, targetKind),
    reasonCodes: uniqueStrings2([
      "trail_target:safe_internal_scope",
      explicitHref ? "trail_target:explicit_href_sanitized" : undefined,
      refs.length > 0 ? "trail_target:refs_mapped" : "trail_target:project_scope_only",
      `trail_target:fanout_${fanoutLaneForTargetKind(targetKind)}`,
      "authority:no_navigation_side_effects"
    ]),
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function normalizeRefs(refs) {
  const output = [];
  const seen = new Set;
  for (const ref of refs) {
    const kind = cleanString2(ref?.kind);
    const id = cleanString2(ref?.id);
    const href = cleanString2(ref?.href);
    if (!kind && !id && !href)
      continue;
    const normalized = {
      kind,
      id,
      label: cleanString2(ref?.label),
      path: cleanString2(ref?.path),
      href,
      metadata: ref?.metadata
    };
    const key = `${normalized.kind ?? "ref"}:${normalized.id ?? normalized.href ?? ""}:${normalized.path ?? ""}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(normalized);
  }
  return output;
}
function mapRefToTrailParams(params, ref) {
  const kind = normalizeKind(ref.kind);
  const id = cleanString2(ref.id);
  if (!id)
    return;
  switch (kind) {
    case "code_session":
    case "code_task_session":
    case "session":
      setParam(params, "sessionId", id);
      return;
    case "code_workroom_run":
    case "workroom_run":
      setParam(params, "workroomRunId", id);
      return;
    case "agent_run":
      setParam(params, "agentRunId", id);
      return;
    case "agent_run_node":
      setParam(params, "agentRunNodeId", id);
      return;
    case "code_patch_run":
    case "patch_run":
      setParam(params, "patchRunId", id);
      return;
    case "agent_edit_session":
    case "edit_session":
      setParam(params, "editSessionId", id);
      return;
    case "agent_edit_session_row":
    case "edit_session_row":
      setParam(params, "editSessionRowId", id);
      return;
    case "truth_candidate":
      setParam(params, "truthCandidateId", id);
      return;
    case "capability_run":
      setParam(params, "capabilityRunId", id);
      return;
    case "receipt":
    case "code_context_receipt":
    case "context_receipt":
      setParam(params, "receiptId", id);
      return;
    case "artifact":
      setParam(params, "artifactId", id);
      return;
    case "evidence_job":
    case "connection_evidence":
      setParam(params, "evidenceJobId", id);
      return;
    case "code_node":
      setParam(params, "codeNodeId", id);
      if (ref.path)
        setParam(params, "filePath", ref.path);
      return;
    case "pulse_signal":
    case "pulse_evidence":
      setParam(params, "pulseSignalId", id);
      return;
    case "code_market":
    case "code_market_snapshot":
      setParam(params, "codeMarketSnapshotId", id);
      return;
    case "mcp_run":
    case "mcp_context_run":
    case "local_mcp_context_run":
      setParam(params, "mcpContextRunId", id);
      return;
    case "mcp_run_graph":
    case "local_mcp_run_graph":
      setParam(params, "sourceMcpRunId", id);
      return;
    case "pr_report":
    case "pr_review":
    case "pr_snapshot":
      setParam(params, "prSnapshotId", id);
      return;
    case "pr_review_story":
    case "code_change_story":
    case "story":
      setParam(params, "storyId", id);
      return;
    case "review_room":
      setParam(params, "reviewRoomId", id);
      return;
    case "trail_import":
      setParam(params, "importId", id);
      return;
    case "file":
      setParam(params, "filePath", ref.path ?? id);
      return;
    default:
      if (kind.endsWith("_receipt"))
        setParam(params, "receiptId", id);
      return;
  }
}
function buildScopeFromParams(params, targetKind) {
  return {
    projectId: params.get("projectId") ?? "",
    repoId: params.get("repoId") ?? undefined,
    sessionId: params.get("sessionId") ?? undefined,
    workroomRunId: params.get("workroomRunId") ?? undefined,
    patchRunId: params.get("patchRunId") ?? undefined,
    editSessionId: params.get("editSessionId") ?? undefined,
    editSessionRowId: params.get("editSessionRowId") ?? undefined,
    truthCandidateId: params.get("truthCandidateId") ?? undefined,
    capabilityRunId: params.get("capabilityRunId") ?? undefined,
    importId: params.get("importId") ?? undefined,
    trailHash: params.get("trailHash") ?? undefined,
    receiptId: params.get("receiptId") ?? undefined,
    artifactId: params.get("artifactId") ?? undefined,
    codeMarketSnapshotId: params.get("codeMarketSnapshotId") ?? undefined,
    mcpContextRunId: params.get("mcpContextRunId") ?? undefined,
    sourceMcpRequestId: params.get("sourceMcpRequestId") ?? undefined,
    sourceMcpRunId: params.get("sourceMcpRunId") ?? undefined,
    agentRunId: params.get("agentRunId") ?? undefined,
    agentRunNodeId: params.get("agentRunNodeId") ?? undefined,
    evidenceJobId: params.get("evidenceJobId") ?? undefined,
    codeNodeId: params.get("codeNodeId") ?? undefined,
    pulseSignalId: params.get("pulseSignalId") ?? undefined,
    prSnapshotId: params.get("prSnapshotId") ?? undefined,
    reviewRoomId: params.get("reviewRoomId") ?? undefined,
    storyId: params.get("storyId") ?? undefined,
    filePath: params.get("filePath") ?? undefined,
    surface: surfaceForTargetKind(targetKind),
    sourceMode: "derived"
  };
}
function firstSafeTrailHref(values) {
  for (const value of values) {
    const href = cleanString2(value);
    if (!href || href.startsWith("//"))
      continue;
    try {
      const parsed = new URL(href, "https://rhei.local");
      if (parsed.origin !== "https://rhei.local")
        continue;
      if (parsed.pathname !== "/trail")
        continue;
      return `${parsed.pathname}${parsed.search}`;
    } catch {
      continue;
    }
  }
  return null;
}
function paramsFromHref(href) {
  try {
    return new URL(href, "https://rhei.local").searchParams;
  } catch {
    return new URLSearchParams;
  }
}
function setParam(params, key, value, force = false) {
  const cleaned = cleanString2(value);
  if (!cleaned)
    return;
  if (!force && params.has(key))
    return;
  params.set(key, cleaned);
}
function inferTargetKind(refs, href) {
  const kinds = refs.map((ref) => normalizeKind(ref.kind));
  if (kinds.some((kind) => kind.includes("market")))
    return "code_market";
  if (kinds.some((kind) => kind === "code_node"))
    return "code_node";
  if (kinds.some((kind) => kind.includes("map")))
    return "code_map";
  if (kinds.some((kind) => kind.includes("pr_impact")))
    return "pr_impact";
  if (kinds.some((kind) => kind.includes("pr_") || kind === "review_room"))
    return "pr_report";
  if (kinds.some((kind) => kind.includes("pulse")))
    return "pulse_evidence";
  if (kinds.some((kind) => kind.includes("backend_readiness") || kind.includes("repo_intelligence")))
    return "backend_readiness";
  if (kinds.some((kind) => kind.includes("mcp")))
    return "mcp_run";
  if (kinds.some((kind) => kind === "agent_run" || kind === "agent_run_node"))
    return "agent_run";
  if (kinds.some((kind) => kind.includes("workroom")))
    return "workroom";
  if (kinds.some((kind) => kind.includes("patch")))
    return "patch_run";
  if (kinds.some((kind) => kind.includes("edit_session")))
    return "edit_session";
  if (kinds.some((kind) => kind === "code_node"))
    return "code_node";
  if (kinds.some((kind) => kind === "artifact"))
    return "artifact";
  if (kinds.some((kind) => kind.includes("receipt")))
    return "receipt";
  return href ? "code_trail" : "receipt";
}
function surfaceForTargetKind(targetKind) {
  switch (targetKind) {
    case "code_market":
      return "code_market";
    case "code_map":
    case "code_node":
      return "code_map";
    case "pulse_evidence":
      return "pulse";
    case "pr_report":
    case "pr_impact":
      return "pr_review";
    case "edit_session":
    case "patch_run":
    case "workroom":
      return "workroom";
    case "mcp_run":
    case "agent_run":
      return "local_mcp";
    default:
      return "web";
  }
}
function buildFanout(params, targetKind) {
  const surfaces = uniqueSurfaceStrings([surfaceForTargetKind(targetKind), ...additionalSurfacesForParams(params)]);
  return {
    lane: fanoutLaneForTargetKind(targetKind),
    surfaces,
    sourceMode: "derived",
    params: Array.from(params.keys()).sort()
  };
}
function additionalSurfacesForParams(params) {
  const surfaces = [];
  if (params.has("prSnapshotId") || params.has("reviewRoomId") || params.has("storyId"))
    surfaces.push("pr_review");
  if (params.has("codeMarketSnapshotId"))
    surfaces.push("code_market");
  if (params.has("codeNodeId") || params.has("filePath"))
    surfaces.push("code_map");
  if (params.has("pulseSignalId") || params.has("evidenceJobId"))
    surfaces.push("pulse");
  if (params.has("workroomRunId") || params.has("patchRunId") || params.has("editSessionId") || params.has("editSessionRowId"))
    surfaces.push("workroom");
  if (params.has("mcpContextRunId") || params.has("sourceMcpRunId") || params.has("agentRunId") || params.has("agentRunNodeId"))
    surfaces.push("local_mcp");
  return surfaces;
}
function fanoutLaneForTargetKind(targetKind) {
  switch (targetKind) {
    case "code_market":
      return "code_market";
    case "code_map":
    case "code_node":
      return "code_map";
    case "pr_report":
    case "pr_impact":
      return "pr_review";
    case "pulse_evidence":
      return "pulse";
    case "workroom":
    case "patch_run":
    case "edit_session":
      return "workroom";
    case "mcp_run":
      return "local_mcp";
    case "agent_run":
      return "agent_run";
    case "backend_readiness":
      return "backend_readiness";
    default:
      return "trail";
  }
}
function uniqueSurfaceStrings(values) {
  const seen = new Set;
  const output = [];
  for (const value of values) {
    if (seen.has(value))
      continue;
    seen.add(value);
    output.push(value);
  }
  return output;
}
function projectIdFromRefs(refs) {
  for (const ref of refs) {
    const projectId = cleanString2(ref.metadata?.["projectId"]);
    if (projectId)
      return projectId;
  }
  return;
}
function stringFromMetadata(metadata, key) {
  return cleanString2(metadata?.[key]);
}
function normalizeKind(value) {
  return (value ?? "").trim().toLowerCase();
}
function cleanString2(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function uniqueStrings2(values) {
  const seen = new Set;
  const output = [];
  for (const value of values) {
    const trimmed = value?.trim();
    if (!trimmed || seen.has(trimmed))
      continue;
    seen.add(trimmed);
    output.push(trimmed);
  }
  return output;
}
export {
  uniqueCodeTrailStrings,
  sortCodeTrailLinks,
  sortCodeTrailEntries,
  sanitizeCodeTrailMetadata,
  normalizeCodeTrailProjection,
  isDeterministicCodeTrailRef,
  getCodeTrailEntryById,
  getCodeTrailEntriesForRef,
  dedupeCodeTrailLinks,
  dedupeCodeTrailEntries,
  codeTrailStatusToCodeMarketWorkClusterStatus,
  codeTrailSourceToCodeMarketSource,
  codeTrailRefToCodeMarketRef,
  codeTrailNoAuthorityBoundary,
  codeTrailGapToCodeMarketGap,
  codeTrailEntryToCodeMarketCompletion,
  codeTrailEntriesToCodeMarketWorkImpactOverlays,
  codeTrailEntriesToCodeMarketWorkClusters,
  buildCodeTrailSourceKey,
  buildCodeTrailRefStableKey,
  buildCodeTrailReceiptTargetV1,
  admitSource,
  admitLink,
  admitEntry,
  admitCodeTrailGap,
  CODE_TRAIL_SCHEMA_VERSION,
  CODE_TRAIL_READ_MODEL_VERSION,
  CODE_TRAIL_NO_AUTHORITY_BOUNDARY,
  CODE_TRAIL_MODEL_VERSION
};
