cognitune 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +184 -41
  3. package/SETUP.md +111 -0
  4. package/dist/cli.js +161 -21
  5. package/dist/web/assets/Map-xBJDQ_Xn.js +1 -0
  6. package/dist/web/assets/{Practice-Xw4Aap9n.js → Practice-DNf-tMjl.js} +3 -3
  7. package/dist/web/assets/{_baseUniq-Sb6_kXmC.js → _baseUniq-7KLmbwxc.js} +1 -1
  8. package/dist/web/assets/{architectureDiagram-UYN6MBPD-x3eTjV-t.js → architectureDiagram-UYN6MBPD-DFK-K3Yp.js} +1 -1
  9. package/dist/web/assets/{blockDiagram-ZHA2E4KO-agwz5ZWE.js → blockDiagram-ZHA2E4KO-D9jSBc-F.js} +1 -1
  10. package/dist/web/assets/{c4Diagram-6F5ED5ID-CJxB9Ung.js → c4Diagram-6F5ED5ID-KAOALvx3.js} +1 -1
  11. package/dist/web/assets/channel-BW4MllLS.js +1 -0
  12. package/dist/web/assets/{chunk-5HRBRIJM-f0vN99nH.js → chunk-5HRBRIJM-Btr12S8H.js} +1 -1
  13. package/dist/web/assets/{chunk-7U56Z5CX-BM--ABPc.js → chunk-7U56Z5CX-NWMyaEQ0.js} +1 -1
  14. package/dist/web/assets/{chunk-ASOPGD6M-CR8uj1YE.js → chunk-ASOPGD6M-DdvxpUSZ.js} +1 -1
  15. package/dist/web/assets/{chunk-KFBOBJHC-5IsURXrq.js → chunk-KFBOBJHC-CLK5Qods.js} +1 -1
  16. package/dist/web/assets/{chunk-T2TOU4HS-Byx0enoR.js → chunk-T2TOU4HS-B-nrzheR.js} +1 -1
  17. package/dist/web/assets/{chunk-TMUBEWPD-BIF411CX.js → chunk-TMUBEWPD-DCsdC8PC.js} +1 -1
  18. package/dist/web/assets/classDiagram-LNE6IOMH-D4kEJsvG.js +1 -0
  19. package/dist/web/assets/classDiagram-v2-MQ7JQ4JX-D4kEJsvG.js +1 -0
  20. package/dist/web/assets/clone-C8mTbP7R.js +1 -0
  21. package/dist/web/assets/{dagre-4EVJKHTY-1RD8lskl.js → dagre-4EVJKHTY-D_09gC0H.js} +1 -1
  22. package/dist/web/assets/{diagram-QW4FP2JN-PO1Q65My.js → diagram-QW4FP2JN-quH5WQny.js} +1 -1
  23. package/dist/web/assets/{erDiagram-6RL3IURR-Cr2hBiWe.js → erDiagram-6RL3IURR-BmJHLDew.js} +1 -1
  24. package/dist/web/assets/{flowDiagram-7ASYPVHJ-ClDedrj1.js → flowDiagram-7ASYPVHJ-DNzT7Cua.js} +1 -1
  25. package/dist/web/assets/{ganttDiagram-NTVNEXSI-D13tzRyI.js → ganttDiagram-NTVNEXSI-6reJ1AIG.js} +1 -1
  26. package/dist/web/assets/{gitGraph-YCYPL57B-BsavMmM6.js → gitGraph-YCYPL57B-BfipSUJ3.js} +1 -1
  27. package/dist/web/assets/{gitGraphDiagram-NRZ2UAAF-DIucBoe8.js → gitGraphDiagram-NRZ2UAAF-BRb9bqzI.js} +1 -1
  28. package/dist/web/assets/{graph-CClVjaHZ.js → graph-BHXuL-RR.js} +1 -1
  29. package/dist/web/assets/{index-DBSUkj1m.js → index-7JDqNzz1.js} +1 -1
  30. package/dist/web/assets/{index-B3eGs35g.js → index-B49g1XNF.js} +1 -1
  31. package/dist/web/assets/{index-D91GOqgw.js → index-B5Tomqy6.js} +1 -1
  32. package/dist/web/assets/{index-D45gW5O5.js → index-BCM7jSxq.js} +1 -1
  33. package/dist/web/assets/{index-DRtWlWMo.js → index-BM9KwSU5.js} +1 -1
  34. package/dist/web/assets/{index-CS1X9Gl5.js → index-BiiiKqbq.js} +1 -1
  35. package/dist/web/assets/{index-2r9n9DTs.js → index-Bli4383n.js} +1 -1
  36. package/dist/web/assets/{index-CMZRuo_o.js → index-BsH1Ca5H.js} +1 -1
  37. package/dist/web/assets/{index-BqYXODG4.js → index-Bsf4UF_h.js} +1 -1
  38. package/dist/web/assets/{index-DxsK976j.js → index-C5JoMvch.js} +1 -1
  39. package/dist/web/assets/{index-DkYraAal.js → index-C67RtHfG.js} +1 -1
  40. package/dist/web/assets/{index-DDrV_F4m.js → index-CNViI9C2.js} +1 -1
  41. package/dist/web/assets/{index-BOSsA0NJ.js → index-CQjof-kk.js} +1 -1
  42. package/dist/web/assets/{index-ByIxB7D0.js → index-CyHGDhfc.js} +1 -1
  43. package/dist/web/assets/index-CyhIx47s.css +1 -0
  44. package/dist/web/assets/{index-B_vWzZYC.js → index-D-DY42g9.js} +1 -1
  45. package/dist/web/assets/{index-Cv-pFH6x.js → index-DRri1mnd.js} +1 -1
  46. package/dist/web/assets/{index-o9r5KATO.js → index-DXji-ikE.js} +1 -1
  47. package/dist/web/assets/{index-SjGg9_vE.js → index-D_DIS1os.js} +1 -1
  48. package/dist/web/assets/{index-DUIbUB4M.js → index-Dl6tJxzv.js} +1 -1
  49. package/dist/web/assets/{index-eIlS8nUF.js → index-TI1LWXRL.js} +1 -1
  50. package/dist/web/assets/index-dA5Y-R2D.js +514 -0
  51. package/dist/web/assets/{index-6LcRt5Lv.js → index-wnqHtEcu.js} +1 -1
  52. package/dist/web/assets/{index-Dls_C4WS.js → index-ysHMZpcw.js} +1 -1
  53. package/dist/web/assets/{infoDiagram-A4XQUW5V-DAnVWlAh.js → infoDiagram-A4XQUW5V-CE9eDiRA.js} +1 -1
  54. package/dist/web/assets/{journeyDiagram-G5WM74LC-pfkLfgwO.js → journeyDiagram-G5WM74LC-D_iPCzBK.js} +1 -1
  55. package/dist/web/assets/{kanban-definition-QRCXZQQD-ntmo18GF.js → kanban-definition-QRCXZQQD-Bxj-EOmZ.js} +1 -1
  56. package/dist/web/assets/{layout-B4CWy8Hm.js → layout-CQ6J22ew.js} +1 -1
  57. package/dist/web/assets/layout.worker-Bzrmqu8H.js +1 -0
  58. package/dist/web/assets/{mermaid.core-lBUDS75V.js → mermaid.core-27sLJoRM.js} +4 -4
  59. package/dist/web/assets/{min-DbZdLDS_.js → min-h0zR_W4w.js} +1 -1
  60. package/dist/web/assets/{mindmap-definition-GWI6TPTV-Bl9WyGjM.js → mindmap-definition-GWI6TPTV-DiBTVWc8.js} +28 -28
  61. package/dist/web/assets/{pieDiagram-YF2LJOPJ-DnH09lh-.js → pieDiagram-YF2LJOPJ-BE2VMHC3.js} +1 -1
  62. package/dist/web/assets/{quadrantDiagram-OS5C2QUG-BxEAU4LU.js → quadrantDiagram-OS5C2QUG-DkN-8Avj.js} +1 -1
  63. package/dist/web/assets/{requirementDiagram-MIRIMTAZ-QAvHb6Mc.js → requirementDiagram-MIRIMTAZ-0OCRbKti.js} +1 -1
  64. package/dist/web/assets/{sankeyDiagram-Y46BX6SQ-eS48EBnq.js → sankeyDiagram-Y46BX6SQ-6v9qBJFv.js} +1 -1
  65. package/dist/web/assets/{sequenceDiagram-G6AWOVSC-CzMqlsbJ.js → sequenceDiagram-G6AWOVSC-CjH7axp-.js} +1 -1
  66. package/dist/web/assets/{stateDiagram-MAYHULR4-xkap43Xx.js → stateDiagram-MAYHULR4-Bbbno_Ix.js} +1 -1
  67. package/dist/web/assets/stateDiagram-v2-4JROLMXI-CvrRdVH2.js +1 -0
  68. package/dist/web/assets/{timeline-definition-U7ZMHBDA-BAuokBbp.js → timeline-definition-U7ZMHBDA-BSIsFSlr.js} +1 -1
  69. package/dist/web/assets/{xychartDiagram-6QU3TZC5-Cnc3AQRt.js → xychartDiagram-6QU3TZC5-B12dxFiy.js} +1 -1
  70. package/dist/web/index.html +2 -2
  71. package/package.json +2 -1
  72. package/dist/web/assets/Map-DyU40kFC.js +0 -1
  73. package/dist/web/assets/channel-BBLQ9UF8.js +0 -1
  74. package/dist/web/assets/classDiagram-LNE6IOMH-BtyOxYYt.js +0 -1
  75. package/dist/web/assets/classDiagram-v2-MQ7JQ4JX-BtyOxYYt.js +0 -1
  76. package/dist/web/assets/clone-qT-pKr2u.js +0 -1
  77. package/dist/web/assets/index-Biw9rLAa.css +0 -1
  78. package/dist/web/assets/index-ChTnBaTd.js +0 -493
  79. package/dist/web/assets/stateDiagram-v2-4JROLMXI-T7PcvgVe.js +0 -1
package/dist/cli.js CHANGED
@@ -157,6 +157,15 @@ var FakeAgent = class {
157
157
  ]
158
158
  };
159
159
  }
160
+ case "lensMore": {
161
+ const q = /^FOLLOW-UP QUESTION: (.*)$/m.exec(prompt)?.[1] ?? "";
162
+ return {
163
+ answer: `Fake answer to "${q}": line 3 is where it happens.`,
164
+ deepDives: [{ title: "Line 3 answers the follow-up", file, line: 3, startLine: 2, endLine: 5, body: "The fake step for the follow-up." }],
165
+ concepts: [{ term: "Follow-up term", explain: "A term the first lesson did not define." }],
166
+ gotchas: ["Line 4 is easy to miss."]
167
+ };
168
+ }
160
169
  case "walkPlan":
161
170
  return { blocks: [1, 2].map((i) => ({ startLine: i, endLine: i + 2, title: `Block ${i} does one thing`, covers: ["a fact"], example: "n = 3", question: "what happens for n = 3?" })) };
162
171
  case "walkBlocks": {
@@ -1267,7 +1276,7 @@ function listFiles(root) {
1267
1276
  return;
1268
1277
  }
1269
1278
  for (const e of entries) {
1270
- if (e.name.startsWith(".") && e.name !== ".github") continue;
1279
+ if (e.name.startsWith(".") && e.name !== ".github" && e.name !== ".claude") continue;
1271
1280
  const p = join6(dir, e.name);
1272
1281
  if (e.isDirectory()) {
1273
1282
  if (!SKIP_DIRS.has(e.name)) walk2(p);
@@ -1922,6 +1931,42 @@ ${x.diff}
1922
1931
  ` : ""}${x.notes ? `THE LEARNER'S NOTES:
1923
1932
  ${x.notes}
1924
1933
 
1934
+ ` : ""}CODE:
1935
+ ${files}`;
1936
+ }
1937
+ function lensMoreSystem(depth = "standard") {
1938
+ const d = DEPTH[depth];
1939
+ return `TASK: lensMore
1940
+ You add to an existing "lens" (a lesson that teaches code). The learner read it and asked a FOLLOW-UP question.
1941
+ Answer that question, building on what the lesson already says; do not repeat it. If the answer needs code walked
1942
+ through, add new steps that point at real lines. If the question is about files that are new to the lesson, use them.
1943
+
1944
+ ${TEACH}
1945
+ ${STYLE}
1946
+
1947
+ JSON shape:
1948
+ {
1949
+ "answer": "markdown: the direct answer to the follow-up, 1-4 short paragraphs or a list",
1950
+ "deepDives": [{
1951
+ "title": "the idea of this step as a claim",
1952
+ "file": "relative/path", "startLine": 10, "endLine": 24, "line": 12, // a SHORT range (3-25 lines)
1953
+ "body": "markdown, up to ${d.words} words, in short paragraphs",
1954
+ "pitfall": "optional: a mistake people make here",
1955
+ "check": {"q": "a question that needs reasoning", "a": "the answer, 1-2 sentences"}
1956
+ }], // 0-4 items; empty when the answer alone is enough
1957
+ "concepts": [{"term": "name", "explain": "1-2 plain sentences", "example": "tiny example", "file": "relative/path", "line": 12}], // 0-3 terms the lesson does NOT already define
1958
+ "gotchas": ["a NEW trap, 1 sentence, with the line"] // 0-3 items, not already in the lesson
1959
+ }`;
1960
+ }
1961
+ function lensMorePrompt(question, lesson, files, notes) {
1962
+ return `FOLLOW-UP QUESTION: ${question}
1963
+
1964
+ THE LESSON SO FAR (do not repeat it):
1965
+ ${lesson}
1966
+
1967
+ ${notes ? `THE LEARNER'S NOTES:
1968
+ ${notes}
1969
+
1925
1970
  ` : ""}CODE:
1926
1971
  ${files}`;
1927
1972
  }
@@ -2037,11 +2082,14 @@ ${STYLE}
2037
2082
  JSON shape:
2038
2083
  { "score": 4, "summary": "1-2 sentences", "right": ["..."], "missing": ["..."], "wrong": ["..."] }`;
2039
2084
  }
2040
- function teachbackPrompt(text2, files) {
2085
+ function teachbackPrompt(text2, files, diff) {
2041
2086
  return `THE LEARNER'S EXPLANATION:
2042
2087
  ${text2}
2043
2088
 
2044
- CODE:
2089
+ ${diff ? `THE CHANGE THEY ARE EXPLAINING (unified diff):
2090
+ ${diff}
2091
+
2092
+ ` : ""}CODE:
2045
2093
  ${files}`;
2046
2094
  }
2047
2095
  function tutorSystem(level, tell) {
@@ -2057,7 +2105,7 @@ Return ONLY one JSON object inside a single \`\`\`json fence.
2057
2105
  JSON shape:
2058
2106
  { "reply": "markdown" }`;
2059
2107
  }
2060
- function tutorPrompt(history, files, notes) {
2108
+ function tutorPrompt(history, files, notes, diff) {
2061
2109
  const h = history.map((m) => `${m.role === "user" ? "LEARNER" : "TUTOR"}: ${m.text}`).join("\n\n");
2062
2110
  return `CONVERSATION SO FAR:
2063
2111
  ${h}
@@ -2065,6 +2113,9 @@ ${h}
2065
2113
  ${notes ? `THE LEARNER'S NOTES:
2066
2114
  ${notes}
2067
2115
 
2116
+ ` : ""}${diff ? `THE CHANGE BEING DISCUSSED (unified diff):
2117
+ ${diff}
2118
+
2068
2119
  ` : ""}CODE:
2069
2120
  ${files}`;
2070
2121
  }
@@ -2253,6 +2304,7 @@ var SCHEMAS = {
2253
2304
  }),
2254
2305
  lensIntro: z.object({ summary: text, intuition: text.optional() }),
2255
2306
  lensSteps: z.object({ steps: z.array(z.object({ body: text })).min(1) }),
2307
+ lensMore: z.object({ answer: text.min(1), deepDives: z.array(z.object({ title: text, body: text })).optional() }),
2256
2308
  plan: z.object({ outline: text.min(10) }),
2257
2309
  lensSketch: z.object({ differences: z.array(text).min(1) }),
2258
2310
  lensTrace: z.object({
@@ -2441,6 +2493,61 @@ ${old.deepDives.map((d) => `- ${d.title}`).join("\n")}` : void 0,
2441
2493
  if (old) this.store.archive(project.id, "lenses", old.id);
2442
2494
  return lens;
2443
2495
  }
2496
+ /**
2497
+ * A follow-up question on a lens, answered on top of it: the reply becomes a new follow-up section,
2498
+ * its new terms and traps join the lens's own lists, and any extra files join the lens.
2499
+ */
2500
+ async lensMore(project, id, req) {
2501
+ const ws = new Workspace(project);
2502
+ const l = this.store.get(project.id, "lenses", id);
2503
+ if (!l) throw new Error("lens not found");
2504
+ const question = (req.question ?? "").trim().slice(0, 4e3);
2505
+ if (!question) throw new Error("ask a question first");
2506
+ const extra = [...new Set((req.files ?? []).map((f) => ws.guard(f)))].filter((f) => !l.files.includes(f));
2507
+ const files = [...l.files, ...extra];
2508
+ const lesson = [
2509
+ `Title: ${l.title}`,
2510
+ l.tldr && `Idea: ${l.tldr}`,
2511
+ `Summary: ${l.summary}`,
2512
+ l.concepts.length && `Terms already defined: ${l.concepts.map((c) => c.term).join(", ")}`,
2513
+ `Steps:
2514
+ ${l.deepDives.map((d) => `- ${d.title}`).join("\n")}`,
2515
+ l.gotchas?.length && `Gotchas:
2516
+ ${l.gotchas.map((g) => `- ${g}`).join("\n")}`,
2517
+ ...(l.followUps ?? []).map((f) => `Earlier follow-up: ${f.question}
2518
+ Answer: ${f.answer.slice(0, 1200)}`)
2519
+ ].filter(Boolean).join("\n\n").slice(0, 12e3);
2520
+ const raw = await this.ask(
2521
+ ws,
2522
+ ["lensMore"],
2523
+ lensMoreSystem(l.depth),
2524
+ lensMorePrompt(question, lesson, this.bundle(ws, files), this.notes(ws, files))
2525
+ );
2526
+ const known = new Set(l.concepts.map((c) => c.term.toLowerCase()));
2527
+ const concepts = arr(raw.concepts).map((c) => {
2528
+ const o = c;
2529
+ return { term: str(o.term, 120), explain: str(o.explain), example: str(o.example, 1e3) || void 0, file: ws.absFromRel(str(o.file, 500)), line: num(o.line) };
2530
+ }).filter((c) => c.term && !known.has(c.term.toLowerCase())).slice(0, 3);
2531
+ const gotchas = strs(raw.gotchas, 400, 3).filter((g) => !l.gotchas?.includes(g));
2532
+ const next = {
2533
+ ...l,
2534
+ files,
2535
+ fileHashes: { ...this.hashes(ws, extra), ...l.fileHashes },
2536
+ concepts: [...l.concepts, ...concepts],
2537
+ gotchas: [...l.gotchas ?? [], ...gotchas],
2538
+ followUps: [
2539
+ ...l.followUps ?? [],
2540
+ {
2541
+ at: now(),
2542
+ question,
2543
+ files: extra,
2544
+ answer: str(raw.answer, 12e3),
2545
+ deepDives: arr(raw.deepDives).map((d) => cleanDive(d, ws)).filter((d) => d.title || d.body).slice(0, 4)
2546
+ }
2547
+ ]
2548
+ };
2549
+ return this.store.put(project.id, "lenses", next);
2550
+ }
2444
2551
  /**
2445
2552
  * A lens in parts instead of one call: the planner outlines (title, tldr, every step with its lines and
2446
2553
  * what it must cover), then the writer fills in the opening and the steps, a few steps per call, side by
@@ -2512,7 +2619,8 @@ ${old.deepDives.map((d) => `- ${d.title}`).join("\n")}` : void 0,
2512
2619
  async quiz(project, req) {
2513
2620
  const ws = new Workspace(project);
2514
2621
  const lens = req.lensId ? this.store.get(project.id, "lenses", req.lensId) : void 0;
2515
- const weak = req.weak ? openMisconceptions(this.store, project.id).slice(0, 6) : [];
2622
+ const pick = req.weakIds?.length ? new Set(req.weakIds) : void 0;
2623
+ const weak = req.weak ? openMisconceptions(this.store, project.id).filter((m) => !pick || pick.has(m.id)).slice(0, 6) : [];
2516
2624
  if (req.weak && !weak.length) throw new Error("no open weak spots: nothing to aim at yet");
2517
2625
  const weakFiles = weak.map((m) => m.file).filter((f) => !!f);
2518
2626
  const files = [...new Set((req.files.length ? req.files : lens?.files ?? weakFiles).map((f) => ws.guard(f)))];
@@ -2683,7 +2791,12 @@ ${this.bundle(ws, paths.filter((f) => DATA.test(f)))}` : "");
2683
2791
  if (!files.length) throw new Error("pick at least one file");
2684
2792
  const text2 = (req.text ?? "").trim().slice(0, 2e4);
2685
2793
  if (text2.length < 20) throw new Error("write a few sentences first");
2686
- const raw = await this.ask(ws, ["teachback"], teachbackSystem(), teachbackPrompt(text2, this.bundle(ws, files)));
2794
+ const raw = await this.ask(
2795
+ ws,
2796
+ ["teachback"],
2797
+ teachbackSystem(),
2798
+ teachbackPrompt(text2, this.bundle(ws, files), this.diffText(ws, req.diff, files))
2799
+ );
2687
2800
  const t = {
2688
2801
  id: newId(),
2689
2802
  projectId: project.id,
@@ -2691,6 +2804,7 @@ ${this.bundle(ws, paths.filter((f) => DATA.test(f)))}` : "");
2691
2804
  files,
2692
2805
  fileHashes: this.hashes(ws, files),
2693
2806
  text: text2,
2807
+ diff: req.diff,
2694
2808
  grade: {
2695
2809
  score: Math.min(5, Math.max(1, num(raw.score) ?? 1)),
2696
2810
  summary: str(raw.summary, 800),
@@ -2710,7 +2824,7 @@ ${this.bundle(ws, paths.filter((f) => DATA.test(f)))}` : "");
2710
2824
  if (!files.length) throw new Error("pick at least one file");
2711
2825
  const text2 = (req.text ?? "").trim();
2712
2826
  if (!text2) throw new Error("ask a question first");
2713
- const t = { id: newId(), projectId: project.id, createdAt: now(), title: text2.split("\n")[0].slice(0, 80), files, messages: [] };
2827
+ const t = { id: newId(), projectId: project.id, createdAt: now(), title: text2.split("\n")[0].slice(0, 80), files, diff: req.diff, messages: [] };
2714
2828
  return this.tutorTurn(project, t, text2, false);
2715
2829
  }
2716
2830
  async tutorReply(project, id, text2, tell) {
@@ -2724,7 +2838,12 @@ ${this.bundle(ws, paths.filter((f) => DATA.test(f)))}` : "");
2724
2838
  t.messages.push({ role: "user", text: text2.slice(0, 8e3), at: now() });
2725
2839
  const since = t.messages.slice(t.messages.map((m) => m.hintLevel === 4).lastIndexOf(true) + 1);
2726
2840
  const level = Math.min(3, since.filter((m) => m.role === "tutor").length + 1);
2727
- const raw = await this.ask(ws, ["tutor"], tutorSystem(level, tell), tutorPrompt(t.messages, this.bundle(ws, t.files), this.notes(ws, t.files)));
2841
+ const raw = await this.ask(
2842
+ ws,
2843
+ ["tutor"],
2844
+ tutorSystem(level, tell),
2845
+ tutorPrompt(t.messages, this.bundle(ws, t.files), this.notes(ws, t.files), this.diffText(ws, t.diff, t.files))
2846
+ );
2728
2847
  t.messages.push({ role: "tutor", text: str(raw.reply, 8e3), at: now(), hintLevel: tell ? 4 : level });
2729
2848
  if (t.messages.length > THREAD_MESSAGE_CAP) t.messages = [t.messages[0], ...t.messages.slice(-(THREAD_MESSAGE_CAP - 1))];
2730
2849
  return this.store.put(project.id, "threads", t);
@@ -3048,19 +3167,31 @@ function lensMarkdown(l, ws) {
3048
3167
  });
3049
3168
  out.push("");
3050
3169
  }
3051
- if (l.deepDives.length) {
3052
- out.push("## Deep dives", "");
3053
- for (const d of l.deepDives) {
3170
+ const dives = (list, h) => {
3171
+ for (const d of list) {
3054
3172
  const where = d.file ? ` (${ws.rel(d.file)}${d.startLine ? `:${d.startLine}-${d.endLine}` : d.line ? `:${d.line}` : ""})` : "";
3055
- out.push(`### ${d.title}${where}`, "", d.body, "");
3173
+ out.push(`${h} ${d.title}${where}`, "", d.body, "");
3056
3174
  if (d.pitfall) out.push(`> **Pitfall:** ${d.pitfall}`, "");
3057
3175
  if (d.check) out.push(`<details><summary>Check yourself: ${d.check.q}</summary>
3058
3176
 
3059
3177
  ${d.check.a}
3060
3178
  </details>`, "");
3061
3179
  }
3180
+ };
3181
+ if (l.deepDives.length) {
3182
+ out.push("## Deep dives", "");
3183
+ dives(l.deepDives, "###");
3062
3184
  }
3063
3185
  if (l.gotchas?.length) out.push("## Gotchas", "", ...l.gotchas.map((g) => `- ${g}`), "");
3186
+ if (l.followUps?.length) {
3187
+ out.push("## Follow-ups", "");
3188
+ for (const f of l.followUps) {
3189
+ out.push(`### ${f.question}`, "");
3190
+ if (f.files.length) out.push(`*Added context:* ${f.files.map((p) => `\`${ws.rel(p)}\``).join(", ")}`, "");
3191
+ out.push(f.answer, "");
3192
+ dives(f.deepDives, "####");
3193
+ }
3194
+ }
3064
3195
  if (l.nextSteps?.length) out.push("## Read next", "", ...l.nextSteps.map((n) => `- \`${ws.rel(n.file)}\`: ${n.why}`), "");
3065
3196
  return out.join("\n");
3066
3197
  }
@@ -3091,12 +3222,13 @@ function createApi(store2, opts2 = {}) {
3091
3222
  sweep();
3092
3223
  if (opts2.pruneEveryMs) setInterval(sweep, opts2.pruneEveryMs).unref();
3093
3224
  const graphs = /* @__PURE__ */ new Map();
3094
- const graphOf = (p) => {
3095
- const hit = graphs.get(p.id);
3096
- if (hit && Date.now() - hit.at < 6e4) return hit.g;
3097
- const g = new Workspace(p).graph();
3098
- graphs.set(p.id, { at: Date.now(), g });
3099
- return g;
3225
+ const graphOf = (p, refresh = false) => {
3226
+ let hit = graphs.get(p.id);
3227
+ if (!hit || refresh) {
3228
+ hit = { at: Date.now(), g: new Workspace(p).graph() };
3229
+ graphs.set(p.id, hit);
3230
+ }
3231
+ return { ...hit.g, builtAt: new Date(hit.at).toISOString() };
3100
3232
  };
3101
3233
  const hubs = (p) => graphOf(p).nodes.filter((n) => n.fanIn > 0).sort((a, b) => b.fanIn - a.fanIn).map((n) => n.path);
3102
3234
  const offline = () => new Learn(store2, { name: "none", complete: async () => "" });
@@ -3203,6 +3335,14 @@ function createApi(store2, opts2 = {}) {
3203
3335
  if (!store2.get(p.id, "lenses", id)) return fail(c, 404, "lens not found");
3204
3336
  return startJob(c, "lens", p, (l) => l.lens(p, { files: [], kind: "", refreshOf: id }));
3205
3337
  });
3338
+ api.post("/projects/:pid/lenses/:id/more", async (c) => {
3339
+ const p = project(c);
3340
+ const id = c.req.param("id");
3341
+ if (!store2.get(p.id, "lenses", id)) return fail(c, 404, "lens not found");
3342
+ const req = await body(c);
3343
+ if (!req.question?.trim()) return fail(c, 400, "ask a question first");
3344
+ return startJob(c, "lens", p, (l) => l.lensMore(p, id, { question: req.question, files: req.files }));
3345
+ });
3206
3346
  api.get("/projects/:pid/lenses/:id/export", (c) => {
3207
3347
  const p = project(c);
3208
3348
  const l = store2.get(p.id, "lenses", c.req.param("id"));
@@ -3318,13 +3458,13 @@ function createApi(store2, opts2 = {}) {
3318
3458
  api.post("/projects/:pid/teachbacks", async (c) => {
3319
3459
  const p = project(c);
3320
3460
  const req = await body(c);
3321
- return startJob(c, "teachback", p, (l) => l.teachback(p, { files: req.files ?? [], text: req.text ?? "" }));
3461
+ return startJob(c, "teachback", p, (l) => l.teachback(p, { files: req.files ?? [], text: req.text ?? "", diff: req.diff }));
3322
3462
  });
3323
3463
  crud("threads", "threads");
3324
3464
  api.post("/projects/:pid/threads", async (c) => {
3325
3465
  const p = project(c);
3326
3466
  const req = await body(c);
3327
- return startJob(c, "tutor", p, (l) => l.startThread(p, { files: req.files ?? [], text: req.text ?? "" }));
3467
+ return startJob(c, "tutor", p, (l) => l.startThread(p, { files: req.files ?? [], text: req.text ?? "", diff: req.diff }));
3328
3468
  });
3329
3469
  api.post("/projects/:pid/threads/:id/messages", async (c) => {
3330
3470
  const p = project(c);
@@ -3364,7 +3504,7 @@ function createApi(store2, opts2 = {}) {
3364
3504
  if (!store2.get(p.id, "hunts", id)) return fail(c, 404, "bug hunt not found");
3365
3505
  return startJob(c, "huntgrade", p, (l) => l.huntgrade(p, id));
3366
3506
  });
3367
- api.get("/projects/:pid/graph", (c) => c.json(graphOf(project(c))));
3507
+ api.get("/projects/:pid/graph", (c) => c.json(graphOf(project(c), c.req.query("refresh") === "1")));
3368
3508
  api.get("/projects/:pid/glossary", (c) => c.json(glossary(store2, project(c).id)));
3369
3509
  const pathView = (x) => ({ ...x, done: pathDone(store2, x) });
3370
3510
  crud("paths", "paths", pathView);
@@ -0,0 +1 @@
1
+ import{u as Q,a as ve,b as Me,c as Ne,d as $e,e as _,r as d,f as Se,j as t,S as Le,g as Re,B as Ie,R as qe,E as de,M as Be,G as Ee,F as Fe,h as We,i as ze,k as H}from"./index-dA5Y-R2D.js";const he=8,Oe=()=>({new:0,seen:0,understood:0,fading:0,stale:0});function me(n,l,j,k){var R,F;const f=l.nodes.map(r=>r.path).filter(r=>Q(n,r)),u=j.filter(r=>Q(n,r.path)),x=r=>{const a=u.find(I=>Q(I.path,r));if(a)return{key:a.path,kind:"repo"};const g=r.slice(n.length+1),w=g.indexOf("/");return w<0?{key:r,kind:"file"}:{key:`${n}/${g.slice(0,w)}`,kind:"dir"}},i=new Map;for(const r of f){const{key:a}=x(r);i.set(a,(i.get(a)??0)+1)}if(i.size===1){const[r]=i.keys();if(!f.includes(r)&&r!==n)return me(r,l,j,k)}const h=new Map;for(const r of f){const a=x(r);h.set(r,a.kind==="dir"&&(i.get(a.key)??0)<=he?{key:r,kind:"file"}:a)}const N=new Map;for(const[r,{key:a,kind:g}]of h){let w=N.get(a);w||N.set(a,w={id:a,label:a.slice(n.length+1),kind:g,files:0,fanIn:0,fanOut:0,counts:Oe()}),w.files++,w.counts[k.get(r)??"new"]++}const L=new Map;let m=0;for(const r of l.edges){const a=(R=h.get(r.from))==null?void 0:R.key,g=(F=h.get(r.to))==null?void 0:F.key;if(!a&&!g)continue;if(!a||!g){m++;continue}if(a===g)continue;const w=`${a}\0${g}`,I=L.get(w)??{from:a,to:g,weight:0};I.weight++,L.set(w,I)}for(const r of L.values())N.get(r.to).fanIn+=r.weight,N.get(r.from).fanOut+=r.weight;return{scope:n,nodes:[...N.values()],edges:[...L.values()],outside:m}}const B={new:"rgb(var(--muted) / 0.45)",seen:"rgb(var(--accent) / 0.45)",understood:"rgb(var(--good))",fading:"rgb(var(--warn) / 0.7)",stale:"rgb(var(--warn))"};function fe(n){const l=n.files-n.counts.new;return n.counts.stale?B.stale:n.counts.fading?B.fading:n.counts.understood*2>=n.files?B.understood:l?B.seen:B.new}const Z=n=>n.kind==="file"?Math.min(16,5+Math.sqrt(n.fanIn)*2.5):Math.min(34,10+Math.sqrt(n.files)*2.2);function Te(n,l){const j=d.useRef(null),k=d.useRef(0),[f,u]=d.useState(null);return d.useEffect(()=>{const x=new Worker(new URL("/assets/layout.worker-Bzrmqu8H.js",import.meta.url),{type:"module"});return j.current=x,x.onmessage=i=>i.data.id===k.current&&u(i.data),()=>x.terminate()},[]),d.useEffect(()=>{if(!j.current||!n.length)return;const x=++k.current;u(null);const i={id:x,nodes:n.map(h=>({id:h.id,r:Z(h)})),links:l.map(h=>({source:h.from,target:h.to,weight:h.weight}))};j.current.postMessage(i)},[n,l]),(f==null?void 0:f.pos)??null}function ue({text:n}){const l=[[-140,-60,22],[-40,-110,14],[70,-70,26],[160,-10,12],[110,80,18],[-10,40,30],[-120,70,16],[30,140,10],[-200,10,10]],j=[[0,5],[0,1],[1,2],[2,3],[2,5],[4,5],[5,6],[4,7],[6,8],[3,4]];return t.jsxs("div",{className:"relative h-full w-full bg-panel",children:[t.jsxs("svg",{className:"h-full w-full animate-pulse",viewBox:"-260 -180 520 360",children:[j.map(([k,f],u)=>t.jsx("line",{x1:l[k][0],y1:l[k][1],x2:l[f][0],y2:l[f][1],stroke:"rgb(var(--muted) / 0.18)",strokeWidth:1.5},u)),l.map(([k,f,u],x)=>t.jsx("rect",{x:k-u,y:f-u,width:u*2,height:u*2,rx:x%2?u:6,fill:"rgb(var(--muted) / 0.14)"},x))]}),t.jsx("div",{className:"absolute inset-0 grid place-items-center",children:t.jsx("div",{className:"rounded-full bg-raised/90 px-4 py-1.5 text-[13px] text-muted shadow-soft",children:n})})]})}function Ce(){var ne,re;const{project:n,setOpenFile:l,setSelected:j}=ve(),k=Me(),f=Ne(),[u,x]=$e(),i=n.root.replace(/\/$/,""),h=(u.get("in")??"").replace(/^\/+|\/+$/g,""),N=h?`${i}/${h}`:i,L=e=>x(e&&e!==i?{in:e.slice(i.length+1)}:{}),m=_({queryKey:["graph",n.id],queryFn:()=>H(`/projects/${n.id}/graph`),staleTime:1/0}),R=_({queryKey:["progress",n.id],queryFn:()=>H(`/projects/${n.id}/progress`)}),F=_({queryKey:["repos",n.id,n.contexts],queryFn:()=>H(`/projects/${n.id}/repos`)}),r=d.useMemo(()=>F.data??[],[F.data]),a=d.useMemo(()=>new Map((R.data??[]).map(e=>[e.path,e.level])),[R.data]),g=d.useMemo(()=>new Map((R.data??[]).map(e=>[e.path,e])),[R.data]),w=d.useMemo(()=>{var e;return(((e=m.data)==null?void 0:e.nodes)??[]).map(c=>c.path).filter(c=>Q(i,c))},[m.data,i]),I=d.useMemo(()=>r.length>1?Se(i,w,g,r).filter(e=>e.kind==="repo"):[],[r,i,w,g]),o=d.useMemo(()=>m.data?me(N,m.data,r,a):null,[m.data,N,r,a]),D=(o==null?void 0:o.scope)??N,W=Te((o==null?void 0:o.nodes)??[],(o==null?void 0:o.edges)??[]),[C,ee]=d.useState(!1),pe=async()=>{ee(!0);try{f.setQueryData(["graph",n.id],await H(`/projects/${n.id}/graph?refresh=1`))}finally{ee(!1)}},[p,z]=d.useState(null),[O,K]=d.useState({x:0,y:0,k:1}),S=d.useRef(null);d.useEffect(()=>{K({x:0,y:0,k:1}),z(null)},[D]);const xe=e=>{l(e),j([e]),k(`/p/${n.id}/explore`)},te=e=>e.kind==="file"?xe(e.id):L(e.id),ge=t.jsxs(Le,{className:"rounded-none border-x-0 border-t-0",root:i,rootLabel:n.name,scope:D,repos:r,repoRows:I,onScope:L,children:[((ne=m.data)==null?void 0:ne.builtAt)&&t.jsxs("span",{className:"text-[12px] text-muted",children:["imports read ",Re(m.data.builtAt)]}),t.jsx(Ie,{size:"sm",variant:"ghost",icon:t.jsx(qe,{className:C?"h-3.5 w-3.5 animate-spin":"h-3.5 w-3.5"}),disabled:C||m.isLoading,onClick:pe,children:"Refresh"})]});if(!m.isLoading&&!((re=m.data)!=null&&re.nodes.length))return t.jsx(de,{icon:t.jsx(Be,{className:"h-6 w-6"}),title:"No imports found",children:"The map reads import lines in TypeScript, JavaScript and Python files. This folder has none that point to other files in it."});const b=(o==null?void 0:o.nodes)??[],E=new Map(b.map(e=>[e.id,e])),G=new Set;if(p)for(const e of(o==null?void 0:o.edges)??[])e.from===p&&G.add(e.to),e.to===p&&G.add(e.from);const se=b.filter(e=>e.fanIn>0).sort((e,c)=>c.fanIn-e.fanIn||c.files-e.files).slice(0,12),we=new Set((b.length<=40?b:[...b].sort((e,c)=>c.fanIn+c.files-(e.fanIn+e.files)).slice(0,14)).map(e=>e.id)),J=e=>e.kind==="file"?e.label.split("/").pop():e.label,P=b.filter(e=>e.kind!=="file").length,U=b.length-P,ke=((o==null?void 0:o.edges)??[]).reduce((e,c)=>e+c.weight,0);let T;if(m.isLoading||C)T=t.jsx(ue,{text:C?"Reading imports again…":"Reading imports…"});else if(!b.length)T=t.jsx(de,{title:"Nothing to show",children:"No code files in here import, or are imported by, another file."});else if(!W)T=t.jsx(ue,{text:"Drawing the map…"});else{const e=b.map(s=>W[s.id]??[0,0]),c=e.map(s=>s[0]),X=e.map(s=>s[1]),oe=70,ae=Math.max(Math.max(...c)-Math.min(...c)+oe*2,420),ie=Math.max(Math.max(...X)-Math.min(...X)+oe*2,300),ye=(Math.max(...c)+Math.min(...c))/2,je=(Math.max(...X)+Math.min(...X))/2,A={x:ye-ae/2,y:je-ie/2,w:ae,h:ie},be=Math.max(1,...((o==null?void 0:o.edges)??[]).map(s=>s.weight));T=t.jsxs("div",{className:"relative h-full bg-panel",children:[t.jsxs("svg",{className:"h-full w-full cursor-grab active:cursor-grabbing",viewBox:`${A.x+O.x} ${A.y+O.y} ${A.w/O.k} ${A.h/O.k}`,onWheel:s=>K(v=>({...v,k:Math.min(8,Math.max(.3,v.k*(s.deltaY<0?1.15:1/1.15)))})),onMouseDown:s=>S.current={x:s.clientX,y:s.clientY,moved:!1},onMouseUp:()=>S.current=null,onMouseLeave:()=>S.current=null,onMouseMove:s=>{if(!S.current)return;const v=s.currentTarget.getBoundingClientRect(),$=A.w/O.k/v.width,y=(s.clientX-S.current.x)*$,q=(s.clientY-S.current.y)*$;S.current={x:s.clientX,y:s.clientY,moved:!0},K(M=>({...M,x:M.x-y,y:M.y-q}))},children:[t.jsxs("defs",{children:[t.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"5",markerHeight:"5",orient:"auto-start-reverse",children:t.jsx("path",{d:"M0,0 L10,5 L0,10 z",fill:"rgb(var(--muted) / 0.55)"})}),t.jsx("marker",{id:"arrow-on",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"5",markerHeight:"5",orient:"auto-start-reverse",children:t.jsx("path",{d:"M0,0 L10,5 L0,10 z",fill:"rgb(var(--accent))"})})]}),((o==null?void 0:o.edges)??[]).map(s=>{const v=E.get(s.from),$=E.get(s.to),[y,q]=W[v.id]??[0,0],[M,V]=W[$.id]??[0,0],le=Math.hypot(M-y,V-q)||1,ce=Z($)+3,Y=p===v.id||p===$.id;return t.jsx("line",{x1:y,y1:q,x2:M-(M-y)/le*ce,y2:V-(V-q)/le*ce,stroke:Y?"rgb(var(--accent))":"rgb(var(--muted) / 0.28)",strokeWidth:(Y?1.2:.8)+Math.log2(1+s.weight/be*15)*.8,markerEnd:Y?"url(#arrow-on)":"url(#arrow)",opacity:p&&!Y?.25:1,children:t.jsx("title",{children:`${J(v)} → ${J($)}: ${s.weight} import${s.weight===1?"":"s"}`})},`${s.from}>${s.to}`)}),b.map(s=>{const[v,$]=W[s.id]??[0,0],y=Z(s),q=p&&s.id!==p&&!G.has(s.id);return t.jsxs("g",{transform:`translate(${v},${$})`,opacity:q?.25:1,className:"cursor-pointer",onMouseEnter:()=>z(s.id),onMouseLeave:()=>z(null),onClick:()=>{var M;return!((M=S.current)!=null&&M.moved)&&te(s)},children:[s.kind==="file"?t.jsx("circle",{r:y,fill:s.counts.new?B.new:fe(s),stroke:"rgb(var(--panel))",strokeWidth:1.5}):t.jsx("rect",{x:-y,y:-y,width:y*2,height:y*2,rx:7,fill:fe(s),stroke:s.kind==="repo"?"rgb(var(--accent) / 0.7)":"rgb(var(--panel))",strokeWidth:s.kind==="repo"?2:1.5}),s.kind!=="file"&&t.jsx("text",{textAnchor:"middle",dy:"0.35em",fontSize:10,className:"fill-ink font-mono",opacity:.7,children:s.files}),(we.has(s.id)||s.id===p)&&t.jsxs("text",{y:-y-6,textAnchor:"middle",className:"fill-ink font-mono",fontSize:11,paintOrder:"stroke",stroke:"rgb(var(--panel))",strokeWidth:3,strokeLinejoin:"round",children:[J(s),s.kind!=="file"?"/":""]})]},s.id)})]}),t.jsxs("div",{className:"pointer-events-none absolute bottom-3 left-3 flex flex-wrap items-center gap-2 text-[12px] text-muted",children:[t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"h-2.5 w-2.5 rounded-[3px] border border-muted/50"}),"folder (number = files)"]}),t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"h-2.5 w-2.5 rounded-full border border-muted/50"}),"file"]}),["new","seen","understood","fading","stale"].map(s=>t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:B[s]}}),s==="new"?"not yet":s]},s)),t.jsx("span",{children:"· thicker arrow = more imports · click a folder to go in · scroll to zoom"})]}),p&&E.get(p)&&t.jsxs("div",{className:"absolute left-3 top-3 rounded-md bg-raised px-2 py-1 font-mono text-xs",children:[E.get(p).label,E.get(p).kind!=="file"&&` · ${E.get(p).files} files, click to open`]})]})}return t.jsxs("div",{className:"flex h-full flex-col",children:[ge,t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1",children:T}),t.jsxs("aside",{className:"w-[300px] shrink-0 overflow-auto border-l border-line bg-panel p-4",children:[t.jsx("h1",{className:"text-base font-semibold",children:"Map"}),t.jsx("p",{className:"text-xs text-muted",children:o?t.jsxs(t.Fragment,{children:[P>0&&`${P} ${I.length&&D===i?"repos and folders":"folders"}`,P>0&&U>0&&", ",U>0&&`${U} files`,", ",ke," imports between them.",o.outside>0&&` ${o.outside} more cross out of this view.`," Folders of ",he," files or fewer show their files."]}):"Reading the imports in TypeScript, JavaScript and Python files."}),se.length>0&&t.jsx("div",{className:"label mt-4",children:"Most depended on"}),t.jsx("ol",{className:"space-y-1",children:se.map(e=>t.jsx("li",{children:t.jsxs("button",{className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-left hover:bg-raised",onMouseEnter:()=>z(e.id),onMouseLeave:()=>z(null),onClick:()=>te(e),children:[e.kind==="repo"?t.jsx(Ee,{className:"h-3.5 w-3.5 shrink-0 text-accent"}):e.kind==="dir"?t.jsx(Fe,{className:"h-3.5 w-3.5 shrink-0 text-muted"}):t.jsx(We,{className:"h-3.5 w-3.5 shrink-0 text-muted"}),t.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[12.5px]",title:e.label,children:e.label}),t.jsx(ze,{children:e.fanIn})]})},e.id))})]})]})]})}export{Ce as MapPage};