@johnz4021/illuminate 0.1.0 → 0.2.0

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.
package/dist/cli.mjs CHANGED
@@ -21,7 +21,65 @@ var init_browser = __esm({
21
21
  }
22
22
  });
23
23
 
24
+ // packages/facts/src/facts/context.ts
25
+ function resolverOf(fn) {
26
+ return fn[KEY]?.() ?? null;
27
+ }
28
+ function attachResolver(fn, get) {
29
+ Object.defineProperty(fn, KEY, { value: get, enumerable: false, configurable: true });
30
+ return fn;
31
+ }
32
+ function carryResolver(fn, from) {
33
+ const get = from[KEY];
34
+ const root = rootOf(from);
35
+ if (root !== null) attachRoot(fn, root);
36
+ return get ? attachResolver(fn, get) : fn;
37
+ }
38
+ function attachRoot(fn, root) {
39
+ Object.defineProperty(fn, ROOT, { value: root, enumerable: false, configurable: true });
40
+ return fn;
41
+ }
42
+ var KEY, ROOT, rootOf;
43
+ var init_context = __esm({
44
+ "packages/facts/src/facts/context.ts"() {
45
+ "use strict";
46
+ KEY = Symbol.for("illuminate.repoResolver");
47
+ ROOT = Symbol.for("illuminate.repoRoot");
48
+ rootOf = (fn) => fn[ROOT] ?? null;
49
+ }
50
+ });
51
+
24
52
  // packages/facts/src/facts/diff.ts
53
+ function diffSymbols(before, after) {
54
+ const old = new Map(before.map((s) => [s.id, s]));
55
+ const now = new Map(after.map((s) => [s.id, s]));
56
+ const sig = [];
57
+ const body = [];
58
+ for (const s of after) {
59
+ const o = old.get(s.id);
60
+ if (!o) continue;
61
+ if (o.sigHash !== s.sigHash) sig.push(s.id);
62
+ else if (o.bodyHash !== s.bodyHash) body.push(s.id);
63
+ }
64
+ const removed = before.filter((s) => !now.has(s.id));
65
+ const added = after.filter((s) => !old.has(s.id));
66
+ const renamed = [];
67
+ const taken = /* @__PURE__ */ new Set();
68
+ for (const r of removed) {
69
+ const a = added.find((x) => !taken.has(x.id) && x.kind === r.kind && x.bodyHash === r.bodyHash);
70
+ if (!a) continue;
71
+ taken.add(a.id);
72
+ taken.add(r.id);
73
+ renamed.push([r.id, a.id]);
74
+ }
75
+ return {
76
+ added: added.filter((s) => !taken.has(s.id)).map((s) => s.id),
77
+ removed: removed.filter((s) => !taken.has(s.id)).map((s) => s.id),
78
+ sig,
79
+ body,
80
+ renamed
81
+ };
82
+ }
25
83
  var init_diff = __esm({
26
84
  "packages/facts/src/facts/diff.ts"() {
27
85
  "use strict";
@@ -619,34 +677,6 @@ var init_tables = __esm({
619
677
  }
620
678
  });
621
679
 
622
- // packages/facts/src/facts/context.ts
623
- function resolverOf(fn) {
624
- return fn[KEY]?.() ?? null;
625
- }
626
- function attachResolver(fn, get) {
627
- Object.defineProperty(fn, KEY, { value: get, enumerable: false, configurable: true });
628
- return fn;
629
- }
630
- function carryResolver(fn, from) {
631
- const get = from[KEY];
632
- const root = rootOf(from);
633
- if (root !== null) attachRoot(fn, root);
634
- return get ? attachResolver(fn, get) : fn;
635
- }
636
- function attachRoot(fn, root) {
637
- Object.defineProperty(fn, ROOT, { value: root, enumerable: false, configurable: true });
638
- return fn;
639
- }
640
- var KEY, ROOT, rootOf;
641
- var init_context = __esm({
642
- "packages/facts/src/facts/context.ts"() {
643
- "use strict";
644
- KEY = Symbol.for("illuminate.repoResolver");
645
- ROOT = Symbol.for("illuminate.repoRoot");
646
- rootOf = (fn) => fn[ROOT] ?? null;
647
- }
648
- });
649
-
650
680
  // packages/facts/src/imports.ts
651
681
  function normalizePath(path11) {
652
682
  const parts = [];
@@ -2083,6 +2113,7 @@ var init_entries = __esm({
2083
2113
  });
2084
2114
 
2085
2115
  // packages/facts/src/scan.ts
2116
+ import { execFileSync } from "node:child_process";
2086
2117
  import * as fs4 from "node:fs";
2087
2118
  function isCodeFile(path11) {
2088
2119
  return CODE_EXTENSIONS.some((ext) => path11.endsWith(ext));
@@ -2111,7 +2142,33 @@ function fileExistsIn(root) {
2111
2142
  }
2112
2143
  });
2113
2144
  }
2145
+ function gitFiles(root) {
2146
+ let out;
2147
+ try {
2148
+ out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
2149
+ cwd: root,
2150
+ encoding: "utf8",
2151
+ maxBuffer: 512 * 1024 * 1024,
2152
+ stdio: ["ignore", "pipe", "ignore"]
2153
+ });
2154
+ } catch {
2155
+ return null;
2156
+ }
2157
+ const files = out.split("\0").filter(Boolean);
2158
+ return files.length ? files : null;
2159
+ }
2114
2160
  function listRepoFiles(root, ignore = DEFAULT_IGNORE) {
2161
+ const listed = gitFiles(root);
2162
+ if (listed) {
2163
+ return listed.filter((path11) => {
2164
+ if (path11.split("/").some((seg) => seg === "node_modules" || seg === ".git") || matchesAny(ignore, path11)) return false;
2165
+ try {
2166
+ return fs4.lstatSync(`${root}/${path11}`).isFile();
2167
+ } catch {
2168
+ return false;
2169
+ }
2170
+ }).sort();
2171
+ }
2115
2172
  const files = [];
2116
2173
  const walk = (dir) => {
2117
2174
  for (const entry of fs4.readdirSync(dir ? `${root}/${dir}` : root, { withFileTypes: true })) {
@@ -2200,7 +2257,19 @@ var init_scan = __esm({
2200
2257
  init_glob();
2201
2258
  init_imports();
2202
2259
  CODE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts"];
2203
- DEFAULT_IGNORE = [".illuminate/**", ".codemap/**", "**/dist/**", "**/build/**", "**/coverage/**", "**/.next/**"];
2260
+ DEFAULT_IGNORE = [
2261
+ ".illuminate/**",
2262
+ ".codemap/**",
2263
+ "**/dist/**",
2264
+ "**/build/**",
2265
+ "**/coverage/**",
2266
+ "**/.next/**",
2267
+ // Installed packages, for repos that aren't in git (in git, ignored files are never listed).
2268
+ "**/venv/**",
2269
+ "**/.venv/**",
2270
+ "**/site-packages/**",
2271
+ "**/__pycache__/**"
2272
+ ];
2204
2273
  isTreeSitterFile = (path11) => treeSitterLang(path11) !== null && treeSitterReady();
2205
2274
  }
2206
2275
  });
@@ -2209,6 +2278,7 @@ var init_scan = __esm({
2209
2278
  var init_src = __esm({
2210
2279
  "packages/facts/src/index.ts"() {
2211
2280
  "use strict";
2281
+ init_context();
2212
2282
  init_diff();
2213
2283
  init_extract();
2214
2284
  init_hash();
@@ -2248,26 +2318,57 @@ function parseMap(input) {
2248
2318
  const edges = ids("edge", map.edges);
2249
2319
  const absences = ids("absence", map.absences);
2250
2320
  ids("tour stop", map.tour);
2251
- const evidence = (where, list) => {
2252
- for (const e of list) if (!isSafeRelativePath(e.file)) problems.push(`${where}: evidence file "${e.file}" must be a path inside the repo`);
2321
+ const evidence = (where, item) => {
2322
+ if (!item.evidence.length && !isAddition(item)) problems.push(`${where}: cite at least one line of code in \`evidence\` (only a proposed addition goes without)`);
2323
+ for (const e of item.evidence) if (!isSafeRelativePath(e.file)) problems.push(`${where}: evidence file "${e.file}" must be a path inside the repo`);
2324
+ };
2325
+ const added = new Set(map.nodes.filter(isAddition).map((n) => n.id));
2326
+ const removed = new Set(map.nodes.filter((n) => n.removed).map((n) => n.id));
2327
+ const gone = (where, item) => {
2328
+ if (!item.removed) return;
2329
+ if (!map.since) problems.push(`${where}: \`removed\` needs the map's \`since\` (the commit it was removed after)`);
2330
+ if (item.proposed) problems.push(`${where}: it can't be both \`removed\` (already gone) and \`proposed\` (not done yet)`);
2253
2331
  };
2254
2332
  for (const n of map.nodes) {
2255
2333
  if (!areas.has(n.area)) problems.push(`node "${n.id}": unknown area "${n.area}"`);
2256
2334
  if (n.symbol && !isSafeRelativePath(n.symbol.slice(0, n.symbol.indexOf("#")))) problems.push(`node "${n.id}": symbol file must be a path inside the repo`);
2257
- evidence(`node "${n.id}"`, n.evidence);
2335
+ evidence(`node "${n.id}"`, n);
2258
2336
  const sc = n.screen;
2259
2337
  if (sc?.kind === "capture" && !sc.capture) problems.push(`node "${n.id}": a capture screen needs the \`capture\` id illuminate_capture returned`);
2260
2338
  if (sc && sc.kind !== "capture" && (!sc.file || !isSafeRelativePath(sc.file))) problems.push(`node "${n.id}": a ${sc.kind} screen needs \`file\`, a path inside the repo`);
2261
2339
  if (sc?.kind === "sketch" && !sc.elements) problems.push(`node "${n.id}": a sketch screen needs \`elements\``);
2340
+ if (!n.proposed && sc?.elements?.some((e) => e.proposed)) problems.push(`node "${n.id}": only a box that carries \`proposed\` can have proposed screen elements`);
2341
+ gone(`node "${n.id}"`, n);
2262
2342
  }
2263
2343
  for (const e of map.edges) {
2264
2344
  if (!nodes.has(e.from)) problems.push(`edge "${e.id}": unknown node "${e.from}"`);
2265
2345
  if (!nodes.has(e.to)) problems.push(`edge "${e.id}": unknown node "${e.to}"`);
2266
- evidence(`edge "${e.id}"`, e.evidence);
2346
+ evidence(`edge "${e.id}"`, e);
2347
+ const end = [e.from, e.to].find((id) => added.has(id));
2348
+ if (end && !isAddition(e)) problems.push(`edge "${e.id}": box "${end}" is a proposed addition, so an arrow to or from it must be one too (\`proposed\`: { "kind": "add" })`);
2349
+ gone(`edge "${e.id}"`, e);
2350
+ const wasAt = [e.from, e.to].find((id) => removed.has(id));
2351
+ if (wasAt && !e.removed) problems.push(`edge "${e.id}": box "${wasAt}" was removed, so an arrow to or from it was removed too (\`removed\`: true)`);
2352
+ }
2353
+ if (added.size) {
2354
+ const anchored = new Set(map.nodes.filter((n) => !added.has(n.id)).map((n) => n.id));
2355
+ for (let grew = true; grew; ) {
2356
+ grew = false;
2357
+ for (const e of map.edges) {
2358
+ if (anchored.has(e.from) === anchored.has(e.to)) continue;
2359
+ anchored.add(e.from).add(e.to);
2360
+ grew = true;
2361
+ }
2362
+ }
2363
+ for (const id of added) if (nodes.has(id) && !anchored.has(id)) problems.push(`node "${id}": a proposed box must connect, through arrows, to a box that exists in the code`);
2267
2364
  }
2268
2365
  for (const a of map.absences) {
2269
2366
  if (a.between && !nodes.has(a.between.from)) problems.push(`absence "${a.id}": unknown node "${a.between.from}"`);
2270
2367
  if (a.between && !nodes.has(a.between.to)) problems.push(`absence "${a.id}": unknown node "${a.between.to}"`);
2368
+ const end = a.between && [a.between.from, a.between.to].find((id) => added.has(id));
2369
+ if (end) problems.push(`absence "${a.id}": box "${end}" is a proposed addition; an absence is about the code as it is`);
2370
+ const was = a.between && [a.between.from, a.between.to].find((id) => removed.has(id));
2371
+ if (was) problems.push(`absence "${a.id}": box "${was}" was removed; an absence is about the code as it is`);
2271
2372
  }
2272
2373
  for (const t of map.tour) {
2273
2374
  const refs = [
@@ -2280,7 +2381,7 @@ function parseMap(input) {
2280
2381
  }
2281
2382
  return problems.length ? { ok: false, problems } : { ok: true, map };
2282
2383
  }
2283
- var Id, Evidence, NodeKind, EdgeKind, ScreenElement, Screen, Area, Node, Edge, Absence, TourStop, CodeMap;
2384
+ var Id, Evidence, NodeKind, EdgeKind, ScreenElement, Screen, Proposal, GitRef, Area, Node, Edge, Absence, TourStop, CodeMap, isAddition;
2284
2385
  var init_format = __esm({
2285
2386
  "packages/core/src/format.ts"() {
2286
2387
  "use strict";
@@ -2290,9 +2391,14 @@ var init_format = __esm({
2290
2391
  line: z.number().int().positive(),
2291
2392
  text: z.string().min(1).max(400)
2292
2393
  });
2293
- NodeKind = z.enum(["entry", "step", "store", "external", "job"]);
2394
+ NodeKind = z.enum(["entry", "step", "store", "external", "job", "screen", "action", "choice"]);
2294
2395
  EdgeKind = z.enum(["calls", "request", "imports", "then"]);
2295
- ScreenElement = z.object({ kind: z.enum(["heading", "button", "field", "link", "text", "image"]), text: z.string().min(1).max(80) });
2396
+ ScreenElement = z.object({
2397
+ kind: z.enum(["heading", "button", "field", "link", "text", "image"]),
2398
+ text: z.string().min(1).max(80),
2399
+ /** Not on the screen yet: something a proposal would put there. Only on a box that carries `proposed`. */
2400
+ proposed: z.boolean().optional()
2401
+ });
2296
2402
  Screen = z.object({
2297
2403
  kind: z.enum(["capture", "image", "sketch"]),
2298
2404
  capture: Id.optional(),
@@ -2300,6 +2406,12 @@ var init_format = __esm({
2300
2406
  elements: z.array(ScreenElement).min(1).max(12).optional(),
2301
2407
  highlight: z.string().min(1).max(80).optional()
2302
2408
  });
2409
+ Proposal = z.object({
2410
+ kind: z.enum(["add", "change", "remove"]),
2411
+ /** What would change and why, in a plain sentence. */
2412
+ note: z.string().min(1).max(300).optional()
2413
+ });
2414
+ GitRef = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_./~^-]{0,99}$/, 'a commit, branch or tag name, e.g. "HEAD"');
2303
2415
  Area = z.object({ id: Id, label: z.string().min(1).max(40) });
2304
2416
  Node = z.object({
2305
2417
  id: Id,
@@ -2309,8 +2421,12 @@ var init_format = __esm({
2309
2421
  /** `<file>#<symbol>` as the facts name it, e.g. `src/patients/service.ts#markConverted`. */
2310
2422
  symbol: z.string().regex(/^[^#]+#.+$/, "symbol is <file>#<name>").optional(),
2311
2423
  explain: z.object({ concept: z.string(), how: z.string(), code: z.string() }).partial().optional(),
2312
- evidence: z.array(Evidence).min(1),
2313
- screen: Screen.optional()
2424
+ /** At least one line, except on a proposed addition (`parseMap` enforces it). */
2425
+ evidence: z.array(Evidence).default([]),
2426
+ screen: Screen.optional(),
2427
+ proposed: Proposal.optional(),
2428
+ /** Only on a map with `since`: this code was there at that commit and is gone now. Its `evidence` cites it as it was. */
2429
+ removed: z.boolean().optional()
2314
2430
  });
2315
2431
  Edge = z.object({
2316
2432
  id: Id,
@@ -2318,7 +2434,11 @@ var init_format = __esm({
2318
2434
  to: Id,
2319
2435
  kind: EdgeKind.default("then"),
2320
2436
  label: z.string().min(1).max(60),
2321
- evidence: z.array(Evidence).min(1)
2437
+ /** At least one line, except on a proposed addition (`parseMap` enforces it). */
2438
+ evidence: z.array(Evidence).default([]),
2439
+ proposed: Proposal.optional(),
2440
+ /** Only on a map with `since`: this connection was there at that commit and is gone now. Its `evidence` cites it as it was. */
2441
+ removed: z.boolean().optional()
2322
2442
  });
2323
2443
  Absence = z.object({
2324
2444
  id: Id,
@@ -2351,12 +2471,21 @@ var init_format = __esm({
2351
2471
  question: z.string().min(1).max(300),
2352
2472
  /** The commit the map was made from, when known. */
2353
2473
  commit: z.string().nullable().optional(),
2474
+ /** `journey`: drawn as a user flow (left to right, shapes by kind, no code on the boxes). The claims are checked the same. */
2475
+ view: z.enum(["journey"]).optional(),
2476
+ /**
2477
+ * Set on a map of a change: the commit the code is compared with. The checker marks each box and arrow that is new
2478
+ * or different since then, and confirms the ones the map says were `removed`. Stored as a full hash once resolved,
2479
+ * so the comparison stays the same after later commits.
2480
+ */
2481
+ since: GitRef.optional(),
2354
2482
  areas: z.array(Area).min(1),
2355
2483
  nodes: z.array(Node).min(1),
2356
2484
  edges: z.array(Edge).default([]),
2357
2485
  absences: z.array(Absence).default([]),
2358
2486
  tour: z.array(TourStop).default([])
2359
2487
  });
2488
+ isAddition = (x) => x.proposed?.kind === "add";
2360
2489
  }
2361
2490
  });
2362
2491
 
@@ -2480,9 +2609,123 @@ var init_repo = __esm({
2480
2609
  }
2481
2610
  });
2482
2611
 
2612
+ // packages/core/src/base.ts
2613
+ import { execFileSync as execFileSync2 } from "node:child_process";
2614
+ import * as fs6 from "node:fs";
2615
+ function resolveCommit(root, ref) {
2616
+ if (!GitRef.safeParse(ref).success) return null;
2617
+ const out = git(root, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`])?.trim();
2618
+ return out && /^[0-9a-f]{40,64}$/.test(out) ? out : null;
2619
+ }
2620
+ function commitInfo(root, commit) {
2621
+ const out = git(root, ["show", "-s", "--format=%cI%x00%s", "--end-of-options", commit])?.trim();
2622
+ if (!out) return { date: null, subject: null };
2623
+ const [date, subject] = out.split("\0");
2624
+ return { date: date || null, subject: subject || null };
2625
+ }
2626
+ function createBaseReader(root, ref) {
2627
+ const realRoot = fs6.realpathSync(root);
2628
+ const commit = resolveCommit(realRoot, ref);
2629
+ if (!commit) return null;
2630
+ let files = null;
2631
+ const has = (rel) => (files ??= new Set((git(realRoot, ["ls-tree", "-r", "--name-only", "-z", commit]) ?? "").split("\0").filter(Boolean))).has(rel);
2632
+ const cache2 = /* @__PURE__ */ new Map();
2633
+ const readUncached = (rel) => {
2634
+ if (!isSafeRelativePath(rel)) return { ok: false, reason: "path is outside the repo" };
2635
+ if (isSecretPath(rel)) return { ok: false, reason: "secret files are never read" };
2636
+ if (!has(rel)) return { ok: false, reason: "file not found" };
2637
+ const text2 = git(realRoot, ["show", `${commit}:./${rel}`]);
2638
+ if (text2 === null) return { ok: false, reason: "file not found" };
2639
+ if (text2.length > MAX_FILE_BYTES) return { ok: false, reason: "file is too large to check" };
2640
+ if (text2.slice(0, 8e3).includes("\0")) return { ok: false, reason: "binary file" };
2641
+ return { ok: true, text: text2 };
2642
+ };
2643
+ const read = (rel) => {
2644
+ let hit = cache2.get(rel);
2645
+ if (!hit) cache2.set(rel, hit = readUncached(rel));
2646
+ return hit;
2647
+ };
2648
+ return { root: realRoot, commit, has, read, text: (rel) => {
2649
+ const r = read(rel);
2650
+ return r.ok ? r.text : null;
2651
+ } };
2652
+ }
2653
+ function lineDiff(before, after, context = 2, max = 60) {
2654
+ const a = before.split("\n");
2655
+ const b = after.split("\n");
2656
+ let start = 0;
2657
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
2658
+ let endA = a.length;
2659
+ let endB = b.length;
2660
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
2661
+ endA--;
2662
+ endB--;
2663
+ }
2664
+ const n = endA - start;
2665
+ const m = endB - start;
2666
+ if (n * m > 1e6) return null;
2667
+ const lcs = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
2668
+ for (let i = n - 1; i >= 0; i--) {
2669
+ for (let j = m - 1; j >= 0; j--) {
2670
+ lcs[i][j] = a[start + i] === b[start + j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
2671
+ }
2672
+ }
2673
+ const ops = a.slice(0, start).map((l) => [" ", l]);
2674
+ for (let i = 0, j = 0; i < n || j < m; ) {
2675
+ if (i < n && j < m && a[start + i] === b[start + j]) {
2676
+ ops.push([" ", a[start + i]]);
2677
+ i++;
2678
+ j++;
2679
+ } else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) {
2680
+ ops.push(["-", a[start + i]]);
2681
+ i++;
2682
+ } else {
2683
+ ops.push(["+", b[start + j]]);
2684
+ j++;
2685
+ }
2686
+ }
2687
+ for (const l of a.slice(endA)) ops.push([" ", l]);
2688
+ const keep = ops.map(() => false);
2689
+ ops.forEach(([op], i) => {
2690
+ if (op === " ") return;
2691
+ for (let k = Math.max(0, i - context); k <= Math.min(ops.length - 1, i + context); k++) keep[k] = true;
2692
+ });
2693
+ const out = [];
2694
+ let skipped = false;
2695
+ for (const [i, [op, line]] of ops.entries()) {
2696
+ if (!keep[i]) {
2697
+ skipped = true;
2698
+ continue;
2699
+ }
2700
+ if (skipped && out.length) out.push("\u2026");
2701
+ skipped = false;
2702
+ if (out.length >= max) {
2703
+ out.push("\u2026");
2704
+ break;
2705
+ }
2706
+ out.push(`${op === " " ? " " : `${op} `}${line}`);
2707
+ }
2708
+ return out;
2709
+ }
2710
+ var git;
2711
+ var init_base = __esm({
2712
+ "packages/core/src/base.ts"() {
2713
+ "use strict";
2714
+ init_format();
2715
+ init_repo();
2716
+ git = (root, args) => {
2717
+ try {
2718
+ return execFileSync2("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).toString();
2719
+ } catch {
2720
+ return null;
2721
+ }
2722
+ };
2723
+ }
2724
+ });
2725
+
2483
2726
  // packages/core/src/screens.ts
2484
2727
  import * as crypto from "node:crypto";
2485
- import * as fs6 from "node:fs";
2728
+ import * as fs7 from "node:fs";
2486
2729
  import * as path3 from "node:path";
2487
2730
  import { z as z2 } from "zod";
2488
2731
  function readCapture(root, id) {
@@ -2490,7 +2733,7 @@ function readCapture(root, id) {
2490
2733
  const p = capturePaths(root, id);
2491
2734
  let capture2;
2492
2735
  try {
2493
- const parsed = Capture.safeParse(JSON.parse(fs6.readFileSync(p.record, "utf8")));
2736
+ const parsed = Capture.safeParse(JSON.parse(fs7.readFileSync(p.record, "utf8")));
2494
2737
  if (!parsed.success || parsed.data.id !== id) return { ok: false, reason: `the record of capture ${id} can't be read` };
2495
2738
  capture2 = parsed.data;
2496
2739
  } catch {
@@ -2498,7 +2741,7 @@ function readCapture(root, id) {
2498
2741
  }
2499
2742
  let image;
2500
2743
  try {
2501
- image = fs6.readFileSync(p.image);
2744
+ image = fs7.readFileSync(p.image);
2502
2745
  } catch {
2503
2746
  return { ok: false, reason: `the image of capture ${id} is missing` };
2504
2747
  }
@@ -2510,15 +2753,15 @@ function repoImage(root, rel) {
2510
2753
  if (isSecretPath(rel)) return { ok: false, reason: "secret files are never shown" };
2511
2754
  const type = IMAGE_TYPES[path3.extname(rel).toLowerCase()];
2512
2755
  if (!type) return { ok: false, reason: `${rel} is not an image file` };
2513
- const realRoot = fs6.realpathSync(root);
2756
+ const realRoot = fs7.realpathSync(root);
2514
2757
  let real;
2515
2758
  try {
2516
- real = fs6.realpathSync(path3.join(realRoot, rel));
2759
+ real = fs7.realpathSync(path3.join(realRoot, rel));
2517
2760
  } catch {
2518
2761
  return { ok: false, reason: `${rel} doesn't exist` };
2519
2762
  }
2520
2763
  if (!real.startsWith(realRoot + path3.sep)) return { ok: false, reason: `${rel} is outside the repo` };
2521
- const stat = fs6.statSync(real);
2764
+ const stat = fs7.statSync(real);
2522
2765
  if (!stat.isFile()) return { ok: false, reason: `${rel} is not a file` };
2523
2766
  if (stat.size > MAX_IMAGE_BYTES) return { ok: false, reason: `${rel} is too large to show` };
2524
2767
  return { ok: true, path: real, type };
@@ -2558,12 +2801,14 @@ function checkScreen(n, repo) {
2558
2801
  return { status: "confirmed", reasons: [], show: { kind: "image", file } };
2559
2802
  }
2560
2803
  const read = repo.read(file);
2561
- if (!read.ok) return fail(`${file}: ${read.reason}`);
2562
- const text2 = norm(read.text);
2563
- const elements = sc.elements ?? [];
2564
- const missing = elements.filter((e) => !text2.includes(norm(e.text)));
2804
+ const adding = isAddition(n);
2805
+ if (!read.ok && !adding) return fail(`${file}: ${read.reason}`);
2806
+ const text2 = read.ok ? norm(read.text) : "";
2807
+ const written = sc.elements ?? [];
2808
+ const missing = written.filter((e) => !(adding || e.proposed) && !text2.includes(norm(e.text)));
2565
2809
  if (missing.length) return fail(...missing.map((e) => `"${e.text}" isn't in ${file}`));
2566
- if (sc.highlight && !elements.some((e) => norm(e.text) === norm(sc.highlight))) return fail(`the highlight "${sc.highlight}" isn't one of the sketch's elements`);
2810
+ if (sc.highlight && !written.some((e) => norm(e.text) === norm(sc.highlight))) return fail(`the highlight "${sc.highlight}" isn't one of the sketch's elements`);
2811
+ const elements = written.map((e) => ({ kind: e.kind, text: e.text, ...text2.includes(norm(e.text)) ? {} : { proposed: true } }));
2567
2812
  return { status: "confirmed", reasons: [], show: { kind: "sketch", file, elements, highlight: sc.highlight ?? null } };
2568
2813
  }
2569
2814
  var SCREENS_DIR, IMAGE_TYPES, MAX_IMAGE_BYTES, CAPTURE_ID, CapturedElement, Capture, norm, capturePaths;
@@ -2608,14 +2853,17 @@ var init_screens = __esm({
2608
2853
  function check(map, root, options = {}) {
2609
2854
  const repo = createRepoReader(root);
2610
2855
  const window = options.lineWindow ?? 3;
2611
- const facts = factsFor(repo);
2856
+ const now = { repo, facts: factsFor(repo, fileExistsIn(repo.root)) };
2857
+ const baseRepo = map.since ? createBaseReader(repo.root, map.since) : null;
2858
+ const base = baseRepo && { repo: baseRepo, facts: factsFor(baseRepo, carryResolver((p) => baseRepo.has(p), fileExistsIn(repo.root))) };
2859
+ const cmp = map.since ? { ref: map.since, base } : null;
2612
2860
  const byId = new Map(map.nodes.map((n) => [n.id, n]));
2613
2861
  let repoFiles = null;
2614
2862
  const files = () => repoFiles ??= listRepoFiles(repo.root, [...DEFAULT_IGNORE, ...options.ignore ?? []]).filter((f) => !isSecretPath(f));
2615
2863
  const nodes = {};
2616
- for (const n of map.nodes) nodes[n.id] = checkNode(n, repo, facts, window);
2864
+ for (const n of map.nodes) nodes[n.id] = checkNode(n, now, cmp, window);
2617
2865
  const edges = {};
2618
- for (const e of map.edges) edges[e.id] = checkEdge(e, byId, repo, facts, window);
2866
+ for (const e of map.edges) edges[e.id] = checkEdge(e, byId, now, cmp, window);
2619
2867
  const absences = {};
2620
2868
  for (const a of map.absences) absences[a.id] = checkAbsence(a, repo, files());
2621
2869
  const screens = {};
@@ -2625,19 +2873,41 @@ function check(map, root, options = {}) {
2625
2873
  }
2626
2874
  const tour = {};
2627
2875
  for (const t of map.tour) {
2628
- const unconfirmed = [
2629
- ...(t.focus.nodes ?? []).filter((id) => nodes[id]?.status !== "confirmed"),
2630
- ...(t.focus.edges ?? []).filter((id) => edges[id]?.status !== "confirmed"),
2876
+ const unconfirmed2 = [
2877
+ ...(t.focus.nodes ?? []).filter((id) => nodes[id]?.status === "unconfirmed"),
2878
+ ...(t.focus.edges ?? []).filter((id) => edges[id]?.status === "unconfirmed"),
2631
2879
  ...(t.focus.absences ?? []).filter((id) => absences[id]?.status !== "confirmed")
2632
2880
  ];
2633
- tour[t.id] = { status: unconfirmed.length ? "mentions-unconfirmed" : "ok", unconfirmed };
2881
+ tour[t.id] = { status: unconfirmed2.length ? "mentions-unconfirmed" : "ok", unconfirmed: unconfirmed2 };
2634
2882
  }
2635
2883
  const all = [...Object.values(nodes), ...Object.values(edges), ...Object.values(absences)];
2636
- const confirmed = all.filter((c) => c.status === "confirmed").length;
2637
- return { nodes, edges, absences, tour, screens, summary: { claims: all.length, confirmed, unconfirmed: all.length - confirmed } };
2884
+ const count = (status) => all.filter((c) => c.status === status).length;
2885
+ const proposals = [...Object.values(nodes), ...Object.values(edges)].flatMap((c) => c.proposal ? [c.proposal] : []);
2886
+ const confirmed = count("confirmed");
2887
+ const unconfirmed = count("unconfirmed");
2888
+ const changes = [...Object.values(nodes), ...Object.values(edges)].flatMap((c) => c.change ? [c.change.kind] : []);
2889
+ return {
2890
+ nodes,
2891
+ edges,
2892
+ absences,
2893
+ tour,
2894
+ screens,
2895
+ summary: {
2896
+ claims: confirmed + unconfirmed,
2897
+ confirmed,
2898
+ unconfirmed,
2899
+ proposals: { pending: proposals.filter((p) => p.state === "pending").length, done: proposals.filter((p) => p.state === "done").length },
2900
+ ...cmp && { changes: { added: changes.filter((k) => k === "added").length, changed: changes.filter((k) => k === "changed").length, removed: changes.filter((k) => k === "removed").length } }
2901
+ },
2902
+ ...cmp && { since: { ref: cmp.ref, commit: baseRepo?.commit ?? null, ...baseRepo ? commitInfo(repo.root, baseRepo.commit) : { date: null, subject: null } } }
2903
+ };
2904
+ }
2905
+ function settledProposals(report) {
2906
+ const of = (what, group) => Object.entries(group).flatMap(([id, c]) => c.proposal?.state === "done" ? [{ id, what, kind: c.proposal.kind, reasons: c.reasons }] : []);
2907
+ return [...of("box", report.nodes), ...of("arrow", report.edges)];
2638
2908
  }
2639
- function factsFor(repo) {
2640
- const index = createFactsIndex(repo.root, fileExistsIn(repo.root), repo.text);
2909
+ function factsFor(repo, exists) {
2910
+ const index = createFactsIndex(repo.root, exists, repo.text);
2641
2911
  const cache2 = /* @__PURE__ */ new Map();
2642
2912
  const get = (file) => {
2643
2913
  if (!cache2.has(file)) {
@@ -2684,7 +2954,61 @@ function evidenceReasons(evidence) {
2684
2954
  function result(evidence, reasons, proof) {
2685
2955
  return reasons.length ? { status: "unconfirmed", proof: null, evidence, reasons } : { status: "confirmed", proof, evidence, reasons };
2686
2956
  }
2687
- function checkNode(n, repo, facts, window) {
2957
+ function asProposal(kind, c) {
2958
+ const inCode = c.status === "confirmed";
2959
+ if (kind === "add") return inCode ? { ...c, proposal: { kind, state: "done" } } : { ...c, status: "proposed", proposal: { kind, state: "pending" } };
2960
+ return inCode ? { ...c, proposal: { kind, state: "pending" } } : { ...c, status: "proposed", proposal: { kind, state: "done" } };
2961
+ }
2962
+ function checkNode(n, now, cmp, window) {
2963
+ if (n.removed) return checkGone(cmp, (side) => checkNodeNow(n, side.repo, side.facts, window), (base) => nodeStillThere(n, now, base));
2964
+ const c = checkNodeAsIs(n, now.repo, now.facts, window);
2965
+ if (!cmp?.base || n.proposed || c.status !== "confirmed") return c;
2966
+ const change = nodeChange(n, now, cmp.base);
2967
+ return change ? { ...c, change } : c;
2968
+ }
2969
+ function checkNodeAsIs(n, repo, facts, window) {
2970
+ if (!n.proposed) return checkNodeNow(n, repo, facts, window);
2971
+ if (!isAddition(n)) return asProposal(n.proposed.kind, checkNodeNow(n, repo, facts, window));
2972
+ if (!n.symbol) return asProposal("add", { status: "unconfirmed", proof: null, evidence: [], reasons: ["it names no `symbol`, so the code can't show whether it has been built"] });
2973
+ return asProposal("add", checkNodeNow({ ...n, evidence: [] }, repo, facts, window));
2974
+ }
2975
+ function checkGone(cmp, at, stillThere) {
2976
+ const fail = (evidence, reasons) => ({ status: "unconfirmed", proof: null, evidence, reasons });
2977
+ if (!cmp) return fail([], ["the map names no commit (`since`) for this to have been removed after"]);
2978
+ if (!cmp.base) return fail([], [`"${cmp.ref}" isn't a commit in this repo, so there is nothing to compare with`]);
2979
+ const was = at(cmp.base);
2980
+ if (was.status !== "confirmed") return fail(was.evidence, was.reasons.map((r) => `in the code as it was: ${r}`));
2981
+ if (stillThere(cmp.base)) return fail(was.evidence, ["it is still in the code, so it wasn't removed (drop `removed`)"]);
2982
+ return { ...was, change: { kind: "removed" } };
2983
+ }
2984
+ function hasLine(side, file, text2) {
2985
+ const source = side.repo.text(file);
2986
+ if (source === null) return false;
2987
+ const want = squash(text2);
2988
+ return source.split("\n").some((line) => squash(line).includes(want));
2989
+ }
2990
+ function nodeStillThere(n, now, _base) {
2991
+ if (n.symbol && now.facts.get(fileOf(n.symbol))) return !!symbolIn(now, n.symbol);
2992
+ return n.evidence.some((e) => hasLine(now, e.file, e.text));
2993
+ }
2994
+ function nodeChange(n, now, base) {
2995
+ if (n.symbol) {
2996
+ const file = fileOf(n.symbol);
2997
+ const cur = symbolIn(now, n.symbol);
2998
+ if (cur && !base.repo.has(file)) return { kind: "added" };
2999
+ if (cur && base.facts.get(file)) {
3000
+ const old = symbolIn(base, n.symbol);
3001
+ if (!old) return { kind: "added" };
3002
+ if (old.sigHash === cur.sigHash && old.bodyHash === cur.bodyHash) return null;
3003
+ const diff = lineDiff(base.repo.text(file).slice(old.span.start, old.span.end), now.repo.text(file).slice(cur.span.start, cur.span.end));
3004
+ return { kind: "changed", ...diff?.length && { diff } };
3005
+ }
3006
+ }
3007
+ if (!n.evidence.length) return null;
3008
+ if (n.evidence.every((e) => !base.repo.has(e.file))) return { kind: "added" };
3009
+ return n.evidence.some((e) => !hasLine(base, e.file, e.text)) ? { kind: "changed" } : null;
3010
+ }
3011
+ function checkNodeNow(n, repo, facts, window) {
2688
3012
  const evidence = n.evidence.map((e) => checkEvidence(repo, e, window));
2689
3013
  const reasons = evidenceReasons(evidence);
2690
3014
  if (reasons.length || !n.symbol) return result(evidence, reasons, "text");
@@ -2692,7 +3016,30 @@ function checkNode(n, repo, facts, window) {
2692
3016
  if (!found) reasons.push(`the code has no symbol ${n.symbol}`);
2693
3017
  return result(evidence, reasons, "fact");
2694
3018
  }
2695
- function checkEdge(e, byId, repo, facts, window) {
3019
+ function factBacked(e, byId) {
3020
+ const from = byId.get(e.from);
3021
+ const to = byId.get(e.to);
3022
+ return e.kind !== "then" && !!from && !!to && (e.kind !== "calls" || !!from.symbol && !!to.symbol) && [from, to].every((n) => n.symbol || n.evidence.length);
3023
+ }
3024
+ function checkEdge(e, byId, now, cmp, window) {
3025
+ const inFacts = (side) => factBacked(e, byId) && checkEdgeNow({ ...e, evidence: [] }, byId, side.repo, side.facts, window).status === "confirmed";
3026
+ if (e.removed) {
3027
+ const stillThere = () => factBacked(e, byId) ? inFacts(now) : e.evidence.every((x) => hasLine(now, x.file, x.text));
3028
+ return checkGone(cmp, (side) => checkEdgeNow(e, byId, side.repo, side.facts, window), stillThere);
3029
+ }
3030
+ const c = checkEdgeAsIs(e, byId, now.repo, now.facts, window);
3031
+ if (!cmp?.base || e.proposed || c.status !== "confirmed") return c;
3032
+ const base = cmp.base;
3033
+ const added = factBacked(e, byId) ? !inFacts(base) : e.evidence.some((x) => !hasLine(base, x.file, x.text));
3034
+ return added ? { ...c, change: { kind: "added" } } : c;
3035
+ }
3036
+ function checkEdgeAsIs(e, byId, repo, facts, window) {
3037
+ if (!e.proposed) return checkEdgeNow(e, byId, repo, facts, window);
3038
+ if (!isAddition(e)) return asProposal(e.proposed.kind, checkEdgeNow(e, byId, repo, facts, window));
3039
+ if (!factBacked(e, byId)) return asProposal("add", { status: "unconfirmed", proof: null, evidence: [], reasons: ["the code facts can't show whether this arrow has been built (it isn't a call, request or import between named functions)"] });
3040
+ return asProposal("add", checkEdgeNow({ ...e, evidence: [] }, byId, repo, facts, window));
3041
+ }
3042
+ function checkEdgeNow(e, byId, repo, facts, window) {
2696
3043
  const evidence = e.evidence.map((x) => checkEvidence(repo, x, window));
2697
3044
  const reasons = evidenceReasons(evidence);
2698
3045
  const from = byId.get(e.from);
@@ -2735,14 +3082,16 @@ function checkAbsence(a, repo, files) {
2735
3082
  try {
2736
3083
  pattern = new RegExp(a.search.regex ? a.search.pattern : a.search.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
2737
3084
  } catch {
2738
- return { status: "unconfirmed", found: 0, locations: [], reasons: ["the search pattern is not a valid regular expression"] };
3085
+ return { status: "unconfirmed", found: 0, searched: 0, locations: [], reasons: ["the search pattern is not a valid regular expression"] };
2739
3086
  }
2740
3087
  let found = 0;
3088
+ let searched = 0;
2741
3089
  const locations = [];
2742
3090
  for (const file of files) {
2743
3091
  if (a.search.paths && !matchesAny(a.search.paths, file)) continue;
2744
3092
  const text2 = repo.text(file);
2745
3093
  if (text2 === null) continue;
3094
+ searched++;
2746
3095
  text2.split("\n").forEach((line, i) => {
2747
3096
  const n = line.match(pattern)?.length ?? 0;
2748
3097
  if (!n) return;
@@ -2751,19 +3100,23 @@ function checkAbsence(a, repo, files) {
2751
3100
  });
2752
3101
  }
2753
3102
  const reasons = found === a.matches ? [] : [`the search finds ${found} ${found === 1 ? "match" : "matches"}; the map says ${a.matches}`];
2754
- return { status: reasons.length ? "unconfirmed" : "confirmed", found, locations, reasons };
3103
+ if (!searched) reasons.push(a.search.paths ? `no files match ${a.search.paths.join(", ")}, so nothing was searched` : "there were no files to search");
3104
+ return { status: reasons.length ? "unconfirmed" : "confirmed", found, searched, locations, reasons };
2755
3105
  }
2756
- var MAX_LOCATIONS, fileOf, within, short;
3106
+ var MAX_LOCATIONS, fileOf, within, short, symbolIn;
2757
3107
  var init_check = __esm({
2758
3108
  "packages/core/src/check.ts"() {
2759
3109
  "use strict";
2760
3110
  init_src();
3111
+ init_base();
3112
+ init_format();
2761
3113
  init_repo();
2762
3114
  init_screens();
2763
3115
  MAX_LOCATIONS = 20;
2764
3116
  fileOf = (symbol) => symbol.slice(0, symbol.indexOf("#"));
2765
3117
  within = (from, symbol) => from === symbol || from.startsWith(`${symbol}.`);
2766
3118
  short = (text2) => text2.length > 60 ? `${text2.slice(0, 57)}\u2026` : text2;
3119
+ symbolIn = (side, symbol) => side.facts.get(fileOf(symbol))?.symbols.find((s) => s.id === symbol) ?? null;
2767
3120
  }
2768
3121
  });
2769
3122
 
@@ -2773,6 +3126,7 @@ var init_src2 = __esm({
2773
3126
  "use strict";
2774
3127
  init_format();
2775
3128
  init_edit();
3129
+ init_base();
2776
3130
  init_check();
2777
3131
  init_repo();
2778
3132
  init_screens();
@@ -2859,26 +3213,26 @@ var init_agent = __esm({
2859
3213
  });
2860
3214
 
2861
3215
  // packages/server/src/git.ts
2862
- import { execFileSync } from "node:child_process";
2863
- var git, headCommit, hasUncommittedChanges;
3216
+ import { execFileSync as execFileSync3 } from "node:child_process";
3217
+ var git2, headCommit, hasUncommittedChanges;
2864
3218
  var init_git = __esm({
2865
3219
  "packages/server/src/git.ts"() {
2866
3220
  "use strict";
2867
- git = (root, args) => {
3221
+ git2 = (root, args) => {
2868
3222
  try {
2869
- return execFileSync("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
3223
+ return execFileSync3("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
2870
3224
  } catch {
2871
3225
  return null;
2872
3226
  }
2873
3227
  };
2874
- headCommit = (root) => git(root, ["rev-parse", "HEAD"]) || null;
2875
- hasUncommittedChanges = (root, file) => !!git(root, ["status", "--porcelain", "--", file]);
3228
+ headCommit = (root) => git2(root, ["rev-parse", "HEAD"]) || null;
3229
+ hasUncommittedChanges = (root, file) => !!git2(root, ["status", "--porcelain", "--", file]);
2876
3230
  }
2877
3231
  });
2878
3232
 
2879
3233
  // packages/server/src/fixes.ts
2880
3234
  import * as crypto2 from "node:crypto";
2881
- import * as fs7 from "node:fs";
3235
+ import * as fs8 from "node:fs";
2882
3236
  import * as path5 from "node:path";
2883
3237
  function allowed(file) {
2884
3238
  if (!isSafeRelativePath(file)) return `${file}: must be a path inside the repo`;
@@ -2923,7 +3277,7 @@ function proposeFix(root, map, raw) {
2923
3277
  problems.push(bad);
2924
3278
  continue;
2925
3279
  }
2926
- if (fs7.existsSync(path5.join(root, c.file)) || after.has(c.file)) {
3280
+ if (fs8.existsSync(path5.join(root, c.file)) || after.has(c.file)) {
2927
3281
  problems.push(`${c.file}: already exists`);
2928
3282
  continue;
2929
3283
  }
@@ -2963,11 +3317,11 @@ function applyFix(root, proposal) {
2963
3317
  for (const f of proposal.files) {
2964
3318
  const abs = path5.join(root, f.file);
2965
3319
  if (f.change === "create") {
2966
- if (fs7.existsSync(abs)) problems.push(`${f.file} was created since this fix was proposed`);
3320
+ if (fs8.existsSync(abs)) problems.push(`${f.file} was created since this fix was proposed`);
2967
3321
  originals.push({ file: f.file, content: null });
2968
3322
  continue;
2969
3323
  }
2970
- const text2 = fs7.existsSync(abs) ? fs7.readFileSync(abs, "utf8") : null;
3324
+ const text2 = fs8.existsSync(abs) ? fs8.readFileSync(abs, "utf8") : null;
2971
3325
  if (text2 === null || sha(text2) !== f.hash) {
2972
3326
  problems.push(`${f.file} changed since this fix was proposed; ask for the fix again`);
2973
3327
  continue;
@@ -2982,13 +3336,13 @@ function applyFix(root, proposal) {
2982
3336
  }
2983
3337
  for (const c of proposal.creates) contents.set(c.file, c.content);
2984
3338
  const backup = path5.join(root, ".illuminate", "fixes", proposal.id);
2985
- fs7.mkdirSync(backup, { recursive: true });
2986
- fs7.writeFileSync(path5.join(backup, "originals.json"), JSON.stringify({ proposal, originals }, null, 2));
3339
+ fs8.mkdirSync(backup, { recursive: true });
3340
+ fs8.writeFileSync(path5.join(backup, "originals.json"), JSON.stringify({ proposal, originals }, null, 2));
2987
3341
  const written = [];
2988
3342
  for (const [file, text2] of contents) {
2989
3343
  const abs = path5.join(root, file);
2990
- fs7.mkdirSync(path5.dirname(abs), { recursive: true });
2991
- fs7.writeFileSync(abs, text2);
3344
+ fs8.mkdirSync(path5.dirname(abs), { recursive: true });
3345
+ fs8.writeFileSync(abs, text2);
2992
3346
  written.push({ file, hash: sha(text2) });
2993
3347
  }
2994
3348
  return { ok: true, applied: { proposal, originals, written } };
@@ -2997,14 +3351,14 @@ function undoFix(root, applied) {
2997
3351
  const problems = [];
2998
3352
  for (const w of applied.written) {
2999
3353
  const abs = path5.join(root, w.file);
3000
- const text2 = fs7.existsSync(abs) ? fs7.readFileSync(abs, "utf8") : null;
3354
+ const text2 = fs8.existsSync(abs) ? fs8.readFileSync(abs, "utf8") : null;
3001
3355
  if (text2 === null || sha(text2) !== w.hash) problems.push(`${w.file} changed after the fix; undo it by hand`);
3002
3356
  }
3003
3357
  if (problems.length) return { ok: false, problems };
3004
3358
  for (const o of applied.originals) {
3005
3359
  const abs = path5.join(root, o.file);
3006
- if (o.content === null) fs7.rmSync(abs, { force: true });
3007
- else fs7.writeFileSync(abs, o.content);
3360
+ if (o.content === null) fs8.rmSync(abs, { force: true });
3361
+ else fs8.writeFileSync(abs, o.content);
3008
3362
  }
3009
3363
  return { ok: true };
3010
3364
  }
@@ -3045,8 +3399,14 @@ function makerPrompt(question, headStart2) {
3045
3399
  "",
3046
3400
  ...MAP_RULES,
3047
3401
  "",
3402
+ ...JOURNEY_RULES,
3403
+ "",
3048
3404
  ...EVIDENCE_RULES,
3049
3405
  "",
3406
+ ...PROPOSAL_RULES,
3407
+ "",
3408
+ ...CHANGE_RULES,
3409
+ "",
3050
3410
  ...SCREEN_RULES,
3051
3411
  "",
3052
3412
  ...TOUR_RULES,
@@ -3054,7 +3414,7 @@ function makerPrompt(question, headStart2) {
3054
3414
  "## Head start (from a quick automatic scan; it may be incomplete)",
3055
3415
  headStart2,
3056
3416
  "",
3057
- "Return the map: `version` 1, the `question`, `areas`, `nodes`, `edges`, `absences`, `tour`."
3417
+ "Return the map: `version` 1, the `question`, `areas`, `nodes`, `edges`, `absences`, `tour` (and `view` or `since` when the rules above call for them)."
3058
3418
  ].join("\n");
3059
3419
  }
3060
3420
  function shapeRepairPrompt(problems) {
@@ -3078,8 +3438,9 @@ function withSuggestion(reason, symbolsIn) {
3078
3438
  function evidenceRepairPrompt(report, symbolsIn) {
3079
3439
  const why = (reasons) => reasons.map((r) => withSuggestion(r, symbolsIn)).join("; ");
3080
3440
  const lines = [
3081
- ...Object.entries(report.nodes).filter(([, c]) => c.status !== "confirmed").map(([id, c]) => `- box ${id}: ${why(c.reasons)}`),
3082
- ...Object.entries(report.edges).filter(([, c]) => c.status !== "confirmed").map(([id, c]) => `- arrow ${id}: ${why(c.reasons)}`),
3441
+ ...Object.entries(report.nodes).filter(([, c]) => c.status === "unconfirmed").map(([id, c]) => `- box ${id}: ${why(c.reasons)}`),
3442
+ ...Object.entries(report.edges).filter(([, c]) => c.status === "unconfirmed").map(([id, c]) => `- arrow ${id}: ${why(c.reasons)}`),
3443
+ ...settledProposals(report).map((p) => p.kind === "add" ? `- ${p.what} ${p.id}: you propose adding it, but the code already has it. Draw it as code that exists (cite its line, no \`proposed\`), or drop it.` : `- ${p.what} ${p.id}: you propose to ${p.kind} it, so it must cite code that is there now: ${why(p.reasons)}`),
3083
3444
  ...Object.entries(report.absences).filter(([, c]) => c.status !== "confirmed").map(([id, c]) => `- absence ${id}: ${c.reasons.join("; ")}${c.locations.length ? ` (found at ${c.locations.slice(0, 5).map((l) => `${l.file}:${l.line}`).join(", ")})` : ""}`)
3084
3445
  ];
3085
3446
  const screens = Object.entries(report.screens ?? {}).filter(([, c]) => c.status !== "confirmed").map(([id, c]) => `- screen on box ${id}: ${c.reasons.join("; ")}`);
@@ -3102,16 +3463,16 @@ function patchRepairPrompt(problems) {
3102
3463
  ].join("\n");
3103
3464
  }
3104
3465
  function questionContext(map, report, selection, question) {
3105
- const unconfirmed = [
3106
- ...Object.entries(report.nodes),
3107
- ...Object.entries(report.edges),
3108
- ...Object.entries(report.absences)
3109
- ].filter(([, c]) => c.status !== "confirmed").map(([id]) => id);
3466
+ const all = [...Object.entries(report.nodes), ...Object.entries(report.edges), ...Object.entries(report.absences)];
3467
+ const unconfirmed = all.filter(([, c]) => c.status === "unconfirmed").map(([id]) => id);
3468
+ const proposals = [...Object.entries(report.nodes), ...Object.entries(report.edges)].flatMap(([id, c]) => c.proposal ? [`${id} (${c.proposal.kind}: ${c.proposal.state === "done" ? "now done in the code" : "not done yet"})`] : []);
3110
3469
  return [
3111
3470
  "## The map (JSON)",
3112
3471
  JSON.stringify(map),
3113
3472
  unconfirmed.length ? `
3114
- The checker could not confirm: ${unconfirmed.join(", ")}. Don't rely on those without checking.` : "\nThe checker confirmed every claim in the map.",
3473
+ The checker could not confirm: ${unconfirmed.join(", ")}. Don't rely on those without checking.` : "\nThe checker confirmed every claim in the map about the code as it is.",
3474
+ ...proposals.length ? [`These are proposals, not code as it is; the checker says where each stands: ${proposals.join(", ")}.`] : [],
3475
+ ...changesContext(report),
3115
3476
  "",
3116
3477
  selection.length ? `## They selected
3117
3478
  ${selection.map((s) => `- ${s.id}: ${s.label}`).join("\n")}` : "## They selected nothing (the question is about the whole map)",
@@ -3120,6 +3481,18 @@ ${selection.map((s) => `- ${s.id}: ${s.label}`).join("\n")}` : "## They selected
3120
3481
  "${question}"`
3121
3482
  ];
3122
3483
  }
3484
+ function changesContext(report) {
3485
+ if (!report.since) return [];
3486
+ if (!report.since.commit) return [`
3487
+ This map is meant to show a change since "${report.since.ref}", but that isn't a commit in this repo, so nothing could be compared.`];
3488
+ const marked = [...Object.entries(report.nodes), ...Object.entries(report.edges)].flatMap(([id, c]) => c.change ? [{ id, ...c.change }] : []);
3489
+ return [
3490
+ `
3491
+ This map shows a change: the code as it is now, compared with commit ${report.since.commit.slice(0, 12)}${report.since.subject ? ` ("${report.since.subject}")` : ""}. The checker worked out what differs:`,
3492
+ marked.length ? marked.map((m) => `${m.id} (${m.kind})`).join(", ") + ". Everything else on the map is the same as it was." : "nothing on this map differs from that commit.",
3493
+ ...marked.filter((m) => m.diff?.length).flatMap((m) => [`Lines of ${m.id} that changed (- before, + now):`, ...m.diff])
3494
+ ];
3495
+ }
3123
3496
  function conversationSoFar(earlier) {
3124
3497
  if (!earlier.length) return [];
3125
3498
  return [
@@ -3171,6 +3544,8 @@ function explainerPrompt(map, report, selection, question, missing = "", wordsOn
3171
3544
  "You answer questions about a code map for someone semi-technical. You can Read, Grep and Glob the repo; you cannot edit anything.",
3172
3545
  "",
3173
3546
  ...questionContext(map, report, selection, question),
3547
+ ...map.view === "journey" ? ["", "## This map is a journey", "It shows only what a person sees and does. Anything you add must be the same: `kind` is `screen`, `action` or `choice`, and no boxes for what goes on behind the screen. Say that part in words."] : [],
3548
+ ...map.since ? ["", "## This map shows a change", `It compares the code as it is now with commit ${map.since.slice(0, 12)}, and a program marks what is new or different since then. Anything you add is compared the same way, so don't mark it yourself. Only code that was deleted since that commit gets \`"removed": true\`, citing its lines as they were then (an arrow to or from a removed box is removed too).`] : [],
3174
3549
  ...missing ? ["", `## Why the map alone wasn't enough
3175
3550
  ${missing}`] : [],
3176
3551
  "",
@@ -3179,22 +3554,26 @@ ${missing}`] : [],
3179
3554
  ...ANSWER_STYLE,
3180
3555
  "- If the map doesn't cover it, explore. Put what you found in `add` (new areas, nodes, edges or absences with evidence, same rules as the map; ids must be new) only when it belongs to the flow this map follows and seeing it drawn helps answer the question. If the answer is a fact you can say in words, or about something beside the flow, leave `add` empty. Connect new boxes to existing ones with arrows where the code really connects them.",
3181
3556
  "- `moves`: `focus` on the most relevant id; `highlight` the ids that make up the path that answers the question.",
3182
- "- If they ask for a change, don't edit (you can't). Propose a `fix`: illuminate shows it to them on the map, and if they approve, illuminate applies exactly your edits and re-checks the map. So describe it as a proposal waiting for their approval, never as something for them to apply by hand.",
3557
+ '- If they ask what a change would look like, how you would do something, or for a plan, without asking you to make it: draw it on the map as proposals (see Proposals). New boxes and arrows go in `add` with `proposed`; for a box or arrow already on the map that would change or go, put `{ "id": "<its id>", "proposed": { "kind": "change" | "remove", "note": "\u2026" } }` in `propose`. Say in the answer what the proposal is; nothing is edited.',
3558
+ "- If they ask you to make a change, don't edit (you can't). Propose a `fix`: illuminate shows it to them on the map, and if they approve, illuminate applies exactly your edits and re-checks the map. So describe it as a proposal waiting for their approval, never as something for them to apply by hand.",
3183
3559
  "- The `fix`: `summary` in plain words; `edits` as exact replacements (`find` copied exactly from the file, occurring once; `replace` is the new text); `creates` for new files. If the fix creates a connection between two boxes, fill `connects` with `from`, `to`, a short `label`, and `evidenceFile` + `evidenceText` (text that will appear in the new code). Keep fixes small and in the style of the surrounding code.",
3184
3560
  '- When the question is about what the person sees at a step ("what does this look like?", "where is that button?"), answer with a picture: put `{ "node": "<box id>", "screen": { \u2026 } }` in `screens`, for a box already on the map or one in `add` (see Screens below). Otherwise leave `screens` out: most questions don\'t need one.',
3185
3561
  "",
3186
3562
  ...EVIDENCE_RULES,
3187
3563
  "",
3564
+ ...PROPOSAL_RULES,
3565
+ "",
3188
3566
  ...SCREEN_RULES
3189
3567
  ].join("\n");
3190
3568
  }
3191
- var EVIDENCE_RULES, MAP_RULES, SCREEN_RULES, TOUR_RULES, NO_SYMBOL, ANSWER_STYLE;
3569
+ var EVIDENCE_RULES, MAP_RULES, JOURNEY_RULES, PROPOSAL_RULES, CHANGE_RULES, SCREEN_RULES, TOUR_RULES, NO_SYMBOL, ANSWER_STYLE;
3192
3570
  var init_prompts = __esm({
3193
3571
  "packages/server/src/prompts.ts"() {
3194
3572
  "use strict";
3573
+ init_src2();
3195
3574
  EVIDENCE_RULES = [
3196
3575
  "## Evidence rules (a program checks every claim; anything it can't confirm is shown as unconfirmed)",
3197
- "- Every box and arrow cites at least one line: `file` (repo-relative), `line` (1-based), and `text` copied exactly from that line. A distinctive fragment of 10\u201380 characters works best.",
3576
+ "- Every box and arrow that is in the code cites at least one line: `file` (repo-relative), `line` (1-based), and `text` copied exactly from that line. A distinctive fragment of 10\u201380 characters works best.",
3198
3577
  '- A box that is a function or method gets `symbol`: "<file>#<name>", named the way the checker names it: methods as Class.method, object members as obj.member ("src/db.ts#db.update"), a function inside another function as outer.inner, and a function in the object a factory returns as factory.member. When a list of functions by file is given, copy the name from it. If you aren\'t sure of the name, leave `symbol` out: the box is still checked by its cited line.',
3199
3578
  "- Arrow `kind`: `calls` when a function in the from box literally calls the function in the to box; `request` when an HTTP call in the from box hits a route handled by the to box; `imports`; `then` for anything else (events, ordering). The checker verifies calls, request and imports against the code, so use them only when literally true.",
3200
3579
  "- Never cite or read secret files (.env, keys)."
@@ -3203,7 +3582,12 @@ var init_prompts = __esm({
3203
3582
  "## What a good map is",
3204
3583
  "- It follows what happens, in order, from where it starts (a button, a route, a job, a command) to where it ends (a table write, an email, an outside API), or to where it stops.",
3205
3584
  "- 2\u20136 `areas` named in product language (Patients, Billing, Background jobs), not folder names.",
3206
- '- 4\u201312 boxes (`nodes`). Each is one step a person would recognize. `name`: plain English, at most 30 characters ("Patient marked enrolled", not "markConverted()").',
3585
+ "- Aim for 6\u20138 boxes (`nodes`); 12 is a hard ceiling, reached only when the question asks about several things at once. A map is an answer, not an inventory: someone should be able to hold it in their head. Each box is one step a person would recognize and that the answer turns on.",
3586
+ "- Leave plumbing off the map unless the question is about it: a request arriving, a job being started, a result being saved, an update being sent to the screen. Fold each into the box it serves and say it in that box's `explain` or on the arrow.",
3587
+ "- When several steps in a row just hand on to the next (a route that calls a handler that calls a service), they are one box, cited at the step that matters.",
3588
+ "- When the answer is a list of like things (five kinds of rule, four checks), that is one box naming the group, or at most the two or three that differ in a way the question cares about; put the rest in `explain`.",
3589
+ "- Before returning, go through the boxes one at a time: if the answer would be the same without it, drop or merge it.",
3590
+ '- Box `name`: plain English, at most 30 characters ("Patient marked enrolled", not "markConverted()").',
3207
3591
  "- `kind`: entry (a way in), step, store (table, queue, cache), external (outside service), job (scheduled or background work).",
3208
3592
  "- `explain` for every box: just `concept`, 1\u20132 plain sentences, no jargon, saying what this step does. The box already shows its function and file, so leave those out.",
3209
3593
  '- Arrow `label`: 1\u20133 words saying how one step leads to the next ("sends request", "calls", "announces", "every night").',
@@ -3211,6 +3595,38 @@ var init_prompts = __esm({
3211
3595
  `- An \`absence\` is a break in the flow you were asked about: a step on that path should lead to the next one and doesn't (something is announced that nothing listens for, a job that nothing ever starts). Most maps have none, and a map without one is complete. Don't go looking for one, and don't use one for a design choice or guarantee ("X never calls Y", "nothing here edits files"): say that in a box's explanation or the walkthrough instead. Don't record small mismatches beside the question (a command the docs don't mention, an unused option).`,
3212
3596
  "- When there is a break, record it: the `claim` in plain words, the two boxes it should connect (`between`), and the exact `search` that proves nothing is there (`pattern`, `regex`, optional `paths` globs covering every file where the missing piece could live), with `matches` set to the count that search returns (usually 0). Run that search yourself with Grep first."
3213
3597
  ];
3598
+ JOURNEY_RULES = [
3599
+ "## When the question is about what a person sees or does (a journey, a user flow)",
3600
+ '- Set `"view": "journey"` on the map: it is then drawn as a user flow, left to right, with no code on the boxes (the code is one click away).',
3601
+ '- `kind` here is one of: `screen` (something the person looks at), `action` (something they do that is a step in itself: "Fills in the form", "Pays"), `choice` (a point where they pick between ways forward, named as the question they face: "Buy now or add to bag?"; each arrow out of it is one option, labeled with what they pick). Use a `choice` wherever the path forks on what the person decides, rather than two arrows out of a screen.',
3602
+ '- Draw only what the person sees and does. Every box is a screen they look at or something they do on one, in order, named the way they would say it ("Sign-up form", "Email confirmed"). Areas are the stages of the journey as the person lives them ("Choosing", "Paying", "Waiting for it"). Arrows say what the person does or what happens to them next ("taps Sign up", "is sent to").',
3603
+ '- Leave out what goes on behind the screen: no boxes for routes, requests, functions, jobs, database writes or other services. When several of those sit between two screens, they are one arrow ("pays, and lands on"), and that arrow cites the code that does it. A step that happens outside the app is a box only if the person sees it (a payment page, an email they get), cited at the line that sends them there or sends it.',
3604
+ `- A wait is part of the journey: when the next thing the person sees comes later (an email after a nightly job, an order shipped after approval), say so on the arrow in their terms ("a day later, gets"), and don't draw the job.`,
3605
+ "- Each box and arrow still cites the code that makes it so: the component, the handler, the redirect.",
3606
+ "- Give every screen box a `screen` (see Screens), so the journey can be followed in pictures. Here more than two is right.",
3607
+ "- Where the journey stops short (a button that leads nowhere, a result with no screen, nothing ever telling the person what happened), that is a break: record it as an absence.",
3608
+ "- The walkthrough is told as the person's experience too, one stop per screen."
3609
+ ];
3610
+ PROPOSAL_RULES = [
3611
+ "## Proposals (`proposed` on a box or arrow; only when a change is asked for)",
3612
+ '- When they ask how something could or should change ("how would we add\u2026", "plan\u2026", "what would it take to\u2026", "propose\u2026"), draw the code as it is, cited and checked as usual, and the change on top of it. A question about how things work today gets no proposals.',
3613
+ '- `"proposed": { "kind": "add", "note": "\u2026" }`: a box or arrow that isn\'t in the code yet. It cites nothing, so leave `evidence` out. Give a new box the `symbol` it would have ("<file>#<name>"; the file may be new) and a new arrow its real `kind` (`calls`, `request`, `imports`): that is how the check can tell, later, that it has been built. An arrow to or from a new box is itself an addition.',
3614
+ '- `"kind": "change"` or `"remove"`: code that is there today and would be changed or deleted. Cite it like any other claim.',
3615
+ "- `note`: one plain sentence saying what would change and why.",
3616
+ "- Every new box must connect, through arrows, to a box that exists. Keep it small: only the boxes and arrows the change needs.",
3617
+ '- On a screen: a box with `proposed` may have a sketch with elements marked `"proposed": true` for what would be added to it, and a new screen is a new box whose sketch is all new.',
3618
+ "- A program checks proposals against the code too. Proposing to add what the code already has, or to change or remove what it doesn't have, is sent back."
3619
+ ];
3620
+ CHANGE_RULES = [
3621
+ '## When the question is about a change (what changed, what a commit or a task did, "what did you just change")',
3622
+ '- Set `"since"` on the map to the commit to compare with: "HEAD" for work that isn\'t committed yet, "HEAD~1" for the last commit, or the branch or commit they name. A question about how things work today gets no `since`.',
3623
+ "- Draw the flow the change belongs to as it works now, the map you would draw if they had asked how it works: start where it starts and follow it through, steps that didn't change included. The person reads the change against those: a map where every box is new or changed shows no before, and can't be told from a map of something else. As a guide, at least a third of the boxes are ones that didn't change (the steps the change plugs into, what calls the new code, what it hands on to). Leave out helpers the change added that aren't steps of the flow.",
3624
+ "- Cite everything as usual. Don't mark what is new or different: a program compares every box and arrow with that commit and marks them itself. It compares a box that names its function (`symbol`) as that function, so give new and changed boxes their `symbol`; for anything else, cite a line that is new.",
3625
+ '- Code that was deleted is a box or arrow with `"removed": true`. It cites the code as it was at that commit: `file`, `line` and `text` from the old version (`git show <since>:<file>` shows it, when you can run git). An arrow to or from a removed box is removed too. The program checks that it was there then and is gone now, so use it only for code that is really gone, not for code that moved or was renamed.',
3626
+ '- In the explanation of each box that changed, say what is different now, in plain words ("Now also tells the listener"), not as a diff.',
3627
+ "- If you made the change yourself in this conversation, draw what you changed and what it touches. Other differences from that commit that aren't part of it stay off the map.",
3628
+ "- The walkthrough says what changed first, then follows the changed path in the order things happen."
3629
+ ];
3214
3630
  SCREEN_RULES = [
3215
3631
  "## Screens (`screen` on a box; optional, and your call)",
3216
3632
  "- A picture of what the person sees can ground a map for people who don't read code. Add one where the flow touches the screen and seeing it helps: usually the box where it starts (the button or form), sometimes where a result appears. For backend-only questions, add none. One or two per map is plenty.",
@@ -3221,9 +3637,11 @@ var init_prompts = __esm({
3221
3637
  ];
3222
3638
  TOUR_RULES = [
3223
3639
  "## Walkthrough (`tour`, written last)",
3224
- "- 4\u20137 stops in the order a newcomer should read them: what the map shows, then the path, then what it means. If the map has a break, give it a stop where it happens on the path.",
3640
+ "- 4\u20137 stops in the order a newcomer should read them: the answer, then the path, then what it means. If the map has a break, give it a stop where it happens on the path.",
3641
+ '- The first stop answers their question outright, in a sentence or two, as you would if they asked you in person ("The welcome email never goes out: the app announces the conversion, but nothing is listening."). Its `title` is the answer in a few words. Don\'t open by describing the map ("This map follows\u2026", "It has three areas\u2026"): they can see it. Focus it on the boxes the answer turns on.',
3225
3642
  "- Each stop: `title`, `text` (2\u20133 plain sentences), `focus` (ids of the areas, nodes, edges or absences it's about), and optional `terms` it uses that need defining.",
3226
- "- Point stops only at boxes, arrows and absences you're confident in."
3643
+ "- Point stops only at boxes, arrows and absences you're confident in.",
3644
+ "- If the map has proposals, give them a stop after the path: what would change, and what stays as it is."
3227
3645
  ];
3228
3646
  NO_SYMBOL = /^the code has no symbol (.+)#(.+)$/;
3229
3647
  ANSWER_STYLE = [
@@ -3274,6 +3692,8 @@ var init_schemas = __esm({
3274
3692
  moves: z3.object({ focus: z3.string().optional(), highlight: z3.array(z3.string()).optional() }).optional(),
3275
3693
  /** Pictures of the screen for boxes on the map (existing ones, or ones in `add`), when the question is about what the person sees. */
3276
3694
  screens: z3.array(z3.object({ node: z3.string(), screen: Screen })).max(4).optional(),
3695
+ /** Boxes or arrows already on the map that a suggested change would alter or remove (new ones go in `add`, marked there). */
3696
+ propose: z3.array(z3.object({ id: z3.string(), proposed: Proposal })).max(12).optional(),
3277
3697
  fix: RawFix.optional()
3278
3698
  });
3279
3699
  RawQuickAnswer = RawAnswer.pick({ refs: true, moves: true }).extend({
@@ -3316,23 +3736,25 @@ import * as crypto3 from "node:crypto";
3316
3736
  function citedExcerpts(root, map, selection) {
3317
3737
  const repo = createRepoReader(root);
3318
3738
  const picked = /* @__PURE__ */ new Set([...selection.nodes ?? [], ...selection.edges ?? []]);
3319
- const items = [...map.nodes.map((n) => ({ id: n.id, evidence: n.evidence })), ...map.edges.map((e) => ({ id: e.id, evidence: e.evidence }))];
3739
+ const base = map.since && [...map.nodes, ...map.edges].some((x) => x.removed) ? createBaseReader(root, map.since) : null;
3740
+ const items = [...map.nodes, ...map.edges].map((x) => ({ id: x.id, evidence: x.evidence, was: !!x.removed }));
3320
3741
  items.sort((a, b) => Number(picked.has(b.id)) - Number(picked.has(a.id)));
3321
3742
  const seen = /* @__PURE__ */ new Set();
3322
3743
  const out = [];
3323
3744
  let size = 0;
3324
3745
  for (const item of items) {
3325
3746
  for (const e of item.evidence) {
3326
- const key = `${e.file}:${e.line}`;
3747
+ const key = `${item.was ? "was:" : ""}${e.file}:${e.line}`;
3327
3748
  if (seen.has(key) || out.length >= MAX_EXCERPTS) continue;
3328
3749
  seen.add(key);
3329
- const read = repo.read(e.file);
3750
+ if (item.was && !base) continue;
3751
+ const read = (item.was ? base : repo).read(e.file);
3330
3752
  if (!read.ok) continue;
3331
3753
  const lines = read.text.split("\n");
3332
3754
  const from = Math.max(1, e.line - EXCERPT_RADIUS);
3333
3755
  const to = Math.min(lines.length, e.line + EXCERPT_RADIUS);
3334
3756
  const body = lines.slice(from - 1, to).map((l, i) => `${String(from + i).padStart(5)} | ${l}`).join("\n");
3335
- const block = `${e.file}:${from}-${to} (cited by ${item.id})
3757
+ const block = `${e.file}:${from}-${to} (${item.was ? "removed since; as it was, " : ""}cited by ${item.id})
3336
3758
  ${body}`;
3337
3759
  if (size + block.length > MAX_EXCERPT_CHARS) return out.join("\n\n");
3338
3760
  out.push(block);
@@ -3442,7 +3864,7 @@ async function answer(o) {
3442
3864
  });
3443
3865
  const parsed = RawAnswer.safeParse(res.output);
3444
3866
  if (!parsed.success) throw new Error(`Claude's answer couldn't be read: ${parsed.error.issues.slice(0, 3).map((i) => i.message).join("; ")}`);
3445
- const raw = o.wordsOnly ? { ...parsed.data, add: void 0, fix: void 0, screens: void 0 } : parsed.data;
3867
+ const raw = o.wordsOnly ? { ...parsed.data, add: void 0, fix: void 0, screens: void 0, propose: void 0 } : parsed.data;
3446
3868
  const problems = [];
3447
3869
  let map = o.map;
3448
3870
  let added = [];
@@ -3456,6 +3878,44 @@ async function answer(o) {
3456
3878
  problems.push(...merged.problems.map((p) => `Not added to the map: ${p}`));
3457
3879
  }
3458
3880
  }
3881
+ let report = check(map, o.root);
3882
+ for (const id of added) {
3883
+ const c = report.screens[id];
3884
+ if (c && c.status !== "confirmed") problems.push(`No screen shown for "${map.nodes.find((n) => n.id === id)?.name ?? id}": ${c.reasons.join("; ")}`);
3885
+ }
3886
+ const misread = new Set(settledProposals(report).map((p) => p.id));
3887
+ const failed = added.filter((id) => statusOf(report, id) === "unconfirmed" || misread.has(id));
3888
+ if (failed.length) {
3889
+ for (const id of failed) {
3890
+ const c = report.nodes[id] ?? report.edges[id] ?? report.absences[id];
3891
+ problems.push(misread.has(id) ? `Not drawn, ${id} was proposed as new but the code already has it` : `Not drawn, couldn't confirm ${id}: ${c?.reasons.join("; ") ?? "unknown"}`);
3892
+ }
3893
+ map = removeFromMap(map, new Set(failed));
3894
+ report = check(map, o.root);
3895
+ const live2 = mapIds(map);
3896
+ added = added.filter((id) => live2.has(id));
3897
+ }
3898
+ const marked = [];
3899
+ for (const p of raw.propose ?? []) {
3900
+ const name = map.nodes.find((n) => n.id === p.id)?.name ?? p.id;
3901
+ if (p.proposed.kind === "add" || added.includes(p.id)) {
3902
+ problems.push(`Not marked as a proposal: "${name}" (new boxes and arrows carry their own \`proposed\`)`);
3903
+ continue;
3904
+ }
3905
+ if (statusOf(report, p.id) !== "confirmed" || !(report.nodes[p.id] ?? report.edges[p.id])) {
3906
+ problems.push(`Not marked as a proposal: "${name}" isn't a confirmed box or arrow on this map`);
3907
+ continue;
3908
+ }
3909
+ const mark = (items) => items.map((x) => x.id === p.id ? { ...x, proposed: p.proposed } : x);
3910
+ const next = parseMap({ ...map, nodes: mark(map.nodes), edges: mark(map.edges) });
3911
+ if (!next.ok) {
3912
+ problems.push(`Not marked as a proposal: ${next.problems.join("; ")}`);
3913
+ continue;
3914
+ }
3915
+ map = next.map;
3916
+ marked.push(p.id);
3917
+ }
3918
+ if (marked.length) report = check(map, o.root);
3459
3919
  const wanted = (raw.screens ?? []).filter((s) => {
3460
3920
  if (map.nodes.some((n) => n.id === s.node)) return true;
3461
3921
  problems.push(`No screen shown: there is no box "${s.node}"`);
@@ -3474,22 +3934,7 @@ async function answer(o) {
3474
3934
  problems.push(`No screen shown for "${map.nodes.find((n) => n.id === s.node)?.name ?? s.node}": ${why}`);
3475
3935
  }
3476
3936
  }
3477
- let report = check(map, o.root);
3478
- for (const id of added) {
3479
- const c = report.screens[id];
3480
- if (c && c.status !== "confirmed") problems.push(`No screen shown for "${map.nodes.find((n) => n.id === id)?.name ?? id}": ${c.reasons.join("; ")}`);
3481
- }
3482
- const failed = added.filter((id) => statusOf(report, id) === "unconfirmed");
3483
- if (failed.length) {
3484
- for (const id of failed) {
3485
- const c = report.nodes[id] ?? report.edges[id] ?? report.absences[id];
3486
- problems.push(`Not drawn, couldn't confirm ${id}: ${c?.reasons.join("; ") ?? "unknown"}`);
3487
- }
3488
- map = removeFromMap(map, new Set(failed));
3489
- report = check(map, o.root);
3490
- const live2 = mapIds(map);
3491
- added = added.filter((id) => live2.has(id));
3492
- }
3937
+ if (screened.length) report = check(map, o.root);
3493
3938
  let fix = null;
3494
3939
  if (raw.fix) {
3495
3940
  const proposed = proposeFix(o.root, map, raw.fix);
@@ -3508,6 +3953,7 @@ async function answer(o) {
3508
3953
  highlight: (raw.moves?.highlight ?? []).filter((id) => live.has(id))
3509
3954
  },
3510
3955
  added,
3956
+ proposed: marked,
3511
3957
  screens: screened.filter((id) => live.has(id)),
3512
3958
  problems,
3513
3959
  fix,
@@ -3531,14 +3977,67 @@ var init_explainer = __esm({
3531
3977
  }
3532
3978
  });
3533
3979
 
3980
+ // packages/server/src/changes.ts
3981
+ import { execFileSync as execFileSync4 } from "node:child_process";
3982
+ function changesSince(root, ref) {
3983
+ const base = createBaseReader(root, ref);
3984
+ if (!base) return null;
3985
+ const now = createRepoReader(root);
3986
+ const found = /* @__PURE__ */ new Map();
3987
+ const diff = gitList(base.root, ["diff", "--name-status", "--no-renames", "--relative", "-z", base.commit, "--", "."]);
3988
+ for (let i = 0; i + 1 < diff.length; i += 2) found.set(diff[i + 1], diff[i] === "A" ? "new" : diff[i] === "D" ? "deleted" : "changed");
3989
+ for (const f of gitList(base.root, ["ls-files", "--others", "--exclude-standard", "-z"])) found.set(f, "new");
3990
+ const index = createFactsIndex(base.root, fileExistsIn(base.root), now.text);
3991
+ const symbols = (file, text2) => text2 === null ? [] : index.extract(file, text2).facts.symbols.filter((s) => !s.name.includes("<") && s.kind !== "property");
3992
+ const names = (label, ids) => ids.length ? [`${label}: ${ids.slice(0, MAX_NAMES).map((id) => id.slice(id.indexOf("#") + 1)).join(", ")}${ids.length > MAX_NAMES ? `, \u2026and ${ids.length - MAX_NAMES} more` : ""}`] : [];
3993
+ const files = [...found].filter(([file]) => !file.startsWith(".illuminate/") && !isSecretPath(file)).map(([file, what]) => {
3994
+ if (!isCodeFile(file)) return { file, what, detail: "" };
3995
+ const d = diffSymbols(symbols(file, base.text(file)), symbols(file, what === "deleted" ? null : now.text(file)));
3996
+ const changed = [...d.sig, ...d.body];
3997
+ return { file, what, detail: [...names("new", d.added), ...names("changed", changed), ...names("removed", d.removed), ...names("renamed", d.renamed.map(([, to]) => to))].join("; ") };
3998
+ }).sort((a, b) => Number(isCodeFile(b.file)) - Number(isCodeFile(a.file)) || a.file.localeCompare(b.file));
3999
+ return { commit: base.commit, subject: commitInfo(base.root, base.commit).subject, files };
4000
+ }
4001
+ function recentChanges(root) {
4002
+ const line = (c) => ` - ${c.what} ${c.file}${c.detail ? ` (${c.detail})` : ""}`;
4003
+ const open = changesSince(root, "HEAD");
4004
+ if (open?.files.length) return { title: `Not committed yet (differences from the last commit, ${open.commit.slice(0, 7)}; a map of these sets \`since\`: "HEAD")`, lines: open.files.map(line) };
4005
+ const last = changesSince(root, "HEAD~1");
4006
+ if (last?.files.length) return { title: `Everything is committed. What the last commit changed (a map of it sets \`since\`: "HEAD~1")`, lines: last.files.map(line) };
4007
+ return null;
4008
+ }
4009
+ var MAX_NAMES, gitList;
4010
+ var init_changes = __esm({
4011
+ "packages/server/src/changes.ts"() {
4012
+ "use strict";
4013
+ init_src2();
4014
+ init_src();
4015
+ MAX_NAMES = 8;
4016
+ gitList = (root, args) => {
4017
+ try {
4018
+ return execFileSync4("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).toString().split("\0").filter(Boolean);
4019
+ } catch {
4020
+ return [];
4021
+ }
4022
+ };
4023
+ }
4024
+ });
4025
+
3534
4026
  // packages/server/src/hints.ts
3535
- import * as fs8 from "node:fs";
4027
+ import * as fs9 from "node:fs";
3536
4028
  function symbolIndex(scan) {
3537
4029
  return Object.values(scan.fileFacts).filter((f) => !TEST_FILE.test(f.path)).map((f) => ({ path: f.path, names: f.symbols.filter((s) => CITABLE.has(s.kind) && !s.name.includes("<")).map((s) => s.name) })).filter((f) => f.names.length).sort((a, b) => a.path.localeCompare(b.path)).map((f) => ` - ${f.path}: ${f.names.slice(0, MAX_SYMBOLS_PER_FILE).join(", ")}${f.names.length > MAX_SYMBOLS_PER_FILE ? `, \u2026and ${f.names.length - MAX_SYMBOLS_PER_FILE} more` : ""}`);
3538
4030
  }
3539
4031
  function symbolIndexOf(scan) {
3540
4032
  return (file) => scan?.fileFacts[file]?.symbols.filter((s) => CITABLE.has(s.kind) && !s.name.includes("<")).map((s) => s.name) ?? [];
3541
4033
  }
4034
+ function functionSection(index) {
4035
+ if (index.length <= MAX_SYMBOL_FILES) return section("Functions by file (use these exact names for `symbol`)", index, MAX_SYMBOL_FILES);
4036
+ return [
4037
+ `Functions by file: not listed (${index.length} files have functions, too many to list). Name each \`symbol\` by the rules above; if a name is off, the check sends back the real names in that file.`,
4038
+ ""
4039
+ ];
4040
+ }
3542
4041
  async function headStart(root) {
3543
4042
  await initTreeSitter();
3544
4043
  let scan;
@@ -3547,12 +4046,12 @@ async function headStart(root) {
3547
4046
  } catch {
3548
4047
  return { text: "(The automatic scan could not read this repo; explore it directly.)", scan: null };
3549
4048
  }
3550
- const facts = Object.values(scan.fileFacts);
4049
+ const facts = Object.values(scan.fileFacts).filter((f) => !TEST_FILE.test(f.path));
3551
4050
  const entries = facts.flatMap((f) => f.entries).map((e) => ` - ${e.kind} ${e.label}${e.symbol ? ` \u2192 ${e.symbol}` : ` (${e.file})`}`);
3552
4051
  const routes = facts.flatMap((f) => f.routes);
3553
4052
  const routeLines = routes.map((r) => ` - ${r.method} ${r.path} \u2192 ${r.handler ?? r.file}`);
3554
4053
  const fetchFiles = facts.filter((f) => /\.(tsx?|jsx?|mjs|cjs)$/.test(f.path)).flatMap((f) => {
3555
- const source = fs8.readFileSync(`${root}/${f.path}`, "utf8");
4054
+ const source = fs9.readFileSync(`${root}/${f.path}`, "utf8");
3556
4055
  return /\bfetch\(|axios|ky\./.test(source) ? [{ path: f.path, source, symbols: f.symbols }] : [];
3557
4056
  });
3558
4057
  const requests = findFetchSites(fetchFiles).flatMap((site) => {
@@ -3564,17 +4063,25 @@ async function headStart(root) {
3564
4063
  const tables = [...writers].map(([t, by]) => ` - ${t} \u2190 ${[...by].slice(0, 4).join(", ")}`);
3565
4064
  const folders = /* @__PURE__ */ new Map();
3566
4065
  for (const f of scan.files) {
4066
+ if (TEST_FILE.test(f)) continue;
3567
4067
  const top = f.includes("/") ? f.slice(0, f.indexOf("/")) : "(root)";
3568
4068
  folders.set(top, (folders.get(top) ?? 0) + 1);
3569
4069
  }
3570
4070
  const folderLines = [...folders].sort((a, b) => b[1] - a[1]).map(([d, n]) => ` - ${d}/ (${n} files)`);
4071
+ let recent = null;
4072
+ try {
4073
+ recent = recentChanges(root);
4074
+ } catch {
4075
+ recent = null;
4076
+ }
3571
4077
  const text2 = [
3572
4078
  ...section("Ways in (entry points)", entries),
3573
4079
  ...section("Routes and their handlers", routeLines),
3574
4080
  ...section("Requests from the code that match a route", requests),
3575
4081
  ...section("Tables and what writes them", tables),
3576
4082
  ...section("Top-level folders", folderLines),
3577
- ...section("Functions by file (use these exact names for `symbol`)", symbolIndex(scan), MAX_SYMBOL_FILES)
4083
+ ...functionSection(symbolIndex(scan)),
4084
+ ...recent ? section(recent.title, recent.lines) : []
3578
4085
  ].join("\n");
3579
4086
  return { text: text2 || "(The automatic scan found no entry points; explore the repo directly.)", scan };
3580
4087
  }
@@ -3583,11 +4090,12 @@ var init_hints = __esm({
3583
4090
  "packages/server/src/hints.ts"() {
3584
4091
  "use strict";
3585
4092
  init_src();
4093
+ init_changes();
3586
4094
  MAX_LINES = 40;
3587
4095
  MAX_SYMBOL_FILES = 150;
3588
4096
  MAX_SYMBOLS_PER_FILE = 40;
3589
4097
  CITABLE = /* @__PURE__ */ new Set(["function", "method", "component", "class"]);
3590
- TEST_FILE = /(^|\/)(test|tests|__tests__|fixtures?)\/|\.(test|spec)\.[cm]?[jt]sx?$/;
4098
+ TEST_FILE = /(^|\/)(test|tests|__tests__|__mocks__|e2e|fixtures?)\/|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py)$|(^|\/)test_[^/]*\.py$/;
3591
4099
  section = (title, lines, max = MAX_LINES) => lines.length ? [`${title}:`, ...lines.slice(0, max), ...lines.length > max ? [` \u2026and ${lines.length - max} more`] : [], ""] : [];
3592
4100
  }
3593
4101
  });
@@ -3598,6 +4106,12 @@ function applyPatch(map, output) {
3598
4106
  if (!raw.success) return { ok: false, problems: raw.error.issues.map((i) => `${i.path.join(".") || "(changes)"}: ${i.message}`) };
3599
4107
  return patchMap(map, raw.data);
3600
4108
  }
4109
+ function pinned(parsed, root) {
4110
+ if (!parsed.ok || !parsed.map.since) return parsed;
4111
+ const commit = resolveCommit(root, parsed.map.since);
4112
+ if (!commit) return { ok: false, problems: [`since: "${parsed.map.since}" isn't a commit in this repo. Use "HEAD" for work that isn't committed yet, "HEAD~1" for the last commit, or leave \`since\` out if the map isn't about a change.`] };
4113
+ return { ok: true, map: { ...parsed.map, since: commit } };
4114
+ }
3601
4115
  async function makeMap(o) {
3602
4116
  const status = (text2) => o.onProgress?.({ kind: "status", text: text2 });
3603
4117
  status("Scanning the code for ways in, routes and tables");
@@ -3608,12 +4122,13 @@ async function makeMap(o) {
3608
4122
  let res = await run(makerPrompt(o.question, hints.text), null, MAP_SCHEMA);
3609
4123
  let cost = res.cost ?? 0;
3610
4124
  let rounds = 1;
4125
+ const off = (r) => r.summary.unconfirmed + settledProposals(r).length;
3611
4126
  let best = null;
3612
4127
  let lastProblems = [];
3613
4128
  let reply = "map";
3614
4129
  let current = null;
3615
4130
  for (let attempt = 0; ; attempt++) {
3616
- const parsed = reply === "map" || !current ? parseMap(withQuestion(res.output, o.question)) : applyPatch(current, res.output);
4131
+ const parsed = pinned(reply === "map" || !current ? parseMap(withQuestion(res.output, o.question)) : applyPatch(current, res.output), o.root);
3617
4132
  let repair = null;
3618
4133
  if (!parsed.ok) {
3619
4134
  lastProblems = parsed.problems;
@@ -3622,9 +4137,9 @@ async function makeMap(o) {
3622
4137
  current = parsed.map;
3623
4138
  status("Checking every claim against the code");
3624
4139
  const report = check(parsed.map, o.root);
3625
- if (!best || report.summary.unconfirmed < best.report.summary.unconfirmed) best = { map: parsed.map, report };
4140
+ if (!best || off(report) < off(best.report)) best = { map: parsed.map, report };
3626
4141
  status(`${report.summary.confirmed} of ${report.summary.claims} claims confirmed`);
3627
- if (report.summary.unconfirmed > 0) repair = { prompt: evidenceRepairPrompt(report, symbolsIn), reply: "patch" };
4142
+ if (off(report) > 0) repair = { prompt: evidenceRepairPrompt(report, symbolsIn), reply: "patch" };
3628
4143
  }
3629
4144
  if (!repair || attempt >= (o.repairs ?? 2)) break;
3630
4145
  status(parsed.ok ? "Asking Claude to fix the claims that didn't check out" : current ? "Asking Claude to fix its changes" : "Asking Claude to fix the map's structure");
@@ -3649,17 +4164,17 @@ var init_maker = __esm({
3649
4164
  });
3650
4165
 
3651
4166
  // packages/server/src/store.ts
3652
- import * as fs9 from "node:fs";
4167
+ import * as fs10 from "node:fs";
3653
4168
  import * as path6 from "node:path";
3654
4169
  function createStore(root) {
3655
4170
  const base = path6.join(root, ".illuminate");
3656
4171
  const dir = path6.join(base, "maps");
3657
4172
  const legacy = path6.join(root, ".codemap");
3658
- if (!fs9.existsSync(base) && fs9.existsSync(path6.join(legacy, "maps"))) fs9.renameSync(legacy, base);
4173
+ if (!fs10.existsSync(base) && fs10.existsSync(path6.join(legacy, "maps"))) fs10.renameSync(legacy, base);
3659
4174
  const ensure = () => {
3660
- fs9.mkdirSync(dir, { recursive: true });
4175
+ fs10.mkdirSync(dir, { recursive: true });
3661
4176
  const ignore = path6.join(base, ".gitignore");
3662
- if (!fs9.existsSync(ignore)) fs9.writeFileSync(ignore, "fixes/\nws-modules/\n");
4177
+ if (!fs10.existsSync(ignore)) fs10.writeFileSync(ignore, "fixes/\nws-modules/\n");
3663
4178
  };
3664
4179
  const file = (id) => {
3665
4180
  if (!ID.test(id)) throw new Error(`Not a map id: ${id}`);
@@ -3670,7 +4185,7 @@ function createStore(root) {
3670
4185
  get(id) {
3671
4186
  let raw;
3672
4187
  try {
3673
- raw = JSON.parse(fs9.readFileSync(file(id), "utf8"));
4188
+ raw = JSON.parse(fs10.readFileSync(file(id), "utf8"));
3674
4189
  } catch {
3675
4190
  return null;
3676
4191
  }
@@ -3684,15 +4199,15 @@ function createStore(root) {
3684
4199
  ensure();
3685
4200
  const target = file(stored.meta.id);
3686
4201
  const tmp = `${target}.tmp`;
3687
- fs9.writeFileSync(tmp, `${JSON.stringify(stored, null, 2)}
4202
+ fs10.writeFileSync(tmp, `${JSON.stringify(stored, null, 2)}
3688
4203
  `);
3689
- fs9.renameSync(tmp, target);
4204
+ fs10.renameSync(tmp, target);
3690
4205
  },
3691
4206
  list() {
3692
- if (!fs9.existsSync(dir)) return [];
3693
- return fs9.readdirSync(dir).filter((f) => f.endsWith(".json")).flatMap((f) => {
4207
+ if (!fs10.existsSync(dir)) return [];
4208
+ return fs10.readdirSync(dir).filter((f) => f.endsWith(".json")).flatMap((f) => {
3694
4209
  try {
3695
- const meta = JSON.parse(fs9.readFileSync(path6.join(dir, f), "utf8")).meta;
4210
+ const meta = JSON.parse(fs10.readFileSync(path6.join(dir, f), "utf8")).meta;
3696
4211
  return meta ? [meta] : [];
3697
4212
  } catch {
3698
4213
  return [];
@@ -3704,7 +4219,7 @@ function createStore(root) {
3704
4219
  const base2 = slugify(question);
3705
4220
  for (let i = 1; ; i++) {
3706
4221
  const id = i === 1 ? base2 : `${base2}-${i}`;
3707
- if (!taken.has(id) && !fs9.existsSync(file(id))) return id;
4222
+ if (!taken.has(id) && !fs10.existsSync(file(id))) return id;
3708
4223
  }
3709
4224
  }
3710
4225
  };
@@ -3720,13 +4235,13 @@ var init_store = __esm({
3720
4235
 
3721
4236
  // packages/server/src/server.ts
3722
4237
  import * as crypto4 from "node:crypto";
3723
- import * as fs10 from "node:fs";
4238
+ import * as fs11 from "node:fs";
3724
4239
  import * as http from "node:http";
3725
4240
  import * as path7 from "node:path";
3726
4241
  import { fileURLToPath } from "node:url";
3727
4242
  import { WebSocketServer } from "ws";
3728
4243
  async function startServer(o) {
3729
- const root = fs10.realpathSync(o.root);
4244
+ const root = fs11.realpathSync(o.root);
3730
4245
  const agent = o.agent ?? sdkAgent;
3731
4246
  const token = o.token ?? crypto4.randomBytes(18).toString("base64url");
3732
4247
  const viewerDir = o.viewerDir ?? DEFAULT_VIEWER;
@@ -3832,13 +4347,13 @@ async function startServer(o) {
3832
4347
  const next = {
3833
4348
  ...latest,
3834
4349
  meta: { ...latest.meta, explainerSession: r.sessionId, cost: latest.meta.cost + r.answer.cost, updatedAt: (/* @__PURE__ */ new Date()).toISOString() },
3835
- map: r.answer.added.length || r.answer.screens?.length ? r.map : latest.map,
4350
+ map: r.answer.added.length || r.answer.screens?.length || r.answer.proposed?.length ? r.map : latest.map,
3836
4351
  answers: [...latest.answers ?? [], r.answer],
3837
4352
  fixes: r.answer.fix ? withFix(latest, r.answer.fix.id, { status: "proposed" }) : latest.fixes
3838
4353
  };
3839
4354
  store.save(next);
3840
4355
  endJob(mapId);
3841
- if (r.answer.added.length || r.answer.screens?.length) publishMap(next);
4356
+ if (r.answer.added.length || r.answer.screens?.length || r.answer.proposed?.length) publishMap(next);
3842
4357
  broadcast({ type: "answer", mapId, answer: r.answer });
3843
4358
  broadcast({ type: "job", mapId, job: "ask", status: "done", question: q });
3844
4359
  } catch (err) {
@@ -4008,25 +4523,25 @@ async function startServer(o) {
4008
4523
  }
4009
4524
  function sendFile(res, file, type) {
4010
4525
  res.writeHead(200, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
4011
- fs10.createReadStream(file).pipe(res);
4526
+ fs11.createReadStream(file).pipe(res);
4012
4527
  }
4013
4528
  function serveStatic(res, pathname) {
4014
4529
  const index = path7.join(viewerDir, "index.html");
4015
- if (!fs10.existsSync(index)) {
4530
+ if (!fs11.existsSync(index)) {
4016
4531
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
4017
4532
  return res.end(`<!doctype html><meta charset="utf-8"><title>illuminate</title><p style="font:16px system-ui;margin:40px">The viewer isn't built yet. Run <code>npm run build</code> in the illuminate repo, then reload.</p>`);
4018
4533
  }
4019
4534
  const rel = decodeURIComponent(pathname).replace(/^\/+/, "");
4020
4535
  const file = path7.resolve(viewerDir, rel);
4021
4536
  const inside = file.startsWith(path7.resolve(viewerDir) + path7.sep);
4022
- const target = inside && rel.startsWith("assets/") && fs10.existsSync(file) && fs10.statSync(file).isFile() ? file : index;
4537
+ const target = inside && rel.startsWith("assets/") && fs11.existsSync(file) && fs11.statSync(file).isFile() ? file : index;
4023
4538
  res.writeHead(200, {
4024
4539
  "content-type": TYPES[path7.extname(target)] ?? "application/octet-stream",
4025
4540
  "cache-control": target === index ? "no-store" : "public, max-age=31536000, immutable",
4026
4541
  "x-content-type-options": "nosniff",
4027
4542
  ...target === index ? { "content-security-policy": "default-src 'self'; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'" } : {}
4028
4543
  });
4029
- fs10.createReadStream(target).pipe(res);
4544
+ fs11.createReadStream(target).pipe(res);
4030
4545
  }
4031
4546
  const server = http.createServer((req, res) => {
4032
4547
  void (async () => {
@@ -4115,7 +4630,7 @@ var init_server = __esm({
4115
4630
  init_git();
4116
4631
  init_maker();
4117
4632
  init_store();
4118
- DEFAULT_VIEWER = [new URL("../viewer/", import.meta.url), new URL("../../viewer/dist/", import.meta.url)].map((u) => fileURLToPath(u)).find((dir) => fs10.existsSync(path7.join(dir, "index.html"))) ?? fileURLToPath(new URL("../../viewer/dist/", import.meta.url));
4633
+ DEFAULT_VIEWER = [new URL("../viewer/", import.meta.url), new URL("../../viewer/dist/", import.meta.url)].map((u) => fileURLToPath(u)).find((dir) => fs11.existsSync(path7.join(dir, "index.html"))) ?? fileURLToPath(new URL("../../viewer/dist/", import.meta.url));
4119
4634
  TYPES = {
4120
4635
  ".html": "text/html; charset=utf-8",
4121
4636
  ".js": "text/javascript",
@@ -4273,15 +4788,15 @@ var init_bridge = __esm({
4273
4788
  // packages/server/src/screens.ts
4274
4789
  import { spawn as spawn2 } from "node:child_process";
4275
4790
  import * as crypto5 from "node:crypto";
4276
- import * as fs11 from "node:fs";
4791
+ import * as fs12 from "node:fs";
4277
4792
  import * as os from "node:os";
4278
4793
  import * as path8 from "node:path";
4279
4794
  import { pathToFileURL } from "node:url";
4280
4795
  import { WebSocket } from "ws";
4281
4796
  function findChrome() {
4282
4797
  const given = process.env.ILLUMINATE_CHROME;
4283
- if (given) return fs11.existsSync(given) ? given : null;
4284
- return CHROME_PATHS.find((p) => fs11.existsSync(p)) ?? null;
4798
+ if (given) return fs12.existsSync(given) ? given : null;
4799
+ return CHROME_PATHS.find((p) => fs12.existsSync(p)) ?? null;
4285
4800
  }
4286
4801
  function resolveTarget(root, target) {
4287
4802
  if ("url" in target) {
@@ -4297,10 +4812,10 @@ function resolveTarget(root, target) {
4297
4812
  }
4298
4813
  const rel = target.file;
4299
4814
  if (!isSafeRelativePath(rel) || isSecretPath(rel) || !/\.html?$/i.test(rel)) return { ok: false, reason: "`file` must be an .html file inside the repo." };
4300
- const realRoot = fs11.realpathSync(root);
4815
+ const realRoot = fs12.realpathSync(root);
4301
4816
  let real;
4302
4817
  try {
4303
- real = fs11.realpathSync(path8.join(realRoot, rel));
4818
+ real = fs12.realpathSync(path8.join(realRoot, rel));
4304
4819
  } catch {
4305
4820
  return { ok: false, reason: `${rel} doesn't exist.` };
4306
4821
  }
@@ -4327,10 +4842,10 @@ async function capture(root, target, shoot = shootWithChrome) {
4327
4842
  takenAt: (/* @__PURE__ */ new Date()).toISOString(),
4328
4843
  elements: shot.elements
4329
4844
  };
4330
- const p = capturePaths(fs11.realpathSync(root), id);
4331
- fs11.mkdirSync(path8.dirname(p.image), { recursive: true });
4332
- fs11.writeFileSync(p.image, shot.png);
4333
- fs11.writeFileSync(p.record, `${JSON.stringify(record, null, 2)}
4845
+ const p = capturePaths(fs12.realpathSync(root), id);
4846
+ fs12.mkdirSync(path8.dirname(p.image), { recursive: true });
4847
+ fs12.writeFileSync(p.image, shot.png);
4848
+ fs12.writeFileSync(p.record, `${JSON.stringify(record, null, 2)}
4334
4849
  `);
4335
4850
  return { ok: true, result: { capture: record, png: shot.png, text: shot.text } };
4336
4851
  }
@@ -4354,7 +4869,7 @@ async function listScreens(root, o = {}) {
4354
4869
  const pages = (await Promise.all(ports.map(probe))).filter((p) => !!p);
4355
4870
  let scripts = {};
4356
4871
  try {
4357
- scripts = JSON.parse(fs11.readFileSync(path8.join(root, "package.json"), "utf8")).scripts ?? {};
4872
+ scripts = JSON.parse(fs12.readFileSync(path8.join(root, "package.json"), "utf8")).scripts ?? {};
4358
4873
  } catch {
4359
4874
  }
4360
4875
  const few = (list, max) => [...list.slice(0, max).map((f) => ` - ${f}`), ...list.length > max ? [` - \u2026and ${list.length - max} more`] : []];
@@ -4422,7 +4937,7 @@ var init_screens2 = __esm({
4422
4937
  shootWithChrome = async (url) => {
4423
4938
  const chrome = findChrome();
4424
4939
  if (!chrome) throw new Error("No Chrome, Chromium, Edge or Brave was found on this machine, so no screen can be captured. Use an image file or a sketch instead.");
4425
- const profile = fs11.mkdtempSync(path8.join(os.tmpdir(), "illuminate-chrome-"));
4940
+ const profile = fs12.mkdtempSync(path8.join(os.tmpdir(), "illuminate-chrome-"));
4426
4941
  let child = null;
4427
4942
  let ws = null;
4428
4943
  try {
@@ -4500,7 +5015,7 @@ var init_screens2 = __esm({
4500
5015
  } finally {
4501
5016
  ws?.close();
4502
5017
  child?.kill("SIGKILL");
4503
- setTimeout(() => fs11.rm(profile, { recursive: true, force: true }, () => {
5018
+ setTimeout(() => fs12.rm(profile, { recursive: true, force: true }, () => {
4504
5019
  }), 500).unref?.();
4505
5020
  }
4506
5021
  };
@@ -4515,7 +5030,7 @@ __export(channel_exports, {
4515
5030
  requestText: () => requestText,
4516
5031
  runChannel: () => runChannel
4517
5032
  });
4518
- import * as fs12 from "node:fs";
5033
+ import * as fs13 from "node:fs";
4519
5034
  import * as path9 from "node:path";
4520
5035
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4521
5036
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -4562,8 +5077,8 @@ function createChannel(o) {
4562
5077
  });
4563
5078
  const rootOf2 = (repo) => {
4564
5079
  const dir = path9.resolve(o.root, typeof repo === "string" && repo.trim() ? repo : ".");
4565
- if (!fs12.existsSync(dir) || !fs12.statSync(dir).isDirectory()) throw new Error(`No such folder: ${dir}`);
4566
- return fs12.realpathSync(dir);
5080
+ if (!fs13.existsSync(dir) || !fs13.statSync(dir).isDirectory()) throw new Error(`No such folder: ${dir}`);
5081
+ return fs13.realpathSync(dir);
4567
5082
  };
4568
5083
  const serverFor = (root) => {
4569
5084
  let s = servers.get(root);
@@ -4807,7 +5322,9 @@ var init_channel = __esm({
4807
5322
  init_store();
4808
5323
  CHANNEL_INSTRUCTIONS = [
4809
5324
  "illuminate draws checked, interactive maps of how this codebase works, in the person's browser. You do the reading and writing; illuminate checks every claim against the code before it shows anything.",
4810
- '- When the person asks how something works across files ("what happens when\u2026", "how does X reach Y", "what did this change do") or asks for a map, diagram or walkthrough, call illuminate_map with their question in their own words.',
5325
+ `- When the person asks how something works across files ("what happens when\u2026", "how does X reach Y", "what did this change do"), what someone sees or goes through in the app (a user journey), or how a change would look before it's made ("how would we add\u2026", "plan\u2026"), or asks for a map, diagram or walkthrough, call illuminate_map with their question in their own words.`,
5326
+ "- A map can hold proposals: boxes and arrows that aren't in the code yet, or that would change or go, drawn on top of the code as it is. The request explains how. illuminate works out from the code which proposals are done, so after you build a change you proposed on a map, the person can reopen that map to see it.",
5327
+ '- A map can show a change that was made: "what did you just change?", "what did the last commit do?". The request explains how. You draw the code as it is now and name the commit to compare with; illuminate works out from the two versions what is new, different or gone. Use it when the person wants to see what a task changed.',
4811
5328
  "- illuminate gives you work as requests in tool results. Each request says what to do and the JSON to return. Explore the code with Read, Grep and Glob, then call illuminate_submit with the request_id and your output. If the result holds another request, do that one too. If you can't finish one, call illuminate_fail.",
4812
5329
  "- Once a map is ready or an answer is shown, call illuminate_listen and leave it running. It moves to the background, so the person keeps their terminal. When they ask something on the map it returns with a request: do it, submit it, then call illuminate_listen again. If it returns saying nothing was asked yet, call it again without telling the person. Only one is needed at a time.",
4813
5330
  "- A picture of the screen can ground a map for people who don't read code. Use your judgement: when a flow starts from something the person sees (a button, a form, a page) a screen on that box helps; for backend-only questions leave screens out. illuminate_screens lists what this repo can show; illuminate_capture screenshots a page already running on this machine, or an HTML file in the repo, and shows you the result. Look at it before using it: if it shows a login page, an error or the wrong state, don't use it. Never start the app yourself to get a screenshot.",
@@ -4895,7 +5412,7 @@ var init_channel = __esm({
4895
5412
 
4896
5413
  // packages/server/src/cli.ts
4897
5414
  init_browser();
4898
- import * as fs13 from "node:fs";
5415
+ import * as fs14 from "node:fs";
4899
5416
  import * as path10 from "node:path";
4900
5417
 
4901
5418
  // packages/server/src/cli-support.ts
@@ -4952,7 +5469,7 @@ async function main() {
4952
5469
  const { runChannel: runChannel2 } = await Promise.resolve().then(() => (init_channel(), channel_exports));
4953
5470
  return runChannel2({ root: args.repoGiven ? args.repo : void 0, port: args.port });
4954
5471
  }
4955
- if (!fs13.existsSync(args.repo)) throw new Error(`No such folder: ${args.repo}`);
5472
+ if (!fs14.existsSync(args.repo)) throw new Error(`No such folder: ${args.repo}`);
4956
5473
  if (args.command === "list") {
4957
5474
  const maps = createStore(args.repo).list();
4958
5475
  if (!maps.length) return console.log('No maps yet. Try: illume "what happens when \u2026?"');
@@ -4963,7 +5480,7 @@ async function main() {
4963
5480
  const target = args.rest[0];
4964
5481
  if (!target) throw new Error("Which map? illume check <map-id|file>");
4965
5482
  await initTreeSitterForChecks();
4966
- const raw = fs13.existsSync(target) ? JSON.parse(fs13.readFileSync(target, "utf8")) : createStore(args.repo).get(target);
5483
+ const raw = fs14.existsSync(target) ? JSON.parse(fs14.readFileSync(target, "utf8")) : createStore(args.repo).get(target);
4967
5484
  if (!raw) throw new Error(`No map "${target}" in ${args.repo}/.illuminate/maps`);
4968
5485
  const parsed = parseMap("map" in raw ? raw.map : raw);
4969
5486
  if (!parsed.ok) throw new Error(`The map isn't valid:
@@ -4971,8 +5488,10 @@ ${parsed.problems.join("\n")}`);
4971
5488
  const report = check(parsed.map, args.repo);
4972
5489
  console.log(`${report.summary.confirmed} of ${report.summary.claims} claims confirmed`);
4973
5490
  for (const [kind, group] of [["box", report.nodes], ["arrow", report.edges], ["missing connection", report.absences]]) {
4974
- for (const [id, c] of Object.entries(group)) if (c.status !== "confirmed") console.log(` \u2717 ${kind} ${id}: ${c.reasons.join("; ")}`);
5491
+ for (const [id, c] of Object.entries(group)) if (c.status === "unconfirmed") console.log(` \u2717 ${kind} ${id}: ${c.reasons.join("; ")}`);
4975
5492
  }
5493
+ const { pending, done } = report.summary.proposals;
5494
+ if (pending + done) console.log(`${done} of ${pending + done} proposed changes are done in the code`);
4976
5495
  process.exitCode = report.summary.unconfirmed ? 1 : 0;
4977
5496
  return;
4978
5497
  }