"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var memory_exports = {};
__export(memory_exports, {
  register: () => register
});
module.exports = __toCommonJS(memory_exports);
var import_ui = require("../ui");
function register(program) {
  const mem = program.command("mem").description("Persistent cross-session memory (requires enableMemory: true)");
  mem.command("search <query>").description("Search memory observations (hybrid FTS + vector)").option("--kind <kind>", "Filter by kind: decision, error, pattern, architecture, summary, note").option("--limit <n>", "Max results", "10").option("--session <id>", "Filter to specific session").option("--format <fmt>", "Output format: text, json", "text").action(async (query, opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const { trackCliToolSaving } = await Promise.resolve().then(() => require("./utils.js"));
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled. Set enableMemory: true in .kirograph/config.json");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const results = await mem2.search(query, {
      limit: parseInt(opts.limit),
      kind: opts.kind,
      sessionId: opts.session
    });
    if (opts.format === "json") {
      console.log(JSON.stringify(results.map((r) => ({
        id: r.observation.id,
        kind: r.observation.kind,
        content: r.observation.content,
        score: r.score,
        createdAt: r.observation.createdAt,
        sessionId: r.observation.sessionId
      })), null, 2));
    } else {
      if (results.length === 0) {
        console.log(`
  ${import_ui.dim}No observations found for "${query}"${import_ui.reset}
`);
      } else {
        console.log(`
  ${(0, import_ui.section)("Memory Search:")} ${import_ui.violet}${import_ui.bold}${query}${import_ui.reset}
`);
        for (const r of results) {
          const age = formatAge(r.observation.createdAt);
          console.log(`  ${import_ui.violet}[${r.observation.kind}]${import_ui.reset} ${r.observation.content}`);
          console.log(`  ${import_ui.dim}${age} \xB7 score: ${r.score.toFixed(3)}${import_ui.reset}
`);
        }
      }
    }
    const output = results.map((r) => `[${r.observation.kind}] ${r.observation.content}`).join("\n");
    trackCliToolSaving(cwd, "kirograph_mem_search", output, { limit: parseInt(opts.limit) });
    cg.close();
  });
  mem.command("store [content]").description("Store an observation in memory").option("--kind <kind>", "Observation kind", "note").action(async (content, opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled. Set enableMemory: true in .kirograph/config.json");
      process.exit(1);
    }
    let text = content;
    if (!text) {
      const chunks = [];
      for await (const chunk of process.stdin) {
        chunks.push(chunk);
      }
      text = Buffer.concat(chunks).toString("utf8").trim();
    }
    if (!text) {
      console.error("  \u2716 No content provided. Pass as argument or pipe from stdin.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const id = await mem2.store({ content: text, kind: opts.kind, source: "manual" });
    if (id) {
      console.log(`  \u2713 Stored observation ${import_ui.dim}${id}${import_ui.reset} [${import_ui.violet}${opts.kind}${import_ui.reset}]`);
    } else {
      console.log(`  ${import_ui.dim}Duplicate observation \u2014 already stored.${import_ui.reset}`);
    }
    cg.close();
  });
  mem.command("timeline").description("List recent sessions and observations").option("--limit <n>", "Number of sessions", "5").option("--session <id>", "Show observations for a specific session").option("--format <fmt>", "Output format: text, json", "text").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const { trackCliToolSaving } = await Promise.resolve().then(() => require("./utils.js"));
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled. Set enableMemory: true in .kirograph/config.json");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const { sessions, observations } = mem2.timeline({
      limit: parseInt(opts.limit),
      sessionId: opts.session
    });
    if (opts.format === "json") {
      console.log(JSON.stringify({
        sessions: sessions.map((s) => ({
          id: s.id,
          ide: s.ide,
          startedAt: s.startedAt,
          endedAt: s.endedAt,
          observations: (observations.get(s.id) ?? []).map((o) => ({
            id: o.id,
            kind: o.kind,
            content: o.content,
            createdAt: o.createdAt
          }))
        }))
      }, null, 2));
    } else {
      if (sessions.length === 0) {
        console.log(`
  ${import_ui.dim}No memory sessions found.${import_ui.reset}
`);
      } else {
        console.log(`
  ${(0, import_ui.section)("Memory Timeline")}
`);
        for (const session of sessions) {
          const start = new Date(session.startedAt).toISOString().slice(0, 16).replace("T", " ");
          const status = session.endedAt ? import_ui.dim + "ended" + import_ui.reset : import_ui.violet + "active" + import_ui.reset;
          const obs = observations.get(session.id) ?? [];
          console.log(`  ${import_ui.bold}${start}${import_ui.reset} [${session.ide ?? "unknown"}] ${status} \xB7 ${obs.length} observations`);
          for (const o of obs.slice(0, 5)) {
            console.log(`    ${import_ui.dim}\xB7${import_ui.reset} ${import_ui.violet}[${o.kind}]${import_ui.reset} ${o.content.slice(0, 100)}`);
          }
          if (obs.length > 5) console.log(`    ${import_ui.dim}\u2026and ${obs.length - 5} more${import_ui.reset}`);
          console.log("");
        }
      }
    }
    const output = sessions.map((s) => s.id).join("\n");
    trackCliToolSaving(cwd, "kirograph_mem_timeline", output, { limit: parseInt(opts.limit) });
    cg.close();
  });
  mem.command("status").description("Show memory subsystem health").action(async () => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled. Set enableMemory: true in .kirograph/config.json");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const stats = mem2.getStats();
    console.log(`
  ${(0, import_ui.section)("Memory Status")}
`);
    console.log(`  Sessions:       ${import_ui.bold}${stats.sessions}${import_ui.reset} (${stats.activeSessions} active)`);
    console.log(`  Observations:   ${import_ui.bold}${stats.observations}${import_ui.reset}`);
    console.log(`  Symbol links:   ${import_ui.bold}${stats.links}${import_ui.reset}`);
    console.log(`  Embeddings:     ${import_ui.bold}${stats.vectors}${import_ui.reset} / ${stats.embeddableCount}`);
    console.log(`  Model mismatch: ${stats.modelMismatch ? import_ui.violet + "\u26A0 yes \u2014 run kirograph mem reembed" + import_ui.reset : import_ui.dim + "no" + import_ui.reset}`);
    console.log(`  Compression:    ${config.cavemanMode !== "off" ? import_ui.violet + config.cavemanMode + import_ui.reset : import_ui.dim + "off (storing raw)" + import_ui.reset}`);
    console.log("");
    cg.close();
  });
  mem.command("prune").description("Remove old observations").option("--older-than <duration>", "Duration (e.g. 90d, 6m)", "90d").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled.");
      process.exit(1);
    }
    const ms = parseDuration(opts.olderThan);
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const deleted = mem2.prune(ms);
    console.log(`  \u2713 Pruned ${deleted} observation(s) older than ${opts.olderThan}`);
    cg.close();
  });
  mem.command("export").description("Export memory observations").option("--format <fmt>", "Output format: jsonl, md", "jsonl").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const { sessions, observations } = mem2.timeline({ limit: 1e3 });
    if (opts.format === "jsonl") {
      for (const session of sessions) {
        const obs = observations.get(session.id) ?? [];
        for (const o of obs) {
          console.log(JSON.stringify({
            id: o.id,
            content: o.content,
            content_raw: o.contentRaw,
            kind: o.kind,
            tags: o.tags,
            created_at: o.createdAt,
            session_id: o.sessionId
          }));
        }
      }
    } else {
      for (const session of sessions) {
        const start = new Date(session.startedAt).toISOString().slice(0, 10);
        console.log(`## Session ${start} (${session.ide ?? "unknown"})
`);
        const obs = observations.get(session.id) ?? [];
        for (const o of obs) {
          const time = new Date(o.createdAt).toISOString().slice(11, 16);
          console.log(`### [${o.kind}] ${time}`);
          console.log(o.content);
          console.log("");
        }
      }
    }
    cg.close();
  });
  mem.command("import <file>").description("Import observations from JSONL backup").action(async (file) => {
    const fs = await import("fs");
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled.");
      process.exit(1);
    }
    if (!fs.existsSync(file)) {
      console.error(`  \u2716 File not found: ${file}`);
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const lines = fs.readFileSync(file, "utf8").split("\n").filter((l) => l.trim());
    let imported = 0;
    let skipped = 0;
    for (const line of lines) {
      try {
        const data = JSON.parse(line);
        const id = await mem2.store({
          content: data.content_raw || data.content,
          kind: data.kind ?? "note",
          source: "manual",
          tags: data.tags
        });
        if (id) imported++;
        else skipped++;
      } catch {
        skipped++;
      }
    }
    console.log(`  \u2713 Imported ${imported} observation(s), skipped ${skipped} (duplicates/errors)`);
    cg.close();
  });
  mem.command("reembed").description("Re-embed all observations with the current model").option("--batch <n>", "Batch size", "32").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    console.log("  Re-embedding all observations...");
    const count = await mem2.reembed(parseInt(opts.batch));
    console.log(`  \u2713 Re-embedded ${count} observation(s)`);
    cg.close();
  });
  mem.command("lint").description("Health check: find stale links, model mismatch, orphans").option("--fix", "Auto-fix issues (remove stale links, close stale sessions)").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph is not initialized. Run `kirograph init` first.");
      process.exit(1);
    }
    const config = await loadConfig(cwd);
    if (!config.enableMemory) {
      console.error("  \u2716 Memory is not enabled.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const result = mem2.lint();
    console.log(`
  ${(0, import_ui.section)("Memory Lint")}
`);
    console.log(`  Stale links:    ${result.staleLinks > 0 ? import_ui.violet + result.staleLinks + import_ui.reset : import_ui.dim + "0" + import_ui.reset}`);
    console.log(`  Model mismatch: ${result.modelMismatch ? import_ui.violet + "yes" + import_ui.reset : import_ui.dim + "no" + import_ui.reset}`);
    console.log(`  Stale sessions: ${result.staleSessions > 0 ? import_ui.violet + String(result.staleSessions) + " (auto-closed)" + import_ui.reset : import_ui.dim + "0" + import_ui.reset}`);
    if (opts.fix && result.staleLinks > 0) {
      const removed = mem2.removeStaleLinks();
      console.log(`
  \u2713 Removed ${removed} stale link(s)`);
    } else if (result.staleLinks > 0) {
      console.log(`
  ${import_ui.dim}Run with --fix to remove stale links${import_ui.reset}`);
    }
    if (result.modelMismatch) {
      console.log(`  ${import_ui.dim}Run 'kirograph mem reembed' to fix model mismatch${import_ui.reset}`);
    }
    console.log("");
    cg.close();
  });
  mem.command("session-start").description("Start a new memory session (called by hooks)").option("--ide <name>", "IDE name", "kiro").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) return;
    const config = await loadConfig(cwd);
    if (!config.enableMemory) return;
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    const { MemoryDatabase } = await Promise.resolve().then(() => require("../../memory/database.js"));
    const memDb = new MemoryDatabase(db.getRawDb());
    memDb.initialize();
    const sessionId = memDb.getOrCreateSession(opts.ide, cwd);
    console.log(sessionId);
    cg.close();
  });
  mem.command("session-end").description("End the current memory session (called by hooks)").option("--ide <name>", "IDE name", "kiro").action(async (opts) => {
    const { MemoryManager } = await Promise.resolve().then(() => require("../../memory/index.js"));
    const { loadConfig } = await Promise.resolve().then(() => require("../../config.js"));
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    const cwd = process.cwd();
    if (!KiroGraph.isInitialized(cwd)) return;
    const config = await loadConfig(cwd);
    if (!config.enableMemory) return;
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyMemorySchema();
    const mem2 = new MemoryManager(config, db.getRawDb());
    mem2.initialize();
    mem2.endCurrentSession(opts.ide);
    cg.close();
  });
}
function formatAge(timestamp) {
  const diff = Date.now() - timestamp;
  const minutes = Math.floor(diff / 6e4);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}d ago`;
  const weeks = Math.floor(days / 7);
  if (weeks < 5) return `${weeks}w ago`;
  const months = Math.floor(days / 30);
  return `${months}mo ago`;
}
function parseDuration(duration) {
  const match = duration.match(/^(\d+)(d|m|w|h)$/);
  if (!match) return 90 * 24 * 60 * 60 * 1e3;
  const value = parseInt(match[1]);
  switch (match[2]) {
    case "h":
      return value * 60 * 60 * 1e3;
    case "d":
      return value * 24 * 60 * 60 * 1e3;
    case "w":
      return value * 7 * 24 * 60 * 60 * 1e3;
    case "m":
      return value * 30 * 24 * 60 * 60 * 1e3;
    default:
      return 90 * 24 * 60 * 60 * 1e3;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  register
});
//# sourceMappingURL=memory.js.map
