// Force strict mode and setup for ESM
"use strict";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/goals/goal-protocol.ts
init_esbuild_shims();
var GOAL_STATE_VERSION = 2;
var GOAL_PROPOSAL_REASON_MAX_CHARACTERS = 8e3;
var GOAL_PROPOSAL_REASON_MAX_BYTES = 16e3;
var PAUSED_GOAL_SYSTEM_REMINDER = "<system-reminder>\nThe Goal is paused. Do not continue its objective unless the user resumes it. Treat this message as ordinary conversation.\n</system-reminder>";
function goalRequiresExactPermit(snapshot) {
  return snapshot.goal !== null && (snapshot.goal.status === "active" || snapshot.activity === "running");
}
__name(goalRequiresExactPermit, "goalRequiresExactPermit");
function validateGoalProposalReason(reason) {
  if (!reason.trim()) return "Goal proposal reason must not be empty";
  if ([...reason].length > GOAL_PROPOSAL_REASON_MAX_CHARACTERS) {
    return `Goal proposal reason exceeds ${GOAL_PROPOSAL_REASON_MAX_CHARACTERS} characters`;
  }
  if (new TextEncoder().encode(reason).byteLength > GOAL_PROPOSAL_REASON_MAX_BYTES) {
    return `Goal proposal reason exceeds ${GOAL_PROPOSAL_REASON_MAX_BYTES} UTF-8 bytes`;
  }
  return null;
}
__name(validateGoalProposalReason, "validateGoalProposalReason");

// packages/core/src/goals/goal-evidence.ts
init_esbuild_shims();
var CATALOG_PREVIEW_LIMIT = 240;
var CATALOG_ENTRY_LIMIT = 100;
var CATALOG_BYTE_LIMIT = 24e3;
var CATALOG_LINEAGE_LIMIT = 16;
var GOAL_EVIDENCE_REFERENCE_LIMIT = CATALOG_ENTRY_LIMIT;
var VERIFIER_EVIDENCE_BYTE_LIMIT = 256e3;
var EvidenceSourceUnavailableError = class extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
    this.name = "EvidenceSourceUnavailableError";
  }
  static {
    __name(this, "EvidenceSourceUnavailableError");
  }
};
var InvalidGoalEvidenceReferenceError = class extends Error {
  constructor(code, message, reference) {
    super(message);
    this.code = code;
    this.reference = reference;
    this.name = "InvalidGoalEvidenceReferenceError";
  }
  static {
    __name(this, "InvalidGoalEvidenceReferenceError");
  }
};
function buildGoalEvidenceCatalog(input) {
  const analysis = analyzeEvidence(input);
  return {
    entries: analysis.catalog.map((entry) => ({ ...entry })),
    lineageTurnIds: analysis.lineageTurnIds.slice(-CATALOG_LINEAGE_LIMIT),
    truncated: analysis.catalogTruncated
  };
}
__name(buildGoalEvidenceCatalog, "buildGoalEvidenceCatalog");
function validateGoalEvidenceReferences(input) {
  const references = input.proposal.evidenceRefs;
  if (references.length === 0) {
    throw new InvalidGoalEvidenceReferenceError(
      "no_evidence_references",
      "A terminal Goal proposal must cite at least one evidence record."
    );
  }
  if (references.length > GOAL_EVIDENCE_REFERENCE_LIMIT) {
    throw new InvalidGoalEvidenceReferenceError(
      "too_many_evidence_references",
      `A terminal Goal proposal may cite at most ${GOAL_EVIDENCE_REFERENCE_LIMIT} evidence records.`
    );
  }
  if (new Set(references).size !== references.length) {
    throw new InvalidGoalEvidenceReferenceError(
      "duplicate_evidence_reference",
      "A terminal Goal proposal must not cite the same evidence record more than once."
    );
  }
  const analysis = analyzeEvidence(input);
  const citedRecords = references.map(
    (reference) => validateReference(reference, input, analysis)
  );
  if (input.proposal.status === "complete" && analysis.catalogTruncated) {
    throw new InvalidGoalEvidenceReferenceError(
      "catalog_truncated",
      "A complete Goal proposal requires an exhaustive bounded evidence catalog."
    );
  }
  const evidenceBytes = citedRecords.reduce(
    (total, record) => total + Buffer.byteLength(record.content, "utf8"),
    0
  );
  if (evidenceBytes > VERIFIER_EVIDENCE_BYTE_LIMIT) {
    throw new InvalidGoalEvidenceReferenceError(
      "evidence_payload_too_large",
      `Cited Goal evidence exceeds the ${VERIFIER_EVIDENCE_BYTE_LIMIT}-byte verifier limit.`
    );
  }
  validateBlockerCoverage(input.proposal, citedRecords, analysis);
  return {
    citedRecords: citedRecords.map((entry) => ({ ...entry }))
  };
}
__name(validateGoalEvidenceReferences, "validateGoalEvidenceReferences");
function analyzeEvidence(input) {
  if (input.permit.goalId !== input.goal.goalId || input.permit.revision !== input.goal.revision || !isNonEmptyString(input.permit.turnId)) {
    throw new EvidenceSourceUnavailableError(
      "permit_goal_mismatch",
      "The current Goal permit does not match the Goal evidence revision."
    );
  }
  const cursorId = input.goal.evidenceCursor.recordId;
  if (cursorId === null) {
    throw new EvidenceSourceUnavailableError(
      "cursor_unset",
      "The Goal evidence cursor is not available."
    );
  }
  const indexByUuid = /* @__PURE__ */ new Map();
  for (let index = 0; index < input.records.length; index += 1) {
    const uuid = input.records[index].uuid;
    if (indexByUuid.has(uuid)) {
      throw new EvidenceSourceUnavailableError(
        "duplicate_record_uuid",
        `The active transcript chain contains duplicate record UUID ${uuid}.`
      );
    }
    indexByUuid.set(uuid, index);
  }
  const cursorIndex = indexByUuid.get(cursorId);
  if (cursorIndex === void 0) {
    throw new EvidenceSourceUnavailableError(
      "cursor_not_found",
      `The Goal evidence cursor ${cursorId} is not in the active transcript chain.`
    );
  }
  const lineageTurnIds = collectLineageTurnIds(input, cursorIndex);
  if (lineageTurnIds.at(-1) !== input.permit.turnId) {
    throw new EvidenceSourceUnavailableError(
      "current_turn_not_tail",
      "The current Goal permit is not the tail of the active transcript lineage."
    );
  }
  const selectedEvidence = [];
  let catalogBytes = 0;
  let catalogTruncated = false;
  for (let index = input.records.length - 1; index > cursorIndex; index -= 1) {
    if (selectedEvidence.length >= CATALOG_ENTRY_LIMIT) {
      catalogTruncated = true;
      break;
    }
    const evidence = catalogEvidence(input.records[index], input);
    if (!evidence) continue;
    const entryBytes = Buffer.byteLength(JSON.stringify(evidence), "utf8");
    if (catalogBytes + entryBytes > CATALOG_BYTE_LIMIT) {
      catalogTruncated = true;
      break;
    }
    selectedEvidence.push(evidence);
    catalogBytes += entryBytes;
  }
  selectedEvidence.reverse();
  const eligibleByUuid = new Map(
    selectedEvidence.map((entry) => [entry.uuid, entry])
  );
  return {
    cursorIndex,
    catalog: selectedEvidence,
    eligibleByUuid,
    indexByUuid,
    lineageTurnIds,
    catalogTruncated
  };
}
__name(analyzeEvidence, "analyzeEvidence");
function collectLineageTurnIds(input, cursorIndex) {
  const lineageTurnIds = [];
  const seenTurnIds = /* @__PURE__ */ new Set();
  let currentTurnId;
  for (let index = cursorIndex + 1; index < input.records.length; index += 1) {
    const record = input.records[index];
    const context = parseGoalContext(record.goalContext);
    if (!context) {
      if (claimsGoalRevision(record.goalContext, input.goal)) {
        throw new EvidenceSourceUnavailableError(
          "malformed_turn_context",
          `Goal-owned transcript record ${record.uuid} has malformed turn context.`
        );
      }
      continue;
    }
    if (context.goalId !== input.goal.goalId || context.revision !== input.goal.revision) {
      continue;
    }
    if (context.turnId === currentTurnId) continue;
    if (seenTurnIds.has(context.turnId)) {
      throw new EvidenceSourceUnavailableError(
        "turn_reentry",
        `Goal turn ${context.turnId} re-enters the active transcript lineage.`
      );
    }
    seenTurnIds.add(context.turnId);
    lineageTurnIds.push(context.turnId);
    currentTurnId = context.turnId;
  }
  return lineageTurnIds;
}
__name(collectLineageTurnIds, "collectLineageTurnIds");
function validateReference(reference, input, analysis) {
  const recordIndex = analysis.indexByUuid.get(reference);
  if (recordIndex === void 0) {
    throw new InvalidGoalEvidenceReferenceError(
      "missing_reference",
      `Evidence reference ${reference} is not in the active transcript chain.`,
      reference
    );
  }
  if (recordIndex <= analysis.cursorIndex) {
    throw new InvalidGoalEvidenceReferenceError(
      "pre_cursor_reference",
      `Evidence reference ${reference} is not after the Goal evidence cursor.`,
      reference
    );
  }
  const record = input.records[recordIndex];
  if (!coherentEvidenceProvenance(record)) {
    throw new InvalidGoalEvidenceReferenceError(
      "ineligible_reference",
      `Transcript record ${reference} is not an eligible evidence source.`,
      reference
    );
  }
  const context = parseGoalContext(record.goalContext);
  if (!context) {
    throw new InvalidGoalEvidenceReferenceError(
      "missing_goal_context",
      `Evidence reference ${reference} has no valid Goal turn context.`,
      reference
    );
  }
  if (context.goalId !== input.goal.goalId) {
    throw new InvalidGoalEvidenceReferenceError(
      "wrong_goal_id",
      `Evidence reference ${reference} belongs to a different Goal.`,
      reference
    );
  }
  if (context.revision !== input.goal.revision) {
    throw new InvalidGoalEvidenceReferenceError(
      "wrong_revision",
      `Evidence reference ${reference} belongs to a different Goal revision.`,
      reference
    );
  }
  if (!analysis.lineageTurnIds.includes(context.turnId)) {
    throw new InvalidGoalEvidenceReferenceError(
      "wrong_turn_lineage",
      `Evidence reference ${reference} is not in the active Goal turn lineage.`,
      reference
    );
  }
  const catalogEntry = analysis.eligibleByUuid.get(reference);
  if (!catalogEntry) {
    throw new InvalidGoalEvidenceReferenceError(
      "reference_not_catalogued",
      `Evidence reference ${reference} is outside the bounded Goal evidence catalog.`,
      reference
    );
  }
  const content = evidenceContent(record, catalogEntry.provenance);
  if (!content) {
    throw new InvalidGoalEvidenceReferenceError(
      "ineligible_reference",
      `Transcript record ${reference} has no eligible evidence content.`,
      reference
    );
  }
  return { ...catalogEntry, content };
}
__name(validateReference, "validateReference");
function validateBlockerCoverage(proposal, citedRecords, analysis) {
  if (proposal.status !== "blocked") return;
  if (proposal.blockerKind === "authority" || proposal.blockerKind === "external") {
    if (!citedRecords.some(
      ({ provenance }) => provenance === "real_user" || provenance === "tool_result"
    )) {
      throw new InvalidGoalEvidenceReferenceError(
        "immediate_blocker_external_evidence_required",
        "An immediate blocker requires cited user input or external tool evidence."
      );
    }
    const citedIds = new Set(citedRecords.map(({ uuid }) => uuid));
    const oldestBlockerIndex = Math.min(
      ...citedRecords.filter(
        ({ provenance }) => provenance === "real_user" || provenance === "tool_result"
      ).map(
        ({ uuid }) => analysis.catalog.findIndex((entry) => entry.uuid === uuid)
      )
    );
    const uncitedNewerEvidence = analysis.catalog.slice(oldestBlockerIndex + 1).filter(({ uuid }) => !citedIds.has(uuid));
    if (uncitedNewerEvidence.length > 0) {
      throw new InvalidGoalEvidenceReferenceError(
        "immediate_blocker_newer_evidence_required",
        "An immediate blocker must cite every newer bounded evidence record so contradictory evidence cannot be omitted."
      );
    }
    return;
  }
  const requiredTurnIds = analysis.lineageTurnIds.slice(-3);
  const currentTurnId = requiredTurnIds.at(-1);
  const citedTurnIds = new Set(
    citedRecords.filter(
      (record) => record.provenance !== "assistant_output" || record.turnId === currentTurnId
    ).map(({ turnId }) => turnId)
  );
  if (requiredTurnIds.length !== 3 || !requiredTurnIds.every((turnId) => citedTurnIds.has(turnId))) {
    throw new InvalidGoalEvidenceReferenceError(
      "repeated_blocker_turn_coverage",
      "A repeated blocker requires evidence from the current and two immediately preceding Goal turns."
    );
  }
}
__name(validateBlockerCoverage, "validateBlockerCoverage");
function catalogEvidence(record, input) {
  const provenance = coherentEvidenceProvenance(record);
  if (!provenance) return void 0;
  const context = parseGoalContext(record.goalContext);
  if (!context || context.goalId !== input.goal.goalId || context.revision !== input.goal.revision) {
    return void 0;
  }
  const preview = evidencePreview(record, provenance);
  if (!preview) return void 0;
  return {
    uuid: record.uuid,
    provenance,
    turnId: context.turnId,
    preview,
    proofKind: proofKindOf(provenance)
  };
}
__name(catalogEvidence, "catalogEvidence");
function coherentEvidenceProvenance(record) {
  if (record.type === "system") return void 0;
  const provenance = record.provenance ?? legacySafeProvenance(record);
  if (provenance === "real_user") {
    return record.type === "user" && (record.subtype === void 0 || record.subtype === "mid_turn_user_message") ? provenance : void 0;
  }
  if (provenance === "assistant_output") {
    return record.type === "assistant" && record.subtype === void 0 ? provenance : void 0;
  }
  if (provenance === "tool_result") {
    return record.type === "tool_result" && record.subtype === void 0 ? provenance : void 0;
  }
  return void 0;
}
__name(coherentEvidenceProvenance, "coherentEvidenceProvenance");
function legacySafeProvenance(record) {
  if (record.type === "user" && (record.subtype === void 0 || record.subtype === "mid_turn_user_message")) {
    return "real_user";
  }
  if (record.type === "assistant" && record.subtype === void 0) {
    return "assistant_output";
  }
  if (record.type === "tool_result" && record.subtype === void 0) {
    return "tool_result";
  }
  return void 0;
}
__name(legacySafeProvenance, "legacySafeProvenance");
function evidenceContent(record, provenance) {
  const content = [];
  for (const part of record.message?.parts ?? []) {
    if (part.thought !== true && typeof part.text === "string") {
      content.push(part.text);
    }
    if (provenance === "tool_result" && part.functionResponse) {
      const rendered = renderToolResponse(part.functionResponse);
      if (rendered) content.push(rendered);
    }
  }
  return content.join("\n").trim();
}
__name(evidenceContent, "evidenceContent");
function evidencePreview(record, provenance) {
  let preview = "";
  const append = /* @__PURE__ */ __name((value) => {
    if (!value || preview.length >= CATALOG_PREVIEW_LIMIT) return;
    const separator = preview ? "\n" : "";
    const remaining = CATALOG_PREVIEW_LIMIT - preview.length;
    preview += `${separator}${value}`.slice(0, remaining);
  }, "append");
  for (const part of record.message?.parts ?? []) {
    if (part.thought !== true && typeof part.text === "string") {
      append(part.text);
    }
    if (provenance === "tool_result" && part.functionResponse) {
      append(renderToolResponsePreview(part.functionResponse));
    }
    if (preview.length >= CATALOG_PREVIEW_LIMIT) break;
  }
  return preview.trim();
}
__name(evidencePreview, "evidencePreview");
function renderToolResponse(functionResponse) {
  if (functionResponse.response === void 0) return "";
  try {
    return JSON.stringify({
      ...functionResponse.name === void 0 ? {} : { name: functionResponse.name },
      response: functionResponse.response
    });
  } catch {
    return "";
  }
}
__name(renderToolResponse, "renderToolResponse");
function renderToolResponsePreview(functionResponse) {
  if (functionResponse.response === void 0) return "";
  try {
    return JSON.stringify({
      ...functionResponse.name === void 0 ? {} : { name: functionResponse.name },
      response: summarizeJsonValue(
        functionResponse.response,
        0,
        /* @__PURE__ */ new WeakSet()
      )
    }).slice(0, CATALOG_PREVIEW_LIMIT);
  } catch {
    return "";
  }
}
__name(renderToolResponsePreview, "renderToolResponsePreview");
function summarizeJsonValue(value, depth, seen) {
  if (typeof value === "string") {
    return value.slice(0, CATALOG_PREVIEW_LIMIT);
  }
  if (value === null || typeof value === "number" || typeof value === "boolean") {
    return value;
  }
  if (typeof value !== "object") return String(value);
  if (seen.has(value)) return "[Circular]";
  if (depth >= 2) return "[Nested value]";
  seen.add(value);
  if (Array.isArray(value)) {
    return value.slice(0, 6).map((entry) => summarizeJsonValue(entry, depth + 1, seen));
  }
  return Object.fromEntries(
    Object.entries(value).slice(0, 6).map(([key, entry]) => [key, summarizeJsonValue(entry, depth + 1, seen)])
  );
}
__name(summarizeJsonValue, "summarizeJsonValue");
function proofKindOf(provenance) {
  if (provenance === "real_user") return "user_input";
  if (provenance === "assistant_output") return "delivered_output";
  return "external_fact";
}
__name(proofKindOf, "proofKindOf");
function parseGoalContext(value) {
  if (!isRecord(value)) return void 0;
  if (!hasOnlyKeys(value, ["goalId", "revision", "turnId"]) || !isNonEmptyString(value["goalId"]) || typeof value["revision"] !== "number" || !Number.isInteger(value["revision"]) || value["revision"] < 1 || !isNonEmptyString(value["turnId"])) {
    return void 0;
  }
  return {
    goalId: value["goalId"],
    revision: value["revision"],
    turnId: value["turnId"]
  };
}
__name(parseGoalContext, "parseGoalContext");
function claimsGoalRevision(value, goal) {
  if (!isRecord(value)) return false;
  return value["goalId"] === goal.goalId && value["revision"] === goal.revision;
}
__name(claimsGoalRevision, "claimsGoalRevision");
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isRecord, "isRecord");
function hasOnlyKeys(value, keys) {
  return Object.keys(value).every((key) => keys.includes(key));
}
__name(hasOnlyKeys, "hasOnlyKeys");
function isNonEmptyString(value) {
  return typeof value === "string" && value.trim().length > 0;
}
__name(isNonEmptyString, "isNonEmptyString");

// packages/core/src/goals/goal-runtime.ts
init_esbuild_shims();
import { randomUUID } from "node:crypto";

// packages/core/src/goals/goal-reducer.ts
init_esbuild_shims();
var MAX_BLOCKED_AUDIT_COUNT = 3;
var GoalConflictError = class extends Error {
  constructor(current) {
    super("Goal version does not match the current session Goal");
    this.current = current;
    this.name = "GoalConflictError";
  }
  static {
    __name(this, "GoalConflictError");
  }
};
var GoalInvalidTransitionError = class extends Error {
  constructor(message, current) {
    super(message);
    this.current = current;
    this.name = "GoalInvalidTransitionError";
  }
  static {
    __name(this, "GoalInvalidTransitionError");
  }
};
function elapsedActiveTime(goal, now) {
  return goal.activeTimeMs + (goal.status === "active" ? Math.max(0, now - goal.updatedAt) : 0);
}
__name(elapsedActiveTime, "elapsedActiveTime");
function reduceGoalControl(current, transition) {
  const { request } = transition;
  if (request.action === "create") {
    if (current) throw new GoalConflictError(snapshotOf(current));
    return createGoal(
      transition.nextGoalId,
      normalizeObjective(request.objective, snapshotOf(null)),
      transition.now,
      transition.cursor
    );
  }
  assertExpectedVersion(
    current,
    request.expectedGoalId,
    request.expectedRevision
  );
  if (request.action === "clear") return null;
  if (request.action === "replace") {
    return createGoal(
      transition.nextGoalId,
      normalizeObjective(request.objective, snapshotOf(current)),
      transition.now,
      transition.cursor
    );
  }
  if (request.action === "edit") {
    if (current.status === "complete") {
      throw new GoalInvalidTransitionError(
        "A completed Goal cannot be edited",
        snapshotOf(current)
      );
    }
    return transitionGoal(current, transition.now, {
      revision: current.revision + 1,
      objective: normalizeObjective(request.objective, snapshotOf(current)),
      evidenceCursor: copyCursor(transition.cursor)
    });
  }
  if (request.action === "pause") {
    if (current.status !== "active") {
      throw new GoalInvalidTransitionError(
        "Only an active Goal can be paused",
        snapshotOf(current)
      );
    }
    return transitionGoal(current, transition.now, { status: "paused" });
  }
  if (current.status === "complete") {
    throw new GoalInvalidTransitionError(
      "A completed Goal cannot be resumed",
      snapshotOf(current)
    );
  }
  if (current.status === "active") {
    throw new GoalInvalidTransitionError(
      "An active Goal cannot be resumed",
      snapshotOf(current)
    );
  }
  if (request.action !== "resume") {
    return assertNever(request, snapshotOf(current));
  }
  return transitionGoal(current, transition.now, { status: "active" });
}
__name(reduceGoalControl, "reduceGoalControl");
function reduceGoalTurnFinished(current, transition) {
  if (current.status !== "active" && current.status !== "paused") {
    throw new GoalInvalidTransitionError(
      "Only an active or paused Goal can finish a turn",
      snapshotOf(current)
    );
  }
  return transitionGoal(current, transition.now, {
    turnCount: current.turnCount + 1,
    ...transition.lastReason === void 0 ? {} : { lastReason: transition.lastReason }
  });
}
__name(reduceGoalTurnFinished, "reduceGoalTurnFinished");
function parseGoalStateRecordPayloadV2(value) {
  if (!isRecord2(value) || !hasOnlyKeys2(value, ["v", "cause", "snapshot", "blockedAudit"]) || value["v"] !== GOAL_STATE_VERSION || !isGoalStateCause(value["cause"]) || !isBlockedAudit(value["blockedAudit"])) {
    return void 0;
  }
  const parsedSnapshot = parseGoalSnapshotV2(value["snapshot"]);
  return parsedSnapshot?.activity === "idle" ? {
    v: GOAL_STATE_VERSION,
    cause: value["cause"],
    snapshot: parsedSnapshot,
    ...value["blockedAudit"] ? { blockedAudit: structuredClone(value["blockedAudit"]) } : {}
  } : void 0;
}
__name(parseGoalStateRecordPayloadV2, "parseGoalStateRecordPayloadV2");
function parseGoalSnapshotV2(value) {
  if (!isRecord2(value) || !hasOnlyKeys2(value, ["v", "goal", "activity"]) || value["v"] !== GOAL_STATE_VERSION || !isGoalActivity(value["activity"])) {
    return void 0;
  }
  if (value["goal"] === null) {
    return {
      v: GOAL_STATE_VERSION,
      goal: null,
      activity: value["activity"]
    };
  }
  const goal = parseGoalRecord(value["goal"]);
  return goal ? { v: GOAL_STATE_VERSION, goal, activity: value["activity"] } : void 0;
}
__name(parseGoalSnapshotV2, "parseGoalSnapshotV2");
function createGoal(goalId, objective, now, cursor) {
  return {
    goalId,
    revision: 1,
    objective,
    status: "active",
    evidenceCursor: copyCursor(cursor),
    turnCount: 0,
    activeTimeMs: 0,
    createdAt: now,
    updatedAt: now
  };
}
__name(createGoal, "createGoal");
function assertExpectedVersion(current, expectedGoalId, expectedRevision) {
  if (!current || current.goalId !== expectedGoalId || current.revision !== expectedRevision) {
    throw new GoalConflictError(snapshotOf(current));
  }
}
__name(assertExpectedVersion, "assertExpectedVersion");
function normalizeObjective(objective, current) {
  const normalized = objective.trim();
  if (!normalized) {
    throw new GoalInvalidTransitionError(
      "Goal objective must not be empty",
      current
    );
  }
  return normalized;
}
__name(normalizeObjective, "normalizeObjective");
function transitionGoal(goal, now, changes) {
  return {
    ...goal,
    ...changes,
    activeTimeMs: elapsedActiveTime(goal, now),
    updatedAt: now
  };
}
__name(transitionGoal, "transitionGoal");
function snapshotOf(goal) {
  return { v: GOAL_STATE_VERSION, goal, activity: "idle" };
}
__name(snapshotOf, "snapshotOf");
function copyCursor(cursor) {
  return { recordId: cursor.recordId };
}
__name(copyCursor, "copyCursor");
function parseGoalRecord(value) {
  if (!isRecord2(value) || !hasOnlyKeys2(value, [
    "goalId",
    "revision",
    "objective",
    "status",
    "evidenceCursor",
    "turnCount",
    "activeTimeMs",
    "createdAt",
    "updatedAt",
    "lastReason"
  ]) || typeof value["goalId"] !== "string" || !value["goalId"] || !isNonNegativeInteger(value["revision"]) || value["revision"] === 0 || typeof value["objective"] !== "string" || !value["objective"].trim() || !isGoalStatus(value["status"]) || !isTranscriptCursor(value["evidenceCursor"]) || !isNonNegativeInteger(value["turnCount"]) || !isNonNegativeNumber(value["activeTimeMs"]) || !isFiniteNumber(value["createdAt"]) || !isFiniteNumber(value["updatedAt"]) || value["lastReason"] !== void 0 && typeof value["lastReason"] !== "string") {
    return void 0;
  }
  return {
    goalId: value["goalId"],
    revision: value["revision"],
    objective: value["objective"],
    status: value["status"],
    evidenceCursor: copyCursor(value["evidenceCursor"]),
    turnCount: value["turnCount"],
    activeTimeMs: value["activeTimeMs"],
    createdAt: value["createdAt"],
    updatedAt: value["updatedAt"],
    ...value["lastReason"] === void 0 ? {} : { lastReason: value["lastReason"] }
  };
}
__name(parseGoalRecord, "parseGoalRecord");
function isTranscriptCursor(value) {
  return isRecord2(value) && hasOnlyKeys2(value, ["recordId"]) && (typeof value["recordId"] === "string" || value["recordId"] === null);
}
__name(isTranscriptCursor, "isTranscriptCursor");
function isGoalStatus(value) {
  return value === "active" || value === "paused" || value === "blocked" || value === "usage_limited" || value === "complete";
}
__name(isGoalStatus, "isGoalStatus");
function isGoalActivity(value) {
  return value === "idle" || value === "running" || value === "verifying";
}
__name(isGoalActivity, "isGoalActivity");
function isGoalStateCause(value) {
  return value === "create" || value === "replace" || value === "edit" || value === "pause" || value === "resume" || value === "turn_finished" || value === "verifier_accept" || value === "verifier_reject" || value === "complete" || value === "blocked" || value === "usage_limited" || value === "clear" || value === "migrated";
}
__name(isGoalStateCause, "isGoalStateCause");
function isBlockedAudit(value) {
  return value === void 0 || isRecord2(value) && hasOnlyKeys2(value, ["fingerprint", "count", "turnIds"]) && typeof value["fingerprint"] === "string" && value["fingerprint"].length > 0 && isNonNegativeInteger(value["count"]) && value["count"] > 0 && value["count"] <= MAX_BLOCKED_AUDIT_COUNT && Array.isArray(value["turnIds"]) && value["turnIds"].length === value["count"] && value["turnIds"].every(
    (turnId) => typeof turnId === "string" && turnId.length > 0
  );
}
__name(isBlockedAudit, "isBlockedAudit");
function isRecord2(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isRecord2, "isRecord");
function hasOnlyKeys2(value, keys) {
  return Object.keys(value).every((key) => keys.includes(key));
}
__name(hasOnlyKeys2, "hasOnlyKeys");
function isNonNegativeInteger(value) {
  return typeof value === "number" && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeInteger, "isNonNegativeInteger");
function isNonNegativeNumber(value) {
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
}
__name(isNonNegativeNumber, "isNonNegativeNumber");
function isFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value);
}
__name(isFiniteNumber, "isFiniteNumber");
function assertNever(value, snapshot) {
  throw new GoalInvalidTransitionError(
    `Unsupported Goal control action: ${String(value)}`,
    snapshot
  );
}
__name(assertNever, "assertNever");

// packages/core/src/goals/goal-persistence.ts
init_esbuild_shims();
var LEGACY_ACTIVE_KINDS = /* @__PURE__ */ new Set(["set", "checking"]);
var LEGACY_STOPPED_KINDS = /* @__PURE__ */ new Set([
  "achieved",
  "cleared",
  "failed",
  "aborted",
  "paused"
]);
function recoverGoalFromRecords(records) {
  let unsupported;
  for (let index = records.length - 1; index >= 0; index -= 1) {
    const record = records[index];
    if (record?.subtype !== "goal_state") continue;
    const payload = record.type === "system" ? parseGoalStateRecordPayloadV2(record.systemPayload) : void 0;
    if (payload) return { kind: "v2", payload };
    unsupported ??= {
      kind: "unsupported",
      reason: `Goal lifecycle record ${record.uuid} is malformed or uses an unsupported version`
    };
  }
  return unsupported ?? recoverLegacyGoal(records);
}
__name(recoverGoalFromRecords, "recoverGoalFromRecords");
function recoverLegacyGoal(records) {
  for (let recordIndex = records.length - 1; recordIndex >= 0; recordIndex -= 1) {
    const record = records[recordIndex];
    if (record?.type !== "system" || record.subtype !== "slash_command") {
      continue;
    }
    const payload = record.systemPayload;
    if (payload?.phase !== "result" || !Array.isArray(payload.outputHistoryItems)) {
      continue;
    }
    for (let itemIndex = payload.outputHistoryItems.length - 1; itemIndex >= 0; itemIndex -= 1) {
      const value = payload.outputHistoryItems[itemIndex];
      if (!isObjectRecord(value) || value["type"] !== "goal_status") continue;
      const kind = value["kind"];
      const condition = value["condition"];
      if (typeof kind !== "string" || typeof condition !== "string") {
        return unsupportedLegacy(record.uuid);
      }
      if (LEGACY_STOPPED_KINDS.has(kind)) return { kind: "none" };
      if (!LEGACY_ACTIVE_KINDS.has(kind) || condition.trim().length === 0) {
        return unsupportedLegacy(record.uuid);
      }
      return { kind: "legacy", objective: condition.trim() };
    }
  }
  return { kind: "none" };
}
__name(recoverLegacyGoal, "recoverLegacyGoal");
function unsupportedLegacy(recordUuid) {
  return {
    kind: "unsupported",
    reason: `Legacy Goal record ${recordUuid} cannot be recovered safely`
  };
}
__name(unsupportedLegacy, "unsupportedLegacy");
function isObjectRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isObjectRecord, "isObjectRecord");
function createMigratedGoalState(input) {
  const objective = input.objective.trim();
  if (!objective) {
    throw new Error("Migrated Goal objective must not be empty");
  }
  return {
    v: GOAL_STATE_VERSION,
    cause: "migrated",
    snapshot: {
      v: GOAL_STATE_VERSION,
      activity: "idle",
      goal: {
        goalId: input.goalId,
        revision: 1,
        objective,
        status: "paused",
        evidenceCursor: { recordId: input.recordUuid },
        turnCount: 0,
        activeTimeMs: 0,
        createdAt: input.now,
        updatedAt: input.now
      }
    }
  };
}
__name(createMigratedGoalState, "createMigratedGoalState");

// packages/core/src/goals/goal-runtime.ts
var GOAL_RUNTIME_DISPOSED_MESSAGE = "Goal runtime has been disposed";
var STALE_GOAL_TURN_MESSAGE = "Goal turn permit is no longer valid";
var GoalPersistenceUnavailableError = class extends Error {
  static {
    __name(this, "GoalPersistenceUnavailableError");
  }
  constructor(message = "Goal persistence is unavailable for this session", options) {
    super(message, options);
    this.name = "GoalPersistenceUnavailableError";
  }
};
function normalizeRecoveredBlockedAudit(audit) {
  return {
    ...structuredClone(audit),
    fingerprint: audit.fingerprint.startsWith("\n") ? `repeated${audit.fingerprint}` : audit.fingerprint
  };
}
__name(normalizeRecoveredBlockedAudit, "normalizeRecoveredBlockedAudit");
function createGoalRuntime(options) {
  if (Boolean(options.evidenceSource) !== Boolean(options.verifier)) {
    throw new Error(
      "Goal evidence source and verifier must be configured together"
    );
  }
  let snapshot = {
    v: GOAL_STATE_VERSION,
    goal: null,
    activity: "idle"
  };
  const listeners = /* @__PURE__ */ new Set();
  let dispatchTail = Promise.resolve();
  let host;
  let currentPermit;
  let currentPermitHost;
  let currentTurnKey;
  let queuedTurnKey;
  let continuationQueued = false;
  let currentProposal;
  let pendingProposal;
  let verificationAttempt;
  let blockedAudit;
  let nextVerifierFeedback;
  let currentTurnFeedback;
  let restored = false;
  let disposed = false;
  let recoveryError;
  const assertAvailable = /* @__PURE__ */ __name(() => {
    if (disposed) throw new Error(GOAL_RUNTIME_DISPOSED_MESSAGE);
  }, "assertAvailable");
  const assertOperational = /* @__PURE__ */ __name(() => {
    assertAvailable();
    if (recoveryError) throw recoveryError;
  }, "assertOperational");
  const getSnapshot = /* @__PURE__ */ __name(() => structuredClone(snapshot), "getSnapshot");
  const broadcast = /* @__PURE__ */ __name((cause) => {
    for (const listener of listeners) {
      try {
        listener(getSnapshot(), cause);
      } catch {
      }
    }
  }, "broadcast");
  const preemptHost = /* @__PURE__ */ __name((reason, target = host) => {
    try {
      target?.preemptGoalTurn(reason);
    } catch {
    }
  }, "preemptHost");
  const flushContinuation = /* @__PURE__ */ __name((cause) => {
    if (!continuationQueued || !host || currentPermit || pendingProposal || verificationAttempt || snapshot.activity !== "idle" || snapshot.goal?.status !== "active") {
      return;
    }
    continuationQueued = false;
    const scheduledHost = host;
    const continuationContext = snapshot.goal.objective;
    const verifierFeedback = nextVerifierFeedback;
    nextVerifierFeedback = void 0;
    currentTurnFeedback = verifierFeedback;
    currentPermit = {
      goalId: snapshot.goal.goalId,
      revision: snapshot.goal.revision,
      turnId: randomUUID()
    };
    currentPermitHost = scheduledHost;
    currentTurnKey = `goal-runtime:${currentPermit.turnId}`;
    const startedPermit = structuredClone(currentPermit);
    snapshot = { ...snapshot, activity: "running" };
    broadcast(cause);
    const handleStartFailure = /* @__PURE__ */ __name(() => {
      void enqueue(async () => {
        if (isCurrentPermit(startedPermit)) {
          const nextTurnKey = queuedTurnKey;
          currentPermit = void 0;
          currentPermitHost = void 0;
          currentTurnKey = void 0;
          currentProposal = void 0;
          if (currentTurnFeedback !== void 0) {
            nextVerifierFeedback ??= currentTurnFeedback;
          }
          currentTurnFeedback = void 0;
          if (host === scheduledHost) host = void 0;
          if (nextTurnKey && snapshot.goal?.status === "active") {
            currentPermit = {
              goalId: snapshot.goal.goalId,
              revision: snapshot.goal.revision,
              turnId: randomUUID()
            };
            currentPermitHost = host;
            currentTurnKey = nextTurnKey;
            currentTurnFeedback = nextVerifierFeedback;
            nextVerifierFeedback = void 0;
            queuedTurnKey = void 0;
            continuationQueued = false;
            snapshot = { ...snapshot, activity: "running" };
          } else {
            snapshot = { ...snapshot, activity: "idle" };
          }
          broadcast();
          if (!currentPermit) queueContinuation();
        }
      }).catch(() => void 0);
    }, "handleStartFailure");
    let started;
    try {
      started = scheduledHost.startGoalTurn({
        permit: startedPermit,
        continuationContext,
        ...verifierFeedback ? { verifierFeedback } : {}
      });
    } catch {
      handleStartFailure();
      return;
    }
    void started.catch(handleStartFailure);
  }, "flushContinuation");
  const queueContinuation = /* @__PURE__ */ __name((cause) => {
    if (snapshot.goal?.status !== "active" || currentPermit || pendingProposal || verificationAttempt) {
      return;
    }
    continuationQueued = true;
    flushContinuation(cause);
  }, "queueContinuation");
  const enqueue = /* @__PURE__ */ __name((operation) => {
    const result = dispatchTail.then(operation, operation);
    dispatchTail = result.then(
      () => void 0,
      () => void 0
    );
    return result;
  }, "enqueue");
  const isCurrentPermit = /* @__PURE__ */ __name((permit) => snapshot.goal?.goalId === permit.goalId && snapshot.goal.revision === permit.revision && currentPermit?.goalId === permit.goalId && currentPermit.revision === permit.revision && currentPermit.turnId === permit.turnId, "isCurrentPermit");
  const getSnapshotForPermit = /* @__PURE__ */ __name((permit) => {
    assertOperational();
    if (!isCurrentPermit(permit) || !snapshot.goal) {
      throw new Error(STALE_GOAL_TURN_MESSAGE);
    }
    return getSnapshot();
  }, "getSnapshotForPermit");
  const isCurrentVerificationAttempt = /* @__PURE__ */ __name((attempt) => verificationAttempt === attempt && snapshot.goal?.goalId === attempt.permit.goalId && snapshot.goal.revision === attempt.permit.revision && snapshot.goal.status === "active" && snapshot.activity === "verifying", "isCurrentVerificationAttempt");
  const invalidateVerification = /* @__PURE__ */ __name((reason) => {
    const attempt = verificationAttempt;
    verificationAttempt = void 0;
    pendingProposal = void 0;
    if (attempt && !attempt.controller.signal.aborted) {
      attempt.controller.abort(new Error(reason));
    }
  }, "invalidateVerification");
  const verifierInput = /* @__PURE__ */ __name((attempt, evidence) => {
    const currentDeliveredOutput = evidence.citedRecords.filter(
      (record) => record.proofKind === "delivered_output" && record.turnId === attempt.permit.turnId
    ).map((record) => record.content);
    const base = {
      goal: {
        goalId: attempt.goal.goalId,
        revision: attempt.goal.revision,
        objective: attempt.goal.objective
      },
      currentTurnId: attempt.permit.turnId,
      evidence: evidence.citedRecords,
      ...currentDeliveredOutput.length > 0 ? { currentDeliveredOutput } : {}
    };
    if (attempt.proposal.status === "complete") {
      return {
        ...base,
        proposal: { ...attempt.proposal, status: "complete" }
      };
    }
    return {
      ...base,
      proposal: { ...attempt.proposal, status: "blocked" },
      blockedPolicy: "A blocked Goal is resumable. It may be accepted immediately only when the evidence shows that new user authority or a material user choice is required, or that an external state change is required, and no meaningful in-scope work remains. An ordinary technical blocker requires evidence of the same cause from the current and two immediately preceding Goal turns. Difficulty, uncertainty, incomplete work, or a preference for clarification do not by themselves justify blocked."
    };
  }, "verifierInput");
  const promoteQueuedUserTurn = /* @__PURE__ */ __name(() => {
    const nextTurnKey = queuedTurnKey;
    if (!nextTurnKey || currentPermit || snapshot.goal?.status !== "active") {
      return false;
    }
    queuedTurnKey = void 0;
    continuationQueued = false;
    currentPermit = {
      goalId: snapshot.goal.goalId,
      revision: snapshot.goal.revision,
      turnId: randomUUID()
    };
    currentPermitHost = host;
    currentTurnKey = nextTurnKey;
    currentTurnFeedback = nextVerifierFeedback;
    nextVerifierFeedback = void 0;
    snapshot = { ...snapshot, activity: "running" };
    return true;
  }, "promoteQueuedUserTurn");
  const admitAfterRejection = /* @__PURE__ */ __name(() => {
    continuationQueued = false;
    if (promoteQueuedUserTurn()) return false;
    const activityBefore = snapshot.activity;
    queueContinuation("verifier_reject");
    return activityBefore !== snapshot.activity;
  }, "admitAfterRejection");
  const recordVerificationOutcome = /* @__PURE__ */ __name(async (attempt, outcome) => {
    await enqueue(async () => {
      if (!isCurrentVerificationAttempt(attempt) || !snapshot.goal) return;
      const now = Date.now();
      if (outcome.kind === "decision" && outcome.result.decision === "accept") {
        const acceptedGoal = {
          ...snapshot.goal,
          activeTimeMs: elapsedActiveTime(snapshot.goal, now),
          updatedAt: now,
          lastReason: outcome.result.reason
        };
        const acceptedSnapshot = {
          v: GOAL_STATE_VERSION,
          goal: acceptedGoal,
          activity: "idle"
        };
        const terminalSnapshot = {
          v: GOAL_STATE_VERSION,
          goal: {
            ...acceptedGoal,
            status: attempt.proposal.status
          },
          activity: "idle"
        };
        await options.journal.recordGoalState(randomUUID(), {
          v: GOAL_STATE_VERSION,
          cause: "verifier_accept",
          snapshot: acceptedSnapshot
        });
        if (!isCurrentVerificationAttempt(attempt) || !snapshot.goal) return;
        await options.journal.recordGoalState(randomUUID(), {
          v: GOAL_STATE_VERSION,
          cause: attempt.proposal.status,
          snapshot: terminalSnapshot
        });
        if (!isCurrentVerificationAttempt(attempt) || !snapshot.goal) return;
        verificationAttempt = void 0;
        pendingProposal = void 0;
        if (attempt.proposal.status === "complete") queuedTurnKey = void 0;
        continuationQueued = false;
        nextVerifierFeedback = void 0;
        currentTurnFeedback = void 0;
        snapshot = structuredClone(terminalSnapshot);
        broadcast(attempt.proposal.status);
        return;
      }
      if (outcome.kind === "usage_limited") {
        const limitedSnapshot = {
          v: GOAL_STATE_VERSION,
          goal: {
            ...snapshot.goal,
            status: "usage_limited",
            activeTimeMs: elapsedActiveTime(snapshot.goal, now),
            updatedAt: now,
            lastReason: outcome.reason
          },
          activity: "idle"
        };
        await options.journal.recordGoalState(randomUUID(), {
          v: GOAL_STATE_VERSION,
          cause: "usage_limited",
          snapshot: limitedSnapshot
        });
        if (!isCurrentVerificationAttempt(attempt) || !snapshot.goal) return;
        verificationAttempt = void 0;
        pendingProposal = void 0;
        continuationQueued = false;
        nextVerifierFeedback = void 0;
        currentTurnFeedback = void 0;
        snapshot = structuredClone(limitedSnapshot);
        broadcast("usage_limited");
        return;
      }
      const rejectedSnapshot = {
        v: GOAL_STATE_VERSION,
        goal: {
          ...snapshot.goal,
          activeTimeMs: elapsedActiveTime(snapshot.goal, now),
          updatedAt: now,
          lastReason: outcome.result.reason
        },
        activity: "idle"
      };
      await options.journal.recordGoalState(randomUUID(), {
        v: GOAL_STATE_VERSION,
        cause: "verifier_reject",
        snapshot: rejectedSnapshot,
        ...blockedAudit ? { blockedAudit: structuredClone(blockedAudit) } : {}
      });
      if (!isCurrentVerificationAttempt(attempt) || !snapshot.goal) return;
      verificationAttempt = void 0;
      pendingProposal = void 0;
      snapshot = structuredClone(rejectedSnapshot);
      nextVerifierFeedback = outcome.result.reason;
      const continuationBroadcast = admitAfterRejection();
      if (!continuationBroadcast) broadcast("verifier_reject");
    });
  }, "recordVerificationOutcome");
  const runVerification = /* @__PURE__ */ __name(async (attempt) => {
    const evidenceSource = options.evidenceSource;
    const verifier = options.verifier;
    if (!evidenceSource || !verifier) return;
    let outcome;
    try {
      await evidenceSource.flush();
      if (attempt.controller.signal.aborted) return;
      const records = await evidenceSource.readActiveTranscriptChain();
      if (attempt.controller.signal.aborted) return;
      const evidence = validateGoalEvidenceReferences({
        records,
        goal: attempt.goal,
        permit: attempt.permit,
        proposal: attempt.proposal
      });
      const result = await verifier(
        verifierInput(attempt, evidence),
        attempt.controller.signal
      );
      if (attempt.controller.signal.aborted) return;
      outcome = { kind: "decision", result };
    } catch (error) {
      if (attempt.controller.signal.aborted) return;
      if (error instanceof InvalidGoalEvidenceReferenceError) {
        outcome = {
          kind: "decision",
          result: { decision: "reject", reason: error.message }
        };
      } else {
        const reason = error instanceof EvidenceSourceUnavailableError ? error.message : error instanceof Error ? error.message : String(error);
        outcome = { kind: "usage_limited", reason };
      }
    }
    await recordVerificationOutcome(attempt, outcome);
  }, "runVerification");
  return {
    getSnapshot,
    getSnapshotForPermit,
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    restore(records) {
      return enqueue(async () => {
        assertAvailable();
        if (restored) return;
        const recovery = recoverGoalFromRecords(records);
        if (recovery.kind === "unsupported") {
          recoveryError = new GoalPersistenceUnavailableError(recovery.reason);
          throw recoveryError;
        }
        try {
          let recoveredSnapshot;
          let recoveredCause;
          if (recovery.kind === "v2") {
            recoveredSnapshot = {
              ...structuredClone(recovery.payload.snapshot),
              activity: "idle"
            };
            blockedAudit = recovery.payload.blockedAudit ? normalizeRecoveredBlockedAudit(recovery.payload.blockedAudit) : void 0;
            recoveredCause = recovery.payload.cause;
          } else if (recovery.kind === "legacy") {
            const recordUuid = randomUUID();
            const payload = createMigratedGoalState({
              objective: recovery.objective,
              goalId: randomUUID(),
              recordUuid,
              now: Date.now()
            });
            try {
              await options.journal.recordGoalState(recordUuid, payload);
            } catch (error) {
              throw new GoalPersistenceUnavailableError(
                error instanceof Error ? error.message : String(error),
                { cause: error }
              );
            }
            assertAvailable();
            recoveredSnapshot = structuredClone(payload.snapshot);
            recoveredCause = payload.cause;
          }
          if (recoveredSnapshot) snapshot = recoveredSnapshot;
          recoveryError = void 0;
          restored = true;
          if (recoveredSnapshot) broadcast(recoveredCause);
          queueContinuation();
        } catch (error) {
          if (!disposed) {
            recoveryError = error instanceof Error ? error : new Error(String(error));
          }
          throw error;
        }
      });
    },
    bindHost(nextHost) {
      assertOperational();
      host = nextHost;
      queueContinuation();
      return () => {
        if (host === nextHost) host = void 0;
      };
    },
    beginTurn(turnKey) {
      assertOperational();
      if (snapshot.goal?.status !== "active") return void 0;
      if (snapshot.activity === "verifying" || pendingProposal || verificationAttempt) {
        queuedTurnKey ??= turnKey;
        continuationQueued = false;
        return void 0;
      }
      if (currentPermit) {
        if (currentTurnKey === turnKey) return structuredClone(currentPermit);
        queuedTurnKey ??= turnKey;
        continuationQueued = false;
        return void 0;
      }
      continuationQueued = false;
      currentPermit = {
        goalId: snapshot.goal.goalId,
        revision: snapshot.goal.revision,
        turnId: randomUUID()
      };
      currentPermitHost = host;
      currentTurnKey = turnKey;
      currentTurnFeedback = nextVerifierFeedback;
      nextVerifierFeedback = void 0;
      snapshot = { ...snapshot, activity: "running" };
      broadcast();
      return structuredClone(currentPermit);
    },
    releaseTurn(turnKey) {
      return enqueue(async () => {
        assertOperational();
        let released = false;
        if (queuedTurnKey === turnKey) {
          queuedTurnKey = void 0;
          released = true;
        }
        if (currentPermit && currentTurnKey === turnKey) {
          if (currentTurnFeedback !== void 0) {
            nextVerifierFeedback ??= currentTurnFeedback;
          }
          currentPermit = void 0;
          currentPermitHost = void 0;
          currentTurnKey = void 0;
          currentTurnFeedback = void 0;
          currentProposal = void 0;
          snapshot = { ...snapshot, activity: "idle" };
          broadcast();
          released = true;
        }
        if (released) queueContinuation();
        return released;
      });
    },
    permitForTurn(turnKey) {
      assertOperational();
      return currentPermit && currentTurnKey === turnKey ? structuredClone(currentPermit) : void 0;
    },
    getVerifierFeedback(permit) {
      assertOperational();
      if (!isCurrentPermit(permit)) {
        throw new Error(STALE_GOAL_TURN_MESSAGE);
      }
      return currentTurnFeedback;
    },
    finishTurn(permit) {
      const finish = enqueue(
        async () => {
          assertOperational();
          if (!isCurrentPermit(permit) || !snapshot.goal) {
            throw new Error(STALE_GOAL_TURN_MESSAGE);
          }
          const recordUuid = randomUUID();
          const nextGoal = reduceGoalTurnFinished(snapshot.goal, {
            now: Date.now()
          });
          const persistedSnapshot = {
            v: GOAL_STATE_VERSION,
            goal: nextGoal,
            activity: "idle"
          };
          const persistedBlockedAudit = currentProposal?.blockedAuditCandidate;
          await options.journal.recordGoalState(recordUuid, {
            v: GOAL_STATE_VERSION,
            cause: "turn_finished",
            snapshot: persistedSnapshot,
            ...persistedBlockedAudit ? { blockedAudit: structuredClone(persistedBlockedAudit) } : {}
          });
          assertAvailable();
          const nextTurnKey = queuedTurnKey;
          const proposal = currentProposal;
          const activeProposal = proposal && persistedSnapshot.goal?.status === "active" ? proposal : void 0;
          if (activeProposal?.blockedAuditCandidate) {
            blockedAudit = activeProposal.blockedAuditCandidate;
          } else if (persistedSnapshot.goal?.status === "active") {
            blockedAudit = void 0;
          }
          pendingProposal = activeProposal?.readyForVerification && !options.verifier ? {
            permit: structuredClone(permit),
            proposal: structuredClone(activeProposal.proposal)
          } : void 0;
          verificationAttempt = activeProposal?.readyForVerification && options.verifier ? {
            permit: structuredClone(permit),
            proposal: structuredClone(activeProposal.proposal),
            goal: structuredClone(nextGoal),
            controller: new AbortController()
          } : void 0;
          const verifying = Boolean(pendingProposal || verificationAttempt);
          snapshot = {
            ...structuredClone(persistedSnapshot),
            activity: verifying ? "verifying" : "idle"
          };
          currentPermit = void 0;
          currentPermitHost = void 0;
          currentTurnKey = void 0;
          currentTurnFeedback = void 0;
          queuedTurnKey = verifying ? nextTurnKey : void 0;
          continuationQueued = false;
          currentProposal = void 0;
          if (!verifying && nextTurnKey && snapshot.goal?.status === "active") {
            currentPermit = {
              goalId: snapshot.goal.goalId,
              revision: snapshot.goal.revision,
              turnId: randomUUID()
            };
            currentPermitHost = host;
            currentTurnKey = nextTurnKey;
            currentTurnFeedback = nextVerifierFeedback;
            nextVerifierFeedback = void 0;
            snapshot = { ...snapshot, activity: "running" };
          }
          broadcast("turn_finished");
          if (!verifying && !currentPermit) {
            queueContinuation();
          }
          return verificationAttempt;
        }
      );
      return finish.then(async (attempt) => {
        if (attempt) await runVerification(attempt);
      });
    },
    async getGoalForWorker(permit) {
      assertOperational();
      if (!isCurrentPermit(permit) || !snapshot.goal) {
        throw new Error(STALE_GOAL_TURN_MESSAGE);
      }
      const goal = structuredClone(snapshot.goal);
      const verifierFeedback = currentTurnFeedback;
      const evidenceSource = options.evidenceSource;
      if (!evidenceSource) {
        return {
          goalId: goal.goalId,
          revision: goal.revision,
          objective: goal.objective,
          evidenceCursor: structuredClone(goal.evidenceCursor),
          ...verifierFeedback ? { verifierFeedback } : {}
        };
      }
      await evidenceSource.flush();
      const records = await evidenceSource.readActiveTranscriptChain();
      const evidenceCatalog = buildGoalEvidenceCatalog({
        records,
        goal,
        permit
      });
      if (!isCurrentPermit(permit) || !snapshot.goal) {
        throw new Error(STALE_GOAL_TURN_MESSAGE);
      }
      return {
        goalId: goal.goalId,
        revision: goal.revision,
        objective: goal.objective,
        evidenceCursor: structuredClone(goal.evidenceCursor),
        evidenceCatalog,
        ...verifierFeedback ? { verifierFeedback } : {}
      };
    },
    recordTerminalProposal(permit, proposal) {
      assertOperational();
      if (!isCurrentPermit(permit)) {
        throw new Error(STALE_GOAL_TURN_MESSAGE);
      }
      const reasonError = validateGoalProposalReason(proposal.reason);
      if (reasonError) throw new Error(reasonError);
      if (currentProposal) {
        return {
          recorded: false,
          readyForVerification: currentProposal.readyForVerification
        };
      }
      let readyForVerification = true;
      let blockedAuditCandidate;
      if (proposal.status === "blocked" && proposal.blockerKind !== "authority" && proposal.blockerKind !== "external") {
        const fingerprint = `${proposal.blockerKind ?? "repeated"}
${proposal.reason}`;
        blockedAuditCandidate = {
          fingerprint,
          count: blockedAudit?.fingerprint === fingerprint ? Math.min(blockedAudit.count + 1, 3) : 1,
          turnIds: blockedAudit?.fingerprint === fingerprint ? [...blockedAudit.turnIds, permit.turnId].slice(-3) : [permit.turnId]
        };
        readyForVerification = blockedAuditCandidate.count >= 3;
      }
      currentProposal = {
        proposal: structuredClone(proposal),
        readyForVerification,
        ...blockedAuditCandidate ? { blockedAuditCandidate } : {}
      };
      return { recorded: true, readyForVerification };
    },
    takePendingTerminalProposal() {
      assertOperational();
      const proposal = pendingProposal;
      pendingProposal = void 0;
      return proposal ? structuredClone(proposal) : void 0;
    },
    dispatch(request) {
      const execute = /* @__PURE__ */ __name(async () => {
        assertOperational();
        const recordUuid = randomUUID();
        const nextGoal = reduceGoalControl(snapshot.goal, {
          request,
          now: Date.now(),
          nextGoalId: randomUUID(),
          cursor: request.action === "create" || request.action === "replace" || request.action === "edit" ? { recordId: recordUuid } : options.journal.getTranscriptCursor()
        });
        const nextSnapshot = {
          v: GOAL_STATE_VERSION,
          goal: nextGoal,
          activity: "idle"
        };
        await options.journal.recordGoalState(recordUuid, {
          v: GOAL_STATE_VERSION,
          cause: request.action,
          snapshot: nextSnapshot
        });
        assertAvailable();
        const invalidatesPermit = request.action === "create" || request.action === "replace" || request.action === "edit" || request.action === "pause" || request.action === "clear";
        const invalidatedHost = currentPermitHost ?? host;
        if (invalidatesPermit) {
          invalidateVerification(`Goal ${request.action}`);
        }
        if (invalidatesPermit) {
          currentPermit = void 0;
          currentPermitHost = void 0;
          currentTurnKey = void 0;
          queuedTurnKey = void 0;
          currentProposal = void 0;
          pendingProposal = void 0;
          blockedAudit = void 0;
          nextVerifierFeedback = void 0;
          currentTurnFeedback = void 0;
          continuationQueued = false;
        } else if (request.action === "resume") {
          blockedAudit = void 0;
        }
        snapshot = {
          ...structuredClone(nextSnapshot),
          activity: currentPermit && request.action === "resume" ? "running" : "idle"
        };
        if (request.action === "resume") promoteQueuedUserTurn();
        broadcast(request.action);
        if (invalidatesPermit) {
          preemptHost(`Goal ${request.action}`, invalidatedHost);
        }
        if (request.action === "resume" || request.action !== "clear" && snapshot.goal?.status === "active") {
          queueContinuation();
        }
        return { snapshot: getSnapshot() };
      }, "execute");
      return enqueue(execute);
    },
    dispose() {
      if (disposed) return;
      disposed = true;
      const invalidatedHost = currentPermitHost ?? host;
      currentPermit = void 0;
      currentPermitHost = void 0;
      currentTurnKey = void 0;
      queuedTurnKey = void 0;
      continuationQueued = false;
      currentProposal = void 0;
      pendingProposal = void 0;
      invalidateVerification("Goal runtime disposed");
      blockedAudit = void 0;
      nextVerifierFeedback = void 0;
      currentTurnFeedback = void 0;
      preemptHost("Goal runtime disposed", invalidatedHost);
      host = void 0;
      listeners.clear();
    }
  };
}
__name(createGoalRuntime, "createGoalRuntime");

// packages/core/src/goals/goal-turn-context.ts
init_esbuild_shims();
import { AsyncLocalStorage } from "node:async_hooks";
var goalTurnContext = new AsyncLocalStorage();

export {
  GOAL_PROPOSAL_REASON_MAX_CHARACTERS,
  PAUSED_GOAL_SYSTEM_REMINDER,
  goalRequiresExactPermit,
  validateGoalProposalReason,
  GOAL_EVIDENCE_REFERENCE_LIMIT,
  parseGoalStateRecordPayloadV2,
  parseGoalSnapshotV2,
  GOAL_RUNTIME_DISPOSED_MESSAGE,
  STALE_GOAL_TURN_MESSAGE,
  GoalPersistenceUnavailableError,
  createGoalRuntime,
  goalTurnContext
};
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
