// src/memory-worth-outcomes.ts
import path from "path";
var outcomeLocks = /* @__PURE__ */ new Map();
function runSerialized(key, task) {
  const prev = outcomeLocks.get(key) ?? Promise.resolve();
  const next = prev.catch(() => void 0).then(task);
  outcomeLocks.set(key, next);
  next.then(
    () => {
      if (outcomeLocks.get(key) === next) outcomeLocks.delete(key);
    },
    () => {
      if (outcomeLocks.get(key) === next) outcomeLocks.delete(key);
    }
  ).catch(() => {
  });
  return next;
}
var MEMORY_WORTH_OUTCOME_ELIGIBLE_CATEGORIES = /* @__PURE__ */ new Set(["fact"]);
function memoryWorthOutcomeEligibleCategories() {
  return new Set(MEMORY_WORTH_OUTCOME_ELIGIBLE_CATEGORIES);
}
function memoryIdFromPath(memoryPath) {
  if (!memoryPath || typeof memoryPath !== "string") return null;
  if (!memoryPath.endsWith(".md")) return null;
  const basename = path.basename(memoryPath, ".md");
  if (!basename) return null;
  return basename;
}
async function recordMemoryOutcome(storage, input) {
  if (input.outcome !== "success" && input.outcome !== "failure") {
    return {
      ok: false,
      reason: "invalid_outcome",
      message: `outcome must be "success" or "failure"; got ${JSON.stringify(input.outcome)}`
    };
  }
  const memoryId = memoryIdFromPath(input.memoryPath);
  if (memoryId === null) {
    return {
      ok: false,
      reason: "invalid_path",
      message: `memoryPath must end in .md; got ${JSON.stringify(input.memoryPath)}`
    };
  }
  return runSerialized(memoryId, async () => {
    const memory = await storage.getMemoryById(memoryId);
    if (!memory) {
      return {
        ok: false,
        reason: "not_found",
        message: `no memory with id ${memoryId}`
      };
    }
    if (!MEMORY_WORTH_OUTCOME_ELIGIBLE_CATEGORIES.has(memory.frontmatter.category)) {
      return {
        ok: false,
        reason: "ineligible_category",
        message: `category ${memory.frontmatter.category} is not instrumented for Memory Worth`
      };
    }
    const currentSuccess = memory.frontmatter.mw_success ?? 0;
    const currentFail = memory.frontmatter.mw_fail ?? 0;
    const nextSuccess = input.outcome === "success" ? currentSuccess + 1 : currentSuccess;
    const nextFail = input.outcome === "failure" ? currentFail + 1 : currentFail;
    const updated = await storage.updateMemoryFrontmatter(memoryId, {
      mw_success: nextSuccess,
      mw_fail: nextFail
    });
    if (!updated) {
      return {
        ok: false,
        reason: "not_found",
        message: `memory ${memoryId} disappeared between read and write`
      };
    }
    return {
      ok: true,
      memoryId,
      mw_success: nextSuccess,
      mw_fail: nextFail
    };
  });
}

export {
  memoryWorthOutcomeEligibleCategories,
  recordMemoryOutcome
};
//# sourceMappingURL=chunk-EIR5VLIH.js.map