// ../core/src/briefs/types.ts
var BRIEF_SCHEMA_VERSION = 1;
var TASK_BRIEF_READ_MODEL_VERSION = 1;
var CONTEXT_DEPTHS = ["light", "normal", "deep"];
var BRIEF_SURFACES_V1 = ["task", "daily", "agent_handoff", "impact"];
var TASK_BRIEF_STATES_V1 = ["empty", "warming", "ready"];
var BRIEF_ITEM_KINDS_V1 = [
  "action",
  "context",
  "connection",
  "receipt",
  "gap",
  "source",
  "workroom",
  "impact",
  "handoff"
];
var BRIEF_SECTION_KINDS_V1 = [
  "resume",
  "waiting",
  "in_motion",
  "review",
  "changed",
  "context",
  "gaps"
];
var FEEDBACK_COMMANDS_V1 = [
  "open",
  "ask_with_this",
  "ask_with_brief",
  "pin",
  "hide_for_me",
  "why_this_appears",
  "not_useful_here",
  "not_related",
  "wrong",
  "request_review"
];
var SESSION_ACTIVITY_TYPES_V1 = [
  "brief_viewed",
  "item_opened",
  "ask_with_this",
  "ask_with_brief",
  "why_viewed",
  "pin_applied",
  "hide_applied",
  "feedback_submitted",
  "review_requested"
];
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]));
var BRIEF_ITEM_READ_MODEL_VERSION_V2 = 2;
var DETERMINISTIC_WHY_SCHEMA_VERSION = 1;
var DETERMINISTIC_WHY_COPY_VERSION = "product-safe-v1";
var DETERMINISTIC_WHY_BULLET_KINDS_V1 = [
  "status",
  "evidence",
  "recency",
  "desk",
  "policy",
  "uncertainty"
];
var BRIEF_ITEM_RELEVANCE_SOURCES_V1 = [
  "signal",
  "desk",
  "feedback",
  "resume",
  "review",
  "changed"
];
function defaultFeedbackScopeForCommand(command) {
  return BRIEF_COMMAND_DEFAULT_SCOPES_V1[command] ?? "personal_ranking";
}
function activityTypeForFeedbackCommand(command) {
  if (command === "open")
    return "item_opened";
  if (command === "ask_with_this")
    return "ask_with_this";
  if (command === "ask_with_brief")
    return "ask_with_brief";
  if (command === "why_this_appears")
    return "why_viewed";
  if (command === "pin")
    return "pin_applied";
  if (command === "hide_for_me")
    return "hide_applied";
  if (command === "request_review")
    return "review_requested";
  return "feedback_submitted";
}
function isCorrectionFeedbackCommand(command) {
  return BRIEF_COMMAND_DESCRIPTORS_V1[command].correctionTool === true;
}
function isGovernanceFeedbackCommand(command) {
  return BRIEF_COMMAND_DESCRIPTORS_V1[command].governanceOnly === true;
}
function feedbackCommandRecordsPositiveEvidence(command) {
  return BRIEF_COMMAND_DESCRIPTORS_V1[command].recordsPositiveEvidence === true;
}
function briefCommandsForItem(item) {
  const base = [
    "open",
    "ask_with_this",
    "pin",
    "hide_for_me",
    "why_this_appears",
    "not_useful_here"
  ];
  const connectionCommands = item.connectionId ? ["not_related", "wrong", "request_review"] : [];
  const commands = [...base, ...connectionCommands];
  return commands.map((command) => BRIEF_COMMAND_DESCRIPTORS_V1[command]);
}
function buildTaskBriefV1FromActionItems(args) {
  const briefItems = args.items.map(actionSurfaceItemToBriefItem);
  const sections = groupBriefItems(briefItems);
  const state = args.readiness.state;
  return {
    schemaVersion: BRIEF_SCHEMA_VERSION,
    readModelVersion: TASK_BRIEF_READ_MODEL_VERSION,
    surface: "task",
    projectId: args.projectId,
    generatedAt: args.generatedAt,
    contextDepth: args.readiness.contextDepth,
    state,
    title: args.title ?? defaultTaskBriefTitle(state),
    subtitle: args.subtitle ?? args.readiness.label,
    primaryItem: briefItems[0],
    sections,
    items: briefItems,
    primaryAction: args.primaryAction,
    secondaryActions: args.secondaryActions ?? [],
    commands: [BRIEF_COMMAND_DESCRIPTORS_V1.ask_with_brief],
    readiness: args.readiness,
    sourceModel: briefItems.length > 0 ? "before_work_brief" : "empty",
    metadata: args.metadata
  };
}
function actionSurfaceItemToBriefItem(item) {
  const targetRef = item.primaryAction?.targetRef ?? item.allActions[0]?.targetRef ?? {
    kind: "action",
    id: item.signalItem.primaryAction.targetRef,
    label: item.title
  };
  const connectionId = readConnectionId(item);
  const briefItem = {
    schemaVersion: BRIEF_SCHEMA_VERSION,
    id: item.id,
    kind: briefItemKindForActionItem(item),
    title: item.title,
    subtitle: item.subtitle,
    summary: item.evidenceSummary,
    statusLabel: item.statusLabel,
    targetRef,
    sourceRefs: item.sourceRefs.map((ref) => ({ kind: ref.kind, id: ref.id, label: ref.label })),
    evidenceRefs: item.allActions.flatMap((action) => action.evidenceRefs),
    receiptRefs: item.receiptRefs.map((ref) => ({ kind: ref.kind ?? "receipt", id: ref.id, label: ref.label })),
    connectionId,
    actionIds: item.allActions.map((action) => action.id),
    commands: briefCommandsForItem({ connectionId }),
    privacyLabel: item.privacyBoundary === "private_personal" ? "Private to you" : undefined,
    reasonCodes: Array.from(new Set(item.allActions.flatMap((action) => action.reasonCodes))),
    metadata: {
      groupKey: item.groupKey,
      sourceSignalIds: item.sourceSignalIds,
      latestStatus: item.latestStatus
    }
  };
  return briefItem;
}
function groupBriefItems(items) {
  const groups = [
    { id: "resume", title: "Resume", items: [] },
    { id: "waiting", title: "Waiting", items: [] },
    { id: "in_motion", title: "In motion", items: [] },
    { id: "review", title: "For review", items: [] },
    { id: "changed", title: "Changed", items: [] },
    { id: "context", title: "Context", items: [] }
  ];
  const byId = new Map(groups.map((section) => [section.id, section]));
  for (const item of items) {
    const sectionId = sectionForBriefItem(item);
    byId.get(sectionId)?.items.push(item);
  }
  return groups.filter((section) => section.items.length > 0);
}
function briefItemKindForActionItem(item) {
  if (item.signalItem.primaryAction.targetRef.startsWith("connected_work:"))
    return "connection";
  if (item.signalItem.primaryAction.targetRef.includes("workroom"))
    return "workroom";
  if (item.receiptRefs.length > 0)
    return "receipt";
  if (item.allActions.some((action) => action.reasonCodes.some((code) => code.includes("context"))))
    return "context";
  return "action";
}
function sectionForBriefItem(item) {
  const status = item.metadata?.["latestStatus"];
  if (item.reasonCodes.includes("attention:resume"))
    return "resume";
  if (item.reasonCodes.some((code) => code.includes("review")))
    return "review";
  if (item.reasonCodes.some((code) => code.includes("changed")))
    return "changed";
  if (item.kind === "context")
    return "context";
  if (status === "queued" || status === "scheduled" || status === "awaiting_approval")
    return "waiting";
  if (status === "running")
    return "in_motion";
  return "waiting";
}
function readConnectionId(item) {
  const candidates = [
    item.primaryAction?.targetRef.id,
    item.allActions.find((action) => action.targetRef.kind === "observed_connection")?.targetRef.id,
    item.allActions.find((action) => action.targetRef.kind === "connected_work")?.targetRef.id,
    item.signalItem.primaryAction.targetRef,
    ...item.allActions.map((action) => action.targetRef.id)
  ];
  for (const candidate of candidates) {
    if (typeof candidate !== "string" || candidate.length === 0)
      continue;
    if (candidate.startsWith("connected_work:"))
      return candidate.slice("connected_work:".length);
    if (candidate.startsWith("observed_connection:"))
      return candidate.slice("observed_connection:".length);
  }
  const connectedWorkAction = item.allActions.find((action) => action.targetRef.kind === "observed_connection" || action.targetRef.kind === "connected_work");
  return connectedWorkAction?.targetRef.id;
}
function defaultTaskBriefTitle(state) {
  if (state === "empty")
    return "No task brief yet";
  if (state === "warming")
    return "Rhei is preparing your Task Brief";
  return "Task Brief";
}
// ../core/src/briefs/why.ts
var DEFAULT_WHY_HEADLINE = "Rhei found a task-relevant signal.";
var DEFAULT_WHY_BULLET = "No additional explanation was available, so this item is shown with conservative context only.";
function buildDeterministicWhyV1(args = {}) {
  const bullets = normalizeWhyBullets(args.bullets);
  if (bullets.length === 0) {
    bullets.push({ kind: "uncertainty", text: cleanText(args.fallbackText) ?? DEFAULT_WHY_BULLET });
  }
  return {
    schemaVersion: DETERMINISTIC_WHY_SCHEMA_VERSION,
    headline: cleanText(args.headline) ?? DEFAULT_WHY_HEADLINE,
    bullets,
    confidenceLabel: confidenceLabelFor(args.confidence, args.confidenceLabel),
    evidenceCount: safeEvidenceCount(args.evidenceCount, bullets),
    copyVersion: DETERMINISTIC_WHY_COPY_VERSION
  };
}
function buildDeterministicWhyForBriefItem(item) {
  const bullets = [];
  const refIds = refIdsForBriefRefs([...item.sourceRefs, ...item.evidenceRefs, ...item.receiptRefs]);
  if (item.statusLabel) {
    bullets.push({ kind: "status", text: `Status: ${item.statusLabel}.`, refIds });
  }
  if (item.summary) {
    bullets.push({ kind: "evidence", text: item.summary, refIds });
  }
  if (item.sourceRefs.length > 0 || item.evidenceRefs.length > 0) {
    bullets.push({
      kind: "evidence",
      text: `Backed by ${item.sourceRefs.length + item.evidenceRefs.length} source or evidence reference(s).`,
      refIds
    });
  }
  if (item.receiptRefs.length > 0) {
    bullets.push({ kind: "recency", text: `Includes ${item.receiptRefs.length} recent receipt reference(s).`, refIds });
  }
  if (item.stale) {
    bullets.push({ kind: "recency", text: "This item may be stale; inspect the source before acting.", refIds });
  }
  if (item.conflicted) {
    bullets.push({ kind: "uncertainty", text: "Some signals conflict, so treat this as a prompt to inspect rather than a fact.", refIds });
  }
  if (item.reasonCodes.some((code) => code.startsWith("policy:"))) {
    bullets.push({ kind: "policy", text: "Policy state comes from the action offer and does not grant new authority.", refIds });
  }
  return buildDeterministicWhyV1({
    headline: item.title,
    bullets,
    confidence: item.confidence,
    evidenceCount: item.sourceRefs.length + item.evidenceRefs.length + item.receiptRefs.length
  });
}
function normalizeWhyBullets(bullets) {
  if (!bullets)
    return [];
  return bullets.map((bullet) => ({
    ...bullet,
    text: cleanText(bullet.text) ?? DEFAULT_WHY_BULLET,
    refIds: bullet.refIds ? Array.from(new Set(bullet.refIds.filter(Boolean))) : undefined
  })).filter((bullet) => bullet.text.length > 0).slice(0, 6);
}
function confidenceLabelFor(confidence, fallback) {
  if (fallback)
    return fallback;
  if (typeof confidence !== "number")
    return;
  if (confidence >= 0.75)
    return "high";
  if (confidence >= 0.45)
    return "medium";
  return "low";
}
function safeEvidenceCount(count, bullets) {
  if (typeof count === "number" && Number.isFinite(count))
    return Math.max(0, Math.floor(count));
  return bullets.reduce((total, bullet) => total + (bullet.refIds?.length ?? 0), 0);
}
function refIdsForBriefRefs(refs) {
  const ids = Array.from(new Set(refs.map((ref) => ref.id).filter(Boolean)));
  return ids.length > 0 ? ids : undefined;
}
function cleanText(value) {
  const text = value?.trim();
  return text && text.length > 0 ? text : undefined;
}
// ../core/src/briefs/contextPlan.ts
var DEFAULT_MAX_CONTEXT_ITEMS = 8;
var DEFAULT_ASK_GOAL = "Use this Task Brief context to answer without broad project search.";
function buildContextPlanV1(args = {}) {
  return {
    schemaVersion: BRIEF_SCHEMA_VERSION,
    planner: "task_brief_v1",
    intent: args.intent ?? "explain_why",
    scope: args.scope ?? "item",
    allowProjectSearch: args.allowProjectSearch ?? false,
    maxContextItems: positiveInteger(args.maxContextItems, DEFAULT_MAX_CONTEXT_ITEMS),
    maxTokens: args.maxTokens,
    exactRefs: dedupeRefs(args.exactRefs ?? []),
    sourceRoles: dedupeSourceRoles(args.sourceRoles ?? []),
    serviceConnectionIds: dedupeStrings(args.serviceConnectionIds ?? []),
    constraints: {
      privacyBoundary: args.constraints?.privacyBoundary ?? "project",
      requireExplicitRefs: args.constraints?.requireExplicitRefs ?? true,
      productSafeCopy: true,
      workingSetGrantsAuthority: false
    }
  };
}
function buildContextPlanForBriefItem(item, command = "ask_with_this", args = {}) {
  return buildContextPlanV1({
    ...args,
    intent: args.intent ?? contextPlanIntentForFeedbackCommand(command),
    scope: args.scope ?? contextPlanScopeForFeedbackCommand(command),
    allowProjectSearch: args.allowProjectSearch ?? false,
    exactRefs: args.exactRefs ?? exactRefsForBriefItem(item),
    sourceRoles: args.sourceRoles ?? sourceRolesForBriefItem(item),
    constraints: {
      ...args.constraints,
      privacyBoundary: args.constraints?.privacyBoundary ?? privacyBoundaryForBriefItem(item),
      requireExplicitRefs: args.constraints?.requireExplicitRefs ?? true,
      productSafeCopy: true,
      workingSetGrantsAuthority: false
    }
  });
}
function buildBriefItemRelevanceV1(item, args = {}) {
  return {
    source: args.source ?? relevanceSourceForReasonCodes(item.reasonCodes),
    deskRole: args.deskRole,
    pinned: args.pinned,
    hiddenForViewer: args.hiddenForViewer,
    downrankedForViewer: args.downrankedForViewer,
    score: clampScore(args.score),
    reasonCodes: dedupeStrings(args.reasonCodes ?? item.reasonCodes)
  };
}
function buildBriefItemV2(args) {
  const item = args.item;
  const existing = isBriefItemV2(item) ? item : undefined;
  const actionOffers = args.actionOffers ?? existing?.actionOffers ?? [];
  const primaryOffer = args.primaryOffer ?? existing?.primaryOffer ?? actionOffers[0];
  return {
    ...item,
    readModelVersion: BRIEF_ITEM_READ_MODEL_VERSION_V2,
    why: args.why ?? existing?.why ?? buildDeterministicWhyForBriefItem(item),
    actionOffers,
    primaryOffer,
    relevance: args.relevance ?? existing?.relevance ?? buildBriefItemRelevanceV1(item),
    contextPlan: args.contextPlan ?? existing?.contextPlan ?? buildContextPlanForBriefItem(item)
  };
}
function buildAgentWorkBriefV1(args) {
  const selectedSourceItems = sourceItemsForAgentWorkBrief(args);
  const selectedItems = selectedSourceItems.map(agentWorkBriefSelectedItemForBriefItem);
  const selectedItem = selectedItems[0];
  const contextPlan = args.contextPlan ?? contextPlanForAgentWorkBrief(args, selectedItems);
  const primaryOffer = isBriefItemV2(args.item) ? args.item.primaryOffer : undefined;
  return {
    schemaVersion: BRIEF_SCHEMA_VERSION,
    workBriefVersion: 1,
    source: {
      surface: "task",
      briefId: briefIdForAgentWorkBrief(args),
      itemId: args.item?.id,
      command: args.command,
      projectId: args.brief.projectId,
      generatedAt: args.generatedAt ?? args.brief.generatedAt
    },
    userGoal: cleanText2(args.userGoal) ?? DEFAULT_ASK_GOAL,
    briefTitle: args.brief.title,
    selectedItem,
    items: selectedItems,
    selectedItems,
    contextPlan,
    actionIntent: {
      command: args.command,
      label: BRIEF_COMMAND_DESCRIPTORS_V1[args.command].label,
      actionId: primaryOffer?.id,
      actionVerb: primaryOffer?.verb,
      executionPath: primaryOffer?.executionPath,
      policyState: primaryOffer?.policyState,
      targetRef: primaryOffer?.targetRef ?? args.item?.targetRef
    },
    evidenceRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.evidenceRefs)),
    sourceRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.sourceRefs)),
    receiptRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.receiptRefs)),
    workingSetSnapshotHash: args.workingSetSnapshotHash,
    plannerHandoffGraphAdvisory: args.plannerHandoffGraphAdvisory,
    guardrails: {
      actionLayerOffersOnly: true,
      workingSetGrantsAuthority: false,
      canonicalChangesRequireTruthGate: true,
      memoryPromotionRequiresExplicitPath: true
    }
  };
}
function contextPlanIntentForFeedbackCommand(command) {
  if (command === "ask_with_this")
    return "ask_with_item";
  if (command === "ask_with_brief")
    return "ask_with_brief";
  if (command === "open")
    return "open_item";
  if (command === "request_review")
    return "review_relationship";
  return "explain_why";
}
function contextPlanScopeForFeedbackCommand(command) {
  if (command === "ask_with_brief")
    return "brief";
  return "item";
}
function sourceItemsForAgentWorkBrief(args) {
  const sourceItems = args.item ? [args.item] : args.items ?? args.brief.items;
  const limit = positiveInteger(args.contextPlan?.maxContextItems, DEFAULT_MAX_CONTEXT_ITEMS);
  return sourceItems.slice(0, limit);
}
function agentWorkBriefSelectedItemForBriefItem(item) {
  return {
    id: item.id,
    kind: item.kind,
    title: item.title,
    subtitle: item.subtitle,
    summary: item.summary,
    statusLabel: item.statusLabel,
    targetRef: item.targetRef,
    why: isBriefItemV2(item) ? item.why : buildDeterministicWhyForBriefItem(item),
    relevance: isBriefItemV2(item) ? item.relevance : undefined,
    reasonCodes: item.reasonCodes
  };
}
function contextPlanForAgentWorkBrief(args, selectedItems) {
  if (args.item)
    return buildContextPlanForBriefItem(args.item, args.command);
  return buildContextPlanV1({
    intent: contextPlanIntentForFeedbackCommand(args.command),
    scope: contextPlanScopeForFeedbackCommand(args.command),
    allowProjectSearch: false,
    maxContextItems: selectedItems.length || DEFAULT_MAX_CONTEXT_ITEMS,
    exactRefs: dedupeRefs(selectedItems.map((item) => item.targetRef)),
    sourceRoles: selectedItems.map((item, index) => ({
      role: index === 0 ? "selected_item" : "brief_neighbor",
      ref: item.targetRef
    })),
    constraints: {
      privacyBoundary: "project",
      requireExplicitRefs: true,
      productSafeCopy: true,
      workingSetGrantsAuthority: false
    }
  });
}
function exactRefsForBriefItem(item) {
  return dedupeRefs([item.targetRef, ...item.sourceRefs, ...item.evidenceRefs, ...item.receiptRefs]);
}
function sourceRolesForBriefItem(item) {
  return dedupeSourceRoles([
    { role: "selected_item", ref: item.targetRef },
    ...item.sourceRefs.map((ref) => ({ role: "evidence", ref })),
    ...item.evidenceRefs.map((ref) => ({ role: "evidence", ref })),
    ...item.receiptRefs.map((ref) => ({ role: "receipt", ref }))
  ]);
}
function privacyBoundaryForBriefItem(item) {
  return item.privacyLabel ? "private_personal" : "project";
}
function relevanceSourceForReasonCodes(reasonCodes) {
  if (reasonCodes.some((code) => code.includes("resume")))
    return "resume";
  if (reasonCodes.some((code) => code.includes("review")))
    return "review";
  if (reasonCodes.some((code) => code.includes("changed")))
    return "changed";
  return "signal";
}
function isBriefItemV2(item) {
  if (!item)
    return false;
  return item.readModelVersion === BRIEF_ITEM_READ_MODEL_VERSION_V2;
}
function briefIdForAgentWorkBrief(args) {
  const value = args.brief.metadata?.["briefId"];
  if (typeof value === "string" && value.length > 0)
    return value;
  return `task_brief:${args.brief.projectId}:${args.generatedAt ?? args.brief.generatedAt}`;
}
function dedupeRefs(refs) {
  const seen = new Set;
  const output = [];
  for (const ref of refs) {
    const key = `${ref.kind}:${ref.id}:${ref.versionId ?? ""}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(ref);
  }
  return output;
}
function dedupeSourceRoles(sourceRoles) {
  const seen = new Set;
  const output = [];
  for (const sourceRole of sourceRoles) {
    const key = `${sourceRole.role}:${sourceRole.ref.kind}:${sourceRole.ref.id}:${sourceRole.ref.versionId ?? ""}`;
    if (seen.has(key))
      continue;
    seen.add(key);
    output.push(sourceRole);
  }
  return output;
}
function dedupeStrings(values) {
  return Array.from(new Set(values.filter(Boolean)));
}
function positiveInteger(value, fallback) {
  if (typeof value !== "number" || !Number.isFinite(value) || value < 1)
    return fallback;
  return Math.floor(value);
}
function clampScore(value) {
  if (typeof value !== "number" || !Number.isFinite(value))
    return;
  if (value < 0)
    return 0;
  if (value > 1)
    return 1;
  return value;
}
function cleanText2(value) {
  const text = value?.trim();
  return text && text.length > 0 ? text : undefined;
}
// ../core/src/actionRouting/display.ts
function renderActionRouteSummaryMarkdown(actionRoute) {
  if (!actionRoute)
    return ["- None supplied."];
  return [
    `- Action mode: ${formatRouteValue(actionRoute.actionMode)}`,
    `- Primary lens: ${formatRouteValue(actionRoute.primaryLens)}`,
    `- Supporting lenses: ${actionRoute.supportingLenses.length > 0 ? actionRoute.supportingLenses.map(formatRouteValue).join(", ") : "none"}`,
    `- Surface scopes: ${actionRoute.surfaceScopes.length > 0 ? actionRoute.surfaceScopes.map(formatRouteValue).join(", ") : "none"}`,
    `- Confidence band: ${formatRouteValue(actionRoute.confidenceBand)}`,
    `- Route metadata is report-only, advisory-only, and grants no execution or canon authority: ${actionRoute.reportOnly && actionRoute.advisoryOnly && actionRoute.noAuthority}`
  ];
}
function formatRouteValue(value) {
  return value.replace(/\n/g, " ").trim();
}

// ../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 PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY = "Graph routing advisory explains context selection. It does not authorize graph mutation, provider synthesis, Memgraph execution, code writes, or Truth Gate promotion.";
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/briefs/agentHandoffMarkdown.ts
var AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION = 1;
function buildAgentHandoffMarkdownV1(args) {
  const generatedAt = args.generatedAt ?? 0;
  const contextPlan = args.agentWorkBrief?.contextPlan ?? args.contextPacket?.links?.contextPlan;
  const lines = [
    `# ${formatInline(args.title ?? args.agentWorkBrief?.briefTitle ?? "Agent handoff")}`,
    "",
    "## Goal",
    `- ${formatInline(args.agentWorkBrief?.userGoal ?? args.contextPacket?.objective ?? "No goal supplied.")}`,
    "",
    "## Scope",
    ...renderScope(args.contextPacket, args.agentWorkBrief),
    "",
    "## Semantic summary",
    ...renderSemanticSummary(args.contextPacket, args.agentWorkBrief),
    "",
    "## Action route",
    ...renderActionRoute(contextPlan, args.contextPacket, args.agentWorkBrief),
    "",
    ...renderPlannerGraphAdvisory(args.agentWorkBrief?.plannerHandoffGraphAdvisory),
    "## Exact context refs",
    ...renderExactRefs(contextPlan, args.contextPacket, args.agentWorkBrief),
    "",
    "## Guardrails",
    ...renderGuardrails(contextPlan, args.contextPacket, args.agentWorkBrief),
    "",
    "## Receipts",
    ...renderReceipts(args.executionReceipts ?? []),
    "",
    "## Open questions",
    ...renderOpenQuestions(args.contextPacket),
    "",
    "## Next agent instructions",
    ...renderNextAgentInstructions()
  ];
  return {
    schemaVersion: AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION,
    kind: "agent_handoff_markdown",
    markdown: `${lines.join(`
`)}
`,
    source: {
      contextPacketId: args.contextPacket?.packetId ?? args.agentWorkBrief?.contextPacketId,
      agentWorkBriefId: args.agentWorkBrief?.source.briefId,
      receiptIds: (args.executionReceipts ?? []).map((receipt) => receipt.receiptId)
    },
    generatedAt
  };
}
function renderScope(contextPacket, agentWorkBrief) {
  const lines = [
    `- Repo: ${formatInline(contextPacket ? `${contextPacket.repo.name} (${contextPacket.repo.repoId})` : "Not supplied")}`,
    `- Packet id: ${formatInline(contextPacket?.packetId ?? agentWorkBrief?.contextPacketId ?? "Not supplied")}`,
    `- Brief id: ${formatInline(agentWorkBrief?.source.briefId ?? "Not supplied")}`
  ];
  lines.push(...renderPathList("Primary files", contextPacket?.primaryEditFiles.map((ref) => ref.path) ?? []));
  lines.push(...renderSliceList(contextPacket));
  lines.push(...renderPathList("Docs", contextPacket?.affectedDocs.map((ref) => ref.path) ?? []));
  lines.push(...renderPathList("Tests", contextPacket?.affectedTests.map((ref) => ref.path) ?? []));
  lines.push(...renderPathList("Config", contextPacket?.configFiles.map((ref) => ref.path) ?? []));
  return lines;
}
function renderSemanticSummary(contextPacket, agentWorkBrief) {
  const semanticSignals = semanticSelectionSignals2(contextPacket);
  const parsedSignals = semanticSignals.map(parseSemanticSelectionSignal).filter(isDefined);
  const coveredSurfaces = renderCoveredSurfaces(contextPacket, agentWorkBrief);
  const semanticSurfaces = uniqueStrings(parsedSignals.filter((signal) => signal.kind === "connected_surface" && signal.value).map((signal) => `${signal.value} (${signal.authority === "parser_fact" ? "parser fact" : "advisory"})`));
  const parserFacts = parsedSignals.filter((signal) => signal.authority === "parser_fact").map(formatParsedSemanticSignal);
  const advisoryLabels = parsedSignals.filter((signal) => signal.authority !== "parser_fact").map(formatParsedSemanticSignal);
  const advisoryConstraints = advisoryConstraintSummary(contextPacket);
  const warnings = staleOrLowConfidenceWarnings(contextPacket);
  return [
    `- Covered surfaces: ${coveredSurfaces.length > 0 ? coveredSurfaces.join("; ") : "none supplied"}`,
    `- Semantic connected surfaces: ${semanticSurfaces.length > 0 ? semanticSurfaces.map(formatInline).join(", ") : "none signaled"}`,
    `- Parser facts from selection signals: ${parserFacts.length > 0 ? parserFacts.map(formatInline).join(", ") : "none supplied"}`,
    `- Advisory signals/labels from selection signals (not authority): ${advisoryLabels.length > 0 ? advisoryLabels.map(formatInline).join(", ") : "none supplied"}`,
    `- Advisory constraints (not authority): ${advisoryConstraints.length > 0 ? advisoryConstraints.map(formatInline).join("; ") : "none supplied"}`,
    `- Stale/low-confidence warnings: ${warnings.length > 0 ? warnings.map(formatInline).join("; ") : "none supplied"}`,
    `- Semantic selection signals used: ${semanticSignals.length}`,
    ...semanticSignals.map((signal) => `  - ${formatInline(signal)}`)
  ];
}
function renderActionRoute(contextPlan, contextPacket, agentWorkBrief) {
  const actionRoute = agentWorkBrief?.actionRoute ?? contextPacket?.links?.actionRoute ?? contextPlan?.actionRoute;
  return renderActionRouteSummaryMarkdown(actionRoute);
}
function renderPlannerGraphAdvisory(advisory) {
  if (!advisory)
    return [];
  return [
    "## Planner graph advisory",
    `- ${PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY}`,
    `- Source: ${formatInline(advisory.source)}; basis: ${formatInline(advisory.basis)}`,
    `- Recommended mode: ${formatInline(String(advisory.recommendedGraphMode ?? advisory.recommendedMode ?? "unspecified"))}`,
    `- Selected mode: ${formatInline(String(advisory.selectedGraphMode ?? advisory.selectedMode ?? "unspecified"))}`,
    `- Policy blockers: ${advisory.policyBlockers.length > 0 ? advisory.policyBlockers.map((blocker) => formatInline(String(blocker))).join(", ") : "none"}`,
    `- Memgraph allowed by this handoff: ${advisory.executionPolicy.memgraphAllowed}`,
    `- Depth5 default: ${advisory.depthPolicy.depth5Default}`,
    `- Depth5 allowed: ${advisory.depthPolicy.depth5Allowed}`,
    `- Synapse prediction input allowed: ${advisory.executionPolicy.synapsePredictionInputAllowed}`,
    `- Production defaults changed: ${advisory.executionPolicy.productionDefaultsChanged}`,
    ""
  ];
}
function renderExactRefs(contextPlan, contextPacket, agentWorkBrief) {
  const exactRefs = contextPlan?.exactRefs ?? [];
  const sourceRefs = uniqueStrings([...contextPacket?.sourceRefs ?? [], ...formatRefIds(agentWorkBrief?.sourceRefs ?? [])]);
  const evidenceRefs = uniqueStrings([
    ...contextPacket?.evidenceRefs ?? [],
    ...formatRefIds(agentWorkBrief?.evidenceRefs ?? [])
  ]);
  const receiptRefs = uniqueStrings([
    ...contextPacket?.receiptRefs ?? [],
    ...formatRefIds(agentWorkBrief?.receiptRefs ?? [])
  ]);
  const serviceConnectionIds = uniqueStrings([
    ...contextPlan?.serviceConnectionIds ?? [],
    ...contextPacket?.serviceConnectionIds ?? [],
    ...agentWorkBrief?.serviceConnectionIds ?? []
  ]);
  const serviceConnectionRefs = formatRefIds(agentWorkBrief?.serviceConnectionRefs ?? []);
  return [
    `- Exact refs: ${exactRefs.length}`,
    ...renderRefList(exactRefs),
    `- Source refs: ${sourceRefs.length}${sourceRefs.length > 0 ? ` (${sourceRefs.map(formatInline).join(", ")})` : ""}`,
    `- Evidence refs: ${evidenceRefs.length}${evidenceRefs.length > 0 ? ` (${evidenceRefs.map(formatInline).join(", ")})` : ""}`,
    `- Receipt refs: ${receiptRefs.length}${receiptRefs.length > 0 ? ` (${receiptRefs.map(formatInline).join(", ")})` : ""}`,
    `- Service connection ids: ${serviceConnectionIds.length}${serviceConnectionIds.length > 0 ? ` (${serviceConnectionIds.map(formatInline).join(", ")})` : ""}`,
    `- Service connection refs: ${serviceConnectionRefs.length}${serviceConnectionRefs.length > 0 ? ` (${serviceConnectionRefs.map(formatInline).join(", ")})` : ""}`,
    "- Service connection evidence is advisory and grants no authority unless separately promoted by governance."
  ];
}
function renderGuardrails(contextPlan, contextPacket, agentWorkBrief) {
  return [
    "- Context is advisory and grants no authority.",
    "- Do not mutate canon from this handoff alone; canonical changes require explicit approval and gates.",
    "- Do not perform hidden execution; execution requires an explicit path and receipt trail.",
    `- Explicit refs required: ${contextPlan?.constraints.requireExplicitRefs ?? true}`,
    `- Project search allowed by plan: ${contextPlan?.allowProjectSearch ?? false}`,
    `- Context packet write mode: ${contextPacket?.guardrails?.writeMode ?? "report_only_no_write"}`,
    `- Working set grants authority: ${agentWorkBrief?.guardrails.workingSetGrantsAuthority ?? false}`
  ];
}
function renderReceipts(receipts) {
  if (receipts.length === 0)
    return ["- None supplied."];
  return receipts.flatMap((receipt) => [
    `- ${formatInline(receipt.receiptId)}: ${receipt.status}; blast radius ${receipt.safetySummary.blastRadiusStatus}; changed files ${receipt.safetySummary.changedFileCount}; out of scope ${receipt.safetySummary.outOfScopeFileCount}; denied ${receipt.safetySummary.deniedFileCount}`,
    `  - Traceability flags: ${receipt.safetySummary.traceabilityFlags.length > 0 ? receipt.safetySummary.traceabilityFlags.map(formatInline).join(", ") : "none"}`,
    `  - Warnings: ${receipt.warnings.length > 0 ? receipt.warnings.map(formatInline).join("; ") : "none"}`,
    `  - Errors: ${receipt.errors.length > 0 ? receipt.errors.map(formatInline).join("; ") : "none"}`
  ]);
}
function renderOpenQuestions(contextPacket) {
  const questions = contextPacket?.openQuestions ?? [];
  if (questions.length === 0)
    return ["- None supplied."];
  return questions.map((question) => `- ${formatInline(question)}`);
}
function renderNextAgentInstructions() {
  return [
    "- Start by verifying the worktree state and preserving unrelated changes.",
    "- Use the refs and files above as the initial context, then ask before broadening scope.",
    "- Keep changes within the stated scope and leave a receipt trail for execution or canon changes."
  ];
}
function renderPathList(label, paths) {
  if (paths.length === 0)
    return [`- ${label}: none supplied`];
  return [`- ${label}: ${paths.length}`, ...uniqueStrings(paths).map((path) => `  - ${formatInline(path)}`)];
}
function renderSliceList(contextPacket) {
  const slices = contextPacket?.contextSlices ?? [];
  if (slices.length === 0)
    return ["- Slices: none supplied"];
  return [
    `- Slices: ${slices.length}`,
    ...slices.map((slice) => {
      const range = slice.startLine && slice.endLine ? `:${slice.startLine}-${slice.endLine}` : "";
      return `  - ${formatInline(`${slice.path}${range}`)} (${slice.role}, ${slice.contentMode ?? "path_only"})`;
    })
  ];
}
var LOW_CONFIDENCE_THRESHOLD = 0.7;
var SEMANTIC_SIGNAL_PREFIX = "semantic_label:v1:";
function semanticSelectionSignals2(contextPacket) {
  return uniqueStrings((contextPacket?.contextSlices ?? []).flatMap((slice) => slice.selectionSignals ?? []).filter((signal) => signal.startsWith(SEMANTIC_SIGNAL_PREFIX) && parseSemanticSelectionSignal(signal) !== undefined));
}
function parseSemanticSelectionSignal(signal) {
  const parts = signal.split(":");
  if (parts[0] !== "semantic_label" || parts[1] !== "v1" || parts.length < 5)
    return;
  const [, , source, authority, kind] = parts;
  if (!source || !authority || !kind)
    return;
  if (kind === "label") {
    return { source, authority, kind, namespace: parts[5], key: parts[6], value: parts.slice(7).join(":") };
  }
  return { source, authority, kind, value: parts.slice(5).join(":") };
}
function formatParsedSemanticSignal(signal) {
  if (signal.kind === "label") {
    const namespace = signal.namespace ?? "unknown";
    const key = signal.key ?? "unknown";
    const value2 = signal.value ?? "unknown";
    return `${namespace}.${key}=${value2} (${signal.source}, ${signal.authority})`;
  }
  const value = signal.value ? `:${signal.value}` : "";
  return `${signal.kind}${value} (${signal.source}, ${signal.authority})`;
}
function renderCoveredSurfaces(contextPacket, agentWorkBrief) {
  if (!contextPacket)
    return renderWorkBriefCoveredSurfaces(agentWorkBrief);
  const roleCounts = new Map;
  for (const slice of contextPacket.contextSlices) {
    const role = `slice:${slice.role}`;
    roleCounts.set(role, (roleCounts.get(role) ?? 0) + 1);
  }
  const contextSurfaces = [
    countSurface("primary_files", contextPacket.primaryEditFiles.length),
    ...Array.from(roleCounts.entries()).map(([role, count]) => `${role} ${count}`),
    countSurface("docs", contextPacket.affectedDocs.length),
    countSurface("tests", contextPacket.affectedTests.length),
    countSurface("config", contextPacket.configFiles.length)
  ].filter(isDefined);
  return contextSurfaces.length > 0 ? contextSurfaces : renderWorkBriefCoveredSurfaces(agentWorkBrief);
}
function countSurface(label, count) {
  return count > 0 ? `${label} ${count}` : undefined;
}
function renderWorkBriefCoveredSurfaces(agentWorkBrief) {
  const paths = uniqueStrings([
    ...(agentWorkBrief?.contextPlan.exactRefs ?? []).map(refPathFromActionRef).filter(isDefined),
    ...(agentWorkBrief?.sourceRefs ?? []).map(refPathFromActionRef).filter(isDefined),
    ...(agentWorkBrief?.evidenceRefs ?? []).map(refPathFromActionRef).filter(isDefined),
    ...(agentWorkBrief?.receiptRefs ?? []).map(refPathFromActionRef).filter(isDefined)
  ]);
  if (paths.length === 0)
    return [];
  return [
    countSurface("backend_code", paths.filter(isBackendCodePath).length),
    countSurface("ui_surface", paths.filter(isUiSurfacePath).length),
    countSurface("tests", paths.filter(isTestPath).length),
    countSurface("docs", paths.filter(isDocPath).length),
    countSurface("config", paths.filter(isConfigPath).length),
    countSurface("mcp_server", paths.filter((path) => path.includes("packages/mcp-server/")).length)
  ].filter(isDefined);
}
function refPathFromActionRef(ref) {
  const metadataPath = ref.metadata?.["path"];
  if (typeof metadataPath === "string" && metadataPath.length > 0)
    return metadataPath;
  if (looksLikePath(ref.id))
    return ref.id;
  if (ref.label && looksLikePath(ref.label))
    return ref.label;
  return;
}
function looksLikePath(value) {
  return value.includes("/") || value.endsWith(".ts") || value.endsWith(".tsx") || value.endsWith(".md") || value.endsWith(".json");
}
function isBackendCodePath(path) {
  return path.startsWith("convex/") || path.startsWith("packages/core/") || path.startsWith("packages/state/");
}
function isUiSurfacePath(path) {
  return path.startsWith("apps/") || path.startsWith("packages/ui/") || path.endsWith(".tsx");
}
function isTestPath(path) {
  return path.includes("convex-tests/") || path.includes(".test.") || path.includes(".spec.");
}
function isDocPath(path) {
  return path.startsWith("docs/") || path.endsWith(".md") || path.includes("/README.");
}
function isConfigPath(path) {
  return path.endsWith("package.json") || path.endsWith("tsconfig.json") || path.endsWith("vite.config.ts");
}
function advisoryConstraintSummary(contextPacket) {
  return uniqueStrings([
    ...contextPacket?.constraints ?? [],
    ...contextPacket?.guardrails?.reportOnly ? ["report_only"] : [],
    ...contextPacket?.guardrails?.sourceContextGrantsNoAuthority ? ["source_context_grants_no_authority"] : [],
    ...contextPacket?.guardrails?.contextDoesNotMutateCanon ? ["context_does_not_mutate_canon"] : []
  ]);
}
function staleOrLowConfidenceWarnings(contextPacket) {
  if (!contextPacket)
    return [];
  const warnings = [];
  for (const fileRef of fileRefsWithLabels(contextPacket)) {
    if (isLowConfidence(fileRef.ref.confidence)) {
      warnings.push(`${fileRef.label} ${fileRef.ref.path} confidence ${formatConfidence(fileRef.ref.confidence)}`);
    }
  }
  for (const slice of contextPacket.contextSlices) {
    if (!isLowConfidence(slice.confidence))
      continue;
    const range = slice.startLine && slice.endLine ? `:${slice.startLine}-${slice.endLine}` : "";
    warnings.push(`slice ${slice.path}${range} confidence ${formatConfidence(slice.confidence)}`);
  }
  return warnings;
}
function fileRefsWithLabels(contextPacket) {
  return [
    ...contextPacket.primaryEditFiles.map((ref) => ({ label: "primary_file", ref })),
    ...contextPacket.affectedDocs.map((ref) => ({ label: "doc", ref })),
    ...contextPacket.affectedTests.map((ref) => ({ label: "test", ref })),
    ...contextPacket.configFiles.map((ref) => ({ label: "config", ref }))
  ];
}
function isLowConfidence(confidence) {
  return typeof confidence === "number" && Number.isFinite(confidence) && confidence < LOW_CONFIDENCE_THRESHOLD;
}
function formatConfidence(confidence) {
  return typeof confidence === "number" && Number.isFinite(confidence) ? confidence.toFixed(2) : "unknown";
}
function renderRefList(refs) {
  if (refs.length === 0)
    return [];
  return refs.map((ref) => `  - ${formatInline(`${ref.kind}:${ref.id}${ref.label ? ` (${ref.label})` : ""}`)}`);
}
function formatRefIds(refs) {
  return refs.map((ref) => `${ref.kind}:${ref.id}`);
}
function isDefined(value) {
  return value !== undefined;
}
function uniqueStrings(values) {
  return Array.from(new Set(values.filter((value) => value.length > 0)));
}
function formatInline(value) {
  return value.replace(/\n/g, " ").trim();
}
export {
  isGovernanceFeedbackCommand,
  isCorrectionFeedbackCommand,
  isBriefItemV2,
  feedbackCommandRecordsPositiveEvidence,
  defaultFeedbackScopeForCommand,
  contextPlanIntentForFeedbackCommand,
  buildTaskBriefV1FromActionItems,
  buildDeterministicWhyV1,
  buildDeterministicWhyForBriefItem,
  buildContextPlanV1,
  buildContextPlanForBriefItem,
  buildBriefItemV2,
  buildBriefItemRelevanceV1,
  buildAgentWorkBriefV1,
  buildAgentHandoffMarkdownV1,
  briefCommandsForItem,
  activityTypeForFeedbackCommand,
  TASK_BRIEF_STATES_V1,
  TASK_BRIEF_READ_MODEL_VERSION,
  SESSION_ACTIVITY_TYPES_V1,
  FEEDBACK_COMMANDS_V1,
  DETERMINISTIC_WHY_SCHEMA_VERSION,
  DETERMINISTIC_WHY_COPY_VERSION,
  DETERMINISTIC_WHY_BULLET_KINDS_V1,
  CONTEXT_DEPTHS,
  BRIEF_SURFACES_V1,
  BRIEF_SECTION_KINDS_V1,
  BRIEF_SCHEMA_VERSION,
  BRIEF_ITEM_RELEVANCE_SOURCES_V1,
  BRIEF_ITEM_READ_MODEL_VERSION_V2,
  BRIEF_ITEM_KINDS_V1,
  BRIEF_COMMAND_LABELS_V1,
  BRIEF_COMMAND_DESCRIPTORS_V1,
  BRIEF_COMMAND_DEFAULT_SCOPES_V1,
  AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION
};
