@johnz4021/illuminate 0.1.0 → 0.3.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,70 @@ 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 pages = new Map((map.pages ?? []).map((p) => [p.id, p]));
2322
+ ids("page", map.pages ?? []);
2323
+ for (const p of map.pages ?? []) {
2324
+ ids(`page "${p.id}" region`, p.regions);
2325
+ for (const f of [p.file, ...p.regions.map((r) => r.file)]) if (!isSafeRelativePath(f)) problems.push(`page "${p.id}": file "${f}" must be a path inside the repo`);
2326
+ if (p.regions.some((r) => r.elements.some((e) => e.proposed))) problems.push(`page "${p.id}": a page shows the screen as it is, so its elements can't be \`proposed\` (use a sketch on the proposed box for that)`);
2327
+ }
2328
+ const evidence = (where, item) => {
2329
+ if (!item.evidence.length && !isAddition(item)) problems.push(`${where}: cite at least one line of code in \`evidence\` (only a proposed addition goes without)`);
2330
+ for (const e of item.evidence) if (!isSafeRelativePath(e.file)) problems.push(`${where}: evidence file "${e.file}" must be a path inside the repo`);
2331
+ };
2332
+ const added = new Set(map.nodes.filter(isAddition).map((n) => n.id));
2333
+ const removed = new Set(map.nodes.filter((n) => n.removed).map((n) => n.id));
2334
+ const gone = (where, item) => {
2335
+ if (!item.removed) return;
2336
+ if (!map.since) problems.push(`${where}: \`removed\` needs the map's \`since\` (the commit it was removed after)`);
2337
+ if (item.proposed) problems.push(`${where}: it can't be both \`removed\` (already gone) and \`proposed\` (not done yet)`);
2253
2338
  };
2254
2339
  for (const n of map.nodes) {
2255
2340
  if (!areas.has(n.area)) problems.push(`node "${n.id}": unknown area "${n.area}"`);
2256
2341
  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);
2342
+ evidence(`node "${n.id}"`, n);
2258
2343
  const sc = n.screen;
2259
2344
  if (sc?.kind === "capture" && !sc.capture) problems.push(`node "${n.id}": a capture screen needs the \`capture\` id illuminate_capture returned`);
2260
- 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`);
2345
+ if (sc && (sc.kind === "image" || sc.kind === "sketch") && (!sc.file || !isSafeRelativePath(sc.file))) problems.push(`node "${n.id}": a ${sc.kind} screen needs \`file\`, a path inside the repo`);
2346
+ if (sc?.kind === "wireframe") {
2347
+ const page = pages.get(sc.page ?? "");
2348
+ if (!page) problems.push(`node "${n.id}": a wireframe screen needs \`page\`, the id of one of the map's \`pages\`${sc.page ? ` (there is no page "${sc.page}")` : ""}`);
2349
+ else if (sc.region && !page.regions.some((r) => r.id === sc.region)) problems.push(`node "${n.id}": page "${page.id}" has no region "${sc.region}"`);
2350
+ if (sc.highlight && !sc.region) problems.push(`node "${n.id}": a wireframe's \`highlight\` needs the \`region\` the element is in`);
2351
+ }
2261
2352
  if (sc?.kind === "sketch" && !sc.elements) problems.push(`node "${n.id}": a sketch screen needs \`elements\``);
2353
+ 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`);
2354
+ gone(`node "${n.id}"`, n);
2262
2355
  }
2263
2356
  for (const e of map.edges) {
2264
2357
  if (!nodes.has(e.from)) problems.push(`edge "${e.id}": unknown node "${e.from}"`);
2265
2358
  if (!nodes.has(e.to)) problems.push(`edge "${e.id}": unknown node "${e.to}"`);
2266
- evidence(`edge "${e.id}"`, e.evidence);
2359
+ evidence(`edge "${e.id}"`, e);
2360
+ const end = [e.from, e.to].find((id) => added.has(id));
2361
+ 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" })`);
2362
+ gone(`edge "${e.id}"`, e);
2363
+ const wasAt = [e.from, e.to].find((id) => removed.has(id));
2364
+ 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)`);
2365
+ }
2366
+ if (added.size) {
2367
+ const anchored = new Set(map.nodes.filter((n) => !added.has(n.id)).map((n) => n.id));
2368
+ for (let grew = true; grew; ) {
2369
+ grew = false;
2370
+ for (const e of map.edges) {
2371
+ if (anchored.has(e.from) === anchored.has(e.to)) continue;
2372
+ anchored.add(e.from).add(e.to);
2373
+ grew = true;
2374
+ }
2375
+ }
2376
+ 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
2377
  }
2268
2378
  for (const a of map.absences) {
2269
2379
  if (a.between && !nodes.has(a.between.from)) problems.push(`absence "${a.id}": unknown node "${a.between.from}"`);
2270
2380
  if (a.between && !nodes.has(a.between.to)) problems.push(`absence "${a.id}": unknown node "${a.between.to}"`);
2381
+ const end = a.between && [a.between.from, a.between.to].find((id) => added.has(id));
2382
+ if (end) problems.push(`absence "${a.id}": box "${end}" is a proposed addition; an absence is about the code as it is`);
2383
+ const was = a.between && [a.between.from, a.between.to].find((id) => removed.has(id));
2384
+ if (was) problems.push(`absence "${a.id}": box "${was}" was removed; an absence is about the code as it is`);
2271
2385
  }
2272
2386
  for (const t of map.tour) {
2273
2387
  const refs = [
@@ -2280,7 +2394,7 @@ function parseMap(input) {
2280
2394
  }
2281
2395
  return problems.length ? { ok: false, problems } : { ok: true, map };
2282
2396
  }
2283
- var Id, Evidence, NodeKind, EdgeKind, ScreenElement, Screen, Area, Node, Edge, Absence, TourStop, CodeMap;
2397
+ var Id, Evidence, NodeKind, EdgeKind, ScreenElement, Screen, Slot, PageRegion, Page, Proposal, GitRef, Area, Node, Edge, Absence, TourStop, CodeMap, isAddition;
2284
2398
  var init_format = __esm({
2285
2399
  "packages/core/src/format.ts"() {
2286
2400
  "use strict";
@@ -2290,16 +2404,44 @@ var init_format = __esm({
2290
2404
  line: z.number().int().positive(),
2291
2405
  text: z.string().min(1).max(400)
2292
2406
  });
2293
- NodeKind = z.enum(["entry", "step", "store", "external", "job"]);
2407
+ NodeKind = z.enum(["entry", "step", "store", "external", "job", "screen", "action", "choice"]);
2294
2408
  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) });
2409
+ ScreenElement = z.object({
2410
+ kind: z.enum(["heading", "button", "field", "link", "text", "image"]),
2411
+ text: z.string().min(1).max(80),
2412
+ /** Not on the screen yet: something a proposal would put there. Only on a box that carries `proposed`. */
2413
+ proposed: z.boolean().optional()
2414
+ });
2296
2415
  Screen = z.object({
2297
- kind: z.enum(["capture", "image", "sketch"]),
2416
+ kind: z.enum(["capture", "image", "sketch", "wireframe"]),
2298
2417
  capture: Id.optional(),
2418
+ /** For a wireframe: the id of one of the map's `pages`, and of the region of it this box is about. */
2419
+ page: Id.optional(),
2420
+ region: Id.optional(),
2299
2421
  file: z.string().min(1).optional(),
2300
2422
  elements: z.array(ScreenElement).min(1).max(12).optional(),
2301
2423
  highlight: z.string().min(1).max(80).optional()
2302
2424
  });
2425
+ Slot = z.enum(["top", "left", "main", "right", "bottom"]);
2426
+ PageRegion = z.object({
2427
+ id: Id,
2428
+ slot: Slot,
2429
+ label: z.string().min(1).max(40),
2430
+ file: z.string().min(1),
2431
+ elements: z.array(ScreenElement).max(6).default([])
2432
+ });
2433
+ Page = z.object({
2434
+ id: Id,
2435
+ name: z.string().min(1).max(60),
2436
+ file: z.string().min(1),
2437
+ regions: z.array(PageRegion).min(1).max(8)
2438
+ });
2439
+ Proposal = z.object({
2440
+ kind: z.enum(["add", "change", "remove"]),
2441
+ /** What would change and why, in a plain sentence. */
2442
+ note: z.string().min(1).max(300).optional()
2443
+ });
2444
+ GitRef = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_./~^-]{0,99}$/, 'a commit, branch or tag name, e.g. "HEAD"');
2303
2445
  Area = z.object({ id: Id, label: z.string().min(1).max(40) });
2304
2446
  Node = z.object({
2305
2447
  id: Id,
@@ -2309,8 +2451,12 @@ var init_format = __esm({
2309
2451
  /** `<file>#<symbol>` as the facts name it, e.g. `src/patients/service.ts#markConverted`. */
2310
2452
  symbol: z.string().regex(/^[^#]+#.+$/, "symbol is <file>#<name>").optional(),
2311
2453
  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()
2454
+ /** At least one line, except on a proposed addition (`parseMap` enforces it). */
2455
+ evidence: z.array(Evidence).default([]),
2456
+ screen: Screen.optional(),
2457
+ proposed: Proposal.optional(),
2458
+ /** Only on a map with `since`: this code was there at that commit and is gone now. Its `evidence` cites it as it was. */
2459
+ removed: z.boolean().optional()
2314
2460
  });
2315
2461
  Edge = z.object({
2316
2462
  id: Id,
@@ -2318,7 +2464,11 @@ var init_format = __esm({
2318
2464
  to: Id,
2319
2465
  kind: EdgeKind.default("then"),
2320
2466
  label: z.string().min(1).max(60),
2321
- evidence: z.array(Evidence).min(1)
2467
+ /** At least one line, except on a proposed addition (`parseMap` enforces it). */
2468
+ evidence: z.array(Evidence).default([]),
2469
+ proposed: Proposal.optional(),
2470
+ /** Only on a map with `since`: this connection was there at that commit and is gone now. Its `evidence` cites it as it was. */
2471
+ removed: z.boolean().optional()
2322
2472
  });
2323
2473
  Absence = z.object({
2324
2474
  id: Id,
@@ -2351,12 +2501,23 @@ var init_format = __esm({
2351
2501
  question: z.string().min(1).max(300),
2352
2502
  /** The commit the map was made from, when known. */
2353
2503
  commit: z.string().nullable().optional(),
2504
+ /** `journey`: drawn as a user flow (left to right, shapes by kind, no code on the boxes). The claims are checked the same. */
2505
+ view: z.enum(["journey"]).optional(),
2506
+ /**
2507
+ * Set on a map of a change: the commit the code is compared with. The checker marks each box and arrow that is new
2508
+ * or different since then, and confirms the ones the map says were `removed`. Stored as a full hash once resolved,
2509
+ * so the comparison stays the same after later commits.
2510
+ */
2511
+ since: GitRef.optional(),
2512
+ /** The pages boxes show as wireframes (`screen.kind: 'wireframe'`). */
2513
+ pages: z.array(Page).optional(),
2354
2514
  areas: z.array(Area).min(1),
2355
2515
  nodes: z.array(Node).min(1),
2356
2516
  edges: z.array(Edge).default([]),
2357
2517
  absences: z.array(Absence).default([]),
2358
2518
  tour: z.array(TourStop).default([])
2359
2519
  });
2520
+ isAddition = (x) => x.proposed?.kind === "add";
2360
2521
  }
2361
2522
  });
2362
2523
 
@@ -2480,9 +2641,123 @@ var init_repo = __esm({
2480
2641
  }
2481
2642
  });
2482
2643
 
2644
+ // packages/core/src/base.ts
2645
+ import { execFileSync as execFileSync2 } from "node:child_process";
2646
+ import * as fs6 from "node:fs";
2647
+ function resolveCommit(root, ref) {
2648
+ if (!GitRef.safeParse(ref).success) return null;
2649
+ const out = git(root, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`])?.trim();
2650
+ return out && /^[0-9a-f]{40,64}$/.test(out) ? out : null;
2651
+ }
2652
+ function commitInfo(root, commit) {
2653
+ const out = git(root, ["show", "-s", "--format=%cI%x00%s", "--end-of-options", commit])?.trim();
2654
+ if (!out) return { date: null, subject: null };
2655
+ const [date, subject] = out.split("\0");
2656
+ return { date: date || null, subject: subject || null };
2657
+ }
2658
+ function createBaseReader(root, ref) {
2659
+ const realRoot = fs6.realpathSync(root);
2660
+ const commit = resolveCommit(realRoot, ref);
2661
+ if (!commit) return null;
2662
+ let files = null;
2663
+ const has = (rel) => (files ??= new Set((git(realRoot, ["ls-tree", "-r", "--name-only", "-z", commit]) ?? "").split("\0").filter(Boolean))).has(rel);
2664
+ const cache2 = /* @__PURE__ */ new Map();
2665
+ const readUncached = (rel) => {
2666
+ if (!isSafeRelativePath(rel)) return { ok: false, reason: "path is outside the repo" };
2667
+ if (isSecretPath(rel)) return { ok: false, reason: "secret files are never read" };
2668
+ if (!has(rel)) return { ok: false, reason: "file not found" };
2669
+ const text2 = git(realRoot, ["show", `${commit}:./${rel}`]);
2670
+ if (text2 === null) return { ok: false, reason: "file not found" };
2671
+ if (text2.length > MAX_FILE_BYTES) return { ok: false, reason: "file is too large to check" };
2672
+ if (text2.slice(0, 8e3).includes("\0")) return { ok: false, reason: "binary file" };
2673
+ return { ok: true, text: text2 };
2674
+ };
2675
+ const read = (rel) => {
2676
+ let hit = cache2.get(rel);
2677
+ if (!hit) cache2.set(rel, hit = readUncached(rel));
2678
+ return hit;
2679
+ };
2680
+ return { root: realRoot, commit, has, read, text: (rel) => {
2681
+ const r = read(rel);
2682
+ return r.ok ? r.text : null;
2683
+ } };
2684
+ }
2685
+ function lineDiff(before, after, context = 2, max = 60) {
2686
+ const a = before.split("\n");
2687
+ const b = after.split("\n");
2688
+ let start = 0;
2689
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
2690
+ let endA = a.length;
2691
+ let endB = b.length;
2692
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
2693
+ endA--;
2694
+ endB--;
2695
+ }
2696
+ const n = endA - start;
2697
+ const m = endB - start;
2698
+ if (n * m > 1e6) return null;
2699
+ const lcs = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
2700
+ for (let i = n - 1; i >= 0; i--) {
2701
+ for (let j = m - 1; j >= 0; j--) {
2702
+ 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]);
2703
+ }
2704
+ }
2705
+ const ops = a.slice(0, start).map((l) => [" ", l]);
2706
+ for (let i = 0, j = 0; i < n || j < m; ) {
2707
+ if (i < n && j < m && a[start + i] === b[start + j]) {
2708
+ ops.push([" ", a[start + i]]);
2709
+ i++;
2710
+ j++;
2711
+ } else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) {
2712
+ ops.push(["-", a[start + i]]);
2713
+ i++;
2714
+ } else {
2715
+ ops.push(["+", b[start + j]]);
2716
+ j++;
2717
+ }
2718
+ }
2719
+ for (const l of a.slice(endA)) ops.push([" ", l]);
2720
+ const keep = ops.map(() => false);
2721
+ ops.forEach(([op], i) => {
2722
+ if (op === " ") return;
2723
+ for (let k = Math.max(0, i - context); k <= Math.min(ops.length - 1, i + context); k++) keep[k] = true;
2724
+ });
2725
+ const out = [];
2726
+ let skipped = false;
2727
+ for (const [i, [op, line]] of ops.entries()) {
2728
+ if (!keep[i]) {
2729
+ skipped = true;
2730
+ continue;
2731
+ }
2732
+ if (skipped && out.length) out.push("\u2026");
2733
+ skipped = false;
2734
+ if (out.length >= max) {
2735
+ out.push("\u2026");
2736
+ break;
2737
+ }
2738
+ out.push(`${op === " " ? " " : `${op} `}${line}`);
2739
+ }
2740
+ return out;
2741
+ }
2742
+ var git;
2743
+ var init_base = __esm({
2744
+ "packages/core/src/base.ts"() {
2745
+ "use strict";
2746
+ init_format();
2747
+ init_repo();
2748
+ git = (root, args) => {
2749
+ try {
2750
+ return execFileSync2("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).toString();
2751
+ } catch {
2752
+ return null;
2753
+ }
2754
+ };
2755
+ }
2756
+ });
2757
+
2483
2758
  // packages/core/src/screens.ts
2484
2759
  import * as crypto from "node:crypto";
2485
- import * as fs6 from "node:fs";
2760
+ import * as fs7 from "node:fs";
2486
2761
  import * as path3 from "node:path";
2487
2762
  import { z as z2 } from "zod";
2488
2763
  function readCapture(root, id) {
@@ -2490,7 +2765,7 @@ function readCapture(root, id) {
2490
2765
  const p = capturePaths(root, id);
2491
2766
  let capture2;
2492
2767
  try {
2493
- const parsed = Capture.safeParse(JSON.parse(fs6.readFileSync(p.record, "utf8")));
2768
+ const parsed = Capture.safeParse(JSON.parse(fs7.readFileSync(p.record, "utf8")));
2494
2769
  if (!parsed.success || parsed.data.id !== id) return { ok: false, reason: `the record of capture ${id} can't be read` };
2495
2770
  capture2 = parsed.data;
2496
2771
  } catch {
@@ -2498,7 +2773,7 @@ function readCapture(root, id) {
2498
2773
  }
2499
2774
  let image;
2500
2775
  try {
2501
- image = fs6.readFileSync(p.image);
2776
+ image = fs7.readFileSync(p.image);
2502
2777
  } catch {
2503
2778
  return { ok: false, reason: `the image of capture ${id} is missing` };
2504
2779
  }
@@ -2510,15 +2785,15 @@ function repoImage(root, rel) {
2510
2785
  if (isSecretPath(rel)) return { ok: false, reason: "secret files are never shown" };
2511
2786
  const type = IMAGE_TYPES[path3.extname(rel).toLowerCase()];
2512
2787
  if (!type) return { ok: false, reason: `${rel} is not an image file` };
2513
- const realRoot = fs6.realpathSync(root);
2788
+ const realRoot = fs7.realpathSync(root);
2514
2789
  let real;
2515
2790
  try {
2516
- real = fs6.realpathSync(path3.join(realRoot, rel));
2791
+ real = fs7.realpathSync(path3.join(realRoot, rel));
2517
2792
  } catch {
2518
2793
  return { ok: false, reason: `${rel} doesn't exist` };
2519
2794
  }
2520
2795
  if (!real.startsWith(realRoot + path3.sep)) return { ok: false, reason: `${rel} is outside the repo` };
2521
- const stat = fs6.statSync(real);
2796
+ const stat = fs7.statSync(real);
2522
2797
  if (!stat.isFile()) return { ok: false, reason: `${rel} is not a file` };
2523
2798
  if (stat.size > MAX_IMAGE_BYTES) return { ok: false, reason: `${rel} is too large to show` };
2524
2799
  return { ok: true, path: real, type };
@@ -2530,12 +2805,47 @@ function findOnCapture(capture2, label) {
2530
2805
  const holding = capture2.elements.filter((e) => norm(e.text).includes(want)).sort((a, b) => a.w * a.h - b.w * b.h);
2531
2806
  return holding[0] ?? null;
2532
2807
  }
2533
- function checkScreen(n, repo) {
2808
+ function checkPage(page, repo, importsOf) {
2809
+ const own = repo.read(page.file);
2810
+ if (!own.ok) return { show: null, reason: `${page.file}: ${own.reason}`, dropped: {} };
2811
+ const reached = /* @__PURE__ */ new Set([page.file]);
2812
+ for (const queue = [page.file]; queue.length && reached.size < MAX_PAGE_FILES; ) {
2813
+ for (const to of importsOf(queue.shift())) {
2814
+ if (reached.has(to)) continue;
2815
+ reached.add(to);
2816
+ queue.push(to);
2817
+ }
2818
+ }
2819
+ const dropped = {};
2820
+ const regions = [];
2821
+ for (const r of page.regions) {
2822
+ const read = repo.read(r.file);
2823
+ const missing = read.ok ? r.elements.filter((e) => !norm(read.text).includes(norm(e.text))) : [];
2824
+ if (!read.ok) dropped[r.id] = `${r.file}: ${read.reason}`;
2825
+ else if (!reached.has(r.file)) dropped[r.id] = `${r.file} isn't part of this page: ${page.file} doesn't bring it in`;
2826
+ else if (missing.length) dropped[r.id] = missing.map((e) => `"${e.text}" isn't in ${r.file}`).join("; ");
2827
+ else regions.push({ id: r.id, slot: r.slot, label: r.label, file: r.file, elements: r.elements.map((e) => ({ kind: e.kind, text: e.text })) });
2828
+ }
2829
+ if (!regions.length) return { show: null, reason: `no region of page "${page.id}" checked out: ${Object.values(dropped).join("; ")}`, dropped };
2830
+ return { show: { id: page.id, name: page.name, file: page.file, regions }, reason: null, dropped };
2831
+ }
2832
+ function checkScreen(n, repo, pageOf = () => null) {
2534
2833
  const sc = n.screen;
2535
2834
  if (!sc) return null;
2536
2835
  const fail = (...reasons) => ({ status: "unconfirmed", reasons, show: null });
2537
2836
  const cited = [...new Set(n.evidence.map((e) => e.file))];
2538
2837
  const inCitedCode = (text3) => cited.some((f) => norm(repo.text(f) ?? "").includes(norm(text3)));
2838
+ if (sc.kind === "wireframe") {
2839
+ const page = pageOf(sc.page ?? "");
2840
+ if (!page) return fail(`the map has no page "${sc.page ?? ""}"`);
2841
+ if (!page.show) return fail(page.reason ?? "the page could not be checked");
2842
+ const region = sc.region ? page.show.regions.find((r) => r.id === sc.region) : null;
2843
+ if (sc.region && !region) return fail(page.dropped[sc.region] ?? `page "${page.show.id}" has no region "${sc.region}"`);
2844
+ if (sc.highlight && !region?.elements.some((e) => norm(e.text) === norm(sc.highlight))) return fail(`the highlight "${sc.highlight}" isn't one of the elements of region "${sc.region ?? ""}"`);
2845
+ const about = cited.includes(page.show.file) || !!region && cited.includes(region.file) || !!sc.highlight && inCitedCode(sc.highlight);
2846
+ if (!about) return fail(`the code this box cites (${cited.join(", ")}) isn't part of what it marks on page "${page.show.id}"`);
2847
+ return { status: "confirmed", reasons: [], show: { kind: "wireframe", page: page.show, region: region?.id ?? null, highlight: sc.highlight ?? null } };
2848
+ }
2539
2849
  if (sc.kind === "capture") {
2540
2850
  const got = readCapture(repo.root, sc.capture ?? "");
2541
2851
  if (!got.ok) return fail(got.reason);
@@ -2558,15 +2868,17 @@ function checkScreen(n, repo) {
2558
2868
  return { status: "confirmed", reasons: [], show: { kind: "image", file } };
2559
2869
  }
2560
2870
  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)));
2871
+ const adding = isAddition(n);
2872
+ if (!read.ok && !adding) return fail(`${file}: ${read.reason}`);
2873
+ const text2 = read.ok ? norm(read.text) : "";
2874
+ const written = sc.elements ?? [];
2875
+ const missing = written.filter((e) => !(adding || e.proposed) && !text2.includes(norm(e.text)));
2565
2876
  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`);
2877
+ 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`);
2878
+ const elements = written.map((e) => ({ kind: e.kind, text: e.text, ...text2.includes(norm(e.text)) ? {} : { proposed: true } }));
2567
2879
  return { status: "confirmed", reasons: [], show: { kind: "sketch", file, elements, highlight: sc.highlight ?? null } };
2568
2880
  }
2569
- var SCREENS_DIR, IMAGE_TYPES, MAX_IMAGE_BYTES, CAPTURE_ID, CapturedElement, Capture, norm, capturePaths;
2881
+ var SCREENS_DIR, IMAGE_TYPES, MAX_IMAGE_BYTES, CAPTURE_ID, CapturedElement, Capture, norm, capturePaths, MAX_PAGE_FILES;
2570
2882
  var init_screens = __esm({
2571
2883
  "packages/core/src/screens.ts"() {
2572
2884
  "use strict";
@@ -2601,6 +2913,7 @@ var init_screens = __esm({
2601
2913
  record: path3.join(root, SCREENS_DIR, `${id}.json`),
2602
2914
  image: path3.join(root, SCREENS_DIR, `${id}.png`)
2603
2915
  });
2916
+ MAX_PAGE_FILES = 600;
2604
2917
  }
2605
2918
  });
2606
2919
 
@@ -2608,36 +2921,69 @@ var init_screens = __esm({
2608
2921
  function check(map, root, options = {}) {
2609
2922
  const repo = createRepoReader(root);
2610
2923
  const window = options.lineWindow ?? 3;
2611
- const facts = factsFor(repo);
2924
+ const now = { repo, facts: factsFor(repo, fileExistsIn(repo.root)) };
2925
+ const baseRepo = map.since ? createBaseReader(repo.root, map.since) : null;
2926
+ const base = baseRepo && { repo: baseRepo, facts: factsFor(baseRepo, carryResolver((p) => baseRepo.has(p), fileExistsIn(repo.root))) };
2927
+ const cmp = map.since ? { ref: map.since, base } : null;
2612
2928
  const byId = new Map(map.nodes.map((n) => [n.id, n]));
2613
2929
  let repoFiles = null;
2614
2930
  const files = () => repoFiles ??= listRepoFiles(repo.root, [...DEFAULT_IGNORE, ...options.ignore ?? []]).filter((f) => !isSecretPath(f));
2615
2931
  const nodes = {};
2616
- for (const n of map.nodes) nodes[n.id] = checkNode(n, repo, facts, window);
2932
+ for (const n of map.nodes) nodes[n.id] = checkNode(n, now, cmp, window);
2617
2933
  const edges = {};
2618
- for (const e of map.edges) edges[e.id] = checkEdge(e, byId, repo, facts, window);
2934
+ for (const e of map.edges) edges[e.id] = checkEdge(e, byId, now, cmp, window);
2619
2935
  const absences = {};
2620
2936
  for (const a of map.absences) absences[a.id] = checkAbsence(a, repo, files());
2621
2937
  const screens = {};
2938
+ const pageChecks = /* @__PURE__ */ new Map();
2939
+ const pageOf = (id) => {
2940
+ if (!pageChecks.has(id)) {
2941
+ const page = map.pages?.find((p) => p.id === id);
2942
+ pageChecks.set(id, page ? checkPage(page, repo, (file) => now.facts.get(file)?.imports.map((i) => i.to).filter((to) => !to.startsWith("vendor:")) ?? []) : null);
2943
+ }
2944
+ return pageChecks.get(id) ?? null;
2945
+ };
2622
2946
  for (const n of map.nodes) {
2623
- const sc = checkScreen(n, repo);
2947
+ const sc = checkScreen(n, repo, pageOf);
2624
2948
  if (sc) screens[n.id] = sc;
2625
2949
  }
2626
2950
  const tour = {};
2627
2951
  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"),
2952
+ const unconfirmed2 = [
2953
+ ...(t.focus.nodes ?? []).filter((id) => nodes[id]?.status === "unconfirmed"),
2954
+ ...(t.focus.edges ?? []).filter((id) => edges[id]?.status === "unconfirmed"),
2631
2955
  ...(t.focus.absences ?? []).filter((id) => absences[id]?.status !== "confirmed")
2632
2956
  ];
2633
- tour[t.id] = { status: unconfirmed.length ? "mentions-unconfirmed" : "ok", unconfirmed };
2957
+ tour[t.id] = { status: unconfirmed2.length ? "mentions-unconfirmed" : "ok", unconfirmed: unconfirmed2 };
2634
2958
  }
2635
2959
  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 } };
2960
+ const count = (status) => all.filter((c) => c.status === status).length;
2961
+ const proposals = [...Object.values(nodes), ...Object.values(edges)].flatMap((c) => c.proposal ? [c.proposal] : []);
2962
+ const confirmed = count("confirmed");
2963
+ const unconfirmed = count("unconfirmed");
2964
+ const changes = [...Object.values(nodes), ...Object.values(edges)].flatMap((c) => c.change ? [c.change.kind] : []);
2965
+ return {
2966
+ nodes,
2967
+ edges,
2968
+ absences,
2969
+ tour,
2970
+ screens,
2971
+ summary: {
2972
+ claims: confirmed + unconfirmed,
2973
+ confirmed,
2974
+ unconfirmed,
2975
+ proposals: { pending: proposals.filter((p) => p.state === "pending").length, done: proposals.filter((p) => p.state === "done").length },
2976
+ ...cmp && { changes: { added: changes.filter((k) => k === "added").length, changed: changes.filter((k) => k === "changed").length, removed: changes.filter((k) => k === "removed").length } }
2977
+ },
2978
+ ...cmp && { since: { ref: cmp.ref, commit: baseRepo?.commit ?? null, ...baseRepo ? commitInfo(repo.root, baseRepo.commit) : { date: null, subject: null } } }
2979
+ };
2980
+ }
2981
+ function settledProposals(report) {
2982
+ const of = (what, group) => Object.entries(group).flatMap(([id, c]) => c.proposal?.state === "done" ? [{ id, what, kind: c.proposal.kind, reasons: c.reasons }] : []);
2983
+ return [...of("box", report.nodes), ...of("arrow", report.edges)];
2638
2984
  }
2639
- function factsFor(repo) {
2640
- const index = createFactsIndex(repo.root, fileExistsIn(repo.root), repo.text);
2985
+ function factsFor(repo, exists) {
2986
+ const index = createFactsIndex(repo.root, exists, repo.text);
2641
2987
  const cache2 = /* @__PURE__ */ new Map();
2642
2988
  const get = (file) => {
2643
2989
  if (!cache2.has(file)) {
@@ -2684,7 +3030,61 @@ function evidenceReasons(evidence) {
2684
3030
  function result(evidence, reasons, proof) {
2685
3031
  return reasons.length ? { status: "unconfirmed", proof: null, evidence, reasons } : { status: "confirmed", proof, evidence, reasons };
2686
3032
  }
2687
- function checkNode(n, repo, facts, window) {
3033
+ function asProposal(kind, c) {
3034
+ const inCode = c.status === "confirmed";
3035
+ if (kind === "add") return inCode ? { ...c, proposal: { kind, state: "done" } } : { ...c, status: "proposed", proposal: { kind, state: "pending" } };
3036
+ return inCode ? { ...c, proposal: { kind, state: "pending" } } : { ...c, status: "proposed", proposal: { kind, state: "done" } };
3037
+ }
3038
+ function checkNode(n, now, cmp, window) {
3039
+ if (n.removed) return checkGone(cmp, (side) => checkNodeNow(n, side.repo, side.facts, window), (base) => nodeStillThere(n, now, base));
3040
+ const c = checkNodeAsIs(n, now.repo, now.facts, window);
3041
+ if (!cmp?.base || n.proposed || c.status !== "confirmed") return c;
3042
+ const change = nodeChange(n, now, cmp.base);
3043
+ return change ? { ...c, change } : c;
3044
+ }
3045
+ function checkNodeAsIs(n, repo, facts, window) {
3046
+ if (!n.proposed) return checkNodeNow(n, repo, facts, window);
3047
+ if (!isAddition(n)) return asProposal(n.proposed.kind, checkNodeNow(n, repo, facts, window));
3048
+ 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"] });
3049
+ return asProposal("add", checkNodeNow({ ...n, evidence: [] }, repo, facts, window));
3050
+ }
3051
+ function checkGone(cmp, at, stillThere) {
3052
+ const fail = (evidence, reasons) => ({ status: "unconfirmed", proof: null, evidence, reasons });
3053
+ if (!cmp) return fail([], ["the map names no commit (`since`) for this to have been removed after"]);
3054
+ if (!cmp.base) return fail([], [`"${cmp.ref}" isn't a commit in this repo, so there is nothing to compare with`]);
3055
+ const was = at(cmp.base);
3056
+ if (was.status !== "confirmed") return fail(was.evidence, was.reasons.map((r) => `in the code as it was: ${r}`));
3057
+ if (stillThere(cmp.base)) return fail(was.evidence, ["it is still in the code, so it wasn't removed (drop `removed`)"]);
3058
+ return { ...was, change: { kind: "removed" } };
3059
+ }
3060
+ function hasLine(side, file, text2) {
3061
+ const source = side.repo.text(file);
3062
+ if (source === null) return false;
3063
+ const want = squash(text2);
3064
+ return source.split("\n").some((line) => squash(line).includes(want));
3065
+ }
3066
+ function nodeStillThere(n, now, _base) {
3067
+ if (n.symbol && now.facts.get(fileOf(n.symbol))) return !!symbolIn(now, n.symbol);
3068
+ return n.evidence.some((e) => hasLine(now, e.file, e.text));
3069
+ }
3070
+ function nodeChange(n, now, base) {
3071
+ if (n.symbol) {
3072
+ const file = fileOf(n.symbol);
3073
+ const cur = symbolIn(now, n.symbol);
3074
+ if (cur && !base.repo.has(file)) return { kind: "added" };
3075
+ if (cur && base.facts.get(file)) {
3076
+ const old = symbolIn(base, n.symbol);
3077
+ if (!old) return { kind: "added" };
3078
+ if (old.sigHash === cur.sigHash && old.bodyHash === cur.bodyHash) return null;
3079
+ 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));
3080
+ return { kind: "changed", ...diff?.length && { diff } };
3081
+ }
3082
+ }
3083
+ if (!n.evidence.length) return null;
3084
+ if (n.evidence.every((e) => !base.repo.has(e.file))) return { kind: "added" };
3085
+ return n.evidence.some((e) => !hasLine(base, e.file, e.text)) ? { kind: "changed" } : null;
3086
+ }
3087
+ function checkNodeNow(n, repo, facts, window) {
2688
3088
  const evidence = n.evidence.map((e) => checkEvidence(repo, e, window));
2689
3089
  const reasons = evidenceReasons(evidence);
2690
3090
  if (reasons.length || !n.symbol) return result(evidence, reasons, "text");
@@ -2692,7 +3092,30 @@ function checkNode(n, repo, facts, window) {
2692
3092
  if (!found) reasons.push(`the code has no symbol ${n.symbol}`);
2693
3093
  return result(evidence, reasons, "fact");
2694
3094
  }
2695
- function checkEdge(e, byId, repo, facts, window) {
3095
+ function factBacked(e, byId) {
3096
+ const from = byId.get(e.from);
3097
+ const to = byId.get(e.to);
3098
+ return e.kind !== "then" && !!from && !!to && (e.kind !== "calls" || !!from.symbol && !!to.symbol) && [from, to].every((n) => n.symbol || n.evidence.length);
3099
+ }
3100
+ function checkEdge(e, byId, now, cmp, window) {
3101
+ const inFacts = (side) => factBacked(e, byId) && checkEdgeNow({ ...e, evidence: [] }, byId, side.repo, side.facts, window).status === "confirmed";
3102
+ if (e.removed) {
3103
+ const stillThere = () => factBacked(e, byId) ? inFacts(now) : e.evidence.every((x) => hasLine(now, x.file, x.text));
3104
+ return checkGone(cmp, (side) => checkEdgeNow(e, byId, side.repo, side.facts, window), stillThere);
3105
+ }
3106
+ const c = checkEdgeAsIs(e, byId, now.repo, now.facts, window);
3107
+ if (!cmp?.base || e.proposed || c.status !== "confirmed") return c;
3108
+ const base = cmp.base;
3109
+ const added = factBacked(e, byId) ? !inFacts(base) : e.evidence.some((x) => !hasLine(base, x.file, x.text));
3110
+ return added ? { ...c, change: { kind: "added" } } : c;
3111
+ }
3112
+ function checkEdgeAsIs(e, byId, repo, facts, window) {
3113
+ if (!e.proposed) return checkEdgeNow(e, byId, repo, facts, window);
3114
+ if (!isAddition(e)) return asProposal(e.proposed.kind, checkEdgeNow(e, byId, repo, facts, window));
3115
+ 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)"] });
3116
+ return asProposal("add", checkEdgeNow({ ...e, evidence: [] }, byId, repo, facts, window));
3117
+ }
3118
+ function checkEdgeNow(e, byId, repo, facts, window) {
2696
3119
  const evidence = e.evidence.map((x) => checkEvidence(repo, x, window));
2697
3120
  const reasons = evidenceReasons(evidence);
2698
3121
  const from = byId.get(e.from);
@@ -2735,14 +3158,16 @@ function checkAbsence(a, repo, files) {
2735
3158
  try {
2736
3159
  pattern = new RegExp(a.search.regex ? a.search.pattern : a.search.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
2737
3160
  } catch {
2738
- return { status: "unconfirmed", found: 0, locations: [], reasons: ["the search pattern is not a valid regular expression"] };
3161
+ return { status: "unconfirmed", found: 0, searched: 0, locations: [], reasons: ["the search pattern is not a valid regular expression"] };
2739
3162
  }
2740
3163
  let found = 0;
3164
+ let searched = 0;
2741
3165
  const locations = [];
2742
3166
  for (const file of files) {
2743
3167
  if (a.search.paths && !matchesAny(a.search.paths, file)) continue;
2744
3168
  const text2 = repo.text(file);
2745
3169
  if (text2 === null) continue;
3170
+ searched++;
2746
3171
  text2.split("\n").forEach((line, i) => {
2747
3172
  const n = line.match(pattern)?.length ?? 0;
2748
3173
  if (!n) return;
@@ -2751,19 +3176,23 @@ function checkAbsence(a, repo, files) {
2751
3176
  });
2752
3177
  }
2753
3178
  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 };
3179
+ if (!searched) reasons.push(a.search.paths ? `no files match ${a.search.paths.join(", ")}, so nothing was searched` : "there were no files to search");
3180
+ return { status: reasons.length ? "unconfirmed" : "confirmed", found, searched, locations, reasons };
2755
3181
  }
2756
- var MAX_LOCATIONS, fileOf, within, short;
3182
+ var MAX_LOCATIONS, fileOf, within, short, symbolIn;
2757
3183
  var init_check = __esm({
2758
3184
  "packages/core/src/check.ts"() {
2759
3185
  "use strict";
2760
3186
  init_src();
3187
+ init_base();
3188
+ init_format();
2761
3189
  init_repo();
2762
3190
  init_screens();
2763
3191
  MAX_LOCATIONS = 20;
2764
3192
  fileOf = (symbol) => symbol.slice(0, symbol.indexOf("#"));
2765
3193
  within = (from, symbol) => from === symbol || from.startsWith(`${symbol}.`);
2766
3194
  short = (text2) => text2.length > 60 ? `${text2.slice(0, 57)}\u2026` : text2;
3195
+ symbolIn = (side, symbol) => side.facts.get(fileOf(symbol))?.symbols.find((s) => s.id === symbol) ?? null;
2767
3196
  }
2768
3197
  });
2769
3198
 
@@ -2773,6 +3202,7 @@ var init_src2 = __esm({
2773
3202
  "use strict";
2774
3203
  init_format();
2775
3204
  init_edit();
3205
+ init_base();
2776
3206
  init_check();
2777
3207
  init_repo();
2778
3208
  init_screens();
@@ -2859,26 +3289,26 @@ var init_agent = __esm({
2859
3289
  });
2860
3290
 
2861
3291
  // packages/server/src/git.ts
2862
- import { execFileSync } from "node:child_process";
2863
- var git, headCommit, hasUncommittedChanges;
3292
+ import { execFileSync as execFileSync3 } from "node:child_process";
3293
+ var git2, headCommit, hasUncommittedChanges;
2864
3294
  var init_git = __esm({
2865
3295
  "packages/server/src/git.ts"() {
2866
3296
  "use strict";
2867
- git = (root, args) => {
3297
+ git2 = (root, args) => {
2868
3298
  try {
2869
- return execFileSync("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
3299
+ return execFileSync3("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
2870
3300
  } catch {
2871
3301
  return null;
2872
3302
  }
2873
3303
  };
2874
- headCommit = (root) => git(root, ["rev-parse", "HEAD"]) || null;
2875
- hasUncommittedChanges = (root, file) => !!git(root, ["status", "--porcelain", "--", file]);
3304
+ headCommit = (root) => git2(root, ["rev-parse", "HEAD"]) || null;
3305
+ hasUncommittedChanges = (root, file) => !!git2(root, ["status", "--porcelain", "--", file]);
2876
3306
  }
2877
3307
  });
2878
3308
 
2879
3309
  // packages/server/src/fixes.ts
2880
3310
  import * as crypto2 from "node:crypto";
2881
- import * as fs7 from "node:fs";
3311
+ import * as fs8 from "node:fs";
2882
3312
  import * as path5 from "node:path";
2883
3313
  function allowed(file) {
2884
3314
  if (!isSafeRelativePath(file)) return `${file}: must be a path inside the repo`;
@@ -2923,7 +3353,7 @@ function proposeFix(root, map, raw) {
2923
3353
  problems.push(bad);
2924
3354
  continue;
2925
3355
  }
2926
- if (fs7.existsSync(path5.join(root, c.file)) || after.has(c.file)) {
3356
+ if (fs8.existsSync(path5.join(root, c.file)) || after.has(c.file)) {
2927
3357
  problems.push(`${c.file}: already exists`);
2928
3358
  continue;
2929
3359
  }
@@ -2963,11 +3393,11 @@ function applyFix(root, proposal) {
2963
3393
  for (const f of proposal.files) {
2964
3394
  const abs = path5.join(root, f.file);
2965
3395
  if (f.change === "create") {
2966
- if (fs7.existsSync(abs)) problems.push(`${f.file} was created since this fix was proposed`);
3396
+ if (fs8.existsSync(abs)) problems.push(`${f.file} was created since this fix was proposed`);
2967
3397
  originals.push({ file: f.file, content: null });
2968
3398
  continue;
2969
3399
  }
2970
- const text2 = fs7.existsSync(abs) ? fs7.readFileSync(abs, "utf8") : null;
3400
+ const text2 = fs8.existsSync(abs) ? fs8.readFileSync(abs, "utf8") : null;
2971
3401
  if (text2 === null || sha(text2) !== f.hash) {
2972
3402
  problems.push(`${f.file} changed since this fix was proposed; ask for the fix again`);
2973
3403
  continue;
@@ -2982,13 +3412,13 @@ function applyFix(root, proposal) {
2982
3412
  }
2983
3413
  for (const c of proposal.creates) contents.set(c.file, c.content);
2984
3414
  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));
3415
+ fs8.mkdirSync(backup, { recursive: true });
3416
+ fs8.writeFileSync(path5.join(backup, "originals.json"), JSON.stringify({ proposal, originals }, null, 2));
2987
3417
  const written = [];
2988
3418
  for (const [file, text2] of contents) {
2989
3419
  const abs = path5.join(root, file);
2990
- fs7.mkdirSync(path5.dirname(abs), { recursive: true });
2991
- fs7.writeFileSync(abs, text2);
3420
+ fs8.mkdirSync(path5.dirname(abs), { recursive: true });
3421
+ fs8.writeFileSync(abs, text2);
2992
3422
  written.push({ file, hash: sha(text2) });
2993
3423
  }
2994
3424
  return { ok: true, applied: { proposal, originals, written } };
@@ -2997,14 +3427,14 @@ function undoFix(root, applied) {
2997
3427
  const problems = [];
2998
3428
  for (const w of applied.written) {
2999
3429
  const abs = path5.join(root, w.file);
3000
- const text2 = fs7.existsSync(abs) ? fs7.readFileSync(abs, "utf8") : null;
3430
+ const text2 = fs8.existsSync(abs) ? fs8.readFileSync(abs, "utf8") : null;
3001
3431
  if (text2 === null || sha(text2) !== w.hash) problems.push(`${w.file} changed after the fix; undo it by hand`);
3002
3432
  }
3003
3433
  if (problems.length) return { ok: false, problems };
3004
3434
  for (const o of applied.originals) {
3005
3435
  const abs = path5.join(root, o.file);
3006
- if (o.content === null) fs7.rmSync(abs, { force: true });
3007
- else fs7.writeFileSync(abs, o.content);
3436
+ if (o.content === null) fs8.rmSync(abs, { force: true });
3437
+ else fs8.writeFileSync(abs, o.content);
3008
3438
  }
3009
3439
  return { ok: true };
3010
3440
  }
@@ -3045,8 +3475,14 @@ function makerPrompt(question, headStart2) {
3045
3475
  "",
3046
3476
  ...MAP_RULES,
3047
3477
  "",
3478
+ ...JOURNEY_RULES,
3479
+ "",
3048
3480
  ...EVIDENCE_RULES,
3049
3481
  "",
3482
+ ...PROPOSAL_RULES,
3483
+ "",
3484
+ ...CHANGE_RULES,
3485
+ "",
3050
3486
  ...SCREEN_RULES,
3051
3487
  "",
3052
3488
  ...TOUR_RULES,
@@ -3054,7 +3490,7 @@ function makerPrompt(question, headStart2) {
3054
3490
  "## Head start (from a quick automatic scan; it may be incomplete)",
3055
3491
  headStart2,
3056
3492
  "",
3057
- "Return the map: `version` 1, the `question`, `areas`, `nodes`, `edges`, `absences`, `tour`."
3493
+ "Return the map: `version` 1, the `question`, `areas`, `nodes`, `edges`, `absences`, `tour` (and `view` or `since` when the rules above call for them)."
3058
3494
  ].join("\n");
3059
3495
  }
3060
3496
  function shapeRepairPrompt(problems) {
@@ -3078,8 +3514,9 @@ function withSuggestion(reason, symbolsIn) {
3078
3514
  function evidenceRepairPrompt(report, symbolsIn) {
3079
3515
  const why = (reasons) => reasons.map((r) => withSuggestion(r, symbolsIn)).join("; ");
3080
3516
  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)}`),
3517
+ ...Object.entries(report.nodes).filter(([, c]) => c.status === "unconfirmed").map(([id, c]) => `- box ${id}: ${why(c.reasons)}`),
3518
+ ...Object.entries(report.edges).filter(([, c]) => c.status === "unconfirmed").map(([id, c]) => `- arrow ${id}: ${why(c.reasons)}`),
3519
+ ...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
3520
  ...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
3521
  ];
3085
3522
  const screens = Object.entries(report.screens ?? {}).filter(([, c]) => c.status !== "confirmed").map(([id, c]) => `- screen on box ${id}: ${c.reasons.join("; ")}`);
@@ -3102,16 +3539,16 @@ function patchRepairPrompt(problems) {
3102
3539
  ].join("\n");
3103
3540
  }
3104
3541
  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);
3542
+ const all = [...Object.entries(report.nodes), ...Object.entries(report.edges), ...Object.entries(report.absences)];
3543
+ const unconfirmed = all.filter(([, c]) => c.status === "unconfirmed").map(([id]) => id);
3544
+ 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
3545
  return [
3111
3546
  "## The map (JSON)",
3112
3547
  JSON.stringify(map),
3113
3548
  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.",
3549
+ 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.",
3550
+ ...proposals.length ? [`These are proposals, not code as it is; the checker says where each stands: ${proposals.join(", ")}.`] : [],
3551
+ ...changesContext(report),
3115
3552
  "",
3116
3553
  selection.length ? `## They selected
3117
3554
  ${selection.map((s) => `- ${s.id}: ${s.label}`).join("\n")}` : "## They selected nothing (the question is about the whole map)",
@@ -3120,6 +3557,18 @@ ${selection.map((s) => `- ${s.id}: ${s.label}`).join("\n")}` : "## They selected
3120
3557
  "${question}"`
3121
3558
  ];
3122
3559
  }
3560
+ function changesContext(report) {
3561
+ if (!report.since) return [];
3562
+ if (!report.since.commit) return [`
3563
+ 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.`];
3564
+ const marked = [...Object.entries(report.nodes), ...Object.entries(report.edges)].flatMap(([id, c]) => c.change ? [{ id, ...c.change }] : []);
3565
+ return [
3566
+ `
3567
+ 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:`,
3568
+ 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.",
3569
+ ...marked.filter((m) => m.diff?.length).flatMap((m) => [`Lines of ${m.id} that changed (- before, + now):`, ...m.diff])
3570
+ ];
3571
+ }
3123
3572
  function conversationSoFar(earlier) {
3124
3573
  if (!earlier.length) return [];
3125
3574
  return [
@@ -3171,6 +3620,8 @@ function explainerPrompt(map, report, selection, question, missing = "", wordsOn
3171
3620
  "You answer questions about a code map for someone semi-technical. You can Read, Grep and Glob the repo; you cannot edit anything.",
3172
3621
  "",
3173
3622
  ...questionContext(map, report, selection, question),
3623
+ ...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."] : [],
3624
+ ...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
3625
  ...missing ? ["", `## Why the map alone wasn't enough
3175
3626
  ${missing}`] : [],
3176
3627
  "",
@@ -3179,22 +3630,26 @@ ${missing}`] : [],
3179
3630
  ...ANSWER_STYLE,
3180
3631
  "- 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
3632
  "- `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.",
3633
+ '- 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.',
3634
+ "- 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
3635
  "- 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
- '- 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.',
3636
+ '- 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). In an answer a wireframe can only use a page already in the map\'s `pages`; when the map has no page for it, a sketch of the component will do. Otherwise leave `screens` out: most questions don\'t need one.',
3185
3637
  "",
3186
3638
  ...EVIDENCE_RULES,
3187
3639
  "",
3640
+ ...PROPOSAL_RULES,
3641
+ "",
3188
3642
  ...SCREEN_RULES
3189
3643
  ].join("\n");
3190
3644
  }
3191
- var EVIDENCE_RULES, MAP_RULES, SCREEN_RULES, TOUR_RULES, NO_SYMBOL, ANSWER_STYLE;
3645
+ var EVIDENCE_RULES, MAP_RULES, JOURNEY_RULES, PROPOSAL_RULES, CHANGE_RULES, SCREEN_RULES, TOUR_RULES, NO_SYMBOL, ANSWER_STYLE;
3192
3646
  var init_prompts = __esm({
3193
3647
  "packages/server/src/prompts.ts"() {
3194
3648
  "use strict";
3649
+ init_src2();
3195
3650
  EVIDENCE_RULES = [
3196
3651
  "## 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.",
3652
+ "- 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
3653
  '- 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
3654
  "- 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
3655
  "- Never cite or read secret files (.env, keys)."
@@ -3203,7 +3658,12 @@ var init_prompts = __esm({
3203
3658
  "## What a good map is",
3204
3659
  "- 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
3660
  "- 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()").',
3661
+ "- 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.",
3662
+ "- 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.",
3663
+ "- 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.",
3664
+ "- 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`.",
3665
+ "- Before returning, go through the boxes one at a time: if the answer would be the same without it, drop or merge it.",
3666
+ '- Box `name`: plain English, at most 30 characters ("Patient marked enrolled", not "markConverted()").',
3207
3667
  "- `kind`: entry (a way in), step, store (table, queue, cache), external (outside service), job (scheduled or background work).",
3208
3668
  "- `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
3669
  '- Arrow `label`: 1\u20133 words saying how one step leads to the next ("sends request", "calls", "announces", "every night").',
@@ -3211,19 +3671,56 @@ var init_prompts = __esm({
3211
3671
  `- 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
3672
  "- 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
3673
  ];
3674
+ JOURNEY_RULES = [
3675
+ "## When the question is about what a person sees or does (a journey, a user flow)",
3676
+ '- 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).',
3677
+ '- `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.',
3678
+ '- 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").',
3679
+ '- 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.',
3680
+ `- 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.`,
3681
+ "- Each box and arrow still cites the code that makes it so: the component, the handler, the redirect.",
3682
+ "- Show where each step happens: define the pages the journey goes through once, in `pages`, and give each screen box a wireframe of its page with its own part marked (see Screens). Several boxes usually share one page. A box whose page can't be drawn usefully (nothing recognisable on it, or it isn't in this repo) gets no `screen`: no picture is better than a thin one.",
3683
+ "- 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.",
3684
+ "- The walkthrough is told as the person's experience too, one stop per screen."
3685
+ ];
3686
+ PROPOSAL_RULES = [
3687
+ "## Proposals (`proposed` on a box or arrow; only when a change is asked for)",
3688
+ '- 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.',
3689
+ '- `"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.',
3690
+ '- `"kind": "change"` or `"remove"`: code that is there today and would be changed or deleted. Cite it like any other claim.',
3691
+ "- `note`: one plain sentence saying what would change and why.",
3692
+ "- Every new box must connect, through arrows, to a box that exists. Keep it small: only the boxes and arrows the change needs.",
3693
+ '- 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.',
3694
+ "- 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."
3695
+ ];
3696
+ CHANGE_RULES = [
3697
+ '## When the question is about a change (what changed, what a commit or a task did, "what did you just change")',
3698
+ '- 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`.',
3699
+ "- 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.",
3700
+ "- 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.",
3701
+ '- 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.',
3702
+ '- 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.',
3703
+ "- 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.",
3704
+ "- The walkthrough says what changed first, then follows the changed path in the order things happen."
3705
+ ];
3214
3706
  SCREEN_RULES = [
3215
- "## Screens (`screen` on a box; optional, and your call)",
3216
- "- 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.",
3217
- '- `{ "kind": "capture", "capture": "<id>", "highlight": "<label>" }`: a real screenshot. Only if you have the illuminate_capture tool: it screenshots a page already running on this machine or an HTML file in the repo, and returns the id. Look at the image first, and don\'t use one that shows a login page, an error or the wrong state. Never start the app yourself.',
3707
+ "## Screens (`pages` on the map, `screen` on a box; optional, and your call)",
3708
+ "- A picture of where a step happens on the screen 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.",
3709
+ '- The usual picture is a wireframe of the whole page, with the part the box is about marked. Define each page once, in the map\'s `pages`: `{ "id": "\u2026", "name": "Patient page", "file": "<the page\'s own component or template>", "regions": [ \u2026 ] }`.',
3710
+ '- A region is one visible part of the page: `{ "id": "\u2026", "slot": "top" | "left" | "main" | "right" | "bottom", "label": "Top bar", "file": "<the file it comes from>", "elements": [{ "kind": "heading|button|field|link|text|image", "text": "\u2026" }] }`. Give the 3\u20136 regions a person would recognise the page by, not only the one the step uses. Put each in the slot where it appears on screen, going by the markup and the styles (a bar across the top is `top`, a sidebar is `left` or `right`, the content is `main`). `elements`: up to 6 of the most recognisable things in the region, in the order they appear, each `text` copied exactly from that region\'s file; a region may have none.',
3711
+ '- Then on a box: `"screen": { "kind": "wireframe", "page": "<page id>", "region": "<region id>", "highlight": "<text of one element in that region>" }`. Boxes that happen on the same page use the same page, each marking its own region and element.',
3712
+ "- A program checks every page: a region's `file` must be the page's `file` or one it imports (directly or through other files), every element's text must be in its region's file, and the box must cite the page's code or the code the marked element is in. A region that fails is left off; where regions sit can't be checked, so read the layout from the code and don't invent parts.",
3713
+ '- `{ "kind": "capture", "capture": "<id>", "highlight": "<label>" }`: a real screenshot, in place of a wireframe, when a page is already running on this machine. Only if you have the illuminate_capture tool: it screenshots a running page or an HTML file in the repo, and returns the id. Look at the image first, and don\'t use one that shows a login page, an error or the wrong state. Never start the app yourself.',
3218
3714
  '- `{ "kind": "image", "file": "<path>" }`: an image file in the repo (an icon, a sprite) that the box\'s cited code names.',
3219
- '- `{ "kind": "sketch", "file": "<markup file>", "elements": [{ "kind": "heading|button|field|link|text|image", "text": "\u2026" }], "highlight": "<one element\'s text>" }`: a rough wireframe of the visible things in a component or template, top to bottom, at most 12. Use it when there is no screenshot to take. Copy each `text` exactly from the file.',
3220
- "- A program checks screens too: a capture's `highlight` must be a label visible on it and appear in the code the box cites; every sketch element must be in its file. A screen that fails is left out; the box stays."
3715
+ '- `{ "kind": "sketch", "file": "<markup file>", "elements": [ \u2026 ], "highlight": "<one element\'s text>" }`: the visible things in one component, as a list. Only for a proposal (see Proposals): it can show elements that aren\'t there yet.'
3221
3716
  ];
3222
3717
  TOUR_RULES = [
3223
3718
  "## 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.",
3719
+ "- 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.",
3720
+ '- 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
3721
  "- 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."
3722
+ "- Point stops only at boxes, arrows and absences you're confident in.",
3723
+ "- If the map has proposals, give them a stop after the path: what would change, and what stays as it is."
3227
3724
  ];
3228
3725
  NO_SYMBOL = /^the code has no symbol (.+)#(.+)$/;
3229
3726
  ANSWER_STYLE = [
@@ -3274,6 +3771,8 @@ var init_schemas = __esm({
3274
3771
  moves: z3.object({ focus: z3.string().optional(), highlight: z3.array(z3.string()).optional() }).optional(),
3275
3772
  /** 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
3773
  screens: z3.array(z3.object({ node: z3.string(), screen: Screen })).max(4).optional(),
3774
+ /** Boxes or arrows already on the map that a suggested change would alter or remove (new ones go in `add`, marked there). */
3775
+ propose: z3.array(z3.object({ id: z3.string(), proposed: Proposal })).max(12).optional(),
3277
3776
  fix: RawFix.optional()
3278
3777
  });
3279
3778
  RawQuickAnswer = RawAnswer.pick({ refs: true, moves: true }).extend({
@@ -3316,23 +3815,25 @@ import * as crypto3 from "node:crypto";
3316
3815
  function citedExcerpts(root, map, selection) {
3317
3816
  const repo = createRepoReader(root);
3318
3817
  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 }))];
3818
+ const base = map.since && [...map.nodes, ...map.edges].some((x) => x.removed) ? createBaseReader(root, map.since) : null;
3819
+ const items = [...map.nodes, ...map.edges].map((x) => ({ id: x.id, evidence: x.evidence, was: !!x.removed }));
3320
3820
  items.sort((a, b) => Number(picked.has(b.id)) - Number(picked.has(a.id)));
3321
3821
  const seen = /* @__PURE__ */ new Set();
3322
3822
  const out = [];
3323
3823
  let size = 0;
3324
3824
  for (const item of items) {
3325
3825
  for (const e of item.evidence) {
3326
- const key = `${e.file}:${e.line}`;
3826
+ const key = `${item.was ? "was:" : ""}${e.file}:${e.line}`;
3327
3827
  if (seen.has(key) || out.length >= MAX_EXCERPTS) continue;
3328
3828
  seen.add(key);
3329
- const read = repo.read(e.file);
3829
+ if (item.was && !base) continue;
3830
+ const read = (item.was ? base : repo).read(e.file);
3330
3831
  if (!read.ok) continue;
3331
3832
  const lines = read.text.split("\n");
3332
3833
  const from = Math.max(1, e.line - EXCERPT_RADIUS);
3333
3834
  const to = Math.min(lines.length, e.line + EXCERPT_RADIUS);
3334
3835
  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})
3836
+ const block = `${e.file}:${from}-${to} (${item.was ? "removed since; as it was, " : ""}cited by ${item.id})
3336
3837
  ${body}`;
3337
3838
  if (size + block.length > MAX_EXCERPT_CHARS) return out.join("\n\n");
3338
3839
  out.push(block);
@@ -3442,7 +3943,7 @@ async function answer(o) {
3442
3943
  });
3443
3944
  const parsed = RawAnswer.safeParse(res.output);
3444
3945
  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;
3946
+ const raw = o.wordsOnly ? { ...parsed.data, add: void 0, fix: void 0, screens: void 0, propose: void 0 } : parsed.data;
3446
3947
  const problems = [];
3447
3948
  let map = o.map;
3448
3949
  let added = [];
@@ -3456,6 +3957,44 @@ async function answer(o) {
3456
3957
  problems.push(...merged.problems.map((p) => `Not added to the map: ${p}`));
3457
3958
  }
3458
3959
  }
3960
+ let report = check(map, o.root);
3961
+ for (const id of added) {
3962
+ const c = report.screens[id];
3963
+ if (c && c.status !== "confirmed") problems.push(`No screen shown for "${map.nodes.find((n) => n.id === id)?.name ?? id}": ${c.reasons.join("; ")}`);
3964
+ }
3965
+ const misread = new Set(settledProposals(report).map((p) => p.id));
3966
+ const failed = added.filter((id) => statusOf(report, id) === "unconfirmed" || misread.has(id));
3967
+ if (failed.length) {
3968
+ for (const id of failed) {
3969
+ const c = report.nodes[id] ?? report.edges[id] ?? report.absences[id];
3970
+ 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"}`);
3971
+ }
3972
+ map = removeFromMap(map, new Set(failed));
3973
+ report = check(map, o.root);
3974
+ const live2 = mapIds(map);
3975
+ added = added.filter((id) => live2.has(id));
3976
+ }
3977
+ const marked = [];
3978
+ for (const p of raw.propose ?? []) {
3979
+ const name = map.nodes.find((n) => n.id === p.id)?.name ?? p.id;
3980
+ if (p.proposed.kind === "add" || added.includes(p.id)) {
3981
+ problems.push(`Not marked as a proposal: "${name}" (new boxes and arrows carry their own \`proposed\`)`);
3982
+ continue;
3983
+ }
3984
+ if (statusOf(report, p.id) !== "confirmed" || !(report.nodes[p.id] ?? report.edges[p.id])) {
3985
+ problems.push(`Not marked as a proposal: "${name}" isn't a confirmed box or arrow on this map`);
3986
+ continue;
3987
+ }
3988
+ const mark = (items) => items.map((x) => x.id === p.id ? { ...x, proposed: p.proposed } : x);
3989
+ const next = parseMap({ ...map, nodes: mark(map.nodes), edges: mark(map.edges) });
3990
+ if (!next.ok) {
3991
+ problems.push(`Not marked as a proposal: ${next.problems.join("; ")}`);
3992
+ continue;
3993
+ }
3994
+ map = next.map;
3995
+ marked.push(p.id);
3996
+ }
3997
+ if (marked.length) report = check(map, o.root);
3459
3998
  const wanted = (raw.screens ?? []).filter((s) => {
3460
3999
  if (map.nodes.some((n) => n.id === s.node)) return true;
3461
4000
  problems.push(`No screen shown: there is no box "${s.node}"`);
@@ -3474,22 +4013,7 @@ async function answer(o) {
3474
4013
  problems.push(`No screen shown for "${map.nodes.find((n) => n.id === s.node)?.name ?? s.node}": ${why}`);
3475
4014
  }
3476
4015
  }
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
- }
4016
+ if (screened.length) report = check(map, o.root);
3493
4017
  let fix = null;
3494
4018
  if (raw.fix) {
3495
4019
  const proposed = proposeFix(o.root, map, raw.fix);
@@ -3508,6 +4032,7 @@ async function answer(o) {
3508
4032
  highlight: (raw.moves?.highlight ?? []).filter((id) => live.has(id))
3509
4033
  },
3510
4034
  added,
4035
+ proposed: marked,
3511
4036
  screens: screened.filter((id) => live.has(id)),
3512
4037
  problems,
3513
4038
  fix,
@@ -3531,14 +4056,67 @@ var init_explainer = __esm({
3531
4056
  }
3532
4057
  });
3533
4058
 
4059
+ // packages/server/src/changes.ts
4060
+ import { execFileSync as execFileSync4 } from "node:child_process";
4061
+ function changesSince(root, ref) {
4062
+ const base = createBaseReader(root, ref);
4063
+ if (!base) return null;
4064
+ const now = createRepoReader(root);
4065
+ const found = /* @__PURE__ */ new Map();
4066
+ const diff = gitList(base.root, ["diff", "--name-status", "--no-renames", "--relative", "-z", base.commit, "--", "."]);
4067
+ for (let i = 0; i + 1 < diff.length; i += 2) found.set(diff[i + 1], diff[i] === "A" ? "new" : diff[i] === "D" ? "deleted" : "changed");
4068
+ for (const f of gitList(base.root, ["ls-files", "--others", "--exclude-standard", "-z"])) found.set(f, "new");
4069
+ const index = createFactsIndex(base.root, fileExistsIn(base.root), now.text);
4070
+ const symbols = (file, text2) => text2 === null ? [] : index.extract(file, text2).facts.symbols.filter((s) => !s.name.includes("<") && s.kind !== "property");
4071
+ 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` : ""}`] : [];
4072
+ const files = [...found].filter(([file]) => !file.startsWith(".illuminate/") && !isSecretPath(file)).map(([file, what]) => {
4073
+ if (!isCodeFile(file)) return { file, what, detail: "" };
4074
+ const d = diffSymbols(symbols(file, base.text(file)), symbols(file, what === "deleted" ? null : now.text(file)));
4075
+ const changed = [...d.sig, ...d.body];
4076
+ return { file, what, detail: [...names("new", d.added), ...names("changed", changed), ...names("removed", d.removed), ...names("renamed", d.renamed.map(([, to]) => to))].join("; ") };
4077
+ }).sort((a, b) => Number(isCodeFile(b.file)) - Number(isCodeFile(a.file)) || a.file.localeCompare(b.file));
4078
+ return { commit: base.commit, subject: commitInfo(base.root, base.commit).subject, files };
4079
+ }
4080
+ function recentChanges(root) {
4081
+ const line = (c) => ` - ${c.what} ${c.file}${c.detail ? ` (${c.detail})` : ""}`;
4082
+ const open = changesSince(root, "HEAD");
4083
+ 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) };
4084
+ const last = changesSince(root, "HEAD~1");
4085
+ 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) };
4086
+ return null;
4087
+ }
4088
+ var MAX_NAMES, gitList;
4089
+ var init_changes = __esm({
4090
+ "packages/server/src/changes.ts"() {
4091
+ "use strict";
4092
+ init_src2();
4093
+ init_src();
4094
+ MAX_NAMES = 8;
4095
+ gitList = (root, args) => {
4096
+ try {
4097
+ return execFileSync4("git", args, { cwd: root, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).toString().split("\0").filter(Boolean);
4098
+ } catch {
4099
+ return [];
4100
+ }
4101
+ };
4102
+ }
4103
+ });
4104
+
3534
4105
  // packages/server/src/hints.ts
3535
- import * as fs8 from "node:fs";
4106
+ import * as fs9 from "node:fs";
3536
4107
  function symbolIndex(scan) {
3537
4108
  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
4109
  }
3539
4110
  function symbolIndexOf(scan) {
3540
4111
  return (file) => scan?.fileFacts[file]?.symbols.filter((s) => CITABLE.has(s.kind) && !s.name.includes("<")).map((s) => s.name) ?? [];
3541
4112
  }
4113
+ function functionSection(index) {
4114
+ if (index.length <= MAX_SYMBOL_FILES) return section("Functions by file (use these exact names for `symbol`)", index, MAX_SYMBOL_FILES);
4115
+ return [
4116
+ `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.`,
4117
+ ""
4118
+ ];
4119
+ }
3542
4120
  async function headStart(root) {
3543
4121
  await initTreeSitter();
3544
4122
  let scan;
@@ -3547,12 +4125,12 @@ async function headStart(root) {
3547
4125
  } catch {
3548
4126
  return { text: "(The automatic scan could not read this repo; explore it directly.)", scan: null };
3549
4127
  }
3550
- const facts = Object.values(scan.fileFacts);
4128
+ const facts = Object.values(scan.fileFacts).filter((f) => !TEST_FILE.test(f.path));
3551
4129
  const entries = facts.flatMap((f) => f.entries).map((e) => ` - ${e.kind} ${e.label}${e.symbol ? ` \u2192 ${e.symbol}` : ` (${e.file})`}`);
3552
4130
  const routes = facts.flatMap((f) => f.routes);
3553
4131
  const routeLines = routes.map((r) => ` - ${r.method} ${r.path} \u2192 ${r.handler ?? r.file}`);
3554
4132
  const fetchFiles = facts.filter((f) => /\.(tsx?|jsx?|mjs|cjs)$/.test(f.path)).flatMap((f) => {
3555
- const source = fs8.readFileSync(`${root}/${f.path}`, "utf8");
4133
+ const source = fs9.readFileSync(`${root}/${f.path}`, "utf8");
3556
4134
  return /\bfetch\(|axios|ky\./.test(source) ? [{ path: f.path, source, symbols: f.symbols }] : [];
3557
4135
  });
3558
4136
  const requests = findFetchSites(fetchFiles).flatMap((site) => {
@@ -3564,17 +4142,25 @@ async function headStart(root) {
3564
4142
  const tables = [...writers].map(([t, by]) => ` - ${t} \u2190 ${[...by].slice(0, 4).join(", ")}`);
3565
4143
  const folders = /* @__PURE__ */ new Map();
3566
4144
  for (const f of scan.files) {
4145
+ if (TEST_FILE.test(f)) continue;
3567
4146
  const top = f.includes("/") ? f.slice(0, f.indexOf("/")) : "(root)";
3568
4147
  folders.set(top, (folders.get(top) ?? 0) + 1);
3569
4148
  }
3570
4149
  const folderLines = [...folders].sort((a, b) => b[1] - a[1]).map(([d, n]) => ` - ${d}/ (${n} files)`);
4150
+ let recent = null;
4151
+ try {
4152
+ recent = recentChanges(root);
4153
+ } catch {
4154
+ recent = null;
4155
+ }
3571
4156
  const text2 = [
3572
4157
  ...section("Ways in (entry points)", entries),
3573
4158
  ...section("Routes and their handlers", routeLines),
3574
4159
  ...section("Requests from the code that match a route", requests),
3575
4160
  ...section("Tables and what writes them", tables),
3576
4161
  ...section("Top-level folders", folderLines),
3577
- ...section("Functions by file (use these exact names for `symbol`)", symbolIndex(scan), MAX_SYMBOL_FILES)
4162
+ ...functionSection(symbolIndex(scan)),
4163
+ ...recent ? section(recent.title, recent.lines) : []
3578
4164
  ].join("\n");
3579
4165
  return { text: text2 || "(The automatic scan found no entry points; explore the repo directly.)", scan };
3580
4166
  }
@@ -3583,11 +4169,12 @@ var init_hints = __esm({
3583
4169
  "packages/server/src/hints.ts"() {
3584
4170
  "use strict";
3585
4171
  init_src();
4172
+ init_changes();
3586
4173
  MAX_LINES = 40;
3587
4174
  MAX_SYMBOL_FILES = 150;
3588
4175
  MAX_SYMBOLS_PER_FILE = 40;
3589
4176
  CITABLE = /* @__PURE__ */ new Set(["function", "method", "component", "class"]);
3590
- TEST_FILE = /(^|\/)(test|tests|__tests__|fixtures?)\/|\.(test|spec)\.[cm]?[jt]sx?$/;
4177
+ TEST_FILE = /(^|\/)(test|tests|__tests__|__mocks__|e2e|fixtures?)\/|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py)$|(^|\/)test_[^/]*\.py$/;
3591
4178
  section = (title, lines, max = MAX_LINES) => lines.length ? [`${title}:`, ...lines.slice(0, max), ...lines.length > max ? [` \u2026and ${lines.length - max} more`] : [], ""] : [];
3592
4179
  }
3593
4180
  });
@@ -3598,6 +4185,12 @@ function applyPatch(map, output) {
3598
4185
  if (!raw.success) return { ok: false, problems: raw.error.issues.map((i) => `${i.path.join(".") || "(changes)"}: ${i.message}`) };
3599
4186
  return patchMap(map, raw.data);
3600
4187
  }
4188
+ function pinned(parsed, root) {
4189
+ if (!parsed.ok || !parsed.map.since) return parsed;
4190
+ const commit = resolveCommit(root, parsed.map.since);
4191
+ 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.`] };
4192
+ return { ok: true, map: { ...parsed.map, since: commit } };
4193
+ }
3601
4194
  async function makeMap(o) {
3602
4195
  const status = (text2) => o.onProgress?.({ kind: "status", text: text2 });
3603
4196
  status("Scanning the code for ways in, routes and tables");
@@ -3608,12 +4201,13 @@ async function makeMap(o) {
3608
4201
  let res = await run(makerPrompt(o.question, hints.text), null, MAP_SCHEMA);
3609
4202
  let cost = res.cost ?? 0;
3610
4203
  let rounds = 1;
4204
+ const off = (r) => r.summary.unconfirmed + settledProposals(r).length;
3611
4205
  let best = null;
3612
4206
  let lastProblems = [];
3613
4207
  let reply = "map";
3614
4208
  let current = null;
3615
4209
  for (let attempt = 0; ; attempt++) {
3616
- const parsed = reply === "map" || !current ? parseMap(withQuestion(res.output, o.question)) : applyPatch(current, res.output);
4210
+ const parsed = pinned(reply === "map" || !current ? parseMap(withQuestion(res.output, o.question)) : applyPatch(current, res.output), o.root);
3617
4211
  let repair = null;
3618
4212
  if (!parsed.ok) {
3619
4213
  lastProblems = parsed.problems;
@@ -3622,9 +4216,9 @@ async function makeMap(o) {
3622
4216
  current = parsed.map;
3623
4217
  status("Checking every claim against the code");
3624
4218
  const report = check(parsed.map, o.root);
3625
- if (!best || report.summary.unconfirmed < best.report.summary.unconfirmed) best = { map: parsed.map, report };
4219
+ if (!best || off(report) < off(best.report)) best = { map: parsed.map, report };
3626
4220
  status(`${report.summary.confirmed} of ${report.summary.claims} claims confirmed`);
3627
- if (report.summary.unconfirmed > 0) repair = { prompt: evidenceRepairPrompt(report, symbolsIn), reply: "patch" };
4221
+ if (off(report) > 0) repair = { prompt: evidenceRepairPrompt(report, symbolsIn), reply: "patch" };
3628
4222
  }
3629
4223
  if (!repair || attempt >= (o.repairs ?? 2)) break;
3630
4224
  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 +4243,17 @@ var init_maker = __esm({
3649
4243
  });
3650
4244
 
3651
4245
  // packages/server/src/store.ts
3652
- import * as fs9 from "node:fs";
4246
+ import * as fs10 from "node:fs";
3653
4247
  import * as path6 from "node:path";
3654
4248
  function createStore(root) {
3655
4249
  const base = path6.join(root, ".illuminate");
3656
4250
  const dir = path6.join(base, "maps");
3657
4251
  const legacy = path6.join(root, ".codemap");
3658
- if (!fs9.existsSync(base) && fs9.existsSync(path6.join(legacy, "maps"))) fs9.renameSync(legacy, base);
4252
+ if (!fs10.existsSync(base) && fs10.existsSync(path6.join(legacy, "maps"))) fs10.renameSync(legacy, base);
3659
4253
  const ensure = () => {
3660
- fs9.mkdirSync(dir, { recursive: true });
4254
+ fs10.mkdirSync(dir, { recursive: true });
3661
4255
  const ignore = path6.join(base, ".gitignore");
3662
- if (!fs9.existsSync(ignore)) fs9.writeFileSync(ignore, "fixes/\nws-modules/\n");
4256
+ if (!fs10.existsSync(ignore)) fs10.writeFileSync(ignore, "fixes/\nws-modules/\n");
3663
4257
  };
3664
4258
  const file = (id) => {
3665
4259
  if (!ID.test(id)) throw new Error(`Not a map id: ${id}`);
@@ -3670,7 +4264,7 @@ function createStore(root) {
3670
4264
  get(id) {
3671
4265
  let raw;
3672
4266
  try {
3673
- raw = JSON.parse(fs9.readFileSync(file(id), "utf8"));
4267
+ raw = JSON.parse(fs10.readFileSync(file(id), "utf8"));
3674
4268
  } catch {
3675
4269
  return null;
3676
4270
  }
@@ -3684,15 +4278,15 @@ function createStore(root) {
3684
4278
  ensure();
3685
4279
  const target = file(stored.meta.id);
3686
4280
  const tmp = `${target}.tmp`;
3687
- fs9.writeFileSync(tmp, `${JSON.stringify(stored, null, 2)}
4281
+ fs10.writeFileSync(tmp, `${JSON.stringify(stored, null, 2)}
3688
4282
  `);
3689
- fs9.renameSync(tmp, target);
4283
+ fs10.renameSync(tmp, target);
3690
4284
  },
3691
4285
  list() {
3692
- if (!fs9.existsSync(dir)) return [];
3693
- return fs9.readdirSync(dir).filter((f) => f.endsWith(".json")).flatMap((f) => {
4286
+ if (!fs10.existsSync(dir)) return [];
4287
+ return fs10.readdirSync(dir).filter((f) => f.endsWith(".json")).flatMap((f) => {
3694
4288
  try {
3695
- const meta = JSON.parse(fs9.readFileSync(path6.join(dir, f), "utf8")).meta;
4289
+ const meta = JSON.parse(fs10.readFileSync(path6.join(dir, f), "utf8")).meta;
3696
4290
  return meta ? [meta] : [];
3697
4291
  } catch {
3698
4292
  return [];
@@ -3704,7 +4298,7 @@ function createStore(root) {
3704
4298
  const base2 = slugify(question);
3705
4299
  for (let i = 1; ; i++) {
3706
4300
  const id = i === 1 ? base2 : `${base2}-${i}`;
3707
- if (!taken.has(id) && !fs9.existsSync(file(id))) return id;
4301
+ if (!taken.has(id) && !fs10.existsSync(file(id))) return id;
3708
4302
  }
3709
4303
  }
3710
4304
  };
@@ -3720,13 +4314,13 @@ var init_store = __esm({
3720
4314
 
3721
4315
  // packages/server/src/server.ts
3722
4316
  import * as crypto4 from "node:crypto";
3723
- import * as fs10 from "node:fs";
4317
+ import * as fs11 from "node:fs";
3724
4318
  import * as http from "node:http";
3725
4319
  import * as path7 from "node:path";
3726
4320
  import { fileURLToPath } from "node:url";
3727
4321
  import { WebSocketServer } from "ws";
3728
4322
  async function startServer(o) {
3729
- const root = fs10.realpathSync(o.root);
4323
+ const root = fs11.realpathSync(o.root);
3730
4324
  const agent = o.agent ?? sdkAgent;
3731
4325
  const token = o.token ?? crypto4.randomBytes(18).toString("base64url");
3732
4326
  const viewerDir = o.viewerDir ?? DEFAULT_VIEWER;
@@ -3832,13 +4426,13 @@ async function startServer(o) {
3832
4426
  const next = {
3833
4427
  ...latest,
3834
4428
  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,
4429
+ map: r.answer.added.length || r.answer.screens?.length || r.answer.proposed?.length ? r.map : latest.map,
3836
4430
  answers: [...latest.answers ?? [], r.answer],
3837
4431
  fixes: r.answer.fix ? withFix(latest, r.answer.fix.id, { status: "proposed" }) : latest.fixes
3838
4432
  };
3839
4433
  store.save(next);
3840
4434
  endJob(mapId);
3841
- if (r.answer.added.length || r.answer.screens?.length) publishMap(next);
4435
+ if (r.answer.added.length || r.answer.screens?.length || r.answer.proposed?.length) publishMap(next);
3842
4436
  broadcast({ type: "answer", mapId, answer: r.answer });
3843
4437
  broadcast({ type: "job", mapId, job: "ask", status: "done", question: q });
3844
4438
  } catch (err) {
@@ -4008,25 +4602,25 @@ async function startServer(o) {
4008
4602
  }
4009
4603
  function sendFile(res, file, type) {
4010
4604
  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);
4605
+ fs11.createReadStream(file).pipe(res);
4012
4606
  }
4013
4607
  function serveStatic(res, pathname) {
4014
4608
  const index = path7.join(viewerDir, "index.html");
4015
- if (!fs10.existsSync(index)) {
4609
+ if (!fs11.existsSync(index)) {
4016
4610
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
4017
4611
  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
4612
  }
4019
4613
  const rel = decodeURIComponent(pathname).replace(/^\/+/, "");
4020
4614
  const file = path7.resolve(viewerDir, rel);
4021
4615
  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;
4616
+ const target = inside && rel.startsWith("assets/") && fs11.existsSync(file) && fs11.statSync(file).isFile() ? file : index;
4023
4617
  res.writeHead(200, {
4024
4618
  "content-type": TYPES[path7.extname(target)] ?? "application/octet-stream",
4025
4619
  "cache-control": target === index ? "no-store" : "public, max-age=31536000, immutable",
4026
4620
  "x-content-type-options": "nosniff",
4027
4621
  ...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
4622
  });
4029
- fs10.createReadStream(target).pipe(res);
4623
+ fs11.createReadStream(target).pipe(res);
4030
4624
  }
4031
4625
  const server = http.createServer((req, res) => {
4032
4626
  void (async () => {
@@ -4115,7 +4709,7 @@ var init_server = __esm({
4115
4709
  init_git();
4116
4710
  init_maker();
4117
4711
  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));
4712
+ 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
4713
  TYPES = {
4120
4714
  ".html": "text/html; charset=utf-8",
4121
4715
  ".js": "text/javascript",
@@ -4273,15 +4867,15 @@ var init_bridge = __esm({
4273
4867
  // packages/server/src/screens.ts
4274
4868
  import { spawn as spawn2 } from "node:child_process";
4275
4869
  import * as crypto5 from "node:crypto";
4276
- import * as fs11 from "node:fs";
4870
+ import * as fs12 from "node:fs";
4277
4871
  import * as os from "node:os";
4278
4872
  import * as path8 from "node:path";
4279
4873
  import { pathToFileURL } from "node:url";
4280
4874
  import { WebSocket } from "ws";
4281
4875
  function findChrome() {
4282
4876
  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;
4877
+ if (given) return fs12.existsSync(given) ? given : null;
4878
+ return CHROME_PATHS.find((p) => fs12.existsSync(p)) ?? null;
4285
4879
  }
4286
4880
  function resolveTarget(root, target) {
4287
4881
  if ("url" in target) {
@@ -4297,10 +4891,10 @@ function resolveTarget(root, target) {
4297
4891
  }
4298
4892
  const rel = target.file;
4299
4893
  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);
4894
+ const realRoot = fs12.realpathSync(root);
4301
4895
  let real;
4302
4896
  try {
4303
- real = fs11.realpathSync(path8.join(realRoot, rel));
4897
+ real = fs12.realpathSync(path8.join(realRoot, rel));
4304
4898
  } catch {
4305
4899
  return { ok: false, reason: `${rel} doesn't exist.` };
4306
4900
  }
@@ -4327,10 +4921,10 @@ async function capture(root, target, shoot = shootWithChrome) {
4327
4921
  takenAt: (/* @__PURE__ */ new Date()).toISOString(),
4328
4922
  elements: shot.elements
4329
4923
  };
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)}
4924
+ const p = capturePaths(fs12.realpathSync(root), id);
4925
+ fs12.mkdirSync(path8.dirname(p.image), { recursive: true });
4926
+ fs12.writeFileSync(p.image, shot.png);
4927
+ fs12.writeFileSync(p.record, `${JSON.stringify(record, null, 2)}
4334
4928
  `);
4335
4929
  return { ok: true, result: { capture: record, png: shot.png, text: shot.text } };
4336
4930
  }
@@ -4354,7 +4948,7 @@ async function listScreens(root, o = {}) {
4354
4948
  const pages = (await Promise.all(ports.map(probe))).filter((p) => !!p);
4355
4949
  let scripts = {};
4356
4950
  try {
4357
- scripts = JSON.parse(fs11.readFileSync(path8.join(root, "package.json"), "utf8")).scripts ?? {};
4951
+ scripts = JSON.parse(fs12.readFileSync(path8.join(root, "package.json"), "utf8")).scripts ?? {};
4358
4952
  } catch {
4359
4953
  }
4360
4954
  const few = (list, max) => [...list.slice(0, max).map((f) => ` - ${f}`), ...list.length > max ? [` - \u2026and ${list.length - max} more`] : []];
@@ -4422,7 +5016,7 @@ var init_screens2 = __esm({
4422
5016
  shootWithChrome = async (url) => {
4423
5017
  const chrome = findChrome();
4424
5018
  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-"));
5019
+ const profile = fs12.mkdtempSync(path8.join(os.tmpdir(), "illuminate-chrome-"));
4426
5020
  let child = null;
4427
5021
  let ws = null;
4428
5022
  try {
@@ -4500,7 +5094,7 @@ var init_screens2 = __esm({
4500
5094
  } finally {
4501
5095
  ws?.close();
4502
5096
  child?.kill("SIGKILL");
4503
- setTimeout(() => fs11.rm(profile, { recursive: true, force: true }, () => {
5097
+ setTimeout(() => fs12.rm(profile, { recursive: true, force: true }, () => {
4504
5098
  }), 500).unref?.();
4505
5099
  }
4506
5100
  };
@@ -4515,7 +5109,7 @@ __export(channel_exports, {
4515
5109
  requestText: () => requestText,
4516
5110
  runChannel: () => runChannel
4517
5111
  });
4518
- import * as fs12 from "node:fs";
5112
+ import * as fs13 from "node:fs";
4519
5113
  import * as path9 from "node:path";
4520
5114
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4521
5115
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -4562,8 +5156,8 @@ function createChannel(o) {
4562
5156
  });
4563
5157
  const rootOf2 = (repo) => {
4564
5158
  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);
5159
+ if (!fs13.existsSync(dir) || !fs13.statSync(dir).isDirectory()) throw new Error(`No such folder: ${dir}`);
5160
+ return fs13.realpathSync(dir);
4567
5161
  };
4568
5162
  const serverFor = (root) => {
4569
5163
  let s = servers.get(root);
@@ -4807,10 +5401,12 @@ var init_channel = __esm({
4807
5401
  init_store();
4808
5402
  CHANNEL_INSTRUCTIONS = [
4809
5403
  "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.',
5404
+ `- 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.`,
5405
+ "- 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.",
5406
+ '- 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
5407
  "- 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
5408
  "- 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
- "- 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.",
5409
+ "- 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. When nothing is running, a map can still show a wireframe of the page drawn from the code; the request explains how.",
4814
5410
  "- If an illuminate channel message arrives instead, call illuminate_next to get the request.",
4815
5411
  "- While working on an illuminate request, don't edit files or run commands that change anything, and never read secret files (.env, keys). A fix is only proposed; illuminate applies it after the person approves it on the map.",
4816
5412
  "- Answers are shown on the map. In the terminal, say at most a sentence or two."
@@ -4895,7 +5491,7 @@ var init_channel = __esm({
4895
5491
 
4896
5492
  // packages/server/src/cli.ts
4897
5493
  init_browser();
4898
- import * as fs13 from "node:fs";
5494
+ import * as fs14 from "node:fs";
4899
5495
  import * as path10 from "node:path";
4900
5496
 
4901
5497
  // packages/server/src/cli-support.ts
@@ -4952,7 +5548,7 @@ async function main() {
4952
5548
  const { runChannel: runChannel2 } = await Promise.resolve().then(() => (init_channel(), channel_exports));
4953
5549
  return runChannel2({ root: args.repoGiven ? args.repo : void 0, port: args.port });
4954
5550
  }
4955
- if (!fs13.existsSync(args.repo)) throw new Error(`No such folder: ${args.repo}`);
5551
+ if (!fs14.existsSync(args.repo)) throw new Error(`No such folder: ${args.repo}`);
4956
5552
  if (args.command === "list") {
4957
5553
  const maps = createStore(args.repo).list();
4958
5554
  if (!maps.length) return console.log('No maps yet. Try: illume "what happens when \u2026?"');
@@ -4963,7 +5559,7 @@ async function main() {
4963
5559
  const target = args.rest[0];
4964
5560
  if (!target) throw new Error("Which map? illume check <map-id|file>");
4965
5561
  await initTreeSitterForChecks();
4966
- const raw = fs13.existsSync(target) ? JSON.parse(fs13.readFileSync(target, "utf8")) : createStore(args.repo).get(target);
5562
+ const raw = fs14.existsSync(target) ? JSON.parse(fs14.readFileSync(target, "utf8")) : createStore(args.repo).get(target);
4967
5563
  if (!raw) throw new Error(`No map "${target}" in ${args.repo}/.illuminate/maps`);
4968
5564
  const parsed = parseMap("map" in raw ? raw.map : raw);
4969
5565
  if (!parsed.ok) throw new Error(`The map isn't valid:
@@ -4971,8 +5567,10 @@ ${parsed.problems.join("\n")}`);
4971
5567
  const report = check(parsed.map, args.repo);
4972
5568
  console.log(`${report.summary.confirmed} of ${report.summary.claims} claims confirmed`);
4973
5569
  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("; ")}`);
5570
+ for (const [id, c] of Object.entries(group)) if (c.status === "unconfirmed") console.log(` \u2717 ${kind} ${id}: ${c.reasons.join("; ")}`);
4975
5571
  }
5572
+ const { pending, done } = report.summary.proposals;
5573
+ if (pending + done) console.log(`${done} of ${pending + done} proposed changes are done in the code`);
4976
5574
  process.exitCode = report.summary.unconfirmed ? 1 : 0;
4977
5575
  return;
4978
5576
  }