import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
import {
  planFm,
  sporeFm
} from "./chunk-RY76WEN3.js";
import {
  MycoIndex
} from "./chunk-TWSTAVLO.js";
import {
  loadConfig
} from "./chunk-YG6MLLGL.js";
import "./chunk-JSK7L46L.js";
import {
  readStdin
} from "./chunk-CQ4RKK67.js";
import {
  DaemonClient
} from "./chunk-CPVXNRGW.js";
import "./chunk-CK24O5YQ.js";
import {
  resolveVaultDir
} from "./chunk-N33KUCFP.js";
import "./chunk-RNWALAFP.js";
import {
  CONTEXT_PLAN_PREVIEW_CHARS,
  CONTEXT_SESSION_PREVIEW_CHARS,
  CONTEXT_SPORE_PREVIEW_CHARS,
  estimateTokens
} from "./chunk-WBLTISAK.js";
import "./chunk-PZUWP5VK.js";

// src/context/relevance.ts
var RECENCY_TIERS = [
  { maxHours: 24, score: 3, label: "recent (<24h)" },
  { maxHours: 72, score: 2, label: "recent (<72h)" },
  { maxHours: 168, score: 1, label: "recent (<1w)" }
];
var BRANCH_MATCH_SCORE = 3;
var PLAN_MATCH_SCORE = 2;
var MS_PER_HOUR = 36e5;
function scoreRelevance(notes, input) {
  return notes.map((note) => {
    let score = 0;
    const reasons = [];
    const fm = note.frontmatter;
    const age = Date.now() - new Date(note.created).getTime();
    const hoursOld = age / MS_PER_HOUR;
    for (const tier of RECENCY_TIERS) {
      if (hoursOld < tier.maxHours) {
        score += tier.score;
        reasons.push(tier.label);
        break;
      }
    }
    if (input.branch && fm.branch === input.branch) {
      score += BRANCH_MATCH_SCORE;
      reasons.push("same branch");
    }
    if (input.activePlanIds?.length) {
      const planRef = fm.plan;
      if (planRef && input.activePlanIds.some(
        (id) => planRef === `[[${id}]]` || planRef === id
      )) {
        score += PLAN_MATCH_SCORE;
        reasons.push("active plan");
      }
    }
    return { note, score, reason: reasons.join(", ") };
  }).filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
}

// src/context/injector.ts
function buildInjectedContext(index, config, context) {
  const budgets = config.context.layers;
  const plans = index.query({ type: "plan" });
  const activePlans = plans.filter(
    (p) => ["active", "in_progress"].includes(planFm(p).status ?? "")
  );
  const plansText = formatLayer(
    "Active Plans",
    activePlans.map((p) => `- **${p.title}** (${planFm(p).status}): ${p.content.slice(0, CONTEXT_PLAN_PREVIEW_CHARS)}`),
    budgets.plans
  );
  const sessions = index.query({ type: "session", limit: 10 });
  const activePlanIds = activePlans.map((p) => p.id);
  const scoredSessions = scoreRelevance(sessions, {
    branch: context.branch,
    activePlanIds
  });
  const sessionsText = formatLayer(
    "Recent Sessions",
    scoredSessions.slice(0, 5).map(
      (s) => `- **${s.note.title}**: ${s.note.content.slice(0, CONTEXT_SESSION_PREVIEW_CHARS)} (${s.reason})`
    ),
    budgets.sessions
  );
  const spores = index.query({ type: "spore", limit: 20 }).filter((m) => {
    const status = sporeFm(m).status;
    return status !== "superseded" && status !== "archived";
  });
  const scoredSpores = scoreRelevance(spores, {
    branch: context.branch,
    activePlanIds
  });
  const sporesText = formatLayer(
    "Relevant Spores",
    scoredSpores.slice(0, 5).map(
      (m) => `- **${m.note.title}** (${sporeFm(m.note).observation_type}): ${m.note.content.slice(0, CONTEXT_SPORE_PREVIEW_CHARS)}`
    ),
    budgets.spores
  );
  const teamText = formatLayer("Team Activity", [], budgets.team);
  const allLayers = [plansText, sessionsText, sporesText, teamText].filter(Boolean);
  const parts = [];
  let totalTokens = 0;
  for (const layer of allLayers) {
    const layerTokens = estimateTokens(layer);
    if (totalTokens + layerTokens > config.context.max_tokens) break;
    parts.push(layer);
    totalTokens += layerTokens;
  }
  const fullText = parts.join("\n\n");
  return {
    text: fullText,
    tokenEstimate: totalTokens,
    layers: {
      plans: plansText,
      sessions: sessionsText,
      spores: sporesText,
      team: teamText
    }
  };
}
function formatLayer(heading, items, budget) {
  if (items.length === 0) return "";
  let text = `### ${heading}
`;
  let currentTokens = estimateTokens(text);
  for (const item of items) {
    const itemTokens = estimateTokens(item);
    if (currentTokens + itemTokens > budget) break;
    text += item + "\n";
    currentTokens += itemTokens;
  }
  return text.trim();
}

// src/hooks/session-start.ts
import { execFileSync } from "child_process";
import fs from "fs";
import path from "path";
async function main() {
  const VAULT_DIR = resolveVaultDir();
  if (!fs.existsSync(path.join(VAULT_DIR, "myco.yaml"))) return;
  try {
    const config = loadConfig(VAULT_DIR);
    const client = new DaemonClient(VAULT_DIR);
    const healthy = await client.ensureRunning();
    const input = JSON.parse(await readStdin());
    const sessionId = input.session_id ?? `s-${Date.now()}`;
    let branch;
    try {
      branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf-8" }).trim();
    } catch {
    }
    if (healthy) {
      await client.post("/sessions/register", {
        session_id: sessionId,
        branch,
        started_at: (/* @__PURE__ */ new Date()).toISOString()
      });
      const contextResult = await client.post("/context", { session_id: sessionId, branch });
      if (contextResult.ok && contextResult.data?.text) {
        if (contextResult.data.source === "digest") {
          process.stderr.write(`[myco] Injecting digest extract (tier ${contextResult.data.tier})
`);
        }
        process.stdout.write(contextResult.data.text);
        return;
      }
    }
    const index = new MycoIndex(path.join(VAULT_DIR, "index.db"));
    const injected = buildInjectedContext(index, config, { branch });
    if (injected.text) process.stdout.write(injected.text);
    index.close();
  } catch (error) {
    process.stderr.write(`[myco] session-start error: ${error.message}
`);
  }
}
main();
//# sourceMappingURL=session-start-KQ4KCQMZ.js.map