codechart 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,18 +1,34 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/program.ts
4
- import { Command as Command7, CommanderError } from "commander";
4
+ import { Command as Command9, CommanderError } from "commander";
5
5
 
6
6
  // src/commands/check.ts
7
7
  import path2 from "path";
8
8
  import { Command } from "commander";
9
9
 
10
10
  // src/config/load.ts
11
- import { existsSync, readFileSync, realpathSync, statSync } from "fs";
11
+ import { existsSync, realpathSync } from "fs";
12
12
  import { homedir } from "os";
13
13
  import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
14
14
  import { parse } from "yaml";
15
15
 
16
+ // src/read-regular.ts
17
+ import { closeSync, constants, fstatSync, openSync, readSync } from "fs";
18
+ function readRegularFile(path3, accept) {
19
+ const fd = openSync(path3, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
20
+ try {
21
+ const st = fstatSync(fd);
22
+ if (!accept(st)) return void 0;
23
+ const buf = Buffer.alloc(st.size);
24
+ let n = 0;
25
+ for (let r = 1; r > 0 && n < buf.length; n += r) r = readSync(fd, buf, n, buf.length - n, null);
26
+ return buf.toString("utf8", 0, n);
27
+ } finally {
28
+ closeSync(fd);
29
+ }
30
+ }
31
+
16
32
  // src/config/builtin-rules.ts
17
33
  var MAP_RULES = [
18
34
  {
@@ -185,18 +201,25 @@ function findRepoRoot(cwd) {
185
201
  }
186
202
  }
187
203
  function readConfigFile(file, root) {
188
- if (!existsSync(file)) return void 0;
189
- const real = realpathSync(file);
204
+ let real;
205
+ try {
206
+ real = realpathSync(file);
207
+ } catch (e) {
208
+ if (e.code === "ENOENT") return void 0;
209
+ throw e;
210
+ }
190
211
  if (root !== void 0) {
191
212
  const rel = relative(realpathSync(root), real);
192
213
  if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`${file}: resolves outside the repo`);
193
214
  }
194
- const st = statSync(real);
195
- if (!st.isFile()) throw new Error(`${file}: not a regular file`);
196
- if (st.size > MAX_BYTES) throw new Error(`${file}: too large (over 1 MB)`);
215
+ const text = readRegularFile(real, (st) => {
216
+ if (!st.isFile()) throw new Error(`${file}: not a regular file`);
217
+ if (st.size > MAX_BYTES) throw new Error(`${file}: too large (over 1 MB)`);
218
+ return true;
219
+ });
197
220
  let raw;
198
221
  try {
199
- raw = parse(readFileSync(real, "utf8"));
222
+ raw = parse(text);
200
223
  } catch (e) {
201
224
  throw new Error(`${file}: ${e.message.split("\n")[0]}`);
202
225
  }
@@ -233,11 +256,11 @@ function loadConfigWithSources(opts) {
233
256
  const configHome = xdg && isAbsolute(xdg) ? xdg : home ? join(home, ".config") : void 0;
234
257
  const root = findRepoRoot(opts.cwd) ?? resolve(opts.cwd);
235
258
  const globalPath = configHome ? join(configHome, "codechart", "config.yaml") : void 0;
236
- const repoPath = join(root, ".codechart.yaml");
259
+ const repoPath2 = join(root, ".codechart.yaml");
237
260
  const global = globalPath ? readConfigFile(globalPath) : void 0;
238
- const repo = dropGlobalOnly(readConfigFile(repoPath, root), repoPath, opts.warn);
261
+ const repo = dropGlobalOnly(readConfigFile(repoPath2, root), repoPath2, opts.warn);
239
262
  const globalSource = `global: ${globalPath}`;
240
- const repoSource = `repo: ${repoPath}`;
263
+ const repoSource = `repo: ${repoPath2}`;
241
264
  const files = [
242
265
  { file: global, source: globalSource },
243
266
  { file: repo, source: repoSource }
@@ -281,124 +304,6 @@ function loadConfig(opts) {
281
304
  return loadConfigWithSources(opts).config;
282
305
  }
283
306
 
284
- // src/rules/git-files.ts
285
- import { execFileSync } from "child_process";
286
- import { existsSync as existsSync2 } from "fs";
287
- import { win32 } from "path";
288
- var MAX_REF = 200;
289
- function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
290
- if (platform !== "win32") return "git";
291
- for (const raw of (env.PATH ?? env.Path ?? "").split(";")) {
292
- const dir = raw.replace(/^"(.*)"$/, "$1");
293
- if (!win32.isAbsolute(dir)) continue;
294
- const file = win32.join(dir, "git.exe");
295
- if (exists(file)) return file;
296
- }
297
- throw new Error("git not found on PATH");
298
- }
299
- var gitPath;
300
- var SAFE_ARGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never"];
301
- function git(cwd, args, config = []) {
302
- try {
303
- gitPath ??= gitBinary();
304
- const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
305
- const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_CONFIG_COUNT: String(n + config.length) };
306
- config.forEach(([k, v], i) => {
307
- env[`GIT_CONFIG_KEY_${n + i}`] = k;
308
- env[`GIT_CONFIG_VALUE_${n + i}`] = v;
309
- });
310
- return execFileSync(gitPath, [...SAFE_ARGS, ...args], {
311
- cwd,
312
- env,
313
- timeout: 3e4,
314
- encoding: "utf8",
315
- // -uall on big trees can exceed the 1 MiB default
316
- maxBuffer: 256 * 1024 * 1024,
317
- stdio: ["ignore", "pipe", "pipe"]
318
- });
319
- } catch (e) {
320
- const stderr = String(e.stderr ?? "").trim().split("\n")[0];
321
- throw new Error(`git ${args.find((a) => !a.startsWith("-"))} failed: ${stderr || e.message}`);
322
- }
323
- }
324
- function repoFilterOverrides(cwd) {
325
- let out;
326
- try {
327
- out = git(cwd, ["config", "--show-scope", "--includes", "-z", "--name-only", "--get-regexp", "^filter\\."]);
328
- } catch {
329
- return [];
330
- }
331
- const keys = /* @__PURE__ */ new Set();
332
- const drivers = /* @__PURE__ */ new Set();
333
- const recs = out.split("\0");
334
- for (let i = 0; i + 1 < recs.length; i += 2) {
335
- const [scope, key] = [recs[i], recs[i + 1]];
336
- const m = /^(filter\..+)\.(clean|process)$/i.exec(key);
337
- if ((scope === "local" || scope === "worktree") && m) {
338
- keys.add(key);
339
- drivers.add(m[1]);
340
- }
341
- }
342
- return [...[...keys].map((k) => [k, ""]), ...[...drivers].map((d) => [`${d}.required`, "false"])];
343
- }
344
- var nulList = (out) => out.split("\0").filter(Boolean);
345
- function refProblem(ref) {
346
- if (ref === "") return "is empty";
347
- if (ref.length > MAX_REF) return `is longer than ${MAX_REF} characters`;
348
- if (ref.startsWith("-")) return 'must not start with "-"';
349
- if (/\s/.test(ref) || hasHiddenChars(ref)) return "must not contain spaces, control or invisible characters";
350
- return void 0;
351
- }
352
- function checkRef(flag, ref) {
353
- const problem = refProblem(ref);
354
- if (problem) throw new Error(`${flag} ${problem}`);
355
- }
356
- function gitChangedFiles(cwd) {
357
- const records = git(cwd, ["status", "--porcelain=v1", "-z", "-uall"], repoFilterOverrides(cwd)).split("\0");
358
- const files = [];
359
- for (let i = 0; i < records.length; i++) {
360
- const rec = records[i];
361
- if (!rec || rec.length < 4) continue;
362
- files.push(rec.slice(3));
363
- if (rec[0] === "R" || rec[0] === "C" || rec[1] === "R" || rec[1] === "C") i++;
364
- }
365
- return files;
366
- }
367
- function resolveCommit(cwd, flag, ref) {
368
- checkRef(flag, ref);
369
- try {
370
- return git(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]).trim();
371
- } catch {
372
- throw new Error(`${flag} ${ref} is not a commit`);
373
- }
374
- }
375
- function gitCommitFiles(cwd, ref) {
376
- const sha = resolveCommit(cwd, "--commit", ref);
377
- const parent = git(cwd, ["rev-list", "--parents", "-n", "1", sha, "--"]).trim().split(" ")[1];
378
- if (!parent) return nulList(git(cwd, ["diff-tree", "-r", "--root", "--no-commit-id", "--name-only", "-z", sha]));
379
- return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", parent, sha, "--"]));
380
- }
381
- function gitSinceFiles(cwd, base, head = "HEAD") {
382
- checkRef("--since", base);
383
- checkRef("--head", head);
384
- return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", `${base}...${head}`, "--"]));
385
- }
386
- function gitListFiles(cwd, sha) {
387
- return nulList(
388
- sha ? git(cwd, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", sha]) : git(cwd, ["ls-files", "-z", "--cached", "--full-name"])
389
- );
390
- }
391
- function gitFileAt(cwd, sha, rel, maxBytes) {
392
- const entry = git(cwd, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", sha, "--", rel]).split("\0")[0];
393
- if (!entry) return null;
394
- const [meta, path3] = entry.split(" ");
395
- const [mode, type, oid] = meta.split(" ");
396
- if (path3 !== rel) return null;
397
- if (type !== "blob" || mode === "120000") return { error: `${rel} is not a regular file at ${sha.slice(0, 12)}` };
398
- if (Number(git(cwd, ["cat-file", "-s", oid]).trim()) > maxBytes) return { error: `${rel} is too large (over 5 MB)` };
399
- return git(cwd, ["cat-file", "blob", oid]);
400
- }
401
-
402
307
  // src/rules/resolve.ts
403
308
  import path from "path";
404
309
  import picomatch from "picomatch";
@@ -408,18 +313,18 @@ function normalizePath(p, root) {
408
313
  const rootSlashed = root.replace(/\\/g, "/");
409
314
  if (DRIVE_PATH.test(slashed)) {
410
315
  if (!DRIVE_PATH.test(rootSlashed)) return slashed;
411
- const relative4 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
412
- return isInside(relative4) ? relative4 : slashed;
316
+ const relative5 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
317
+ return isInside(relative5) ? relative5 : slashed;
413
318
  }
414
319
  if (!path.posix.isAbsolute(slashed)) return slashed;
415
- const relative3 = path.posix.relative(rootSlashed, slashed);
416
- return isInside(relative3) ? relative3 : slashed;
320
+ const relative4 = path.posix.relative(rootSlashed, slashed);
321
+ return isInside(relative4) ? relative4 : slashed;
417
322
  }
418
323
  function lowerDrive(p) {
419
324
  return p.charAt(0).toLowerCase() + p.slice(1);
420
325
  }
421
- function isInside(relative3) {
422
- return relative3 !== "" && relative3 !== ".." && !relative3.startsWith("../");
326
+ function isInside(relative4) {
327
+ return relative4 !== "" && relative4 !== ".." && !relative4.startsWith("../");
423
328
  }
424
329
  function isPathRule(rule) {
425
330
  return rule.paths !== void 0;
@@ -520,71 +425,251 @@ function resolveRules(config, files, matched, root = process.cwd()) {
520
425
  return result;
521
426
  }
522
427
 
523
- // src/commands/check.ts
524
- var csv = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
525
- function terseResult(r) {
526
- const out = {};
527
- if (r.pathMatches.length > 0) out.pathMatches = r.pathMatches;
528
- if (r.excludedFiles.map.length + r.excludedFiles.flow.length > 0) {
529
- out.excludedFiles = r.excludedFiles;
530
- out.remainingFiles = r.remainingFiles;
428
+ // src/rules/git-files.ts
429
+ import { execFileSync } from "child_process";
430
+ import { existsSync as existsSync2, lstatSync } from "fs";
431
+ import { join as join2, win32 } from "path";
432
+ var MAX_REF = 200;
433
+ function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
434
+ if (platform !== "win32") return "git";
435
+ for (const raw of (env.PATH ?? env.Path ?? "").split(";")) {
436
+ const dir = raw.replace(/^"(.*)"$/, "$1");
437
+ if (!win32.isAbsolute(dir)) continue;
438
+ const file = win32.join(dir, "git.exe");
439
+ if (exists(file)) return file;
531
440
  }
532
- if (r.toJudge.length > 0 && (r.unknownMatched || !onlyBuiltinsToJudge(r.toJudge))) out.toJudge = r.toJudge;
533
- else if (r.toJudge.length > 0 && !r.final) out.judgeBuiltins = r.toJudge.map((t) => t.rule);
534
- if (r.unknownMatched) out.unknownMatched = r.unknownMatched;
535
- if (r.final) out.final = r.final;
536
- return out;
441
+ throw new Error("git not found on PATH");
537
442
  }
538
- function selectionError(o) {
539
- if (o.files !== void 0 && csv(o.files).length === 0) return "--files is empty";
540
- const sources = [o.files !== void 0, o.git, o.commit !== void 0, o.since !== void 0].filter(Boolean).length;
541
- const gitPlusSince = sources === 2 && o.git && o.since !== void 0;
542
- if (sources === 0 || sources > 1 && !gitPlusSince) {
543
- return "specify one of --files, --git, --commit or --since (only --git and --since combine)";
443
+ var gitPath;
444
+ var SAFE_ARGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never"];
445
+ var OutputTooLarge = class extends Error {
446
+ };
447
+ function git(cwd, args, config = [], input, maxBuffer = 256 * 1024 * 1024) {
448
+ try {
449
+ gitPath ??= gitBinary();
450
+ const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
451
+ const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_CONFIG_COUNT: String(n + config.length) };
452
+ config.forEach(([k, v], i) => {
453
+ env[`GIT_CONFIG_KEY_${n + i}`] = k;
454
+ env[`GIT_CONFIG_VALUE_${n + i}`] = v;
455
+ });
456
+ return execFileSync(gitPath, [...SAFE_ARGS, ...args], {
457
+ cwd,
458
+ env,
459
+ timeout: 3e4,
460
+ encoding: "utf8",
461
+ // -uall on big trees can exceed the 1 MiB default
462
+ maxBuffer,
463
+ ...input === void 0 ? { stdio: ["ignore", "pipe", "pipe"] } : { input, stdio: ["pipe", "pipe", "pipe"] }
464
+ });
465
+ } catch (e) {
466
+ if (e.code === "ENOBUFS") throw new OutputTooLarge(`git output over ${maxBuffer} bytes`);
467
+ const stderr = String(e.stderr ?? "").trim().split("\n")[0];
468
+ throw new Error(`git ${args.find((a) => !a.startsWith("-"))} failed: ${stderr || e.message}`);
544
469
  }
545
- if (o.head !== void 0 && o.since === void 0) return "--head needs --since";
546
- if (o.head !== void 0 && o.git) return "--head compares another branch, so it does not combine with --git";
470
+ }
471
+ function repoFilterOverrides(cwd) {
472
+ let out;
473
+ try {
474
+ out = git(cwd, ["config", "--show-scope", "--includes", "-z", "--name-only", "--get-regexp", "^filter\\."]);
475
+ } catch {
476
+ return [];
477
+ }
478
+ const keys = /* @__PURE__ */ new Set();
479
+ const drivers = /* @__PURE__ */ new Set();
480
+ const recs = out.split("\0");
481
+ for (let i = 0; i + 1 < recs.length; i += 2) {
482
+ const [scope, key] = [recs[i], recs[i + 1]];
483
+ const m = /^(filter\..+)\.(clean|process)$/i.exec(key);
484
+ if ((scope === "local" || scope === "worktree") && m) {
485
+ keys.add(key);
486
+ drivers.add(m[1]);
487
+ }
488
+ }
489
+ return [...[...keys].map((k) => [k, ""]), ...[...drivers].map((d) => [`${d}.required`, "false"])];
490
+ }
491
+ var nulList = (out) => out.split("\0").filter(Boolean);
492
+ function refProblem(ref) {
493
+ if (ref === "") return "is empty";
494
+ if (ref.length > MAX_REF) return `is longer than ${MAX_REF} characters`;
495
+ if (ref.startsWith("-")) return 'must not start with "-"';
496
+ if (/\s/.test(ref) || hasHiddenChars(ref)) return "must not contain spaces, control or invisible characters";
547
497
  return void 0;
548
498
  }
549
- function gitFiles(root, o) {
550
- if (!root) throw new Error("not a git repository (use --files)");
499
+ function checkRef(flag, ref) {
500
+ const problem = refProblem(ref);
501
+ if (problem) throw new Error(`${flag} ${problem}`);
502
+ }
503
+ function gitChangedFiles(cwd, renameSources = false) {
504
+ const records = git(cwd, ["status", "--porcelain=v1", "-z", "-uall"], repoFilterOverrides(cwd)).split("\0");
551
505
  const files = [];
552
- if (o.since !== void 0) files.push(...gitSinceFiles(root, o.since, o.head));
553
- if (o.commit !== void 0) files.push(...gitCommitFiles(root, o.commit));
554
- if (o.git) files.push(...gitChangedFiles(root));
506
+ for (let i = 0; i < records.length; i++) {
507
+ const rec = records[i];
508
+ if (!rec || rec.length < 4) continue;
509
+ files.push(rec.slice(3));
510
+ if (rec[0] === "R" || rec[0] === "C" || rec[1] === "R" || rec[1] === "C") {
511
+ i++;
512
+ if (renameSources && (rec[0] === "R" || rec[1] === "R") && records[i]) files.push(records[i]);
513
+ }
514
+ }
555
515
  return files;
556
516
  }
557
- function checkCommand(opts) {
558
- const cwd = opts.cwd ?? process.cwd();
559
- return new Command("check").description("resolve which rules apply to a set of changed files").option("--files <csv>", "comma-separated changed files").option("--git", "use staged, unstaged and untracked files from git").option("--commit <sha>", "use the files one commit changed (a merge: against its first parent)").option("--since <base>", "use the files committed since <base> (git diff <base>...HEAD); add --git for uncommitted ones too").option("--head <ref>", "with --since: compare <base>...<ref> instead of HEAD (another branch)").option("--matched <csv>", "plain-language rules that matched").action((o, cmd) => {
560
- const usage = selectionError(o);
561
- if (usage) cmd.error(usage, { exitCode: 2 });
562
- try {
563
- const root = findRepoRoot(cwd);
564
- const files = o.files !== void 0 ? csv(o.files).map((f) => path2.resolve(cwd, f)) : gitFiles(root, o);
565
- const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
566
- `) });
567
- const result = resolveRules(config, files, o.matched !== void 0 ? csv(o.matched) : void 0, root ?? path2.resolve(cwd));
568
- opts.stdout(escapeJsonControls(JSON.stringify(terseResult(result), null, 2)) + "\n");
569
- } catch (e) {
570
- opts.stderr(`codechart: ${e.message}
571
- `);
572
- process.exitCode = 2;
573
- }
574
- });
517
+ function resolveCommit(cwd, flag, ref) {
518
+ checkRef(flag, ref);
519
+ try {
520
+ return git(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]).trim();
521
+ } catch {
522
+ throw new Error(`${flag} ${ref} is not a commit`);
523
+ }
575
524
  }
576
-
577
- // src/commands/config.ts
578
- import { Command as Command2 } from "commander";
579
-
580
- // src/render/terminal/wrap.ts
581
- var flat = (s) => stripInvisible(s).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
582
- var ANSI = /\u001b\[[0-9;]*m/g;
583
- var ZERO = /* @__PURE__ */ new Set([65039, 8205]);
584
- var WIDE = [
585
- [4352, 4447],
586
- [9881, 9881],
587
- [9898, 9899],
525
+ function gitParent(cwd, sha) {
526
+ return git(cwd, ["rev-list", "--parents", "-n", "1", sha, "--"]).trim().split(" ")[1];
527
+ }
528
+ function gitEmptyTree(cwd) {
529
+ return git(cwd, ["hash-object", "-t", "tree", "--stdin"], [], "").trim();
530
+ }
531
+ function gitMergeBase(cwd, base, head = "HEAD") {
532
+ checkRef("--since", base);
533
+ return git(cwd, ["merge-base", base, head]).trim();
534
+ }
535
+ function gitFileDiff(cwd, range, rel, maxBytes) {
536
+ return git(
537
+ cwd,
538
+ ["--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--submodule=short", "-U3", ...range.args, "--", rel],
539
+ range.config,
540
+ void 0,
541
+ maxBytes
542
+ );
543
+ }
544
+ function gitUntracked(cwd, rel) {
545
+ return git(cwd, ["--literal-pathspecs", "ls-files", "-z", "--others", "--exclude-standard", "--", rel]).split("\0")[0] === rel;
546
+ }
547
+ function gitCommitFiles(cwd, ref) {
548
+ const sha = resolveCommit(cwd, "--commit", ref);
549
+ const parent = gitParent(cwd, sha);
550
+ if (!parent) return nulList(git(cwd, ["diff-tree", "-r", "--root", "--no-commit-id", "--name-only", "-z", sha]));
551
+ return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", parent, sha, "--"]));
552
+ }
553
+ function gitSinceFiles(cwd, base, head = "HEAD") {
554
+ checkRef("--since", base);
555
+ checkRef("--head", head);
556
+ return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", `${base}...${head}`, "--"]));
557
+ }
558
+ function gitListFiles(cwd, sha) {
559
+ return nulList(
560
+ sha ? git(cwd, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", sha]) : git(cwd, ["ls-files", "-z", "--cached", "--full-name"])
561
+ );
562
+ }
563
+ function gitFileAt(cwd, sha, rel, maxBytes) {
564
+ const entry = git(cwd, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", sha, "--", rel]).split("\0")[0];
565
+ if (!entry) return null;
566
+ const [meta, path3] = entry.split(" ");
567
+ const [mode, type, oid] = meta.split(" ");
568
+ if (path3 !== rel) return null;
569
+ if (type !== "blob" || mode === "120000") return { error: `${rel} is not a regular file at ${sha.slice(0, 12)}` };
570
+ if (Number(git(cwd, ["cat-file", "-s", oid]).trim()) > maxBytes) return { error: `${rel} is too large (over 5 MB)` };
571
+ return git(cwd, ["cat-file", "blob", oid]);
572
+ }
573
+ function gitHead(cwd) {
574
+ try {
575
+ return git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]).trim() || void 0;
576
+ } catch {
577
+ return void 0;
578
+ }
579
+ }
580
+ function gitDirtyHashes(cwd, max = Infinity) {
581
+ const files = gitChangedFiles(cwd);
582
+ if (files.length > max) return void 0;
583
+ const out = {};
584
+ const present2 = files.filter((f) => !f.includes("\n") && lstatSync(join2(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
585
+ const hashes = present2.length ? git(cwd, ["hash-object", "--no-filters", "--stdin-paths"], [], present2.join("\n")).trim().split("\n") : [];
586
+ for (const f of files) out[f] = existsSync2(join2(cwd, f)) ? "present" : "deleted";
587
+ present2.forEach((f, i) => out[f] = hashes[i] ?? "");
588
+ return out;
589
+ }
590
+ function gitDiffFiles(cwd, from, to) {
591
+ return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", from, to, "--"]));
592
+ }
593
+
594
+ // src/rules/selection.ts
595
+ var csv = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
596
+ function selectionError(o) {
597
+ if (o.files !== void 0 && csv(o.files).length === 0) return "--files is empty";
598
+ const sources = [o.files !== void 0, o.git, o.commit !== void 0, o.since !== void 0].filter(Boolean).length;
599
+ const gitPlusSince = sources === 2 && o.git && o.since !== void 0;
600
+ if (sources === 0 || sources > 1 && !gitPlusSince) {
601
+ return "specify one of --files, --git, --commit or --since (only --git and --since combine)";
602
+ }
603
+ if (o.head !== void 0 && o.since === void 0) return "--head needs --since";
604
+ if (o.head !== void 0 && o.git) return "--head compares another branch, so it does not combine with --git";
605
+ return void 0;
606
+ }
607
+ var hasGitSelection = (o) => Boolean(o.git) || o.commit !== void 0 || o.since !== void 0 || o.head !== void 0;
608
+ function gitFiles(root, o, renameSources = false) {
609
+ if (!root) throw new Error("not a git repository (use --files)");
610
+ const files = [];
611
+ if (o.since !== void 0) files.push(...gitSinceFiles(root, o.since, o.head));
612
+ if (o.commit !== void 0) files.push(...gitCommitFiles(root, o.commit));
613
+ if (o.git) files.push(...gitChangedFiles(root, renameSources));
614
+ return files;
615
+ }
616
+ function diffRange(root, o) {
617
+ if (o.commit !== void 0) {
618
+ const sha = resolveCommit(root, "--commit", o.commit);
619
+ return { args: [gitParent(root, sha) ?? gitEmptyTree(root), sha], worktree: false, config: [] };
620
+ }
621
+ if (o.since !== void 0 && !o.git) {
622
+ return { args: [`${o.since}...${o.head ?? "HEAD"}`], worktree: false, config: [] };
623
+ }
624
+ const from = o.since !== void 0 ? gitMergeBase(root, o.since) : gitHead(root) ?? gitEmptyTree(root);
625
+ return { args: [from], worktree: true, config: repoFilterOverrides(root) };
626
+ }
627
+
628
+ // src/commands/check.ts
629
+ function terseResult(r) {
630
+ const out = {};
631
+ if (r.pathMatches.length > 0) out.pathMatches = r.pathMatches;
632
+ if (r.excludedFiles.map.length + r.excludedFiles.flow.length > 0) {
633
+ out.excludedFiles = r.excludedFiles;
634
+ out.remainingFiles = r.remainingFiles;
635
+ }
636
+ if (r.toJudge.length > 0 && (r.unknownMatched || !onlyBuiltinsToJudge(r.toJudge))) out.toJudge = r.toJudge;
637
+ else if (r.toJudge.length > 0 && !r.final) out.judgeBuiltins = r.toJudge.map((t) => t.rule);
638
+ if (r.unknownMatched) out.unknownMatched = r.unknownMatched;
639
+ if (r.final) out.final = r.final;
640
+ return out;
641
+ }
642
+ function checkCommand(opts) {
643
+ const cwd = opts.cwd ?? process.cwd();
644
+ return new Command("check").description("resolve which rules apply to a set of changed files").option("--files <csv>", "comma-separated changed files").option("--git", "use staged, unstaged and untracked files from git").option("--commit <sha>", "use the files one commit changed (a merge: against its first parent)").option("--since <base>", "use the files committed since <base> (git diff <base>...HEAD); add --git for uncommitted ones too").option("--head <ref>", "with --since: compare <base>...<ref> instead of HEAD (another branch)").option("--matched <csv>", "plain-language rules that matched").action((o, cmd) => {
645
+ const usage = selectionError(o);
646
+ if (usage) cmd.error(usage, { exitCode: 2 });
647
+ try {
648
+ const root = findRepoRoot(cwd);
649
+ const files = o.files !== void 0 ? csv(o.files).map((f) => path2.resolve(cwd, f)) : gitFiles(root, o);
650
+ const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
651
+ `) });
652
+ const result = resolveRules(config, files, o.matched !== void 0 ? csv(o.matched) : void 0, root ?? path2.resolve(cwd));
653
+ opts.stdout(escapeJsonControls(JSON.stringify(terseResult(result), null, 2)) + "\n");
654
+ } catch (e) {
655
+ opts.stderr(`codechart: ${e.message}
656
+ `);
657
+ process.exitCode = 2;
658
+ }
659
+ });
660
+ }
661
+
662
+ // src/commands/config.ts
663
+ import { Command as Command2 } from "commander";
664
+
665
+ // src/render/terminal/wrap.ts
666
+ var flat = (s) => stripInvisible(s).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
667
+ var ANSI = /\u001b\[[0-9;]*m/g;
668
+ var ZERO = /* @__PURE__ */ new Set([65039, 8205]);
669
+ var WIDE = [
670
+ [4352, 4447],
671
+ [9881, 9881],
672
+ [9898, 9899],
588
673
  [9989, 9989],
589
674
  [9999, 9999],
590
675
  [10060, 10060],
@@ -643,9 +728,9 @@ function wrapItems(head, items, width) {
643
728
  };
644
729
  items.forEach((raw, i) => {
645
730
  const item2 = typeof raw === "string" ? { text: raw } : raw;
646
- const sep3 = i === 0 ? "" : " \xB7 ";
647
- if (columns(sep3 + item2.text) <= room()) {
648
- append(sep3);
731
+ const sep4 = i === 0 ? "" : " \xB7 ";
732
+ if (columns(sep4 + item2.text) <= room()) {
733
+ append(sep4);
649
734
  return append(item2.text, item2);
650
735
  }
651
736
  if (!fresh) newLine();
@@ -723,28 +808,144 @@ function configCommand(opts) {
723
808
  });
724
809
  }
725
810
 
726
- // src/commands/init.ts
811
+ // src/commands/hook.ts
812
+ import { closeSync as closeSync2, fstatSync as fstatSync2, mkdirSync, openSync as openSync2, readdirSync, readFileSync, readSync as readSync2, statSync, unlinkSync, writeFileSync } from "fs";
813
+ import { homedir as homedir2 } from "os";
727
814
  import { join as join3 } from "path";
728
- import { Command as Command3 } from "commander";
815
+ import { Argument, Command as Command3 } from "commander";
816
+ var MIN_FILES = 3;
817
+ var MAX_INPUT = 1024 * 1024;
818
+ var MAX_TRANSCRIPT_TAIL = 8 * 1024 * 1024;
819
+ var MAX_DIRTY = 5e3;
820
+ var KEEP_DAYS = 7;
821
+ var SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
822
+ var DIAGRAM = /\*\*(Map|Flow)\*\*/;
823
+ function changedFiles(before, now, diff) {
824
+ const changed = /* @__PURE__ */ new Set();
825
+ for (const f of /* @__PURE__ */ new Set([...Object.keys(before.files), ...Object.keys(now.files)])) {
826
+ if (before.files[f] !== now.files[f]) changed.add(f);
827
+ }
828
+ if (now.head && before.head !== now.head) for (const f of diff(before.head, now.head)) changed.add(f);
829
+ return [...changed].sort();
830
+ }
831
+ var blocks = (e) => Array.isArray(e.message?.content) ? e.message.content : [];
832
+ var isPrompt = (e) => e.type === "user" && !e.isMeta && (typeof e.message?.content === "string" || blocks(e).length > 0 && !blocks(e).some((b) => b.type === "tool_result"));
833
+ function turnUsedCodechart(jsonl) {
834
+ let used = false;
835
+ for (const line of jsonl.split("\n")) {
836
+ let e;
837
+ try {
838
+ e = JSON.parse(line);
839
+ } catch {
840
+ continue;
841
+ }
842
+ if (isPrompt(e)) used = false;
843
+ else if (e.type === "assistant") {
844
+ for (const b of blocks(e)) {
845
+ if (b.type === "text" && DIAGRAM.test(b.text ?? "")) used = true;
846
+ if (b.type === "tool_use" && typeof b.input?.command === "string" && /\bcodechart\s+(check|render)\b/.test(b.input.command)) used = true;
847
+ }
848
+ }
849
+ }
850
+ return used;
851
+ }
852
+ function readTail(file, max) {
853
+ const fd = openSync2(file, "r");
854
+ try {
855
+ const st = fstatSync2(fd);
856
+ if (!st.isFile()) return "";
857
+ const size = Math.min(st.size, max);
858
+ const buf = Buffer.alloc(size);
859
+ readSync2(fd, buf, 0, size, st.size - size);
860
+ return buf.toString("utf8");
861
+ } finally {
862
+ closeSync2(fd);
863
+ }
864
+ }
865
+ async function readInput(stdin) {
866
+ const text = await stdin();
867
+ if (text.length > MAX_INPUT) return {};
868
+ const v = JSON.parse(text);
869
+ return typeof v === "object" && v !== null ? v : {};
870
+ }
871
+ async function readStdin() {
872
+ let text = "";
873
+ for await (const chunk of process.stdin) {
874
+ text += String(chunk);
875
+ if (text.length > MAX_INPUT) break;
876
+ }
877
+ return text;
878
+ }
879
+ function snapshot(root) {
880
+ const files = gitDirtyHashes(root, MAX_DIRTY);
881
+ return files && { head: gitHead(root), files };
882
+ }
883
+ function prune(dir, now) {
884
+ for (const f of readdirSync(dir)) {
885
+ const p = join3(dir, f);
886
+ if (now - statSync(p).mtimeMs > KEEP_DAYS * 864e5) unlinkSync(p);
887
+ }
888
+ }
889
+ var nudge = (count) => `This turn changed ${count} files and your reply has no codechart diagram. Unless the user said no diagram, follow the codechart skill now (check, then render) and reply with what it prints; if it says no diagram applies, stop without mentioning it.`;
890
+ function hookCommand(opts) {
891
+ return new Command3("hook").description("Claude Code hook (install with install-skill --hook): asks for a diagram after a turn that changed 3+ files without one").addArgument(new Argument("<event>").choices(["prompt", "stop"])).action(async (event) => {
892
+ try {
893
+ const input = await readInput(opts.stdin ?? readStdin);
894
+ const id = input.session_id;
895
+ const cwd = input.cwd;
896
+ if (typeof id !== "string" || !SESSION_ID.test(id) || typeof cwd !== "string") return;
897
+ const root = findRepoRoot(cwd);
898
+ if (!root) return;
899
+ const dir = join3(opts.home ?? homedir2(), ".cache", "codechart", "turns");
900
+ const file = join3(dir, `${id}.json`);
901
+ if (event === "prompt") {
902
+ const snap = snapshot(root);
903
+ mkdirSync(dir, { recursive: true, mode: 448 });
904
+ prune(dir, (opts.now?.() ?? /* @__PURE__ */ new Date()).getTime());
905
+ if (snap) writeFileSync(file, JSON.stringify({ root, ...snap }), { mode: 384 });
906
+ else unlinkSync(file);
907
+ return;
908
+ }
909
+ if (input.stop_hook_active === true) return;
910
+ const before = JSON.parse(readFileSync(file, "utf8"));
911
+ if (before.root !== root) return;
912
+ const now = snapshot(root);
913
+ if (!now) return;
914
+ const files = changedFiles(before, now, (a, b) => a ? gitDiffFiles(root, a, b) : gitListFiles(root, b));
915
+ if (files.length < MIN_FILES) return;
916
+ const last = input.last_assistant_message;
917
+ if (typeof last === "string" && DIAGRAM.test(last)) return;
918
+ const transcript = input.transcript_path;
919
+ if (typeof transcript === "string" && turnUsedCodechart(readTail(transcript, MAX_TRANSCRIPT_TAIL))) return;
920
+ opts.stdout(`${JSON.stringify({ hookSpecificOutput: { hookEventName: "Stop", additionalContext: nudge(files.length) } })}
921
+ `);
922
+ } catch {
923
+ }
924
+ });
925
+ }
926
+
927
+ // src/commands/init.ts
928
+ import { join as join5 } from "path";
929
+ import { Command as Command4 } from "commander";
729
930
 
730
931
  // src/assets.ts
731
932
  import { existsSync as existsSync3 } from "fs";
732
- import { dirname as dirname2, join as join2 } from "path";
933
+ import { dirname as dirname2, join as join4 } from "path";
733
934
  import { fileURLToPath } from "url";
734
- function packageFile(relative3) {
935
+ function packageFile(relative4) {
735
936
  let dir = dirname2(fileURLToPath(import.meta.url));
736
- while (!existsSync3(join2(dir, "package.json"))) {
937
+ while (!existsSync3(join4(dir, "package.json"))) {
737
938
  const parent = dirname2(dir);
738
939
  if (parent === dir) throw new Error("package root not found");
739
940
  dir = parent;
740
941
  }
741
- return join2(dir, relative3);
942
+ return join4(dir, relative4);
742
943
  }
743
944
 
744
945
  // src/commands/copy-file.ts
745
- import { constants, copyFileSync, existsSync as existsSync4, lstatSync, mkdirSync, unlinkSync } from "fs";
946
+ import { constants as constants2, copyFileSync, existsSync as existsSync4, lstatSync as lstatSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "fs";
746
947
  import { dirname as dirname3 } from "path";
747
- var isSymlink = (path3) => lstatSync(path3, { throwIfNoEntry: false })?.isSymbolicLink() === true;
948
+ var isSymlink = (path3) => lstatSync2(path3, { throwIfNoEntry: false })?.isSymbolicLink() === true;
748
949
  function copyFiles(pairs, force, opts) {
749
950
  try {
750
951
  const link = force ? void 0 : pairs.find(({ target }) => isSymlink(target));
@@ -762,9 +963,9 @@ function copyFiles(pairs, force, opts) {
762
963
  return false;
763
964
  }
764
965
  for (const { source, target } of pairs) {
765
- mkdirSync(dirname3(target), { recursive: true });
766
- if (force && isSymlink(target)) unlinkSync(target);
767
- copyFileSync(source, target, force ? 0 : constants.COPYFILE_EXCL);
966
+ mkdirSync2(dirname3(target), { recursive: true });
967
+ if (force && isSymlink(target)) unlinkSync2(target);
968
+ copyFileSync(source, target, force ? 0 : constants2.COPYFILE_EXCL);
768
969
  opts.stdout(`wrote ${target}
769
970
  `);
770
971
  }
@@ -779,32 +980,32 @@ function copyFiles(pairs, force, opts) {
779
980
 
780
981
  // src/commands/init.ts
781
982
  function initCommand(opts) {
782
- return new Command3("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
983
+ return new Command4("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
783
984
  const root = findRepoRoot(opts.cwd ?? process.cwd());
784
985
  if (!root) {
785
986
  opts.stderr("codechart: not a git repository\n");
786
987
  process.exitCode = 1;
787
988
  return;
788
989
  }
789
- copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join3(root, ".codechart.yaml") }], o.force === true, opts);
990
+ copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join5(root, ".codechart.yaml") }], o.force === true, opts);
790
991
  });
791
992
  }
792
993
 
793
994
  // src/commands/install-skill.ts
794
- import { existsSync as existsSync5, lstatSync as lstatSync2, readdirSync } from "fs";
795
- import { homedir as homedir2 } from "os";
796
- import { join as join4, resolve as resolve2 } from "path";
797
- import { Command as Command4 } from "commander";
995
+ import { existsSync as existsSync5, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "fs";
996
+ import { homedir as homedir3 } from "os";
997
+ import { join as join6, resolve as resolve2 } from "path";
998
+ import { Command as Command5 } from "commander";
798
999
 
799
1000
  // src/commands/agents.ts
800
1001
  var SHARED = ".agents/skills";
801
1002
  var AGENTS = [
802
- { name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [] },
803
- { name: "codex", label: "Codex", home: ".codex", skills: SHARED, reads: [] },
804
- { name: "gemini", label: "Gemini CLI", home: ".gemini", skills: ".gemini/skills", reads: [SHARED] },
1003
+ { name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [], instructions: ".claude/CLAUDE.md" },
1004
+ { name: "codex", label: "Codex", home: ".codex", skills: SHARED, reads: [], instructions: ".codex/AGENTS.md" },
1005
+ { name: "gemini", label: "Gemini CLI", home: ".gemini", skills: ".gemini/skills", reads: [SHARED], instructions: ".gemini/GEMINI.md" },
805
1006
  { name: "copilot", label: "GitHub Copilot", home: ".copilot", skills: ".copilot/skills", reads: [SHARED] },
806
1007
  { name: "cursor", label: "Cursor", home: ".cursor", skills: ".cursor/skills", reads: [SHARED, ".claude/skills", ".codex/skills"] },
807
- { name: "opencode", label: "OpenCode", home: ".config/opencode", skills: ".config/opencode/skills", reads: [SHARED, ".claude/skills"] },
1008
+ { name: "opencode", label: "OpenCode", home: ".config/opencode", skills: ".config/opencode/skills", reads: [SHARED, ".claude/skills"], instructions: ".config/opencode/AGENTS.md" },
808
1009
  { name: "goose", label: "Goose", home: ".config/goose", skills: SHARED, reads: [".claude/skills"] },
809
1010
  { name: "amp", label: "Amp", home: ".config/amp", skills: ".config/agents/skills", reads: [".claude/skills"] },
810
1011
  { name: "windsurf", label: "Windsurf", home: ".codeium/windsurf", skills: ".codeium/windsurf/skills", reads: [SHARED] },
@@ -824,6 +1025,110 @@ function skillFolders(agents) {
824
1025
  return groups;
825
1026
  }
826
1027
 
1028
+ // src/commands/nudges.ts
1029
+ import { mkdirSync as mkdirSync3, realpathSync as realpathSync2, writeFileSync as writeFileSync2 } from "fs";
1030
+ import { dirname as dirname4 } from "path";
1031
+ var REMINDER = "Before summarizing or planning a change that touches 3+ files or adds behaviour with branches, use the codechart skill (skip it for small edits: typos, formatting, one-line fixes).";
1032
+ var START = "<!-- codechart -->";
1033
+ var END = "<!-- /codechart -->";
1034
+ var BLOCK = `${START}
1035
+ ${REMINDER}
1036
+ ${END}`;
1037
+ function readRegular(file) {
1038
+ let path3;
1039
+ try {
1040
+ path3 = realpathSync2(file);
1041
+ } catch (e) {
1042
+ if (e.code === "ENOENT") return { path: file };
1043
+ throw e;
1044
+ }
1045
+ const text = readRegularFile(path3, (st) => st.isFile());
1046
+ if (text === void 0) throw new Error(`${file}: not a regular file`);
1047
+ return { path: path3, text };
1048
+ }
1049
+ function blockAt(text) {
1050
+ const at = text.indexOf(START);
1051
+ const end = at < 0 ? -1 : text.indexOf(END, at);
1052
+ return end > at ? [at, end + END.length] : void 0;
1053
+ }
1054
+ function addReminder(file, force) {
1055
+ const { path: path3, text = "" } = readRegular(file);
1056
+ const block = blockAt(text);
1057
+ if (block) {
1058
+ if (text.slice(...block) === BLOCK) return "present";
1059
+ if (!force) return "outdated";
1060
+ writeFileSync2(path3, text.slice(0, block[0]) + BLOCK + text.slice(block[1]));
1061
+ return "updated";
1062
+ }
1063
+ mkdirSync3(dirname4(path3), { recursive: true });
1064
+ const gap = text === "" || text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
1065
+ writeFileSync2(path3, `${text}${gap}${BLOCK}
1066
+ `);
1067
+ return "added";
1068
+ }
1069
+ function removeReminder(file) {
1070
+ const { path: path3, text } = readRegular(file);
1071
+ const block = text === void 0 ? void 0 : blockAt(text);
1072
+ if (!text || !block) return "absent";
1073
+ const before = text.slice(0, block[0]).replace(/\n\n$/, "\n");
1074
+ const after = text.slice(block[1]).replace(/^\n/, "");
1075
+ writeFileSync2(path3, before + after);
1076
+ return "removed";
1077
+ }
1078
+ var HOOK_COMMANDS = { UserPromptSubmit: "codechart hook prompt", Stop: "codechart hook stop" };
1079
+ var TIMEOUTS = { UserPromptSubmit: 10, Stop: 30 };
1080
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1081
+ var isCodechartHook = (h) => isObject(h) && typeof h.command === "string" && h.command.startsWith("codechart hook ");
1082
+ function readSettings(file) {
1083
+ const { path: path3, text } = readRegular(file);
1084
+ let settings;
1085
+ try {
1086
+ settings = text === void 0 || text.trim() === "" ? {} : JSON.parse(text);
1087
+ } catch {
1088
+ throw new Error(`${file}: not valid JSON; edit the hooks by hand (see the README)`);
1089
+ }
1090
+ if (!isObject(settings)) throw new Error(`${file}: not a JSON object`);
1091
+ settings.hooks ??= {};
1092
+ if (!isObject(settings.hooks)) throw new Error(`${file}: "hooks" is not an object`);
1093
+ return { path: path3, settings };
1094
+ }
1095
+ function installClaudeHooks(file) {
1096
+ const { path: path3, settings } = readSettings(file);
1097
+ let added = false;
1098
+ for (const [event, command] of Object.entries(HOOK_COMMANDS)) {
1099
+ const groups = settings.hooks[event] ??= [];
1100
+ if (!Array.isArray(groups)) throw new Error(`${file}: "hooks.${event}" is not a list`);
1101
+ if (groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isCodechartHook))) continue;
1102
+ groups.push({ hooks: [{ type: "command", command, timeout: TIMEOUTS[event] }] });
1103
+ added = true;
1104
+ }
1105
+ if (!added) return "present";
1106
+ mkdirSync3(dirname4(path3), { recursive: true });
1107
+ writeFileSync2(path3, `${JSON.stringify(settings, null, 2)}
1108
+ `);
1109
+ return "added";
1110
+ }
1111
+ function removeClaudeHooks(file) {
1112
+ const { path: path3, settings } = readSettings(file);
1113
+ let removed = false;
1114
+ for (const [event, groups] of Object.entries(settings.hooks)) {
1115
+ if (!Array.isArray(groups)) continue;
1116
+ const kept = groups.flatMap((g) => {
1117
+ if (!isObject(g) || !Array.isArray(g.hooks) || !g.hooks.some(isCodechartHook)) return [g];
1118
+ removed = true;
1119
+ const hooks2 = g.hooks.filter((h) => !isCodechartHook(h));
1120
+ return hooks2.length ? [{ ...g, hooks: hooks2 }] : [];
1121
+ });
1122
+ if (kept.length) settings.hooks[event] = kept;
1123
+ else delete settings.hooks[event];
1124
+ }
1125
+ if (!removed) return "absent";
1126
+ const { hooks, ...rest } = settings;
1127
+ writeFileSync2(path3, `${JSON.stringify(Object.keys(hooks).length ? settings : rest, null, 2)}
1128
+ `);
1129
+ return "removed";
1130
+ }
1131
+
827
1132
  // src/commands/picker.ts
828
1133
  import { emitKeypressEvents } from "readline";
829
1134
  function pickerStep(s, key) {
@@ -860,19 +1165,19 @@ function pickerLines(title, items, s, width = Infinity) {
860
1165
  const head = cut(`${i === s.cursor ? "\u276F" : " "} ${s.checked[i] ? "\u25C9" : "\u25EF"} ${it.label.padEnd(pad2)} `, width);
861
1166
  return head + dim(cut(it.hint, width - head.length));
862
1167
  }),
863
- dim(cut("\u2191/\u2193 move \xB7 Space toggle \xB7 a all \xB7 Enter install \xB7 Esc cancel", width))
1168
+ dim(cut("\u2191/\u2193 move \xB7 Space toggle \xB7 a all \xB7 Enter confirm \xB7 Esc cancel", width))
864
1169
  ];
865
1170
  }
866
- function terminalPicker(title, items) {
1171
+ function terminalPicker(title, items, checked = true) {
867
1172
  const { stdin, stdout } = process;
868
- let s = { cursor: 0, checked: items.map(() => true) };
1173
+ let s = { cursor: 0, checked: items.map(() => checked) };
869
1174
  let drawn = 0;
870
1175
  const draw = () => {
871
1176
  const lines = pickerLines(title, items, s, (stdout.columns || 80) - 1);
872
1177
  stdout.write((drawn ? `\x1B[${drawn}A\r\x1B[0J` : "") + lines.join("\n") + "\n");
873
1178
  drawn = lines.length;
874
1179
  };
875
- return new Promise((resolve7) => {
1180
+ return new Promise((resolve9) => {
876
1181
  emitKeypressEvents(stdin);
877
1182
  stdin.setRawMode(true);
878
1183
  stdin.resume();
@@ -885,7 +1190,7 @@ function terminalPicker(title, items) {
885
1190
  stdin.setRawMode(false);
886
1191
  stdin.pause();
887
1192
  stdout.write("\x1B[?25h");
888
- resolve7(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
1193
+ resolve9(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
889
1194
  };
890
1195
  stdin.on("keypress", onKey);
891
1196
  });
@@ -896,14 +1201,53 @@ var NAMES = AGENTS.map((a) => a.name).join(", ");
896
1201
  var terminalChoose = () => process.stdin.isTTY && process.stdout.isTTY ? terminalPicker : void 0;
897
1202
  var hasAny = (paths) => paths.some((p) => {
898
1203
  try {
899
- return lstatSync2(p, { throwIfNoEntry: false }) !== void 0;
1204
+ return lstatSync3(p, { throwIfNoEntry: false }) !== void 0;
900
1205
  } catch {
901
1206
  return false;
902
1207
  }
903
1208
  });
1209
+ async function chooseExtras(agents, opts) {
1210
+ const choose = opts.choose ?? terminalChoose();
1211
+ const files = agents.flatMap((a) => a.instructions ? [`~/${a.instructions}`] : []);
1212
+ const items = [];
1213
+ if (files.length) items.push({ key: "reminder", label: "Reminder line", hint: `use codechart for 3+ file changes \u2192 ${files.join(", ")}` });
1214
+ if (agents.some((a) => a.name === "claude")) {
1215
+ items.push({ key: "hook", label: "Claude Code hook", hint: "ask for a diagram when a turn changed 3+ files \u2192 ~/.claude/settings.json" });
1216
+ }
1217
+ if (!choose || items.length === 0) return { reminder: false, hook: false };
1218
+ const picked = await choose("Optional: help agents remember to use codechart", items, false);
1219
+ const keys = new Set((picked ?? []).map((i) => items[i].key));
1220
+ return { reminder: keys.has("reminder"), hook: keys.has("hook") };
1221
+ }
1222
+ function installExtras(extras, agents, home, force, opts) {
1223
+ const report = (what, run) => {
1224
+ try {
1225
+ opts.stdout(`${run()}
1226
+ `);
1227
+ } catch (e) {
1228
+ opts.stderr(`codechart: ${what}: ${e.message}
1229
+ `);
1230
+ process.exitCode = 1;
1231
+ }
1232
+ };
1233
+ if (extras.reminder) {
1234
+ for (const a of agents) {
1235
+ if (!a.instructions) continue;
1236
+ const file = join6(home, a.instructions);
1237
+ report("reminder", () => {
1238
+ const r = addReminder(file, force);
1239
+ return r === "outdated" ? `reminder differs in ${file} (--force to update)` : r === "present" ? `reminder already in ${file}` : `reminder ${r}: ${file}`;
1240
+ });
1241
+ }
1242
+ }
1243
+ if (extras.hook) {
1244
+ const file = join6(home, ".claude", "settings.json");
1245
+ report("hook", () => installClaudeHooks(file) === "added" ? `hook added: ${file}` : `hook already in ${file}`);
1246
+ }
1247
+ }
904
1248
  function installSkillCommand(opts) {
905
- return new Command4("install-skill").description("install the skill for the agents found in your home folder (or --agent / --dir)").option("--agent <names...>", `install for these agents: ${NAMES}`).option("--dir <path>", "install into this skills folder").option("--force", "overwrite an existing install").action(async (o) => {
906
- const home = opts.home ?? homedir2();
1249
+ return new Command5("install-skill").description("install the skill for the agents found in your home folder (or --agent / --dir)").option("--agent <names...>", `install for these agents: ${NAMES}`).option("--dir <path>", "install into this skills folder").option("--force", "overwrite an existing install").option("--reminder", "add a one-line reminder to use codechart to each agent's global instructions file").option("--hook", "add a Claude Code hook that asks for a diagram after a turn that changed 3+ files without one").action(async (o) => {
1250
+ const home = opts.home ?? homedir3();
907
1251
  const names = o.agent?.flatMap((n) => n.split(",")).map((n) => n.trim().toLowerCase()).filter(Boolean);
908
1252
  const unknown = names?.find((n) => !AGENTS.some((a) => a.name === n));
909
1253
  if (unknown !== void 0) {
@@ -912,7 +1256,7 @@ function installSkillCommand(opts) {
912
1256
  process.exitCode = 1;
913
1257
  return;
914
1258
  }
915
- let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync5(join4(home, a.home))) : [];
1259
+ let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync5(join6(home, a.home))) : [];
916
1260
  if (agents.length === 0 && o.dir === void 0) {
917
1261
  opts.stderr(`codechart: no agent found in ${home}; use --agent <name> (${NAMES}) or --dir <path>
918
1262
  `);
@@ -942,16 +1286,16 @@ function installSkillCommand(opts) {
942
1286
  `);
943
1287
  }
944
1288
  }
945
- const files = readdirSync(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
1289
+ const files = readdirSync2(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
946
1290
  const groups = skillFolders(agents);
947
1291
  for (const folder of new Set(agents.flatMap((a) => [a.skills, ...a.reads]))) {
948
- if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join4(home, folder, "codechart", f)))) continue;
1292
+ if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join6(home, folder, "codechart", f)))) continue;
949
1293
  groups.push({ folder, agents: agents.filter((a) => [a.skills, ...a.reads].includes(folder)) });
950
1294
  }
951
- const targets = groups.map((g) => ({ dir: join4(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", ") }));
952
- if (o.dir !== void 0) targets.push({ dir: join4(resolve2(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: "your folder" });
1295
+ const targets = groups.map((g) => ({ dir: join6(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", ") }));
1296
+ if (o.dir !== void 0) targets.push({ dir: join6(resolve2(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: "your folder" });
953
1297
  for (const { dir, who } of targets) {
954
- const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join4(dir, f) }));
1298
+ const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join6(dir, f) }));
955
1299
  if (o.force !== true && hasAny(pairs.map((p) => p.target))) {
956
1300
  opts.stdout(`already installed for ${who}: ${dir} (--force to update)
957
1301
  `);
@@ -961,16 +1305,22 @@ function installSkillCommand(opts) {
961
1305
  } })) opts.stdout(`installed for ${who}: ${dir}
962
1306
  `);
963
1307
  }
1308
+ const asked = !o.reminder && !o.hook && !names;
1309
+ const extras = asked ? await chooseExtras(agents, opts) : { reminder: o.reminder === true, hook: o.hook === true };
1310
+ installExtras(extras, agents, home, o.force === true, opts);
964
1311
  });
965
1312
  }
966
1313
 
967
1314
  // src/commands/render.ts
968
- import { chmodSync, constants as constants2, closeSync, fstatSync, lstatSync as lstatSync4, mkdirSync as mkdirSync2, openSync, readSync, writeFileSync } from "fs";
969
- import { basename as basename2, dirname as dirname4, resolve as resolve6 } from "path";
970
- import { Command as Command5, Option } from "commander";
1315
+ import { chmodSync, constants as constants3, closeSync as closeSync3, fstatSync as fstatSync3, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync3, readSync as readSync3, writeFileSync as writeFileSync3 } from "fs";
1316
+ import { basename as basename2, dirname as dirname5, resolve as resolve8 } from "path";
1317
+ import { Command as Command6, Option } from "commander";
1318
+
1319
+ // src/render/check.ts
1320
+ import { relative as relative3, resolve as resolve6, sep as sep3 } from "path";
971
1321
 
972
1322
  // src/render/flow/anchors.ts
973
- import { readFileSync as readFileSync2, realpathSync as realpathSync2, statSync as statSync2 } from "fs";
1323
+ import { realpathSync as realpathSync3, statSync as statSync2 } from "fs";
974
1324
  import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve3, sep as sep2 } from "path";
975
1325
  var SNIPPET_MAX_LINES = 15;
976
1326
  var MAX_BYTES2 = 5 * 1024 * 1024;
@@ -999,7 +1349,7 @@ function readLinesAt(path3, rel, root, sha, budget) {
999
1349
  function readLines(path3, root, realRoot, budget) {
1000
1350
  let real;
1001
1351
  try {
1002
- real = realpathSync2(resolve3(root, path3));
1352
+ real = realpathSync3(resolve3(root, path3));
1003
1353
  } catch (e) {
1004
1354
  const code = e.code;
1005
1355
  return code === "ENOENT" || code === "ENOTDIR" ? null : { error: `${path3} cannot be read (${code})` };
@@ -1008,12 +1358,15 @@ function readLines(path3, root, realRoot, budget) {
1008
1358
  if (escapes(rel)) return { error: `${path3} is outside the repo` };
1009
1359
  if (inGit(rel)) return { error: `${path3} is inside .git` };
1010
1360
  try {
1011
- const st = statSync2(real);
1012
- if (!st.isFile()) return { error: `${path3} is not a regular file` };
1013
- if (st.size > MAX_BYTES2) return { error: `${path3} is too large (over 5 MB)` };
1014
- if (st.size > budget.left) return overBudget(path3);
1015
- budget.left -= st.size;
1016
- return toLines(readFileSync2(real, "utf8"));
1361
+ let refused2;
1362
+ const text = readRegularFile(real, (st) => {
1363
+ if (!st.isFile()) refused2 = { error: `${path3} is not a regular file` };
1364
+ else if (st.size > MAX_BYTES2) refused2 = { error: `${path3} is too large (over 5 MB)` };
1365
+ else if (st.size > budget.left) refused2 = overBudget(path3);
1366
+ else budget.left -= st.size;
1367
+ return refused2 === void 0;
1368
+ });
1369
+ return refused2 ?? toLines(text);
1017
1370
  } catch (e) {
1018
1371
  return { error: `${path3} cannot be read (${e.code})` };
1019
1372
  }
@@ -1041,29 +1394,73 @@ function findMatch(path3, match, lines) {
1041
1394
  const line = hits[0];
1042
1395
  return { snippet: { source: `${path3}:${line}`, startLine: line, lines: [clip(lines[line - 1])] } };
1043
1396
  }
1044
- function read(c, path3) {
1045
- const rel = relative2(c.root, resolve3(c.root, path3));
1397
+ function anchorContext(root, at, cwd) {
1398
+ return {
1399
+ root,
1400
+ realRoot: realpathSync3(root),
1401
+ at,
1402
+ budget: { left: MAX_TOTAL_BYTES },
1403
+ cwd: cwd !== void 0 && resolve3(cwd) !== resolve3(root) ? resolve3(cwd) : void 0,
1404
+ cache: /* @__PURE__ */ new Map()
1405
+ };
1406
+ }
1407
+ function refused(path3, rel) {
1046
1408
  if (isAbsolute2(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
1047
1409
  if (inGit(rel)) return { error: `${path3} is inside .git` };
1410
+ return void 0;
1411
+ }
1412
+ function read(c, path3) {
1413
+ const rel = relative2(c.root, resolve3(c.root, path3));
1414
+ const no = refused(path3, rel);
1415
+ if (no) return no;
1048
1416
  return c.at ? readLinesAt(path3, rel, c.root, c.at, c.budget) : readLines(path3, c.root, c.realRoot, c.budget);
1049
1417
  }
1050
- function load(c, path3) {
1051
- const hit = c.cache.get(path3);
1052
- if (hit) return hit;
1053
- const direct = read(c, path3);
1054
- let loaded = { path: path3, lines: direct };
1418
+ function present(c, path3) {
1419
+ const rel = relative2(c.root, resolve3(c.root, path3));
1420
+ const no = refused(path3, rel);
1421
+ if (no) return no;
1422
+ if (c.at) {
1423
+ c.tree ??= new Set(gitListFiles(c.root, c.at));
1424
+ const slashed = rel.split(sep2).join("/");
1425
+ if (slashed === "" || c.tree.has(slashed)) return true;
1426
+ for (const f of c.tree) if (f.startsWith(`${slashed}/`)) return true;
1427
+ return false;
1428
+ }
1429
+ try {
1430
+ const real = realpathSync3(resolve3(c.root, path3));
1431
+ if (escapes(relative2(c.realRoot, real))) return { error: `${path3} is outside the repo` };
1432
+ statSync2(real);
1433
+ return true;
1434
+ } catch (e) {
1435
+ const code = e.code;
1436
+ return code === "ENOENT" || code === "ENOTDIR" ? false : { error: `${path3} cannot be read (${code})` };
1437
+ }
1438
+ }
1439
+ function withCwd(c, path3, get, missing) {
1440
+ const direct = get(path3);
1055
1441
  const outside = !isAbsolute2(path3) && escapes(relative2(c.root, resolve3(c.root, path3)));
1056
- if (c.cwd && (direct === null || outside)) {
1442
+ if (c.cwd && (missing(direct) || outside)) {
1057
1443
  const rel = relative2(c.root, resolve3(c.cwd, path3));
1058
1444
  if (rel !== "" && !escapes(rel)) {
1059
1445
  const alt = rel.split(sep2).join("/");
1060
- const lines = read(c, alt);
1061
- if (lines !== null) loaded = { path: alt, lines };
1446
+ const value = get(alt);
1447
+ if (!missing(value)) return { path: alt, value };
1062
1448
  }
1063
1449
  }
1450
+ return { path: path3, value: direct };
1451
+ }
1452
+ function load(c, path3) {
1453
+ const hit = c.cache.get(path3);
1454
+ if (hit) return hit;
1455
+ const { path: found, value } = withCwd(c, path3, (p) => read(c, p), (v) => v === null);
1456
+ const loaded = { path: found, lines: value };
1064
1457
  c.cache.set(path3, loaded);
1065
1458
  return loaded;
1066
1459
  }
1460
+ function locate(c, path3) {
1461
+ const { path: found, value } = withCwd(c, path3, (p) => present(c, p), (v) => v === false);
1462
+ return typeof value === "boolean" ? { path: found, found: value } : value;
1463
+ }
1067
1464
  var MAX_LISTED_FILES = 2e5;
1068
1465
  function likelyPath(c, path3) {
1069
1466
  const slashed = path3.replaceAll("\\", "/");
@@ -1112,45 +1509,221 @@ function resolveAnchor(source, match, c) {
1112
1509
  };
1113
1510
  }
1114
1511
  function checkFlowAnchors(spec, root, at, cwd) {
1115
- const ctx = {
1116
- root,
1117
- realRoot: realpathSync2(root),
1118
- at,
1119
- budget: { left: MAX_TOTAL_BYTES },
1120
- cwd: cwd !== void 0 && resolve3(cwd) !== resolve3(root) ? resolve3(cwd) : void 0,
1121
- cache: /* @__PURE__ */ new Map()
1122
- };
1512
+ const ctx = anchorContext(root, at, cwd);
1123
1513
  const errors = [];
1124
1514
  const snippets = { steps: /* @__PURE__ */ new Map(), links: {} };
1515
+ let checked = 0;
1125
1516
  const check = (label, { source, match }, store) => {
1126
1517
  if (!source) return;
1127
1518
  const r = resolveAnchor(source, match, ctx);
1128
1519
  if ("error" in r) errors.push(`${label}.${r.field ?? "source"}: ${r.error}`);
1129
- else store(r.snippet);
1520
+ else {
1521
+ checked++;
1522
+ store(r.snippet);
1523
+ }
1130
1524
  };
1131
1525
  spec.steps.forEach((step, i) => check(`steps[${i}]`, step, (s) => snippets.steps.set(step.id, s)));
1132
1526
  spec.links.forEach((link, i) => check(`links[${i}]`, link, (s) => snippets.links[i] = s));
1133
- return errors.length ? { ok: false, errors } : { ok: true, snippets };
1527
+ return errors.length ? { ok: false, errors } : { ok: true, snippets, checked };
1134
1528
  }
1135
1529
 
1136
- // src/render/markdown.ts
1137
- import { resolve as resolve4 } from "path";
1138
- import { pathToFileURL } from "url";
1139
- var longestTicks = (s) => Math.max(0, ...(s.match(/`+/g) ?? []).map((run) => run.length));
1140
- function markdownBlock(header, body, htmlPath) {
1141
- const lines = [header];
1142
- if (body !== void 0) {
1143
- const fence = "`".repeat(Math.max(3, longestTicks(body) + 1));
1144
- lines.push(`${fence}text
1145
- ${body.trimEnd()}
1146
- ${fence}`);
1147
- }
1148
- if (htmlPath) {
1149
- const href = pathToFileURL(resolve4(htmlPath)).href;
1150
- lines.push("", `[Open full map](${href.replace(/\(/g, "%28").replace(/\)/g, "%29")})`);
1151
- }
1152
- return `${lines.join("\n")}
1153
- `;
1530
+ // src/spec/flow.ts
1531
+ import { z as z3 } from "zod";
1532
+ var STEP_TYPES = ["step", "decision", "end"];
1533
+ var STEP_STATUSES = ["existing", "new", "changed", "planned", "removed"];
1534
+ var SOURCE_RE = /^[^\s:\u0000-\u001f\u007f-\u009f]+(:\d+(-\d+)?)?$/;
1535
+ var sourceSchema = pathStr().regex(SOURCE_RE, "must be path:line or path:start-end, or a path with match");
1536
+ var hasLine = (source) => source.includes(":");
1537
+ var ANCHOR = "(path:line, path:start-end, or a path with match)";
1538
+ var matchSchema = z3.string().trim().min(1, "must not be blank").max(SHORT).refine((v) => !hasHiddenChars(v.replaceAll(" ", " ")), "must be one line without control or invisible characters (tabs are fine); quote a single line").describe("Text on the anchored line (plain substring, not a regex); source is then the path only");
1539
+ var stepSchema = z3.strictObject({
1540
+ id: ident(),
1541
+ label: short(),
1542
+ type: z3.enum(STEP_TYPES).optional().describe("Inferred when left out: 0 outgoing links end, 1 step, 2 or more decision"),
1543
+ status: z3.enum(STEP_STATUSES),
1544
+ source: sourceSchema.optional(),
1545
+ match: matchSchema.optional()
1546
+ });
1547
+ var linkSchema = z3.strictObject({
1548
+ from: ident(),
1549
+ to: ident(),
1550
+ label: short().optional(),
1551
+ source: sourceSchema.optional(),
1552
+ match: matchSchema.optional(),
1553
+ planned: z3.boolean().optional(),
1554
+ removed: z3.boolean().optional().describe("Plan only: a link that exists now and the plan drops, between steps that stay")
1555
+ });
1556
+ var MAX_ITEMS = 200;
1557
+ function anchorIssues(a) {
1558
+ if (a.match !== void 0 && !a.source) return [["match", "needs source set to the file path"]];
1559
+ if (!a.source || !SOURCE_RE.test(a.source)) return [];
1560
+ if (a.match !== void 0 && hasLine(a.source)) return [["source", "with match, give only the path (no :line)"]];
1561
+ if (a.match === void 0 && !hasLine(a.source)) return [["source", "needs a line (path:line or path:start-end) or a match"]];
1562
+ return [];
1563
+ }
1564
+ function isPlannedLink(spec, link) {
1565
+ const planned = (id) => spec.steps.some((s) => s.id === id && s.status === "planned");
1566
+ return link.planned === true || planned(link.from) || planned(link.to);
1567
+ }
1568
+ function isRemovedLink(spec, link) {
1569
+ const removed = (id) => spec.steps.some((s) => s.id === id && s.status === "removed");
1570
+ return link.removed === true || removed(link.from) || removed(link.to);
1571
+ }
1572
+ var inferType = (outgoing) => outgoing === 0 ? "end" : outgoing >= 2 ? "decision" : "step";
1573
+ function outgoingLinks(spec, links) {
1574
+ const removedStep = new Set(spec.steps.filter((s) => s.status === "removed").map((s) => s.id));
1575
+ const out = /* @__PURE__ */ new Map();
1576
+ for (const l of links) {
1577
+ if (!removedStep.has(l.from) && isRemovedLink(spec, l)) continue;
1578
+ out.set(l.from, [...out.get(l.from) ?? [], l]);
1579
+ }
1580
+ return out;
1581
+ }
1582
+ function outgoingCounts(spec, links) {
1583
+ return new Map([...outgoingLinks(spec, links)].map(([id, ls]) => [id, ls.length]));
1584
+ }
1585
+ var flowSchema = z3.strictObject({
1586
+ diagram: z3.literal("flow").optional().describe("Optional: a spec with steps is a flow"),
1587
+ kind: z3.enum(["plan", "summary"]),
1588
+ title: short(),
1589
+ rules: z3.array(shortOpt()).optional(),
1590
+ start: ident(),
1591
+ steps: z3.array(stepSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} steps; split the flow`),
1592
+ links: z3.array(linkSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} links; split the flow`),
1593
+ gaps: z3.array(long()).optional()
1594
+ }).superRefine((spec, ctx) => {
1595
+ const issue = (path3, message) => ctx.addIssue({ code: "custom", path: path3, message });
1596
+ const counts = outgoingCounts(spec, spec.links);
1597
+ const live = outgoingLinks(spec, spec.links.map((l, i) => ({ ...l, i })));
1598
+ const typeOf = (step) => step.type ?? inferType(counts.get(step.id) ?? 0);
1599
+ const byId = /* @__PURE__ */ new Map();
1600
+ spec.steps.forEach((step, i) => {
1601
+ if (byId.has(step.id)) issue(["steps", i, "id"], `duplicate "${step.id}"`);
1602
+ byId.set(step.id, step);
1603
+ for (const m of labelIssues(step.label, "step", "source", "migration: add invoices")) {
1604
+ issue(["steps", i, "label"], m);
1605
+ }
1606
+ if (spec.kind === "summary" && step.status === "planned") {
1607
+ issue(["steps", i, "status"], 'a summary describes code that exists; "planned" is for plans');
1608
+ }
1609
+ if (spec.kind === "summary" && step.status === "removed") {
1610
+ issue(["steps", i, "status"], 'a summary describes code that exists; "removed" is for plans');
1611
+ }
1612
+ if (spec.kind === "plan" && (step.status === "new" || step.status === "changed")) {
1613
+ issue(["steps", i, "status"], `a plan uses only "existing", "planned" or "removed" steps, not "${step.status}"`);
1614
+ }
1615
+ if (step.status !== "planned" && !step.source) {
1616
+ issue(["steps", i, "source"], `required for a non-planned step ${ANCHOR}`);
1617
+ }
1618
+ for (const [field, m] of anchorIssues(step)) issue(["steps", i, field], m);
1619
+ });
1620
+ let refsOk = byId.has(spec.start);
1621
+ if (!refsOk) issue(["start"], `unknown step "${spec.start}"`);
1622
+ else if (byId.get(spec.start).status === "removed") issue(["start"], "the start step cannot be removed; start where the flow begins after the plan");
1623
+ const brandNew = (id) => byId.get(id)?.status === "planned" && !byId.get(id)?.source;
1624
+ const removedStep = (id) => byId.get(id)?.status === "removed";
1625
+ const existsNow = (link) => link.planned !== true && !brandNew(link.from) && !brandNew(link.to);
1626
+ const nowOut = /* @__PURE__ */ new Map();
1627
+ spec.links.forEach((link, i) => {
1628
+ if (existsNow(link)) nowOut.set(link.from, [...nowOut.get(link.from) ?? [], i]);
1629
+ });
1630
+ const branchesNow = (id) => spec.kind === "plan" && (nowOut.get(id)?.length ?? 0) >= 2 && (live.get(id)?.length ?? 0) < 2;
1631
+ const outgoing = /* @__PURE__ */ new Map();
1632
+ spec.links.forEach((link, i) => {
1633
+ for (const end of ["from", "to"]) {
1634
+ if (byId.has(link[end])) continue;
1635
+ refsOk = false;
1636
+ issue(["links", i, end], `unknown step "${link[end]}"`);
1637
+ }
1638
+ const list2 = outgoing.get(link.from) ?? [];
1639
+ list2.push(i);
1640
+ outgoing.set(link.from, list2);
1641
+ if (spec.kind === "summary" && link.planned) {
1642
+ issue(["links", i, "planned"], 'a summary describes code that exists; "planned" is for plans');
1643
+ }
1644
+ if (spec.kind === "summary" && link.removed) {
1645
+ issue(["links", i, "removed"], 'a summary describes code that exists; "removed" is for plans');
1646
+ }
1647
+ if (link.removed && link.planned) issue(["links", i, "removed"], "a link is either planned or removed, not both");
1648
+ const ends = [link.from, link.to];
1649
+ if (ends.some(brandNew) && (link.removed || ends.some(removedStep))) {
1650
+ issue(["links", i], "joins a planned step not in the code yet to something the plan removes; they never exist at the same time");
1651
+ } else if (link.planned && ends.some(removedStep)) {
1652
+ issue(["links", i, "planned"], "a link to a removed step cannot be planned");
1653
+ }
1654
+ const from = byId.get(link.from);
1655
+ const leavesDecision = from !== void 0 && (typeOf(from) === "decision" || branchesNow(from.id) && existsNow(link));
1656
+ if (leavesDecision && !isPlannedLink(spec, link) && !link.source) {
1657
+ issue(["links", i, "source"], `required for a non-planned branch leaving a decision ${ANCHOR}`);
1658
+ }
1659
+ for (const [field, m] of anchorIssues(link)) issue(["links", i, field], m);
1660
+ });
1661
+ spec.steps.forEach((step, i) => {
1662
+ const links = (live.get(step.id) ?? []).map((l) => l.i);
1663
+ if (step.type === void 0 && step.label.trim().endsWith("?") && links.length < 2 && !branchesNow(step.id)) {
1664
+ issue(["steps", i, "type"], `label ends in "?", so this is a decision: it needs at least 2 outgoing links, has ${links.length}`);
1665
+ return;
1666
+ }
1667
+ const type = typeOf(step);
1668
+ if (type === "end" && links.length > 0) {
1669
+ issue(["steps", i, "type"], `an end has no outgoing links, has ${links.length}`);
1670
+ }
1671
+ if (type === "step" && links.length > 1) {
1672
+ issue(["steps", i, "type"], `has ${links.length} outgoing links; make it a decision with labelled branches`);
1673
+ }
1674
+ const label = (li) => {
1675
+ if (!spec.links[li].label) issue(["links", li, "label"], "required on a link leaving a decision");
1676
+ };
1677
+ if (type !== "decision") {
1678
+ if (branchesNow(step.id)) (nowOut.get(step.id) ?? []).forEach(label);
1679
+ return;
1680
+ }
1681
+ if (links.length < 2) {
1682
+ issue(["steps", i, "id"], `decision "${step.id}" needs at least 2 outgoing links, has ${links.length}`);
1683
+ }
1684
+ (outgoing.get(step.id) ?? []).forEach(label);
1685
+ });
1686
+ if (refsOk) {
1687
+ const reached = /* @__PURE__ */ new Set([spec.start]);
1688
+ for (const id of reached) {
1689
+ for (const li of outgoing.get(id) ?? []) {
1690
+ if (!isRemovedLink(spec, spec.links[li])) reached.add(spec.links[li].to);
1691
+ }
1692
+ }
1693
+ spec.steps.forEach((step, i) => {
1694
+ if (step.status !== "removed" && !reached.has(step.id)) issue(["steps", i], "not reachable from start");
1695
+ });
1696
+ }
1697
+ });
1698
+ function validateFlowSpec(input) {
1699
+ const result = flowSchema.safeParse(input);
1700
+ if (!result.success) return { ok: false, errors: formatIssues(result.error) };
1701
+ const counts = outgoingCounts(result.data, result.data.links);
1702
+ const steps = result.data.steps.map((s) => ({ ...s, type: s.type ?? inferType(counts.get(s.id) ?? 0) }));
1703
+ return { ok: true, spec: { ...result.data, diagram: "flow", steps } };
1704
+ }
1705
+ function flowJsonSchema() {
1706
+ return z3.toJSONSchema(flowSchema, { io: "input" });
1707
+ }
1708
+
1709
+ // src/render/markdown.ts
1710
+ import { resolve as resolve4 } from "path";
1711
+ import { pathToFileURL } from "url";
1712
+ var longestTicks = (s) => Math.max(0, ...(s.match(/`+/g) ?? []).map((run) => run.length));
1713
+ function markdownBlock(header, body, htmlPath) {
1714
+ const lines = [header];
1715
+ if (body !== void 0) {
1716
+ const fence = "`".repeat(Math.max(3, longestTicks(body) + 1));
1717
+ lines.push(`${fence}text
1718
+ ${body.trimEnd()}
1719
+ ${fence}`);
1720
+ }
1721
+ if (htmlPath) {
1722
+ const href = pathToFileURL(resolve4(htmlPath)).href;
1723
+ lines.push("", `[Open full map](${href.replace(/\(/g, "%28").replace(/\)/g, "%29")})`);
1724
+ }
1725
+ return `${lines.join("\n")}
1726
+ `;
1154
1727
  }
1155
1728
  function openBlockedNote(htmlPath, md) {
1156
1729
  const href = pathToFileURL(resolve4(htmlPath)).href;
@@ -1165,65 +1738,6 @@ ${href}
1165
1738
  `;
1166
1739
  }
1167
1740
 
1168
- // src/render/output-path.ts
1169
- import { createHash } from "crypto";
1170
- import { basename, join as join5 } from "path";
1171
- var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow)?)\.html$/;
1172
- var pad = (n) => String(n).padStart(2, "0");
1173
- function stamp(d) {
1174
- return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1175
- }
1176
- function parseStamp(s) {
1177
- const n = (from, to) => Number(s.slice(from, to));
1178
- return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
1179
- }
1180
- function slugify(title) {
1181
- const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
1182
- return slug || "map";
1183
- }
1184
- function needsWeb(spec, hidden, minNodes) {
1185
- return hidden > 0 || spec.nodes.length >= minNodes;
1186
- }
1187
- var fileSlug = (title, diagram) => diagram === "flow" ? `${slugify(title)}.flow` : slugify(title);
1188
- function htmlOutputPath(config, repo, slug, now) {
1189
- return join5(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
1190
- }
1191
- function repoFolder(root) {
1192
- return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
1193
- }
1194
-
1195
- // src/render/prune.ts
1196
- import { lstatSync as lstatSync3, readdirSync as readdirSync2, rmSync } from "fs";
1197
- import { join as join6 } from "path";
1198
- var DAY_MS = 864e5;
1199
- function pruneHtml(dir, opts) {
1200
- let names;
1201
- try {
1202
- if (lstatSync3(dir).isSymbolicLink()) return [];
1203
- names = readdirSync2(dir);
1204
- } catch {
1205
- return [];
1206
- }
1207
- const current = stamp(opts.now);
1208
- const files = names.map((name) => ({ name, m: HTML_NAME.exec(name) })).filter((f) => f.m !== null).map(({ name, m }) => ({ name, stamp: m[1], slug: m[2] })).sort((a, b) => b.stamp.localeCompare(a.stamp));
1209
- const doomed = /* @__PURE__ */ new Set();
1210
- for (const f of files) if (f.slug === opts.replaceSlug && f.stamp < current) doomed.add(f.name);
1211
- const cutoff = opts.now.getTime() - opts.maxAgeDays * DAY_MS;
1212
- files.filter((f) => !doomed.has(f.name)).forEach((f, i) => {
1213
- if (f.stamp !== current && i >= opts.keep && parseStamp(f.stamp).getTime() < cutoff) doomed.add(f.name);
1214
- });
1215
- const deleted = [];
1216
- for (const name of doomed) {
1217
- const file = join6(dir, name);
1218
- try {
1219
- rmSync(file);
1220
- deleted.push(file);
1221
- } catch {
1222
- }
1223
- }
1224
- return deleted;
1225
- }
1226
-
1227
1741
  // src/render/terminal/render.ts
1228
1742
  import { resolve as resolve5 } from "path";
1229
1743
  import { pathToFileURL as pathToFileURL2 } from "url";
@@ -1244,7 +1758,7 @@ var shown = (node) => {
1244
1758
  if (node.status === "changed") return (node.fields ?? []).filter((f) => f.change !== void 0);
1245
1759
  return [];
1246
1760
  };
1247
- var item = (f) => flat(`${f.change ? MARKER2[f.change] : ""}${f.name}${f.type ? ` ${f.type}` : ""}`);
1761
+ var item = (f) => flat(`${f.change ? MARKER2[f.change] : ""}${f.name}${f.was !== void 0 ? ` ${f.was} \u2192 ${f.type ?? "?"}` : f.type ? ` ${f.type}` : ""}`);
1248
1762
  function renderFieldLines(spec, ids, width, color, cuts) {
1249
1763
  const rows = spec.nodes.filter((n) => ids.has(n.id) && shown(n).length > 0).map((n) => ({ node: n, label: plainLabel(n) }));
1250
1764
  const pad2 = Math.min(Math.max(0, ...rows.map((r) => columns(r.label))), Math.floor(width / 3));
@@ -1302,12 +1816,13 @@ function selectTerminalNodes(spec, max) {
1302
1816
  }
1303
1817
 
1304
1818
  // src/render/terminal/links.ts
1819
+ var EDGE_MARK = { added: "+", removed: "-" };
1305
1820
  var linksAmong = (spec, ids) => spec.edges.filter((e) => ids.has(e.from) && ids.has(e.to));
1306
1821
  function sourceLines(source, links, byId, width, color, cuts) {
1307
1822
  const cap = Math.floor(width / 3);
1308
1823
  const name = truncate(plainLabel(source), cap, cuts);
1309
1824
  const indent = 2 + columns(name) + 1;
1310
- const labels = links.map((e) => flat(e.label ?? ""));
1825
+ const labels = links.map((e) => `${e.change ? EDGE_MARK[e.change] : ""}${flat(e.label ?? "")}`);
1311
1826
  const targets = links.map((e) => byId.get(e.to));
1312
1827
  const longest = Math.max(...labels.map(columns));
1313
1828
  const room = Math.min(...targets.map((t) => width - indent - 4 - columns(targetLabel(t))));
@@ -1335,15 +1850,46 @@ function renderLinks(spec, ids, width, color, cuts = { truncated: false }) {
1335
1850
  const links = linksAmong(spec, ids);
1336
1851
  const layers = [...new Set(spec.nodes.map((n) => n.layer))];
1337
1852
  const sections = layers.flatMap((layer) => {
1338
- const blocks = spec.nodes.filter((n) => n.layer === layer).flatMap((n) => {
1853
+ const blocks2 = spec.nodes.filter((n) => n.layer === layer).flatMap((n) => {
1339
1854
  const own = links.filter((e) => e.from === n.id);
1340
1855
  return own.length > 0 ? sourceLines(n, own, byId, width, color, cuts) : [];
1341
1856
  });
1342
- return blocks.length > 0 ? [[truncate(flat(layer), width, cuts), ...blocks].join("\n")] : [];
1857
+ return blocks2.length > 0 ? [[truncate(flat(layer), width, cuts), ...blocks2].join("\n")] : [];
1343
1858
  });
1344
1859
  return sections.join("\n\n");
1345
1860
  }
1346
1861
 
1862
+ // src/render/terminal/check-lines.ts
1863
+ var MAX_SHOWN = 5;
1864
+ var units = (n, unit) => `${n} ${unit}${n === 1 ? "" : "s"}`;
1865
+ function checkTag(c) {
1866
+ if (!c || c.checked === 0) return "";
1867
+ const total = c.unit === "node" ? String(c.checked) : units(c.checked, c.unit);
1868
+ return ` \xB7 \u2713 ${c.mismatches.length ? `${c.checked - c.mismatches.length} of ` : ""}${total} checked`;
1869
+ }
1870
+ function alertLine(c, width) {
1871
+ const n = c?.mismatches.length ?? 0;
1872
+ if (!c || n === 0) return "";
1873
+ const items = c.mismatches.slice(0, MAX_SHOWN).map((m) => `${flat(m.label)} ${m.short}`);
1874
+ if (n > MAX_SHOWN) items.push(`+${n - MAX_SHOWN} more`);
1875
+ const head = `\u2717 ${n} ${n === 1 ? "claim doesn't" : "claims don't"} match the code: `;
1876
+ if (columns(head) <= width / 2) return wrapItems(head, items, width);
1877
+ return `${truncate(head.trimEnd(), width)}
1878
+ ${wrapItems(" ", items, width)}`;
1879
+ }
1880
+ function countLines(counts, c, width) {
1881
+ const tag2 = checkTag(c);
1882
+ if (columns(counts + tag2) <= width) return counts + tag2;
1883
+ return tag2 ? `${truncate(counts, width)}
1884
+ ${truncate(tag2.replace(/^ · /, ""), width)}` : truncate(counts, width);
1885
+ }
1886
+ function checkHeadline(c) {
1887
+ if (!c || c.checked === 0) return "";
1888
+ const n = c.mismatches.length;
1889
+ const total = units(c.checked, c.unit);
1890
+ return n ? `\u2717 ${n} of ${total} ${n === 1 ? "doesn't" : "don't"} match the code` : `\u2713 ${total} checked against the code`;
1891
+ }
1892
+
1347
1893
  // src/render/terminal/render.ts
1348
1894
  var MIN_WIDTH = 20;
1349
1895
  var MAX_WIDTH = 100;
@@ -1357,11 +1903,11 @@ function defaultWidth(stdout = process.stdout, env = process.env) {
1357
1903
  const fromEnv = Math.floor(Number(env.COLUMNS));
1358
1904
  return Number.isFinite(fromEnv) && fromEnv > 0 && fromEnv <= MAX_ENV_WIDTH ? fromEnv : NOT_TTY_WIDTH;
1359
1905
  }
1360
- function footer(spec, hidden, width, keyLine, htmlPath) {
1906
+ function footer(spec, hidden, width, keyLine, htmlPath, check) {
1361
1907
  const count = (status) => spec.nodes.filter((n) => n.status === status).length;
1362
1908
  const removed = count("removed") > 0 ? ` \xB7 ${count("removed")} removed` : "";
1363
1909
  const lines = [
1364
- truncate(`${spec.nodes.length} nodes \xB7 ${count("new")} new \xB7 ${count("changed")} changed${removed} \xB7 ${count("config")} config`, width)
1910
+ countLines(`${spec.nodes.length} nodes \xB7 ${count("new")} new \xB7 ${count("changed")} changed${removed} \xB7 ${count("config")} config`, check, width)
1365
1911
  ];
1366
1912
  if (keyLine) lines.push(truncate(KEY, width));
1367
1913
  if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), width));
@@ -1375,6 +1921,8 @@ function renderTerminalDetailed(spec, opts) {
1375
1921
  const width = Math.max(opts.width ?? defaultWidth(), MIN_WIDTH);
1376
1922
  const { ids, hidden } = selectTerminalNodes(spec, opts.maxNodes);
1377
1923
  const sections = [];
1924
+ const alert = alertLine(opts.check, width);
1925
+ if (alert) sections.push(alert);
1378
1926
  const links = renderLinks(spec, ids, width, opts.color, cuts);
1379
1927
  if (links) sections.push(links);
1380
1928
  const shown2 = new Set(linksAmong(spec, ids).flatMap((e) => [e.from, e.to]));
@@ -1388,40 +1936,486 @@ function renderTerminalDetailed(spec, opts) {
1388
1936
  const fields = renderFieldLines(spec, ids, width, opts.color, cuts);
1389
1937
  if (fields) sections.push(fields);
1390
1938
  }
1391
- sections.push(footer(spec, hidden, width, opts.keyLine ?? true, opts.htmlPath));
1939
+ sections.push(footer(spec, hidden, width, opts.keyLine ?? true, opts.htmlPath, opts.check));
1392
1940
  return { text: `${sections.join("\n\n")}
1393
1941
  `, truncated: cuts.truncated };
1394
1942
  }
1395
1943
 
1396
- // src/render/web/layout.ts
1397
- var NODE_WIDTH = 220;
1398
- var HEADER_HEIGHT = 28;
1399
- var LINE_HEIGHT = 16;
1400
- var LAYER_PREFIX = "layer:";
1401
- var SUMMARY_CHARS_PER_LINE = 34;
1402
- var SUMMARY_MAX_LINES = 3;
1403
- function wrapSummary(text) {
1404
- return wrapText(text, SUMMARY_CHARS_PER_LINE, SUMMARY_MAX_LINES);
1405
- }
1406
- function wrapText(text, chars, maxLines) {
1407
- const words = text.split(/\s+/).filter(Boolean).flatMap((w) => {
1408
- const parts = [];
1409
- for (let i = 0; i < w.length; i += chars) {
1410
- parts.push(w.slice(i, i + chars));
1944
+ // src/render/flow/walk.ts
1945
+ function walkFlow(spec, budget) {
1946
+ const byId = new Map(spec.steps.map((s) => [s.id, s]));
1947
+ const out = /* @__PURE__ */ new Map();
1948
+ const incoming = /* @__PURE__ */ new Map([[spec.start, 1]]);
1949
+ for (const link of spec.links) {
1950
+ out.set(link.from, [...out.get(link.from) ?? [], link]);
1951
+ incoming.set(link.to, (incoming.get(link.to) ?? 0) + 1);
1952
+ }
1953
+ const shared = new Set([...incoming].filter(([, n]) => n > 1).map(([id]) => id));
1954
+ const seen = /* @__PURE__ */ new Set();
1955
+ const queue = [];
1956
+ let placed = 0;
1957
+ let truncated = false;
1958
+ const take = (id) => {
1959
+ if (placed >= budget) return false;
1960
+ placed++;
1961
+ seen.add(id);
1962
+ return true;
1963
+ };
1964
+ const cut2 = (id, via) => {
1965
+ truncated = true;
1966
+ let hidden = 0;
1967
+ const stack = [id];
1968
+ while (stack.length > 0) {
1969
+ const next = stack.pop();
1970
+ if (seen.has(next)) continue;
1971
+ seen.add(next);
1972
+ hidden++;
1973
+ stack.push(...(out.get(next) ?? []).map((l) => l.to));
1411
1974
  }
1412
- return parts;
1413
- });
1414
- const lines = [];
1415
- let cur = "";
1416
- let overflow = false;
1417
- for (const w of words) {
1418
- if (cur && cur.length + 1 + w.length <= chars) {
1419
- cur += " " + w;
1420
- continue;
1975
+ return { kind: "cut", hidden, via };
1976
+ };
1977
+ const ref = (step, via) => {
1978
+ if (queue.includes(step.id)) return { kind: "ref", step, via };
1979
+ if (!take(step.id)) return cut2(step.id, via);
1980
+ queue.push(step.id);
1981
+ return { kind: "ref", step, via };
1982
+ };
1983
+ const chain = (first, firstPaid) => {
1984
+ const items = [];
1985
+ let step = first;
1986
+ let via;
1987
+ for (let paid = firstPaid; ; paid = false) {
1988
+ if (!paid && !take(step.id)) return { items: [...items, cut2(step.id, via)] };
1989
+ const links = out.get(step.id) ?? [];
1990
+ if (step.type === "decision" || links.length > 1) {
1991
+ return { items, branch: { head: step, arms: links.map((link) => ({ link, chain: arm(link.to) })) } };
1992
+ }
1993
+ items.push({ kind: "step", step, via });
1994
+ if (links.length === 0) return { items };
1995
+ via = links[0];
1996
+ const next = byId.get(via.to);
1997
+ if (shared.has(next.id)) return { items: [...items, ref(next, via)] };
1998
+ step = next;
1421
1999
  }
1422
- if (cur) lines.push(cur);
1423
- if (lines.length === maxLines) {
1424
- overflow = true;
2000
+ };
2001
+ const arm = (to) => {
2002
+ const step = byId.get(to);
2003
+ return shared.has(to) ? { items: [ref(step)] } : chain(step, false);
2004
+ };
2005
+ const start = byId.get(spec.start);
2006
+ let head;
2007
+ if (shared.has(start.id)) {
2008
+ if (!take(start.id)) return { blocks: [], unreachable: 0, truncated: true };
2009
+ queue.push(start.id);
2010
+ head = { shared: true, chain: chain(start, true) };
2011
+ } else {
2012
+ head = { shared: false, chain: chain(start, false) };
2013
+ }
2014
+ if (head.chain.items.some((i) => i.kind === "cut")) return { blocks: [], unreachable: 0, truncated: true };
2015
+ const blocks2 = [head];
2016
+ for (let i = head.shared ? 1 : 0; i < queue.length; i++) {
2017
+ blocks2.push({ shared: true, chain: chain(byId.get(queue[i]), true) });
2018
+ }
2019
+ const unreachable = spec.steps.filter((s) => !seen.has(s.id)).length;
2020
+ return { blocks: blocks2, unreachable, truncated: truncated || unreachable > 0 };
2021
+ }
2022
+
2023
+ // src/render/flow/tree.ts
2024
+ var FLOW_KEY = "key: + new ~ changed ? planned \u25C7 decision \u2937 shared step";
2025
+ var flowKey = (spec) => hasRemoved(spec) ? FLOW_KEY.replace("? planned", "? planned - removed") : FLOW_KEY;
2026
+ var hasRemoved = (spec) => spec.steps.some((s) => s.status === "removed") || spec.links.some((l) => l.removed === true);
2027
+ var MARKER3 = { existing: "", new: "+", changed: "~", planned: "?", removed: "-" };
2028
+ var stepLabel = (step) => MARKER3[step.status] + flat(step.label);
2029
+ var SGR2 = { existing: void 0, new: "32", changed: "33", planned: "35", removed: "31" };
2030
+ var painter = (status, ctx) => ctx.color && SGR2[status] ? (text) => text ? `\x1B[${SGR2[status]}m${text}\x1B[0m` : text : void 0;
2031
+ var stepSegment = (step, ctx) => ({
2032
+ text: stepLabel(step),
2033
+ paint: painter(step.status, ctx)
2034
+ });
2035
+ var cutText = (hidden, ctx) => hidden > 0 ? `\u2026 (+${hidden} steps ${ctx.htmlPath ? "in web view" : "not shown"})` : "\u2026";
2036
+ function itemSegments(item2, ctx) {
2037
+ if (item2.kind === "cut") return [{ text: cutText(item2.hidden, ctx) }];
2038
+ const label = stepSegment(item2.step, ctx);
2039
+ return item2.kind === "ref" ? [{ text: "\u2937 " }, label] : [label];
2040
+ }
2041
+ var segWidth = (segments) => columns(segments.map((s) => s.text).join(""));
2042
+ function linkMark(link, ctx) {
2043
+ if (link.removed === true && !endsAre(ctx.spec, link, "removed")) return "-";
2044
+ return link.planned === true && !endsAre(ctx.spec, link, "planned") ? "?" : "";
2045
+ }
2046
+ var endsAre = (spec, link, status) => spec.steps.some((s) => s.status === status && (s.id === link.from || s.id === link.to));
2047
+ function runLines(items, first, rest, ctx) {
2048
+ const lines = [];
2049
+ let line = first;
2050
+ items.forEach((item2, i) => {
2051
+ const segs = itemSegments(item2, ctx);
2052
+ const mark = item2.via ? linkMark(item2.via, ctx) : "";
2053
+ const arrow = { text: `${mark}\u2192 `, paint: mark ? painter(mark === "-" ? "removed" : "planned", ctx) : void 0 };
2054
+ if (i === 0) {
2055
+ line = [...line, ...segs];
2056
+ } else if (segWidth(line) + segWidth(segs) + 2 + columns(arrow.text) <= ctx.width) {
2057
+ line = [...line, { text: " " }, arrow, ...segs];
2058
+ } else {
2059
+ lines.push(line);
2060
+ line = [{ text: `${rest} ` }, arrow, ...segs];
2061
+ }
2062
+ });
2063
+ lines.push(line);
2064
+ return lines.map((l) => fit(l, ctx.width, ctx.cuts));
2065
+ }
2066
+ function armLines(arms, rest, ctx) {
2067
+ const tones = arms.map(
2068
+ ({ link }) => isRemovedLink(ctx.spec, link) ? "removed" : isPlannedLink(ctx.spec, link) ? "planned" : void 0
2069
+ );
2070
+ const labels = arms.map(({ link }, i) => (tones[i] ? MARKER3[tones[i]] : "") + flat(link.label ?? ""));
2071
+ const pad2 = Math.min(Math.max(...labels.map(columns)), Math.floor(ctx.width / 3));
2072
+ return arms.flatMap((arm, i) => {
2073
+ const last = i === arms.length - 1;
2074
+ const glyph = last ? "\u2514\u2500 " : "\u251C\u2500 ";
2075
+ const label = truncate(labels[i], pad2, ctx.cuts);
2076
+ const head = [{ text: rest + glyph }];
2077
+ if (pad2 > 0) {
2078
+ const paint2 = tones[i] ? painter(tones[i], ctx) : void 0;
2079
+ head.push({ text: label, paint: paint2 }, { text: `${" ".repeat(pad2 - columns(label))} \u2192 ` });
2080
+ }
2081
+ const under = `${rest}${last ? " " : "\u2502 "}${pad2 > 0 ? " ".repeat(pad2 + 3) : ""}`;
2082
+ return chainLines(arm.chain, head, under, "", ctx);
2083
+ });
2084
+ }
2085
+ function chainLines(chain, first, rest, lead, ctx) {
2086
+ const lines = [];
2087
+ let prefix = [...first, { text: lead }];
2088
+ if (chain.items.length > 0) {
2089
+ lines.push(...runLines(chain.items, prefix, rest, ctx));
2090
+ prefix = [{ text: rest }];
2091
+ }
2092
+ if (chain.branch) {
2093
+ const { head, arms } = chain.branch;
2094
+ const glyph = head.type === "decision" ? "\u25C7 " : "";
2095
+ lines.push(fit([...prefix, { text: glyph }, stepSegment(head, ctx)], ctx.width, ctx.cuts));
2096
+ lines.push(...armLines(arms, rest, ctx));
2097
+ }
2098
+ return lines;
2099
+ }
2100
+ function footer2(spec, ctx, md) {
2101
+ const count = (status) => spec.steps.filter((s) => s.status === status).length;
2102
+ const lines = [
2103
+ countLines(
2104
+ `${spec.steps.length} steps \xB7 ${count("new")} new \xB7 ${count("changed")} changed \xB7 ${count("planned")} planned${count("removed") ? ` \xB7 ${count("removed")} removed` : ""}`,
2105
+ ctx.check,
2106
+ ctx.width
2107
+ )
2108
+ ];
2109
+ if (!md) lines.push(truncate(flowKey(spec), ctx.width));
2110
+ if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), ctx.width));
2111
+ if (ctx.htmlPath && !md) lines.push(fullMapLine(ctx.htmlPath));
2112
+ return lines.join("\n");
2113
+ }
2114
+ function flowMarkdown(title, tree, htmlPath, width, cuts, key = FLOW_KEY) {
2115
+ const heading = truncate(flat(title), Math.max(width, MIN_WIDTH), cuts);
2116
+ const titled = `${heading}
2117
+ ${"\u2500".repeat(columns(heading))}`;
2118
+ return markdownBlock(`**Flow** _(${key})_`, tree === void 0 ? titled : `${titled}
2119
+ ${tree}`, htmlPath);
2120
+ }
2121
+ var TOO_LARGE = "flow too large for the terminal; use --output both or web";
2122
+ function renderFlowTree(spec, opts) {
2123
+ const ctx = {
2124
+ width: Math.max(opts.width ?? defaultWidth(), MIN_WIDTH),
2125
+ color: opts.color && !opts.md,
2126
+ cuts: { truncated: false },
2127
+ htmlPath: opts.htmlPath,
2128
+ spec,
2129
+ check: opts.check
2130
+ };
2131
+ const walk = walkFlow(spec, opts.maxNodes);
2132
+ const md = opts.md ?? false;
2133
+ const alert = alertLine(opts.check, ctx.width);
2134
+ if (walk.blocks.length === 0) {
2135
+ const body = (line) => alert ? `${alert}
2136
+ ${line}` : line;
2137
+ if (!opts.htmlPath) return { text: md ? flowMarkdown(spec.title, body(TOO_LARGE), void 0, ctx.width, void 0, flowKey(spec)) : `${body(TOO_LARGE)}
2138
+ `, truncated: true };
2139
+ const text2 = md ? flowMarkdown(spec.title, alert || void 0, opts.htmlPath, ctx.width, void 0, flowKey(spec)) : `${body(fullMapLine(opts.htmlPath))}
2140
+ `;
2141
+ return { text: text2, truncated: true };
2142
+ }
2143
+ const blocks2 = walk.blocks.map((b) => chainLines(b.chain, [], "", b.shared ? "\u2937 " : "", ctx).join("\n"));
2144
+ if (spec.kind === "plan" && (spec.steps.some((s) => s.status === "planned") || spec.links.some((l) => isPlannedLink(spec, l)))) {
2145
+ blocks2[0] = `${truncate("planned flow", ctx.width)}
2146
+ ${blocks2[0]}`;
2147
+ }
2148
+ if (walk.unreachable > 0) blocks2[blocks2.length - 1] += `
2149
+ ${truncate(cutText(walk.unreachable, ctx), ctx.width, ctx.cuts)}`;
2150
+ const tree = [...alert ? [alert] : [], ...blocks2, footer2(spec, ctx, md)].join("\n\n");
2151
+ const text = md ? flowMarkdown(spec.title, tree, opts.htmlPath, ctx.width, ctx.cuts, flowKey(spec)) : `${tree}
2152
+ `;
2153
+ return { text, truncated: walk.truncated || ctx.cuts.truncated };
2154
+ }
2155
+
2156
+ // src/render/check.ts
2157
+ function diffOf(files) {
2158
+ const set = new Set(files);
2159
+ return {
2160
+ has: (p) => p === "" ? files.length > 0 : set.has(p) || files.some((f) => f.startsWith(`${p}/`)),
2161
+ hasFile: (p) => set.has(p)
2162
+ };
2163
+ }
2164
+ var repoPath = (root, path3) => relative3(root, resolve6(root, path3)).split(sep3).join("/");
2165
+ var mustExist = (spec, node) => spec.kind === "plan" ? node.status !== "new" : node.status !== "removed";
2166
+ var IN_DIFF = /* @__PURE__ */ new Set(["new", "changed", "removed"]);
2167
+ var inDiff = (c, path3, diff) => diff.has(repoPath(c.root, path3)) || c.cwd !== void 0 && diff.has(repoPath(c.root, resolve6(c.cwd, path3)));
2168
+ function checkNode(c, spec, node, diff, result) {
2169
+ const needed = mustExist(spec, node);
2170
+ const where = locate(c, node.path);
2171
+ if ("error" in where) return { short: "file unreadable", detail: where.error };
2172
+ if (where.found) result.found.set(node.id, repoPath(c.root, where.path));
2173
+ if (!where.found && needed) {
2174
+ const at = c.at ? ` at ${c.at.slice(0, 12)}` : "";
2175
+ return { short: "file missing", detail: `${node.path} does not exist${at}${likelyPath(c, node.path)}` };
2176
+ }
2177
+ if (diff && spec.kind === "summary" && IN_DIFF.has(node.status) && !inDiff(c, where.path, diff)) {
2178
+ return { short: "not in diff", detail: `marked ${node.status}, but ${where.path} isn't in the diff` };
2179
+ }
2180
+ if (node.match === void 0 || !needed || !where.found) return void 0;
2181
+ const loaded = load(c, where.path);
2182
+ if (loaded.lines === null || !Array.isArray(loaded.lines)) {
2183
+ return { short: "file unreadable", detail: loaded.lines?.error ?? `${where.path} does not exist` };
2184
+ }
2185
+ const r = findMatch(loaded.path, node.match, loaded.lines);
2186
+ if ("error" in r) {
2187
+ return { short: r.error.endsWith(` not found in ${loaded.path}`) ? "match not found" : "match on several lines", detail: r.error };
2188
+ }
2189
+ result.matches.set(node.id, r.snippet);
2190
+ return void 0;
2191
+ }
2192
+ function checkMapNodes(spec, root, opts = {}) {
2193
+ const c = anchorContext(root, opts.at, opts.cwd);
2194
+ const result = { checked: 0, mismatches: [], matches: /* @__PURE__ */ new Map(), found: /* @__PURE__ */ new Map(), unit: "node" };
2195
+ for (const node of spec.nodes) {
2196
+ if (node.path === void 0) continue;
2197
+ result.checked++;
2198
+ const problem = checkNode(c, spec, { ...node, path: node.path }, opts.diff, result);
2199
+ if (problem) result.mismatches.push({ id: node.id, label: plainLabel(node), ...problem });
2200
+ }
2201
+ return result;
2202
+ }
2203
+ function checkFlowDiff(spec, snippets, checked, root, diff) {
2204
+ const mismatches = [];
2205
+ if (diff && spec.kind === "summary") {
2206
+ for (const step of spec.steps) {
2207
+ const snippet = snippets.steps.get(step.id);
2208
+ if (!snippet || step.status !== "new" && step.status !== "changed") continue;
2209
+ const path3 = snippet.source.replace(/:\d+(-\d+)?$/, "");
2210
+ if (diff.has(repoPath(root, path3))) continue;
2211
+ mismatches.push({ id: step.id, label: stepLabel(step), short: "not in diff", detail: `marked ${step.status}, but ${path3} isn't in the diff` });
2212
+ }
2213
+ }
2214
+ return { checked, mismatches, unit: "anchor" };
2215
+ }
2216
+
2217
+ // src/render/output-path.ts
2218
+ import { createHash } from "crypto";
2219
+ import { basename, join as join7 } from "path";
2220
+
2221
+ // src/render/web/states.ts
2222
+ var SIDES = ["now", "after"];
2223
+ var SIDE_TITLE = { now: "Now", after: "After plan" };
2224
+ var SIDE_KEY = {
2225
+ now: [{ text: "red: removed by the plan", tone: "rem" }],
2226
+ after: [{ text: "green: added by the plan", tone: "new" }]
2227
+ };
2228
+ function hasNowAfter(spec) {
2229
+ if (spec.kind !== "plan") return false;
2230
+ return spec.nodes.some((n) => n.status === "changed" || n.status === "removed" || n.fields?.some(touchesExisting)) || spec.edges.some((e) => e.change !== void 0);
2231
+ }
2232
+ var touchesExisting = (f) => f.change === "removed" || f.change === "modified" || f.was !== void 0;
2233
+ var nodeOn = (side, status) => side === "now" ? status !== "new" : status !== "removed";
2234
+ function edgeChange(e, statusOf) {
2235
+ if (e.change) return e.change;
2236
+ const ends = [statusOf.get(e.from), statusOf.get(e.to)];
2237
+ if (ends.includes("new")) return "added";
2238
+ if (ends.includes("removed")) return "removed";
2239
+ return void 0;
2240
+ }
2241
+ var edgeOn = (side, change) => change !== (side === "now" ? "added" : "removed");
2242
+ function fieldsOn(side, node) {
2243
+ const fields = node.fields ?? [];
2244
+ if (side === "after") return fields.filter((f) => f.change !== "removed").map((f) => ({ ...f, was: void 0 }));
2245
+ return fields.filter((f) => f.change !== "added").map((f) => f.was === void 0 ? f : { ...f, type: f.was, was: void 0 });
2246
+ }
2247
+
2248
+ // src/render/output-path.ts
2249
+ var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow)?)\.html$/;
2250
+ var pad = (n) => String(n).padStart(2, "0");
2251
+ function stamp(d) {
2252
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
2253
+ }
2254
+ function parseStamp(s) {
2255
+ const n = (from, to) => Number(s.slice(from, to));
2256
+ return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
2257
+ }
2258
+ function slugify(title) {
2259
+ const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
2260
+ return slug || "map";
2261
+ }
2262
+ function needsWeb(spec, hidden, minNodes) {
2263
+ return hidden > 0 || spec.nodes.length >= minNodes || hasNowAfter(spec);
2264
+ }
2265
+ var fileSlug = (title, diagram) => diagram === "flow" ? `${slugify(title)}.flow` : slugify(title);
2266
+ function htmlOutputPath(config, repo, slug, now) {
2267
+ return join7(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
2268
+ }
2269
+ function repoFolder(root) {
2270
+ return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
2271
+ }
2272
+
2273
+ // src/render/preview.ts
2274
+ import { join as join8, resolve as resolve7 } from "path";
2275
+ var MAX_HUNKS = 3;
2276
+ var MAX_LINES = 40;
2277
+ var MAX_CHARS = 300;
2278
+ var MAX_BYTES3 = 5 * 1024 * 1024;
2279
+ var MAX_TOTAL_BYTES2 = 25 * 1024 * 1024;
2280
+ var clip2 = (l) => l.length > MAX_CHARS ? `${l.slice(0, MAX_CHARS)}\u2026` : l;
2281
+ function parseDiff(path3, text) {
2282
+ const p = { path: path3, lines: [], shown: 0, total: 0 };
2283
+ let hunks = 0;
2284
+ let oldN = 0;
2285
+ let newN = 0;
2286
+ const room = () => hunks <= MAX_HUNKS && p.lines.length < MAX_LINES;
2287
+ for (const raw of text.split("\n")) {
2288
+ const h = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
2289
+ if (h) {
2290
+ hunks++;
2291
+ oldN = Number(h[1]);
2292
+ newN = Number(h[2]);
2293
+ if (room()) p.lines.push({ kind: "hunk", text: clip2(raw) });
2294
+ continue;
2295
+ }
2296
+ if (hunks === 0) {
2297
+ if (/^Binary files .* differ$/.test(raw)) p.note = "binary file";
2298
+ continue;
2299
+ }
2300
+ let line;
2301
+ if (raw[0] === "+") line = { kind: "add", n: newN++, text: raw.slice(1) };
2302
+ else if (raw[0] === "-") line = { kind: "del", n: oldN++, text: raw.slice(1) };
2303
+ else if (raw[0] === " ") {
2304
+ line = { kind: "ctx", n: newN++, text: raw.slice(1) };
2305
+ oldN++;
2306
+ } else continue;
2307
+ if (line.kind !== "ctx") p.total++;
2308
+ if (!room()) continue;
2309
+ p.lines.push({ ...line, text: clip2(line.text.replace(/\r$/, "")) });
2310
+ if (line.kind !== "ctx") p.shown++;
2311
+ }
2312
+ return p;
2313
+ }
2314
+ var TOO_LARGE2 = "diff is too large (over 5 MB)";
2315
+ var OVER_BUDGET = "not shown: the diffs pass 25 MB together";
2316
+ function untrackedDiff(root, rel, max) {
2317
+ let size = 0;
2318
+ const text = readRegularFile(join8(root, rel), (st) => st.isFile() && (size = st.size) <= max);
2319
+ if (text === void 0) return { note: size > MAX_BYTES3 ? TOO_LARGE2 : size > max ? OVER_BUDGET : "not a regular file" };
2320
+ if (text.includes("\0")) return { note: "binary file" };
2321
+ const lines = text.split("\n");
2322
+ if (lines[lines.length - 1] === "") lines.pop();
2323
+ return `@@ -0,0 +1,${lines.length} @@
2324
+ ${lines.map((l) => `+${l}`).join("\n")}`;
2325
+ }
2326
+ function fileDiff(root, range, rel, left) {
2327
+ const max = Math.min(MAX_BYTES3, left);
2328
+ try {
2329
+ const text = gitFileDiff(root, range, rel, max);
2330
+ return text === "" && range.worktree && gitUntracked(root, rel) ? untrackedDiff(root, rel, max) : text;
2331
+ } catch (e) {
2332
+ if (e instanceof OutputTooLarge) return { note: max < MAX_BYTES3 ? OVER_BUDGET : TOO_LARGE2 };
2333
+ return { note: `diff not read (${e.message})` };
2334
+ }
2335
+ }
2336
+ function nodePreviews(spec, root, diff, range, found, cwd) {
2337
+ const out = /* @__PURE__ */ new Map();
2338
+ if (spec.kind !== "summary") return out;
2339
+ const byFile = /* @__PURE__ */ new Map();
2340
+ let left = MAX_TOTAL_BYTES2;
2341
+ for (const node of spec.nodes) {
2342
+ if (node.path === void 0 || !IN_DIFF.has(node.status)) continue;
2343
+ const at = found.get(node.id);
2344
+ const candidates2 = at !== void 0 ? [at] : [repoPath(root, node.path), ...cwd ? [repoPath(root, resolve7(cwd, node.path))] : []];
2345
+ const rel = candidates2.find((p) => diff.hasFile(p));
2346
+ if (rel === void 0) continue;
2347
+ if (!byFile.has(rel)) {
2348
+ const text = left > 0 ? fileDiff(root, range, rel, left) : { note: OVER_BUDGET };
2349
+ if (typeof text === "string") left -= Buffer.byteLength(text);
2350
+ byFile.set(rel, typeof text !== "string" ? { path: rel, lines: [], shown: 0, total: 0, note: text.note } : text === "" ? void 0 : parseDiff(rel, text));
2351
+ }
2352
+ const preview = byFile.get(rel);
2353
+ if (preview) out.set(node.id, preview);
2354
+ }
2355
+ return out;
2356
+ }
2357
+
2358
+ // src/render/prune.ts
2359
+ import { lstatSync as lstatSync4, readdirSync as readdirSync3, rmSync } from "fs";
2360
+ import { join as join9 } from "path";
2361
+ var DAY_MS = 864e5;
2362
+ function pruneHtml(dir, opts) {
2363
+ let names;
2364
+ try {
2365
+ if (lstatSync4(dir).isSymbolicLink()) return [];
2366
+ names = readdirSync3(dir);
2367
+ } catch {
2368
+ return [];
2369
+ }
2370
+ const current = stamp(opts.now);
2371
+ const files = names.map((name) => ({ name, m: HTML_NAME.exec(name) })).filter((f) => f.m !== null).map(({ name, m }) => ({ name, stamp: m[1], slug: m[2] })).sort((a, b) => b.stamp.localeCompare(a.stamp));
2372
+ const doomed = /* @__PURE__ */ new Set();
2373
+ for (const f of files) if (f.slug === opts.replaceSlug && f.stamp < current) doomed.add(f.name);
2374
+ const cutoff = opts.now.getTime() - opts.maxAgeDays * DAY_MS;
2375
+ files.filter((f) => !doomed.has(f.name)).forEach((f, i) => {
2376
+ if (f.stamp !== current && i >= opts.keep && parseStamp(f.stamp).getTime() < cutoff) doomed.add(f.name);
2377
+ });
2378
+ const deleted = [];
2379
+ for (const name of doomed) {
2380
+ const file = join9(dir, name);
2381
+ try {
2382
+ rmSync(file);
2383
+ deleted.push(file);
2384
+ } catch {
2385
+ }
2386
+ }
2387
+ return deleted;
2388
+ }
2389
+
2390
+ // src/render/web/layout.ts
2391
+ var NODE_WIDTH = 220;
2392
+ var HEADER_HEIGHT = 28;
2393
+ var LINE_HEIGHT = 16;
2394
+ var LAYER_PREFIX = "layer:";
2395
+ var SUMMARY_CHARS_PER_LINE = 34;
2396
+ var SUMMARY_MAX_LINES = 3;
2397
+ function wrapSummary(text) {
2398
+ return wrapText(text, SUMMARY_CHARS_PER_LINE, SUMMARY_MAX_LINES);
2399
+ }
2400
+ function wrapText(text, chars, maxLines) {
2401
+ const words = text.split(/\s+/).filter(Boolean).flatMap((w) => {
2402
+ const parts = [];
2403
+ for (let i = 0; i < w.length; i += chars) {
2404
+ parts.push(w.slice(i, i + chars));
2405
+ }
2406
+ return parts;
2407
+ });
2408
+ const lines = [];
2409
+ let cur = "";
2410
+ let overflow = false;
2411
+ for (const w of words) {
2412
+ if (cur && cur.length + 1 + w.length <= chars) {
2413
+ cur += " " + w;
2414
+ continue;
2415
+ }
2416
+ if (cur) lines.push(cur);
2417
+ if (lines.length === maxLines) {
2418
+ overflow = true;
1425
2419
  cur = "";
1426
2420
  break;
1427
2421
  }
@@ -1439,7 +2433,32 @@ function nodeHeight(fields, summary) {
1439
2433
  const summaryLines = summary ? wrapSummary(summary).length : 0;
1440
2434
  return HEADER_HEIGHT + LINE_HEIGHT * (fields + summaryLines);
1441
2435
  }
1442
- async function layoutSpec(spec) {
2436
+ var FIT_CANVASES = [
2437
+ [1140, 800],
2438
+ [420, 800]
2439
+ ];
2440
+ var PANE_CANVASES = [
2441
+ [560, 770],
2442
+ [420, 770]
2443
+ ];
2444
+ function fitScale(l, [w, h]) {
2445
+ return Math.min(w / l.width, h / l.height, 1);
2446
+ }
2447
+ function pickLayout(right, down, canvases = FIT_CANVASES) {
2448
+ for (const canvas of canvases) {
2449
+ const r = fitScale(right, canvas);
2450
+ const d = fitScale(down, canvas);
2451
+ if (Math.abs(r - d) > 5e-3) return d > r ? down : right;
2452
+ }
2453
+ return right;
2454
+ }
2455
+ async function layoutSpec(spec, canvases) {
2456
+ const { default: ELK } = await import("elkjs/lib/elk.bundled.js");
2457
+ const elk = new ELK();
2458
+ const [right, down] = await Promise.all([layoutIn(elk, spec, "RIGHT"), layoutIn(elk, spec, "DOWN")]);
2459
+ return pickLayout(right, down, canvases);
2460
+ }
2461
+ async function layoutIn(elk, spec, direction) {
1443
2462
  const layers = [...new Set(spec.nodes.map((n) => n.layer))];
1444
2463
  const children = layers.map((layer) => ({
1445
2464
  id: LAYER_PREFIX + layer,
@@ -1461,7 +2480,7 @@ async function layoutSpec(spec) {
1461
2480
  id: "root",
1462
2481
  layoutOptions: {
1463
2482
  "elk.algorithm": "layered",
1464
- "elk.direction": "RIGHT",
2483
+ "elk.direction": direction,
1465
2484
  "elk.hierarchyHandling": "INCLUDE_CHILDREN",
1466
2485
  "elk.spacing.nodeNode": "24",
1467
2486
  "elk.layered.spacing.nodeNodeBetweenLayers": "60"
@@ -1469,8 +2488,7 @@ async function layoutSpec(spec) {
1469
2488
  children,
1470
2489
  edges
1471
2490
  };
1472
- const { default: ELK } = await import("elkjs/lib/elk.bundled.js");
1473
- const root = await new ELK().layout(graph);
2491
+ const root = await elk.layout(graph);
1474
2492
  const containerOrigin = /* @__PURE__ */ new Map();
1475
2493
  const groups = [];
1476
2494
  const nodes = [];
@@ -1490,13 +2508,14 @@ async function layoutSpec(spec) {
1490
2508
  const points = sec ? [sec.startPoint, ...sec.bendPoints ?? [], sec.endPoint] : [];
1491
2509
  const origin = e.container && containerOrigin.get(e.container) || { x: 0, y: 0 };
1492
2510
  return {
2511
+ index: idx,
1493
2512
  from: specEdge.from,
1494
2513
  to: specEdge.to,
1495
2514
  ...specEdge.label ? { label: specEdge.label } : {},
1496
2515
  points: points.map((p) => ({ x: p.x + origin.x, y: p.y + origin.y }))
1497
2516
  };
1498
2517
  });
1499
- return { width: root.width ?? 0, height: root.height ?? 0, groups, nodes, edges: outEdges };
2518
+ return { direction, width: root.width ?? 0, height: root.height ?? 0, groups, nodes, edges: outEdges };
1500
2519
  }
1501
2520
 
1502
2521
  // src/render/web/page.ts
@@ -1518,22 +2537,40 @@ header{padding:8px 14px;border-bottom:1px solid var(--line);background:var(--pan
1518
2537
  header h1{margin:0;font-size:15px}
1519
2538
  header .meta{color:var(--muted);font-size:11px;margin-right:auto}
1520
2539
  main{flex:1;display:flex;min-height:0}
1521
- #canvas{flex:1;min-width:0;cursor:grab;overflow:hidden;touch-action:none}
1522
- #canvas.drag{cursor:grabbing}
1523
- #canvas svg{width:100%;height:100%;display:block}
1524
- aside{width:300px;border-left:1px solid var(--line);background:var(--panel);overflow:auto;padding:10px 14px}
2540
+ .canvas{flex:1;min-width:0;min-height:0;cursor:grab;overflow:hidden;touch-action:none}
2541
+ .canvas.drag{cursor:grabbing}
2542
+ .canvas svg{width:100%;height:100%;display:block}
2543
+ #panes{flex:1;min-width:0;display:flex}
2544
+ .pane{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column}
2545
+ .pane+.pane{border-left:1px solid var(--line)}
2546
+ #panes~aside{width:clamp(200px,17.5vw,300px);min-width:200px}
2547
+ .pane-title{padding:4px 10px;font-size:11px;font-weight:600;text-transform:uppercase;color:var(--muted);border-bottom:1px solid var(--line)}
2548
+ .pane-key{font-weight:400;text-transform:none}.k-rem{color:var(--rem)}.k-new{color:var(--new-t)}.k-chg{color:var(--chg-t)}.k-cfg{color:var(--cfg-t)}
2549
+ @media (max-width:900px){#panes{flex-direction:column}.pane+.pane{border-left:0;border-top:1px solid var(--line)}}
2550
+ aside{width:clamp(300px,35vw,600px);min-width:300px;max-width:80vw;border-left:1px solid var(--line);background:var(--panel);overflow:auto;padding:10px 14px}
2551
+ #resize{flex:none;width:5px;margin-right:-5px;position:relative;z-index:1;cursor:col-resize;touch-action:none}
2552
+ #resize:hover,#resize:focus-visible,#resize.drag{background:var(--edge);outline:none}
1525
2553
  aside h2{margin:0 0 6px;font-size:13px}
1526
2554
  aside h3{margin:12px 0 4px;font-size:11px;text-transform:uppercase;color:var(--muted)}
1527
2555
  aside ul{margin:0;padding-left:18px}
1528
2556
  aside .fields-note{color:var(--muted);font-size:11.5px;font-style:italic;margin:6px 0 0}
1529
2557
  aside code{font-family:ui-monospace,monospace;font-size:11px;font-style:normal}
1530
- aside .path{font-family:ui-monospace,monospace;font-size:11px;word-break:break-all;color:var(--muted)}
2558
+ aside .path{font-family:ui-monospace,monospace;font-size:11px;overflow-wrap:anywhere;color:var(--muted)}
2559
+ aside .snippet{font:11px/1.45 ui-monospace,monospace;background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:6px 8px;margin:6px 0;white-space:pre-wrap;overflow-wrap:anywhere}
2560
+ aside .snippet code{display:grid;grid-template-columns:auto minmax(0,1fr);column-gap:10px}
2561
+ aside .snippet .ln{min-width:3ch;color:var(--muted);text-align:right;user-select:none}
2562
+ aside .d-add{color:var(--add)}aside .d-del{color:var(--rem)}aside .d-hunk{color:var(--muted)}
2563
+ aside .mismatch-note{color:var(--rem);margin:6px 0}
2564
+ header .check{font-size:11px;color:var(--new-t)}header .check.bad{color:var(--rem);font-weight:600}
2565
+ .node .flag{fill:var(--rem);font-size:13px;font-weight:700;text-anchor:middle}
1531
2566
  .group rect{fill:none;stroke:var(--line);stroke-dasharray:4 3}
1532
2567
  .group text{fill:var(--muted);font-size:10px;text-transform:uppercase}
1533
2568
  .edge path{fill:none;stroke:var(--edge);stroke-width:1.2}
1534
2569
  .edge text{fill:var(--edge);font-size:9.5px;text-anchor:middle}
1535
2570
  .edge rect{fill:var(--bg);opacity:.9}
1536
2571
  #arrow path{fill:var(--edge)}
2572
+ .edge-added path{stroke:var(--new)}.edge-added text{fill:var(--new-t)}#arrow-added path{fill:var(--new)}
2573
+ .edge-removed path{stroke:var(--rem);stroke-dasharray:5 3}.edge-removed text{fill:var(--rem)}#arrow-removed path{fill:var(--rem);stroke:none}
1537
2574
  .node{cursor:pointer}
1538
2575
  .node .card{fill:var(--card);stroke:var(--line);stroke-width:1}
1539
2576
  .node .head{stroke:var(--line);stroke-width:1}
@@ -1563,49 +2600,56 @@ aside .path{font-family:ui-monospace,monospace;font-size:11px;word-break:break-a
1563
2600
  var CLIENT_JS = `
1564
2601
  (function () {
1565
2602
  var data = JSON.parse(document.getElementById('spec-data').textContent);
1566
- var svg = document.querySelector('#canvas svg');
1567
- var vp = document.getElementById('viewport');
1568
- var canvas = document.getElementById('canvas');
2603
+ var canvases = [].slice.call(document.querySelectorAll('.canvas'));
2604
+ var vps = [].slice.call(document.querySelectorAll('.viewport'));
1569
2605
  var panel = document.getElementById('panel');
1570
2606
  var info = document.getElementById('page-info');
1571
2607
  var infoBtn = document.getElementById('info-toggle');
2608
+ // One transform for every pane, so Now and After stay aligned.
1572
2609
  var t = { x: 0, y: 0, k: 1 };
1573
- function apply() { vp.setAttribute('transform', 'translate(' + t.x + ',' + t.y + ') scale(' + t.k + ')'); }
2610
+ function apply() {
2611
+ vps.forEach(function (vp) { vp.setAttribute('transform', 'translate(' + t.x + ',' + t.y + ') scale(' + t.k + ')'); });
2612
+ }
1574
2613
  function fit() {
1575
- var r = svg.getBoundingClientRect();
2614
+ var r = canvases[0].querySelector('svg').getBoundingClientRect();
1576
2615
  var k = Math.min(r.width / data.width, r.height / data.height, 1) || 1;
1577
2616
  t = { k: k, x: (r.width - data.width * k) / 2, y: (r.height - data.height * k) / 2 };
1578
2617
  apply();
1579
2618
  }
1580
- canvas.addEventListener('wheel', function (e) {
1581
- e.preventDefault();
1582
- var r = svg.getBoundingClientRect();
1583
- var px = e.clientX - r.left, py = e.clientY - r.top;
1584
- var k = Math.min(4, Math.max(0.1, t.k * Math.exp(-e.deltaY * 0.0015)));
1585
- t.x = px - ((px - t.x) / t.k) * k;
1586
- t.y = py - ((py - t.y) / t.k) * k;
1587
- t.k = k;
1588
- apply();
1589
- }, { passive: false });
1590
2619
  var drag = null, moved = false;
1591
- canvas.addEventListener('pointerdown', function (e) {
1592
- drag = { x: e.clientX - t.x, y: e.clientY - t.y, sx: e.clientX, sy: e.clientY };
1593
- moved = false;
2620
+ canvases.forEach(function (canvas) {
2621
+ var svg = canvas.querySelector('svg');
2622
+ canvas.addEventListener('wheel', function (e) {
2623
+ e.preventDefault();
2624
+ var r = svg.getBoundingClientRect();
2625
+ var px = e.clientX - r.left, py = e.clientY - r.top;
2626
+ var k = Math.min(4, Math.max(0.1, t.k * Math.exp(-e.deltaY * 0.0015)));
2627
+ t.x = px - ((px - t.x) / t.k) * k;
2628
+ t.y = py - ((py - t.y) / t.k) * k;
2629
+ t.k = k;
2630
+ apply();
2631
+ }, { passive: false });
2632
+ canvas.addEventListener('pointerdown', function (e) {
2633
+ drag = { x: e.clientX - t.x, y: e.clientY - t.y, sx: e.clientX, sy: e.clientY, canvas: canvas };
2634
+ moved = false;
2635
+ });
1594
2636
  });
1595
2637
  window.addEventListener('pointermove', function (e) {
1596
2638
  if (!drag) return;
1597
- if (Math.abs(e.clientX - drag.sx) + Math.abs(e.clientY - drag.sy) > 3) { moved = true; canvas.classList.add('drag'); }
2639
+ if (Math.abs(e.clientX - drag.sx) + Math.abs(e.clientY - drag.sy) > 3) { moved = true; drag.canvas.classList.add('drag'); }
1598
2640
  if (!moved) return;
1599
2641
  t.x = e.clientX - drag.x; t.y = e.clientY - drag.y; apply();
1600
2642
  });
1601
- function endDrag() { drag = null; canvas.classList.remove('drag'); }
2643
+ function endDrag() {
2644
+ if (drag) drag.canvas.classList.remove('drag');
2645
+ drag = null;
2646
+ }
1602
2647
  window.addEventListener('pointerup', endDrag);
1603
2648
  window.addEventListener('pointercancel', endDrag);
1604
2649
  function select(id) {
1605
2650
  document.querySelectorAll('.node.selected').forEach(function (g) { g.classList.remove('selected'); });
1606
2651
  if (id == null) return;
1607
- var g = document.querySelector('.node[data-id="' + CSS.escape(id) + '"]');
1608
- if (g) g.classList.add('selected');
2652
+ document.querySelectorAll('.node[data-id="' + CSS.escape(id) + '"]').forEach(function (g) { g.classList.add('selected'); });
1609
2653
  }
1610
2654
  function setInfo(on) {
1611
2655
  info.hidden = !on;
@@ -1644,6 +2688,46 @@ var CLIENT_JS = `
1644
2688
  var i = themes.indexOf(root.getAttribute('data-theme'));
1645
2689
  setTheme(themes[(i + 1) % themes.length], true);
1646
2690
  });
2691
+ var aside = document.querySelector('aside');
2692
+ var handle = document.getElementById('resize');
2693
+ var width = 0;
2694
+ // Two panes need the room, so their panel starts at half width and remembers its own size.
2695
+ var panes = !!document.getElementById('panes');
2696
+ var widthKey = panes ? 'codechart.panel.panes' : 'codechart.panel';
2697
+ var minWidth = panes ? 200 : 300;
2698
+ function setWidth(w, save) {
2699
+ width = Math.round(Math.max(minWidth, Math.min(w, window.innerWidth * 0.8)));
2700
+ aside.style.width = width + 'px';
2701
+ if (save) { try { localStorage.setItem(widthKey, String(width)); } catch (e) {} }
2702
+ }
2703
+ function currentWidth() { return width || aside.getBoundingClientRect().width; }
2704
+ var savedWidth = null;
2705
+ try { savedWidth = Number(localStorage.getItem(widthKey)); } catch (e) {}
2706
+ if (savedWidth > 0) setWidth(savedWidth, false);
2707
+ var sizing = false;
2708
+ handle.addEventListener('pointerdown', function (e) {
2709
+ sizing = true;
2710
+ handle.classList.add('drag');
2711
+ if (handle.setPointerCapture) handle.setPointerCapture(e.pointerId);
2712
+ e.preventDefault();
2713
+ });
2714
+ handle.addEventListener('pointermove', function (e) {
2715
+ if (sizing) setWidth(window.innerWidth - e.clientX, false);
2716
+ });
2717
+ function endSize() {
2718
+ if (!sizing) return;
2719
+ sizing = false;
2720
+ handle.classList.remove('drag');
2721
+ setWidth(currentWidth(), true);
2722
+ }
2723
+ handle.addEventListener('pointerup', endSize);
2724
+ handle.addEventListener('pointercancel', endSize);
2725
+ handle.addEventListener('keydown', function (e) {
2726
+ var step = e.key === 'ArrowLeft' ? 40 : e.key === 'ArrowRight' ? -40 : 0;
2727
+ if (!step) return;
2728
+ e.preventDefault();
2729
+ setWidth(currentWidth() + step, true);
2730
+ });
1647
2731
  window.addEventListener('resize', fit);
1648
2732
  fit();
1649
2733
  })();
@@ -1657,6 +2741,8 @@ function jsonForScript(v) {
1657
2741
  return JSON.stringify(v).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1658
2742
  }
1659
2743
  var num = (n) => String(Math.round(n * 10) / 10);
2744
+ var arrowMarker = (id) => `<marker id="${id}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>`;
2745
+ var CHANGE_ARROWS = arrowMarker("arrow-added") + arrowMarker("arrow-removed");
1660
2746
  function list(items) {
1661
2747
  return `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>`;
1662
2748
  }
@@ -1678,20 +2764,25 @@ function midpoint(points) {
1678
2764
  }
1679
2765
  return points[0] ?? { x: 0, y: 0 };
1680
2766
  }
2767
+ var keyHtml = (key) => key.map((k) => `<span class="k-${k.tone}">${esc(k.text)}</span>`).join(" \xB7 ");
1681
2768
  var CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${createHash2("sha256").update(CLIENT_JS).digest("base64")}'; img-src data:; base-uri 'none'; form-action 'none'`;
1682
2769
  function renderPage(p) {
1683
2770
  const theme = p.meta.theme && THEMES.includes(p.meta.theme) ? p.meta.theme : "auto";
1684
2771
  const data = { width: p.width, height: p.height };
2772
+ const defs = `<defs>${arrowMarker("arrow")}${p.extraDefs ?? ""}</defs>`;
2773
+ const canvas = (viewport3, i) => `<div class="canvas"${p.panes ? "" : ' id="canvas"'}><svg>${i === 0 ? defs : ""}
2774
+ <g class="viewport">${viewport3}</g></svg></div>`;
2775
+ const body = p.panes ? `<div id="panes">${p.panes.map((pane, i) => `<section class="pane" aria-label="${esc(pane.title)}"><div class="pane-title">${esc(pane.title)}<span class="pane-key"> \xB7 ${keyHtml(pane.key)}</span></div>${canvas(pane.viewport, i)}</section>`).join("")}</div>` : canvas(p.viewport, 0);
1685
2776
  return `<!doctype html>
1686
2777
  <html lang="en" data-theme="${theme}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1687
2778
  <meta http-equiv="Content-Security-Policy" content="${CSP}">
1688
2779
  <title>${esc(p.title)}</title>
1689
2780
  <style>${CSS}${p.extraCss ?? ""}</style></head>
1690
2781
  <body>
1691
- <header><h1>${esc(p.title)}</h1><span class="meta">${esc(p.meta.repo)} \xB7 ${esc(p.meta.generatedAt.toISOString())}</span>${p.infoButton}<button id="theme-toggle" type="button" title="Cycle theme: auto, light, dark"></button></header>
2782
+ <header><h1>${esc(p.title)}</h1>${p.headerNote ?? ""}<span class="meta">${esc(p.meta.repo)} \xB7 ${esc(p.meta.generatedAt.toISOString())}</span>${p.infoButton}<button id="theme-toggle" type="button" title="Cycle theme: auto, light, dark"></button></header>
1692
2783
  <main>
1693
- <div id="canvas"><svg><defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>${p.extraDefs ?? ""}</defs>
1694
- <g id="viewport">${p.viewport}</g></svg></div>
2784
+ ${body}
2785
+ <div id="resize" role="separator" aria-orientation="vertical" aria-label="Resize panel" tabindex="0" title="Drag to resize the panel"></div>
1695
2786
  <aside>${p.aside}</aside>
1696
2787
  </main>
1697
2788
  <script type="application/json" id="spec-data">${jsonForScript(data)}</script>
@@ -1700,376 +2791,47 @@ function renderPage(p) {
1700
2791
  `;
1701
2792
  }
1702
2793
 
1703
- // src/render/web/html.ts
1704
- var FIELD_CHARS = 34;
1705
- function clip2(s, max) {
1706
- return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
1707
- }
1708
- var FIELD_MARK = { added: "+ ", removed: "- ", modified: "~ " };
1709
- function fieldText(f) {
1710
- return `${f.change ? FIELD_MARK[f.change] : ""}${f.name}${f.type ? ": " + f.type : ""}${f.note ? " (" + f.note + ")" : ""}`;
1711
- }
1712
- function renderEdge(e) {
1713
- if (e.points.length < 2) return "";
1714
- const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
1715
- let out = `<path d="${d}" marker-end="url(#arrow)"/>`;
1716
- if (e.label) {
1717
- const m = midpoint(e.points);
1718
- const w = e.label.length * 5.6 + 6;
1719
- out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - 8)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 1)}">${esc(e.label)}</text>`;
1720
- }
1721
- return `<g class="edge">${out}</g>`;
1722
- }
1723
- function renderNode(n, box) {
1724
- const x = Math.round(box.x * 10) / 10;
1725
- const y = Math.round(box.y * 10) / 10;
1726
- const w = box.w;
1727
- const lines = [];
1728
- let row = 28;
1729
- const text = (cls, s) => {
1730
- lines.push(`<text class="${cls}" x="${x + 8}" y="${y + row + 12}">${esc(s)}</text>`);
1731
- row += 16;
1732
- };
1733
- if (n.summary) for (const l of wrapSummary(n.summary)) text("summary", l);
1734
- for (const f of n.fields ?? []) {
1735
- text(f.change ? `field field-${f.change}` : "field", clip2(fieldText(f), FIELD_CHARS));
1736
- }
1737
- return `<g class="node status-${n.status}" data-id="${esc(n.id)}" tabindex="0" role="button" aria-label="${esc(`${n.label} (${n.status})`)}"><rect class="card" x="${x}" y="${y}" width="${w}" height="${row}" rx="6"/><line class="head" x1="${x}" y1="${y + 28}" x2="${x + w}" y2="${y + 28}"/><text class="label" x="${x + 8}" y="${y + 18}">${esc(clip2(n.label, 22))}</text><text class="badge" x="${x + w - 8}" y="${y + 18}">${esc(n.status)}</text>` + lines.join("") + `</g>`;
1738
- }
1739
- var FIELDS_NOTE = "Only the fields the agent saw are listed. Set <code>defaults.context: full</code> in <code>.codechart.yaml</code> to let it read the full definition.";
1740
- function cardPanel(n) {
1741
- let out = `<h2>${esc(`${n.label} (${n.status} ${n.kind})`)}</h2>`;
1742
- if (n.path) out += `<div class="path">${esc(n.path)}</div>`;
1743
- if (n.summary) out += `<p>${esc(n.summary)}</p>`;
1744
- if (n.fields?.length) {
1745
- out += `<h3>Fields</h3><ul>${n.fields.map((f) => `<li${f.change ? ` class="field-${f.change}-t"` : ""}>${esc(fieldText(f))}</li>`).join("")}</ul>`;
1746
- if (n.fieldsComplete === false) out += `<p class="fields-note">${FIELDS_NOTE}</p>`;
1747
- }
1748
- if (n.notes?.length) out += `<h3>Notes</h3>${list(n.notes)}`;
1749
- return `<template class="card-panel" data-for="${esc(n.id)}">${out}</template>`;
1750
- }
1751
- function pageInfo(spec) {
1752
- let out = "<p>Click a node for details. Scroll to zoom, drag to pan.</p>";
1753
- if (spec.gaps?.length) out += `<h3>Gaps</h3>${list(spec.gaps)}`;
1754
- if (spec.omitted?.length) out += `<h3>Not on map</h3>${list(spec.omitted)}`;
1755
- return `<section id="page-info">${out}</section>`;
1756
- }
1757
- function renderHtml(spec, layout, meta) {
1758
- const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
1759
- const groups = layout.groups.map(
1760
- (g) => `<g class="group"><rect x="${num(g.x)}" y="${num(g.y)}" width="${num(g.w)}" height="${num(g.h)}" rx="8"/><text x="${num(g.x + 10)}" y="${num(g.y + 16)}">${esc(g.layer)}</text></g>`
1761
- ).join("");
1762
- const nodes = spec.nodes.map((n) => {
1763
- const b = boxes.get(n.id);
1764
- return b ? renderNode(n, b) : "";
1765
- }).join("");
1766
- const edges = layout.edges.map(renderEdge).join("");
1767
- const infoButton = spec.gaps?.length || spec.omitted?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what is not on the map and what the agent did not read">Not on map / gaps</button>' : "";
1768
- return renderPage({
1769
- title: spec.title,
1770
- meta,
1771
- infoButton,
1772
- viewport: `${groups}${edges}${nodes}`,
1773
- aside: `${pageInfo(spec)}<div id="panel" hidden></div>${spec.nodes.map(cardPanel).join("")}`,
1774
- width: layout.width,
1775
- height: layout.height
1776
- });
1777
- }
1778
-
1779
- // src/spec/schema.ts
1780
- import { z as z4 } from "zod";
2794
+ // src/render/web/check-html.ts
2795
+ function checkNote(c) {
2796
+ const line = checkHeadline(c);
2797
+ if (!line) return "";
2798
+ return `<span class="check${c.mismatches.length ? " bad" : ""}">${esc(line)}</span>`;
2799
+ }
2800
+ function checkSection(c) {
2801
+ if (!c?.mismatches.length) return "";
2802
+ const items = c.mismatches.map((m) => `<li><b>${esc(m.label)}</b>: ${esc(m.detail)}</li>`).join("");
2803
+ return `<h3>Doesn't match the code</h3><ul>${items}</ul>`;
2804
+ }
2805
+ function mismatchNote(c, id) {
2806
+ const m = c?.mismatches.find((x) => x.id === id);
2807
+ return m ? `<p class="mismatch-note">\u2717 ${esc(m.detail)}</p>` : "";
2808
+ }
2809
+ var isFlagged = (c, id) => c?.mismatches.some((m) => m.id === id) ?? false;
2810
+ var flagMark = (x, y) => `<text class="flag" x="${num(x)}" y="${num(y + 4)}" aria-hidden="true">\u2717</text>`;
1781
2811
 
1782
- // src/spec/flow.ts
1783
- import { z as z3 } from "zod";
1784
- var STEP_TYPES = ["step", "decision", "end"];
1785
- var STEP_STATUSES = ["existing", "new", "changed", "planned"];
1786
- var SOURCE_RE = /^[^\s:\u0000-\u001f\u007f-\u009f]+(:\d+(-\d+)?)?$/;
1787
- var sourceSchema = pathStr().regex(SOURCE_RE, "must be path:line or path:start-end, or a path with match");
1788
- var hasLine = (source) => source.includes(":");
1789
- var ANCHOR = "(path:line, path:start-end, or a path with match)";
1790
- var matchSchema = z3.string().trim().min(1, "must not be blank").max(SHORT).refine((v) => !hasHiddenChars(v.replaceAll(" ", " ")), "must be one line without control or invisible characters (tabs are fine); quote a single line").describe("Text on the anchored line (plain substring, not a regex); source is then the path only");
1791
- var stepSchema = z3.strictObject({
1792
- id: ident(),
1793
- label: short(),
1794
- type: z3.enum(STEP_TYPES).optional().describe("Inferred when left out: 0 outgoing links end, 1 step, 2 or more decision"),
1795
- status: z3.enum(STEP_STATUSES),
1796
- source: sourceSchema.optional(),
1797
- match: matchSchema.optional()
1798
- });
1799
- var linkSchema = z3.strictObject({
1800
- from: ident(),
1801
- to: ident(),
1802
- label: short().optional(),
1803
- source: sourceSchema.optional(),
1804
- match: matchSchema.optional(),
1805
- planned: z3.boolean().optional()
1806
- });
1807
- var MAX_ITEMS = 200;
1808
- function anchorIssues(a) {
1809
- if (a.match !== void 0 && !a.source) return [["match", "needs source set to the file path"]];
1810
- if (!a.source || !SOURCE_RE.test(a.source)) return [];
1811
- if (a.match !== void 0 && hasLine(a.source)) return [["source", "with match, give only the path (no :line)"]];
1812
- if (a.match === void 0 && !hasLine(a.source)) return [["source", "needs a line (path:line or path:start-end) or a match"]];
1813
- return [];
1814
- }
1815
- function isPlannedLink(spec, link) {
1816
- const planned = (id) => spec.steps.some((s) => s.id === id && s.status === "planned");
1817
- return link.planned === true || planned(link.from) || planned(link.to);
1818
- }
1819
- var inferType = (outgoing) => outgoing === 0 ? "end" : outgoing >= 2 ? "decision" : "step";
1820
- function outgoingCounts(links) {
1821
- const counts = /* @__PURE__ */ new Map();
1822
- for (const l of links) counts.set(l.from, (counts.get(l.from) ?? 0) + 1);
1823
- return counts;
1824
- }
1825
- var flowSchema = z3.strictObject({
1826
- diagram: z3.literal("flow").optional().describe("Optional: a spec with steps is a flow"),
1827
- kind: z3.enum(["plan", "summary"]),
1828
- title: short(),
1829
- rules: z3.array(shortOpt()).optional(),
1830
- start: ident(),
1831
- steps: z3.array(stepSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} steps; split the flow`),
1832
- links: z3.array(linkSchema).max(MAX_ITEMS, `at most ${MAX_ITEMS} links; split the flow`),
1833
- gaps: z3.array(long()).optional()
1834
- }).superRefine((spec, ctx) => {
1835
- const issue = (path3, message) => ctx.addIssue({ code: "custom", path: path3, message });
1836
- const counts = outgoingCounts(spec.links);
1837
- const typeOf = (step) => step.type ?? inferType(counts.get(step.id) ?? 0);
1838
- const byId = /* @__PURE__ */ new Map();
1839
- spec.steps.forEach((step, i) => {
1840
- if (byId.has(step.id)) issue(["steps", i, "id"], `duplicate "${step.id}"`);
1841
- byId.set(step.id, step);
1842
- for (const m of labelIssues(step.label, "step", "source", "migration: add invoices")) {
1843
- issue(["steps", i, "label"], m);
1844
- }
1845
- if (spec.kind === "summary" && step.status === "planned") {
1846
- issue(["steps", i, "status"], 'a summary describes code that exists; "planned" is for plans');
1847
- }
1848
- if (spec.kind === "plan" && step.status !== "existing" && step.status !== "planned") {
1849
- issue(["steps", i, "status"], `a plan uses only "existing" or "planned" steps, not "${step.status}"`);
1850
- }
1851
- if (step.status !== "planned" && !step.source) {
1852
- issue(["steps", i, "source"], `required for a non-planned step ${ANCHOR}`);
1853
- }
1854
- for (const [field, m] of anchorIssues(step)) issue(["steps", i, field], m);
1855
- });
1856
- let refsOk = byId.has(spec.start);
1857
- if (!refsOk) issue(["start"], `unknown step "${spec.start}"`);
1858
- const outgoing = /* @__PURE__ */ new Map();
1859
- spec.links.forEach((link, i) => {
1860
- for (const end of ["from", "to"]) {
1861
- if (byId.has(link[end])) continue;
1862
- refsOk = false;
1863
- issue(["links", i, end], `unknown step "${link[end]}"`);
1864
- }
1865
- const list2 = outgoing.get(link.from) ?? [];
1866
- list2.push(i);
1867
- outgoing.set(link.from, list2);
1868
- if (spec.kind === "summary" && link.planned) {
1869
- issue(["links", i, "planned"], 'a summary describes code that exists; "planned" is for plans');
1870
- }
1871
- const from = byId.get(link.from);
1872
- const leavesDecision = from !== void 0 && typeOf(from) === "decision";
1873
- if (leavesDecision && !isPlannedLink(spec, link) && !link.source) {
1874
- issue(["links", i, "source"], `required for a non-planned branch leaving a decision ${ANCHOR}`);
1875
- }
1876
- for (const [field, m] of anchorIssues(link)) issue(["links", i, field], m);
1877
- });
1878
- spec.steps.forEach((step, i) => {
1879
- const links = outgoing.get(step.id) ?? [];
1880
- if (step.type === void 0 && step.label.trim().endsWith("?") && links.length < 2) {
1881
- issue(["steps", i, "type"], `label ends in "?", so this is a decision: it needs at least 2 outgoing links, has ${links.length}`);
1882
- return;
1883
- }
1884
- const type = typeOf(step);
1885
- if (type === "end" && links.length > 0) {
1886
- issue(["steps", i, "type"], `an end has no outgoing links, has ${links.length}`);
1887
- }
1888
- if (type === "step" && links.length > 1) {
1889
- issue(["steps", i, "type"], `has ${links.length} outgoing links; make it a decision with labelled branches`);
1890
- }
1891
- if (type !== "decision") return;
1892
- if (links.length < 2) {
1893
- issue(["steps", i, "id"], `decision "${step.id}" needs at least 2 outgoing links, has ${links.length}`);
1894
- }
1895
- for (const li of links) {
1896
- if (!spec.links[li].label) issue(["links", li, "label"], "required on a link leaving a decision");
1897
- }
1898
- });
1899
- if (refsOk) {
1900
- const reached = /* @__PURE__ */ new Set([spec.start]);
1901
- for (const id of reached) {
1902
- for (const li of outgoing.get(id) ?? []) reached.add(spec.links[li].to);
1903
- }
1904
- spec.steps.forEach((step, i) => {
1905
- if (!reached.has(step.id)) issue(["steps", i], "not reachable from start");
1906
- });
1907
- }
1908
- });
1909
- function validateFlowSpec(input) {
1910
- const result = flowSchema.safeParse(input);
1911
- if (!result.success) return { ok: false, errors: formatIssues(result.error) };
1912
- const counts = outgoingCounts(result.data.links);
1913
- const steps = result.data.steps.map((s) => ({ ...s, type: s.type ?? inferType(counts.get(s.id) ?? 0) }));
1914
- return { ok: true, spec: { ...result.data, diagram: "flow", steps } };
1915
- }
1916
- function flowJsonSchema() {
1917
- return z3.toJSONSchema(flowSchema, { io: "input" });
1918
- }
1919
-
1920
- // src/spec/schema.ts
1921
- var STATUSES = ["new", "changed", "removed", "context", "config"];
1922
- var NODE_KINDS = [
1923
- "table",
1924
- "enum",
1925
- "model",
1926
- "service",
1927
- "endpoint",
1928
- "component",
1929
- "file",
1930
- "config",
1931
- "other"
1932
- ];
1933
- var EDGE_KINDS = [
1934
- "fk",
1935
- "calls",
1936
- "imports",
1937
- "reads",
1938
- "writes",
1939
- "renders",
1940
- "configures",
1941
- "other"
1942
- ];
1943
- var fieldSchema = z4.strictObject({
1944
- name: short(),
1945
- type: shortOpt().optional(),
1946
- note: long().optional(),
1947
- change: z4.enum(["added", "removed", "modified"]).optional()
1948
- });
1949
- var nodeSchema = z4.strictObject({
1950
- id: ident(),
1951
- label: short(),
1952
- kind: z4.enum(NODE_KINDS).optional().describe("Defaults to file when path is set"),
1953
- status: z4.enum(STATUSES),
1954
- layer: short(),
1955
- summary: long().optional(),
1956
- path: pathStr().optional(),
1957
- fields: z4.array(fieldSchema).optional(),
1958
- fieldsComplete: z4.boolean().optional().describe("Required when fields is non-empty: true if every field is listed, false if only the fields you saw"),
1959
- notes: z4.array(long()).optional()
1960
- });
1961
- var edgeSchema = z4.strictObject({
1962
- from: ident(),
1963
- to: ident(),
1964
- label: shortOpt().optional(),
1965
- kind: z4.enum(EDGE_KINDS).optional()
1966
- });
1967
- var MAX_NODES = 500;
1968
- var MAX_EDGES = 1e3;
1969
- var specSchema = z4.strictObject({
1970
- diagram: z4.literal("map").optional(),
1971
- title: short(),
1972
- kind: z4.enum(["plan", "summary"]),
1973
- rules: z4.array(shortOpt()).optional(),
1974
- nodes: z4.array(nodeSchema).max(MAX_NODES, `at most ${MAX_NODES} nodes; split the map`),
1975
- edges: z4.array(edgeSchema).max(MAX_EDGES, `at most ${MAX_EDGES} edges; split the map`),
1976
- gaps: z4.array(long()).optional(),
1977
- omitted: z4.array(long()).optional()
1978
- }).superRefine((spec, ctx) => {
1979
- const ids = /* @__PURE__ */ new Set();
1980
- spec.nodes.forEach((node, i) => {
1981
- if (ids.has(node.id)) {
1982
- ctx.addIssue({
1983
- code: "custom",
1984
- path: ["nodes", i, "id"],
1985
- message: `duplicate "${node.id}"`
1986
- });
1987
- }
1988
- ids.add(node.id);
1989
- if (node.kind === void 0 && node.path === void 0) {
1990
- ctx.addIssue({ code: "custom", path: ["nodes", i, "kind"], message: 'required unless path is set (then it defaults to "file")' });
1991
- }
1992
- if (node.fields?.length && node.fieldsComplete === void 0) {
1993
- ctx.addIssue({
1994
- code: "custom",
1995
- path: ["nodes", i, "fieldsComplete"],
1996
- message: "required when fields are listed (true if you listed every field, false if only what you saw)"
1997
- });
1998
- }
1999
- for (const message of labelIssues(
2000
- node.label,
2001
- "node",
2002
- "path",
2003
- "migration: add invoices"
2004
- )) {
2005
- ctx.addIssue({ code: "custom", path: ["nodes", i, "label"], message });
2006
- }
2007
- });
2008
- spec.edges.forEach((edge, i) => {
2009
- for (const end of ["from", "to"]) {
2010
- if (!ids.has(edge[end])) {
2011
- ctx.addIssue({
2012
- code: "custom",
2013
- path: ["edges", i, end],
2014
- message: `unknown node "${edge[end]}"`
2015
- });
2016
- }
2017
- }
2018
- });
2019
- });
2020
- function isFlow(input) {
2021
- if (typeof input !== "object" || input === null) return false;
2022
- const diagram = input.diagram;
2023
- return diagram === "flow" || diagram === void 0 && Object.hasOwn(input, "steps");
2024
- }
2025
- function validateSpec(input) {
2026
- if (isFlow(input)) return validateFlowSpec(input);
2027
- const result = specSchema.safeParse(input);
2028
- if (!result.success) return { ok: false, errors: formatIssues(result.error) };
2029
- const nodes = result.data.nodes.map((n) => ({ ...n, kind: n.kind ?? "file" }));
2030
- return { ok: true, spec: { ...result.data, nodes } };
2031
- }
2032
- function specJsonSchema() {
2033
- return z4.toJSONSchema(specSchema, { io: "input" });
2034
- }
2035
-
2036
- // src/commands/open.ts
2037
- import { spawn, spawnSync } from "child_process";
2038
- import { win32 as win322 } from "path";
2039
- function openArgv(platform, file, env = process.env) {
2040
- if (platform === "darwin") return ["open", [file]];
2041
- if (platform === "win32") {
2042
- return [win322.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
2043
- }
2044
- return ["xdg-open", [file]];
2045
- }
2046
- function inCodeEditor(env) {
2047
- return Boolean(env.VSCODE_PID) || env.TERM_PROGRAM === "vscode";
2048
- }
2049
- function openInBrowser(file, { platform = process.platform, run = spawnSync, detach = spawn } = {}) {
2050
- const [cmd, args] = openArgv(platform, file);
2051
- try {
2052
- if (platform === "linux") {
2053
- detach(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {
2054
- }).unref();
2055
- return void 0;
2056
- }
2057
- const r = run(cmd, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 1e4, encoding: "utf8" });
2058
- if (r.error?.code === "ETIMEDOUT") return void 0;
2059
- if (r.error) return r.error.message;
2060
- if (r.status === 0) return void 0;
2061
- const why = (r.stderr ?? "").trim().split("\n")[0]?.slice(0, 200);
2062
- return `${cmd} exited with ${r.status ?? r.signal}${why ? `: ${why}` : ""}`;
2063
- } catch (e) {
2064
- return e.message;
2065
- }
2812
+ // src/render/flow/states.ts
2813
+ var isAltered = (step) => step.status === "planned" && step.source !== void 0;
2814
+ function hasFlowNowAfter(spec) {
2815
+ if (spec.kind !== "plan") return false;
2816
+ return spec.steps.some((s) => s.status === "removed" || isAltered(s)) || spec.links.some((l) => l.removed === true);
2817
+ }
2818
+ var stepOn = (side, step) => side === "now" ? step.status !== "planned" || isAltered(step) : step.status !== "removed";
2819
+ function linkOn(side, spec, link, byId) {
2820
+ const ends = [byId.get(link.from), byId.get(link.to)];
2821
+ if (!ends.every((s) => stepOn(side, s))) return false;
2822
+ return side === "now" ? link.planned !== true : !isRemovedLink(spec, link);
2823
+ }
2824
+ function linkTone(side, spec, link) {
2825
+ if (side !== "after" && isRemovedLink(spec, link)) return "removed";
2826
+ if (side === "now") return void 0;
2827
+ return isPlannedLink(spec, link) ? "planned" : void 0;
2066
2828
  }
2067
2829
 
2068
2830
  // src/render/flow/layout.ts
2069
2831
  var LINE_HEIGHT2 = 14;
2070
2832
  var BADGE_HEIGHT = 12;
2071
2833
  var PAD = 8;
2072
- var MAX_LINES = 3;
2834
+ var MAX_LINES2 = 3;
2073
2835
  var CHAR_W = 6;
2074
2836
  var SHAPE = {
2075
2837
  step: { w: 180, chars: 26 },
@@ -2078,7 +2840,7 @@ var SHAPE = {
2078
2840
  };
2079
2841
  function sizeOf(step) {
2080
2842
  const { w, chars } = SHAPE[step.type];
2081
- const lines = wrapText(step.label, chars, MAX_LINES);
2843
+ const lines = wrapText(step.label, chars, MAX_LINES2);
2082
2844
  const badge = step.status === "existing" ? void 0 : step.status;
2083
2845
  const content = lines.length * LINE_HEIGHT2 + (badge ? BADGE_HEIGHT : 0);
2084
2846
  const h = step.type === "decision" ? 2 * content + 2 * PAD : content + 2 * PAD;
@@ -2131,12 +2893,12 @@ async function layoutFlow(spec) {
2131
2893
  });
2132
2894
  const byId = new Map(nodes.map((n) => [n.id, n]));
2133
2895
  const decisions = new Set(spec.steps.filter((s) => s.type === "decision").map((s) => s.id));
2134
- const clip3 = (p, id) => decisions.has(id) ? clipToDiamond(p, byId.get(id)) : p;
2896
+ const clip4 = (p, id) => decisions.has(id) ? clipToDiamond(p, byId.get(id)) : p;
2135
2897
  const laidOut = new Map((root.edges ?? []).map((e) => [e.id, e]));
2136
2898
  const out = spec.links.map((link, i) => {
2137
2899
  const e = laidOut.get(`e${i}`);
2138
2900
  const sec = e?.sections?.[0];
2139
- const points = sec ? [clip3(sec.startPoint, link.from), ...sec.bendPoints ?? [], clip3(sec.endPoint, link.to)] : [];
2901
+ const points = sec ? [clip4(sec.startPoint, link.from), ...sec.bendPoints ?? [], clip4(sec.endPoint, link.to)] : [];
2140
2902
  const lab = e?.labels?.[0];
2141
2903
  return {
2142
2904
  points,
@@ -2155,14 +2917,14 @@ var FLOW_CSS = `
2155
2917
  .node:focus-visible .shape{stroke:var(--edge);stroke-width:3.5}
2156
2918
  .status-new .shape{stroke:var(--new)}
2157
2919
  .status-changed .shape{stroke:var(--chg)}
2920
+ .status-removed .shape{stroke:var(--rem)}
2921
+ aside .tag-removed{color:var(--rem)}aside .removed-note{color:var(--rem);font-style:italic;margin:6px 0}
2158
2922
  .status-planned .shape{stroke:var(--cfg);stroke-dasharray:6 4;fill:var(--bg)}.status-planned .badge{fill:var(--cfg-t)}
2159
2923
  .edge.planned path{stroke:var(--cfg);stroke-dasharray:6 4}#arrow-planned path{fill:var(--cfg)}.edge.planned text{fill:var(--cfg-t)}
2160
2924
  aside .status{color:var(--muted);margin-bottom:4px}
2161
2925
  aside .tag{font-size:10px;text-transform:uppercase;border:1px solid currentColor;border-radius:8px;padding:0 5px}
2162
2926
  aside .tag-new{color:var(--new-t)}aside .tag-changed{color:var(--chg-t)}aside .tag-planned{color:var(--cfg-t);border-style:dashed}
2163
2927
  aside .planned-note{color:var(--cfg-t);font-style:italic;margin:6px 0}
2164
- aside .snippet{font:11px/1.45 ui-monospace,monospace;background:var(--bg);border:1px solid var(--line);border-radius:4px;padding:6px 8px;margin:6px 0;overflow:auto;white-space:pre}
2165
- aside .snippet .ln{display:inline-block;min-width:3ch;margin-right:10px;color:var(--muted);text-align:right;user-select:none}
2166
2928
  aside .more{color:var(--muted);font-size:11px;margin:0}
2167
2929
  aside .branches{padding-left:0;list-style:none}
2168
2930
  aside .branches li{margin:0 0 10px}
@@ -2182,47 +2944,53 @@ function shape(step, b) {
2182
2944
  const rx = step.type === "end" ? b.h / 2 : 4;
2183
2945
  return `<rect class="shape" x="${num(b.x)}" y="${num(b.y)}" width="${num(b.w)}" height="${num(b.h)}" rx="${num(rx)}"/>`;
2184
2946
  }
2185
- function renderStep(step, b) {
2947
+ function renderStep(step, b, flagged, side) {
2186
2948
  const cx = num(b.x + b.w / 2);
2187
2949
  const content = b.lines.length * LINE_HEIGHT2 + (b.badge ? BADGE_HEIGHT : 0);
2188
2950
  let y = b.y + (b.h - content) / 2;
2189
2951
  let text = "";
2952
+ const changing = side === "now" && isAltered(step);
2953
+ const status = changing ? "changed" : step.status;
2190
2954
  if (b.badge) {
2191
- text += `<text class="badge" x="${cx}" y="${num(y + 9)}">${esc(b.badge)}</text>`;
2955
+ text += `<text class="badge" x="${cx}" y="${num(y + 9)}">${esc(changing ? "will change" : b.badge)}</text>`;
2192
2956
  y += BADGE_HEIGHT;
2193
2957
  }
2194
2958
  for (const l of b.lines) {
2195
2959
  text += `<text class="label" x="${cx}" y="${num(y + 11)}">${esc(l)}</text>`;
2196
2960
  y += LINE_HEIGHT2;
2197
2961
  }
2198
- return `<g class="node type-${step.type} status-${step.status}" data-id="${esc(step.id)}" tabindex="0" role="button" aria-label="${esc(`${step.label} (${step.status} ${step.type})`)}">` + shape(step, b) + text + `</g>`;
2962
+ return `<g class="node type-${step.type} status-${status}" data-id="${esc(step.id)}" tabindex="0" role="button" aria-label="${esc(`${step.label} (${step.status} ${step.type}${flagged ? ", doesn't match the code" : ""})`)}">` + shape(step, b) + text + (flagged ? flagMark(b.x + b.w, b.y) : "") + `</g>`;
2199
2963
  }
2200
- function renderLink(link, e, planned) {
2964
+ function renderLink(link, e, tone) {
2201
2965
  if (e.points.length < 2) return "";
2202
2966
  const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
2203
- let out = `<path d="${d}" marker-end="url(#${planned ? "arrow-planned" : "arrow"})"/>`;
2967
+ let out = `<path d="${d}" marker-end="url(#arrow${tone ? `-${tone}` : ""})"/>`;
2204
2968
  if (link.label) {
2205
2969
  const m = e.labelAt ?? midpoint(e.points);
2206
2970
  const w = link.label.length * 5.6 + 6;
2207
2971
  out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - 7)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 2)}">${esc(link.label)}</text>`;
2208
2972
  }
2209
- return `<g class="edge${planned ? " planned" : ""}">${out}</g>`;
2973
+ return `<g class="edge${tone === "planned" ? " planned" : tone === "removed" ? " edge-removed" : ""}">${out}</g>`;
2210
2974
  }
2975
+ var pathHtml = (p) => esc(p).replaceAll("/", "/<wbr>");
2976
+ var codeRow = (n, code, cls) => `<span class="ln">${n ?? ""}</span><span${cls ? ` class="${cls}"` : ""}>${code}</span>`;
2211
2977
  function snippetHtml(s) {
2212
- const code = s.lines.map((l, i) => `<span class="ln">${s.startLine + i}</span>${esc(l)}`).join("\n");
2978
+ const code = s.lines.map((l, i) => codeRow(s.startLine + i, esc(l))).join("\n");
2213
2979
  const end = Number(s.source.match(/-(\d+)$/)?.[1] ?? s.startLine);
2214
2980
  const total = end - s.startLine + 1;
2215
2981
  const more = total > s.lines.length ? `<p class="more">first ${s.lines.length} of ${total} lines</p>` : "";
2216
- return `<div class="path">${esc(s.source)}</div><pre class="snippet"><code>${code}</code></pre>${more}`;
2982
+ return `<div class="path">${pathHtml(s.source)}</div><pre class="snippet"><code>${code}</code></pre>${more}`;
2217
2983
  }
2218
2984
  var tag = (status) => `<span class="tag tag-${esc(status)}">${esc(status)}</span>`;
2219
- function stepPanel(spec, step, snippets, byId) {
2985
+ function stepPanel(spec, step, snippets, byId, check) {
2220
2986
  let out = `<h2>${esc(step.label)}</h2>`;
2221
2987
  out += `<div class="status">${tag(step.status)} ${esc(step.type)}</div>`;
2988
+ out += mismatchNote(check, step.id);
2222
2989
  const snip = snippets.steps.get(step.id);
2223
2990
  if (step.status === "planned") {
2224
2991
  out += `<p class="planned-note">${snip ? "Planned change to the code below." : "Planned: not in the code yet."}</p>`;
2225
2992
  }
2993
+ if (step.status === "removed") out += '<p class="removed-note">Removed by the plan.</p>';
2226
2994
  if (snip) out += snippetHtml(snip);
2227
2995
  else if (step.source) out += `<div class="path">${esc(step.source)}</div>`;
2228
2996
  const next = spec.links.map((l, i) => ({ l, i })).filter(({ l }) => l.from === step.id);
@@ -2230,7 +2998,8 @@ function stepPanel(spec, step, snippets, byId) {
2230
2998
  const items = next.map(({ l, i }) => {
2231
2999
  const target = byId.get(l.to)?.label ?? l.to;
2232
3000
  let li = `${l.label ? `<b>${esc(l.label)}</b> \u2192 ` : "\u2192 "}${esc(target)}`;
2233
- if (isPlannedLink(spec, l)) li += ` ${tag("planned")}`;
3001
+ if (isRemovedLink(spec, l)) li += ` ${tag("removed")}`;
3002
+ else if (isPlannedLink(spec, l)) li += ` ${tag("planned")}`;
2234
3003
  const s = snippets.links[i];
2235
3004
  if (s) li += snippetHtml(s);
2236
3005
  else if (l.source) li += `<div class="path">${esc(l.source)}</div>`;
@@ -2240,241 +3009,358 @@ function stepPanel(spec, step, snippets, byId) {
2240
3009
  }
2241
3010
  return `<template class="card-panel" data-for="${esc(step.id)}">${out}</template>`;
2242
3011
  }
2243
- function pageInfo2(spec, anyPlanned) {
2244
- let out = "<p>Click a step for its status, source and code. Scroll to zoom, drag to pan.</p>";
3012
+ function pageInfo(spec, anyPlanned, sides, check) {
3013
+ let out = `<p>Click a step for its status, source and code. Scroll to zoom, drag to pan${sides ? "; both panes move together" : ""}.</p>`;
3014
+ out += checkSection(check);
2245
3015
  if (anyPlanned) out += '<p class="planned-note">Dashed steps and arrows are planned: not in the code yet.</p>';
3016
+ if (spec.steps.some((s) => s.status === "removed") || spec.links.some((l) => l.removed)) {
3017
+ out += '<p class="removed-note">Red steps and arrows are removed by the plan.</p>';
3018
+ }
2246
3019
  if (spec.gaps?.length) out += `<h3>Gaps</h3>${list(spec.gaps)}`;
2247
3020
  return `<section id="page-info">${out}</section>`;
2248
3021
  }
2249
- function renderFlowHtml(spec, layout, snippets, meta) {
3022
+ var FLOW_KEY_HTML = {
3023
+ now: [
3024
+ { text: "red: removed by the plan", tone: "rem" },
3025
+ { text: "amber: changed by it", tone: "chg" }
3026
+ ],
3027
+ after: [{ text: "dashed: planned", tone: "cfg" }]
3028
+ };
3029
+ function viewport(spec, layout, check, side) {
2250
3030
  const byId = new Map(spec.steps.map((s) => [s.id, s]));
2251
3031
  const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
2252
- const planned = spec.links.map((l) => isPlannedLink(spec, l));
2253
- const edges = spec.links.map((l, i) => layout.edges[i] ? renderLink(l, layout.edges[i], planned[i]) : "").join("");
2254
- const nodes = spec.steps.map((s) => {
3032
+ const edges = spec.links.map((l, i) => {
3033
+ if (!layout.edges[i] || side && !linkOn(side, spec, l, byId)) return "";
3034
+ return renderLink(l, layout.edges[i], linkTone(side, spec, l));
3035
+ }).join("");
3036
+ const nodes = spec.steps.filter((s) => !side || stepOn(side, s)).map((s) => {
2255
3037
  const b = boxes.get(s.id);
2256
- return b ? renderStep(s, b) : "";
3038
+ return b ? renderStep(s, b, isFlagged(check, s.id), side) : "";
2257
3039
  }).join("");
2258
- const anyPlanned = planned.includes(true) || spec.steps.some((s) => s.status === "planned");
2259
- const infoButton = spec.gaps?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what the agent did not check">Gaps</button>' : "";
3040
+ return `${edges}${nodes}`;
3041
+ }
3042
+ function renderFlowHtml(spec, layout, snippets, meta, check) {
3043
+ const byId = new Map(spec.steps.map((s) => [s.id, s]));
3044
+ const sides = hasFlowNowAfter(spec);
3045
+ const anyPlanned = spec.links.some((l) => isPlannedLink(spec, l)) || spec.steps.some((s) => s.status === "planned");
3046
+ const infoButton = check?.mismatches.length ? `<button id="info-toggle" type="button" aria-controls="page-info" title="Show what doesn't match the code and what the agent did not check">Check / gaps</button>` : spec.gaps?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what the agent did not check">Gaps</button>' : "";
2260
3047
  return renderPage({
2261
3048
  title: spec.title,
2262
3049
  meta,
2263
3050
  infoButton,
2264
- viewport: `${edges}${nodes}`,
2265
- aside: `${pageInfo2(spec, anyPlanned)}<div id="panel" hidden></div>${spec.steps.map((s) => stepPanel(spec, s, snippets, byId)).join("")}`,
3051
+ headerNote: checkNote(check),
3052
+ viewport: sides ? "" : viewport(spec, layout, check),
3053
+ ...sides ? { panes: SIDES.map((side) => ({ title: SIDE_TITLE[side], key: FLOW_KEY_HTML[side], viewport: viewport(spec, layout, check, side) })) } : {},
3054
+ aside: `${pageInfo(spec, anyPlanned, sides, check)}<div id="panel" hidden></div>${spec.steps.map((s) => stepPanel(spec, s, snippets, byId, check)).join("")}`,
2266
3055
  width: layout.width,
2267
3056
  height: layout.height,
2268
3057
  extraCss: FLOW_CSS,
2269
- extraDefs: '<marker id="arrow-planned" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>'
3058
+ extraDefs: arrowMarker("arrow-planned") + CHANGE_ARROWS
2270
3059
  });
2271
3060
  }
2272
3061
 
2273
- // src/render/flow/walk.ts
2274
- function walkFlow(spec, budget) {
2275
- const byId = new Map(spec.steps.map((s) => [s.id, s]));
2276
- const out = /* @__PURE__ */ new Map();
2277
- const incoming = /* @__PURE__ */ new Map([[spec.start, 1]]);
2278
- for (const link of spec.links) {
2279
- out.set(link.from, [...out.get(link.from) ?? [], link]);
2280
- incoming.set(link.to, (incoming.get(link.to) ?? 0) + 1);
3062
+ // src/render/web/html.ts
3063
+ var FIELD_CHARS = 34;
3064
+ function clip3(s, max) {
3065
+ return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
3066
+ }
3067
+ var FIELD_MARK = { added: "+ ", removed: "- ", modified: "~ " };
3068
+ function fieldText(f) {
3069
+ const type = f.was !== void 0 ? `${f.was} \u2192 ${f.type ?? "?"}` : f.type;
3070
+ return `${f.change ? FIELD_MARK[f.change] : ""}${f.name}${type ? ": " + type : ""}${f.note ? " (" + f.note + ")" : ""}`;
3071
+ }
3072
+ function renderEdge(e, change) {
3073
+ if (e.points.length < 2) return "";
3074
+ const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
3075
+ let out = `<path d="${d}" marker-end="url(#arrow${change ? `-${change}` : ""})"/>`;
3076
+ if (e.label) {
3077
+ const m = midpoint(e.points);
3078
+ const w = e.label.length * 5.6 + 6;
3079
+ out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - 8)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 1)}">${esc(e.label)}</text>`;
2281
3080
  }
2282
- const shared = new Set([...incoming].filter(([, n]) => n > 1).map(([id]) => id));
2283
- const seen = /* @__PURE__ */ new Set();
2284
- const queue = [];
2285
- let placed = 0;
2286
- let truncated = false;
2287
- const take = (id) => {
2288
- if (placed >= budget) return false;
2289
- placed++;
2290
- seen.add(id);
2291
- return true;
2292
- };
2293
- const cut2 = (id, via) => {
2294
- truncated = true;
2295
- let hidden = 0;
2296
- const stack = [id];
2297
- while (stack.length > 0) {
2298
- const next = stack.pop();
2299
- if (seen.has(next)) continue;
2300
- seen.add(next);
2301
- hidden++;
2302
- stack.push(...(out.get(next) ?? []).map((l) => l.to));
2303
- }
2304
- return { kind: "cut", hidden, via };
2305
- };
2306
- const ref = (step, via) => {
2307
- if (queue.includes(step.id)) return { kind: "ref", step, via };
2308
- if (!take(step.id)) return cut2(step.id, via);
2309
- queue.push(step.id);
2310
- return { kind: "ref", step, via };
2311
- };
2312
- const chain = (first, firstPaid) => {
2313
- const items = [];
2314
- let step = first;
2315
- let via;
2316
- for (let paid = firstPaid; ; paid = false) {
2317
- if (!paid && !take(step.id)) return { items: [...items, cut2(step.id, via)] };
2318
- const links = out.get(step.id) ?? [];
2319
- if (step.type === "decision" || links.length > 1) {
2320
- return { items, branch: { head: step, arms: links.map((link) => ({ link, chain: arm(link.to) })) } };
2321
- }
2322
- items.push({ kind: "step", step, via });
2323
- if (links.length === 0) return { items };
2324
- via = links[0];
2325
- const next = byId.get(via.to);
2326
- if (shared.has(next.id)) return { items: [...items, ref(next, via)] };
2327
- step = next;
2328
- }
2329
- };
2330
- const arm = (to) => {
2331
- const step = byId.get(to);
2332
- return shared.has(to) ? { items: [ref(step)] } : chain(step, false);
3081
+ return `<g class="edge${change ? ` edge-${change}` : ""}">${out}</g>`;
3082
+ }
3083
+ function renderNode(n, box, flagged, fields) {
3084
+ const x = Math.round(box.x * 10) / 10;
3085
+ const y = Math.round(box.y * 10) / 10;
3086
+ const w = box.w;
3087
+ const lines = [];
3088
+ let row = 28;
3089
+ const text = (cls, s) => {
3090
+ lines.push(`<text class="${cls}" x="${x + 8}" y="${y + row + 12}">${esc(s)}</text>`);
3091
+ row += 16;
2333
3092
  };
2334
- const start = byId.get(spec.start);
2335
- let head;
2336
- if (shared.has(start.id)) {
2337
- if (!take(start.id)) return { blocks: [], unreachable: 0, truncated: true };
2338
- queue.push(start.id);
2339
- head = { shared: true, chain: chain(start, true) };
2340
- } else {
2341
- head = { shared: false, chain: chain(start, false) };
3093
+ if (n.summary) for (const l of wrapSummary(n.summary)) text("summary", l);
3094
+ for (const f of fields) {
3095
+ text(f.change ? `field field-${f.change}` : "field", clip3(fieldText(f), FIELD_CHARS));
2342
3096
  }
2343
- if (head.chain.items.some((i) => i.kind === "cut")) return { blocks: [], unreachable: 0, truncated: true };
2344
- const blocks = [head];
2345
- for (let i = head.shared ? 1 : 0; i < queue.length; i++) {
2346
- blocks.push({ shared: true, chain: chain(byId.get(queue[i]), true) });
3097
+ const height = Math.max(row, Math.round(box.h * 10) / 10);
3098
+ return `<g class="node status-${n.status}" data-id="${esc(n.id)}" tabindex="0" role="button" aria-label="${esc(`${n.label} (${n.status}${flagged ? ", doesn't match the code" : ""})`)}"><rect class="card" x="${x}" y="${y}" width="${w}" height="${height}" rx="6"/><line class="head" x1="${x}" y1="${y + 28}" x2="${x + w}" y2="${y + 28}"/><text class="label" x="${x + 8}" y="${y + 18}">${esc(clip3(n.label, 22))}</text><text class="badge" x="${x + w - 8}" y="${y + 18}">${esc(n.status)}</text>` + lines.join("") + (flagged ? flagMark(x + w, y) : "") + `</g>`;
3099
+ }
3100
+ var FIELDS_NOTE = "Only the fields the agent saw are listed. Set <code>defaults.context: full</code> in <code>.codechart.yaml</code> to let it read the full definition.";
3101
+ var DIFF_MARK = { add: "+", del: "-", ctx: " " };
3102
+ function previewHtml(p) {
3103
+ let out = "<h3>Changes</h3>";
3104
+ if (p.note) return `${out}<p class="more">${esc(p.note)}</p>`;
3105
+ const rows = p.lines.map(
3106
+ (l) => l.kind === "hunk" ? codeRow(void 0, esc(l.text), "d-hunk") : codeRow(l.n, esc(DIFF_MARK[l.kind] + l.text), `d-${l.kind}`)
3107
+ );
3108
+ out += `<pre class="snippet diff"><code>${rows.join("\n")}</code></pre>`;
3109
+ const count = p.shown < p.total ? `showing ${p.shown} of ${p.total} changed lines` : `${p.total} changed line${p.total === 1 ? "" : "s"}`;
3110
+ return `${out}<p class="more">${count} \xB7 whole file: <span class="path">${pathHtml(p.path)}</span></p>`;
3111
+ }
3112
+ var fieldList = (fields) => `<ul>${fields.map((f) => `<li${f.change ? ` class="field-${f.change}-t"` : ""}>${esc(fieldText(f))}</li>`).join("")}</ul>`;
3113
+ function fieldsHtml(n, sides) {
3114
+ if (!sides || !nodeOn("now", n.status) || !nodeOn("after", n.status)) return `<h3>Fields</h3>${fieldList(n.fields)}`;
3115
+ const now = fieldsOn("now", n);
3116
+ const after = fieldsOn("after", n);
3117
+ if (JSON.stringify(now) === JSON.stringify(after)) return `<h3>Fields</h3>${fieldList(after)}`;
3118
+ return `<h3>Fields now</h3>${fieldList(now)}<h3>Fields after</h3>${fieldList(after)}`;
3119
+ }
3120
+ function cardPanel(n, check, previews, sides) {
3121
+ let out = `<h2>${esc(`${n.label} (${n.status} ${n.kind})`)}</h2>`;
3122
+ out += mismatchNote(check, n.id);
3123
+ const match = check?.matches.get(n.id);
3124
+ if (match) out += snippetHtml(match);
3125
+ else if (n.path) out += `<div class="path">${pathHtml(n.path)}</div>`;
3126
+ if (n.summary) out += `<p>${esc(n.summary)}</p>`;
3127
+ const preview = previews?.get(n.id);
3128
+ if (preview) out += previewHtml(preview);
3129
+ if (n.fields?.length) {
3130
+ out += fieldsHtml(n, sides);
3131
+ if (n.fieldsComplete === false) out += `<p class="fields-note">${FIELDS_NOTE}</p>`;
2347
3132
  }
2348
- const unreachable = spec.steps.filter((s) => !seen.has(s.id)).length;
2349
- return { blocks, unreachable, truncated: truncated || unreachable > 0 };
3133
+ if (n.notes?.length) out += `<h3>Notes</h3>${list(n.notes)}`;
3134
+ return `<template class="card-panel" data-for="${esc(n.id)}">${out}</template>`;
3135
+ }
3136
+ function pageInfo2(spec, check, sides) {
3137
+ let out = `<p>Click a node for details. Scroll to zoom, drag to pan${sides ? "; both panes move together" : ""}.</p>`;
3138
+ out += checkSection(check);
3139
+ if (spec.gaps?.length) out += `<h3>Gaps</h3>${list(spec.gaps)}`;
3140
+ if (spec.omitted?.length) out += `<h3>Not on map</h3>${list(spec.omitted)}`;
3141
+ return `<section id="page-info">${out}</section>`;
3142
+ }
3143
+ function viewport2(spec, layout, check, side) {
3144
+ const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
3145
+ const statusOf = new Map(spec.nodes.map((n) => [n.id, n.status]));
3146
+ const shown2 = spec.nodes.filter((n) => !side || nodeOn(side, n.status));
3147
+ const layers = new Set(shown2.map((n) => n.layer));
3148
+ const present2 = new Set(shown2.map((n) => n.id));
3149
+ const groups = layout.groups.filter((g) => layers.has(g.layer)).map(
3150
+ (g) => `<g class="group"><rect x="${num(g.x)}" y="${num(g.y)}" width="${num(g.w)}" height="${num(g.h)}" rx="8"/><text x="${num(g.x + 10)}" y="${num(g.y + 16)}">${esc(g.layer)}</text></g>`
3151
+ ).join("");
3152
+ const nodes = shown2.map((n) => {
3153
+ const b = boxes.get(n.id);
3154
+ return b ? renderNode(n, b, isFlagged(check, n.id), side ? fieldsOn(side, n) : n.fields ?? []) : "";
3155
+ }).join("");
3156
+ const edges = layout.edges.map((e) => {
3157
+ const edge = spec.edges[e.index];
3158
+ const change = side ? edgeChange(edge, statusOf) : edge.change;
3159
+ const drawn = !side || edgeOn(side, change) && present2.has(edge.from) && present2.has(edge.to);
3160
+ return drawn ? renderEdge(e, change) : "";
3161
+ }).join("");
3162
+ return `${groups}${edges}${nodes}`;
3163
+ }
3164
+ function renderHtml(spec, layout, meta, check, previews) {
3165
+ const sides = hasNowAfter(spec);
3166
+ const infoButton = check?.mismatches.length ? `<button id="info-toggle" type="button" aria-controls="page-info" title="Show what doesn't match the code, what is not on the map and what the agent did not read">Check / gaps</button>` : spec.gaps?.length || spec.omitted?.length ? '<button id="info-toggle" type="button" aria-controls="page-info" title="Show what is not on the map and what the agent did not read">Not on map / gaps</button>' : "";
3167
+ return renderPage({
3168
+ title: spec.title,
3169
+ meta,
3170
+ infoButton,
3171
+ headerNote: checkNote(check),
3172
+ viewport: sides ? "" : viewport2(spec, layout, check),
3173
+ ...sides ? { panes: SIDES.map((side) => ({ title: SIDE_TITLE[side], key: SIDE_KEY[side], viewport: viewport2(spec, layout, check, side) })) } : {},
3174
+ extraDefs: CHANGE_ARROWS,
3175
+ aside: `${pageInfo2(spec, check, sides)}<div id="panel" hidden></div>${spec.nodes.map((n) => cardPanel(n, check, previews, sides)).join("")}`,
3176
+ width: layout.width,
3177
+ height: layout.height
3178
+ });
2350
3179
  }
2351
3180
 
2352
- // src/render/flow/tree.ts
2353
- var FLOW_KEY = "key: + new ~ changed ? planned \u25C7 decision \u2937 shared step";
2354
- var MARKER3 = { existing: "", new: "+", changed: "~", planned: "?" };
2355
- var SGR2 = { existing: void 0, new: "32", changed: "33", planned: "35" };
2356
- var painter = (status, ctx) => ctx.color && SGR2[status] ? (text) => text ? `\x1B[${SGR2[status]}m${text}\x1B[0m` : text : void 0;
2357
- var stepSegment = (step, ctx) => ({
2358
- text: MARKER3[step.status] + flat(step.label),
2359
- paint: painter(step.status, ctx)
3181
+ // src/spec/schema.ts
3182
+ import { z as z4 } from "zod";
3183
+ var STATUSES = ["new", "changed", "removed", "context", "config"];
3184
+ var NODE_KINDS = [
3185
+ "table",
3186
+ "enum",
3187
+ "model",
3188
+ "service",
3189
+ "endpoint",
3190
+ "component",
3191
+ "file",
3192
+ "config",
3193
+ "other"
3194
+ ];
3195
+ var EDGE_KINDS = [
3196
+ "fk",
3197
+ "calls",
3198
+ "imports",
3199
+ "reads",
3200
+ "writes",
3201
+ "renders",
3202
+ "configures",
3203
+ "other"
3204
+ ];
3205
+ var fieldSchema = z4.strictObject({
3206
+ name: short(),
3207
+ type: shortOpt().optional(),
3208
+ note: long().optional(),
3209
+ change: z4.enum(["added", "removed", "modified"]).optional(),
3210
+ was: shortOpt().optional().describe("The type before the change; only with change modified")
2360
3211
  });
2361
- var cutText = (hidden, ctx) => hidden > 0 ? `\u2026 (+${hidden} steps ${ctx.htmlPath ? "in web view" : "not shown"})` : "\u2026";
2362
- function itemSegments(item2, ctx) {
2363
- if (item2.kind === "cut") return [{ text: cutText(item2.hidden, ctx) }];
2364
- const label = stepSegment(item2.step, ctx);
2365
- return item2.kind === "ref" ? [{ text: "\u2937 " }, label] : [label];
2366
- }
2367
- var segWidth = (segments) => columns(segments.map((s) => s.text).join(""));
2368
- var markedLink = (link, ctx) => link.planned === true && !endsPlanned(ctx.spec, link);
2369
- var endsPlanned = (spec, link) => spec.steps.some((s) => s.status === "planned" && (s.id === link.from || s.id === link.to));
2370
- function runLines(items, first, rest, ctx) {
2371
- const lines = [];
2372
- let line = first;
2373
- items.forEach((item2, i) => {
2374
- const segs = itemSegments(item2, ctx);
2375
- const mark = item2.via && markedLink(item2.via, ctx) ? "?" : "";
2376
- const arrow = { text: `${mark}\u2192 `, paint: mark ? painter("planned", ctx) : void 0 };
2377
- if (i === 0) {
2378
- line = [...line, ...segs];
2379
- } else if (segWidth(line) + segWidth(segs) + 2 + columns(arrow.text) <= ctx.width) {
2380
- line = [...line, { text: " " }, arrow, ...segs];
2381
- } else {
2382
- lines.push(line);
2383
- line = [{ text: `${rest} ` }, arrow, ...segs];
3212
+ var nodeSchema = z4.strictObject({
3213
+ id: ident(),
3214
+ label: short(),
3215
+ kind: z4.enum(NODE_KINDS).optional().describe("Defaults to file when path is set"),
3216
+ status: z4.enum(STATUSES),
3217
+ layer: short(),
3218
+ summary: long().optional(),
3219
+ path: pathStr().optional(),
3220
+ match: matchSchema.describe("Text on exactly one line of path (plain substring, not a regex), checked at render").optional(),
3221
+ fields: z4.array(fieldSchema).optional(),
3222
+ fieldsComplete: z4.boolean().optional().describe("Required when fields is non-empty: true if every field is listed, false if only the fields you saw"),
3223
+ notes: z4.array(long()).optional()
3224
+ });
3225
+ var edgeSchema = z4.strictObject({
3226
+ from: ident(),
3227
+ to: ident(),
3228
+ label: shortOpt().optional(),
3229
+ kind: z4.enum(EDGE_KINDS).optional(),
3230
+ change: z4.enum(["added", "removed"]).optional().describe("Plan only: a link the plan adds or drops between nodes that exist before and after")
3231
+ });
3232
+ var MAX_NODES = 500;
3233
+ var MAX_EDGES = 1e3;
3234
+ var specSchema = z4.strictObject({
3235
+ diagram: z4.literal("map").optional(),
3236
+ title: short(),
3237
+ kind: z4.enum(["plan", "summary"]),
3238
+ rules: z4.array(shortOpt()).optional(),
3239
+ nodes: z4.array(nodeSchema).max(MAX_NODES, `at most ${MAX_NODES} nodes; split the map`),
3240
+ edges: z4.array(edgeSchema).max(MAX_EDGES, `at most ${MAX_EDGES} edges; split the map`),
3241
+ gaps: z4.array(long()).optional(),
3242
+ omitted: z4.array(long()).optional()
3243
+ }).superRefine((spec, ctx) => {
3244
+ const ids = /* @__PURE__ */ new Set();
3245
+ spec.nodes.forEach((node, i) => {
3246
+ if (ids.has(node.id)) {
3247
+ ctx.addIssue({
3248
+ code: "custom",
3249
+ path: ["nodes", i, "id"],
3250
+ message: `duplicate "${node.id}"`
3251
+ });
3252
+ }
3253
+ ids.add(node.id);
3254
+ if (node.kind === void 0 && node.path === void 0) {
3255
+ ctx.addIssue({ code: "custom", path: ["nodes", i, "kind"], message: 'required unless path is set (then it defaults to "file")' });
3256
+ }
3257
+ if (node.match !== void 0 && node.path === void 0) {
3258
+ ctx.addIssue({ code: "custom", path: ["nodes", i, "match"], message: "needs path set to the file the line is in" });
3259
+ }
3260
+ if (node.fields?.length && node.fieldsComplete === void 0) {
3261
+ ctx.addIssue({
3262
+ code: "custom",
3263
+ path: ["nodes", i, "fieldsComplete"],
3264
+ message: "required when fields are listed (true if you listed every field, false if only what you saw)"
3265
+ });
3266
+ }
3267
+ node.fields?.forEach((f, j) => {
3268
+ if (f.was !== void 0 && f.change !== "modified") {
3269
+ ctx.addIssue({ code: "custom", path: ["nodes", i, "fields", j, "was"], message: 'only with "change": "modified"' });
3270
+ }
3271
+ });
3272
+ for (const message of labelIssues(
3273
+ node.label,
3274
+ "node",
3275
+ "path",
3276
+ "migration: add invoices"
3277
+ )) {
3278
+ ctx.addIssue({ code: "custom", path: ["nodes", i, "label"], message });
2384
3279
  }
2385
3280
  });
2386
- lines.push(line);
2387
- return lines.map((l) => fit(l, ctx.width, ctx.cuts));
2388
- }
2389
- function armLines(arms, rest, ctx) {
2390
- const planned = arms.map(({ link }) => isPlannedLink(ctx.spec, link));
2391
- const labels = arms.map(({ link }, i) => (planned[i] ? "?" : "") + flat(link.label ?? ""));
2392
- const pad2 = Math.min(Math.max(...labels.map(columns)), Math.floor(ctx.width / 3));
2393
- return arms.flatMap((arm, i) => {
2394
- const last = i === arms.length - 1;
2395
- const glyph = last ? "\u2514\u2500 " : "\u251C\u2500 ";
2396
- const label = truncate(labels[i], pad2, ctx.cuts);
2397
- const head = [{ text: rest + glyph }];
2398
- if (pad2 > 0) {
2399
- const paint2 = planned[i] ? painter("planned", ctx) : void 0;
2400
- head.push({ text: label, paint: paint2 }, { text: `${" ".repeat(pad2 - columns(label))} \u2192 ` });
3281
+ const statusOf = new Map(spec.nodes.map((n) => [n.id, n.status]));
3282
+ spec.edges.forEach((edge, i) => {
3283
+ for (const end of ["from", "to"]) {
3284
+ if (!ids.has(edge[end])) {
3285
+ ctx.addIssue({
3286
+ code: "custom",
3287
+ path: ["edges", i, end],
3288
+ message: `unknown node "${edge[end]}"`
3289
+ });
3290
+ }
3291
+ }
3292
+ const ends = [statusOf.get(edge.from), statusOf.get(edge.to)];
3293
+ if (spec.kind === "plan" && ends.includes("new") && ends.includes("removed")) {
3294
+ ctx.addIssue({ code: "custom", path: ["edges", i], message: "joins a new and a removed node, which never exist at the same time" });
3295
+ }
3296
+ if (edge.change === void 0) return;
3297
+ if (spec.kind !== "plan") {
3298
+ ctx.addIssue({ code: "custom", path: ["edges", i, "change"], message: "only in a plan" });
3299
+ return;
3300
+ }
3301
+ if (edge.change === "added" && ends.includes("removed")) {
3302
+ ctx.addIssue({ code: "custom", path: ["edges", i, "change"], message: "an edge to a removed node cannot be added" });
3303
+ }
3304
+ if (edge.change === "removed" && ends.includes("new")) {
3305
+ ctx.addIssue({ code: "custom", path: ["edges", i, "change"], message: "an edge to a new node cannot be removed; leave change out" });
2401
3306
  }
2402
- const under = `${rest}${last ? " " : "\u2502 "}${pad2 > 0 ? " ".repeat(pad2 + 3) : ""}`;
2403
- return chainLines(arm.chain, head, under, "", ctx);
2404
3307
  });
3308
+ });
3309
+ function isFlow(input) {
3310
+ if (typeof input !== "object" || input === null) return false;
3311
+ const diagram = input.diagram;
3312
+ return diagram === "flow" || diagram === void 0 && Object.hasOwn(input, "steps");
2405
3313
  }
2406
- function chainLines(chain, first, rest, lead, ctx) {
2407
- const lines = [];
2408
- let prefix = [...first, { text: lead }];
2409
- if (chain.items.length > 0) {
2410
- lines.push(...runLines(chain.items, prefix, rest, ctx));
2411
- prefix = [{ text: rest }];
2412
- }
2413
- if (chain.branch) {
2414
- const { head, arms } = chain.branch;
2415
- const glyph = head.type === "decision" ? "\u25C7 " : "";
2416
- lines.push(fit([...prefix, { text: glyph }, stepSegment(head, ctx)], ctx.width, ctx.cuts));
2417
- lines.push(...armLines(arms, rest, ctx));
2418
- }
2419
- return lines;
2420
- }
2421
- function footer2(spec, ctx, md) {
2422
- const count = (status) => spec.steps.filter((s) => s.status === status).length;
2423
- const lines = [
2424
- truncate(
2425
- `${spec.steps.length} steps \xB7 ${count("new")} new \xB7 ${count("changed")} changed \xB7 ${count("planned")} planned`,
2426
- ctx.width
2427
- )
2428
- ];
2429
- if (!md) lines.push(truncate(FLOW_KEY, ctx.width));
2430
- if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), ctx.width));
2431
- if (ctx.htmlPath && !md) lines.push(fullMapLine(ctx.htmlPath));
2432
- return lines.join("\n");
3314
+ function validateSpec(input) {
3315
+ if (isFlow(input)) return validateFlowSpec(input);
3316
+ const result = specSchema.safeParse(input);
3317
+ if (!result.success) return { ok: false, errors: formatIssues(result.error) };
3318
+ const nodes = result.data.nodes.map((n) => ({ ...n, kind: n.kind ?? "file" }));
3319
+ return { ok: true, spec: { ...result.data, nodes } };
2433
3320
  }
2434
- function flowMarkdown(title, tree, htmlPath, width, cuts) {
2435
- const heading = truncate(flat(title), Math.max(width, MIN_WIDTH), cuts);
2436
- const titled = `${heading}
2437
- ${"\u2500".repeat(columns(heading))}`;
2438
- return markdownBlock(`**Flow** _(${FLOW_KEY})_`, tree === void 0 ? titled : `${titled}
2439
- ${tree}`, htmlPath);
3321
+ function specJsonSchema() {
3322
+ return z4.toJSONSchema(specSchema, { io: "input" });
2440
3323
  }
2441
- var TOO_LARGE = "flow too large for the terminal; use --output both or web";
2442
- function renderFlowTree(spec, opts) {
2443
- const ctx = {
2444
- width: Math.max(opts.width ?? defaultWidth(), MIN_WIDTH),
2445
- color: opts.color && !opts.md,
2446
- cuts: { truncated: false },
2447
- htmlPath: opts.htmlPath,
2448
- spec
2449
- };
2450
- const walk = walkFlow(spec, opts.maxNodes);
2451
- const md = opts.md ?? false;
2452
- if (walk.blocks.length === 0) {
2453
- if (!opts.htmlPath) return { text: md ? flowMarkdown(spec.title, TOO_LARGE, void 0, ctx.width) : `${TOO_LARGE}
2454
- `, truncated: true };
2455
- return { text: md ? flowMarkdown(spec.title, void 0, opts.htmlPath, ctx.width) : `${fullMapLine(opts.htmlPath)}
2456
- `, truncated: true };
3324
+
3325
+ // src/commands/open.ts
3326
+ import { spawn, spawnSync } from "child_process";
3327
+ import { win32 as win322 } from "path";
3328
+ function openArgv(platform, file, env = process.env) {
3329
+ if (platform === "darwin") return ["open", [file]];
3330
+ if (platform === "win32") {
3331
+ return [win322.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
2457
3332
  }
2458
- const blocks = walk.blocks.map((b) => chainLines(b.chain, [], "", b.shared ? "\u2937 " : "", ctx).join("\n"));
2459
- if (spec.kind === "plan" && (spec.steps.some((s) => s.status === "planned") || spec.links.some((l) => isPlannedLink(spec, l)))) {
2460
- blocks[0] = `${truncate("planned flow", ctx.width)}
2461
- ${blocks[0]}`;
3333
+ return ["xdg-open", [file]];
3334
+ }
3335
+ function inCodeEditor(env) {
3336
+ return Boolean(env.VSCODE_PID) || env.TERM_PROGRAM === "vscode";
3337
+ }
3338
+ function openInBrowser(file, { platform = process.platform, run = spawnSync, detach = spawn } = {}) {
3339
+ const [cmd, args] = openArgv(platform, file);
3340
+ try {
3341
+ if (platform === "linux") {
3342
+ detach(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {
3343
+ }).unref();
3344
+ return void 0;
3345
+ }
3346
+ const r = run(cmd, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 1e4, encoding: "utf8" });
3347
+ if (r.error?.code === "ETIMEDOUT") return void 0;
3348
+ if (r.error) return r.error.message;
3349
+ if (r.status === 0) return void 0;
3350
+ const why = (r.stderr ?? "").trim().split("\n")[0]?.slice(0, 200);
3351
+ return `${cmd} exited with ${r.status ?? r.signal}${why ? `: ${why}` : ""}`;
3352
+ } catch (e) {
3353
+ return e.message;
2462
3354
  }
2463
- if (walk.unreachable > 0) blocks[blocks.length - 1] += `
2464
- ${truncate(cutText(walk.unreachable, ctx), ctx.width, ctx.cuts)}`;
2465
- const tree = [...blocks, footer2(spec, ctx, md)].join("\n\n");
2466
- const text = md ? flowMarkdown(spec.title, tree, opts.htmlPath, ctx.width, ctx.cuts) : `${tree}
2467
- `;
2468
- return { text, truncated: walk.truncated || ctx.cuts.truncated };
2469
3355
  }
2470
3356
 
2471
3357
  // src/commands/render-flow.ts
2472
3358
  async function renderFlow(spec, snippets, ctx) {
2473
3359
  const { output } = ctx;
2474
- const writeHtml = () => ctx.writeHtml(async (meta) => renderFlowHtml(spec, await layoutFlow(spec), snippets, meta));
3360
+ const writeHtml = () => ctx.writeHtml(async (meta) => renderFlowHtml(spec, await layoutFlow(spec), snippets, meta, ctx.tree.check));
2475
3361
  let htmlPath;
2476
3362
  let tree;
2477
- if (output === "web" || output === "both" || output === "auto" && spec.steps.length >= ctx.minNodes) {
3363
+ if (output === "web" || output === "both" || output === "auto" && (spec.steps.length >= ctx.minNodes || hasFlowNowAfter(spec))) {
2478
3364
  htmlPath = await writeHtml();
2479
3365
  } else if (output === "auto") {
2480
3366
  tree = renderFlowTree(spec, ctx.tree);
@@ -2483,8 +3369,14 @@ async function renderFlow(spec, snippets, ctx) {
2483
3369
  tree = void 0;
2484
3370
  }
2485
3371
  }
2486
- if (output === "web") return ctx.tree.md ? flowMarkdown(spec.title, void 0, htmlPath, ctx.tree.width ?? defaultWidth()) : `${fullMapLine(htmlPath)}
3372
+ if (output === "web") {
3373
+ const width = ctx.tree.width ?? defaultWidth();
3374
+ const alert = alertLine(ctx.tree.check, width);
3375
+ if (ctx.tree.md) return flowMarkdown(spec.title, alert || void 0, htmlPath, width, void 0, flowKey(spec));
3376
+ return `${alert ? `${alert}
3377
+ ` : ""}${fullMapLine(htmlPath)}
2487
3378
  `;
3379
+ }
2488
3380
  return (tree ?? renderFlowTree(spec, { ...ctx.tree, htmlPath })).text;
2489
3381
  }
2490
3382
 
@@ -2497,7 +3389,7 @@ var InvalidSpec = class extends Error {
2497
3389
  errors;
2498
3390
  };
2499
3391
  var TOO_BIG = "spec is larger than 2 MB";
2500
- async function readStdin() {
3392
+ async function readStdin2() {
2501
3393
  const chunks = [];
2502
3394
  let size = 0;
2503
3395
  for await (const chunk of process.stdin) {
@@ -2508,16 +3400,16 @@ async function readStdin() {
2508
3400
  return Buffer.concat(chunks).toString("utf8");
2509
3401
  }
2510
3402
  function readSpecFile(file) {
2511
- const fd = openSync(file, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0));
3403
+ const fd = openSync3(file, constants3.O_RDONLY | (constants3.O_NONBLOCK ?? 0));
2512
3404
  try {
2513
- if (!fstatSync(fd).isFile()) throw new Error("not a regular file");
3405
+ if (!fstatSync3(fd).isFile()) throw new Error("not a regular file");
2514
3406
  const buf = Buffer.alloc(MAX_SPEC_BYTES + 1);
2515
3407
  let n = 0;
2516
- for (let r = 1; r > 0 && n < buf.length; n += r) r = readSync(fd, buf, n, buf.length - n, null);
3408
+ for (let r = 1; r > 0 && n < buf.length; n += r) r = readSync3(fd, buf, n, buf.length - n, null);
2517
3409
  if (n > MAX_SPEC_BYTES) throw new Error(TOO_BIG);
2518
3410
  return buf.toString("utf8", 0, n);
2519
3411
  } finally {
2520
- closeSync(fd);
3412
+ closeSync3(fd);
2521
3413
  }
2522
3414
  }
2523
3415
  function specOutput(config, ruleNames, diagram) {
@@ -2530,7 +3422,7 @@ function specOutput(config, ruleNames, diagram) {
2530
3422
  return unionOutputs(outputs);
2531
3423
  }
2532
3424
  async function readSpec(arg, cwd, stdin) {
2533
- const source = arg === "-" ? "stdin" : resolve6(cwd, arg);
3425
+ const source = arg === "-" ? "stdin" : resolve8(cwd, arg);
2534
3426
  let raw;
2535
3427
  try {
2536
3428
  const text = arg === "-" ? await stdin() : readSpecFile(source);
@@ -2543,28 +3435,41 @@ async function readSpec(arg, cwd, stdin) {
2543
3435
  if (!result.ok) throw new InvalidSpec(result.errors);
2544
3436
  return result.spec;
2545
3437
  }
2546
- function flowSnippets(spec, root, at, cwd) {
3438
+ function flowAnchors(spec, root, at, cwd) {
2547
3439
  const anchors = checkFlowAnchors(spec, root, at, cwd);
2548
3440
  if (!anchors.ok) throw new InvalidSpec(anchors.errors);
2549
- return anchors.snippets;
3441
+ return anchors;
3442
+ }
3443
+ function renderSelectionError(o) {
3444
+ if (!hasGitSelection(o)) return void 0;
3445
+ if (o.head !== void 0 && o.since === void 0) return "--head needs --since";
3446
+ if (o.commit !== void 0 && (o.git || o.since !== void 0)) return "--commit does not combine with --git or --since";
3447
+ return selectionError(o);
2550
3448
  }
2551
- function markdown(map, htmlPath) {
3449
+ function markdown(map, htmlPath, alert) {
2552
3450
  const body = map !== void 0 && htmlPath ? map.split("\n").filter((l) => l !== fullMapLine(htmlPath)).join("\n") : map;
2553
- return markdownBlock(`**Map** _(${KEY})_`, body, htmlPath);
3451
+ return markdownBlock(`**Map** _(${KEY})_`, body ?? (alert || void 0), htmlPath);
2554
3452
  }
2555
3453
  function renderCommand(opts) {
2556
3454
  const cwd = opts.cwd ?? process.cwd();
2557
- return new Command5("render").description("render a spec as a terminal map and/or a self-contained HTML map").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option("--theme <theme>", "HTML theme").choices(THEMES)).option("--open", "open the HTML file in the browser").option("--md", "print a paste-ready markdown block (no color)").option("--at <rev>", "check flow anchors against the files at this commit instead of the working tree").action(async (arg, o) => {
3455
+ return new Command6("render").description("render a spec as a terminal map and/or a self-contained HTML map").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option("--theme <theme>", "HTML theme").choices(THEMES)).option("--open", "open the HTML file in the browser").option("--md", "print a paste-ready markdown block (no color)").option("--at <rev>", "check anchors and node paths against the files at this commit instead of the working tree").option("--git", "check a summary's new, changed and removed claims against staged, unstaged and untracked files").option("--commit <sha>", "check claims against the files one commit changed").option("--since <base>", "check claims against the files committed since <base>; add --git for uncommitted ones too").option("--head <ref>", "with --since: compare <base>...<ref> instead of HEAD").option("--strict", "exit 1 when a claim doesn't match the code").action(async (arg, o, cmd) => {
3456
+ const usage = renderSelectionError(o);
3457
+ if (usage) cmd.error(usage, { exitCode: 2 });
2558
3458
  try {
2559
- const spec = await readSpec(arg, cwd, opts.stdin ?? readStdin);
3459
+ const spec = await readSpec(arg, cwd, opts.stdin ?? readStdin2);
2560
3460
  const repoRoot = findRepoRoot(cwd);
2561
- const root = repoRoot ?? resolve6(cwd);
3461
+ const root = repoRoot ?? resolve8(cwd);
2562
3462
  let at;
2563
3463
  if (o.at !== void 0) {
2564
3464
  if (!repoRoot) throw new Error("--at needs a git repository");
2565
3465
  at = resolveCommit(root, "--at", o.at);
2566
3466
  }
2567
- const snippets = spec.diagram === "flow" ? flowSnippets(spec, root, at, resolve6(cwd)) : void 0;
3467
+ const anchors = spec.diagram === "flow" ? flowAnchors(spec, root, at, resolve8(cwd)) : void 0;
3468
+ let diff;
3469
+ if (hasGitSelection(o)) {
3470
+ if (!repoRoot) throw new Error("--git, --commit and --since need a git repository");
3471
+ diff = diffOf(gitFiles(root, o, true));
3472
+ }
2568
3473
  const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
2569
3474
  `) });
2570
3475
  const diagram = spec.diagram ?? "map";
@@ -2591,13 +3496,13 @@ function renderCommand(opts) {
2591
3496
  const now = opts.now?.() ?? /* @__PURE__ */ new Date();
2592
3497
  const file = htmlOutputPath(config, repoFolder(root), slug, now);
2593
3498
  const html = await build({ generatedAt: now, repo: basename2(root), theme: o.theme ?? config.web.theme });
2594
- if (lstatSync4(dirname4(file), { throwIfNoEntry: false })?.isSymbolicLink()) {
2595
- throw new Error(`${dirname4(file)}: is a symlink; refusing to write`);
3499
+ if (lstatSync5(dirname5(file), { throwIfNoEntry: false })?.isSymbolicLink()) {
3500
+ throw new Error(`${dirname5(file)}: is a symlink; refusing to write`);
2596
3501
  }
2597
- mkdirSync2(dirname4(file), { recursive: true, mode: 448 });
2598
- chmodSync(dirname4(file), 448);
2599
- writeFileSync(file, html, { mode: 384 });
2600
- pruneHtml(dirname4(file), { ...config.web, now, replaceSlug: slug });
3502
+ mkdirSync4(dirname5(file), { recursive: true, mode: 448 });
3503
+ chmodSync(dirname5(file), 448);
3504
+ writeFileSync3(file, html, { mode: 384 });
3505
+ pruneHtml(dirname5(file), { ...config.web, now, replaceSlug: slug });
2601
3506
  const mode = config.web.open;
2602
3507
  if (o.open || mode === "always" || mode === "auto" && inCodeEditor(opts.env ?? process.env)) {
2603
3508
  const failed = (opts.open ?? openInBrowser)(file);
@@ -2609,15 +3514,23 @@ function renderCommand(opts) {
2609
3514
  }
2610
3515
  return file;
2611
3516
  };
3517
+ const failStrict = (check2) => {
3518
+ if (o.strict && check2.mismatches.length > 0) process.exitCode = 1;
3519
+ };
2612
3520
  if (spec.diagram === "flow") {
2613
- const tree = { maxNodes, width, color, md: o.md };
2614
- print(await renderFlow(spec, snippets, { output, minNodes: config.web.minNodes, tree, writeHtml }));
3521
+ const check2 = checkFlowDiff(spec, anchors.snippets, anchors.checked, root, diff);
3522
+ const tree = { maxNodes, width, color, md: o.md, check: check2 };
3523
+ print(await renderFlow(spec, anchors.snippets, { output, minNodes: config.web.minNodes, tree, writeHtml }));
2615
3524
  printBlocked();
3525
+ failStrict(check2);
2616
3526
  return;
2617
3527
  }
3528
+ const check = checkMapNodes(spec, root, { at, cwd: resolve8(cwd), diff });
2618
3529
  const { hidden } = selectTerminalNodes(spec, maxNodes);
2619
- const termOpts = { maxNodes, keyLine: !o.md, color, width };
2620
- const writeMapHtml = () => writeHtml(async (meta) => renderHtml(spec, await layoutSpec(spec), meta));
3530
+ const termOpts = { maxNodes, keyLine: !o.md, color, width, check };
3531
+ const previews = () => diff ? nodePreviews(spec, root, diff, diffRange(root, o), check.found, resolve8(cwd)) : void 0;
3532
+ const canvases = hasNowAfter(spec) ? PANE_CANVASES : void 0;
3533
+ const writeMapHtml = () => writeHtml(async (meta) => renderHtml(spec, await layoutSpec(spec, canvases), meta, check, previews()));
2621
3534
  let htmlPath;
2622
3535
  let terminal;
2623
3536
  if (output === "web" || output === "both" || output === "auto" && needsWeb(spec, hidden, config.web.minNodes)) {
@@ -2630,10 +3543,13 @@ function renderCommand(opts) {
2630
3543
  }
2631
3544
  }
2632
3545
  const map = output === "web" ? void 0 : (terminal ?? renderTerminalDetailed(spec, { ...termOpts, htmlPath })).text;
2633
- if (o.md) print(markdown(map, htmlPath));
2634
- else print(map ?? `${fullMapLine(htmlPath)}
3546
+ const alert = alertLine(check, width);
3547
+ if (o.md) print(markdown(map, htmlPath, alert));
3548
+ else print(map ?? `${alert ? `${alert}
3549
+ ` : ""}${fullMapLine(htmlPath)}
2635
3550
  `);
2636
3551
  printBlocked();
3552
+ failStrict(check);
2637
3553
  } catch (e) {
2638
3554
  const message = e instanceof Error ? e.message : String(e);
2639
3555
  const lines = e instanceof InvalidSpec ? e.errors : message.split("\n").map((l) => `codechart: ${l}`);
@@ -2645,20 +3561,75 @@ function renderCommand(opts) {
2645
3561
  }
2646
3562
 
2647
3563
  // src/commands/schema.ts
2648
- import { Command as Command6 } from "commander";
3564
+ import { Command as Command7 } from "commander";
2649
3565
  function schemaCommand(opts) {
2650
- return new Command6("schema").description("print the spec JSON schema, the flow spec schema with --flow, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").action((o) => {
3566
+ return new Command7("schema").description("print the spec JSON schema, the flow spec schema with --flow, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").action((o) => {
2651
3567
  const schema = o.config ? configJsonSchema() : o.flow ? flowJsonSchema() : specJsonSchema();
2652
3568
  opts.stdout(JSON.stringify(schema, null, 2) + "\n");
2653
3569
  });
2654
3570
  }
2655
3571
 
3572
+ // src/commands/uninstall.ts
3573
+ import { lstatSync as lstatSync6, readdirSync as readdirSync4, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
3574
+ import { homedir as homedir4 } from "os";
3575
+ import { join as join10 } from "path";
3576
+ import { Command as Command8 } from "commander";
3577
+ function removeSkill(dir, files) {
3578
+ const st = lstatSync6(dir, { throwIfNoEntry: false });
3579
+ if (!st) return void 0;
3580
+ if (!st.isDirectory()) return `left ${dir}: not a folder`;
3581
+ const skill = join10(dir, "SKILL.md");
3582
+ const text = lstatSync6(skill, { throwIfNoEntry: false })?.isFile() ? readRegularFile(skill, (s) => s.isFile()) : void 0;
3583
+ if (!text || !/^---\r?\n(?:.*\r?\n)*?name: codechart\r?\n/.test(text)) return `left ${dir}: not the codechart skill`;
3584
+ for (const f of files) if (lstatSync6(join10(dir, f), { throwIfNoEntry: false })?.isFile()) unlinkSync3(join10(dir, f));
3585
+ if (readdirSync4(dir).length > 0) return `removed skill files from ${dir} (kept your other files there)`;
3586
+ rmdirSync(dir);
3587
+ return `removed skill: ${dir}`;
3588
+ }
3589
+ function uninstallCommand(opts) {
3590
+ return new Command8("uninstall").description("remove what install-skill added (all of it unless flags pick some); run before npm uninstall -g codechart").option("--skill", "remove the skill from every agent folder").option("--reminder", "remove the reminder line from agents' instructions files").option("--hook", "remove the codechart hooks from ~/.claude/settings.json").action((o) => {
3591
+ const home = opts.home ?? homedir4();
3592
+ const all = !o.skill && !o.reminder && !o.hook;
3593
+ let did = false;
3594
+ const step = (run) => {
3595
+ try {
3596
+ const line = run();
3597
+ if (line) {
3598
+ opts.stdout(`${line}
3599
+ `);
3600
+ did = true;
3601
+ }
3602
+ } catch (e) {
3603
+ opts.stderr(`codechart: ${e.message}
3604
+ `);
3605
+ process.exitCode = 1;
3606
+ }
3607
+ };
3608
+ if (all || o.skill) {
3609
+ const files = readdirSync4(packageFile("skills/codechart"));
3610
+ for (const folder of new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))) step(() => removeSkill(join10(home, folder, "codechart"), files));
3611
+ }
3612
+ if (all || o.reminder) {
3613
+ for (const a of AGENTS) {
3614
+ if (!a.instructions) continue;
3615
+ const file = join10(home, a.instructions);
3616
+ step(() => removeReminder(file) === "removed" ? `removed reminder: ${file}` : void 0);
3617
+ }
3618
+ }
3619
+ if (all || o.hook) {
3620
+ const file = join10(home, ".claude", "settings.json");
3621
+ step(() => removeClaudeHooks(file) === "removed" ? `removed hook: ${file}` : void 0);
3622
+ }
3623
+ if (!did && process.exitCode !== 1) opts.stdout("nothing to remove\n");
3624
+ });
3625
+ }
3626
+
2656
3627
  // src/program.ts
2657
3628
  function buildProgram(opts = {}) {
2658
3629
  const stdout = opts.stdout ?? ((s) => process.stdout.write(s));
2659
3630
  const rawStderr = opts.stderr ?? ((s) => process.stderr.write(s));
2660
3631
  const stderr = (s) => rawStderr(sanitizeText(s));
2661
- const program = new Command7().name("codechart").version("0.1.2");
3632
+ const program = new Command9().name("codechart").version("0.2.0");
2662
3633
  const cmdOpts = { ...opts, stdout, stderr };
2663
3634
  program.addCommand(checkCommand(cmdOpts));
2664
3635
  program.addCommand(renderCommand(cmdOpts));
@@ -2666,6 +3637,8 @@ function buildProgram(opts = {}) {
2666
3637
  program.addCommand(configCommand(cmdOpts));
2667
3638
  program.addCommand(initCommand(cmdOpts));
2668
3639
  program.addCommand(installSkillCommand(cmdOpts));
3640
+ program.addCommand(uninstallCommand(cmdOpts));
3641
+ program.addCommand(hookCommand(cmdOpts));
2669
3642
  for (const c of [program, ...program.commands]) {
2670
3643
  c.exitOverride().configureOutput({ writeOut: stdout, writeErr: stderr });
2671
3644
  }