codechart 0.1.3 → 0.2.0

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