// @bun
import {
  ProgressTracker,
  formatProgress,
  init_ProgressTracker
} from "./chunk-psc8avjs.js";
import {
  getProjectsDir,
  init_memoryScan,
  init_sessionStorage,
  scanMemoryFiles
} from "./chunk-4vz571bb.js";
import"./chunk-14p6wvsq.js";
import"./chunk-8hseq8b1.js";
import"./chunk-ddtxq6k5.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-ptxteaeh.js";
import"./chunk-wd53a7m4.js";
import"./chunk-hms8ge0k.js";
import"./chunk-whpphypt.js";
import"./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-qd3r2s2n.js";
import"./chunk-djzd7tef.js";
import"./chunk-gyhnpbkx.js";
import"./chunk-71sdcaq6.js";
import"./chunk-60gf7p5s.js";
import"./chunk-sj3d0nqx.js";
import"./chunk-9pk9rk2w.js";
import"./chunk-javpza6a.js";
import"./chunk-6v7bre98.js";
import"./chunk-24kv69g3.js";
import"./chunk-fcqebw9m.js";
import"./chunk-dnfd3c9s.js";
import"./chunk-15ezj4ww.js";
import"./chunk-1h284c6e.js";
import"./chunk-582g9yce.js";
import"./chunk-y3ztgztb.js";
import"./chunk-4spgkgr3.js";
import {
  init_checkpoint,
  saveCheckpoint
} from "./chunk-n8kbhswc.js";
import"./chunk-60fkafk2.js";
import"./chunk-fgbkrbk3.js";
import"./chunk-ssw61jfd.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-k8wq4qsj.js";
import"./chunk-g7d3xx1p.js";
import"./chunk-3wrx2943.js";
import"./chunk-7p9kkh0f.js";
import"./chunk-qp8cgz66.js";
import"./chunk-1mg610h2.js";
import"./chunk-93hc149s.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-nnat9jw5.js";
import"./chunk-hqxp6b72.js";
import"./chunk-4jzkqgf1.js";
import"./chunk-33rd41ng.js";
import"./chunk-f257kqw9.js";
import"./chunk-w5hnghah.js";
import"./chunk-36twraxy.js";
import"./chunk-1bkvnj0y.js";
import"./chunk-akdpcc5p.js";
import {
  getAutoMemPath,
  init_paths
} from "./chunk-7rrkrej7.js";
import"./chunk-6r0bxrh6.js";
import"./chunk-d6500tvx.js";
import"./chunk-jg4bw4hp.js";
import"./chunk-epvbnq43.js";
import"./chunk-tn2sx7j6.js";
import"./chunk-6tzyv21c.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-ch4pgvwq.js";
import"./chunk-99jc4tcw.js";
import"./chunk-fghczfqt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-f86mwfyd.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-nt5dmk8q.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import"./chunk-0r6npc3t.js";
import"./chunk-gxyx8b8w.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-t0450ma3.js";
import"./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import"./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  init_debug,
  logForDebugging
} from "./chunk-byd20vdq.js";
import"./chunk-kb3758f7.js";
import"./chunk-3j8w0rq8.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm
} from "./chunk-hhsxm2yr.js";

// src/commands/dream/dream.ts
import { readdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
async function scanRecentTranscripts() {
  const projectsDir = getProjectsDir();
  const transcripts = [];
  try {
    const projectDirs = await readdir(projectsDir).catch(() => []);
    for (const projectDir of projectDirs.slice(0, 3)) {
      const projectPath = join(projectsDir, projectDir);
      try {
        const files = await readdir(projectPath);
        const jsonlFiles = files.filter((f) => f.endsWith(".jsonl")).sort().reverse().slice(0, MAX_SESSIONS_TO_SCAN);
        for (const file of jsonlFiles) {
          try {
            const content = await readFile(join(projectPath, file), "utf-8");
            if (content.length <= MAX_TRANSCRIPT_SIZE)
              transcripts.push(content);
          } catch {}
        }
      } catch {}
    }
  } catch {}
  return transcripts;
}
function extractInsights(transcripts) {
  const insights = [];
  for (const transcript of transcripts) {
    const lines = transcript.split(`
`).filter((l) => l.trim());
    const messages = [];
    for (const line of lines) {
      try {
        const entry = JSON.parse(line);
        if (entry.role && entry.content) {
          messages.push({
            role: entry.role,
            content: typeof entry.content === "string" ? entry.content : JSON.stringify(entry.content)
          });
        }
      } catch {}
    }
    for (const msg of messages) {
      if (msg.role !== "user")
        continue;
      const text = msg.content.toLowerCase();
      if (text.includes("\u4E0D\u8981") || text.includes("\u522B") || text.includes("don't")) {
        insights.push({
          title: `User preference: ${msg.content.slice(0, 50)}`,
          description: "User expressed a negative preference",
          type: "feedback",
          content: msg.content
        });
      }
      if (text.includes("\u4E0D\u5BF9") || text.includes("\u9519\u4E86") || text.includes("wrong")) {
        insights.push({
          title: `User correction: ${msg.content.slice(0, 50)}`,
          description: "User corrected an approach",
          type: "feedback",
          content: msg.content
        });
      }
      if (text.includes("\u9879\u76EE") || text.includes("\u67B6\u6784") || text.includes("architecture")) {
        insights.push({
          title: `Project context: ${msg.content.slice(0, 50)}`,
          description: "User described project architecture",
          type: "project",
          content: msg.content
        });
      }
    }
  }
  const seen = new Set;
  return insights.filter((i) => {
    const key = i.description.toLowerCase();
    if (seen.has(key))
      return false;
    seen.add(key);
    return true;
  }).slice(0, 10);
}
var MAX_TRANSCRIPT_SIZE = 200000, MAX_SESSIONS_TO_SCAN = 5, call = async (args, context) => {
  const memoryDir = getAutoMemPath();
  const progress = new ProgressTracker;
  progress.addStep("scan-transcripts", "\u626B\u63CF\u4F1A\u8BDD\u8BB0\u5F55");
  progress.addStep("load-memories", "\u52A0\u8F7D\u73B0\u6709\u8BB0\u5FC6");
  progress.addStep("extract-insights", "\u63D0\u53D6\u6D1E\u5BDF");
  progress.addStep("write-memories", "\u5199\u5165\u65B0\u8BB0\u5FC6");
  progress.addStep("checkpoint", "\u4FDD\u5B58\u68C0\u67E5\u70B9");
  try {
    progress.startStep("scan-transcripts", "\u6B63\u5728\u626B\u63CF\u6700\u8FD1\u7684\u4F1A\u8BDD\u8BB0\u5F55...");
    const transcripts = await scanRecentTranscripts();
    progress.completeStep("scan-transcripts", `\u627E\u5230 ${transcripts.length} \u4E2A\u4F1A\u8BDD\u8BB0\u5F55`);
    progress.startStep("load-memories", "\u6B63\u5728\u52A0\u8F7D\u73B0\u6709\u8BB0\u5FC6...");
    const existingMemories = await scanMemoryFiles(memoryDir, new AbortController().signal);
    const existingDescs = new Set(existingMemories.map((m) => m.description?.toLowerCase()).filter(Boolean));
    progress.completeStep("load-memories", `\u5DF2\u52A0\u8F7D ${existingMemories.length} \u6761\u73B0\u6709\u8BB0\u5FC6`);
    progress.startStep("extract-insights", "\u6B63\u5728\u4ECE\u4F1A\u8BDD\u4E2D\u63D0\u53D6\u6D1E\u5BDF...");
    const insights = extractInsights(transcripts);
    progress.completeStep("extract-insights", `\u63D0\u53D6\u4E86 ${insights.length} \u4E2A\u6D1E\u5BDF`);
    progress.completeStep("extract-insights", `\u63D0\u53D6\u4E86 ${insights.length} \u4E2A\u6D1E\u5BDF`);
    progress.startStep("write-memories", "\u6B63\u5728\u5199\u5165\u65B0\u8BB0\u5FC6...");
    let written = 0;
    for (const insight of insights) {
      if (existingDescs.has(insight.description.toLowerCase()))
        continue;
      const filename = `dream_${Date.now()}_${written}.md`;
      const content = `---
name: ${insight.title}
description: ${insight.description}
metadata:
  type: ${insight.type}
---

${insight.content}
`;
      try {
        await writeFile(join(memoryDir, filename), content, "utf-8");
        written++;
        progress.updateStep("write-memories", Math.round((written + 1) / insights.length * 100), `\u5DF2\u5199\u5165 ${written} \u6761\u65B0\u8BB0\u5FC6`);
      } catch (e) {
        logForDebugging(`dream: failed to write ${filename}: ${String(e)}`, {
          level: "warn"
        });
      }
    }
    progress.completeStep("write-memories", `\u5199\u5165\u4E86 ${written} \u6761\u65B0\u8BB0\u5FC6`);
    progress.startStep("checkpoint", "\u6B63\u5728\u4FDD\u5B58\u68C0\u67E5\u70B9...");
    const now = new Date().toISOString();
    await saveCheckpoint({
      title: `Dream consolidation - ${now}`,
      currentState: `Scanned ${transcripts.length} sessions, extracted ${written} new memories`,
      keyFiles: [],
      recentErrors: "",
      nextSteps: "Continue working",
      taskSummary: "",
      timestamp: now
    });
    progress.completeStep("checkpoint", "\u68C0\u67E5\u70B9\u5DF2\u4FDD\u5B58");
    const progressSummary = formatProgress(progress);
    return {
      type: "text",
      value: `${progressSummary}

\uD83D\uDCAD Dream complete!
- Scanned ${transcripts.length} recent sessions
- Extracted ${written} new memories
- Existing memories: ${existingMemories.length}`
    };
  } catch (e) {
    return { type: "text", value: `\u2717 Dream failed: ${String(e)}` };
  }
};
var init_dream = __esm(() => {
  init_paths();
  init_memoryScan();
  init_checkpoint();
  init_sessionStorage();
  init_debug();
  init_ProgressTracker();
});
init_dream();

export {
  call
};

//# debugId=AE522F667CC6186364756E2164756E21
//# sourceMappingURL=chunk-7fmztfrf.js.map
