import "../chunk-PZ5AY32C.js";

// src/authenticity/index.ts
var DEFAULT_MOCK = /\bmock|\bfake|\bdummy|\bstub\b|simulat|hardcoded|placeholder|TODO|not\s+implemented|FIXME/i;
function basename(p) {
  return p.split("/").pop() ?? p;
}
function escapeRe(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function declaredNames(content) {
  const names = /* @__PURE__ */ new Set();
  const re = /\b(?:contract|library|interface|abstract\s+contract|class|enum|struct|module|package)\s+([A-Za-z_]\w*)/g;
  let m;
  while (m = re.exec(content)) {
    const name = m[1];
    if (name && name.length >= 4) names.add(name);
  }
  return [...names];
}
function isArtifactReferenced(required, others) {
  if (!required.length || !others.length) return false;
  return required.some((rf) => {
    const stem = rf.path.replace(/\.[^.]+$/, "");
    const base = basename(rf.path);
    const names = declaredNames(rf.content ?? "");
    return others.some((o) => {
      const c = o.content ?? "";
      if (!c) return false;
      if (c.includes(base) || c.includes(stem)) return true;
      return names.some((n) => new RegExp(`\\b${escapeRe(n)}\\b`).test(c));
    });
  });
}
function scoreAuthenticity(files, signals) {
  const w = {
    artifact: signals.weights?.artifact ?? 40,
    impl: signals.weights?.impl ?? 25,
    infra: signals.weights?.infra ?? 20,
    wiring: signals.weights?.wiring ?? 15
  };
  const mockRe = signals.mock ?? DEFAULT_MOCK;
  const required = signals.requiredArtifact ? files.filter(
    (f) => signals.requiredArtifact.test(f.path) && !(signals.vendored?.test(f.path) ?? false)
  ) : [];
  const others = signals.requiredArtifact ? files.filter((f) => !required.includes(f)) : files;
  const requiredText = required.map((f) => f.content ?? "").join("\n");
  const otherText = others.map((f) => f.content ?? "").join("\n");
  const allText = files.map((f) => f.content ?? "").join("\n");
  const requiredArtifactPresent = signals.requiredArtifact ? required.length > 0 : true;
  const usesRealImpl = signals.realImpl.test(signals.requiredArtifact ? requiredText : allText);
  const realInfra = signals.realInfra.test(allText);
  const wired = signals.wiring ? signals.wiring.test(otherText || allText) : false;
  const artifactReferenced = isArtifactReferenced(required, others);
  const artifactWired = wired || artifactReferenced;
  const fakeShim = files.some(
    (f) => signals.fakeShim.test(basename(f.path)) || signals.fakeShim.test(f.content ?? "")
  );
  const mockHits = (allText.match(
    new RegExp(mockRe.source, mockRe.flags.includes("g") ? mockRe.flags : `${mockRe.flags}g`)
  ) ?? []).length;
  const loc = Math.max(1, allText.split("\n").length);
  const mockDensity = Math.min(100, Math.round(mockHits / loc * 1e3));
  const decorativeArtifact = requiredArtifactPresent && usesRealImpl && !artifactWired;
  let realness = 0;
  if (requiredArtifactPresent) realness += w.artifact;
  if (usesRealImpl) realness += w.impl;
  if (realInfra) realness += w.infra;
  if (wired) realness += w.wiring;
  if (fakeShim) realness -= 25;
  realness -= Math.min(20, mockDensity);
  realness = Math.max(0, Math.min(100, realness));
  const flags = [];
  if (signals.requiredArtifact && !requiredArtifactPresent) {
    flags.push(
      `NO_REQUIRED_ARTIFACT: task needs ${signals.label} artifact (${signals.requiredArtifact}); none produced`
    );
  }
  if (requiredArtifactPresent && signals.requiredArtifact && !usesRealImpl) {
    flags.push("ARTIFACT_NO_REAL_IMPL: required artifact exists but lacks the real implementation");
  }
  if (fakeShim) flags.push("FAKE_SHIM: ships a client-side stand-in simulating the real infra");
  if (!realInfra && !requiredArtifactPresent)
    flags.push("NO_REAL_INFRA: no real infra calls \u2014 cosmetic at best");
  if (mockDensity >= 8)
    flags.push(`HIGH_MOCK_DENSITY: ${mockDensity} mock/stub markers per 1000 LOC`);
  if (signals.wiring && requiredArtifactPresent && !wired)
    flags.push("NOT_WIRED: artifact exists but is never used by the client");
  if (decorativeArtifact)
    flags.push(
      "DEAD_ARTIFACT: required artifact is not referenced/imported anywhere \u2014 decorative or dead code"
    );
  return {
    realness,
    requiredArtifactPresent,
    requiredArtifactCount: required.length,
    usesRealImpl,
    realInfra,
    wired,
    artifactReferenced,
    artifactWired,
    fakeShim,
    mockDensity,
    flags
  };
}
function gateRealness(r, opts = {}) {
  const floor = opts.floor ?? 30;
  if ((opts.requireArtifact ?? true) && !r.requiredArtifactPresent) {
    return { gated: true, reason: "required artifact missing" };
  }
  if (r.fakeShim && !r.usesRealImpl) {
    return { gated: true, reason: "fake shim with no real implementation" };
  }
  if (opts.requireArtifactWired && r.requiredArtifactPresent && r.usesRealImpl && !r.artifactWired) {
    return { gated: true, reason: "required artifact present but never wired into the system" };
  }
  if (r.realness < floor)
    return { gated: true, reason: `realness ${r.realness} below floor ${floor}` };
  return { gated: false };
}
function fileDigest(files, opts = {}) {
  const maxFiles = opts.maxFiles ?? 14;
  const perFile = opts.perFile ?? 1200;
  const ordered = opts.prioritize ? [...files].sort(
    (a, b) => Number(opts.prioritize.test(b.path)) - Number(opts.prioritize.test(a.path))
  ) : files;
  return ordered.slice(0, maxFiles).map((f) => `// ${f.path}
${(f.content ?? "").slice(0, perFile)}`).join("\n\n");
}
function clampPct(v) {
  const n = typeof v === "number" ? v : Number(v);
  return Number.isFinite(n) ? Math.max(0, Math.min(100, Math.round(n))) : 0;
}
async function scoreAuthenticityNuance(files, complete, opts = {}) {
  const system = 'You audit whether an agent BUILT THE REAL THING or faked it. Be skeptical: a pretty UI, cosmetic labels, simulated/in-memory stand-ins for real infra, and cargo-culted imports do NOT count as real. Respond with ONLY JSON: {"mockedPct":0-100,"fakePct":0-100,"uniquePct":0-100,"verdict":"one sentence"}. mockedPct = how much is mocked/stubbed; fakePct = how hollow/facade it is; uniquePct = how distinctive vs boilerplate.';
  const user = (opts.intent ? `Intended deliverable: ${opts.intent}

` : "") + `Produced files:
${fileDigest(files, { prioritize: opts.prioritize })}`;
  try {
    const raw = await complete(system, user);
    const m = raw.match(/\{[\s\S]*\}/);
    if (!m)
      return { mockedPct: 100, fakePct: 100, uniquePct: 0, verdict: "unparseable judge response" };
    const j = JSON.parse(m[0]);
    return {
      mockedPct: clampPct(j.mockedPct),
      fakePct: clampPct(j.fakePct),
      uniquePct: clampPct(j.uniquePct),
      verdict: typeof j.verdict === "string" ? j.verdict : ""
    };
  } catch (err) {
    return {
      mockedPct: 100,
      fakePct: 100,
      uniquePct: 0,
      verdict: `judge error: ${err instanceof Error ? err.message : String(err)}`
    };
  }
}
async function judgeRealnessLlm(files, complete, opts = {}) {
  const system = "You are a skeptical auditor. Rate how REAL an agent's build is vs the intended deliverable, 0-100. A genuine implementation of the HARD part on the intended infrastructure is SUBSTANTIALLY REAL (>=50) even if peripheral layers are stubbed; a pure simulator / facade / branded-type stand-in / no-op-stubbed dependency with no real implementation is FAKE (<=25). Judge the core on its merits and note the runtime. " + (opts.rubric ? `Domain rubric: ${opts.rubric} ` : "") + 'Respond with ONLY JSON: {"isReal":0-100,"why":"one sentence"}.';
  const user = (opts.intent ? `Intended deliverable: ${opts.intent}

` : "") + `Produced files:
${fileDigest(files, { prioritize: opts.prioritize })}`;
  try {
    const raw = await complete(system, user);
    const m = raw.match(/\{[\s\S]*\}/);
    if (!m) return { isReal: 0, rationale: "unparseable judge response" };
    const j = JSON.parse(m[0]);
    return {
      isReal: clampPct(j.isReal),
      rationale: typeof j.why === "string" ? j.why : ""
    };
  } catch (err) {
    return {
      isReal: 0,
      rationale: `judge error: ${err instanceof Error ? err.message : String(err)}`
    };
  }
}
async function scoreRealnessBlended(files, signals, complete, opts = {}) {
  const det = scoreAuthenticity(files, signals);
  const [lo, hi] = opts.grayBand ?? [30, 70];
  const mockGray = opts.mockGrayThreshold ?? 8;
  const conflict = det.requiredArtifactPresent && det.usesRealImpl && (det.fakeShim || !det.wired || det.mockDensity >= mockGray);
  const midRange = det.realness >= lo && det.realness <= hi;
  let band;
  if (conflict || midRange) band = "gray";
  else if (det.realness < lo) band = "clean-fake";
  else band = "clean-real";
  if (band !== "gray") {
    return { ...det, blendedRealness: det.realness, band, consultedLlm: false };
  }
  const judgment = await judgeRealnessLlm(files, complete, {
    intent: opts.intent,
    rubric: opts.rubric,
    prioritize: signals.requiredArtifact
  });
  const blendedRealness = Math.max(
    0,
    Math.min(100, Math.round(0.25 * det.realness + 0.75 * judgment.isReal))
  );
  return { ...det, blendedRealness, band, consultedLlm: true, judgment };
}
export {
  gateRealness,
  judgeRealnessLlm,
  scoreAuthenticity,
  scoreAuthenticityNuance,
  scoreRealnessBlended
};
//# sourceMappingURL=index.js.map