// ../core/src/goalIntelligence/types.ts
var GOAL_INTELLIGENCE_SCHEMA_VERSION = 1;
var GOAL_INTELLIGENCE_COMPACT_REF_LIMIT = 12;
var GOAL_STEWARD_DECISION_VALUES = [
  "continue_active_goal",
  "replace_active_goal",
  "branch_goal",
  "start_goal",
  "ask_for_goal_boundary"
];
var GOAL_MEMORY_CANDIDATE_KIND_VALUES = [
  "style_preference",
  "code_rewrite_preference",
  "outcome_pattern",
  "lifecycle_file_pattern",
  "lifecycle_worktask_pattern",
  "validation_practice",
  "risk_pattern",
  "proof_requirement",
  "review_process"
];
var GOAL_MEMORY_CANDIDATE_SOURCE_KIND_VALUES = [
  "goal_lifecycle",
  "outcome_feedback",
  "learn_from_outcome",
  "preference_replay",
  "pr_review",
  "code_trail",
  "om_entry",
  "manual",
  "goal_outcome_feedback",
  "goal_lifecycle_observation",
  "code_review",
  "observational_memory",
  "explicit"
];
var GOAL_MEMORY_CANDIDATE_STATUS_VALUES = [
  "candidate",
  "needs_more_evidence",
  "ready_for_review",
  "rejected",
  "promoted_to_learning",
  "submitted_to_truth",
  "truth_approved",
  "truth_rejected"
];
// ../core/src/goalIntelligence/candidateHelpers.ts
var GOAL_MEMORY_HASH_PREFIX = "goal-memory";
function buildGoalMemoryCandidateIdentityV1(args) {
  const normalizedGoal = normalizeGoalMemoryTextV1(args.goal);
  const goalHash = normalizedGoal ? `${GOAL_MEMORY_HASH_PREFIX}:goal:${stableHash(normalizedGoal)}` : undefined;
  const sourceEventId = cleanString(args.sourceEventId) ?? firstString(args.sourceIds) ?? `${GOAL_MEMORY_HASH_PREFIX}:source-event:${stableHash({
    sourceKind: args.sourceKind,
    candidateKind: args.candidateKind,
    title: normalizeGoalMemoryTextV1(args.title),
    summary: normalizeGoalMemoryTextV1(args.summary),
    goalHash,
    goalSessionId: cleanString(args.goalSessionId),
    targetRefs: normalizedStringSet(args.targetRefs),
    filePaths: normalizedStringSet(args.filePaths),
    evidenceRefs: normalizedStringSet(args.evidenceRefs),
    observationRefs: normalizedStringSet(args.observationRefs),
    taskRefs: normalizedStringSet(args.taskRefs)
  })}`;
  const sourceHash = `${GOAL_MEMORY_HASH_PREFIX}:source:${stableHash({
    sourceKind: args.sourceKind,
    sourceEventId,
    sourceIds: normalizedStringSet(args.sourceIds),
    candidateKind: args.candidateKind,
    title: normalizeGoalMemoryTextV1(args.title),
    summary: normalizeGoalMemoryTextV1(args.summary),
    normalizedRule: normalizeGoalMemoryTextV1(args.normalizedRule),
    goalHash,
    goalSessionId: cleanString(args.goalSessionId),
    filePaths: normalizedStringSet(args.filePaths),
    targetRefs: normalizedStringSet(args.targetRefs),
    evidenceRefs: normalizedStringSet(args.evidenceRefs),
    observationRefs: normalizedStringSet(args.observationRefs),
    taskRefs: normalizedStringSet(args.taskRefs),
    serviceConnectionIds: normalizedStringSet(args.serviceConnectionIds)
  })}`;
  const dedupeKey = `${GOAL_MEMORY_HASH_PREFIX}:dedupe:${stableHash({
    sourceKind: args.sourceKind,
    candidateKind: args.candidateKind,
    goalHash: goalHash ?? cleanString(args.goalSessionId),
    goalSessionId: cleanString(args.goalSessionId),
    activeGoalId: cleanString(args.activeGoalId),
    parentGoalId: cleanString(args.parentGoalId),
    supersedesGoalId: cleanString(args.supersedesGoalId),
    filePaths: normalizedStringSet(args.filePaths),
    targetRefs: normalizedStringSet(args.targetRefs),
    normalizedRule: normalizeGoalMemoryTextV1(args.normalizedRule ?? args.summary ?? args.title),
    serviceConnectionIds: normalizedStringSet(args.serviceConnectionIds)
  })}`;
  return {
    candidateId: `${GOAL_MEMORY_HASH_PREFIX}:candidate:${stableHash(dedupeKey)}`,
    dedupeKey,
    sourceHash,
    sourceEventId,
    goalHash
  };
}
function normalizeGoalMemoryTextV1(value) {
  const text = cleanString(value);
  if (!text)
    return;
  return text.toLowerCase().replace(/\s+/g, " ").trim();
}
function collectGoalMemoryFilePathsV1(values) {
  return uniqueStrings(values.flatMap((value) => stringList(value)).filter(looksLikeFilePath));
}
function goalMemoryCandidateSourceIdsV1(values) {
  return uniqueStrings(values.flatMap((value) => stringList(value))).slice(0, 24);
}
function normalizedStringSet(values) {
  return uniqueStrings(values ?? []).map((value) => normalizeGoalMemoryTextV1(value) ?? value).sort();
}
function firstString(values) {
  return uniqueStrings(values ?? [])[0];
}
function stringList(value) {
  if (Array.isArray(value))
    return value.map((item) => cleanString(item)).filter((item) => Boolean(item));
  const text = cleanString(value);
  return text ? [text] : [];
}
function uniqueStrings(values) {
  return Array.from(new Set(values.map((value) => value?.trim()).filter((value) => Boolean(value))));
}
function looksLikeFilePath(value) {
  if (!value.includes("/"))
    return false;
  if (/^(https?:|git:|diff:|trail:|vitest:|test:|validation:|receipt:|goal:|goal-session:|service:)/i.test(value))
    return false;
  return /\.[a-z0-9]+($|[:#])/i.test(value) || value.startsWith("packages/") || value.startsWith("apps/") || value.startsWith("convex/") || value.startsWith("docs/") || value.startsWith("src/");
}
function cleanString(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function stableHash(value) {
  const text = stableJson(value);
  let hash = 2166136261;
  for (let index = 0;index < text.length; index += 1) {
    hash ^= text.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0").slice(0, 12);
}
function stableJson(value) {
  if (Array.isArray(value))
    return `[${value.map(stableJson).join(",")}]`;
  if (value && typeof value === "object") {
    return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
  }
  return JSON.stringify(value);
}
// ../core/src/goalIntelligence/builders.ts
var COMPACT_REF_LIMIT = 12;
var CLOSED_OUTCOMES = new Set(["accepted", "closed", "fixed", "passed", "pass"]);
var GOAL_INTELLIGENCE_GUARDRAILS = {
  reportOnly: true,
  advisoryOnly: true,
  noAuthority: true,
  noHiddenExecution: true,
  noProviderCalls: true,
  noGraphMutation: true,
  noMemoryPromotion: true,
  noTranscriptReplay: true,
  noServiceWrite: true,
  memoryPromotionRequiresExplicitPath: true,
  compactContinuityOnly: true,
  serviceConnectionsAreEvidenceOnly: true,
  appendRequiresExplicitIntent: true
};
function buildGoalIntelligenceGuardrailsV1() {
  return { ...GOAL_INTELLIGENCE_GUARDRAILS };
}
function buildGoalSessionV1({ args, goal }) {
  const session = asRecord(args["goalSession"]) ?? {};
  const steering = asRecord(args["steering"]) ?? {};
  const goalSessionId = cleanString2(session["goalSessionId"]) ?? cleanString2(steering["goalSessionId"]) ?? cleanString2(args["goalSessionId"]);
  const activeGoalId = cleanString2(session["activeGoalId"]) ?? cleanString2(steering["activeGoalId"]) ?? cleanString2(args["activeGoalId"]);
  const incomingGoalId = cleanString2(session["incomingGoalId"]) ?? cleanString2(steering["incomingGoalId"]) ?? cleanString2(args["incomingGoalId"]);
  const parentGoalId = cleanString2(session["parentGoalId"]) ?? cleanString2(steering["parentGoalId"]) ?? activeGoalId;
  const supersedesGoalId = cleanString2(session["supersedesGoalId"]) ?? cleanString2(steering["supersedesGoalId"]);
  const activeGoal = cleanString2(session["activeGoal"]) ?? cleanString2(steering["activeGoal"]) ?? cleanString2(args["activeGoal"]);
  const incomingGoal = cleanString2(session["incomingGoal"]) ?? cleanString2(steering["incomingGoal"]) ?? goal;
  return removeUndefined({
    schemaVersion: 1,
    kind: "goal_session",
    goalSessionId,
    activeGoalId,
    incomingGoalId,
    parentGoalId,
    supersedesGoalId,
    activeGoal,
    incomingGoal,
    contextRunIds: uniqueStrings2(stringList2(session["contextRunIds"])),
    codeMarketSnapshotIds: uniqueStrings2(stringList2(session["codeMarketSnapshotIds"])),
    codeWorkroomSessionId: cleanString2(session["codeWorkroomSessionId"]),
    codeTrailRefs: uniqueStrings2(stringList2(session["codeTrailRefs"])),
    prReviewRefs: uniqueStrings2(stringList2(session["prReviewRefs"])),
    commitRefs: uniqueStrings2(stringList2(session["commitRefs"])),
    validationRefs: uniqueStrings2(stringList2(session["validationRefs"])),
    outcomeFeedbackRefs: uniqueStrings2(stringList2(session["outcomeFeedbackRefs"])),
    serviceConnectionIds: uniqueStrings2(stringList2(session["serviceConnectionIds"])),
    staleRefs: uniqueStrings2(stringList2(session["staleRefs"])),
    openQuestions: uniqueStrings2(stringList2(session["openQuestions"])),
    completedSteps: uniqueStrings2(stringList2(session["completedSteps"])),
    remainingSteps: uniqueStrings2(stringList2(session["remainingSteps"])),
    boundaryPolicy: "new_goal_requires_explicit_steer_decision",
    refsOnly: true,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function goalSessionHasContinuityV1(goalSession) {
  if (!goalSession)
    return false;
  return [
    "completedSteps",
    "remainingSteps",
    "contextRunIds",
    "codeMarketSnapshotIds",
    "codeTrailRefs",
    "prReviewRefs",
    "commitRefs",
    "validationRefs",
    "outcomeFeedbackRefs",
    "staleRefs",
    "openQuestions"
  ].some((field) => stringList2(goalSession[field]).length > 0);
}
function collectGoalServiceConnectionIdsV1(args) {
  const outcomeFeedback = asRecord(args["outcomeFeedback"]);
  const steering = asRecord(args["steering"]);
  const intelligenceCommit = asRecord(args["intelligenceCommit"]);
  const preferenceReplay = asRecord(args["preferenceReplay"]);
  const diagnosticClosure = asRecord(args["diagnosticClosure"]);
  const serviceImpact = asRecord(args["serviceImpact"]);
  return uniqueStrings2([
    ...stringList2(args["serviceConnectionIds"]),
    ...stringList2(outcomeFeedback?.["serviceConnectionIds"]),
    ...stringList2(steering?.["serviceConnectionIds"]),
    ...stringList2(intelligenceCommit?.["serviceConnectionIds"]),
    ...stringList2(preferenceReplay?.["serviceConnectionIds"]),
    ...stringList2(diagnosticClosure?.["serviceConnectionIds"]),
    ...stringList2(serviceImpact?.["serviceConnectionIds"]),
    ...serviceConnectionIdsFromEvidence(args["serviceConnections"])
  ]);
}
function buildGoalOutcomeFeedbackV1({ args, goal, serviceConnectionIds }) {
  const feedback = asRecord(args["outcomeFeedback"]) ?? {};
  const correctionKind = cleanString2(feedback["correctionKind"]) ?? cleanString2(feedback["kind"]) ?? inferCorrectionKind(feedback);
  const outcome = cleanString2(feedback["outcome"]) ?? cleanString2(feedback["status"]);
  const before = cleanString2(feedback["before"]) ?? cleanString2(feedback["original"]);
  const after = cleanString2(feedback["after"]) ?? cleanString2(feedback["rewrite"]) ?? cleanString2(feedback["humanRewrite"]) ?? cleanString2(feedback["corrected"]);
  const stylePreference = cleanString2(feedback["stylePreference"]) ?? cleanString2(feedback["preference"]);
  const rationale = cleanString2(feedback["rationale"]) ?? cleanString2(feedback["reason"]);
  const acceptedRefs = collectAcceptedRefsV1(args, feedback);
  const rejectedRefs = collectRejectedRefsV1(args, feedback);
  const missingRefs = collectMissingRefsV1(args, feedback);
  const evidenceRefs = uniqueStrings2([
    ...stringList2(args["evidenceRefs"]),
    ...stringList2(feedback["evidenceRefs"]),
    ...acceptedRefs,
    ...rejectedRefs,
    ...missingRefs,
    ...stringList2(args["exactRefs"])
  ]);
  const goalSession = asRecord(args["goalSession"]);
  const outcomeFeedbackRefs = uniqueStrings2([
    ...stringList2(args["outcomeFeedbackRefs"]),
    ...stringList2(feedback["outcomeFeedbackRefs"])
  ]);
  const targetRefs = uniqueStrings2([
    ...evidenceRefs,
    ...stringList2(args["refs"]),
    ...stringList2(args["refIds"]),
    ...stringList2(args["selectedRefs"]),
    ...stringList2(args["requiredRefs"]),
    ...stringList2(args["candidateRefs"])
  ]).slice(0, COMPACT_REF_LIMIT);
  const filePaths = collectGoalMemoryFilePathsV1([
    args["changedFiles"],
    args["paths"],
    args["files"],
    args["exactRefs"],
    acceptedRefs,
    rejectedRefs,
    missingRefs,
    evidenceRefs
  ]).slice(0, COMPACT_REF_LIMIT);
  const taskRefs = uniqueStrings2([
    ...stringList2(args["validationRefs"]),
    ...stringList2(args["diffRefs"]),
    ...stringList2(args["codeTrailRefs"]),
    ...stringList2(args["prReviewRefs"]),
    ...outcomeFeedbackRefs
  ]).slice(0, COMPACT_REF_LIMIT);
  const preferenceSignals = buildPreferenceSignals({ outcome, correctionKind, before, after, stylePreference, rationale, evidenceRefs });
  const memoryCandidates = buildOutcomeMemoryCandidates({
    goal,
    goalSessionId: cleanString2(goalSession?.["goalSessionId"]),
    activeGoalId: cleanString2(goalSession?.["activeGoalId"]),
    parentGoalId: cleanString2(goalSession?.["parentGoalId"]),
    supersedesGoalId: cleanString2(goalSession?.["supersedesGoalId"]),
    correctionKind,
    outcome,
    after,
    stylePreference,
    rationale,
    acceptedRefs,
    evidenceRefs,
    targetRefs,
    filePaths,
    taskRefs,
    outcomeFeedbackRefs,
    serviceConnectionIds
  });
  return removeUndefined({
    kind: "rhei_code_goal_outcome_feedback",
    schemaVersion: 1,
    correctionKind,
    outcome,
    rationale,
    evidenceRefs,
    acceptedRefs,
    rejectedRefs,
    missingRefs,
    preferenceSignals,
    memoryCandidates,
    serviceConnectionIds,
    closedLoops: uniqueStrings2([
      "feedback:outcome_captured",
      memoryCandidates.length > 0 ? "feedback:memory_candidate_emitted" : undefined,
      evidenceRefs.length > 0 ? "feedback:evidence_refs_linked" : undefined
    ]),
    noMemoryWrite: true,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildGoalStewardDecisionV1({ args, goal }) {
  const steering = asRecord(args["steering"]) ?? {};
  const goalSession = asRecord(args["goalSession"]) ?? {};
  const activeGoal = cleanString2(steering["activeGoal"]) ?? cleanString2(goalSession["activeGoal"]) ?? cleanString2(args["activeGoal"]);
  const incomingGoal = cleanString2(steering["incomingGoal"]) ?? cleanString2(goalSession["incomingGoal"]) ?? goal;
  const allowAppend = booleanValue(steering["allowAppend"]) ?? booleanValue(args["allowAppend"]) ?? false;
  const forceNewGoal = booleanValue(steering["forceNewGoal"]) ?? booleanValue(args["forceNewGoal"]) ?? false;
  const replaceActiveGoal = booleanValue(steering["replaceActiveGoal"]) ?? booleanValue(args["replaceActiveGoal"]) ?? false;
  const similarity = activeGoal && incomingGoal ? goalSimilarity(activeGoal, incomingGoal) : undefined;
  const decision = steeringDecision({ activeGoal, incomingGoal, allowAppend, forceNewGoal, replaceActiveGoal, similarity });
  const reasonCodes = steeringReasonCodes({ activeGoal, incomingGoal, allowAppend, forceNewGoal, replaceActiveGoal, similarity, decision });
  return removeUndefined({
    kind: "rhei_code_goal_steering",
    schemaVersion: 1,
    decision,
    policy: "latest_explicit_goal_wins_unless_append_is_explicit",
    activeGoal,
    incomingGoal,
    activeGoalId: cleanString2(steering["activeGoalId"]) ?? cleanString2(goalSession["activeGoalId"]) ?? cleanString2(args["activeGoalId"]),
    incomingGoalId: cleanString2(steering["incomingGoalId"]) ?? cleanString2(goalSession["incomingGoalId"]) ?? cleanString2(args["incomingGoalId"]),
    parentGoalId: cleanString2(steering["parentGoalId"]) ?? cleanString2(goalSession["parentGoalId"]),
    supersedesGoalId: cleanString2(steering["supersedesGoalId"]) ?? cleanString2(goalSession["supersedesGoalId"]),
    similarity,
    appendAllowed: allowAppend,
    activeGoalShouldChange: decision === "start_goal" || decision === "branch_goal" || decision === "replace_active_goal",
    requiresExplicitUserConfirmation: decision === "ask_for_goal_boundary" || decision === "branch_goal",
    reasonCodes,
    recommendedNextStep: steeringNextStep(decision),
    serviceConnectionIds: collectGoalServiceConnectionIdsV1(args),
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildGoalResumeV1({ args, goal, goalSession, serviceConnectionIds: baseServiceConnectionIds }) {
  const resume = asRecord(args["resume"]) ?? {};
  const normalizedSession = normalizedGoalSession(goalSession, goal, resume);
  const serviceConnectionIds = uniqueStrings2([
    ...baseServiceConnectionIds,
    ...stringList2(resume["serviceConnectionIds"]),
    ...normalizedSession.serviceConnectionIds
  ]);
  const exactRefs = uniqueStrings2([...stringList2(args["exactRefs"]), ...stringList2(resume["exactRefs"])]);
  const evidenceRefs = collectGoalEvidenceRefsV1(args, resume);
  const continuityPacket = buildGoalContinuityPacketV1({
    goal,
    goalSession: normalizedSession,
    resume,
    exactRefs,
    evidenceRefs
  });
  const commitRefs = uniqueStrings2([...normalizedSession.commitRefs, ...stringList2(resume["commitRefs"])]);
  return {
    kind: "rhei_code_goal_resume",
    schemaVersion: 1,
    goalSession: normalizedSession,
    goalSessionId: normalizedSession.goalSessionId,
    activeGoalId: normalizedSession.activeGoalId,
    parentGoalId: normalizedSession.parentGoalId,
    supersedesGoalId: normalizedSession.supersedesGoalId,
    continuityPacket,
    intelligenceBackends: {
      codeMarket: {
        contextRunIds: uniqueStrings2([...normalizedSession.contextRunIds, ...stringList2(resume["contextRunIds"])]),
        snapshotIds: uniqueStrings2([...normalizedSession.codeMarketSnapshotIds, ...stringList2(resume["codeMarketSnapshotIds"])])
      },
      codeTrail: { refs: uniqueStrings2([...normalizedSession.codeTrailRefs, ...stringList2(resume["codeTrailRefs"])]) },
      prReview: { refs: uniqueStrings2([...normalizedSession.prReviewRefs, ...stringList2(resume["prReviewRefs"])]) },
      git: { commitRefs },
      repoIntelligence: { evidenceRefs: evidenceRefs.slice(0, COMPACT_REF_LIMIT) }
    },
    serviceConnectionIds,
    ...buildGoalIntelligenceGuardrailsV1()
  };
}
function buildGoalContinuityPacketV1({
  goal,
  goalSession,
  resume = {},
  exactRefs = [],
  evidenceRefs = [],
  maxRefs = COMPACT_REF_LIMIT
}) {
  const completedSteps = uniqueStrings2([
    ...goalSession.completedSteps,
    ...stringList2(resume["completedSteps"])
  ]);
  const remainingSteps = uniqueStrings2([
    ...goalSession.remainingSteps,
    ...stringList2(resume["remainingSteps"])
  ]);
  const commitRefs = uniqueStrings2([...goalSession.commitRefs, ...stringList2(resume["commitRefs"])]);
  const validationRefs = uniqueStrings2([...goalSession.validationRefs, ...stringList2(resume["validationRefs"])]);
  const outcomeFeedbackRefs = uniqueStrings2([...goalSession.outcomeFeedbackRefs, ...stringList2(resume["outcomeFeedbackRefs"])]);
  const done = uniqueStrings2([
    ...completedSteps,
    ...commitRefs.map((ref) => `commit:${ref}`),
    ...validationRefs.map((ref) => `validation:${ref}`),
    ...outcomeFeedbackRefs.map((ref) => `outcome:${ref}`)
  ]);
  const staleRefs = uniqueStrings2([...goalSession.staleRefs, ...stringList2(resume["staleRefs"])]);
  const currentRefs = uniqueStrings2([...exactRefs, ...evidenceRefs]);
  return removeUndefined({
    schemaVersion: 1,
    kind: "goal_continuity_packet",
    goal,
    done: done.slice(0, maxRefs),
    doneOmitted: omittedAfterLimit(done.length, maxRefs),
    currentRefs: currentRefs.slice(0, maxRefs),
    currentRefsOmitted: omittedAfterLimit(currentRefs.length, maxRefs),
    openQuestions: uniqueStrings2([...goalSession.openQuestions, ...stringList2(resume["openQuestions"])]),
    remainingSteps,
    staleRefs,
    staleWarnings: staleRefs.map((ref) => `${ref} must be revalidated before reuse.`),
    contextEngineering: "Resume from compact receipts and ranked deltas only; do not replay full transcripts into the next context window.",
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildGoalIntelligenceCommitV1({ args, goal, goalSession, serviceConnectionIds: baseServiceConnectionIds }) {
  const input = asRecord(args["intelligenceCommit"]) ?? {};
  const normalizedSession = normalizedGoalSession(goalSession, goal, input);
  const commitRefs = uniqueStrings2([...stringList2(input["commitRefs"]), ...normalizedSession.commitRefs]);
  const contextRunIds = uniqueStrings2([...stringList2(input["contextRunIds"]), ...normalizedSession.contextRunIds]);
  const codeMarketSnapshotIds = uniqueStrings2([...stringList2(input["codeMarketSnapshotIds"]), ...normalizedSession.codeMarketSnapshotIds]);
  const codeTrailRefs = uniqueStrings2([...stringList2(input["codeTrailRefs"]), ...normalizedSession.codeTrailRefs]);
  const prReviewRefs = uniqueStrings2([...stringList2(input["prReviewRefs"]), ...normalizedSession.prReviewRefs]);
  const validationRefs = uniqueStrings2([...stringList2(input["validationRefs"]), ...normalizedSession.validationRefs]);
  const outcomeFeedbackRefs = uniqueStrings2([...stringList2(input["outcomeFeedbackRefs"]), ...normalizedSession.outcomeFeedbackRefs]);
  const evidenceRefs = uniqueStrings2([
    ...collectGoalEvidenceRefsV1(args, input),
    ...commitRefs.map((ref) => `git:${ref}`),
    ...validationRefs,
    ...codeTrailRefs,
    ...prReviewRefs,
    ...outcomeFeedbackRefs
  ]);
  const intelligenceCommitId = cleanString2(input["intelligenceCommitId"]) ?? cleanString2(input["id"]) ?? `intel-commit:${goalStableHash({ goal, commitRefs, validationRefs, codeTrailRefs, prReviewRefs, evidenceRefs })}`;
  return removeUndefined({
    kind: "rhei_code_goal_intelligence_commit",
    schemaVersion: 1,
    intelligenceCommitId,
    summary: cleanString2(input["summary"]) ?? "Report-only intelligence receipt linking source commits to context, validation, review, and outcome evidence.",
    goal,
    goalSession: normalizedSession,
    gitCommitRefs: commitRefs,
    contextRunIds,
    codeMarketSnapshotIds,
    codeTrailRefs,
    prReviewRefs,
    validationRefs,
    outcomeFeedbackRefs,
    evidenceRefs: evidenceRefs.slice(0, COMPACT_REF_LIMIT),
    evidenceRefsOmitted: omittedAfterLimit(evidenceRefs.length, COMPACT_REF_LIMIT),
    compareToGit: "Git records source diff history; this receipt records why-context, diagnostic, validation, PR review, service, and outcome evidence around that diff.",
    serviceConnectionIds: uniqueStrings2([...baseServiceConnectionIds, ...stringList2(input["serviceConnectionIds"])]),
    noSourceMutation: true,
    noMemoryWrite: true,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildPreferenceReplayV1({ args, goal, serviceConnectionIds }) {
  const replay = asRecord(args["preferenceReplay"]) ?? {};
  const outcomeFeedback = buildGoalOutcomeFeedbackV1({ args, goal, serviceConnectionIds });
  const preferences = uniqueStrings2([
    ...stringList2(replay["preferences"]),
    cleanString2(replay["preference"]),
    cleanString2(replay["stylePreference"]),
    cleanString2(outcomeFeedback.rationale),
    ...outcomeFeedback.preferenceSignals.flatMap((signal) => signal.kind === "style_preference" ? [signal.summary] : [])
  ]);
  const acceptedRefs = uniqueStrings2([
    ...stringList2(args["acceptedRefs"]),
    ...stringList2(replay["acceptedRefs"]),
    ...outcomeFeedback.acceptedRefs
  ]);
  const rejectedRefs = uniqueStrings2([
    ...stringList2(args["rejectedRefs"]),
    ...stringList2(replay["rejectedRefs"]),
    ...outcomeFeedback.rejectedRefs
  ]);
  const evidenceRefs = uniqueStrings2([
    ...collectGoalEvidenceRefsV1(args, replay),
    ...outcomeFeedback.evidenceRefs,
    ...acceptedRefs,
    ...rejectedRefs
  ]);
  return removeUndefined({
    kind: "rhei_code_goal_preference_replay",
    schemaVersion: 1,
    goal,
    preferences,
    acceptedRefs,
    rejectedRefs,
    memoryCandidates: outcomeFeedback.memoryCandidates,
    replayPlan: [
      "Bias future proposals toward accepted human rewrites and explicit style preferences.",
      "Keep rejected refs as negative examples for ranking only.",
      "Promote memory only through the governed memory path after repeated evidence."
    ],
    evaluation: {
      expectedSignals: uniqueStrings2([
        preferences.length > 0 ? "style_preference_reused" : undefined,
        outcomeFeedback.memoryCandidates.length > 0 ? "human_rewrite_pattern_matched" : undefined,
        acceptedRefs.length > 0 ? "accepted_refs_ranked_higher" : undefined,
        rejectedRefs.length > 0 ? "rejected_refs_ranked_lower" : undefined
      ]),
      trialFootprintRefs: evidenceRefs.slice(0, COMPACT_REF_LIMIT),
      trialFootprintRefsOmitted: omittedAfterLimit(evidenceRefs.length, COMPACT_REF_LIMIT),
      status: "replay_plan_ready_report_only"
    },
    rankingBiasEvidence: {
      status: "advisory_only_no_memory_write",
      acceptedRefs,
      rejectedRefs,
      evidenceRefs: evidenceRefs.slice(0, COMPACT_REF_LIMIT)
    },
    serviceConnectionIds,
    noMemoryWrite: true,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildDiagnosticClosureV1({ args, goal, serviceConnectionIds }) {
  const closure = asRecord(args["diagnosticClosure"]) ?? {};
  const diagnosticRefs = uniqueStrings2([...stringList2(closure["diagnosticRefs"]), ...stringList2(args["diagnosticRefs"])]);
  const fixRefs = uniqueStrings2([...stringList2(closure["fixRefs"]), ...stringList2(args["fixRefs"])]);
  const validationRefs = uniqueStrings2([
    ...stringList2(closure["validationRefs"]),
    ...stringList2(args["validationRefs"]),
    ...stringList2(asRecord(args["goalSession"])?.["validationRefs"])
  ]);
  const outcome = cleanString2(closure["outcome"]) ?? cleanString2(closure["status"]) ?? cleanString2(args["outcome"]);
  const evidenceRefs = uniqueStrings2([
    ...collectGoalEvidenceRefsV1(args, closure),
    ...diagnosticRefs,
    ...fixRefs,
    ...validationRefs
  ]);
  const closed = validationRefs.length > 0 && CLOSED_OUTCOMES.has((outcome ?? "").toLowerCase());
  const status = closed ? "closed_with_validation" : validationRefs.length > 0 ? "validation_linked" : "needs_validation";
  return removeUndefined({
    kind: "rhei_code_goal_diagnostic_closure",
    schemaVersion: 1,
    goal,
    status,
    outcome,
    diagnosticRefs,
    fixRefs,
    validationRefs,
    evidenceRefs: evidenceRefs.slice(0, COMPACT_REF_LIMIT),
    evidenceRefsOmitted: omittedAfterLimit(evidenceRefs.length, COMPACT_REF_LIMIT),
    closedLoops: closed ? ["diagnostic:validated_fix", "diagnostic:outcome_captured"] : [],
    nextAction: closed ? {
      tool: "rhei_code_goal",
      mode: "intelligence_commit",
      reason: "Diagnostic evidence has validation; emit a compact intelligence receipt for future resume and replay."
    } : {
      tool: "rhei_code_context_for_goal",
      input: "evidenceIntake",
      reason: "Validation evidence is still required before the diagnostic loop can close."
    },
    serviceConnectionIds,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildServiceImpactV1({ args, goal, serviceConnectionIds: baseServiceConnectionIds }) {
  const impact = asRecord(args["serviceImpact"]) ?? {};
  const serviceConnectionIds = uniqueStrings2([
    ...baseServiceConnectionIds,
    ...stringList2(impact["serviceConnectionIds"]),
    ...serviceConnectionIdsFromEvidence(args["serviceConnections"])
  ]);
  const evidenceRefs = collectGoalEvidenceRefsV1(args, impact);
  const impactedRefs = uniqueStrings2([
    ...stringList2(impact["impactedRefs"]),
    ...stringList2(impact["impactRefs"]),
    ...stringList2(args["exactRefs"]),
    ...evidenceRefs
  ]);
  const backendRefs = uniqueStrings2(stringList2(impact["backendRefs"]));
  const uiRefs = uniqueStrings2(stringList2(impact["uiRefs"]));
  const testRefs = uniqueStrings2(stringList2(impact["testRefs"]));
  const docsRefs = uniqueStrings2(stringList2(impact["docsRefs"]));
  return removeUndefined({
    kind: "rhei_code_goal_service_impact",
    schemaVersion: 1,
    goal,
    serviceConnectionIds,
    serviceConnectionRefs: uniqueStrings2([
      ...stringList2(impact["serviceConnectionRefs"]),
      ...serviceConnectionIds
    ]).slice(0, COMPACT_REF_LIMIT),
    impactedRefs: impactedRefs.slice(0, COMPACT_REF_LIMIT),
    impactedRefsOmitted: omittedAfterLimit(impactedRefs.length, COMPACT_REF_LIMIT),
    impactedServices: serviceConnectionIds,
    impactStatus: "evidence_linked_only",
    promotionPath: "rhei_service_intelligence_for_goal",
    nextSlice: {
      backendRefs,
      uiRefs,
      testRefs,
      docsRefs,
      steps: [
        "Run rhei_service_intelligence_for_goal with the same service evidence.",
        "Choose the smallest backend, UI, test, or docs slice after service evidence is summarized.",
        "Return validation refs to rhei_code_goal before any memory, service, or graph promotion path."
      ],
      guardrails: [
        "No connector sync from service_impact.",
        "No service write from service_impact.",
        "No graph mutation from service_impact."
      ]
    },
    nextAction: {
      tool: "rhei_service_intelligence_for_goal",
      reason: "Service impact is evidence-linked only; use the service intelligence bridge for impacted service/resource mapping."
    },
    gates: {
      noConnectorSync: true,
      noServiceWrite: true,
      noGraphMutation: true,
      requiresGovernedServiceIntelligencePromotion: true
    },
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildGoalFeedbackLoopsV1(args) {
  const loops = [];
  if (args.mode === "edit") {
    loops.push({
      kind: "edit_loop",
      status: "transaction_receipts_ready",
      nextEvidenceLane: "rhei_code_goal mode=outcome_feedback or rhei_code_trail_export",
      summary: "Edit transaction linked context, reads, proposal, dry-run, diff, validation, AgentEditSession receipt, and Trail evidence without apply authority."
    });
  }
  if (args.mode === "verify") {
    loops.push({
      kind: "verify_loop",
      status: "search_read_absence_receipts_ready",
      nextEvidenceLane: "rhei_code_goal mode=edit or rhei_code_goal mode=report",
      summary: "Verify transaction linked scoped search, exact reads, searched scopes/counts/confidence, caveats, absence proof, and Trail evidence without source writes."
    });
  }
  if (args.mode === "trail") {
    loops.push({
      kind: "trail_loop",
      status: "session_history_receipts_ready",
      nextEvidenceLane: "rhei_code_goal mode=outcome_feedback or rhei_code_goal mode=report",
      summary: "Trail transaction linked session reads, proposals, dry-runs, diffs, reverse diffs, validations, human decisions, replay refs, and CodeTrail export evidence without apply authority."
    });
  }
  if (args.mode === "learn_from_outcome") {
    loops.push({
      kind: "learn_from_outcome_loop",
      status: "replay_evidence_ready",
      nextEvidenceLane: "rhei_code_goal mode=preference_replay or governed memory promotion",
      summary: "Accepted/rejected outcomes and human rewrites are captured as replay evidence and memory candidates only; memory promotion remains explicitly gated."
    });
  }
  if (args.mode === "report") {
    loops.push({
      kind: "report_loop",
      status: "markdown_diff_receipt_ready",
      nextEvidenceLane: "rhei_code_goal mode=intelligence_commit",
      summary: "Markdown report output includes a diff preview and receipt; report writes are explicit and grant no product or apply authority."
    });
  }
  if (args.mode === "diagnose") {
    loops.push({
      kind: "diagnostic_loop",
      status: "closed_when_validation_evidence_returns",
      nextEvidenceLane: "evidenceIntake",
      summary: "Feed validation/CI/PR review output back into rhei_code_goal mode=diagnose or rhei_code_context_for_goal evidenceIntake."
    });
  }
  if (args.mode === "outcome_feedback") {
    loops.push({
      kind: "outcome_feedback_loop",
      status: "captured_report_only",
      nextEvidenceLane: "rhei_code_review mode=generate_memory_candidates or governed memory promotion",
      summary: "Human rewrite/style/outcome feedback is represented as memory candidates without writing memory."
    });
  }
  if (args.mode === "steer") {
    loops.push({
      kind: "steering_loop",
      status: "goal_boundary_decided",
      summary: "New instructions branch or replace unless append is explicit or similarity is high."
    });
  }
  if (args.mode === "resume") {
    loops.push({ kind: "resume_loop", status: "continuity_captured_report_only", summary: "Resume metadata links the active goal to evidence without hidden execution." });
  }
  if (args.mode === "intelligence_commit") {
    loops.push({ kind: "intelligence_commit_loop", status: "commit_evidence_captured_report_only", summary: "Commit, validation, PR, and Code Trail refs are linked as evidence only." });
  }
  if (args.mode === "preference_replay") {
    loops.push({ kind: "preference_replay_loop", status: "replay_captured_report_only", summary: "Preference signals can be evaluated without writing memory." });
  }
  if (args.mode === "diagnostic_closure") {
    loops.push({ kind: "diagnostic_closure_loop", status: "closure_captured_report_only", summary: "Diagnostics, fixes, validation, and outcomes are linked without authority escalation." });
  }
  if (args.mode === "service_impact") {
    loops.push({ kind: "service_impact_loop", status: "service_impact_captured_report_only", summary: "Service impact evidence is linked without connector writes or graph mutation." });
  }
  if (args.mode === "start") {
    loops.push({
      kind: "goal_start_loop",
      status: "lifecycle_start_captured_report_only",
      nextEvidenceLane: "rhei_code_goal mode=checkpoint",
      summary: "Goal lifecycle start links bounded context and ContextPacket evidence without creating task authority."
    });
  }
  if (args.mode === "checkpoint") {
    loops.push({
      kind: "goal_checkpoint_loop",
      status: "lifecycle_checkpoint_captured_report_only",
      nextEvidenceLane: "rhei_code_goal mode=finish or validation evidence",
      summary: "Goal lifecycle checkpoint captures edit, validation, PR, service, and CodeTrail refs as interim report-only evidence."
    });
  }
  if (args.mode === "finish") {
    loops.push({
      kind: "goal_finish_loop",
      status: "lifecycle_finish_captured_report_only",
      nextEvidenceLane: "explicit CodeTrail import or governed memory promotion path",
      summary: "Goal lifecycle finish emits final report-only evidence and soft observations without writing truth or memory."
    });
  }
  if (args.mode === "context") {
    loops.push({
      kind: "context_loop",
      status: "bounded_context_ready",
      summary: "Use the compact context handoff, then return diagnostics or outcomes to this central goal surface."
    });
  }
  return loops;
}
function collectGoalEvidenceRefsV1(args, extra) {
  const goalSession = asRecord(args["goalSession"]);
  const records = [
    args,
    goalSession,
    asRecord(args["outcomeFeedback"]),
    asRecord(args["steering"]),
    asRecord(args["resume"]),
    asRecord(args["intelligenceCommit"]),
    asRecord(args["preferenceReplay"]),
    asRecord(args["diagnosticClosure"]),
    asRecord(args["serviceImpact"]),
    extra
  ].filter((record) => Boolean(record));
  const fields = [
    "exactRefs",
    "evidenceRefs",
    "acceptedRefs",
    "rejectedRefs",
    "missingRefs",
    "primaryRefs",
    "diagnosticRefs",
    "fixRefs",
    "validationRefs",
    "commitRefs",
    "contextRunIds",
    "codeMarketSnapshotIds",
    "codeTrailRefs",
    "prReviewRefs",
    "outcomeFeedbackRefs",
    "serviceConnectionRefs",
    "impactedRefs",
    "impactRefs"
  ];
  return uniqueStrings2(records.flatMap((record) => fields.flatMap((field) => stringList2(record[field]))));
}
function collectAcceptedRefsV1(args, input) {
  return uniqueStrings2([
    ...stringList2(args["acceptedRefs"]),
    ...stringList2(input?.["acceptedRefs"])
  ]);
}
function collectRejectedRefsV1(args, input) {
  return uniqueStrings2([
    ...stringList2(args["rejectedRefs"]),
    ...stringList2(input?.["rejectedRefs"])
  ]);
}
function collectMissingRefsV1(args, input) {
  return uniqueStrings2([
    ...stringList2(args["missingRefs"]),
    ...stringList2(input?.["missingRefs"])
  ]);
}
function serviceConnectionIdsFromEvidence(value) {
  return arrayValue(value).flatMap((item) => {
    const record = asRecord(item);
    if (!record)
      return [];
    const source = asRecord(record["source"]);
    const target = asRecord(record["target"]);
    const sourceId = cleanString2(source?.["id"]);
    const targetId = cleanString2(target?.["id"]);
    return uniqueStrings2([
      cleanString2(record["id"]),
      cleanString2(record["serviceConnectionId"]),
      cleanString2(record["dedupeKey"]),
      sourceId && targetId ? `${sourceId}->${targetId}` : undefined
    ]);
  });
}
function inferCorrectionKind(feedback) {
  if (cleanString2(feedback["after"]) || cleanString2(feedback["rewrite"]) || cleanString2(feedback["humanRewrite"]) || cleanString2(feedback["corrected"])) {
    return "human_rewrite";
  }
  if (cleanString2(feedback["stylePreference"]) || cleanString2(feedback["preference"]))
    return "style_preference";
  if (cleanString2(feedback["outcome"]) || cleanString2(feedback["status"]))
    return "outcome";
  return "correction";
}
function buildPreferenceSignals(args) {
  const signals = [];
  if (args.outcome) {
    signals.push({
      kind: "outcome",
      value: args.outcome,
      summary: "Outcome feedback captured for later proposal ranking."
    });
  }
  if (args.after) {
    signals.push({
      kind: "human_rewrite",
      correctionKind: args.correctionKind,
      beforePresent: Boolean(args.before),
      afterPresent: true,
      summary: "Human rewrite captured as a style/preference signal, not as automatic memory."
    });
  }
  if (args.stylePreference) {
    signals.push({
      kind: "style_preference",
      summary: args.stylePreference
    });
  }
  if (args.rationale) {
    signals.push({
      kind: "rationale",
      summary: args.rationale
    });
  }
  if (args.evidenceRefs.length > 0) {
    signals.push({
      kind: "evidence_link",
      refs: args.evidenceRefs.slice(0, COMPACT_REF_LIMIT),
      refsOmitted: omittedAfterLimit(args.evidenceRefs.length, COMPACT_REF_LIMIT)
    });
  }
  return signals;
}
function buildOutcomeMemoryCandidates(args) {
  const candidates = [];
  if (args.after || args.stylePreference) {
    const candidateKind = args.stylePreference ? "style_preference" : "code_rewrite_preference";
    const title = args.stylePreference ? "Human style preference" : "Human rewrite preference";
    const summary = args.stylePreference ?? "Human supplied a corrected rewrite; promote only through the governed memory path if this pattern repeats.";
    const identity = buildGoalMemoryCandidateIdentityV1({
      sourceKind: "outcome_feedback",
      candidateKind,
      title,
      summary,
      normalizedRule: summary,
      goal: args.goal,
      goalSessionId: args.goalSessionId,
      activeGoalId: args.activeGoalId,
      parentGoalId: args.parentGoalId,
      supersedesGoalId: args.supersedesGoalId,
      sourceIds: goalMemoryCandidateSourceIdsV1([args.outcomeFeedbackRefs, args.evidenceRefs]),
      targetRefs: args.targetRefs,
      filePaths: args.filePaths,
      evidenceRefs: args.evidenceRefs,
      taskRefs: args.taskRefs,
      serviceConnectionIds: args.serviceConnectionIds
    });
    const status = args.evidenceRefs.length > 0 ? "ready_for_review" : "candidate";
    candidates.push(removeUndefined({
      kind: "memory_candidate",
      candidateKind,
      title,
      summary,
      normalizedRule: summary,
      goal: args.goal,
      correctionKind: args.correctionKind,
      evidenceRefs: args.evidenceRefs.slice(0, COMPACT_REF_LIMIT),
      serviceConnectionIds: args.serviceConnectionIds.slice(0, COMPACT_REF_LIMIT),
      ...identity,
      sourceKind: "outcome_feedback",
      sourceIds: goalMemoryCandidateSourceIdsV1([args.outcomeFeedbackRefs, args.evidenceRefs]),
      goalSessionId: args.goalSessionId,
      activeGoalId: args.activeGoalId,
      parentGoalId: args.parentGoalId,
      supersedesGoalId: args.supersedesGoalId,
      targetRefs: args.targetRefs.slice(0, COMPACT_REF_LIMIT),
      filePaths: args.filePaths.slice(0, COMPACT_REF_LIMIT),
      taskRefs: args.taskRefs.slice(0, COMPACT_REF_LIMIT),
      outcomeFeedbackRefs: args.outcomeFeedbackRefs.slice(0, COMPACT_REF_LIMIT),
      confidence: status === "ready_for_review" ? 0.8 : 0.55,
      rank: status === "ready_for_review" ? 80 : 55,
      status,
      promotionStatus: status,
      promotionBlockers: status === "ready_for_review" ? [] : ["promotion:requires_evidence_refs"],
      reasonCodes: uniqueStrings2([
        `goal_memory:${candidateKind}`,
        "goal_memory:human_feedback",
        status === "ready_for_review" ? "goal_memory:evidence_linked" : "goal_memory:candidate_only"
      ]),
      candidateOnly: true,
      rankingUseOnly: true,
      requiresUserConfirmation: true,
      requiresRepeatedEvidence: status !== "ready_for_review",
      requiresOmPolicyCheck: true,
      memoryWrite: false,
      truthWrite: false,
      noMemoryWrite: true,
      promotionRequired: true,
      writeAuthority: false,
      promotion: {
        candidateOnly: true,
        rankingUseOnly: true,
        status,
        eligibleForPromotionReview: status === "ready_for_review",
        requiresUserConfirmation: true,
        requiresRepeatedEvidence: status !== "ready_for_review",
        requiresOmPolicyCheck: true,
        promotionRequired: true,
        writeAuthority: false,
        memoryWrite: false,
        truthWrite: false,
        noMemoryWrite: true,
        blockedReasons: status === "ready_for_review" ? [] : ["promotion:requires_evidence_refs"]
      },
      ...buildGoalIntelligenceGuardrailsV1()
    }));
  }
  if (args.outcome || args.rationale) {
    const title = "Outcome feedback pattern";
    const summary = args.rationale ?? `Outcome recorded: ${args.outcome}.`;
    const status = "needs_more_evidence";
    const identity = buildGoalMemoryCandidateIdentityV1({
      sourceKind: "outcome_feedback",
      candidateKind: "outcome_pattern",
      title,
      summary,
      normalizedRule: summary,
      goal: args.goal,
      goalSessionId: args.goalSessionId,
      activeGoalId: args.activeGoalId,
      parentGoalId: args.parentGoalId,
      supersedesGoalId: args.supersedesGoalId,
      sourceIds: goalMemoryCandidateSourceIdsV1([args.outcomeFeedbackRefs, args.acceptedRefs, args.evidenceRefs]),
      targetRefs: args.targetRefs,
      filePaths: args.filePaths,
      evidenceRefs: args.evidenceRefs,
      taskRefs: args.taskRefs,
      serviceConnectionIds: args.serviceConnectionIds
    });
    candidates.push(removeUndefined({
      kind: "memory_candidate",
      candidateKind: "outcome_pattern",
      title,
      summary,
      normalizedRule: summary,
      goal: args.goal,
      evidenceRefs: args.evidenceRefs.slice(0, COMPACT_REF_LIMIT),
      serviceConnectionIds: args.serviceConnectionIds.slice(0, COMPACT_REF_LIMIT),
      ...identity,
      sourceKind: "outcome_feedback",
      sourceIds: goalMemoryCandidateSourceIdsV1([args.outcomeFeedbackRefs, args.acceptedRefs, args.evidenceRefs]),
      goalSessionId: args.goalSessionId,
      activeGoalId: args.activeGoalId,
      parentGoalId: args.parentGoalId,
      supersedesGoalId: args.supersedesGoalId,
      targetRefs: args.targetRefs.slice(0, COMPACT_REF_LIMIT),
      filePaths: args.filePaths.slice(0, COMPACT_REF_LIMIT),
      taskRefs: args.taskRefs.slice(0, COMPACT_REF_LIMIT),
      outcomeFeedbackRefs: args.outcomeFeedbackRefs.slice(0, COMPACT_REF_LIMIT),
      confidence: CLOSED_OUTCOMES.has(args.outcome ?? "") || args.acceptedRefs.length > 0 ? 0.55 : 0.35,
      rank: CLOSED_OUTCOMES.has(args.outcome ?? "") || args.acceptedRefs.length > 0 ? 55 : 35,
      status,
      promotionStatus: status,
      promotionBlockers: ["promotion:outcome_feedback_requires_repeated_evidence"],
      reasonCodes: uniqueStrings2([
        "goal_memory:outcome_pattern",
        "goal_memory:needs_more_evidence",
        args.acceptedRefs.length > 0 ? "goal_memory:accepted_refs_linked" : undefined
      ]),
      candidateOnly: true,
      rankingUseOnly: true,
      requiresUserConfirmation: true,
      requiresRepeatedEvidence: true,
      requiresOmPolicyCheck: true,
      memoryWrite: false,
      truthWrite: false,
      noMemoryWrite: true,
      promotionRequired: true,
      writeAuthority: false,
      promotion: {
        candidateOnly: true,
        rankingUseOnly: true,
        status,
        eligibleForPromotionReview: false,
        requiresUserConfirmation: true,
        requiresRepeatedEvidence: true,
        requiresOmPolicyCheck: true,
        promotionRequired: true,
        writeAuthority: false,
        memoryWrite: false,
        truthWrite: false,
        noMemoryWrite: true,
        blockedReasons: ["promotion:outcome_feedback_requires_repeated_evidence"]
      },
      ...buildGoalIntelligenceGuardrailsV1()
    }));
  }
  return candidates;
}
function steeringDecision(args) {
  if (!args.incomingGoal)
    return "ask_for_goal_boundary";
  if (!args.activeGoal)
    return "start_goal";
  if (args.replaceActiveGoal)
    return "replace_active_goal";
  if (args.forceNewGoal)
    return "branch_goal";
  if (args.allowAppend)
    return "continue_active_goal";
  if ((args.similarity ?? 0) >= 0.62)
    return "continue_active_goal";
  if ((args.similarity ?? 0) <= 0.28)
    return "branch_goal";
  return "ask_for_goal_boundary";
}
function steeringReasonCodes(args) {
  const reasons = ["steering:latest_explicit_goal_wins"];
  if (!args.incomingGoal)
    reasons.push("steering:missing_incoming_goal");
  if (!args.activeGoal)
    reasons.push("steering:no_active_goal");
  if (args.allowAppend)
    reasons.push("steering:append_explicitly_allowed");
  if (!args.allowAppend)
    reasons.push("steering:append_requires_explicit_intent");
  if (args.forceNewGoal)
    reasons.push("steering:force_new_goal");
  if (args.replaceActiveGoal)
    reasons.push("steering:replace_active_goal_requested");
  if (typeof args.similarity === "number") {
    if (args.similarity <= 0.28)
      reasons.push("steering:low_goal_similarity");
    else if (args.similarity >= 0.62)
      reasons.push("steering:high_goal_similarity");
    else
      reasons.push("steering:ambiguous_goal_similarity");
  }
  reasons.push(`steering:decision:${args.decision}`);
  return uniqueStrings2(reasons);
}
function steeringNextStep(decision) {
  if (decision === "continue_active_goal")
    return "Continue only because the goal is similar or append was explicit.";
  if (decision === "replace_active_goal")
    return "Start a new active goal that supersedes the prior goal.";
  if (decision === "branch_goal")
    return "Create a visible child/branch goal instead of appending silently to the active goal.";
  if (decision === "start_goal")
    return "Start a new goal session.";
  return "Ask the operator whether this instruction continues, replaces, or branches from the active goal.";
}
function normalizedGoalSession(goalSession, goal, extra) {
  const base = goalSession ?? buildGoalSessionV1({ args: {}, goal });
  const goalSessionId = cleanString2(extra["goalSessionId"]) ?? base.goalSessionId ?? `goal-session:${goalStableHash({ goal, activeGoal: base.activeGoal, incomingGoal: base.incomingGoal, parentGoalId: base.parentGoalId })}`;
  return removeUndefined({
    schemaVersion: 1,
    kind: "goal_session",
    goalSessionId,
    activeGoalId: cleanString2(extra["activeGoalId"]) ?? base.activeGoalId,
    incomingGoalId: cleanString2(extra["incomingGoalId"]) ?? base.incomingGoalId,
    parentGoalId: cleanString2(extra["parentGoalId"]) ?? base.parentGoalId,
    supersedesGoalId: cleanString2(extra["supersedesGoalId"]) ?? base.supersedesGoalId,
    activeGoal: cleanString2(extra["activeGoal"]) ?? base.activeGoal,
    incomingGoal: cleanString2(extra["incomingGoal"]) ?? base.incomingGoal ?? goal,
    contextRunIds: uniqueStrings2([...base.contextRunIds, ...stringList2(extra["contextRunIds"])]),
    codeMarketSnapshotIds: uniqueStrings2([...base.codeMarketSnapshotIds, ...stringList2(extra["codeMarketSnapshotIds"])]),
    codeWorkroomSessionId: cleanString2(extra["codeWorkroomSessionId"]) ?? base.codeWorkroomSessionId,
    codeTrailRefs: uniqueStrings2([...base.codeTrailRefs, ...stringList2(extra["codeTrailRefs"])]),
    prReviewRefs: uniqueStrings2([...base.prReviewRefs, ...stringList2(extra["prReviewRefs"])]),
    commitRefs: uniqueStrings2([...base.commitRefs, ...stringList2(extra["commitRefs"])]),
    validationRefs: uniqueStrings2([...base.validationRefs, ...stringList2(extra["validationRefs"])]),
    outcomeFeedbackRefs: uniqueStrings2([...base.outcomeFeedbackRefs, ...stringList2(extra["outcomeFeedbackRefs"])]),
    serviceConnectionIds: uniqueStrings2([...base.serviceConnectionIds, ...stringList2(extra["serviceConnectionIds"])]),
    staleRefs: uniqueStrings2([...base.staleRefs, ...stringList2(extra["staleRefs"])]),
    openQuestions: uniqueStrings2([...base.openQuestions, ...stringList2(extra["openQuestions"])]),
    completedSteps: uniqueStrings2([...base.completedSteps, ...stringList2(extra["completedSteps"])]),
    remainingSteps: uniqueStrings2([...base.remainingSteps, ...stringList2(extra["remainingSteps"])]),
    boundaryPolicy: "new_goal_requires_explicit_steer_decision",
    refsOnly: true,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function goalStableHash(value) {
  let text;
  try {
    text = JSON.stringify(value, Object.keys(asRecord(value) ?? {}).sort());
  } catch {
    text = String(value);
  }
  let hash = 2166136261;
  for (let index = 0;index < text.length; index += 1) {
    hash ^= text.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0").slice(0, 8);
}
function goalSimilarity(left, right) {
  const leftTokens = goalTokens(left);
  const rightTokens = goalTokens(right);
  if (leftTokens.size === 0 || rightTokens.size === 0)
    return 0;
  let intersection = 0;
  for (const token of leftTokens) {
    if (rightTokens.has(token))
      intersection += 1;
  }
  const union = new Set([...leftTokens, ...rightTokens]).size;
  return Math.round(intersection / union * 100) / 100;
}
function goalTokens(value) {
  const stopWords = new Set(["a", "an", "and", "are", "as", "be", "by", "for", "in", "is", "it", "of", "on", "or", "the", "this", "to", "with"]);
  return new Set(value.toLowerCase().split(/[^a-z0-9_]+/g).map((token) => token.trim()).filter((token) => token.length > 2 && !stopWords.has(token)));
}
function booleanValue(value) {
  return typeof value === "boolean" ? value : undefined;
}
function stringList2(value) {
  return stringArray(value) ?? [];
}
function stringArray(value) {
  if (!Array.isArray(value))
    return;
  const output = value.map((item) => cleanString2(item)).filter((item) => Boolean(item));
  return output.length > 0 ? output : undefined;
}
function uniqueStrings2(values) {
  return Array.from(new Set(values.map((value) => value?.trim()).filter((value) => Boolean(value))));
}
function cleanString2(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function asRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
}
function arrayValue(value) {
  return Array.isArray(value) ? value : [];
}
function omittedAfterLimit(total, limit) {
  const omitted = Math.max(0, total - limit);
  return omitted > 0 ? omitted : undefined;
}
function removeUndefined(value) {
  return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
}
// ../core/src/goalLifecycle/types.ts
var GOAL_LIFECYCLE_SCHEMA_VERSION = 1;
// ../core/src/goalLifecycle/progressSignals.ts
function detectSearchLoopV1(args) {
  const byQuery = new Map;
  for (const item of args.searchQueries) {
    const query = normalizeQuery(item.query);
    if (!query)
      continue;
    byQuery.set(query, [...byQuery.get(query) ?? [], { query, at: item.at }]);
  }
  for (const [query, occurrences] of byQuery) {
    if (occurrences.length < 3)
      continue;
    const sorted = occurrences.sort((left, right) => left.at - right.at);
    const first = sorted[0]?.at ?? 0;
    const last = sorted[sorted.length - 1]?.at ?? first;
    const changedBetween = args.changeTimestamps.some((at) => at > first && at < last);
    if (changedBetween)
      continue;
    return signal("search_loop", "warning", {
      repeatedQuery: query,
      repeatCount: occurrences.length
    }, "consider_escalation");
  }
  return null;
}
function detectNoProgressCheckpointsV1(args) {
  const span = consecutiveNoGrowthSpan(args.checkpoints, (checkpoint) => [
    ...setKey(checkpoint.changedFiles),
    ...setKey(checkpoint.validationRefs).map((ref) => `validation:${ref}`)
  ]);
  if (span < 2)
    return null;
  return signal("no_progress_checkpoints", span >= 3 ? "warning" : "info", { checkpointSpan: span }, span >= 3 ? "consider_escalation" : "continue");
}
function detectValidationStuckV1(args) {
  let span = 1;
  let repeated = [];
  for (let index = 1;index < args.checkpoints.length; index += 1) {
    const previous = new Set(args.checkpoints[index - 1]?.failingValidationRefs ?? []);
    const current = setKey(args.checkpoints[index]?.failingValidationRefs ?? []);
    const overlap = current.filter((ref) => previous.has(ref));
    if (overlap.length > 0) {
      span += 1;
      repeated = overlap;
    } else {
      span = 1;
      repeated = [];
    }
  }
  if (span < 2 || repeated.length === 0)
    return null;
  return signal("validation_stuck", "warning", {
    checkpointSpan: span,
    failingValidationRefs: repeated
  }, "consider_escalation");
}
function buildGoalProgressObservationsV1(inputs) {
  const checkpoints = (inputs.checkpoints ?? []).map((checkpoint) => ({
    changedFiles: checkpoint.changedFiles ?? [],
    validationRefs: checkpoint.validationRefs ?? [],
    failingValidationRefs: checkpoint.failingValidationRefs ?? []
  }));
  const signals = [
    inputs.searchQueries ? detectSearchLoopV1({ searchQueries: inputs.searchQueries, changeTimestamps: inputs.changeTimestamps ?? [] }) : null,
    checkpoints.length > 0 ? detectNoProgressCheckpointsV1({ checkpoints }) : null,
    checkpoints.length > 0 ? detectValidationStuckV1({ checkpoints }) : null
  ].filter((item) => Boolean(item));
  return signals.map((progressSignal, index) => ({
    kind: "goal_lifecycle_observation",
    observationKind: "progress_observation",
    observationId: `goal-progress:${progressSignal.signal}:${index}`,
    title: progressSignal.signal.replace(/_/g, " "),
    summary: progressSignal.recommendation === "consider_escalation" ? "Progress signal suggests considering escalation." : "Progress signal suggests continuing with the current approach.",
    targetRefs: [],
    filePaths: [],
    evidenceRefs: progressSignal.evidence.failingValidationRefs ?? [],
    serviceConnectionIds: [],
    confidence: progressSignal.severity === "warning" ? 0.8 : 0.55,
    rank: progressSignal.severity === "warning" ? 70 : 45,
    reasonCodes: [`goal_progress:${progressSignal.signal}`, "goal_progress:advisory_only"],
    progressSignal,
    promotion: {
      candidateOnly: true,
      rankingUseOnly: true,
      eligibleForPromotionReview: false,
      requiresUserConfirmation: true,
      requiresRepeatedEvidence: true,
      requiresOmPolicyCheck: true,
      writeAuthority: false,
      memoryWrite: false,
      truthWrite: false,
      blockedReasons: ["progress_signal:no_authority"]
    },
    noAuthority: true
  }));
}
function signal(signalName, severity, evidence, recommendation) {
  return {
    kind: "goal_progress_signal",
    schemaVersion: GOAL_LIFECYCLE_SCHEMA_VERSION,
    signal: signalName,
    severity,
    evidence,
    recommendation,
    noAuthority: true
  };
}
function normalizeQuery(query) {
  return query.trim().toLowerCase().replace(/\s+/g, " ");
}
function setKey(values) {
  return [...new Set(values.map((value) => value.trim()).filter(Boolean))].sort();
}
function consecutiveNoGrowthSpan(items, keyFor) {
  let span = 1;
  for (let index = 1;index < items.length; index += 1) {
    const previous = new Set(keyFor(items[index - 1]));
    const current = keyFor(items[index]);
    const grew = current.some((value) => !previous.has(value));
    span = grew ? 1 : span + 1;
  }
  return span;
}

// ../core/src/goalLifecycle/builders.ts
var COMPACT_REF_LIMIT2 = 12;
var MAX_OBSERVATIONS = 12;
var MAX_MEMORY_CANDIDATES = 12;
var MAX_FILE_OBSERVATION_CANDIDATES = 50;
var UNSAFE_KEY_PATTERN = /(^|_|\b)(rawtranscript|transcript|messages|rawoutput|commandoutput|stdout|stderr|secret|apikey|api_key|token|memorycontent|providercall)(\b|_|$)/i;
function buildGoalLifecycleV1({
  args,
  stage = lifecycleStageFromArgs(args),
  goal,
  goalSession,
  contextPacket,
  serviceConnectionIds = collectGoalServiceConnectionIdsV1(args),
  generatedAt,
  maxObservations = MAX_OBSERVATIONS,
  progressInputs
}) {
  const normalizedSession = goalSession ?? buildGoalSessionV1({ args, goal });
  const stageArgs = lifecycleStageArgs(args, stage);
  const contextSummary = contextPacket ? summarizeContextPacket(contextPacket) : undefined;
  const evidence = collectLifecycleEvidence({
    args,
    stage,
    stageArgs,
    goalSession: normalizedSession,
    contextPacketSummary: contextSummary,
    serviceConnectionIds
  });
  const codeTrailUse = buildGoalLifecycleCodeTrailUseV1(evidence);
  const status = evaluateEvidenceStatus({ stage, contextSummary, evidence, codeTrailUse });
  const finalClaimPolicy = buildFinalClaimPolicy(status, evidence);
  const evidenceStatusDetail = buildEvidenceStatusDetail({ status, evidence, contextSummary, finalClaimPolicy });
  const taskLinks = buildTaskLinks(evidence, normalizedSession);
  const observations = buildGoalLifecycleObservationsV1({
    goal,
    status,
    evidence,
    contextSummary,
    codeTrailUse,
    maxObservations,
    progressInputs
  });
  const rankingHints = buildObservationRankingHintsV1(observations.visible);
  const feedbackLoops = buildLifecycleFeedbackLoops(stage);
  const lifecycleId = `goal-lifecycle:${stableHash2({
    stage,
    goal,
    goalSessionId: normalizedSession.goalSessionId,
    contextPacketId: contextSummary?.packetId,
    changedFiles: evidence.changedFiles,
    validationRefs: evidence.validationRefs,
    diffRefs: evidence.diffRefs,
    codeTrailRefs: evidence.codeTrailRefs,
    status
  })}`;
  const memoryCandidates = buildGoalLifecycleMemoryCandidatesV1({
    lifecycleId,
    stage,
    goal,
    goalSession: normalizedSession,
    status,
    observations: observations.visible,
    taskLinks,
    evidence
  });
  return removeUndefined2({
    kind: "rhei_code_goal_lifecycle",
    schemaVersion: 1,
    lifecycleId,
    stage,
    phase: stage,
    status: lifecycleStatusForStage(stage, status),
    goal,
    goalSession: normalizedSession,
    goalSessionId: normalizedSession.goalSessionId,
    activeGoalId: normalizedSession.activeGoalId,
    parentGoalId: normalizedSession.parentGoalId,
    supersedesGoalId: normalizedSession.supersedesGoalId,
    repoPath: cleanString3(args["repoPath"]),
    projectId: cleanString3(args["projectId"]),
    repoId: cleanString3(args["repoId"]),
    evidenceStatus: status,
    evidenceStatusDetail,
    evidenceStatusReasonCodes: evidenceStatusReasonCodes(status, evidence, contextSummary, codeTrailUse),
    taskLinks,
    contextPacket: contextSummary,
    codeTrailUse,
    finalClaimPolicy,
    observations: observations.visible,
    observationsOmitted: omittedAfterLimit2(observations.total, maxObservations),
    memoryCandidates: memoryCandidates.slice(0, MAX_MEMORY_CANDIDATES),
    memoryCandidatesOmitted: omittedAfterLimit2(memoryCandidates.length, MAX_MEMORY_CANDIDATES),
    rankingHints: rankingHints.slice(0, COMPACT_REF_LIMIT2),
    rankingHintsOmitted: omittedAfterLimit2(rankingHints.length, COMPACT_REF_LIMIT2),
    nextAction: nextActionForStatus(stage, status),
    feedbackLoops,
    generatedAt,
    ...buildGoalIntelligenceGuardrailsV1()
  });
}
function buildGoalStartLifecycleV1(args) {
  return buildGoalLifecycleV1({ ...args, stage: "start" });
}
function buildGoalCheckpointLifecycleV1(args) {
  return buildGoalLifecycleV1({ ...args, stage: "checkpoint" });
}
function buildGoalFinishLifecycleV1(args) {
  return buildGoalLifecycleV1({ ...args, stage: "finish" });
}
function buildGoalLifecycleCodeTrailUseV1(evidence) {
  if (evidence.hasUnsafePayload) {
    return {
      status: "blocked_unsafe_payload",
      codeTrailRefs: [],
      codeChangeStoryRefs: [],
      blockers: ["goal_lifecycle:blocked_unsafe_payload"],
      noAuthority: true
    };
  }
  if (evidence.codeTrailImportRefs.length > 0 || evidence.codeTrailRefs.length > 0) {
    return removeUndefined2({
      status: evidence.stageArgs["durableImportExplicit"] === true ? "imported_by_explicit_durable_path" : "linked_existing_import",
      importId: evidence.codeTrailImportRefs[0],
      codeTrailImportId: evidence.codeTrailImportRefs[0],
      trailHash: cleanString3(evidence.stageArgs["trailHash"]),
      sourceMcpRequestId: cleanString3(evidence.stageArgs["sourceMcpRequestId"]),
      sourceMcpRunId: cleanString3(evidence.stageArgs["sourceMcpRunId"]),
      codeTrailRefs: evidence.codeTrailRefs,
      codeChangeStoryRefs: evidence.codeChangeStoryRefs,
      blockers: [],
      noAuthority: true
    });
  }
  if (evidence.stage === "finish" && (evidence.diffRefs.length > 0 || evidence.changedFiles.length > 0) && (evidence.validationRefs.length > 0 || evidence.hasValidationResult || evidence.hasExecutionReceipt)) {
    const candidateRef = `code-trail-import-candidate:${stableHash2({
      changedFiles: evidence.changedFiles,
      validationRefs: evidence.validationRefs,
      diffRefs: evidence.diffRefs,
      receiptRefs: evidence.receiptRefs
    })}`;
    return {
      status: "import_candidate_emitted",
      codeTrailRefs: [],
      codeChangeStoryRefs: [],
      importCandidateRef: candidateRef,
      importCandidateSummary: {
        entryCount: Math.max(1, evidence.changedFiles.length + evidence.validationRefs.length),
        linkCount: evidence.evidenceRefs.length,
        gapCount: evidence.missingProofRefs.length,
        truncationCount: evidence.truncatedRefs.length,
        safeForImport: true
      },
      blockers: [],
      noAuthority: true
    };
  }
  return {
    status: "unavailable",
    codeTrailRefs: [],
    codeChangeStoryRefs: [],
    blockers: evidence.stage === "finish" ? ["goal_lifecycle:missing_code_trail_use"] : [],
    noAuthority: true
  };
}
function collectLifecycleEvidence(args) {
  const agentEditSession = asRecord2(args.stageArgs["agentEditSession"]) ?? asRecord2(args.args["agentEditSession"]) ?? asRecord2(args.args["agentEditSessionOutput"]);
  const validationResult = asRecord2(args.stageArgs["validationResult"]) ?? asRecord2(args.args["validationResult"]);
  const executionReceipt = asRecord2(args.stageArgs["executionReceipt"]) ?? asRecord2(args.args["executionReceipt"]);
  const changedFiles = uniqueStrings3([
    ...stringList3(args.args["changedFiles"]),
    ...stringList3(args.stageArgs["changedFiles"]),
    ...stringList3(agentEditSession?.["changedFiles"]),
    ...stringList3(agentEditSession?.["primaryEditFiles"])
  ]);
  const finalDiffRef = cleanString3(args.stageArgs["finalDiffRef"]) ?? cleanString3(args.args["finalDiffRef"]) ?? cleanString3(agentEditSession?.["finalDiffRef"]);
  const reverseDiffRef = cleanString3(args.stageArgs["reverseDiffRef"]) ?? cleanString3(args.args["reverseDiffRef"]) ?? cleanString3(agentEditSession?.["reverseDiffRef"]);
  const diffRefs = uniqueStrings3([
    ...stringList3(args.args["diffRefs"]),
    ...stringList3(args.stageArgs["diffRefs"]),
    ...stringList3(agentEditSession?.["diffRefs"]),
    finalDiffRef,
    reverseDiffRef
  ]);
  const validationRefs = uniqueStrings3([
    ...args.goalSession.validationRefs,
    ...stringList3(args.args["validationRefs"]),
    ...stringList3(args.stageArgs["validationRefs"]),
    ...stringList3(agentEditSession?.["validationRefs"]),
    cleanString3(validationResult?.["ref"]),
    cleanString3(validationResult?.["receiptRef"])
  ]);
  const codeTrailImportRefs = uniqueStrings3([
    cleanString3(args.args["codeTrailImportRef"]),
    cleanString3(args.stageArgs["codeTrailImportRef"]),
    cleanString3(agentEditSession?.["codeTrailImportRef"])
  ]);
  const codeTrailRefs = uniqueStrings3([
    ...args.goalSession.codeTrailRefs,
    ...stringList3(args.args["codeTrailRefs"]),
    ...stringList3(args.stageArgs["codeTrailRefs"]),
    ...stringList3(agentEditSession?.["codeTrailRefs"]),
    ...codeTrailImportRefs
  ]);
  const prReviewRefs = uniqueStrings3([
    ...args.goalSession.prReviewRefs,
    ...stringList3(args.args["prReviewRefs"]),
    ...stringList3(args.stageArgs["prReviewRefs"]),
    cleanString3(args.stageArgs["prSnapshotId"]),
    cleanString3(args.stageArgs["reviewRoomId"])
  ]);
  const receiptRefs = uniqueStrings3([
    ...stringList3(args.args["receiptRefs"]),
    ...stringList3(args.stageArgs["receiptRefs"]),
    cleanString3(executionReceipt?.["receiptId"]),
    cleanString3(executionReceipt?.["executionReceiptId"])
  ]);
  const staleRefs = uniqueStrings3([
    ...args.goalSession.staleRefs,
    ...stringList3(args.args["staleRefs"]),
    ...stringList3(args.stageArgs["staleRefs"])
  ]);
  const truncatedRefs = uniqueStrings3([
    ...stringList3(args.args["truncatedRefs"]),
    ...stringList3(args.stageArgs["truncatedRefs"]),
    ...stringList3(args.stageArgs["truncation"]),
    args.contextPacketSummary?.truncated ? args.contextPacketSummary.packetId : undefined
  ]);
  const fallbackStatus = fallbackStatusValue(cleanString3(args.stageArgs["fallbackStatus"]) ?? cleanString3(args.args["fallbackStatus"]));
  const evidenceRefs = uniqueStrings3([
    ...collectGoalEvidenceRefsV1(args.args, args.stageArgs),
    ...validationRefs,
    ...diffRefs,
    ...receiptRefs,
    ...codeTrailRefs,
    ...prReviewRefs,
    ...changedFiles
  ]);
  return {
    stage: args.stage,
    stageArgs: args.stageArgs,
    goalSession: args.goalSession,
    changedFiles,
    validationRefs,
    diffRefs,
    codeTrailRefs,
    codeTrailImportRefs,
    codeChangeStoryRefs: uniqueStrings3([
      ...stringList3(args.args["codeChangeStoryRefs"]),
      ...stringList3(args.stageArgs["codeChangeStoryRefs"])
    ]),
    prReviewRefs,
    receiptRefs,
    serviceConnectionIds: uniqueStrings3([
      ...args.serviceConnectionIds,
      ...args.goalSession.serviceConnectionIds,
      ...stringList3(args.stageArgs["serviceConnectionIds"])
    ]),
    staleRefs,
    truncatedRefs,
    missingProofRefs: uniqueStrings3([
      ...stringList3(args.args["missingProofRefs"]),
      ...stringList3(args.stageArgs["missingProofRefs"])
    ]),
    fallbackRefs: uniqueStrings3([
      ...stringList3(args.args["fallbackRefs"]),
      ...stringList3(args.stageArgs["fallbackRefs"])
    ]),
    fallbackStatus,
    hasValidationResult: Boolean(validationResult),
    hasExecutionReceipt: Boolean(executionReceipt),
    hasNoChangeProof: args.stageArgs["noChangeProof"] === true || args.args["noChangeProof"] === true,
    hasActiveEditSession: Boolean(agentEditSession && !["done", "completed", "failed", "blocked"].includes(cleanString3(agentEditSession["status"]) ?? "")),
    hasUnsafePayload: hasUnsafeLifecyclePayload(args.stageArgs) || hasUnsafeLifecyclePayload(args.args),
    evidenceRefs
  };
}
function evaluateEvidenceStatus(args) {
  if (args.evidence.hasUnsafePayload)
    return "blocked_unsafe_payload";
  if (args.stage === "start") {
    if ((args.contextSummary?.contentSliceCount ?? 0) > 0)
      return "context_ready";
    return "planning_only";
  }
  if (args.stage === "finish") {
    const hasValidation = args.evidence.validationRefs.length > 0 || args.evidence.hasValidationResult || args.evidence.hasExecutionReceipt;
    const hasChangeProof = args.evidence.changedFiles.length === 0 ? args.evidence.hasNoChangeProof || args.evidence.diffRefs.length > 0 : args.evidence.diffRefs.length > 0;
    const hasTrailUse = args.codeTrailUse.status === "linked_existing_import" || args.codeTrailUse.status === "import_candidate_emitted" || args.codeTrailUse.status === "imported_by_explicit_durable_path";
    if (!hasValidation || !hasChangeProof || !hasTrailUse || args.evidence.missingProofRefs.length > 0)
      return "blocked_missing_proof";
    if (args.evidence.staleRefs.length > 0 || args.evidence.truncatedRefs.length > 0)
      return "blocked_stale_or_truncated";
    return "finish_ready_report_only";
  }
  if (args.evidence.staleRefs.length > 0 || args.evidence.truncatedRefs.length > 0)
    return "blocked_stale_or_truncated";
  if (args.stage === "checkpoint") {
    if (args.evidence.validationRefs.length > 0 || args.evidence.hasValidationResult)
      return "validation_linked";
    if (args.evidence.hasActiveEditSession)
      return "work_in_progress";
    if (args.evidence.changedFiles.length > 0 || args.evidence.diffRefs.length > 0 || args.evidence.prReviewRefs.length > 0)
      return "partial_evidence";
    return "blocked_missing_proof";
  }
  return args.evidence.validationRefs.length > 0 ? "validation_linked" : "partial_evidence";
}
function buildFinalClaimPolicy(status, evidence) {
  const blockers = uniqueStrings3([
    status.startsWith("blocked_") ? status : undefined,
    ...evidence.missingProofRefs.map((ref) => `missing:${ref}`),
    ...evidence.staleRefs.map((ref) => `stale:${ref}`),
    ...evidence.truncatedRefs.map((ref) => `truncated:${ref}`)
  ]);
  const absenceProof = asRecord2(evidence.stageArgs["absenceProof"]);
  const canClaimAbsence = status === "finish_ready_report_only" && absenceProof?.["complete"] === true && evidence.staleRefs.length === 0 && evidence.truncatedRefs.length === 0;
  return {
    canClaimDone: status === "finish_ready_report_only",
    canClaimAbsence,
    blockers,
    staleRefs: evidence.staleRefs,
    truncatedRefs: evidence.truncatedRefs,
    missingProofRefs: evidence.missingProofRefs
  };
}
function buildEvidenceStatusDetail(args) {
  const blocked = args.status.startsWith("blocked_");
  const finalClaimsAllowed = args.finalClaimPolicy.canClaimDone;
  const validationRefs = args.evidence.validationRefs.slice(0, COMPACT_REF_LIMIT2);
  return {
    kind: "goal_lifecycle_evidence_status",
    schemaVersion: 1,
    status: blocked ? "blocked" : args.status === "planning_only" || args.status === "partial_evidence" ? "degraded" : "ready",
    runtimeFreshness: {
      status: args.evidence.staleRefs.length > 0 ? "stale" : "unknown",
      reasonCodes: args.evidence.staleRefs.length > 0 ? ["goal_lifecycle:stale_ref"] : ["goal_lifecycle:runtime_freshness_not_claimed"]
    },
    coverage: {
      status: args.contextSummary?.truncated || args.evidence.truncatedRefs.length > 0 ? "truncated" : args.status === "planning_only" || args.status === "partial_evidence" ? "partial" : "complete",
      selectedFileCount: args.contextSummary?.primaryEditFiles.length ?? args.evidence.changedFiles.length,
      omittedRangeCount: args.contextSummary?.truncated ? 1 : 0,
      truncated: Boolean(args.contextSummary?.truncated || args.evidence.truncatedRefs.length > 0),
      reasonCodes: evidenceCoverageReasonCodes(args.status, args.contextSummary, args.evidence)
    },
    proof: {
      status: blocked ? "blocked" : finalClaimsAllowed ? "proved" : args.evidence.validationRefs.length > 0 ? "evidence_only" : "not_proved",
      validationRefs,
      absenceClaimsAllowed: args.finalClaimPolicy.canClaimAbsence,
      finalClaimsAllowed,
      reasonCodes: evidenceProofReasonCodes(args.status, finalClaimsAllowed)
    },
    fallback: {
      status: args.evidence.fallbackStatus,
      fallbackRefs: args.evidence.fallbackRefs.slice(0, COMPACT_REF_LIMIT2),
      reasonCodes: args.evidence.fallbackRefs.length > 0 ? ["goal_lifecycle:fallback_refs_linked"] : ["goal_lifecycle:fallback_not_needed"]
    },
    agentTrust: {
      level: finalClaimsAllowed ? "bounded" : "advisory",
      basisRefs: uniqueStrings3([...args.evidence.validationRefs, ...args.evidence.codeTrailRefs, ...args.evidence.receiptRefs]).slice(0, COMPACT_REF_LIMIT2),
      reasonCodes: ["goal_lifecycle:report_only_no_authority"]
    },
    noAuthority: true
  };
}
function buildTaskLinks(evidence, goalSession) {
  const links = [];
  if (goalSession.goalSessionId) {
    links.push(taskLink("goal_session", goalSession.goalSessionId, "source", undefined, [], evidence.evidenceRefs));
  }
  for (const ref of evidence.validationRefs)
    links.push(taskLink("validation_receipt", ref, "validation", undefined, [], [ref]));
  for (const ref of evidence.prReviewRefs)
    links.push(taskLink(ref.includes("review-room") ? "review_room" : "pr_snapshot", ref, "review", undefined, [], [ref]));
  for (const ref of evidence.serviceConnectionIds)
    links.push(taskLink("service_connection", ref, "service", undefined, [], [ref]));
  const editSessionId = cleanString3(evidence.stageArgs["editSessionId"]) ?? cleanString3(evidence.stageArgs["agentEditSessionId"]) ?? cleanString3(asRecord2(evidence.stageArgs["agentEditSession"])?.["editSessionId"]) ?? cleanString3(asRecord2(evidence.stageArgs["agentEditSession"])?.["id"]);
  if (editSessionId) {
    links.push(taskLink("agent_edit_session", editSessionId, "work", cleanString3(asRecord2(evidence.stageArgs["agentEditSession"])?.["status"]), evidence.changedFiles, evidence.evidenceRefs));
  }
  const workroomRunId = cleanString3(evidence.stageArgs["workroomRunId"]);
  if (workroomRunId)
    links.push(taskLink("code_workroom_run", workroomRunId, "work", undefined, evidence.changedFiles, evidence.evidenceRefs));
  const patchRunId = cleanString3(evidence.stageArgs["patchRunId"]);
  if (patchRunId)
    links.push(taskLink("code_patch_run", patchRunId, "work", undefined, evidence.changedFiles, evidence.evidenceRefs));
  return uniqueTaskLinks(links);
}
function buildGoalLifecycleObservationsV1(args) {
  const candidates = [];
  const evidenceRefs = uniqueStrings3([
    ...args.evidence.evidenceRefs,
    ...args.codeTrailUse.codeTrailRefs,
    args.codeTrailUse.importCandidateRef
  ]);
  if ((args.evidence.changedFiles.length > 0 || evidenceRefs.length > 0) && args.evidence.stage !== "start") {
    candidates.push(observation({
      observationKind: "worktask_observation",
      title: `Goal ${args.evidence.stage} evidence`,
      summary: cleanString3(args.evidence.stageArgs["summary"]) ?? "Goal lifecycle evidence was captured as report-only task context.",
      targetRefs: evidenceRefs,
      filePaths: args.evidence.changedFiles,
      evidenceRefs,
      serviceConnectionIds: args.evidence.serviceConnectionIds,
      rank: observationRank(args.evidence, args.contextSummary, args.codeTrailUse),
      status: args.status,
      reasonCodes: [`goal_lifecycle:${args.evidence.stage}`, "goal_lifecycle:ranking_hint_only"]
    }));
  }
  const filePaths = uniqueStrings3([
    ...args.evidence.changedFiles,
    ...args.contextSummary?.primaryEditFiles ?? []
  ]).slice(0, MAX_FILE_OBSERVATION_CANDIDATES);
  for (const filePath of filePaths) {
    candidates.push(observation({
      observationKind: "file_observation",
      title: `File evidence: ${filePath}`,
      summary: "File participated in the goal lifecycle evidence set; use as a ranking hint only.",
      targetRefs: [filePath],
      filePaths: [filePath],
      evidenceRefs,
      serviceConnectionIds: args.evidence.serviceConnectionIds,
      rank: observationRank(args.evidence, args.contextSummary, args.codeTrailUse) + (args.contextSummary?.primaryEditFiles.includes(filePath) ? 10 : 0),
      status: args.status,
      reasonCodes: ["goal_lifecycle:file_observation", "goal_lifecycle:ranking_hint_only"]
    }));
  }
  if (args.evidence.validationRefs.length > 0 || args.evidence.hasValidationResult) {
    candidates.push(observation({
      observationKind: "validation_observation",
      title: "Validation evidence linked",
      summary: "Validation was linked to the lifecycle as evidence only.",
      targetRefs: args.evidence.validationRefs,
      filePaths: args.evidence.changedFiles,
      evidenceRefs,
      serviceConnectionIds: args.evidence.serviceConnectionIds,
      rank: observationRank(args.evidence, args.contextSummary, args.codeTrailUse) + 30,
      status: args.status,
      reasonCodes: ["goal_lifecycle:validation_observation", "goal_lifecycle:ranking_hint_only"]
    }));
  }
  if (args.status.startsWith("blocked_")) {
    candidates.push(observation({
      observationKind: "risk_observation",
      title: "Lifecycle proof blocked",
      summary: `Lifecycle evidence cannot support final claims: ${args.status}.`,
      targetRefs: uniqueStrings3([...args.evidence.staleRefs, ...args.evidence.truncatedRefs, ...args.evidence.missingProofRefs]),
      filePaths: args.evidence.changedFiles,
      evidenceRefs,
      serviceConnectionIds: args.evidence.serviceConnectionIds,
      rank: 20,
      status: args.status,
      reasonCodes: [`goal_lifecycle:${args.status}`, "goal_lifecycle:risk_observation"]
    }));
  }
  if (args.progressInputs) {
    candidates.push(...buildGoalProgressObservationsV1(args.progressInputs));
  }
  const sorted = candidates.sort((left, right) => right.rank - left.rank || left.observationId.localeCompare(right.observationId));
  return { visible: sorted.slice(0, args.maxObservations), total: sorted.length };
}
function buildGoalLifecycleMemoryCandidatesV1(args) {
  if (args.stage === "start")
    return [];
  const taskRefs = uniqueStrings3(args.taskLinks.map((link) => link.ref)).slice(0, COMPACT_REF_LIMIT2);
  return args.observations.filter((item) => item.observationKind === "file_observation" || item.observationKind === "worktask_observation" || item.observationKind === "validation_observation" || item.observationKind === "risk_observation").map((observation) => {
    const candidateKind = lifecycleMemoryCandidateKind(observation);
    const status = lifecycleMemoryCandidateStatus(args.stage, args.status, observation);
    const blockedReasons = observation.promotion.blockedReasons;
    const identity = buildGoalMemoryCandidateIdentityV1({
      sourceKind: "goal_lifecycle",
      candidateKind,
      title: observation.title,
      summary: observation.summary,
      normalizedRule: observation.summary,
      goal: args.goal,
      goalSessionId: args.goalSession.goalSessionId,
      activeGoalId: args.goalSession.activeGoalId,
      parentGoalId: args.goalSession.parentGoalId,
      supersedesGoalId: args.goalSession.supersedesGoalId,
      sourceEventId: observation.observationId,
      sourceIds: goalMemoryCandidateSourceIdsV1([[args.lifecycleId, observation.observationId], observation.evidenceRefs]),
      targetRefs: observation.targetRefs,
      filePaths: observation.filePaths,
      evidenceRefs: observation.evidenceRefs,
      observationRefs: [observation.observationId],
      taskRefs,
      serviceConnectionIds: observation.serviceConnectionIds
    });
    return removeUndefined2({
      kind: "memory_candidate",
      candidateKind,
      title: observation.title,
      summary: observation.summary,
      normalizedRule: observation.summary,
      goal: args.goal,
      evidenceRefs: observation.evidenceRefs.slice(0, COMPACT_REF_LIMIT2),
      serviceConnectionIds: observation.serviceConnectionIds.slice(0, COMPACT_REF_LIMIT2),
      ...identity,
      sourceKind: "goal_lifecycle",
      sourceIds: goalMemoryCandidateSourceIdsV1([[args.lifecycleId, observation.observationId], observation.evidenceRefs]),
      goalSessionId: args.goalSession.goalSessionId,
      activeGoalId: args.goalSession.activeGoalId,
      parentGoalId: args.goalSession.parentGoalId,
      supersedesGoalId: args.goalSession.supersedesGoalId,
      targetRefs: observation.targetRefs.slice(0, COMPACT_REF_LIMIT2),
      filePaths: observation.filePaths.slice(0, COMPACT_REF_LIMIT2),
      observationRefs: [observation.observationId],
      taskRefs,
      codeTrailRefs: args.evidence.codeTrailRefs.slice(0, COMPACT_REF_LIMIT2),
      prReviewRefs: args.evidence.prReviewRefs.slice(0, COMPACT_REF_LIMIT2),
      confidence: observation.confidence,
      rank: observation.rank,
      status,
      promotionStatus: status,
      promotionBlockers: blockedReasons,
      reasonCodes: uniqueStrings3([
        ...observation.reasonCodes,
        `goal_memory:${candidateKind}`,
        `goal_memory:status:${status}`
      ]),
      candidateOnly: true,
      rankingUseOnly: observation.promotion.rankingUseOnly,
      requiresUserConfirmation: true,
      requiresRepeatedEvidence: observation.promotion.requiresRepeatedEvidence || status !== "ready_for_review",
      requiresOmPolicyCheck: true,
      memoryWrite: false,
      truthWrite: false,
      noMemoryWrite: true,
      promotionRequired: true,
      writeAuthority: false,
      promotion: {
        candidateOnly: true,
        rankingUseOnly: observation.promotion.rankingUseOnly,
        status,
        eligibleForPromotionReview: observation.promotion.eligibleForPromotionReview,
        requiresUserConfirmation: true,
        requiresRepeatedEvidence: observation.promotion.requiresRepeatedEvidence || status !== "ready_for_review",
        requiresOmPolicyCheck: true,
        promotionRequired: true,
        writeAuthority: false,
        memoryWrite: false,
        truthWrite: false,
        noMemoryWrite: true,
        blockedReasons
      },
      ...buildGoalIntelligenceGuardrailsV1()
    });
  }).sort((left, right) => (right.rank ?? 0) - (left.rank ?? 0) || (left.candidateId ?? "").localeCompare(right.candidateId ?? ""));
}
function lifecycleMemoryCandidateKind(observation) {
  if (observation.observationKind === "file_observation")
    return "lifecycle_file_pattern";
  if (observation.observationKind === "worktask_observation")
    return "lifecycle_worktask_pattern";
  if (observation.observationKind === "validation_observation")
    return "validation_practice";
  if (observation.observationKind === "risk_observation")
    return "risk_pattern";
  return "lifecycle_worktask_pattern";
}
function lifecycleMemoryCandidateStatus(stage, status, observation) {
  if (status.startsWith("blocked_") || !observation.promotion.eligibleForPromotionReview)
    return "needs_more_evidence";
  if (stage === "finish" && (status === "finish_ready_report_only" || status === "validation_linked"))
    return "ready_for_review";
  return "candidate";
}
function buildObservationRankingHintsV1(observations) {
  return observations.flatMap((item) => item.targetRefs.map((targetRef) => ({
    kind: "goal_lifecycle_ranking_hint",
    targetRef,
    weight: item.rank,
    reasonCodes: item.reasonCodes,
    sourceObservationId: item.observationId,
    noAuthority: true
  })));
}
function observation(args) {
  const blockedReasons = promotionBlockedReasons(args.status, args.evidenceRefs, args.summary);
  const eligibleForPromotionReview = blockedReasons.length === 0;
  const boundedRank = Math.max(0, Math.min(100, Math.round(args.rank)));
  return {
    kind: "goal_lifecycle_observation",
    observationKind: args.observationKind,
    observationId: `goal-observation:${stableHash2({
      kind: args.observationKind,
      targetRefs: args.targetRefs,
      evidenceRefs: args.evidenceRefs,
      summary: args.summary
    })}`,
    title: args.title.slice(0, 120),
    summary: args.summary.slice(0, 360),
    targetRefs: uniqueStrings3(args.targetRefs).slice(0, COMPACT_REF_LIMIT2),
    filePaths: uniqueStrings3(args.filePaths).slice(0, COMPACT_REF_LIMIT2),
    evidenceRefs: uniqueStrings3(args.evidenceRefs).slice(0, COMPACT_REF_LIMIT2),
    serviceConnectionIds: uniqueStrings3(args.serviceConnectionIds).slice(0, COMPACT_REF_LIMIT2),
    confidence: Math.max(0, Math.min(1, Number((boundedRank / 100).toFixed(2)))),
    rank: boundedRank,
    reasonCodes: uniqueStrings3(args.reasonCodes),
    promotion: {
      candidateOnly: true,
      rankingUseOnly: true,
      eligibleForPromotionReview,
      requiresUserConfirmation: true,
      requiresRepeatedEvidence: true,
      requiresOmPolicyCheck: true,
      writeAuthority: false,
      memoryWrite: false,
      truthWrite: false,
      blockedReasons
    },
    noAuthority: true
  };
}
function observationRank(evidence, contextSummary, codeTrailUse) {
  let score = 0;
  if (evidence.validationRefs.length > 0 || evidence.hasValidationResult)
    score += 30;
  if (codeTrailUse.status !== "unavailable")
    score += 25;
  if (evidence.diffRefs.length > 0)
    score += 20;
  if (evidence.prReviewRefs.length > 0)
    score += 15;
  if ((contextSummary?.primaryEditFiles.length ?? 0) > 0)
    score += 10;
  if (evidence.stageArgs["repoIntelligence"] || evidence.stageArgs["repoIntelligenceStatus"])
    score += 5;
  if (evidence.staleRefs.length > 0)
    score -= 30;
  if (evidence.truncatedRefs.length > 0)
    score -= 30;
  if (evidence.missingProofRefs.length > 0)
    score -= 40;
  if (evidence.hasUnsafePayload)
    score -= 20;
  return Math.max(0, Math.min(100, score));
}
function summarizeContextPacket(packet) {
  const record = packet;
  const slices = objectArray(record["contextSlices"]);
  const primaryEditFiles = objectArray(record["primaryEditFiles"]).map((item) => cleanString3(item["path"])).filter((path) => Boolean(path));
  const contentSliceCount = slices.filter((slice) => Boolean(asRecord2(slice["content"])?.["text"])).length;
  const contentBudget = asRecord2(record["contentBudget"]);
  return {
    packetId: cleanString3(record["packetId"]),
    primaryEditFiles: uniqueStrings3(primaryEditFiles),
    contextSliceCount: slices.length,
    contentSliceCount,
    truncated: Boolean(cleanString3(contentBudget?.["overflowReason"]) || slices.some((slice) => asRecord2(slice["content"])?.["truncated"] === true)),
    sourceRefs: stringList3(record["sourceRefs"]).slice(0, COMPACT_REF_LIMIT2),
    evidenceRefs: stringList3(record["evidenceRefs"]).slice(0, COMPACT_REF_LIMIT2),
    receiptRefs: stringList3(record["receiptRefs"]).slice(0, COMPACT_REF_LIMIT2),
    noAuthority: true
  };
}
function lifecycleStageFromArgs(args) {
  const lifecycle = asRecord2(args["goalLifecycle"]) ?? asRecord2(args["lifecycle"]);
  const explicit = cleanString3(lifecycle?.["stage"]) ?? cleanString3(lifecycle?.["phase"]);
  if (explicit === "start" || explicit === "steer" || explicit === "checkpoint" || explicit === "finish")
    return explicit;
  if (asRecord2(args["start"]))
    return "start";
  if (asRecord2(args["checkpoint"]))
    return "checkpoint";
  if (asRecord2(args["finish"]))
    return "finish";
  return "start";
}
function lifecycleStageArgs(args, stage) {
  const lifecycle = asRecord2(args["goalLifecycle"]) ?? asRecord2(args["lifecycle"]) ?? {};
  return {
    ...asRecord2(lifecycle[stage]),
    ...asRecord2(args[stage]),
    ...lifecycle
  };
}
function lifecycleStatusForStage(stage, status) {
  if (status.startsWith("blocked_"))
    return "blocked";
  if (stage === "start")
    return "started";
  if (stage === "checkpoint")
    return "checkpointed";
  if (stage === "finish")
    return "finished";
  return "continued";
}
function evidenceStatusReasonCodes(status, evidence, contextSummary, codeTrailUse) {
  return uniqueStrings3([
    `goal_lifecycle:${evidence.stage}`,
    `goal_lifecycle:${status}`,
    contextSummary?.contentSliceCount ? "goal_lifecycle:context_content_linked" : undefined,
    codeTrailUse.status !== "unavailable" ? `goal_lifecycle:code_trail:${codeTrailUse.status}` : undefined,
    evidence.validationRefs.length > 0 ? "goal_lifecycle:validation_refs_linked" : undefined,
    evidence.diffRefs.length > 0 ? "goal_lifecycle:diff_refs_linked" : undefined,
    evidence.staleRefs.length > 0 ? "goal_lifecycle:stale_ref" : undefined,
    evidence.truncatedRefs.length > 0 ? "goal_lifecycle:truncated_coverage" : undefined,
    evidence.hasUnsafePayload ? "goal_lifecycle:unsafe_payload_withheld" : undefined
  ]);
}
function evidenceCoverageReasonCodes(status, contextSummary, evidence) {
  return uniqueStrings3([
    contextSummary ? "goal_lifecycle:context_packet_summary" : undefined,
    contextSummary?.truncated || evidence.truncatedRefs.length > 0 ? "goal_lifecycle:coverage_truncated" : undefined,
    status === "planning_only" ? "goal_lifecycle:planner_only" : undefined,
    status === "context_ready" ? "goal_lifecycle:context_ready" : undefined
  ]);
}
function evidenceProofReasonCodes(status, finalClaimsAllowed) {
  return uniqueStrings3([
    finalClaimsAllowed ? "goal_lifecycle:finish_ready_report_only" : "goal_lifecycle:no_final_claim",
    status === "blocked_missing_proof" ? "goal_lifecycle:missing_proof" : undefined,
    status === "blocked_stale_or_truncated" ? "goal_lifecycle:stale_or_truncated_blocks_claims" : undefined,
    status === "blocked_unsafe_payload" ? "goal_lifecycle:unsafe_payload_blocks_claims" : undefined
  ]);
}
function promotionBlockedReasons(status, evidenceRefs, summary) {
  return uniqueStrings3([
    status !== "finish_ready_report_only" && status !== "validation_linked" ? "promotion:requires_finish_or_validation_linked_status" : undefined,
    evidenceRefs.length === 0 ? "promotion:requires_validation_or_code_trail_evidence" : undefined,
    status.startsWith("blocked_") ? "promotion:blocked_lifecycle_status" : undefined,
    summary.length > 360 ? "promotion:summary_too_long" : undefined
  ]);
}
function nextActionForStatus(stage, status) {
  if (status === "finish_ready_report_only") {
    return {
      tool: "rhei_code_trail_export",
      mode: "trail",
      reason: "Finish evidence is report-ready; import or export CodeTrail only through the explicit durable path.",
      noAuthority: true
    };
  }
  if (status.startsWith("blocked_")) {
    return {
      tool: "rhei_code_goal",
      mode: stage === "finish" ? "checkpoint" : "verify",
      reason: "Lifecycle evidence is blocked; add validation, freshness, diff, or proof refs before claiming completion.",
      noAuthority: true
    };
  }
  return {
    tool: "rhei_code_goal",
    mode: stage === "start" ? "checkpoint" : "finish",
    reason: "Continue the report-only lifecycle with bounded evidence refs.",
    noAuthority: true
  };
}
function buildLifecycleFeedbackLoops(stage) {
  if (stage === "steer")
    return buildGoalFeedbackLoopsV1({ mode: "steer" });
  return buildGoalFeedbackLoopsV1({ mode: stage });
}
function taskLink(kind, ref, role, status, filePaths, evidenceRefs) {
  return removeUndefined2({
    kind,
    ref,
    role,
    status,
    filePaths: uniqueStrings3(filePaths).slice(0, COMPACT_REF_LIMIT2),
    evidenceRefs: uniqueStrings3(evidenceRefs).slice(0, COMPACT_REF_LIMIT2),
    noAuthority: true
  });
}
function uniqueTaskLinks(links) {
  const seen = new Set;
  return links.filter((link) => {
    const key = `${link.kind}:${link.ref}:${link.role}`;
    if (seen.has(key))
      return false;
    seen.add(key);
    return true;
  });
}
function fallbackStatusValue(value) {
  if (value === "used" || value === "available" || value === "missing" || value === "blocked")
    return value;
  return "not_needed";
}
function hasUnsafeLifecyclePayload(value, depth = 0) {
  if (depth > 5)
    return false;
  const record = asRecord2(value);
  if (!record)
    return false;
  for (const [key, child] of Object.entries(record)) {
    if (UNSAFE_KEY_PATTERN.test(key) && child !== undefined && child !== null)
      return true;
    if (typeof child === "object" && hasUnsafeLifecyclePayload(child, depth + 1))
      return true;
  }
  return false;
}
function asRecord2(value) {
  if (!value || typeof value !== "object" || Array.isArray(value))
    return;
  return value;
}
function objectArray(value) {
  if (!Array.isArray(value))
    return [];
  return value.map((item) => asRecord2(item)).filter((item) => Boolean(item));
}
function stringList3(value) {
  if (!Array.isArray(value))
    return [];
  return value.map((item) => cleanString3(item)).filter((item) => Boolean(item));
}
function uniqueStrings3(values) {
  return Array.from(new Set(values.map((value) => value?.trim()).filter((value) => Boolean(value))));
}
function cleanString3(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function removeUndefined2(value) {
  return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
}
function omittedAfterLimit2(total, limit) {
  return total > limit ? total - limit : undefined;
}
function stableHash2(value) {
  const text = stableJson2(value);
  let hash = 2166136261;
  for (let index = 0;index < text.length; index += 1) {
    hash ^= text.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0").slice(0, 12);
}
function stableJson2(value) {
  if (Array.isArray(value))
    return `[${value.map(stableJson2).join(",")}]`;
  if (value && typeof value === "object") {
    return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson2(value[key])}`).join(",")}}`;
  }
  return JSON.stringify(value);
}
export {
  normalizeGoalMemoryTextV1,
  goalSessionHasContinuityV1,
  goalMemoryCandidateSourceIdsV1,
  detectValidationStuckV1,
  detectSearchLoopV1,
  detectNoProgressCheckpointsV1,
  collectGoalServiceConnectionIdsV1,
  collectGoalMemoryFilePathsV1,
  collectGoalEvidenceRefsV1,
  buildServiceImpactV1,
  buildPreferenceReplayV1,
  buildGoalStewardDecisionV1,
  buildGoalStartLifecycleV1,
  buildGoalSessionV1,
  buildGoalResumeV1,
  buildGoalProgressObservationsV1,
  buildGoalOutcomeFeedbackV1,
  buildGoalMemoryCandidateIdentityV1,
  buildGoalLifecycleV1,
  buildGoalLifecycleCodeTrailUseV1,
  buildGoalIntelligenceGuardrailsV1,
  buildGoalIntelligenceCommitV1,
  buildGoalFinishLifecycleV1,
  buildGoalFeedbackLoopsV1,
  buildGoalContinuityPacketV1,
  buildGoalCheckpointLifecycleV1,
  buildDiagnosticClosureV1,
  GOAL_STEWARD_DECISION_VALUES,
  GOAL_MEMORY_CANDIDATE_STATUS_VALUES,
  GOAL_MEMORY_CANDIDATE_SOURCE_KIND_VALUES,
  GOAL_MEMORY_CANDIDATE_KIND_VALUES,
  GOAL_LIFECYCLE_SCHEMA_VERSION,
  GOAL_INTELLIGENCE_SCHEMA_VERSION,
  GOAL_INTELLIGENCE_COMPACT_REF_LIMIT
};
