codechart 0.1.3 → 0.3.0

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