codechart 0.8.0 → 0.9.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 Command16, CommanderError } from "commander";
4
+ import { Command as Command17, CommanderError } from "commander";
5
5
 
6
6
  // src/commands/check.ts
7
7
  import path2 from "path";
@@ -10,12 +10,12 @@ import { Command } from "commander";
10
10
  // src/config/load.ts
11
11
  import { realpathSync } from "fs";
12
12
  import { homedir } from "os";
13
- import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
13
+ import { isAbsolute as isAbsolute2, join as join2, relative, resolve as resolve2, sep } from "path";
14
14
  import { parse } from "yaml";
15
15
 
16
16
  // src/read-regular.ts
17
17
  import { closeSync, constants, fstatSync, openSync, readSync } from "fs";
18
- function readRegularFile(path3, accept) {
18
+ function readRegularBytes(path3, accept) {
19
19
  const fd = openSync(path3, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
20
20
  try {
21
21
  const st = fstatSync(fd);
@@ -23,11 +23,14 @@ function readRegularFile(path3, accept) {
23
23
  const buf = Buffer.alloc(st.size);
24
24
  let n = 0;
25
25
  for (let r = 1; r > 0 && n < buf.length; n += r) r = readSync(fd, buf, n, buf.length - n, null);
26
- return buf.toString("utf8", 0, n);
26
+ return buf.subarray(0, n);
27
27
  } finally {
28
28
  closeSync(fd);
29
29
  }
30
30
  }
31
+ function readRegularFile(path3, accept) {
32
+ return readRegularBytes(path3, accept)?.toString("utf8");
33
+ }
31
34
 
32
35
  // src/config/repo-root.ts
33
36
  import { existsSync } from "fs";
@@ -137,6 +140,7 @@ function builtinRules(flows) {
137
140
  }
138
141
 
139
142
  // src/config/schema.ts
143
+ import { isAbsolute, win32 } from "path";
140
144
  import { z as z2 } from "zod";
141
145
 
142
146
  // src/spec/shared.ts
@@ -235,6 +239,8 @@ var THEMES = ["auto", "light", "dark"];
235
239
  var OPEN_MODES = ["auto", "always", "never"];
236
240
  var DIAGRAMS = ["map", "flow"];
237
241
  var FLOWS = ["auto", "always", "request"];
242
+ var RELEASE_AUTO = ["suggest", "draw", "off"];
243
+ var DEFAULT_RELEASE_BRANCHES = ["v[0-9]*", "release-*", "release/*"];
238
244
  var RULE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
239
245
  var ONE_LINE_VISIBLE = /^[^\u0000-\u001f\u007f-\u009f\u200b\u200c\u200e\u200f\u2028-\u202e\u2060-\u2069\ufeff]*$/;
240
246
  var CHARS_MESSAGE = "must be one line without control or invisible characters";
@@ -268,6 +274,13 @@ var configFileSchema = z2.strictObject({
268
274
  maxAgeDays: z2.number().nonnegative().optional(),
269
275
  open: z2.enum(OPEN_MODES).optional()
270
276
  }).optional(),
277
+ release: z2.strictObject({
278
+ product: z2.string().min(1).max(80).regex(ONE_LINE_VISIBLE, CHARS_MESSAGE).optional().describe("Product name on the cover of a release map (default: the repo name)"),
279
+ logo: z2.string().min(1).max(300).regex(ONE_LINE_VISIBLE, CHARS_MESSAGE).optional().describe("Repo-relative path to an .svg or .png of at most 200 KB, shown on the cover of a release map"),
280
+ browser: z2.string().min(1).max(300).regex(ONE_LINE_VISIBLE, CHARS_MESSAGE).refine((p) => isAbsolute(p) || win32.isAbsolute(p), "must be an absolute path").optional().describe("Global only: absolute path of the Chromium-based browser that prints a release map to PDF (default: Chrome, Chromium, Edge or Brave where they are usually installed)"),
281
+ branches: z2.array(glob).min(1).optional().describe("Branches that are release branches, as globs (default: v[0-9]*, release-*, release/*)"),
282
+ auto: z2.enum(RELEASE_AUTO).optional().describe("On a release branch: suggest a release map, draw one, or do nothing (default: suggest)")
283
+ }).optional(),
271
284
  useBuiltinRules: z2.boolean().optional(),
272
285
  updateCheck: z2.boolean().optional().describe("Global only: look up the newest codechart on npm at most once a day and say when there is one (default true)"),
273
286
  rules: z2.array(ruleSchema).optional()
@@ -285,7 +298,7 @@ function parseConfigFile(input) {
285
298
  var BUILTIN = "built-in";
286
299
  var MAX_BYTES = 1024 * 1024;
287
300
  var BUILTIN_DEFAULTS = { output: "auto", context: "short", flows: "auto", terminalMaxNodes: 15 };
288
- var GLOBAL_ONLY = ["web.outDir", "web.keep", "web.maxAgeDays", "web.open", "updateCheck"];
301
+ var GLOBAL_ONLY = ["web.outDir", "web.keep", "web.maxAgeDays", "web.open", "updateCheck", "release.browser"];
289
302
  function readConfigFile(file, root) {
290
303
  let real;
291
304
  try {
@@ -296,7 +309,7 @@ function readConfigFile(file, root) {
296
309
  }
297
310
  if (root !== void 0) {
298
311
  const rel = relative(realpathSync(root), real);
299
- if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`${file}: resolves outside the repo`);
312
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute2(rel)) throw new Error(`${file}: resolves outside the repo`);
300
313
  }
301
314
  const text3 = readRegularFile(real, (st) => {
302
315
  if (!st.isFile()) throw new Error(`${file}: not a regular file`);
@@ -324,9 +337,14 @@ function dropGlobalOnly(file, path3, warn) {
324
337
  if (!file) return file;
325
338
  const { updateCheck, ...rest } = file;
326
339
  const { outDir, keep, maxAgeDays, open, ...web } = file.web ?? {};
327
- const ignored = [...Object.entries({ outDir, keep, maxAgeDays, open }).filter(([, v]) => v !== void 0).map(([k]) => `web.${k}`), ...updateCheck === void 0 ? [] : ["updateCheck"]];
340
+ const { browser, ...release } = file.release ?? {};
341
+ const ignored = [
342
+ ...Object.entries({ outDir, keep, maxAgeDays, open }).filter(([, v]) => v !== void 0).map(([k]) => `web.${k}`),
343
+ ...updateCheck === void 0 ? [] : ["updateCheck"],
344
+ ...browser === void 0 ? [] : ["release.browser"]
345
+ ];
328
346
  if (ignored.length) warn?.(`${path3}: ${ignored.join(", ")} ${ignored.length === 1 ? "is" : "are"} global-only; ignored`);
329
- return file.web ? { ...rest, web } : rest;
347
+ return { ...rest, ...file.web && { web }, ...file.release && { release } };
330
348
  }
331
349
  function firstByName(items2) {
332
350
  const seen = /* @__PURE__ */ new Set();
@@ -336,11 +354,26 @@ function resolveOutDir(dir, home) {
336
354
  const expanded = dir === "~" ? home : dir.startsWith("~/") ? join2(home, dir.slice(2)) : dir;
337
355
  return resolve2(home, expanded);
338
356
  }
357
+ var RELEASE_KEYS = ["product", "logo", "browser", "branches", "auto"];
358
+ function releaseOf(files, sources) {
359
+ const release = { branches: DEFAULT_RELEASE_BRANCHES, auto: "suggest" };
360
+ sources["release.branches"] = BUILTIN;
361
+ sources["release.auto"] = BUILTIN;
362
+ for (const { file, source } of files) {
363
+ for (const key of RELEASE_KEYS) {
364
+ const value = file?.release?.[key];
365
+ if (value === void 0) continue;
366
+ Object.assign(release, { [key]: value });
367
+ sources[`release.${key}`] = source;
368
+ }
369
+ }
370
+ return release;
371
+ }
339
372
  function loadConfigWithSources(opts) {
340
373
  const env = opts.env ?? process.env;
341
374
  const home = opts.home ?? homedir();
342
375
  const xdg = env.XDG_CONFIG_HOME;
343
- const configHome = xdg && isAbsolute(xdg) ? xdg : home ? join2(home, ".config") : void 0;
376
+ const configHome = xdg && isAbsolute2(xdg) ? xdg : home ? join2(home, ".config") : void 0;
344
377
  const root = findRepoRoot(opts.cwd) ?? resolve2(opts.cwd);
345
378
  const globalPath = configHome ? join2(configHome, "codechart", "config.yaml") : void 0;
346
379
  const repoPath2 = join2(root, ".codechart.yaml");
@@ -382,8 +415,9 @@ function loadConfigWithSources(opts) {
382
415
  ...(global?.rules ?? []).map((rule) => ({ rule, source: globalSource })),
383
416
  ...(useBuiltinRules ? builtinRules(defaults.flows) : []).map((rule) => ({ rule, source: BUILTIN }))
384
417
  ]);
418
+ const release = releaseOf(files, sources);
385
419
  return {
386
- config: { defaults, web, useBuiltinRules, updateCheck: global?.updateCheck !== false, rules: tagged.map((t) => t.rule) },
420
+ config: { defaults, web, useBuiltinRules, updateCheck: global?.updateCheck !== false, release, rules: tagged.map((t) => t.rule) },
387
421
  sources,
388
422
  ruleSources: tagged.map((t) => t.source)
389
423
  };
@@ -401,18 +435,18 @@ function normalizePath(p, root) {
401
435
  const rootSlashed = root.replace(/\\/g, "/");
402
436
  if (DRIVE_PATH.test(slashed)) {
403
437
  if (!DRIVE_PATH.test(rootSlashed)) return slashed;
404
- const relative5 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
405
- return isInside(relative5) ? relative5 : slashed;
438
+ const relative6 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
439
+ return isInside(relative6) ? relative6 : slashed;
406
440
  }
407
441
  if (!path.posix.isAbsolute(slashed)) return slashed;
408
- const relative4 = path.posix.relative(rootSlashed, slashed);
409
- return isInside(relative4) ? relative4 : slashed;
442
+ const relative5 = path.posix.relative(rootSlashed, slashed);
443
+ return isInside(relative5) ? relative5 : slashed;
410
444
  }
411
445
  function lowerDrive(p) {
412
446
  return p.charAt(0).toLowerCase() + p.slice(1);
413
447
  }
414
- function isInside(relative4) {
415
- return relative4 !== "" && relative4 !== ".." && !relative4.startsWith("../");
448
+ function isInside(relative5) {
449
+ return relative5 !== "" && relative5 !== ".." && !relative5.startsWith("../");
416
450
  }
417
451
  function isPathRule(rule) {
418
452
  return rule.paths !== void 0;
@@ -519,21 +553,57 @@ function resolveRules(config, files, matched, root = process.cwd()) {
519
553
  return result;
520
554
  }
521
555
 
556
+ // src/commands/release-branch.ts
557
+ import { readdirSync } from "fs";
558
+ import { join as join5 } from "path";
559
+ import picomatch2 from "picomatch";
560
+
561
+ // src/render/output-path.ts
562
+ import { createHash } from "crypto";
563
+ import { basename, join as join3 } from "path";
564
+ var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow|\.business|\.release)?)\.html$/;
565
+ var REVIEW_NAME = /^(\d{8}-\d{6}-[a-z0-9-]+(?:\.flow|\.business)?)\.review\.json$/;
566
+ var reviewFile = (html) => html.replace(/\.html$/, ".review.json");
567
+ var pad = (n) => String(n).padStart(2, "0");
568
+ function stamp(d) {
569
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
570
+ }
571
+ function parseStamp(s) {
572
+ const n = (from, to) => Number(s.slice(from, to));
573
+ return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
574
+ }
575
+ function slugify(title) {
576
+ const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
577
+ return slug || "map";
578
+ }
579
+ var fileSlug = (title, diagram) => diagram === "map" ? slugify(title) : `${slugify(title)}.${diagram}`;
580
+ function htmlOutputPath(config, repo, slug, now) {
581
+ return join3(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
582
+ }
583
+ function repoFolder(root) {
584
+ return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
585
+ }
586
+
587
+ // src/render/release/slug.ts
588
+ var versionSlug = (version2) => version2.replace(/^v(?=\d)/i, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
589
+ var releaseSlug = (version2, title) => fileSlug(`v${versionSlug(version2)} ${title}`, "release");
590
+
522
591
  // src/rules/git-files.ts
523
592
  import { execFileSync } from "child_process";
524
593
  import { existsSync as existsSync2, lstatSync } from "fs";
525
- import { join as join3, win32 } from "path";
594
+ import { join as join4, win32 as win322 } from "path";
526
595
  var MAX_REF = 200;
527
- function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
528
- if (platform !== "win32") return "git";
596
+ function trustedBinary(name, platform = process.platform, env = process.env, exists = existsSync2) {
597
+ if (platform !== "win32") return name;
529
598
  for (const raw of (env.PATH ?? env.Path ?? "").split(";")) {
530
599
  const dir = raw.replace(/^"(.*)"$/, "$1");
531
- if (!win32.isAbsolute(dir)) continue;
532
- const file = win32.join(dir, "git.exe");
600
+ if (!win322.isAbsolute(dir)) continue;
601
+ const file = win322.join(dir, `${name}.exe`);
533
602
  if (exists(file)) return file;
534
603
  }
535
- throw new Error("git not found on PATH");
604
+ throw new Error(`${name} not found on PATH`);
536
605
  }
606
+ var gitBinary = (platform, env, exists) => trustedBinary("git", platform, env, exists);
537
607
  var gitPath;
538
608
  var SAFE_ARGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never"];
539
609
  var OutputTooLarge = class extends Error {
@@ -716,9 +786,9 @@ function gitFileDiffs(cwd, range, rels, maxBytes) {
716
786
  const wanted = new Set(rels);
717
787
  let left = maxBytes;
718
788
  try {
719
- for (const group of chunks(rels)) {
789
+ for (const group2 of chunks(rels)) {
720
790
  if (left <= 0) return void 0;
721
- const text3 = git(cwd, diffArgs(range, group), { config: [["core.bigFileThreshold", "5m"], ["core.quotePath", "false"], ...range.config], maxBuffer: left });
791
+ const text3 = git(cwd, diffArgs(range, group2), { config: [["core.bigFileThreshold", "5m"], ["core.quotePath", "false"], ...range.config], maxBuffer: left });
722
792
  left -= Buffer.byteLength(text3);
723
793
  const starts = [...text3.matchAll(/^diff --git /gm)].map((m) => m.index);
724
794
  for (const [i, start] of starts.entries()) {
@@ -740,8 +810,8 @@ function gitFileDiffs(cwd, range, rels, maxBytes) {
740
810
  function gitUntracked(cwd, rels) {
741
811
  const found = /* @__PURE__ */ new Set();
742
812
  const wanted = new Set(rels);
743
- for (const group of chunks(rels)) {
744
- for (const f of git(cwd, ["--literal-pathspecs", "ls-files", "-z", "--others", "--exclude-standard", "--", ...group]).split("\0")) {
813
+ for (const group2 of chunks(rels)) {
814
+ for (const f of git(cwd, ["--literal-pathspecs", "ls-files", "-z", "--others", "--exclude-standard", "--", ...group2]).split("\0")) {
745
815
  if (wanted.has(f)) found.add(f);
746
816
  }
747
817
  }
@@ -801,15 +871,65 @@ function gitDirtyHashes(cwd, max = Infinity) {
801
871
  const files = gitChangedFiles(cwd);
802
872
  if (files.length > max) return void 0;
803
873
  const out = {};
804
- const present3 = files.filter((f) => !f.includes("\n") && !f.startsWith('"') && lstatSync(join3(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
874
+ const present3 = files.filter((f) => !f.includes("\n") && !f.startsWith('"') && lstatSync(join4(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
805
875
  const hashes = present3.length ? git(cwd, ["hash-object", "--no-filters", "--stdin-paths"], { input: present3.join("\n") }).trim().split("\n") : [];
806
- for (const f of files) out[f] = existsSync2(join3(cwd, f)) ? "present" : "deleted";
876
+ for (const f of files) out[f] = existsSync2(join4(cwd, f)) ? "present" : "deleted";
807
877
  present3.forEach((f, i) => out[f] = hashes[i] ?? "");
808
878
  return out;
809
879
  }
810
880
  function gitDiffFiles(cwd, from, to) {
811
881
  return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", from, to, "--"]));
812
882
  }
883
+ function gitLatestTag(cwd, sha, pattern) {
884
+ try {
885
+ return git(cwd, ["describe", "--tags", "--abbrev=0", "--match", pattern, sha]).trim() || void 0;
886
+ } catch {
887
+ return void 0;
888
+ }
889
+ }
890
+ function gitFirstParentLog(cwd, since, head2) {
891
+ const out = git(cwd, ["log", "--first-parent", "--reverse", "--no-color", "--no-show-signature", "--format=%H%x1f%h%x1f%cI%x1f%s%x1f%b%x1e", `${since}..${head2}`, "--"]);
892
+ return out.split("").map((r) => r.trim()).filter(Boolean).map((r) => {
893
+ const [sha = "", short2 = "", date = "", subject = "", body = ""] = r.split("");
894
+ return { sha, short: short2, date, subject, body: body.trim() };
895
+ });
896
+ }
897
+
898
+ // src/commands/release-branch.ts
899
+ var VERSION = /(?:^|[^0-9A-Za-z])v?(\d+\.\d+(?:\.\d+)?)(?![0-9A-Za-z])/;
900
+ var branchVersion = (branch) => VERSION.exec(branch)?.[1];
901
+ function normalised(slug) {
902
+ const groups = slug.split("-");
903
+ while (groups.length > 2 && groups.at(-1) === "0") groups.pop();
904
+ return groups.join("-");
905
+ }
906
+ var normalisedSaved = (name) => {
907
+ const slug = /^v(\d+(?:-\d+){0,2})-/.exec(name.slice(16))?.[1];
908
+ return slug && normalised(slug);
909
+ };
910
+ function existing(config, root, version2) {
911
+ const dir = join5(config.web.outDir, repoFolder(root));
912
+ const wanted = normalised(versionSlug(version2));
913
+ let names;
914
+ try {
915
+ names = readdirSync(dir);
916
+ } catch {
917
+ return void 0;
918
+ }
919
+ const found = (ext) => names.filter((n) => /^\d{8}-\d{6}-/.test(n) && normalisedSaved(n) === wanted && n.endsWith(`.release.${ext}`)).sort().at(-1);
920
+ const name = found("pdf") ?? found("html");
921
+ return name && join5(dir, name);
922
+ }
923
+ function releaseHint(config, root, head2) {
924
+ const { branches, auto } = config.release;
925
+ const branch = head2 === void 0 ? gitBranch(root) : head2.replace(/^(?:refs\/heads\/|refs\/remotes\/[^/]+\/|origin\/)/, "");
926
+ if (auto === "off" || !branch || branch === "(detached)" || !picomatch2.isMatch(branch, branches, { dot: true })) return void 0;
927
+ const version2 = branchVersion(branch);
928
+ const base = { branch, ...version2 && { version: version2 } };
929
+ if (auto === "suggest" || version2 === void 0) return { action: "suggest", ...base };
930
+ const path3 = version2 === void 0 ? void 0 : existing(config, root, version2);
931
+ return path3 === void 0 ? { action: "draw", ...base } : { action: "done", ...base, path: path3 };
932
+ }
813
933
 
814
934
  // src/rules/selection.ts
815
935
  var csv = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
@@ -888,7 +1008,8 @@ function checkCommand(opts) {
888
1008
  const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
889
1009
  `) });
890
1010
  const result = resolveRules(config, files, o.matched !== void 0 ? csv(o.matched) : void 0, root ?? path2.resolve(cwd));
891
- opts.stdout(escapeJsonControls(formatResult(terseResult(result))) + "\n");
1011
+ const hint = root ? releaseHint(config, root, o.head) : void 0;
1012
+ opts.stdout(escapeJsonControls(formatResult({ ...terseResult(result), ...hint && { release: hint } })) + "\n");
892
1013
  } catch (e) {
893
1014
  opts.stderr(`codechart: ${e.message}
894
1015
  `);
@@ -966,34 +1087,8 @@ function buildDoc(review2) {
966
1087
  }
967
1088
 
968
1089
  // src/review/store.ts
969
- import { closeSync as closeSync2, openSync as openSync2, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
970
- import { join as join5 } from "path";
971
-
972
- // src/render/output-path.ts
973
- import { createHash } from "crypto";
974
- import { basename, join as join4 } from "path";
975
- var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow|\.business)?)\.html$/;
976
- var REVIEW_NAME = /^(\d{8}-\d{6}-[a-z0-9-]+(?:\.flow|\.business)?)\.review\.json$/;
977
- var reviewFile = (html) => html.replace(/\.html$/, ".review.json");
978
- var pad = (n) => String(n).padStart(2, "0");
979
- function stamp(d) {
980
- return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
981
- }
982
- function parseStamp(s) {
983
- const n = (from, to) => Number(s.slice(from, to));
984
- return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
985
- }
986
- function slugify(title) {
987
- const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
988
- return slug || "map";
989
- }
990
- var fileSlug = (title, diagram) => diagram === "map" ? slugify(title) : `${slugify(title)}.${diagram}`;
991
- function htmlOutputPath(config, repo, slug, now) {
992
- return join4(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
993
- }
994
- function repoFolder(root) {
995
- return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
996
- }
1090
+ import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync2, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
1091
+ import { join as join6 } from "path";
997
1092
 
998
1093
  // src/review/carry.ts
999
1094
  function targetExists(target2, lists) {
@@ -1137,13 +1232,13 @@ function updateReview(file, change, times = { waitMs: 2e3, staleMs: 1e4 }) {
1137
1232
  function listReviews(dir, branch, which = "tech") {
1138
1233
  let names;
1139
1234
  try {
1140
- names = readdirSync(dir);
1235
+ names = readdirSync2(dir);
1141
1236
  } catch {
1142
1237
  return [];
1143
1238
  }
1144
1239
  return names.filter((n) => REVIEW_NAME.test(n)).sort().reverse().flatMap((n) => {
1145
- const review2 = readReview(join5(dir, n));
1146
- return review2 && review2.change.branch === branch && (which === "all" || review2.change.kind === "business" === (which === "business")) ? [{ file: join5(dir, n), review: review2 }] : [];
1240
+ const review2 = readReview(join6(dir, n));
1241
+ return review2 && review2.change.branch === branch && (which === "all" || review2.change.kind === "business" === (which === "business")) ? [{ file: join6(dir, n), review: review2 }] : [];
1147
1242
  });
1148
1243
  }
1149
1244
  var sameName = (r, name) => r.change.slug === name || (r.change.title ?? r.change.slug).toLowerCase() === name.toLowerCase();
@@ -1169,13 +1264,13 @@ function saveReview(o) {
1169
1264
  }
1170
1265
 
1171
1266
  // src/commands/review-shared.ts
1172
- import { join as join6, resolve as resolve3 } from "path";
1267
+ import { join as join7, resolve as resolve3 } from "path";
1173
1268
  function locateChange(opts, slug, branch, exact = false, which = "tech") {
1174
1269
  const cwd = opts.cwd ?? process.cwd();
1175
1270
  const root = findRepoRoot(cwd) ?? resolve3(cwd);
1176
1271
  const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
1177
1272
  `) });
1178
- return { root, ...findChange(join6(config.web.outDir, repoFolder(root)), branch ?? gitBranch(root), slug, exact, which) };
1273
+ return { root, ...findChange(join7(config.web.outDir, repoFolder(root)), branch ?? gitBranch(root), slug, exact, which) };
1179
1274
  }
1180
1275
  async function guarded(opts, fn) {
1181
1276
  try {
@@ -1306,9 +1401,9 @@ function wrapItems(head2, items2, width) {
1306
1401
  };
1307
1402
  items2.forEach((raw, i) => {
1308
1403
  const item = typeof raw === "string" ? { text: raw } : raw;
1309
- const sep6 = i === 0 ? "" : " \xB7 ";
1310
- if (columns(sep6 + item.text) <= room()) {
1311
- append(sep6);
1404
+ const sep7 = i === 0 ? "" : " \xB7 ";
1405
+ if (columns(sep7 + item.text) <= room()) {
1406
+ append(sep7);
1312
1407
  return append(item.text, item);
1313
1408
  }
1314
1409
  if (!fresh) newLine();
@@ -1354,7 +1449,8 @@ function formatText({ config, sources, ruleSources }) {
1354
1449
  ...Object.fromEntries(Object.entries(config.defaults).map(([k, v]) => [`defaults.${k}`, v])),
1355
1450
  ...Object.fromEntries(Object.entries(config.web).map(([k, v]) => [`web.${k}`, v])),
1356
1451
  useBuiltinRules: config.useBuiltinRules,
1357
- updateCheck: config.updateCheck
1452
+ updateCheck: config.updateCheck,
1453
+ ...Object.fromEntries(Object.entries(config.release).map(([k, v]) => [`release.${k}`, Array.isArray(v) ? v.join(", ") : v]))
1358
1454
  };
1359
1455
  if (!config.useBuiltinRules) values["defaults.flows"] = "inactive (built-in rules off)";
1360
1456
  const globalOnly = (key) => GLOBAL_ONLY.includes(key) ? "; global-only" : "";
@@ -1393,24 +1489,24 @@ import { Command as Command6 } from "commander";
1393
1489
 
1394
1490
  // src/commands/doctor-checks.ts
1395
1491
  import { accessSync, constants as constants3, existsSync as existsSync8, lstatSync as lstatSync7, statSync as statSync2 } from "fs";
1396
- import { join as join15, posix, win32 as win322 } from "path";
1492
+ import { join as join16, posix, win32 as win323 } from "path";
1397
1493
 
1398
1494
  // src/update/check.ts
1399
1495
  import { readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
1400
- import { join as join9 } from "path";
1496
+ import { join as join10 } from "path";
1401
1497
 
1402
1498
  // src/assets.ts
1403
1499
  import { existsSync as existsSync3 } from "fs";
1404
- import { dirname as dirname2, join as join7 } from "path";
1500
+ import { dirname as dirname2, join as join8 } from "path";
1405
1501
  import { fileURLToPath } from "url";
1406
- function packageFile(relative4) {
1502
+ function packageFile(relative5) {
1407
1503
  let dir = dirname2(fileURLToPath(import.meta.url));
1408
- while (!existsSync3(join7(dir, "package.json"))) {
1504
+ while (!existsSync3(join8(dir, "package.json"))) {
1409
1505
  const parent = dirname2(dir);
1410
1506
  if (parent === dir) throw new Error("package root not found");
1411
1507
  dir = parent;
1412
1508
  }
1413
- return join7(dir, relative4);
1509
+ return join8(dir, relative5);
1414
1510
  }
1415
1511
 
1416
1512
  // src/render/web/write.ts
@@ -1418,8 +1514,8 @@ import { chmodSync, lstatSync as lstatSync3, mkdirSync, writeFileSync as writeFi
1418
1514
  import { basename as basename2, dirname as dirname3 } from "path";
1419
1515
 
1420
1516
  // src/render/prune.ts
1421
- import { lstatSync as lstatSync2, readdirSync as readdirSync2, rmSync as rmSync2 } from "fs";
1422
- import { join as join8 } from "path";
1517
+ import { lstatSync as lstatSync2, readdirSync as readdirSync3, rmSync as rmSync2 } from "fs";
1518
+ import { join as join9 } from "path";
1423
1519
  var DAY_MS = 864e5;
1424
1520
  var BUSINESS_KEEP_DAYS = 30;
1425
1521
  function entriesOf(names) {
@@ -1438,7 +1534,7 @@ function entriesOf(names) {
1438
1534
  }
1439
1535
  function onBranch(dir, e, branch) {
1440
1536
  if (branch === void 0 || !e.review) return true;
1441
- const review2 = readReview(join8(dir, e.review));
1537
+ const review2 = readReview(join9(dir, e.review));
1442
1538
  return !review2 || review2.change.branch === branch;
1443
1539
  }
1444
1540
  var remove = (file) => {
@@ -1453,15 +1549,15 @@ var retained = (e, now) => e.slug.endsWith(".business") && now.getTime() - parse
1453
1549
  function sweepReviews(dir, entries2, now) {
1454
1550
  for (const e of entries2) {
1455
1551
  if (!e.review || e.page || retained(e, now)) continue;
1456
- const review2 = readReview(join8(dir, e.review));
1457
- if (!review2 || review2.change.html !== void 0) remove(join8(dir, e.review));
1552
+ const review2 = readReview(join9(dir, e.review));
1553
+ if (!review2 || review2.change.html !== void 0) remove(join9(dir, e.review));
1458
1554
  }
1459
1555
  }
1460
1556
  function pruneHtml(dir, opts) {
1461
1557
  let names;
1462
1558
  try {
1463
1559
  if (lstatSync2(dir).isSymbolicLink()) return [];
1464
- names = readdirSync2(dir);
1560
+ names = readdirSync3(dir);
1465
1561
  } catch {
1466
1562
  return [];
1467
1563
  }
@@ -1478,8 +1574,8 @@ function pruneHtml(dir, opts) {
1478
1574
  });
1479
1575
  const deleted = [];
1480
1576
  for (const e of [...doomed, ...aged]) {
1481
- if (e.page && remove(join8(dir, e.page))) deleted.push(join8(dir, e.page));
1482
- if (e.review && !(aged.has(e) && retained(e, opts.now))) remove(join8(dir, e.review));
1577
+ if (e.page && remove(join9(dir, e.page))) deleted.push(join9(dir, e.page));
1578
+ if (e.review && !(aged.has(e) && retained(e, opts.now))) remove(join9(dir, e.review));
1483
1579
  }
1484
1580
  sweepReviews(dir, entries2.filter((e) => !doomed.has(e) && !aged.has(e)), opts.now);
1485
1581
  return deleted;
@@ -1535,7 +1631,7 @@ async function writeHtml(build2, o) {
1535
1631
  // src/update/changelog.ts
1536
1632
  var NOTES_URL = "https://github.com/freeleex/codechart/blob/main/CHANGELOG.md";
1537
1633
  var RAW = "https://raw.githubusercontent.com/freeleex/codechart";
1538
- var VERSION = /^\d+\.\d+\.\d+$/;
1634
+ var VERSION2 = /^\d+\.\d+\.\d+$/;
1539
1635
  var MAX_BYTES2 = 256 * 1024;
1540
1636
  var MAX_CHARS = 200;
1541
1637
  function parseChangelog(md2) {
@@ -1567,7 +1663,7 @@ async function readCapped(body) {
1567
1663
  return Buffer.concat(chunks2).toString("utf8");
1568
1664
  }
1569
1665
  async function fetchHighlights(fetchFn, current, latest, timeoutMs) {
1570
- if (!VERSION.test(latest)) return void 0;
1666
+ if (!VERSION2.test(latest)) return void 0;
1571
1667
  try {
1572
1668
  const res = await fetchFn(`${RAW}/v${latest}/CHANGELOG.md`, { signal: AbortSignal.timeout(timeoutMs) });
1573
1669
  if (!res.ok || !res.body || Number(res.headers.get("content-length")) > MAX_BYTES2) return void 0;
@@ -1587,10 +1683,10 @@ function notesLines(h) {
1587
1683
  // src/update/check.ts
1588
1684
  var REGISTRY = "https://registry.npmjs.org/codechart/latest";
1589
1685
  var DAY = 24 * 60 * 60 * 1e3;
1590
- var VERSION2 = /^\d+\.\d+\.\d+$/;
1686
+ var VERSION3 = /^\d+\.\d+\.\d+$/;
1591
1687
  var currentVersion = () => JSON.parse(readFileSync2(packageFile("package.json"), "utf8")).version;
1592
1688
  function isNewer(a, b) {
1593
- if (!VERSION2.test(a) || !VERSION2.test(b)) return false;
1689
+ if (!VERSION3.test(a) || !VERSION3.test(b)) return false;
1594
1690
  const [x, y] = [a, b].map((v) => v.split(".").map(Number));
1595
1691
  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
1596
1692
  return false;
@@ -1599,13 +1695,13 @@ async function fetchLatest(fetchFn, timeoutMs) {
1599
1695
  try {
1600
1696
  const res = await fetchFn(REGISTRY, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1601
1697
  if (!res.ok) return void 0;
1602
- const version = (await res.json()).version;
1603
- return typeof version === "string" && VERSION2.test(version) ? version : void 0;
1698
+ const version2 = (await res.json()).version;
1699
+ return typeof version2 === "string" && VERSION3.test(version2) ? version2 : void 0;
1604
1700
  } catch {
1605
1701
  return void 0;
1606
1702
  }
1607
1703
  }
1608
- var stateFile = (cacheDir) => join9(cacheDir, "update-check.json");
1704
+ var stateFile = (cacheDir) => join10(cacheDir, "update-check.json");
1609
1705
  function readState(cacheDir) {
1610
1706
  try {
1611
1707
  const raw = JSON.parse(readFileSync2(stateFile(cacheDir), "utf8"));
@@ -1666,7 +1762,7 @@ async function updateNotice(c) {
1666
1762
 
1667
1763
  // src/commands/agents.ts
1668
1764
  import { lstatSync as lstatSync4 } from "fs";
1669
- import { join as join10 } from "path";
1765
+ import { join as join11 } from "path";
1670
1766
  var SHARED = ".agents/skills";
1671
1767
  var AGENTS = [
1672
1768
  { name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [], instructions: ".claude/CLAUDE.md" },
@@ -1694,15 +1790,15 @@ function skillFolders(agents) {
1694
1790
  return groups;
1695
1791
  }
1696
1792
  function isCodechartSkill(dir) {
1697
- const skill = join10(dir, "SKILL.md");
1793
+ const skill = join11(dir, "SKILL.md");
1698
1794
  const text3 = lstatSync4(skill, { throwIfNoEntry: false })?.isFile() ? readRegularFile(skill, (s) => s.isFile()) : void 0;
1699
1795
  return text3 !== void 0 && /^---\r?\n(?:.*\r?\n)*?name: codechart\r?\n/.test(text3);
1700
1796
  }
1701
1797
 
1702
1798
  // src/commands/install-skill.ts
1703
- import { existsSync as existsSync6, readdirSync as readdirSync3 } from "fs";
1799
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "fs";
1704
1800
  import { homedir as homedir2 } from "os";
1705
- import { join as join13, resolve as resolve4 } from "path";
1801
+ import { join as join14, resolve as resolve4 } from "path";
1706
1802
  import { Command as Command4 } from "commander";
1707
1803
 
1708
1804
  // src/commands/copy-file.ts
@@ -1929,11 +2025,11 @@ function removeClaudeHooks(file) {
1929
2025
 
1930
2026
  // src/commands/opencode-plugin.ts
1931
2027
  import { existsSync as existsSync5, lstatSync as lstatSync6, unlinkSync as unlinkSync2 } from "fs";
1932
- import { isAbsolute as isAbsolute2, join as join11 } from "path";
2028
+ import { isAbsolute as isAbsolute3, join as join12 } from "path";
1933
2029
  var MARK = "codechart OpenCode plugin";
1934
2030
  function pluginFile(home, env) {
1935
2031
  const xdg = env.XDG_CONFIG_HOME;
1936
- return join11(xdg && isAbsolute2(xdg) ? xdg : join11(home, ".config"), "opencode", "plugins", "codechart.js");
2032
+ return join12(xdg && isAbsolute3(xdg) ? xdg : join12(home, ".config"), "opencode", "plugins", "codechart.js");
1937
2033
  }
1938
2034
  var pair = (file) => ({ source: packageFile("dist/server.js"), target: file });
1939
2035
  function isOurs(file) {
@@ -1959,10 +2055,10 @@ function removePlugin(file) {
1959
2055
 
1960
2056
  // src/commands/opencode-version.ts
1961
2057
  import { execFileSync as execFileSync2 } from "child_process";
1962
- import { join as join12 } from "path";
2058
+ import { join as join13 } from "path";
1963
2059
  var run = (opts, command) => opts.tool ? opts.tool(command, ["--version"]) : execFileSync2(command, ["--version"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
1964
2060
  function opencodeVersion(opts, home) {
1965
- for (const command of ["opencode", join12(home, ".opencode", "bin", "opencode")]) {
2061
+ for (const command of ["opencode", join13(home, ".opencode", "bin", "opencode")]) {
1966
2062
  try {
1967
2063
  const v = /(\d+\.\d+(?:\.\d+)?)/.exec(run(opts, command))?.[1];
1968
2064
  if (v) return v;
@@ -2026,7 +2122,7 @@ function terminalPicker(title, items2, checked = true) {
2026
2122
  stdout.write((drawn ? `\x1B[${drawn}A\r\x1B[0J` : "") + lines.join("\n") + "\n");
2027
2123
  drawn = lines.length;
2028
2124
  };
2029
- return new Promise((resolve15) => {
2125
+ return new Promise((resolve18) => {
2030
2126
  emitKeypressEvents(stdin);
2031
2127
  stdin.setRawMode(true);
2032
2128
  stdin.resume();
@@ -2039,7 +2135,7 @@ function terminalPicker(title, items2, checked = true) {
2039
2135
  stdin.setRawMode(false);
2040
2136
  stdin.pause();
2041
2137
  stdout.write("\x1B[?25h");
2042
- resolve15(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
2138
+ resolve18(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
2043
2139
  };
2044
2140
  stdin.on("keypress", onKey);
2045
2141
  });
@@ -2048,8 +2144,8 @@ function terminalPicker(title, items2, checked = true) {
2048
2144
  // src/commands/install-skill.ts
2049
2145
  var NAMES = AGENTS.map((a) => a.name).join(", ");
2050
2146
  var terminalChoose = () => process.stdin.isTTY && process.stdout.isTTY ? terminalPicker : void 0;
2051
- var skillFiles = () => readdirSync3(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
2052
- var skillIsCurrent = (dir, files) => files.every((f) => sameFile({ source: packageFile(`skills/codechart/${f}`), target: join13(dir, f) }));
2147
+ var skillFiles = () => readdirSync4(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
2148
+ var skillIsCurrent = (dir, files) => files.every((f) => sameFile({ source: packageFile(`skills/codechart/${f}`), target: join14(dir, f) }));
2053
2149
  var hasClaude = (agents) => agents.some((a) => a.name === "claude");
2054
2150
  var hasOpencode = (agents) => agents.some((a) => a.name === "opencode");
2055
2151
  async function chooseExtras(agents, opts) {
@@ -2088,7 +2184,7 @@ function installExtras(extras, agents, home, force, opts) {
2088
2184
  if (extras.reminder) {
2089
2185
  for (const a of agents) {
2090
2186
  if (!a.instructions) continue;
2091
- const file = join13(home, a.instructions);
2187
+ const file = join14(home, a.instructions);
2092
2188
  report("reminder", () => {
2093
2189
  const r = addReminder(file);
2094
2190
  return r === "present" ? `reminder already in ${file}` : `reminder ${r}: ${file}`;
@@ -2096,7 +2192,7 @@ function installExtras(extras, agents, home, force, opts) {
2096
2192
  }
2097
2193
  }
2098
2194
  if (extras.hook) {
2099
- const file = join13(home, ".claude", "settings.json");
2195
+ const file = join14(home, ".claude", "settings.json");
2100
2196
  report("hook", () => installClaudeHooks(file) === "added" ? `hook added: ${file}` : `hook already in ${file}`);
2101
2197
  }
2102
2198
  if (extras.plugin) {
@@ -2116,7 +2212,7 @@ function rememberOwn(installed, opts) {
2116
2212
  }
2117
2213
  }
2118
2214
  function installCopy(dir, who, files, force, opts) {
2119
- const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join13(dir, f) }));
2215
+ const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join14(dir, f) }));
2120
2216
  return installPairs(pairs, dir, who, () => isCodechartSkill(dir), force, opts);
2121
2217
  }
2122
2218
  function installSkillCommand(opts) {
@@ -2130,7 +2226,7 @@ function installSkillCommand(opts) {
2130
2226
  process.exitCode = 1;
2131
2227
  return;
2132
2228
  }
2133
- let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync6(join13(home, a.home))) : [];
2229
+ let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync6(join14(home, a.home))) : [];
2134
2230
  if (agents.length === 0 && o.dir === void 0) {
2135
2231
  opts.stderr(`codechart: no agent found in ${home}; use --agent <name> (${NAMES}) or --dir <path>
2136
2232
  `);
@@ -2163,11 +2259,11 @@ function installSkillCommand(opts) {
2163
2259
  const files = skillFiles();
2164
2260
  const groups = skillFolders(agents);
2165
2261
  for (const folder of new Set(agents.flatMap((a) => [a.skills, ...a.reads]))) {
2166
- if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join13(home, folder, "codechart", f)))) continue;
2262
+ if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join14(home, folder, "codechart", f)))) continue;
2167
2263
  groups.push({ folder, agents: agents.filter((a) => [a.skills, ...a.reads].includes(folder)) });
2168
2264
  }
2169
- const targets = groups.map((g) => ({ dir: join13(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", "), agents: g.agents }));
2170
- if (o.dir !== void 0) targets.push({ dir: join13(resolve4(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: YOUR_FOLDER, agents: [] });
2265
+ const targets = groups.map((g) => ({ dir: join14(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", "), agents: g.agents }));
2266
+ if (o.dir !== void 0) targets.push({ dir: join14(resolve4(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: YOUR_FOLDER, agents: [] });
2171
2267
  const installed = targets.filter((t) => installCopy(t.dir, t.who, files, o.force === true, opts));
2172
2268
  rememberOwn(installed, opts);
2173
2269
  const ready = new Set(installed.flatMap((t) => t.agents));
@@ -2180,7 +2276,7 @@ function installSkillCommand(opts) {
2180
2276
  import { execFileSync as execFileSync3, spawnSync } from "child_process";
2181
2277
  import { existsSync as existsSync7, realpathSync as realpathSync3 } from "fs";
2182
2278
  import { homedir as homedir3 } from "os";
2183
- import { dirname as dirname6, join as join14, resolve as resolve5, sep as sep2 } from "path";
2279
+ import { dirname as dirname6, join as join15, resolve as resolve5, sep as sep2 } from "path";
2184
2280
  import { Command as Command5 } from "commander";
2185
2281
  var spawnOptions = (command, platform = process.platform) => platform === "win32" && command === "npm" ? { shell: true, cwd: dirname6(process.execPath) } : { shell: false };
2186
2282
  var binary = (command) => command === "codechart" ? [process.execPath, [process.argv[1]]] : [command, []];
@@ -2194,7 +2290,7 @@ var defaultRunner = {
2194
2290
  };
2195
2291
  function installedBy(installDir, npmRoot) {
2196
2292
  const real = (p) => existsSync7(p) ? realpathSync3(p) : resolve5(p);
2197
- if (npmRoot && real(installDir) === real(join14(npmRoot, "codechart"))) return { npm: true };
2293
+ if (npmRoot && real(installDir) === real(join15(npmRoot, "codechart"))) return { npm: true };
2198
2294
  if (/[\\/]_npx[\\/]/.test(installDir)) return { npm: false, hint: "npx runs the newest codechart already; nothing to update" };
2199
2295
  if (installDir.includes(`${sep2}pnpm${sep2}`) || installDir.includes("/pnpm/")) return { npm: false, hint: "update it with: pnpm add -g codechart@latest" };
2200
2296
  if (installDir.includes(".bun")) return { npm: false, hint: "update it with: bun add -g codechart@latest" };
@@ -2206,7 +2302,7 @@ function refreshInstalls(home, opts) {
2206
2302
  const files = skillFiles();
2207
2303
  const folders2 = [...new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))];
2208
2304
  const dirs = [
2209
- ...folders2.map((folder) => ({ dir: join14(home, folder, "codechart"), who: AGENTS.filter((a) => [a.skills, ...a.reads].includes(folder)).map((a) => a.label).join(", ") })),
2305
+ ...folders2.map((folder) => ({ dir: join15(home, folder, "codechart"), who: AGENTS.filter((a) => [a.skills, ...a.reads].includes(folder)).map((a) => a.label).join(", ") })),
2210
2306
  ...skillDirs(readState(cacheDirOf(opts))).map((dir) => ({ dir, who: "your folder" }))
2211
2307
  ];
2212
2308
  for (const { dir, who } of dirs) {
@@ -2221,7 +2317,7 @@ function refreshInstalls(home, opts) {
2221
2317
  }
2222
2318
  for (const a of AGENTS) {
2223
2319
  if (!a.instructions) continue;
2224
- if (refreshReminder(join14(home, a.instructions)) === "updated") opts.stdout(`reminder updated: ${join14(home, a.instructions)}
2320
+ if (refreshReminder(join15(home, a.instructions)) === "updated") opts.stdout(`reminder updated: ${join15(home, a.instructions)}
2225
2321
  `);
2226
2322
  }
2227
2323
  const plugin = pluginFile(home, opts.env ?? process.env);
@@ -2306,7 +2402,7 @@ function findOnPath(env, platform = process.platform, usable = runnable(platform
2306
2402
  const dir = win ? raw.replace(/^"(.*)"$/, "$1") : raw;
2307
2403
  if (!dir) continue;
2308
2404
  for (const name of names) {
2309
- const file = (win ? win322 : posix).join(dir, name);
2405
+ const file = (win ? win323 : posix).join(dir, name);
2310
2406
  if (usable(file)) return file;
2311
2407
  }
2312
2408
  }
@@ -2333,7 +2429,7 @@ function skillProblem(a, dirs, seen, item) {
2333
2429
  return fresh.length ? item : { level: "bad", text: `skill: same copy as ${owner}`, same: true };
2334
2430
  }
2335
2431
  function skillItem(a, target2, home, files, opts, seen) {
2336
- const copies = [.../* @__PURE__ */ new Set([a.skills, ...a.reads])].map((f) => join15(home, f, "codechart")).filter(present);
2432
+ const copies = [.../* @__PURE__ */ new Set([a.skills, ...a.reads])].map((f) => join16(home, f, "codechart")).filter(present);
2337
2433
  const own = copies.filter(ours);
2338
2434
  const install = `codechart install-skill --agent ${a.name}`;
2339
2435
  const stale = own.filter((d) => !skillIsCurrent(d, files));
@@ -2350,11 +2446,11 @@ function skillItem(a, target2, home, files, opts, seen) {
2350
2446
  if (copies.length) {
2351
2447
  return skillProblem(a, copies, seen, { level: "bad", text: `skill: ${copies[0]} is not the codechart skill (left alone: move it aside first)`, fix: install });
2352
2448
  }
2353
- const dir = join15(home, target2, "codechart");
2449
+ const dir = join16(home, target2, "codechart");
2354
2450
  return skillProblem(a, [dir], seen, { level: "bad", text: `skill: missing (${dir})`, fix: install, run: () => void installCopy(dir, a.label, files, false, opts) });
2355
2451
  }
2356
2452
  function reminderItem(a, home, opts) {
2357
- const file = join15(home, a.instructions);
2453
+ const file = join16(home, a.instructions);
2358
2454
  const state = reminderState(file);
2359
2455
  if (state === "present") return { level: "ok", text: `reminder: ${file}` };
2360
2456
  const fix2 = `codechart install-skill --agent ${a.name} --reminder`;
@@ -2363,7 +2459,7 @@ function reminderItem(a, home, opts) {
2363
2459
  `) };
2364
2460
  }
2365
2461
  function hookItem(home, opts) {
2366
- const file = join15(home, ".claude", "settings.json");
2462
+ const file = join16(home, ".claude", "settings.json");
2367
2463
  let state;
2368
2464
  try {
2369
2465
  state = claudeHookEvents(file);
@@ -2417,7 +2513,7 @@ function cliSection(opts) {
2417
2513
  return { title: "codechart CLI", items: items2, first: true };
2418
2514
  }
2419
2515
  function runChecks(home, opts) {
2420
- const agents = AGENTS.filter((a) => existsSync8(join15(home, a.home)));
2516
+ const agents = AGENTS.filter((a) => existsSync8(join16(home, a.home)));
2421
2517
  const files = skillFiles();
2422
2518
  const folders2 = skillFolders(agents);
2423
2519
  const seen = /* @__PURE__ */ new Map();
@@ -2427,11 +2523,11 @@ function runChecks(home, opts) {
2427
2523
  }
2428
2524
 
2429
2525
  // src/commands/doctor-last.ts
2430
- import { join as join18 } from "path";
2526
+ import { join as join19 } from "path";
2431
2527
 
2432
2528
  // src/commands/hook-core.ts
2433
- import { lstatSync as lstatSync8, mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "fs";
2434
- import { join as join16 } from "path";
2529
+ import { lstatSync as lstatSync8, mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "fs";
2530
+ import { join as join17 } from "path";
2435
2531
 
2436
2532
  // src/commands/transcript.ts
2437
2533
  var DIAGRAM = /\*\*(Map|Flow)\*\*/;
@@ -2478,13 +2574,13 @@ function snapshot(root) {
2478
2574
  return files && { head: gitHead(root), files };
2479
2575
  }
2480
2576
  function prune(dir, now) {
2481
- for (const f of readdirSync4(dir)) {
2482
- const p = join16(dir, f);
2577
+ for (const f of readdirSync5(dir)) {
2578
+ const p = join17(dir, f);
2483
2579
  const st = lstatSync8(p);
2484
2580
  if (st.isFile() && now - st.mtimeMs > KEEP_DAYS * 864e5) unlinkSync3(p);
2485
2581
  }
2486
2582
  }
2487
- var nudge = (count3) => `This turn changed ${count3} 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.`;
2583
+ var nudge = (count4) => `This turn changed ${count4} 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.`;
2488
2584
  function saveSnapshot(dir, file, root, now) {
2489
2585
  const snap = snapshot(root);
2490
2586
  mkdirSync4(dir, { recursive: true, mode: 448 });
@@ -2514,20 +2610,20 @@ function judgeTurn(root, file, reply, used) {
2514
2610
  }
2515
2611
 
2516
2612
  // src/commands/hook-record.ts
2517
- import { mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync6 } from "fs";
2518
- import { join as join17 } from "path";
2613
+ import { mkdirSync as mkdirSync5, readdirSync as readdirSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync6 } from "fs";
2614
+ import { join as join18 } from "path";
2519
2615
  var MAX_FILES = 500;
2520
2616
  var SUFFIX = ".turn.json";
2521
- var turnsDir = (home) => join17(home, ".cache", "codechart", "turns");
2617
+ var turnsDir = (home) => join18(home, ".cache", "codechart", "turns");
2522
2618
  function writeRecord(dir, record2) {
2523
2619
  mkdirSync5(dir, { recursive: true, mode: 448 });
2524
2620
  const files = record2.files && record2.files.slice(0, MAX_FILES);
2525
- writeFileSync6(join17(dir, `${record2.session}${SUFFIX}`), JSON.stringify({ ...record2, files }), { mode: 384 });
2621
+ writeFileSync6(join18(dir, `${record2.session}${SUFFIX}`), JSON.stringify({ ...record2, files }), { mode: 384 });
2526
2622
  }
2527
2623
  var activity = (r) => [r.at, r.pendingAt, r.quietAt].reduce((m, t) => t && t > m ? t : m, "");
2528
2624
  function readRecord(dir, session) {
2529
2625
  try {
2530
- return JSON.parse(readFileSync5(join17(dir, `${session}${SUFFIX}`), "utf8"));
2626
+ return JSON.parse(readFileSync5(join18(dir, `${session}${SUFFIX}`), "utf8"));
2531
2627
  } catch {
2532
2628
  return void 0;
2533
2629
  }
@@ -2548,14 +2644,14 @@ function recordStop(dir, rec) {
2548
2644
  function latestRecord(dir, root) {
2549
2645
  let names;
2550
2646
  try {
2551
- names = readdirSync5(dir).filter((n) => n.endsWith(SUFFIX));
2647
+ names = readdirSync6(dir).filter((n) => n.endsWith(SUFFIX));
2552
2648
  } catch {
2553
2649
  return void 0;
2554
2650
  }
2555
2651
  let best;
2556
2652
  for (const name of names) {
2557
2653
  try {
2558
- const r = JSON.parse(readFileSync5(join17(dir, name), "utf8"));
2654
+ const r = JSON.parse(readFileSync5(join18(dir, name), "utf8"));
2559
2655
  if (r.root === root && typeof r.at === "string" && (!best || activity(r) > activity(best))) best = r;
2560
2656
  } catch {
2561
2657
  continue;
@@ -2594,7 +2690,7 @@ var attempt = (check) => {
2594
2690
  return false;
2595
2691
  }
2596
2692
  };
2597
- var hasClaudeHooks = (home) => attempt(() => claudeHookEvents(join18(home, ".claude", "settings.json")).ok.length === 2);
2693
+ var hasClaudeHooks = (home) => attempt(() => claudeHookEvents(join19(home, ".claude", "settings.json")).ok.length === 2);
2598
2694
  var hasOpencodePlugin = (home, opts) => attempt(() => ["current", "outdated"].includes(pluginState(pluginFile(home, opts.env ?? process.env))));
2599
2695
  function explainLast(cwd, home, opts) {
2600
2696
  const say = (line) => opts.stdout(`${line}
@@ -2777,7 +2873,7 @@ function parseDoc(text3, review2, now) {
2777
2873
  const warnings = [];
2778
2874
  const notes = [];
2779
2875
  let skipped = 0;
2780
- const existing = review2.notes.filter((n) => n.state === "pending" && !n.target);
2876
+ const existing2 = review2.notes.filter((n) => n.state === "pending" && !n.target);
2781
2877
  let next = lastNoteNumber(review2.notes);
2782
2878
  let node;
2783
2879
  let anchor;
@@ -2807,7 +2903,7 @@ function parseDoc(text3, review2, now) {
2807
2903
  return;
2808
2904
  }
2809
2905
  const note2 = { id: "", node: node.id, ...node.rev && { rev: node.rev }, ...anchor && { anchor }, kind: KIND[m[1] ?? ""], body, state: "pending", at: now.toISOString() };
2810
- const same = existing.find((e) => sameNote(e, note2) && !notes.includes(e));
2906
+ const same = existing2.find((e) => sameNote(e, note2) && !notes.includes(e));
2811
2907
  notes.push(same ?? { ...note2, id: `n${++next}` });
2812
2908
  });
2813
2909
  return { notes, warnings, skipped };
@@ -2975,7 +3071,7 @@ async function importReview(opts) {
2975
3071
  return result.review;
2976
3072
  });
2977
3073
  const { added, outdated } = result;
2978
- const n = (count3) => `${count3} note${count3 === 1 ? "" : "s"}`;
3074
+ const n = (count4) => `${count4} note${count4 === 1 ? "" : "s"}`;
2979
3075
  opts.stderr(
2980
3076
  added === 0 ? "Nothing new to import: these notes are already saved.\n" : sanitizeText(`\u2714 Imported ${n(added)} into "${changeTitle(saved)}"${outdated ? ` (${outdated} outdated: the map changed since the page was drawn)` : ""}
2981
3077
  `)
@@ -3034,7 +3130,7 @@ function feedbackCommand(opts) {
3034
3130
  // src/commands/hook.ts
3035
3131
  import { closeSync as closeSync3, fstatSync as fstatSync2, openSync as openSync3, readSync as readSync2 } from "fs";
3036
3132
  import { homedir as homedir5 } from "os";
3037
- import { join as join19 } from "path";
3133
+ import { join as join20 } from "path";
3038
3134
  import { Argument, Command as Command8 } from "commander";
3039
3135
  var MAX_INPUT = 1024 * 1024;
3040
3136
  var MAX_TRANSCRIPT_TAIL = 8 * 1024 * 1024;
@@ -3094,7 +3190,7 @@ async function runHook(event, opts) {
3094
3190
  const path3 = input.transcript_path;
3095
3191
  let scanned;
3096
3192
  const scan = () => scanned ??= typeof path3 === "string" ? scanTurn(readTail(path3, MAX_TRANSCRIPT_TAIL)) : void 0;
3097
- const turn = { root, dir, file: join19(dir, `${id}.json`), input, scan };
3193
+ const turn = { root, dir, file: join20(dir, `${id}.json`), input, scan };
3098
3194
  const now = opts.now?.() ?? /* @__PURE__ */ new Date();
3099
3195
  if (event === "prompt") {
3100
3196
  try {
@@ -3120,7 +3216,7 @@ function hookCommand(opts) {
3120
3216
  }
3121
3217
 
3122
3218
  // src/commands/init.ts
3123
- import { join as join20 } from "path";
3219
+ import { join as join21 } from "path";
3124
3220
  import { Command as Command9 } from "commander";
3125
3221
  function initCommand(opts) {
3126
3222
  return new Command9("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
@@ -3130,15 +3226,15 @@ function initCommand(opts) {
3130
3226
  process.exitCode = 1;
3131
3227
  return;
3132
3228
  }
3133
- copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join20(root, ".codechart.yaml") }], o.force === true, opts);
3229
+ copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join21(root, ".codechart.yaml") }], o.force === true, opts);
3134
3230
  });
3135
3231
  }
3136
3232
 
3137
3233
  // src/commands/pr-sync.ts
3138
3234
  import { randomUUID } from "crypto";
3139
- import { mkdtempSync, readFileSync as readFileSync8, rmSync as rmSync4 } from "fs";
3140
- import { tmpdir } from "os";
3141
- import { join as join25 } from "path";
3235
+ import { mkdtempSync as mkdtempSync3, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
3236
+ import { tmpdir as tmpdir3 } from "os";
3237
+ import { join as join28 } from "path";
3142
3238
  import { Command as Command11 } from "commander";
3143
3239
 
3144
3240
  // src/render/terminal/check-lines.ts
@@ -5370,8 +5466,8 @@ function mapSnapshot(spec, previews, range, drift, ghostLinks = []) {
5370
5466
  return { kind: "map", title: clean2(spec.title), nodes, ...range && { range }, ...extrasOf(drift, { edges: [...spec.edges, ...ghostLinks], gaps: spec.gaps, omitted: spec.omitted }) };
5371
5467
  }
5372
5468
  var hash = (v) => createHash4("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 12);
5373
- function stepRev(spec, step2, snippets) {
5374
- const { id, label, status, type, source, match } = step2;
5469
+ function stepRev(spec, step3, snippets) {
5470
+ const { id, label, status, type, source, match } = step3;
5375
5471
  const next = spec.links.flatMap((l, i) => l.from === id ? [{ to: l.to, label: l.label, source: l.source, match: l.match, planned: l.planned, removed: l.removed, code: snippets.links[i] }] : []);
5376
5472
  return hash({ label, status, type, source, match, code: snippets.steps.get(id), next });
5377
5473
  }
@@ -5511,7 +5607,7 @@ function flowFacts(spec) {
5511
5607
  brandNew,
5512
5608
  removedStep,
5513
5609
  existsNow,
5514
- typeOf: (step2) => step2.type ?? inferType(counts2.get(step2.id) ?? 0),
5610
+ typeOf: (step3) => step3.type ?? inferType(counts2.get(step3.id) ?? 0),
5515
5611
  branchesNow: (id) => spec.kind === "plan" && (nowOut.get(id)?.length ?? 0) >= 2 && (live.get(id)?.length ?? 0) < 2
5516
5612
  };
5517
5613
  }
@@ -5523,14 +5619,14 @@ function stepStatusIssue(kind2, status) {
5523
5619
  }
5524
5620
  function stepIssues(spec, issue) {
5525
5621
  const seen = /* @__PURE__ */ new Set();
5526
- spec.steps.forEach((step2, i) => {
5527
- if (seen.has(step2.id)) issue(["steps", i, "id"], `duplicate "${step2.id}"`);
5528
- seen.add(step2.id);
5529
- for (const m of labelIssues(step2.label, "step", "source", "migration: add invoices")) issue(["steps", i, "label"], m);
5530
- const status = stepStatusIssue(spec.kind, step2.status);
5622
+ spec.steps.forEach((step3, i) => {
5623
+ if (seen.has(step3.id)) issue(["steps", i, "id"], `duplicate "${step3.id}"`);
5624
+ seen.add(step3.id);
5625
+ for (const m of labelIssues(step3.label, "step", "source", "migration: add invoices")) issue(["steps", i, "label"], m);
5626
+ const status = stepStatusIssue(spec.kind, step3.status);
5531
5627
  if (status) issue(["steps", i, "status"], status);
5532
- if (step2.status !== "planned" && !step2.source) issue(["steps", i, "source"], `required for a non-planned step ${ANCHOR}`);
5533
- for (const [field, m] of anchorIssues(step2)) issue(["steps", i, field], m);
5628
+ if (step3.status !== "planned" && !step3.source) issue(["steps", i, "source"], `required for a non-planned step ${ANCHOR}`);
5629
+ for (const [field, m] of anchorIssues(step3)) issue(["steps", i, field], m);
5534
5630
  });
5535
5631
  }
5536
5632
  function startIssues(spec, facts, issue) {
@@ -5574,21 +5670,21 @@ function shapeIssues(spec, facts, issue) {
5574
5670
  const needLabels = (linkIdx) => {
5575
5671
  for (const li of linkIdx) if (!spec.links[li].label) issue(["links", li, "label"], "required on a link leaving a decision");
5576
5672
  };
5577
- spec.steps.forEach((step2, i) => {
5578
- const count3 = (facts.live.get(step2.id) ?? []).length;
5579
- if (step2.type === void 0 && step2.label.trim().endsWith("?") && count3 < 2 && !facts.branchesNow(step2.id)) {
5580
- issue(["steps", i, "type"], `label ends in "?", so this is a decision: it needs at least 2 outgoing links, has ${count3}`);
5673
+ spec.steps.forEach((step3, i) => {
5674
+ const count4 = (facts.live.get(step3.id) ?? []).length;
5675
+ if (step3.type === void 0 && step3.label.trim().endsWith("?") && count4 < 2 && !facts.branchesNow(step3.id)) {
5676
+ issue(["steps", i, "type"], `label ends in "?", so this is a decision: it needs at least 2 outgoing links, has ${count4}`);
5581
5677
  return;
5582
5678
  }
5583
- const type = facts.typeOf(step2);
5584
- if (type === "end" && count3 > 0) issue(["steps", i, "type"], `an end has no outgoing links, has ${count3}`);
5585
- if (type === "step" && count3 > 1) issue(["steps", i, "type"], `has ${count3} outgoing links; make it a decision with labelled branches`);
5679
+ const type = facts.typeOf(step3);
5680
+ if (type === "end" && count4 > 0) issue(["steps", i, "type"], `an end has no outgoing links, has ${count4}`);
5681
+ if (type === "step" && count4 > 1) issue(["steps", i, "type"], `has ${count4} outgoing links; make it a decision with labelled branches`);
5586
5682
  if (type !== "decision") {
5587
- if (facts.branchesNow(step2.id)) needLabels(facts.nowOut.get(step2.id) ?? []);
5683
+ if (facts.branchesNow(step3.id)) needLabels(facts.nowOut.get(step3.id) ?? []);
5588
5684
  return;
5589
5685
  }
5590
- if (count3 < 2) issue(["steps", i, "id"], `decision "${step2.id}" needs at least 2 outgoing links, has ${count3}`);
5591
- needLabels(facts.outgoing.get(step2.id) ?? []);
5686
+ if (count4 < 2) issue(["steps", i, "id"], `decision "${step3.id}" needs at least 2 outgoing links, has ${count4}`);
5687
+ needLabels(facts.outgoing.get(step3.id) ?? []);
5592
5688
  });
5593
5689
  }
5594
5690
  function reachabilityIssues(spec, facts, issue) {
@@ -5600,8 +5696,8 @@ function reachabilityIssues(spec, facts, issue) {
5600
5696
  if (!isRemovedLink(spec, spec.links[li])) reached.add(spec.links[li].to);
5601
5697
  }
5602
5698
  }
5603
- spec.steps.forEach((step2, i) => {
5604
- if (step2.status !== "removed" && !reached.has(step2.id)) issue(["steps", i], "not reachable from start");
5699
+ spec.steps.forEach((step3, i) => {
5700
+ if (step3.status !== "removed" && !reached.has(step3.id)) issue(["steps", i], "not reachable from start");
5605
5701
  });
5606
5702
  }
5607
5703
  var flowSchema = flowObject.superRefine((spec, ctx) => {
@@ -5618,8 +5714,8 @@ function validateFlowSpec(input) {
5618
5714
  const result = flowSchema.safeParse(input);
5619
5715
  if (!result.success) return { ok: false, errors: formatIssues(result.error) };
5620
5716
  const counts2 = outgoingCounts(result.data, result.data.links);
5621
- const steps2 = result.data.steps.map((s) => ({ ...s, type: s.type ?? inferType(counts2.get(s.id) ?? 0) }));
5622
- return { ok: true, spec: { ...result.data, diagram: "flow", steps: steps2 } };
5717
+ const steps3 = result.data.steps.map((s) => ({ ...s, type: s.type ?? inferType(counts2.get(s.id) ?? 0) }));
5718
+ return { ok: true, spec: { ...result.data, diagram: "flow", steps: steps3 } };
5623
5719
  }
5624
5720
  function flowJsonSchema() {
5625
5721
  return z5.toJSONSchema(flowSchema, { io: "input" });
@@ -5745,9 +5841,9 @@ function driftNote(drift) {
5745
5841
  if (!drift) return "";
5746
5842
  if (!drift.items.length) return '<span class="check">built as planned \u2713</span>';
5747
5843
  const n = drift.items.length;
5748
- const count3 = `\u25C6 ${n} ${n === 1 ? "difference" : "differences"} from the plan`;
5844
+ const count4 = `\u25C6 ${n} ${n === 1 ? "difference" : "differences"} from the plan`;
5749
5845
  const bad2 = drift.unexplained ? ` <span class="bad">\xB7 ${drift.unexplained} without a reason</span>` : "";
5750
- return `<button type="button" class="check warn" aria-controls="page-info" title="Show how the build differs from the plan">${count3}${bad2}</button>`;
5846
+ return `<button type="button" class="check warn" aria-controls="page-info" title="Show how the build differs from the plan">${count4}${bad2}</button>`;
5751
5847
  }
5752
5848
  var ICON = { missing: "\u2212", unplanned: "+", different: "~" };
5753
5849
  var row2 = (label, value, cls = "") => `<span class="drift-l">${label}</span><div class="drift-v${cls}">${value}</div>`;
@@ -5878,7 +5974,7 @@ function renderDiagramPage(p) {
5878
5974
  }
5879
5975
 
5880
5976
  // src/render/flow/states.ts
5881
- var isAltered = (step2) => step2.status === "planned" && step2.source !== void 0;
5977
+ var isAltered = (step3) => step3.status === "planned" && step3.source !== void 0;
5882
5978
  function hasFlowNowAfter(spec) {
5883
5979
  if (spec.kind !== "plan") return false;
5884
5980
  return spec.steps.some((s) => s.status === "removed" || isAltered(s)) || spec.links.some((l) => l.removed === true);
@@ -5890,7 +5986,7 @@ var FLOW_SIDE_KEY = {
5890
5986
  ],
5891
5987
  after: [{ text: "dashed: planned", tone: "cfg" }]
5892
5988
  };
5893
- var stepOn = (side, step2) => side === "now" ? step2.status !== "planned" || isAltered(step2) : step2.status !== "removed";
5989
+ var stepOn = (side, step3) => side === "now" ? step3.status !== "planned" || isAltered(step3) : step3.status !== "removed";
5894
5990
  function linkOn(side, spec, link, byId) {
5895
5991
  const ends = [byId.get(link.from), byId.get(link.to)];
5896
5992
  if (!ends.every((s) => stepOn(side, s))) return false;
@@ -5913,13 +6009,13 @@ var SHAPE = {
5913
6009
  end: { w: 180, chars: 26 },
5914
6010
  decision: { w: 220, chars: 18 }
5915
6011
  };
5916
- function sizeOf(step2) {
5917
- const { w, chars } = SHAPE[step2.type];
5918
- const lines = wrapText(step2.label, chars, MAX_LINES);
5919
- const badge = step2.status === "existing" ? void 0 : step2.status;
6012
+ function sizeOf(step3) {
6013
+ const { w, chars } = SHAPE[step3.type];
6014
+ const lines = wrapText(step3.label, chars, MAX_LINES);
6015
+ const badge = step3.status === "existing" ? void 0 : step3.status;
5920
6016
  const content = lines.length * LINE_HEIGHT2 + (badge ? BADGE_HEIGHT : 0);
5921
- const h = step2.type === "decision" ? 2 * content + 2 * PAD : content + 2 * PAD;
5922
- return { id: step2.id, w, h, lines, ...badge ? { badge } : {} };
6017
+ const h = step3.type === "decision" ? 2 * content + 2 * PAD : content + 2 * PAD;
6018
+ return { id: step3.id, w, h, lines, ...badge ? { badge } : {} };
5923
6019
  }
5924
6020
  function clipToDiamond(p, n) {
5925
6021
  const cx = n.x + n.w / 2;
@@ -5968,12 +6064,12 @@ async function layoutFlow(spec) {
5968
6064
  });
5969
6065
  const byId = new Map(nodes.map((n) => [n.id, n]));
5970
6066
  const decisions = new Set(spec.steps.filter((s) => s.type === "decision").map((s) => s.id));
5971
- const clip3 = (p, id) => decisions.has(id) ? clipToDiamond(p, byId.get(id)) : p;
6067
+ const clip4 = (p, id) => decisions.has(id) ? clipToDiamond(p, byId.get(id)) : p;
5972
6068
  const laidOut = new Map((root.edges ?? []).map((e) => [e.id, e]));
5973
6069
  const out = spec.links.map((link, i) => {
5974
6070
  const e = laidOut.get(`e${i}`);
5975
6071
  const sec = e?.sections?.[0];
5976
- const points = sec ? [clip3(sec.startPoint, link.from), ...sec.bendPoints ?? [], clip3(sec.endPoint, link.to)] : [];
6072
+ const points = sec ? [clip4(sec.startPoint, link.from), ...sec.bendPoints ?? [], clip4(sec.endPoint, link.to)] : [];
5977
6073
  const lab = e?.labels?.[0];
5978
6074
  return {
5979
6075
  points,
@@ -6004,8 +6100,8 @@ aside .more{color:var(--muted);font-size:11px;margin:0}
6004
6100
  aside .branches{padding-left:0;list-style:none}
6005
6101
  aside .branches li{margin:0 0 10px}
6006
6102
  `;
6007
- function shape(step2, b) {
6008
- if (step2.type === "decision") {
6103
+ function shape(step3, b) {
6104
+ if (step3.type === "decision") {
6009
6105
  const cx = b.x + b.w / 2;
6010
6106
  const cy = b.y + b.h / 2;
6011
6107
  const pts = [
@@ -6016,17 +6112,17 @@ function shape(step2, b) {
6016
6112
  ];
6017
6113
  return `<polygon class="shape" points="${pts.map(([x, y]) => `${num(x)},${num(y)}`).join(" ")}"/>`;
6018
6114
  }
6019
- const rx = step2.type === "end" ? b.h / 2 : 4;
6115
+ const rx = step3.type === "end" ? b.h / 2 : 4;
6020
6116
  return `<rect class="shape" x="${num(b.x)}" y="${num(b.y)}" width="${num(b.w)}" height="${num(b.h)}" rx="${num(rx)}"/>`;
6021
6117
  }
6022
- function renderStep(step2, b, flag, side, { drift, ghost = false, rev } = {}) {
6118
+ function renderStep(step3, b, flag, side, { drift, ghost = false, rev } = {}) {
6023
6119
  const flagged2 = flag !== "";
6024
6120
  const cx = num(b.x + b.w / 2);
6025
6121
  const content = b.lines.length * LINE_HEIGHT2 + (b.badge ? BADGE_HEIGHT : 0);
6026
6122
  let y = b.y + (b.h - content) / 2;
6027
6123
  let text3 = "";
6028
- const changing = side === "now" && isAltered(step2);
6029
- const status = changing ? "changed" : step2.status;
6124
+ const changing = side === "now" && isAltered(step3);
6125
+ const status = changing ? "changed" : step3.status;
6030
6126
  if (b.badge) {
6031
6127
  text3 += `<text class="badge" x="${cx}" y="${num(y + 9)}">${esc(ghost ? "not built" : changing ? "will change" : b.badge)}</text>`;
6032
6128
  y += BADGE_HEIGHT;
@@ -6035,7 +6131,7 @@ function renderStep(step2, b, flag, side, { drift, ghost = false, rev } = {}) {
6035
6131
  text3 += `<text class="label" x="${cx}" y="${num(y + 11)}">${esc(l)}</text>`;
6036
6132
  y += LINE_HEIGHT2;
6037
6133
  }
6038
- return `<g class="node type-${step2.type} status-${status}${ghost ? " ghost" : ""}" data-id="${esc(step2.id)}" data-label="${esc(step2.label)}" data-status="${step2.status}"${rev ? ` data-rev="${rev}"` : ""} tabindex="0" role="button" aria-label="${esc(`${step2.label} (${step2.status} ${step2.type}${flagged2 ? ", doesn't match the code" : ""}${drift ? `, ${drift.kind === "missing" ? "in the plan, not built" : "differs from the plan"}` : ""})`)}">` + flag + shape(step2, b) + text3 + (ghost ? "" : tickSvg(b.x, b.y)) + (flagged2 ? flagMark(b.x + b.w, b.y) : "") + (drift ? driftMark(drift, b.x + b.w, b.y + b.h + 8) : "") + `</g>`;
6134
+ return `<g class="node type-${step3.type} status-${status}${ghost ? " ghost" : ""}" data-id="${esc(step3.id)}" data-label="${esc(step3.label)}" data-status="${step3.status}"${rev ? ` data-rev="${rev}"` : ""} tabindex="0" role="button" aria-label="${esc(`${step3.label} (${step3.status} ${step3.type}${flagged2 ? ", doesn't match the code" : ""}${drift ? `, ${drift.kind === "missing" ? "in the plan, not built" : "differs from the plan"}` : ""})`)}">` + flag + shape(step3, b) + text3 + (ghost ? "" : tickSvg(b.x, b.y)) + (flagged2 ? flagMark(b.x + b.w, b.y) : "") + (drift ? driftMark(drift, b.x + b.w, b.y + b.h + 8) : "") + `</g>`;
6039
6135
  }
6040
6136
  function renderLink(link, e, tone, ends, ghost = false) {
6041
6137
  return renderEdgeSvg({
@@ -6071,20 +6167,20 @@ function snippetHtml(s) {
6071
6167
  return `<div class="path">${pathHtml(s.source)}</div><pre class="snippet"><code>${code}</code></pre>${more}`;
6072
6168
  }
6073
6169
  var tag = (status) => `<span class="tag tag-${esc(status)}">${esc(status)}</span>`;
6074
- function stepPanel(spec, step2, snippets, byId, check, mark3) {
6170
+ function stepPanel(spec, step3, snippets, byId, check, mark3) {
6075
6171
  const ghost = mark3?.ghost ?? false;
6076
- let out = panelTitle(step2.id, step2.label, !ghost);
6077
- out += `<div class="status">${ghost ? '<span class="tag">not built</span>' : tag(step2.status)} ${esc(step2.type)}</div>`;
6078
- out += mismatchNote(check, step2.id);
6079
- const snip = snippets.steps.get(step2.id);
6080
- if (step2.status === "planned") {
6172
+ let out = panelTitle(step3.id, step3.label, !ghost);
6173
+ out += `<div class="status">${ghost ? '<span class="tag">not built</span>' : tag(step3.status)} ${esc(step3.type)}</div>`;
6174
+ out += mismatchNote(check, step3.id);
6175
+ const snip = snippets.steps.get(step3.id);
6176
+ if (step3.status === "planned") {
6081
6177
  out += `<p class="planned-note">${snip ? "Planned change to the code below." : "Planned: not in the code yet."}</p>`;
6082
6178
  }
6083
- if (step2.status === "removed") out += '<p class="removed-note">Removed by the plan.</p>';
6179
+ if (step3.status === "removed") out += '<p class="removed-note">Removed by the plan.</p>';
6084
6180
  if (snip) out += snippetHtml(snip);
6085
- else if (step2.source) out += `<div class="path">${esc(step2.source)}</div>`;
6181
+ else if (step3.source) out += `<div class="path">${esc(step3.source)}</div>`;
6086
6182
  out += driftSection(mark3?.drift, ghost);
6087
- const next = spec.links.map((l, i) => ({ l, i })).filter(({ l }) => l.from === step2.id);
6183
+ const next = spec.links.map((l, i) => ({ l, i })).filter(({ l }) => l.from === step3.id);
6088
6184
  if (next.length) {
6089
6185
  const items2 = next.map(({ l, i }) => {
6090
6186
  const target2 = byId.get(l.to)?.label ?? l.to;
@@ -6099,8 +6195,8 @@ function stepPanel(spec, step2, snippets, byId, check, mark3) {
6099
6195
  out += `<h3>Next</h3><ul class="branches">${items2.join("")}</ul>`;
6100
6196
  }
6101
6197
  const links2 = spec.links.map((l) => ({ from: l.from, to: l.to, label: l.label }));
6102
- const relations = relationsHtml(relationsOf(step2.id, links2, (id) => byId.get(id)?.label ?? id));
6103
- return `<template class="card-panel" data-for="${esc(step2.id)}">${panelShell(out, relations)}</template>`;
6198
+ const relations = relationsHtml(relationsOf(step3.id, links2, (id) => byId.get(id)?.label ?? id));
6199
+ return `<template class="card-panel" data-for="${esc(step3.id)}">${panelShell(out, relations)}</template>`;
6104
6200
  }
6105
6201
  function pageInfo(spec, anyPlanned, sides2, check, ghosts, now) {
6106
6202
  const planned = anyPlanned ? '<p class="planned-note">Dashed steps and arrows are planned: not in the code yet.</p>' : "";
@@ -6438,8 +6534,8 @@ ${JSON.stringify(spec).replace(/</g, "\\u003c").replace(/>/g, "\\u003e")}
6438
6534
  -->`;
6439
6535
  var imageHref = (url) => encodeURI(url).replace(/[()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
6440
6536
  function prBlock(spec, check, imageUrl) {
6441
- const count3 = (s) => spec.nodes.filter((n) => n.status === s).length;
6442
- const counts2 = [`${spec.nodes.length} nodes`, `${count3("new")} new`, `${count3("changed")} changed`, ...count3("removed") ? [`${count3("removed")} removed`] : []].join(" \xB7 ");
6537
+ const count4 = (s) => spec.nodes.filter((n) => n.status === s).length;
6538
+ const counts2 = [`${spec.nodes.length} nodes`, `${count4("new")} new`, `${count4("changed")} changed`, ...count4("removed") ? [`${count4("removed")} removed`] : []].join(" \xB7 ");
6443
6539
  const url = imageHref(imageUrl);
6444
6540
  const nodes = [...spec.nodes].sort((a, b) => STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status));
6445
6541
  const parts = [
@@ -6577,7 +6673,7 @@ function reviewFromEnv(env, cwd, fetchFn = fetch) {
6577
6673
  }
6578
6674
 
6579
6675
  // src/commands/render.ts
6580
- import { basename as basename3, dirname as dirname8, join as join24, resolve as resolve14 } from "path";
6676
+ import { basename as basename3, dirname as dirname9, join as join27, resolve as resolve17 } from "path";
6581
6677
  import { Command as Command10, Option as Option3 } from "commander";
6582
6678
 
6583
6679
  // src/render/check.ts
@@ -6585,7 +6681,7 @@ import { relative as relative3, resolve as resolve10, sep as sep4 } from "path";
6585
6681
 
6586
6682
  // src/render/flow/anchors.ts
6587
6683
  import { realpathSync as realpathSync4, statSync as statSync3 } from "fs";
6588
- import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve7, sep as sep3 } from "path";
6684
+ import { isAbsolute as isAbsolute4, relative as relative2, resolve as resolve7, sep as sep3 } from "path";
6589
6685
 
6590
6686
  // src/render/clip.ts
6591
6687
  var MAX_CHARS2 = 300;
@@ -6595,7 +6691,7 @@ var clip2 = (l) => l.length > MAX_CHARS2 ? `${l.slice(0, MAX_CHARS2)}\u2026` : l
6595
6691
  var SNIPPET_MAX_LINES = 15;
6596
6692
  var MAX_BYTES3 = 5 * 1024 * 1024;
6597
6693
  var MAX_TOTAL_BYTES = 25 * 1024 * 1024;
6598
- var escapes = (rel) => rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute3(rel);
6694
+ var escapes = (rel) => rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute4(rel);
6599
6695
  var inGit = (rel) => rel.split(sep3).some((s) => s.toLowerCase() === ".git");
6600
6696
  var toLines = (text3) => {
6601
6697
  const lines = text3.split(/\r?\n/);
@@ -6673,7 +6769,7 @@ function anchorContext(root, at3, cwd) {
6673
6769
  };
6674
6770
  }
6675
6771
  function refused(path3, rel) {
6676
- if (isAbsolute3(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
6772
+ if (isAbsolute4(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
6677
6773
  if (inGit(rel)) return { error: `${path3} is inside .git` };
6678
6774
  return void 0;
6679
6775
  }
@@ -6706,7 +6802,7 @@ function present2(c, path3) {
6706
6802
  }
6707
6803
  function withCwd(c, path3, get, missing) {
6708
6804
  const direct = get(path3);
6709
- const outside2 = !isAbsolute3(path3) && escapes(relative2(c.root, resolve7(c.root, path3)));
6805
+ const outside2 = !isAbsolute4(path3) && escapes(relative2(c.root, resolve7(c.root, path3)));
6710
6806
  if (c.cwd && (missing(direct) || outside2)) {
6711
6807
  const rel = relative2(c.root, resolve7(c.cwd, path3));
6712
6808
  if (rel !== "" && !escapes(rel)) {
@@ -6732,7 +6828,7 @@ function locate(c, path3) {
6732
6828
  var MAX_LISTED_FILES = 2e5;
6733
6829
  function likelyPath(c, path3) {
6734
6830
  const slashed = path3.replaceAll("\\", "/");
6735
- if (isAbsolute3(path3) || slashed.split("/").includes("..")) return "";
6831
+ if (isAbsolute4(path3) || slashed.split("/").includes("..")) return "";
6736
6832
  const tail = `/${slashed.replace(/^(\.\/)+/, "")}`;
6737
6833
  if (!c.listing) {
6738
6834
  try {
@@ -6777,7 +6873,7 @@ function resolveAnchor(source, match, c) {
6777
6873
  }
6778
6874
  };
6779
6875
  }
6780
- function indexList(group, idx) {
6876
+ function indexList(group2, idx) {
6781
6877
  const parts = [];
6782
6878
  for (let i = 0; i < idx.length; ) {
6783
6879
  let j = i;
@@ -6786,7 +6882,7 @@ function indexList(group, idx) {
6786
6882
  else for (let k = i; k <= j; k++) parts.push(String(idx[k]));
6787
6883
  i = j + 1;
6788
6884
  }
6789
- return `${group}[${parts.join(",")}].source`;
6885
+ return `${group2}[${parts.join(",")}].source`;
6790
6886
  }
6791
6887
  function checkFlowAnchors(spec, root, at3, cwd) {
6792
6888
  const ctx = anchorContext(root, at3, cwd);
@@ -6794,7 +6890,7 @@ function checkFlowAnchors(spec, root, at3, cwd) {
6794
6890
  const snippets = { steps: /* @__PURE__ */ new Map(), links: {} };
6795
6891
  let checked = 0;
6796
6892
  const gone = /* @__PURE__ */ new Map();
6797
- const check = (group, i, { source, match }, store) => {
6893
+ const check = (group2, i, { source, match }, store) => {
6798
6894
  if (!source) return;
6799
6895
  const r = resolveAnchor(source, match, ctx);
6800
6896
  if (!("error" in r)) {
@@ -6805,18 +6901,18 @@ function checkFlowAnchors(spec, root, at3, cwd) {
6805
6901
  if (r.missing) {
6806
6902
  const g = gone.get(r.missing.path) ?? { detail: r.missing.detail, at: [], uses: [] };
6807
6903
  g.at.push(errors.length);
6808
- g.uses.push({ group, i });
6904
+ g.uses.push({ group: group2, i });
6809
6905
  gone.set(r.missing.path, g);
6810
6906
  }
6811
- errors.push(`${group}[${i}].${r.field ?? "source"}: ${r.error}`);
6907
+ errors.push(`${group2}[${i}].${r.field ?? "source"}: ${r.error}`);
6812
6908
  };
6813
- spec.steps.forEach((step2, i) => check("steps", i, step2, (s) => snippets.steps.set(step2.id, s)));
6909
+ spec.steps.forEach((step3, i) => check("steps", i, step3, (s) => snippets.steps.set(step3.id, s)));
6814
6910
  spec.links.forEach((link, i) => check("links", i, link, (s) => snippets.links[i] = s));
6815
6911
  for (const [path3, g] of gone) {
6816
6912
  if (g.uses.length < 2) continue;
6817
- const used = ["steps", "links"].flatMap((group) => {
6818
- const idx = g.uses.filter((u) => u.group === group).map((u) => u.i);
6819
- return idx.length ? [indexList(group, idx)] : [];
6913
+ const used = ["steps", "links"].flatMap((group2) => {
6914
+ const idx = g.uses.filter((u) => u.group === group2).map((u) => u.i);
6915
+ return idx.length ? [indexList(group2, idx)] : [];
6820
6916
  });
6821
6917
  errors[g.at[0]] = `${path3}: ${g.detail}; used by ${used.join(", ")}`;
6822
6918
  for (const k of g.at.slice(1)) errors[k] = void 0;
@@ -6978,10 +7074,10 @@ function defaultWidth(stdout = process.stdout, env = process.env) {
6978
7074
  return Number.isFinite(fromEnv) && fromEnv > 0 && fromEnv <= MAX_ENV_WIDTH ? fromEnv : NOT_TTY_WIDTH;
6979
7075
  }
6980
7076
  function footer(spec, hidden, { width, htmlPath, check }, keyLine) {
6981
- const count3 = (status) => spec.nodes.filter((n) => n.status === status).length;
6982
- const removed = count3("removed") > 0 ? ` \xB7 ${count3("removed")} removed` : "";
7077
+ const count4 = (status) => spec.nodes.filter((n) => n.status === status).length;
7078
+ const removed = count4("removed") > 0 ? ` \xB7 ${count4("removed")} removed` : "";
6983
7079
  const lines = [
6984
- countLines(`${spec.nodes.length} nodes \xB7 ${count3("new")} new \xB7 ${count3("changed")} changed${removed} \xB7 ${count3("config")} config`, check, width)
7080
+ countLines(`${spec.nodes.length} nodes \xB7 ${count4("new")} new \xB7 ${count4("changed")} changed${removed} \xB7 ${count4("config")} config`, check, width)
6985
7081
  ];
6986
7082
  if (keyLine) lines.push(truncate(KEY2, width));
6987
7083
  if (spec.gaps?.length) lines.push(wrapItems("gaps: ", spec.gaps.map(flat), width));
@@ -7039,33 +7135,33 @@ function walkFlow(spec, budget) {
7039
7135
  }
7040
7136
  return { kind: "cut", hidden, via };
7041
7137
  };
7042
- const ref = (step2, via) => {
7043
- if (queue.includes(step2.id)) return { kind: "ref", step: step2, via };
7044
- if (!take(step2.id)) return cut2(step2.id, via);
7045
- queue.push(step2.id);
7046
- return { kind: "ref", step: step2, via };
7138
+ const ref = (step3, via) => {
7139
+ if (queue.includes(step3.id)) return { kind: "ref", step: step3, via };
7140
+ if (!take(step3.id)) return cut2(step3.id, via);
7141
+ queue.push(step3.id);
7142
+ return { kind: "ref", step: step3, via };
7047
7143
  };
7048
7144
  const chain = (first, firstPaid) => {
7049
7145
  const items2 = [];
7050
- let step2 = first;
7146
+ let step3 = first;
7051
7147
  let via;
7052
7148
  for (let paid = firstPaid; ; paid = false) {
7053
- if (!paid && !take(step2.id)) return { items: [...items2, cut2(step2.id, via)] };
7054
- const links2 = out.get(step2.id) ?? [];
7055
- if (step2.type === "decision" || links2.length > 1) {
7056
- return { items: items2, branch: { head: step2, arms: links2.map((link) => ({ link, chain: arm(link.to) })) } };
7149
+ if (!paid && !take(step3.id)) return { items: [...items2, cut2(step3.id, via)] };
7150
+ const links2 = out.get(step3.id) ?? [];
7151
+ if (step3.type === "decision" || links2.length > 1) {
7152
+ return { items: items2, branch: { head: step3, arms: links2.map((link) => ({ link, chain: arm(link.to) })) } };
7057
7153
  }
7058
- items2.push({ kind: "step", step: step2, via });
7154
+ items2.push({ kind: "step", step: step3, via });
7059
7155
  if (links2.length === 0) return { items: items2 };
7060
7156
  via = links2[0];
7061
7157
  const next = byId.get(via.to);
7062
7158
  if (shared.has(next.id)) return { items: [...items2, ref(next, via)] };
7063
- step2 = next;
7159
+ step3 = next;
7064
7160
  }
7065
7161
  };
7066
7162
  const arm = (to) => {
7067
- const step2 = byId.get(to);
7068
- return shared.has(to) ? { items: [ref(step2)] } : chain(step2, false);
7163
+ const step3 = byId.get(to);
7164
+ return shared.has(to) ? { items: [ref(step3)] } : chain(step3, false);
7069
7165
  };
7070
7166
  const start = byId.get(spec.start);
7071
7167
  let head2;
@@ -7090,12 +7186,12 @@ var FLOW_KEY = "key: + new ~ changed ? planned \u25C7 decision \u2937 shared
7090
7186
  var flowKey = (spec) => hasRemoved(spec) ? FLOW_KEY.replace("? planned", "? planned - removed") : FLOW_KEY;
7091
7187
  var hasRemoved = (spec) => spec.steps.some((s) => s.status === "removed") || spec.links.some((l) => l.removed === true);
7092
7188
  var MARKER3 = { existing: "", new: "+", changed: "~", planned: "?", removed: "-" };
7093
- var stepLabel = (step2) => MARKER3[step2.status] + flat(step2.label);
7189
+ var stepLabel = (step3) => MARKER3[step3.status] + flat(step3.label);
7094
7190
  var SGR3 = { existing: void 0, new: "32", changed: "33", planned: "35", removed: "31" };
7095
7191
  var painter = (status, ctx) => ctx.color && SGR3[status] ? (text3) => text3 ? `\x1B[${SGR3[status]}m${text3}\x1B[0m` : text3 : void 0;
7096
- var stepSegment = (step2, ctx) => ({
7097
- text: stepLabel(step2),
7098
- paint: painter(step2.status, ctx)
7192
+ var stepSegment = (step3, ctx) => ({
7193
+ text: stepLabel(step3),
7194
+ paint: painter(step3.status, ctx)
7099
7195
  });
7100
7196
  var cutText = (hidden, ctx) => hidden > 0 ? `\u2026 (+${hidden} steps ${ctx.htmlPath ? "in web view" : "not shown"})` : "\u2026";
7101
7197
  function itemSegments(item, ctx) {
@@ -7163,10 +7259,10 @@ function chainLines(chain, first, rest, lead, ctx) {
7163
7259
  return lines;
7164
7260
  }
7165
7261
  function footer2(spec, ctx, md2) {
7166
- const count3 = (status) => spec.steps.filter((s) => s.status === status).length;
7262
+ const count4 = (status) => spec.steps.filter((s) => s.status === status).length;
7167
7263
  const lines = [
7168
7264
  countLines(
7169
- `${spec.steps.length} steps \xB7 ${count3("new")} new \xB7 ${count3("changed")} changed \xB7 ${count3("planned")} planned${count3("removed") ? ` \xB7 ${count3("removed")} removed` : ""}`,
7265
+ `${spec.steps.length} steps \xB7 ${count4("new")} new \xB7 ${count4("changed")} changed \xB7 ${count4("planned")} planned${count4("removed") ? ` \xB7 ${count4("removed")} removed` : ""}`,
7170
7266
  ctx.check,
7171
7267
  ctx.width
7172
7268
  )
@@ -7221,7 +7317,7 @@ ${truncate(cutText(walk.unreachable, ctx), ctx.width, ctx.cuts)}`;
7221
7317
  }
7222
7318
 
7223
7319
  // src/render/omitted.ts
7224
- import picomatch2 from "picomatch";
7320
+ import picomatch3 from "picomatch";
7225
7321
  var GLOB2 = { dot: true, nobrace: true, noextglob: true };
7226
7322
  var SEP = /[\s,:;()]/;
7227
7323
  function mentions(text3, s) {
@@ -7233,7 +7329,7 @@ function mentions(text3, s) {
7233
7329
  return false;
7234
7330
  }
7235
7331
  function tokenNames(t, file) {
7236
- if (/[*?[]/.test(t)) return picomatch2.isMatch(file, t, { ...GLOB2, basename: !t.includes("/") });
7332
+ if (/[*?[]/.test(t)) return picomatch3.isMatch(file, t, { ...GLOB2, basename: !t.includes("/") });
7237
7333
  return t.endsWith("/") && file.startsWith(t);
7238
7334
  }
7239
7335
  function explains(entry, file) {
@@ -7311,12 +7407,12 @@ function uncoveredFiles(c, spec, diff, found, ignored = () => false) {
7311
7407
  function checkFlowDiff(spec, snippets, checked, root, diff) {
7312
7408
  const mismatches = [];
7313
7409
  if (diff && spec.kind === "summary") {
7314
- for (const step2 of spec.steps) {
7315
- const snippet = snippets.steps.get(step2.id);
7316
- if (!snippet || step2.status !== "new" && step2.status !== "changed") continue;
7410
+ for (const step3 of spec.steps) {
7411
+ const snippet = snippets.steps.get(step3.id);
7412
+ if (!snippet || step3.status !== "new" && step3.status !== "changed") continue;
7317
7413
  const path3 = snippet.source.replace(/:\d+(-\d+)?$/, "");
7318
7414
  if (diff.has(repoPath(root, path3))) continue;
7319
- mismatches.push({ id: step2.id, label: stepLabel(step2), short: "not in diff", detail: `marked ${step2.status}, but ${path3} isn't in the diff` });
7415
+ mismatches.push({ id: step3.id, label: stepLabel(step3), short: "not in diff", detail: `marked ${step3.status}, but ${path3} isn't in the diff` });
7320
7416
  }
7321
7417
  }
7322
7418
  return { checked, mismatches, unit: "anchor" };
@@ -7324,11 +7420,11 @@ function checkFlowDiff(spec, snippets, checked, root, diff) {
7324
7420
 
7325
7421
  // src/render/plan-store.ts
7326
7422
  import { createHash as createHash5, randomBytes } from "crypto";
7327
- import { readdirSync as readdirSync6, readFileSync as readFileSync7, renameSync as renameSync2, rmdirSync, rmSync as rmSync3, statSync as statSync4, writeFileSync as writeFileSync7 } from "fs";
7328
- import { join as join21 } from "path";
7423
+ import { readdirSync as readdirSync7, readFileSync as readFileSync7, renameSync as renameSync2, rmdirSync, rmSync as rmSync3, statSync as statSync4, writeFileSync as writeFileSync7 } from "fs";
7424
+ import { join as join22 } from "path";
7329
7425
 
7330
7426
  // src/spec/schema.ts
7331
- import { z as z7 } from "zod";
7427
+ import { z as z8 } from "zod";
7332
7428
 
7333
7429
  // src/spec/business.ts
7334
7430
  import { z as z6 } from "zod";
@@ -7528,57 +7624,58 @@ var businessSchema = z6.strictObject({
7528
7624
  }).superRefine((spec, ctx) => {
7529
7625
  const issue = (path3, message) => ctx.addIssue({ code: "custom", path: path3, message });
7530
7626
  if (!spec.journeys.length && !spec.rules.length && !spec.data.length) issue([], "needs at least one journey, rule or saved data item");
7531
- idIssues(spec, issue);
7532
- spec.journeys.forEach((j, i) => stepIssues2(j, i, issue));
7627
+ itemIssues(spec, issue, /* @__PURE__ */ new Set());
7533
7628
  for (const t of businessTexts(spec)) {
7534
7629
  for (const message of plainTextIssues(t.text)) issue(t.path, message);
7535
7630
  }
7536
7631
  });
7537
- function idIssues(spec, issue) {
7538
- const groups = [["journeys", spec.journeys], ["rules", spec.rules], ["data", spec.data], ["questions", spec.questions]];
7539
- const seen = /* @__PURE__ */ new Set();
7540
- for (const [group, items2] of groups) {
7541
- items2.forEach((item, i) => {
7542
- if (seen.has(item.id)) issue([group, i, "id"], `duplicate "${item.id}"`);
7632
+ function itemIssues(items2, issue, seen, at3 = []) {
7633
+ const questions = items2.questions ?? [];
7634
+ const groups = [["journeys", items2.journeys], ["rules", items2.rules], ["data", items2.data], ["questions", questions]];
7635
+ for (const [group2, list2] of groups) {
7636
+ list2.forEach((item, i) => {
7637
+ if (seen.has(item.id)) issue([...at3, group2, i, "id"], `duplicate "${item.id}"`);
7543
7638
  seen.add(item.id);
7544
7639
  });
7545
7640
  }
7546
- const about = new Set([...spec.journeys, ...spec.rules, ...spec.data].map((x) => x.id));
7547
- spec.questions.forEach((q, i) => {
7548
- if (!about.has(q.about)) issue(["questions", i, "about"], `unknown journey, rule or saved data item "${q.about}"`);
7641
+ const about = new Set([...items2.journeys, ...items2.rules, ...items2.data].map((x) => x.id));
7642
+ questions.forEach((q, i) => {
7643
+ if (!about.has(q.about)) issue([...at3, "questions", i, "about"], `unknown journey, rule or saved data item "${q.about}"`);
7549
7644
  });
7645
+ items2.journeys.forEach((j, i) => stepIssues2(j, [...at3, "journeys", i], issue));
7550
7646
  }
7551
- function stepIssues2(journey, i, issue) {
7552
- if (!journey.now.length && !journey.after.length) issue(["journeys", i, "after"], "needs steps in now or after");
7647
+ function stepIssues2(journey, at3, issue) {
7648
+ if (!journey.now.length && !journey.after.length) issue([...at3, "after"], "needs steps in now or after");
7553
7649
  journey.now.forEach((s, j) => {
7554
- if (s.change === "new") issue(["journeys", i, "now", j, "change"], '"new" belongs in after: a step that exists now is not new');
7650
+ if (s.change === "new") issue([...at3, "now", j, "change"], '"new" belongs in after: a step that exists now is not new');
7555
7651
  });
7556
7652
  journey.after.forEach((s, j) => {
7557
- if (s.change === "removed") issue(["journeys", i, "after", j, "change"], '"removed" belongs in now: a removed step is not in after');
7653
+ if (s.change === "removed") issue([...at3, "after", j, "change"], '"removed" belongs in now: a removed step is not in after');
7558
7654
  });
7559
7655
  }
7560
7656
  function businessTexts(spec) {
7657
+ return [{ path: ["title"], text: spec.title }, { path: ["summary"], text: spec.summary }, ...itemTexts(spec)];
7658
+ }
7659
+ function itemTexts(items2, at3 = []) {
7561
7660
  const out = [];
7562
- const add = (path3, value) => value !== void 0 && out.push({ path: path3, text: value });
7563
- add(["title"], spec.title);
7564
- add(["summary"], spec.summary);
7565
- spec.journeys.forEach((j, i) => {
7661
+ const add = (path3, value) => value !== void 0 && out.push({ path: [...at3, ...path3], text: value });
7662
+ items2.journeys.forEach((j, i) => {
7566
7663
  add(["journeys", i, "name"], j.name);
7567
7664
  add(["journeys", i, "who"], j.who);
7568
7665
  for (const side of ["now", "after"]) j[side].forEach((s, k) => add(["journeys", i, side, k, "text"], s.text));
7569
7666
  });
7570
- spec.rules.forEach((r, i) => {
7667
+ items2.rules.forEach((r, i) => {
7571
7668
  add(["rules", i, "name"], r.name);
7572
7669
  add(["rules", i, "before"], r.before);
7573
7670
  add(["rules", i, "after"], r.after);
7574
7671
  r.exceptions?.forEach((e, k) => add(["rules", i, "exceptions", k], e));
7575
7672
  });
7576
- spec.data.forEach((d, i) => {
7673
+ items2.data.forEach((d, i) => {
7577
7674
  add(["data", i, "name"], d.name);
7578
7675
  add(["data", i, "what"], d.what);
7579
7676
  add(["data", i, "why"], d.why);
7580
7677
  });
7581
- spec.questions.forEach((q, i) => add(["questions", i, "text"], q.text));
7678
+ items2.questions?.forEach((q, i) => add(["questions", i, "text"], q.text));
7582
7679
  return out;
7583
7680
  }
7584
7681
  function validateBusinessSpec(input) {
@@ -7589,6 +7686,85 @@ function businessSpecJsonSchema() {
7589
7686
  return z6.toJSONSchema(businessSchema, { io: "input" });
7590
7687
  }
7591
7688
 
7689
+ // src/spec/release.ts
7690
+ import { z as z7 } from "zod";
7691
+ var MAX_SECTIONS = 12;
7692
+ var MAX_JOURNEYS2 = 4;
7693
+ var MAX_RULES2 = 6;
7694
+ var MAX_DATA2 = 4;
7695
+ var VERSION4 = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,31}$/;
7696
+ var DAY2 = /^\d{4}-\d{2}-\d{2}$/;
7697
+ var version = () => z7.string().regex(VERSION4, "a version such as 0.8.0 or v1.2.0-beta.1");
7698
+ var isDay = (d) => {
7699
+ const at3 = /* @__PURE__ */ new Date(`${d}T00:00:00Z`);
7700
+ return DAY2.test(d) && !Number.isNaN(at3.getTime()) && at3.toISOString().slice(0, 10) === d;
7701
+ };
7702
+ var OMIT = { links: true, evidence: true };
7703
+ var sectionSchema = z7.strictObject({
7704
+ id: ident(),
7705
+ title: short(),
7706
+ change: z7.enum(["new", "changed", "fixed"]).describe("new: a feature that did not exist; changed: an existing one works differently; fixed: something that was wrong now works"),
7707
+ summary: text2().describe("One or two plain sentences: what this means for people using the product"),
7708
+ pr: z7.number().int().positive().optional().describe("Pull request number; not shown on the page"),
7709
+ journeys: z7.array(journeySchema.omit(OMIT)).max(MAX_JOURNEYS2).default([]),
7710
+ rules: z7.array(ruleSchema2.omit(OMIT)).max(MAX_RULES2).default([]),
7711
+ data: z7.array(dataSchema.omit(OMIT)).max(MAX_DATA2).default([])
7712
+ });
7713
+ var releaseSchema = z7.strictObject({
7714
+ diagram: z7.literal("release"),
7715
+ title: short(),
7716
+ version: version(),
7717
+ date: z7.string().refine(isDay, "a real date as YYYY-MM-DD"),
7718
+ since: version().optional().describe("The previous version"),
7719
+ summary: text2().describe("One or two plain sentences: what's new in this release"),
7720
+ sections: z7.array(sectionSchema).min(1).max(MAX_SECTIONS, `at most ${MAX_SECTIONS} sections; group the changes into fewer features`)
7721
+ }).superRefine((spec, ctx) => {
7722
+ const issue = (path3, message) => ctx.addIssue({ code: "custom", path: path3, message });
7723
+ const seen = /* @__PURE__ */ new Set();
7724
+ spec.sections.forEach((s, i) => {
7725
+ if (seen.has(s.id)) issue(["sections", i, "id"], `duplicate "${s.id}"`);
7726
+ seen.add(s.id);
7727
+ });
7728
+ spec.sections.forEach((s, i) => itemIssues(s, issue, seen, ["sections", i]));
7729
+ for (const t of releaseTexts(spec)) {
7730
+ for (const message of plainTextIssues(t.text)) issue(t.path, message);
7731
+ }
7732
+ });
7733
+ function releaseTexts(spec) {
7734
+ return [
7735
+ { path: ["title"], text: spec.title },
7736
+ { path: ["summary"], text: spec.summary },
7737
+ ...spec.sections.flatMap((s, i) => [{ path: ["sections", i, "title"], text: s.title }, { path: ["sections", i, "summary"], text: s.summary }, ...itemTexts(s, ["sections", i])])
7738
+ ];
7739
+ }
7740
+ var CHECKED_ONLY = "a release map only holds facts checked in the code, PR text or diff: ask the developer about anything uncertain, or leave it out";
7741
+ var ITEM_GROUPS = ["journeys", "rules", "data"];
7742
+ var isObj = (v) => typeof v === "object" && v !== null;
7743
+ function reviewIssues(input) {
7744
+ const out = [];
7745
+ const sections2 = isObj(input) && Array.isArray(input.sections) ? input.sections : [];
7746
+ sections2.forEach((s, i) => {
7747
+ if (!isObj(s)) return;
7748
+ if ("questions" in s) out.push(`${formatPath(["sections", i, "questions"])}: not allowed; ${CHECKED_ONLY}`);
7749
+ for (const group2 of ITEM_GROUPS) {
7750
+ const items2 = Array.isArray(s[group2]) ? s[group2] : [];
7751
+ items2.forEach((item, j) => {
7752
+ if (isObj(item) && "evidence" in item) out.push(`${formatPath(["sections", i, group2, j, "evidence"])}: not allowed; ${CHECKED_ONLY}`);
7753
+ });
7754
+ }
7755
+ });
7756
+ return out;
7757
+ }
7758
+ function validateReleaseSpec(input) {
7759
+ const refused2 = reviewIssues(input);
7760
+ if (refused2.length) return { ok: false, errors: refused2 };
7761
+ const result = releaseSchema.safeParse(input);
7762
+ return result.success ? { ok: true, spec: result.data } : { ok: false, errors: formatIssues(result.error) };
7763
+ }
7764
+ function releaseSpecJsonSchema() {
7765
+ return z7.toJSONSchema(releaseSchema, { io: "input" });
7766
+ }
7767
+
7592
7768
  // src/spec/schema.ts
7593
7769
  var STATUSES = ["new", "changed", "removed", "context", "config"];
7594
7770
  var NODE_KINDS = [
@@ -7612,47 +7788,47 @@ var EDGE_KINDS = [
7612
7788
  "configures",
7613
7789
  "other"
7614
7790
  ];
7615
- var fieldSchema = z7.strictObject({
7791
+ var fieldSchema = z8.strictObject({
7616
7792
  name: short(),
7617
7793
  type: shortOpt().optional(),
7618
7794
  note: long().optional(),
7619
- change: z7.enum(["added", "removed", "modified"]).optional(),
7795
+ change: z8.enum(["added", "removed", "modified"]).optional(),
7620
7796
  was: shortOpt().optional().describe("The type before the change; only with change modified")
7621
7797
  });
7622
- var nodeSchema2 = z7.strictObject({
7798
+ var nodeSchema2 = z8.strictObject({
7623
7799
  id: ident(),
7624
7800
  label: short(),
7625
- kind: z7.enum(NODE_KINDS).optional().describe("Defaults to file when path is set"),
7626
- status: z7.enum(STATUSES),
7801
+ kind: z8.enum(NODE_KINDS).optional().describe("Defaults to file when path is set"),
7802
+ status: z8.enum(STATUSES),
7627
7803
  layer: short(),
7628
7804
  summary: long().optional(),
7629
7805
  path: pathStr().optional(),
7630
7806
  match: matchSchema.describe("Text on exactly one line of path (plain substring, not a regex), checked at render").optional(),
7631
- fields: z7.array(fieldSchema).optional(),
7632
- fieldsComplete: z7.boolean().optional().describe("Required when fields is non-empty: true if every field is listed, false if only the fields you saw"),
7633
- notes: z7.array(long()).optional()
7807
+ fields: z8.array(fieldSchema).optional(),
7808
+ fieldsComplete: z8.boolean().optional().describe("Required when fields is non-empty: true if every field is listed, false if only the fields you saw"),
7809
+ notes: z8.array(long()).optional()
7634
7810
  });
7635
- var edgeSchema2 = z7.strictObject({
7811
+ var edgeSchema2 = z8.strictObject({
7636
7812
  from: ident(),
7637
7813
  to: ident(),
7638
7814
  label: shortOpt().optional(),
7639
- kind: z7.enum(EDGE_KINDS).optional(),
7640
- change: z7.enum(["added", "removed"]).optional().describe("Plan only: a link the plan adds or drops between nodes that exist before and after")
7815
+ kind: z8.enum(EDGE_KINDS).optional(),
7816
+ change: z8.enum(["added", "removed"]).optional().describe("Plan only: a link the plan adds or drops between nodes that exist before and after")
7641
7817
  });
7642
- var driftSchema2 = z7.strictObject({ node: ident(), ...driftBase });
7818
+ var driftSchema2 = z8.strictObject({ node: ident(), ...driftBase });
7643
7819
  var MAX_NODES = 500;
7644
7820
  var EDGE_LABEL_EXAMPLE = "additional_training (now a list)";
7645
7821
  var MAX_EDGES = 1e3;
7646
- var specSchema = z7.strictObject({
7647
- diagram: z7.literal("map").optional(),
7822
+ var specSchema = z8.strictObject({
7823
+ diagram: z8.literal("map").optional(),
7648
7824
  title: short(),
7649
- kind: z7.enum(["plan", "summary"]),
7650
- rules: z7.array(shortOpt()).optional(),
7651
- nodes: z7.array(nodeSchema2).max(MAX_NODES, `at most ${MAX_NODES} nodes; split the map`),
7652
- edges: z7.array(edgeSchema2).max(MAX_EDGES, `at most ${MAX_EDGES} edges; split the map`),
7653
- gaps: z7.array(long()).optional(),
7654
- omitted: z7.array(long()).optional(),
7655
- drift: z7.array(driftSchema2).max(MAX_NODES).optional().describe("Summary only: how the build differs from the plan, one entry per node")
7825
+ kind: z8.enum(["plan", "summary"]),
7826
+ rules: z8.array(shortOpt()).optional(),
7827
+ nodes: z8.array(nodeSchema2).max(MAX_NODES, `at most ${MAX_NODES} nodes; split the map`),
7828
+ edges: z8.array(edgeSchema2).max(MAX_EDGES, `at most ${MAX_EDGES} edges; split the map`),
7829
+ gaps: z8.array(long()).optional(),
7830
+ omitted: z8.array(long()).optional(),
7831
+ drift: z8.array(driftSchema2).max(MAX_NODES).optional().describe("Summary only: how the build differs from the plan, one entry per node")
7656
7832
  }).superRefine((spec, ctx) => {
7657
7833
  driftIssues(spec.kind, spec.drift?.map((d) => d.node), (path3, message) => ctx.addIssue({ code: "custom", path: path3, message }));
7658
7834
  const ids = /* @__PURE__ */ new Set();
@@ -7735,11 +7911,12 @@ function validateSpec(input) {
7735
7911
  return { ok: true, spec: { ...result.data, nodes } };
7736
7912
  }
7737
7913
  function validateAnySpec(input) {
7738
- const isBusiness = typeof input === "object" && input !== null && input.diagram === "business";
7739
- return isBusiness ? validateBusinessSpec(input) : validateSpec(input);
7914
+ const diagram = typeof input === "object" && input !== null ? input.diagram : void 0;
7915
+ if (diagram === "business") return validateBusinessSpec(input);
7916
+ return diagram === "release" ? validateReleaseSpec(input) : validateSpec(input);
7740
7917
  }
7741
7918
  function specJsonSchema() {
7742
- return z7.toJSONSchema(specSchema, { io: "input" });
7919
+ return z8.toJSONSchema(specSchema, { io: "input" });
7743
7920
  }
7744
7921
 
7745
7922
  // src/render/plan-store.ts
@@ -7751,11 +7928,11 @@ function branchSegment(branch) {
7751
7928
  var fileName = (diagram) => `${diagram}.json`;
7752
7929
  function branchDir(o) {
7753
7930
  const branch = gitBranch(o.root);
7754
- return !branch || branch === "(detached)" ? void 0 : join21(o.cacheDir, "plans", repoFolder(o.root), branchSegment(branch));
7931
+ return !branch || branch === "(detached)" ? void 0 : join22(o.cacheDir, "plans", repoFolder(o.root), branchSegment(branch));
7755
7932
  }
7756
7933
  var entries = (dir) => {
7757
7934
  try {
7758
- return readdirSync6(dir, { withFileTypes: true });
7935
+ return readdirSync7(dir, { withFileTypes: true });
7759
7936
  } catch {
7760
7937
  return [];
7761
7938
  }
@@ -7766,13 +7943,13 @@ var remove2 = (path3, rm) => {
7766
7943
  } catch {
7767
7944
  }
7768
7945
  };
7769
- var folders = (dir) => entries(dir).filter((e) => e.isDirectory()).map((e) => join21(dir, e.name));
7946
+ var folders = (dir) => entries(dir).filter((e) => e.isDirectory()).map((e) => join22(dir, e.name));
7770
7947
  function prunePlans(cacheDir, now) {
7771
7948
  const old = (file) => now.getTime() - statSync4(file).mtimeMs > MAX_AGE_MS;
7772
- for (const repo of folders(join21(cacheDir, "plans"))) {
7949
+ for (const repo of folders(join22(cacheDir, "plans"))) {
7773
7950
  for (const branch of folders(repo)) {
7774
7951
  for (const file of entries(branch).filter((e) => e.isFile())) {
7775
- remove2(join21(branch, file.name), (f) => old(f) && rmSync3(f));
7952
+ remove2(join22(branch, file.name), (f) => old(f) && rmSync3(f));
7776
7953
  }
7777
7954
  remove2(branch, rmdirSync);
7778
7955
  }
@@ -7795,7 +7972,7 @@ function savePlan(o, spec) {
7795
7972
  const base = gitHead(o.root);
7796
7973
  if (!dir || !base) return;
7797
7974
  privateDir(dir);
7798
- writeAtomically(join21(dir, fileName(spec.diagram === "flow" ? "flow" : "map")), JSON.stringify({ spec, base, savedAt: o.now.toISOString() }));
7975
+ writeAtomically(join22(dir, fileName(spec.diagram === "flow" ? "flow" : "map")), JSON.stringify({ spec, base, savedAt: o.now.toISOString() }));
7799
7976
  prunePlans(o.cacheDir, o.now);
7800
7977
  } catch {
7801
7978
  }
@@ -7804,7 +7981,7 @@ function loadPlan(o, diagram, start) {
7804
7981
  try {
7805
7982
  const dir = branchDir(o);
7806
7983
  if (!dir) return void 0;
7807
- const saved = JSON.parse(readFileSync7(join21(dir, fileName(diagram)), "utf8"));
7984
+ const saved = JSON.parse(readFileSync7(join22(dir, fileName(diagram)), "utf8"));
7808
7985
  const { base, savedAt } = saved;
7809
7986
  if (typeof base !== "string" || typeof savedAt !== "string") return void 0;
7810
7987
  const age = o.now.getTime() - Date.parse(savedAt);
@@ -7822,11 +7999,11 @@ function loadPlan(o, diagram, start) {
7822
7999
 
7823
8000
  // src/commands/open.ts
7824
8001
  import { spawn, spawnSync as spawnSync2 } from "child_process";
7825
- import { win32 as win323 } from "path";
8002
+ import { win32 as win324 } from "path";
7826
8003
  function openArgv(platform, file, env = process.env) {
7827
8004
  if (platform === "darwin") return ["open", [file]];
7828
8005
  if (platform === "win32") {
7829
- return [win323.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
8006
+ return [win324.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
7830
8007
  }
7831
8008
  return ["xdg-open", [file]];
7832
8009
  }
@@ -8031,7 +8208,7 @@ import { writeFileSync as writeFileSync8 } from "fs";
8031
8208
 
8032
8209
  // src/render/preview.ts
8033
8210
  import { lstatSync as lstatSync9, realpathSync as realpathSync5 } from "fs";
8034
- import { dirname as dirname7, join as join22, resolve as resolve11, sep as sep5 } from "path";
8211
+ import { dirname as dirname7, join as join23, resolve as resolve11, sep as sep5 } from "path";
8035
8212
 
8036
8213
  // src/render/generated.ts
8037
8214
  var LOCKFILES = /* @__PURE__ */ new Set([
@@ -8098,7 +8275,7 @@ var OVER_BUDGET = "not shown: the diffs pass 25 MB together";
8098
8275
  var GENERATED = { note: "generated file, not shown" };
8099
8276
  function untrackedPreview(root, rel, budget, max) {
8100
8277
  let size = 0;
8101
- const text3 = readRegularFile(join22(root, rel), (st) => st.isFile() && (size = st.size) <= max);
8278
+ const text3 = readRegularFile(join23(root, rel), (st) => st.isFile() && (size = st.size) <= max);
8102
8279
  if (text3 === void 0) return { note: size > MAX_BYTES4 ? TOO_LARGE2 : size > max ? OVER_BUDGET : "not a regular file" };
8103
8280
  if (text3.includes("\0")) return { note: "binary file" };
8104
8281
  if (PRIVATE_KEY.test(text3)) return SECRET;
@@ -8135,7 +8312,7 @@ var insideRoot = (root, path3) => {
8135
8312
  };
8136
8313
  var noPrefetch = () => ({ sizes: /* @__PURE__ */ new Map(), blobs: /* @__PURE__ */ new Map(), diffs: /* @__PURE__ */ new Map(), untracked: /* @__PURE__ */ new Set(), untrackedKnown: /* @__PURE__ */ new Set() });
8137
8314
  var worktreeSize = (root, rel) => {
8138
- const path3 = join22(root, rel);
8315
+ const path3 = join23(root, rel);
8139
8316
  return insideRoot(root, path3) ? lstatSync9(path3, { throwIfNoEntry: false })?.size ?? 0 : 0;
8140
8317
  };
8141
8318
  function prefetch(root, range, rels, generated) {
@@ -8187,7 +8364,7 @@ function sides(root, range, rel, budget, pre) {
8187
8364
  if (note3) return { note: note3 };
8188
8365
  texts.push(pre.blobs.get(keys[i]) ?? gitBlob(root, range.revs[i], rel));
8189
8366
  }
8190
- const path3 = join22(root, rel);
8367
+ const path3 = join23(root, rel);
8191
8368
  if (!range.worktree || !insideRoot(root, path3)) return texts;
8192
8369
  let note2;
8193
8370
  try {
@@ -8229,8 +8406,8 @@ function nodePreviews(spec, root, diff, range, found, cwd) {
8229
8406
  for (const node of spec.nodes) {
8230
8407
  if (node.path === void 0 || !IN_DIFF.has(node.status)) continue;
8231
8408
  const at3 = found.get(node.id);
8232
- const candidates2 = at3 !== void 0 ? [at3] : [repoPath(root, node.path), ...cwd ? [repoPath(root, resolve11(cwd, node.path))] : []];
8233
- const rel = candidates2.find((p) => diff.hasFile(p));
8409
+ const candidates3 = at3 !== void 0 ? [at3] : [repoPath(root, node.path), ...cwd ? [repoPath(root, resolve11(cwd, node.path))] : []];
8410
+ const rel = candidates3.find((p) => diff.hasFile(p));
8234
8411
  if (rel !== void 0) rels.set(node.id, rel);
8235
8412
  }
8236
8413
  const files = [...new Set(rels.values())];
@@ -8564,10 +8741,10 @@ function businessLinkIssues(spec, boxes) {
8564
8741
  const ids = new Set(boxes.map((b) => b.id));
8565
8742
  const issues = [];
8566
8743
  const groups = [["journeys", spec.journeys], ["rules", spec.rules], ["data", spec.data]];
8567
- for (const [group, items2] of groups) {
8744
+ for (const [group2, items2] of groups) {
8568
8745
  items2.forEach(
8569
8746
  (item, i) => item.links.forEach((link, j) => {
8570
- if (!ids.has(link)) issues.push(`${formatPath([group, i, "links", j])}: "${quotable(link)}" is not a box on the tech map`);
8747
+ if (!ids.has(link)) issues.push(`${formatPath([group2, i, "links", j])}: "${quotable(link)}" is not a box on the tech map`);
8571
8748
  })
8572
8749
  );
8573
8750
  }
@@ -8580,7 +8757,7 @@ function businessLinkIssues(spec, boxes) {
8580
8757
  }
8581
8758
 
8582
8759
  // src/commands/business-tech.ts
8583
- import { join as join23 } from "path";
8760
+ import { join as join24 } from "path";
8584
8761
 
8585
8762
  // src/commands/spec-input.ts
8586
8763
  import { constants as constants4, closeSync as closeSync4, fstatSync as fstatSync3, openSync as openSync4, readSync as readSync3 } from "fs";
@@ -8628,7 +8805,7 @@ async function loadTechBoxes(src) {
8628
8805
  return spec.diagram === "flow" ? spec.steps.map(({ id, label }) => ({ id, label })) : spec.nodes.map(({ id, label }) => ({ id, label }));
8629
8806
  }
8630
8807
  try {
8631
- const { review: review2 } = findChange(join23(src.outDir, repoFolder(src.root)), gitBranch(src.root), src.map, true);
8808
+ const { review: review2 } = findChange(join24(src.outDir, repoFolder(src.root)), gitBranch(src.root), src.map, true);
8632
8809
  return review2.nodes.map(({ id, label }) => ({ id, label }));
8633
8810
  } catch {
8634
8811
  throw new Error(NO_TECH);
@@ -8652,6 +8829,437 @@ async function renderBusinessSpec(spec, o, opts, cwd) {
8652
8829
  if (html.openFailed) opts.stdout(openBlockedNote(html.file, o.md === true));
8653
8830
  }
8654
8831
 
8832
+ // src/commands/render-release.ts
8833
+ import { resolve as resolve16 } from "path";
8834
+
8835
+ // src/pr/merged.ts
8836
+ import { execFileSync as execFileSync6 } from "child_process";
8837
+
8838
+ // src/pr/setup.ts
8839
+ import { mkdtempSync, readFileSync as readFileSync8, rmSync as rmSync4 } from "fs";
8840
+ import { tmpdir } from "os";
8841
+ import { join as join25 } from "path";
8842
+ var PATTERNS = [/^[\w.-]+@([^:/]+):(.+?)(?:\.git)?\/?$/, /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?\/?$/];
8843
+ function parseRemote(url, host) {
8844
+ for (const re of PATTERNS) {
8845
+ const m = re.exec(url.trim());
8846
+ if (!m) continue;
8847
+ const server = m[1].toLowerCase();
8848
+ const found = host ?? (server.includes("github") ? "github" : server.includes("gitlab") ? "gitlab" : void 0);
8849
+ return found ? { host: found, server, path: m[2] } : void 0;
8850
+ }
8851
+ return void 0;
8852
+ }
8853
+ function pinnedTemplate(host, version2) {
8854
+ const file = host === "github" ? "templates/github-workflow.yml" : "templates/gitlab-ci.yml";
8855
+ return readFileSync8(packageFile(file), "utf8").replace("codechart@latest", `codechart@${version2}`);
8856
+ }
8857
+ var GITHUB_NOTES = [
8858
+ "Runs on every push to a pull request that has a codechart map section in its description; others are left alone.",
8859
+ "Uses the built-in GITHUB_TOKEN with contents: write (to push the map image to refs/codechart/pr-<n>, never a branch) and pull-requests: write (to update the description). No secret to add.",
8860
+ "Pull requests from forks are skipped: their token is read-only."
8861
+ ];
8862
+ function gitlabNotes(r) {
8863
+ const base = `https://${r.server}`;
8864
+ return [
8865
+ "Runs in merge request pipelines whose description has a codechart map section; others are left alone.",
8866
+ "Needs one masked CI/CD variable, CODECHART_GITLAB_TOKEN (GitLab\u2019s job token can\u2019t edit merge requests or upload files):",
8867
+ ` 1. Create an access token with api scope, from a user with at least the Developer role: ${base}/-/user_settings/personal_access_tokens?name=codechart&scopes=api`,
8868
+ ` 2. Add it under Settings > CI/CD > Variables, masked: ${base}/${r.path}/-/settings/ci_cd`,
8869
+ "Until the variable exists the job is skipped."
8870
+ ];
8871
+ }
8872
+ function buildPlan(remote, version2, read2) {
8873
+ const added = pinnedTemplate(remote.host, version2);
8874
+ if (remote.host === "github") {
8875
+ const file2 = ".github/workflows/codechart.yml";
8876
+ const existing3 = read2(file2);
8877
+ if (existing3 !== void 0) return existing3.includes("pr-sync") ? void 0 : conflict(file2);
8878
+ return { remote, file: file2, content: added, added, appended: false, notes: GITHUB_NOTES };
8879
+ }
8880
+ const file = ".gitlab-ci.yml";
8881
+ const existing2 = read2(file);
8882
+ if (existing2?.includes("pr-sync")) return void 0;
8883
+ if (existing2 !== void 0 && /^codechart-map:/m.test(existing2)) conflict(file);
8884
+ const content = existing2 === void 0 ? added : `${existing2.replace(/\n*$/, "\n")}
8885
+ ${added}`;
8886
+ return { remote, file, content, added, appended: existing2 !== void 0, notes: gitlabNotes(remote) };
8887
+ }
8888
+ function conflict(file) {
8889
+ throw new Error(`${file} already exists and is not codechart's; move it or set PR maps up by hand: https://github.com/freeleex/codechart/blob/main/docs/pr-maps.md#by-hand`);
8890
+ }
8891
+ var SETUP_BRANCH = "codechart/pr-maps";
8892
+ var PR_TITLE = "Set up codechart PR maps";
8893
+ var prBody = (plan) => [
8894
+ `Adds \`${plan.file}\`${plan.appended ? " (one job appended)" : ""} so codechart keeps the map in pull request descriptions current. Opened by \`codechart setup-pr-maps --pr\`.`,
8895
+ "",
8896
+ "**Merge to turn PR maps on; close to say no.** Nothing runs until this is merged.",
8897
+ "",
8898
+ ...plan.notes.map((n) => n.startsWith(" ") ? n : `- ${n}`)
8899
+ ].join("\n");
8900
+ function prepareSetupReview(root, version2, remote) {
8901
+ const defaultBranch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(gitRun(root, ["ls-remote", "--symref", "origin", "HEAD"]))?.[1];
8902
+ if (!defaultBranch) throw new Error("couldn't find origin's default branch");
8903
+ gitRun(root, ["fetch", "--quiet", "origin", `refs/heads/${defaultBranch}`]);
8904
+ const base = gitRun(root, ["rev-parse", "FETCH_HEAD"]);
8905
+ const plan = buildPlan(remote, version2, (file) => {
8906
+ try {
8907
+ return gitRun(root, ["show", `${base}:${file}`]) + "\n";
8908
+ } catch {
8909
+ return void 0;
8910
+ }
8911
+ });
8912
+ return { defaultBranch, base, plan };
8913
+ }
8914
+ function openSetupReview(root, { defaultBranch, base, plan }, tool) {
8915
+ const dir = mkdtempSync(join25(tmpdir(), "codechart-setup-"));
8916
+ try {
8917
+ const env = { ...process.env, GIT_INDEX_FILE: join25(dir, "index") };
8918
+ gitRun(root, ["read-tree", base], void 0, env);
8919
+ const blob = gitRun(root, ["hash-object", "-w", "--stdin"], plan.content);
8920
+ gitRun(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${plan.file}`], void 0, env);
8921
+ const tree = gitRun(root, ["write-tree"], void 0, env);
8922
+ const commit = gitRun(root, ["commit-tree", tree, "-p", base, "-m", PR_TITLE]);
8923
+ gitRun(root, ["push", "origin", `${commit}:refs/heads/${SETUP_BRANCH}`]);
8924
+ } finally {
8925
+ rmSync4(dir, { recursive: true, force: true });
8926
+ }
8927
+ const out = plan.remote.host === "github" ? tool("gh", ["pr", "create", "--base", defaultBranch, "--head", SETUP_BRANCH, "--title", PR_TITLE, "--body", prBody(plan)]) : tool("glab", ["mr", "create", "--source-branch", SETUP_BRANCH, "--target-branch", defaultBranch, "--title", PR_TITLE, "--description", prBody(plan), "--yes"]);
8928
+ return out.trim().split("\n").pop() ?? "";
8929
+ }
8930
+
8931
+ // src/pr/merged.ts
8932
+ var MAX_DESCRIPTION = 1500;
8933
+ function prNumber({ subject, body }) {
8934
+ const m = /\(#(\d+)\)\s*$/.exec(subject) ?? /^Merge pull request #(\d+)/.exec(subject) ?? /See merge request \S*?!(\d+)/.exec(body);
8935
+ return m ? Number(m[1]) : void 0;
8936
+ }
8937
+ function changeTitle2({ subject, body }) {
8938
+ return /^Merge pull request #\d+/.test(subject) ? body.split("\n").find((l) => l.trim()) ?? subject : subject;
8939
+ }
8940
+ function originRemote(root) {
8941
+ try {
8942
+ return parseRemote(gitRun(root, ["config", "--get", "remote.origin.url"]));
8943
+ } catch {
8944
+ return void 0;
8945
+ }
8946
+ }
8947
+ var clip3 = (s) => s.length > MAX_DESCRIPTION ? `${s.slice(0, MAX_DESCRIPTION).trimEnd()}\u2026` : s;
8948
+ function withoutMap(body) {
8949
+ const start = body.indexOf(BLOCK_START);
8950
+ const end = body.indexOf(BLOCK_END, start);
8951
+ return start < 0 || end < 0 ? body : body.slice(0, start) + body.slice(end + BLOCK_END.length);
8952
+ }
8953
+ function prInfo(title, body) {
8954
+ let map;
8955
+ try {
8956
+ map = specInDescription(body);
8957
+ } catch {
8958
+ }
8959
+ const description = clip3(sanitizeText(withoutMap(body).replace(/\n{3,}/g, "\n\n").trim()));
8960
+ return { title: sanitizeText(title), ...description ? { description } : {}, ...map === void 0 ? {} : { map } };
8961
+ }
8962
+ function fetchPr(tool, remote, n) {
8963
+ if (remote.host === "github") {
8964
+ const repo = remote.server === "github.com" ? remote.path : `${remote.server}/${remote.path}`;
8965
+ const j2 = JSON.parse(tool("gh", ["pr", "view", String(n), "--repo", repo, "--json", "title,body"]));
8966
+ return prInfo(j2.title ?? "", j2.body ?? "");
8967
+ }
8968
+ const j = JSON.parse(tool("glab", ["mr", "view", String(n), "--repo", `https://${remote.server}/${remote.path}`, "--output", "json"]));
8969
+ return prInfo(j.title ?? "", j.description ?? "");
8970
+ }
8971
+ var runTool = (command, args) => {
8972
+ try {
8973
+ return execFileSync6(trustedBinary(command), args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 6e4, maxBuffer: 16 * 1024 * 1024 });
8974
+ } catch (e) {
8975
+ if (e.code === "ENOENT") throw new Error(`${command} is not installed`);
8976
+ const stderr = String(e.stderr ?? "").trim().split("\n")[0];
8977
+ throw new Error(`${command} failed${stderr ? `: ${stderr}` : ""}`);
8978
+ }
8979
+ };
8980
+
8981
+ // src/render/release/logo.ts
8982
+ import { realpathSync as realpathSync6 } from "fs";
8983
+ import { extname, isAbsolute as isAbsolute5, relative as relative4, resolve as resolve14, sep as sep6 } from "path";
8984
+ var MAX_LOGO_BYTES = 200 * 1024;
8985
+ var TYPES = { ".svg": "image/svg+xml", ".png": "image/png" };
8986
+ var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
8987
+ var escapes2 = (rel) => rel === ".." || rel.startsWith(`..${sep6}`) || isAbsolute5(rel);
8988
+ function realInside(root, path3) {
8989
+ if (isAbsolute5(path3) || escapes2(relative4(root, resolve14(root, path3)))) return void 0;
8990
+ const real = realpathSync6(resolve14(root, path3));
8991
+ return escapes2(relative4(realpathSync6(root), real)) ? void 0 : real;
8992
+ }
8993
+ function matchesType(bytes, ext) {
8994
+ return ext === ".png" ? bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) : /<svg[\s>]/i.test(bytes.toString("utf8"));
8995
+ }
8996
+ function loadLogo(root, path3) {
8997
+ const ext = extname(path3).toLowerCase();
8998
+ const type = TYPES[ext];
8999
+ if (!type) return { error: "must be an .svg or .png file" };
9000
+ try {
9001
+ const real = realInside(root, path3);
9002
+ if (!real) return { error: "must be a path inside the repo" };
9003
+ let refused2;
9004
+ const bytes = readRegularBytes(real, (st) => {
9005
+ if (!st.isFile()) refused2 = "is not a regular file";
9006
+ else if (st.size > MAX_LOGO_BYTES) refused2 = "is over 200 KB";
9007
+ return refused2 === void 0;
9008
+ });
9009
+ if (refused2 !== void 0 || !bytes) return { error: refused2 ?? "could not be read" };
9010
+ if (!matchesType(bytes, ext)) return { error: `is not a real ${ext.slice(1).toUpperCase()}` };
9011
+ return { uri: `data:${type};base64,${bytes.toString("base64")}` };
9012
+ } catch (e) {
9013
+ return { error: e.code === "ENOENT" ? "was not found" : "could not be read" };
9014
+ }
9015
+ }
9016
+
9017
+ // src/render/release/cards.ts
9018
+ var MARK6 = { new: ["add", "New"], changed: ["chg", "Changed"], removed: ["rem", "Removed"] };
9019
+ function step2(s) {
9020
+ const [cls, label] = s.change ? MARK6[s.change] : ["same", ""];
9021
+ return `<li class="step ${cls}">${label ? `<span class="mk ${cls}">${label}</span> ` : ""}<span class="t">${esc(s.text)}</span></li>`;
9022
+ }
9023
+ var steps2 = (list2) => list2.length ? `<ol class="steps">${list2.map(step2).join("")}</ol>` : '<p class="none">Nothing happens here.</p>';
9024
+ function journeyCard2(j) {
9025
+ const who = j.who ? `<span class="who">${esc(j.who)}</span>` : "";
9026
+ return `<article class="card journey"><div class="j-head"><h3>${esc(j.name)}</h3>${who}</div>
9027
+ <div class="j-cols"><div class="j-col"><h4>Now</h4>${steps2(j.now)}</div><div class="j-col"><h4>After this change</h4>${steps2(j.after)}</div></div></article>`;
9028
+ }
9029
+ function ruleCard2(r) {
9030
+ const before = r.before === void 0 ? "" : `<dt>Before</dt><dd class="was">${esc(r.before)}</dd>`;
9031
+ const exceptions = r.exceptions?.length ? `<div class="exc"><b>Except:</b><ul>${r.exceptions.map((e) => `<li>${esc(e)}</li>`).join("")}</ul></div>` : "";
9032
+ return `<article class="card rule"><span class="mk ${r.before === void 0 ? "add" : "chg"}">${r.before === void 0 ? "New rule" : "Changed rule"}</span>
9033
+ <h3>${esc(r.name)}</h3><dl class="ba">${before}<dt>After</dt><dd>${esc(r.after)}</dd></dl>${exceptions}</article>`;
9034
+ }
9035
+ function dataCard2(d) {
9036
+ return `<article class="card datum"><span class="mk add">Kept</span><h3>${esc(d.name)}</h3><p>${esc(d.what)}</p><p class="why">${esc(d.why)}</p></article>`;
9037
+ }
9038
+
9039
+ // src/render/release/styles.ts
9040
+ var VARS = "--bg:#e9ecef;--paper:#fff;--sunk:#fafbfc;--line:#d0d7de;--line-soft:#e6eaef;--text:#1f2328;--muted:#656d76;--soft:#2d333b;--edge:#0969da;--new:#2ea043;--new-t:#1a7f37;--new-bg:rgba(46,160,67,.10);--new-line:rgba(46,160,67,.35);--chg:#d29922;--chg-t:#9a6700;--chg-bg:rgba(212,167,44,.13);--rem:#cf222e;--rem-bg:rgba(255,129,130,.16);--rem-t:#6e2a2e";
9041
+ var BASE = `
9042
+ :root{color-scheme:light;${VARS};--serif:"Iowan Old Style",Charter,"Palatino Linotype",Palatino,Georgia,serif;--sans:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",sans-serif}
9043
+ *{box-sizing:border-box}
9044
+ html{background:var(--bg)}
9045
+ body{margin:0;color:var(--text);font:11pt/1.5 var(--sans);-webkit-font-smoothing:antialiased;-webkit-print-color-adjust:exact;print-color-adjust:exact}
9046
+ h1,h2,h3{font-family:var(--serif);font-weight:600;letter-spacing:-.01em;margin:0}
9047
+ img{display:block;object-fit:contain}
9048
+ .cover img{max-height:28mm;max-width:70mm;margin-bottom:12mm}
9049
+ .cover{padding-top:60mm;break-after:page}
9050
+ .co-product{font-size:13pt;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
9051
+ .cover h1{font-size:34pt;line-height:1.1;margin:4mm 0 3mm}
9052
+ .co-meta{font-size:12pt;color:var(--muted);margin-bottom:10mm}
9053
+ .summary{font-size:14pt;line-height:1.6;margin:0;color:var(--soft)}
9054
+ .co-counts{margin-top:10mm;color:var(--soft)}
9055
+ .feature{margin:0 0 10mm;padding-top:8mm;border-top:1px solid var(--line)}
9056
+ .feature:first-of-type{border-top:0;padding-top:0}
9057
+ .f-head{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px;margin-bottom:6px}
9058
+ .f-head h2{font-size:20pt;flex:1 1 60%}
9059
+ .f-head,.f-sum,.f-sub{break-after:avoid}
9060
+ .f-head,.f-sum{break-inside:avoid}
9061
+ .chg-badge{font-size:8.5pt;font-weight:700;letter-spacing:.05em;text-transform:uppercase;border-radius:4px;padding:2px 8px}
9062
+ .chg-new{background:var(--new-bg);color:var(--new-t)}
9063
+ .chg-changed{background:var(--chg-bg);color:var(--chg-t)}
9064
+ .chg-fixed{background:rgba(9,105,218,.07);color:var(--edge)}
9065
+ .f-sum{margin:0 0 14px;font-size:12pt;color:var(--soft)}
9066
+ .f-sub{margin:16px 0 8px;font-size:9pt;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:var(--muted)}
9067
+ .card{background:var(--paper);border:1px solid var(--line);border-radius:8px;break-inside:avoid;margin-bottom:10px}
9068
+ .mk{display:inline-block;font-size:8.5pt;font-weight:700;letter-spacing:.04em;text-transform:uppercase;border-radius:4px;padding:1px 6px}
9069
+ .mk.add{background:var(--new-bg);color:var(--new-t)}
9070
+ .mk.chg{background:var(--chg-bg);color:var(--chg-t)}
9071
+ .mk.rem{background:var(--rem-bg);color:var(--rem)}
9072
+ .j-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 12px;padding:10px 14px;border-bottom:1px solid var(--line-soft)}
9073
+ .j-head h3{font-size:13pt;flex:1 1 60%}
9074
+ .who{font-size:9.5pt;color:var(--muted)}
9075
+ .j-cols{display:grid;grid-template-columns:1fr 1fr}
9076
+ .j-col{padding:10px 14px}
9077
+ .j-col:first-child{background:var(--sunk);border-right:1px solid var(--line-soft);border-radius:0 0 0 8px}
9078
+ .j-col h4{margin:0 0 8px;font-size:8.5pt;text-transform:uppercase;letter-spacing:.09em;color:var(--muted)}
9079
+ .none{margin:0;color:var(--muted);font-style:italic;font-size:10pt}
9080
+ ol.steps{margin:0;padding:0 0 0 18px;font-size:10.5pt}
9081
+ .step{padding:2px 0}
9082
+ .step.rem .t{text-decoration:line-through;text-decoration-color:var(--rem)}
9083
+ .rules,.data{display:grid;grid-template-columns:1fr;gap:0}
9084
+ .rule,.datum{padding:10px 14px}
9085
+ .rule h3,.datum h3{font-size:12.5pt;margin:4px 0 6px}
9086
+ .ba{display:grid;grid-template-columns:auto 1fr;gap:3px 10px;font-size:10.5pt;margin:0}
9087
+ .ba dt{font-size:8.5pt;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);padding-top:3px}
9088
+ .ba dd{margin:0}
9089
+ .ba dd.was{color:var(--muted)}
9090
+ .exc{font-size:10pt;margin-top:8px}
9091
+ .exc ul{margin:2px 0 0;padding-left:18px}
9092
+ .datum p{margin:0;font-size:10.5pt;color:var(--soft)}
9093
+ .datum .why{color:var(--muted)}
9094
+ footer{color:var(--muted);font-size:9pt;padding-top:6mm}
9095
+ `;
9096
+ var SCREEN = `
9097
+ @media screen{
9098
+ body{padding:24px 12px}
9099
+ .sheet{max-width:210mm;margin:0 auto 24px;background:#fff;padding:18mm 16mm 20mm;box-shadow:0 2px 16px rgba(0,0,0,.18)}
9100
+ .cover{min-height:225mm;border-bottom:1px dashed var(--line);margin-bottom:10mm}
9101
+ }
9102
+ @media screen and (max-width:640px){.j-cols{grid-template-columns:1fr}.j-col:first-child{border-right:0;border-bottom:1px solid var(--line-soft)}.cover h1{font-size:26pt}}
9103
+ `;
9104
+ var PRINT = `
9105
+ @page{size:A4;margin:18mm 16mm 20mm;@bottom-right{content:counter(page);font:9pt sans-serif;color:#656d76}}
9106
+ @page:first{@bottom-right{content:none}}
9107
+ @media print{html,body{background:#fff}}
9108
+ `;
9109
+ var RELEASE_CSS = BASE + SCREEN + PRINT;
9110
+
9111
+ // src/render/release/html.ts
9112
+ var STATIC_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'";
9113
+ var CHANGES = ["new", "changed", "fixed"];
9114
+ var LABEL2 = { new: "New", changed: "Changed", fixed: "Fixed" };
9115
+ var day = (d) => `${Number(d.slice(8))} ${MONTHS[Number(d.slice(5, 7)) - 1]} ${d.slice(0, 4)}`;
9116
+ var countOf = (spec, c) => spec.sections.filter((s) => s.change === c).length;
9117
+ var group = (title, body) => body ? `<p class="f-sub">${title}</p>${body}` : "";
9118
+ var cards = (items2, card, wrap = "") => {
9119
+ const body = items2.map(card).join("\n");
9120
+ return body && wrap ? `<div class="${wrap}">${body}</div>` : body;
9121
+ };
9122
+ function section2(s) {
9123
+ return `<section class="feature">
9124
+ <div class="f-head"><span class="chg-badge chg-${s.change}">${LABEL2[s.change]}</span><h2>${esc(s.title)}</h2></div>
9125
+ <p class="f-sum">${esc(s.summary)}</p>
9126
+ ${group("How it works", cards(s.journeys, journeyCard2))}
9127
+ ${group("Rules", cards(s.rules, ruleCard2, "rules"))}
9128
+ ${group("Information kept", cards(s.data, dataCard2, "data"))}
9129
+ </section>`;
9130
+ }
9131
+ var versionLine = (spec) => `Version ${esc(spec.version)}${spec.since ? ` (since ${esc(spec.since)})` : ""} \xB7 ${day(spec.date)}`;
9132
+ var countText = (spec) => CHANGES.flatMap((c) => countOf(spec, c) ? [`${countOf(spec, c)} ${c}`] : []).join(" \xB7 ");
9133
+ function releasePage(spec, meta, brand = {}) {
9134
+ const logo = brand.logo ? `<img src="${esc(brand.logo)}" alt="">` : "";
9135
+ return `<!doctype html>
9136
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
9137
+ <meta http-equiv="Content-Security-Policy" content="${STATIC_CSP}">
9138
+ <title>${esc(spec.title)}</title>
9139
+ <style>${RELEASE_CSS}</style></head>
9140
+ <body>
9141
+ <main class="sheet">
9142
+ <div class="cover">${logo}<div class="co-product">${esc(brand.product ?? meta.repo)}</div><h1>${esc(spec.title)}</h1><div class="co-meta">${versionLine(spec)}</div><p class="summary">${esc(spec.summary)}</p><div class="co-counts">${esc(countText(spec))}</div></div>
9143
+ ${spec.sections.map(section2).join("\n")}
9144
+ <footer>Made by codechart.</footer>
9145
+ </main>
9146
+ </body></html>
9147
+ `;
9148
+ }
9149
+
9150
+ // src/render/release/render.ts
9151
+ var count3 = (n, one, many = `${one}s`) => n ? `${n} ${n === 1 ? one : many}` : void 0;
9152
+ function releaseSummary(spec) {
9153
+ const parts = [count3(spec.sections.length, "feature"), ...["new", "changed", "fixed"].map((c) => count3(spec.sections.filter((s) => s.change === c).length, c, c))];
9154
+ return [`Release map: ${spec.title} (${spec.version})`, ...parts.filter(Boolean)].join(" \xB7 ");
9155
+ }
9156
+ var renderRelease = (spec, ctx) => ctx.write(async (meta) => releasePage(spec, meta, ctx.brand));
9157
+
9158
+ // src/commands/release-pdf.ts
9159
+ import { execFile } from "child_process";
9160
+ import { closeSync as closeSync5, copyFileSync as copyFileSync2, existsSync as existsSync9, mkdtempSync as mkdtempSync2, openSync as openSync5, readSync as readSync4, rmSync as rmSync5, statSync as statSync5 } from "fs";
9161
+ import { tmpdir as tmpdir2 } from "os";
9162
+ import { dirname as dirname8, join as join26, posix as posix2, resolve as resolve15, win32 as win325 } from "path";
9163
+ import { pathToFileURL as pathToFileURL3 } from "url";
9164
+ var TIMEOUT_MS = 6e4;
9165
+ var MAC = ["Google Chrome", "Chromium", "Microsoft Edge", "Brave Browser"].map((n) => `/Applications/${n}.app/Contents/MacOS/${n}`);
9166
+ var LINUX = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"];
9167
+ var WINDOWS = [
9168
+ ["ProgramFiles", "Google\\Chrome\\Application\\chrome.exe"],
9169
+ ["ProgramFiles(x86)", "Google\\Chrome\\Application\\chrome.exe"],
9170
+ ["LOCALAPPDATA", "Google\\Chrome\\Application\\chrome.exe"],
9171
+ ["ProgramFiles", "Microsoft\\Edge\\Application\\msedge.exe"],
9172
+ ["ProgramFiles(x86)", "Microsoft\\Edge\\Application\\msedge.exe"],
9173
+ ["LOCALAPPDATA", "Microsoft\\Edge\\Application\\msedge.exe"]
9174
+ ];
9175
+ function candidates2({ platform = process.platform, env = process.env }) {
9176
+ if (platform === "darwin") return MAC;
9177
+ if (platform === "win32") return WINDOWS.flatMap(([base, rest]) => env[base] ? [win325.join(env[base], rest)] : []);
9178
+ const dirs = (env.PATH ?? "").split(":").filter((d) => posix2.isAbsolute(d));
9179
+ return dirs.flatMap((d) => LINUX.map((n) => posix2.join(d, n)));
9180
+ }
9181
+ function findBrowser(o = {}) {
9182
+ const exists = o.exists ?? existsSync9;
9183
+ const list2 = o.configured === void 0 ? candidates2(o) : [o.configured];
9184
+ return list2.find((p) => exists(p));
9185
+ }
9186
+ function pdfFlagPath(flag, cwd) {
9187
+ const out = resolve15(cwd, flag);
9188
+ if (!out.toLowerCase().endsWith(".pdf")) throw new Error("--pdf must end in .pdf");
9189
+ if (!statSync5(dirname8(out), { throwIfNoEntry: false })?.isDirectory()) throw new Error(`--pdf: ${dirname8(out)} is not a folder`);
9190
+ return out;
9191
+ }
9192
+ function browserArgs(html, pdf, profile) {
9193
+ return ["--headless=new", "--disable-gpu", "--no-pdf-header-footer", "--no-first-run", "--no-default-browser-check", `--user-data-dir=${profile}`, `--print-to-pdf=${pdf}`, pathToFileURL3(html).href];
9194
+ }
9195
+ var runBrowser = (browser, args) => new Promise((done, fail) => {
9196
+ execFile(browser, args, { timeout: TIMEOUT_MS, windowsHide: true }, (e) => e ? fail(e) : done());
9197
+ });
9198
+ function isPdf(file) {
9199
+ try {
9200
+ const fd = openSync5(file, "r");
9201
+ try {
9202
+ const head2 = Buffer.alloc(4);
9203
+ return readSync4(fd, head2, 0, 4, 0) === 4 && head2.toString("latin1") === "%PDF";
9204
+ } finally {
9205
+ closeSync5(fd);
9206
+ }
9207
+ } catch {
9208
+ return false;
9209
+ }
9210
+ }
9211
+ async function printPdf(browser, html, pdf, run2 = runBrowser, remove3 = rmSync5) {
9212
+ const profile = mkdtempSync2(join26(tmpdir2(), "codechart-pdf-"));
9213
+ const printed = join26(profile, "release.pdf");
9214
+ try {
9215
+ await run2(browser, browserArgs(html, printed, profile));
9216
+ if (!isPdf(printed)) return "the browser finished but wrote no PDF";
9217
+ copyFileSync2(printed, pdf);
9218
+ return void 0;
9219
+ } catch (e) {
9220
+ return e.message.split("\n")[0].slice(0, 200);
9221
+ } finally {
9222
+ try {
9223
+ remove3(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
9224
+ } catch {
9225
+ }
9226
+ }
9227
+ }
9228
+
9229
+ // src/commands/render-release.ts
9230
+ var productOf = (release, root) => release?.product ?? originRemote(root)?.path.split("/").pop()?.replace(/\.git$/, "");
9231
+ function brandOf(release, root, warn) {
9232
+ const product = productOf(release, root);
9233
+ if (release?.logo === void 0) return { product };
9234
+ const logo = loadLogo(root, release.logo);
9235
+ if ("error" in logo) warn(`release.logo "${release.logo}" ${logo.error}; the cover has no logo`);
9236
+ return { product, ..."uri" in logo && { logo: logo.uri } };
9237
+ }
9238
+ async function renderReleaseSpec(spec, o, opts, cwd) {
9239
+ if (o.pr) throw new Error("release maps are not for PR descriptions");
9240
+ if (o.tech !== void 0) throw new Error("--tech only applies to business maps");
9241
+ const root = findRepoRoot(cwd) ?? resolve16(cwd);
9242
+ const warn = (line) => opts.stderr(`codechart: ${line}
9243
+ `);
9244
+ const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn });
9245
+ const brand = brandOf(config.release, root, warn);
9246
+ const now = opts.now?.() ?? /* @__PURE__ */ new Date();
9247
+ const flagged2 = o.pdf === void 0 ? void 0 : pdfFlagPath(o.pdf, cwd);
9248
+ const write = htmlWriter({ config, root, slug: releaseSlug(spec.version, spec.title), theme: o.theme, now, open: o.open }, opts);
9249
+ const html = await renderRelease(spec, { brand, write });
9250
+ const md2 = o.md === true;
9251
+ const pdf = flagged2 ?? html.file.replace(/\.html$/, ".pdf");
9252
+ const browser = (opts.pdf?.find ?? ((configured) => findBrowser({ configured, env: opts.env })))(config.release.browser);
9253
+ const failure = browser === void 0 ? "no Chromium-based browser found" : await printPdf(browser, html.file, pdf, opts.pdf?.run ?? runBrowser);
9254
+ const made = failure === void 0;
9255
+ if (!made) warn(`no PDF (${failure}): open ${html.file} in a browser and use Save as PDF, or set release.browser to a Chrome, Chromium, Edge or Brave path in your global config`);
9256
+ const summary = releaseSummary(spec);
9257
+ const pdfLine = made ? `PDF: ${pdf}` : void 0;
9258
+ opts.stdout(md2 ? markdownBlock([`**${summary}**`, pdfLine].filter(Boolean).join("\n\n"), void 0, html.file) : `${[summary, pdfLine, fullMapLine(html.file)].filter(Boolean).join("\n")}
9259
+ `);
9260
+ if (html.openFailed) opts.stdout(openBlockedNote(html.file, md2));
9261
+ }
9262
+
8655
9263
  // src/commands/render.ts
8656
9264
  function specOutput(config, ruleNames, diagram) {
8657
9265
  const outputs = ruleNames.map((name) => {
@@ -8693,8 +9301,8 @@ function selectedDiff(o, repoRoot, root) {
8693
9301
  }
8694
9302
  function prTarget(o, cwd, cacheFile) {
8695
9303
  if (!o.pr) return void 0;
8696
- if (o.svg !== void 0) return { svg: resolve14(cwd, o.svg), imageUrl: o.imageUrl ?? basename3(o.svg) };
8697
- privateDir(dirname8(cacheFile));
9304
+ if (o.svg !== void 0) return { svg: resolve17(cwd, o.svg), imageUrl: o.imageUrl ?? basename3(o.svg) };
9305
+ privateDir(dirname9(cacheFile));
8698
9306
  return { svg: cacheFile, imageUrl: o.imageUrl ?? basename3(cacheFile) };
8699
9307
  }
8700
9308
  function rangeStart(o, root) {
@@ -8719,13 +9327,19 @@ function planFor(spec, diagram, store, o) {
8719
9327
  }
8720
9328
  var failed = (check, drift) => flagged(check) || (drift?.unexplained ?? 0) > 0;
8721
9329
  var clock = (opts) => opts.now?.() ?? /* @__PURE__ */ new Date();
9330
+ var isPageSpec = (spec) => spec.diagram === "business" || spec.diagram === "release";
9331
+ var renderPageSpec = (spec, o, opts, cwd) => spec.diagram === "business" ? renderBusinessSpec(spec, o, opts, cwd) : renderReleaseSpec(spec, o, opts, cwd);
9332
+ function pdfOnlyForRelease(spec, o) {
9333
+ if (o.pdf !== void 0 && spec.diagram !== "release") throw new Error("--pdf only applies to release maps");
9334
+ }
8722
9335
  async function renderSpec(arg, o, opts, cwd) {
8723
9336
  const spec = await readSpec(arg, cwd, opts.stdin ?? (() => readStdin(MAX_SPEC_BYTES, new Error(TOO_BIG))));
8724
- if (spec.diagram === "business") return renderBusinessSpec(spec, o, opts, cwd);
9337
+ pdfOnlyForRelease(spec, o);
9338
+ if (isPageSpec(spec)) return renderPageSpec(spec, o, opts, cwd);
8725
9339
  const repoRoot = findRepoRoot(cwd);
8726
- const root = repoRoot ?? resolve14(cwd);
9340
+ const root = repoRoot ?? resolve17(cwd);
8727
9341
  const at3 = resolveAt(o, repoRoot, root);
8728
- const target2 = targetOf(spec, root, at3, resolve14(cwd), o);
9342
+ const target2 = targetOf(spec, root, at3, resolve17(cwd), o);
8729
9343
  const diff = selectedDiff(o, repoRoot, root);
8730
9344
  const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
8731
9345
  `) });
@@ -8748,9 +9362,9 @@ async function renderSpec(arg, o, opts, cwd) {
8748
9362
  width: defaultWidth({ isTTY: opts.isTTY ?? process.stdout.isTTY, columns: process.stdout.columns }, env),
8749
9363
  color: !o.md && (opts.isTTY ?? process.stdout.isTTY === true),
8750
9364
  md: o.md === true,
8751
- pr: prTarget(o, cwd, join24(config.web.outDir, repoFolder(root), `${slug}.svg`)),
9365
+ pr: prTarget(o, cwd, join27(config.web.outDir, repoFolder(root), `${slug}.svg`)),
8752
9366
  root,
8753
- cwd: resolve14(cwd),
9367
+ cwd: resolve17(cwd),
8754
9368
  at: at3,
8755
9369
  diff,
8756
9370
  unmapped: unmappedFiles(config),
@@ -8770,7 +9384,7 @@ async function renderSpec(arg, o, opts, cwd) {
8770
9384
  }
8771
9385
  function renderCommand(opts) {
8772
9386
  const cwd = opts.cwd ?? process.cwd();
8773
- return new Command10("render").description("render a spec as a terminal map and/or a self-contained HTML map (business maps: HTML only)").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option3("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option3("--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("--pr", "print a collapsed section for a PR or MR description and write the map as an SVG (maps only)").option("--svg <file>", "with --pr: write the SVG here instead of the private cache folder").option("--image-url <url>", "with --pr: where the description loads the SVG from (default: its file name)").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("--tech <file>", "business maps: the tech map's spec file, whose boxes the business map links to (default: the newest saved map on this branch)").option("--strict", "exit 1 when a claim doesn't match the code or the build drifted from the plan without a reason").action(async (arg, o, cmd) => {
9387
+ return new Command10("render").description("render a spec as a terminal map and/or a self-contained HTML map (business and release maps: HTML only)").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option3("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option3("--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("--pr", "print a collapsed section for a PR or MR description and write the map as an SVG (maps only)").option("--svg <file>", "with --pr: write the SVG here instead of the private cache folder").option("--image-url <url>", "with --pr: where the description loads the SVG from (default: its file name)").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("--tech <file>", "business maps: the tech map's spec file, whose boxes the business map links to (default: the newest saved map on this branch)").option("--pdf <file>", "release maps: where to write the PDF (default: next to the HTML page)").option("--strict", "exit 1 when a claim doesn't match the code or the build drifted from the plan without a reason").action(async (arg, o, cmd) => {
8774
9388
  const usage = renderSelectionError(o) ?? (!o.pr && (o.svg !== void 0 || o.imageUrl !== void 0) ? "--svg and --image-url need --pr" : void 0);
8775
9389
  if (usage) cmd.error(usage, { exitCode: 2 });
8776
9390
  try {
@@ -8788,8 +9402,8 @@ function renderCommand(opts) {
8788
9402
  // src/commands/pr-sync.ts
8789
9403
  var NOT_DRAWN = "no map drawn";
8790
9404
  async function render(spec, review2, placeholder, opts, cwd) {
8791
- const dir = mkdtempSync(join25(tmpdir(), "codechart-pr-"));
8792
- const file = join25(dir, "map.svg");
9405
+ const dir = mkdtempSync3(join28(tmpdir3(), "codechart-pr-"));
9406
+ const file = join28(dir, "map.svg");
8793
9407
  let block = "";
8794
9408
  let errors = "";
8795
9409
  try {
@@ -8797,9 +9411,9 @@ async function render(spec, review2, placeholder, opts, cwd) {
8797
9411
  await cmd.parseAsync(["-", "--since", review2.base, "--head", review2.head, "--at", review2.head, "--pr", "--svg", file, "--image-url", placeholder], { from: "user" });
8798
9412
  if (!block && errors.includes(NOT_DRAWN)) return void 0;
8799
9413
  if (!block) throw new Error(errors.trim() || "render printed nothing");
8800
- return { block, svg: readFileSync8(file, "utf8") };
9414
+ return { block, svg: readFileSync9(file, "utf8") };
8801
9415
  } finally {
8802
- rmSync4(dir, { recursive: true, force: true });
9416
+ rmSync6(dir, { recursive: true, force: true });
8803
9417
  }
8804
9418
  }
8805
9419
  async function staleReason(review2, spec) {
@@ -8841,106 +9455,11 @@ function prSyncCommand(opts) {
8841
9455
  }
8842
9456
 
8843
9457
  // src/commands/setup-pr-maps.ts
8844
- import { execFileSync as execFileSync6 } from "child_process";
8845
- import { closeSync as closeSync5, constants as constants5, lstatSync as lstatSync10, mkdirSync as mkdirSync6, openSync as openSync5, writeFileSync as writeFileSync9 } from "fs";
8846
- import { dirname as dirname9, join as join27 } from "path";
9458
+ import { execFileSync as execFileSync7 } from "child_process";
9459
+ import { closeSync as closeSync6, constants as constants5, lstatSync as lstatSync10, mkdirSync as mkdirSync6, openSync as openSync6, writeFileSync as writeFileSync9 } from "fs";
9460
+ import { dirname as dirname10, join as join29 } from "path";
8847
9461
  import { createInterface } from "readline/promises";
8848
9462
  import { Command as Command12, Option as Option4 } from "commander";
8849
-
8850
- // src/pr/setup.ts
8851
- import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync9, rmSync as rmSync5 } from "fs";
8852
- import { tmpdir as tmpdir2 } from "os";
8853
- import { join as join26 } from "path";
8854
- var PATTERNS = [/^[\w.-]+@([^:/]+):(.+?)(?:\.git)?\/?$/, /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?\/?$/];
8855
- function parseRemote(url, host) {
8856
- for (const re of PATTERNS) {
8857
- const m = re.exec(url.trim());
8858
- if (!m) continue;
8859
- const server = m[1].toLowerCase();
8860
- const found = host ?? (server.includes("github") ? "github" : server.includes("gitlab") ? "gitlab" : void 0);
8861
- return found ? { host: found, server, path: m[2] } : void 0;
8862
- }
8863
- return void 0;
8864
- }
8865
- function pinnedTemplate(host, version) {
8866
- const file = host === "github" ? "templates/github-workflow.yml" : "templates/gitlab-ci.yml";
8867
- return readFileSync9(packageFile(file), "utf8").replace("codechart@latest", `codechart@${version}`);
8868
- }
8869
- var GITHUB_NOTES = [
8870
- "Runs on every push to a pull request that has a codechart map section in its description; others are left alone.",
8871
- "Uses the built-in GITHUB_TOKEN with contents: write (to push the map image to refs/codechart/pr-<n>, never a branch) and pull-requests: write (to update the description). No secret to add.",
8872
- "Pull requests from forks are skipped: their token is read-only."
8873
- ];
8874
- function gitlabNotes(r) {
8875
- const base = `https://${r.server}`;
8876
- return [
8877
- "Runs in merge request pipelines whose description has a codechart map section; others are left alone.",
8878
- "Needs one masked CI/CD variable, CODECHART_GITLAB_TOKEN (GitLab\u2019s job token can\u2019t edit merge requests or upload files):",
8879
- ` 1. Create an access token with api scope, from a user with at least the Developer role: ${base}/-/user_settings/personal_access_tokens?name=codechart&scopes=api`,
8880
- ` 2. Add it under Settings > CI/CD > Variables, masked: ${base}/${r.path}/-/settings/ci_cd`,
8881
- "Until the variable exists the job is skipped."
8882
- ];
8883
- }
8884
- function buildPlan(remote, version, read2) {
8885
- const added = pinnedTemplate(remote.host, version);
8886
- if (remote.host === "github") {
8887
- const file2 = ".github/workflows/codechart.yml";
8888
- const existing2 = read2(file2);
8889
- if (existing2 !== void 0) return existing2.includes("pr-sync") ? void 0 : conflict(file2);
8890
- return { remote, file: file2, content: added, added, appended: false, notes: GITHUB_NOTES };
8891
- }
8892
- const file = ".gitlab-ci.yml";
8893
- const existing = read2(file);
8894
- if (existing?.includes("pr-sync")) return void 0;
8895
- if (existing !== void 0 && /^codechart-map:/m.test(existing)) conflict(file);
8896
- const content = existing === void 0 ? added : `${existing.replace(/\n*$/, "\n")}
8897
- ${added}`;
8898
- return { remote, file, content, added, appended: existing !== void 0, notes: gitlabNotes(remote) };
8899
- }
8900
- function conflict(file) {
8901
- throw new Error(`${file} already exists and is not codechart's; move it or set PR maps up by hand: https://github.com/freeleex/codechart/blob/main/docs/pr-maps.md#by-hand`);
8902
- }
8903
- var SETUP_BRANCH = "codechart/pr-maps";
8904
- var PR_TITLE = "Set up codechart PR maps";
8905
- var prBody = (plan) => [
8906
- `Adds \`${plan.file}\`${plan.appended ? " (one job appended)" : ""} so codechart keeps the map in pull request descriptions current. Opened by \`codechart setup-pr-maps --pr\`.`,
8907
- "",
8908
- "**Merge to turn PR maps on; close to say no.** Nothing runs until this is merged.",
8909
- "",
8910
- ...plan.notes.map((n) => n.startsWith(" ") ? n : `- ${n}`)
8911
- ].join("\n");
8912
- function prepareSetupReview(root, version, remote) {
8913
- const defaultBranch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(gitRun(root, ["ls-remote", "--symref", "origin", "HEAD"]))?.[1];
8914
- if (!defaultBranch) throw new Error("couldn't find origin's default branch");
8915
- gitRun(root, ["fetch", "--quiet", "origin", `refs/heads/${defaultBranch}`]);
8916
- const base = gitRun(root, ["rev-parse", "FETCH_HEAD"]);
8917
- const plan = buildPlan(remote, version, (file) => {
8918
- try {
8919
- return gitRun(root, ["show", `${base}:${file}`]) + "\n";
8920
- } catch {
8921
- return void 0;
8922
- }
8923
- });
8924
- return { defaultBranch, base, plan };
8925
- }
8926
- function openSetupReview(root, { defaultBranch, base, plan }, tool) {
8927
- const dir = mkdtempSync2(join26(tmpdir2(), "codechart-setup-"));
8928
- try {
8929
- const env = { ...process.env, GIT_INDEX_FILE: join26(dir, "index") };
8930
- gitRun(root, ["read-tree", base], void 0, env);
8931
- const blob = gitRun(root, ["hash-object", "-w", "--stdin"], plan.content);
8932
- gitRun(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${plan.file}`], void 0, env);
8933
- const tree = gitRun(root, ["write-tree"], void 0, env);
8934
- const commit = gitRun(root, ["commit-tree", tree, "-p", base, "-m", PR_TITLE]);
8935
- gitRun(root, ["push", "origin", `${commit}:refs/heads/${SETUP_BRANCH}`]);
8936
- } finally {
8937
- rmSync5(dir, { recursive: true, force: true });
8938
- }
8939
- const out = plan.remote.host === "github" ? tool("gh", ["pr", "create", "--base", defaultBranch, "--head", SETUP_BRANCH, "--title", PR_TITLE, "--body", prBody(plan)]) : tool("glab", ["mr", "create", "--source-branch", SETUP_BRANCH, "--target-branch", defaultBranch, "--title", PR_TITLE, "--description", prBody(plan), "--yes"]);
8940
- return out.trim().split("\n").pop() ?? "";
8941
- }
8942
-
8943
- // src/commands/setup-pr-maps.ts
8944
9463
  function remoteOf(root, host) {
8945
9464
  let url;
8946
9465
  try {
@@ -8954,7 +9473,7 @@ function remoteOf(root, host) {
8954
9473
  }
8955
9474
  function readWorkTree(root) {
8956
9475
  return (file) => {
8957
- const path3 = join27(root, file);
9476
+ const path3 = join29(root, file);
8958
9477
  let text3;
8959
9478
  try {
8960
9479
  text3 = readRegularFile(path3, (st) => st.isFile() && lstatSync10(path3).isFile());
@@ -8968,12 +9487,12 @@ function readWorkTree(root) {
8968
9487
  };
8969
9488
  }
8970
9489
  function writeWorkTree(root, plan) {
8971
- const path3 = join27(root, plan.file);
8972
- mkdirSync6(dirname9(path3), { recursive: true });
9490
+ const path3 = join29(root, plan.file);
9491
+ mkdirSync6(dirname10(path3), { recursive: true });
8973
9492
  const flags = constants5.O_WRONLY | constants5.O_CREAT | constants5.O_TRUNC | (constants5.O_NOFOLLOW ?? 0) | (plan.appended ? 0 : constants5.O_EXCL);
8974
9493
  let fd;
8975
9494
  try {
8976
- fd = openSync5(path3, flags, 420);
9495
+ fd = openSync6(path3, flags, 420);
8977
9496
  } catch (e) {
8978
9497
  const code = e.code;
8979
9498
  if (code === "EEXIST" || code === "ELOOP") throw new Error(`${plan.file}: changed while codechart was running; run it again`);
@@ -8982,7 +9501,7 @@ function writeWorkTree(root, plan) {
8982
9501
  try {
8983
9502
  writeFileSync9(fd, plan.content);
8984
9503
  } finally {
8985
- closeSync5(fd);
9504
+ closeSync6(fd);
8986
9505
  }
8987
9506
  }
8988
9507
  function describe(plan, pr) {
@@ -9001,7 +9520,7 @@ async function terminalConfirm(question) {
9001
9520
  }
9002
9521
  var defaultTool = (command, args) => {
9003
9522
  try {
9004
- return execFileSync6(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 12e4 });
9523
+ return execFileSync7(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 12e4 });
9005
9524
  } catch (e) {
9006
9525
  if (e.code === "ENOENT") throw new Error(`${command} is not installed; install it or run without --pr`);
9007
9526
  throw new Error(`${command} failed: ${String(e.stderr ?? e.message).trim()}`);
@@ -9055,11 +9574,84 @@ function setupPrMapsCommand(opts) {
9055
9574
  });
9056
9575
  }
9057
9576
 
9058
- // src/commands/review.ts
9059
- import { mkdtempSync as mkdtempSync3, readFileSync as readFileSync10, rmSync as rmSync6, writeFileSync as writeFileSync10 } from "fs";
9060
- import { tmpdir as tmpdir3 } from "os";
9061
- import { join as join28 } from "path";
9577
+ // src/commands/release-context.ts
9062
9578
  import { Command as Command13 } from "commander";
9579
+ var MAX_FILES3 = 40;
9580
+ var MAX_PRS = 50;
9581
+ function repoVersion(root, sha) {
9582
+ try {
9583
+ const text3 = gitFileAt(root, sha, "package.json", 1024 * 1024);
9584
+ const v = typeof text3 === "string" ? JSON.parse(text3).version : void 0;
9585
+ return typeof v === "string" ? sanitizeText(v) : void 0;
9586
+ } catch {
9587
+ return void 0;
9588
+ }
9589
+ }
9590
+ function readPrs(opts, root, numbers) {
9591
+ const prs = /* @__PURE__ */ new Map();
9592
+ if (!numbers.length) return { prs, notes: [] };
9593
+ const remote = originRemote(root);
9594
+ if (!remote) return { prs, notes: ["PR descriptions were not read: origin is not a GitHub or GitLab remote."] };
9595
+ const tool = opts.tool ?? runTool;
9596
+ const notes = [];
9597
+ const wanted = numbers.slice(-MAX_PRS);
9598
+ if (wanted.length < numbers.length) notes.push(`Only the newest ${MAX_PRS} of ${numbers.length} PRs had their descriptions read.`);
9599
+ try {
9600
+ for (const n of wanted) prs.set(n, fetchPr(tool, remote, n));
9601
+ } catch (e) {
9602
+ const why = sanitizeText((e instanceof Error ? e.message : String(e)).split("\n")[0] ?? "").replace(/\.$/, "");
9603
+ return { prs: /* @__PURE__ */ new Map(), notes: [`PR descriptions were not read: ${why}.`] };
9604
+ }
9605
+ return { prs, notes };
9606
+ }
9607
+ function releaseContext(o, opts, root) {
9608
+ const headSha = resolveCommit(root, "--head", o.head ?? "HEAD");
9609
+ const since = o.since ?? gitLatestTag(root, `${headSha}^`, "v*");
9610
+ if (!since) throw new Error("no version tag (v*) found before HEAD; pass --since <ref>");
9611
+ const sinceSha = resolveCommit(root, "--since", since);
9612
+ const log = gitFirstParentLog(root, sinceSha, headSha);
9613
+ const numbers = log.flatMap((e) => prNumber(e) ?? []);
9614
+ const { prs, notes } = readPrs(opts, root, numbers);
9615
+ const changes = log.map((e) => {
9616
+ const files = gitCommitFiles(root, e.sha);
9617
+ const n = prNumber(e);
9618
+ const info = n === void 0 ? void 0 : prs.get(n);
9619
+ const title = sanitizeText(changeTitle2(e));
9620
+ return {
9621
+ sha: e.short,
9622
+ title,
9623
+ date: e.date,
9624
+ ...n === void 0 ? {} : { pr: n },
9625
+ files: files.slice(0, MAX_FILES3).map(sanitizeText),
9626
+ ...files.length > MAX_FILES3 ? { moreFiles: files.length - MAX_FILES3 } : {},
9627
+ ...info && info.title !== title ? { prTitle: info.title } : {},
9628
+ ...info?.description ? { description: info.description } : {},
9629
+ ...info?.map === void 0 ? {} : { map: info.map }
9630
+ };
9631
+ });
9632
+ const version2 = repoVersion(root, headSha);
9633
+ return { since: sanitizeText(since), sinceSha, head: headSha, ...version2 ? { version: version2 } : {}, changes, ...notes.length ? { notes } : {} };
9634
+ }
9635
+ function releaseContextCommand(opts) {
9636
+ const cwd = opts.cwd ?? process.cwd();
9637
+ return new Command13("release-context").description("list what was merged since the last release (JSON for an agent writing a release map)").option("--since <ref>", "the previous release: a tag or commit (default: the newest v* tag before HEAD)").option("--head <ref>", "the release commit (default HEAD)").action((o) => {
9638
+ try {
9639
+ const root = findRepoRoot(cwd);
9640
+ if (!root) throw new Error("not a git repository");
9641
+ opts.stdout(escapeJsonControls(JSON.stringify(releaseContext(o, opts, root))) + "\n");
9642
+ } catch (e) {
9643
+ opts.stderr(`codechart: ${e.message}
9644
+ `);
9645
+ process.exitCode = 2;
9646
+ }
9647
+ });
9648
+ }
9649
+
9650
+ // src/commands/review.ts
9651
+ import { mkdtempSync as mkdtempSync4, readFileSync as readFileSync10, rmSync as rmSync7, writeFileSync as writeFileSync10 } from "fs";
9652
+ import { tmpdir as tmpdir4 } from "os";
9653
+ import { join as join30 } from "path";
9654
+ import { Command as Command14 } from "commander";
9063
9655
 
9064
9656
  // src/review/color.ts
9065
9657
  var SGR4 = (code, s) => `\x1B[${code}m${s}\x1B[0m`;
@@ -9087,13 +9679,13 @@ function mergeNotes(opened, parsed, fresh) {
9087
9679
 
9088
9680
  // src/commands/review-editor.ts
9089
9681
  import { spawnSync as spawnSync3 } from "child_process";
9090
- import { win32 as win324 } from "path";
9682
+ import { win32 as win326 } from "path";
9091
9683
  var VI_FAMILY = /* @__PURE__ */ new Set(["vi", "vim", "nvim", "gvim", "mvim"]);
9092
9684
  var VI_ARGS = '-c "syntax on" -c "set ft=diff" -c "syn match codechartNote /^>.*/" -c "syn match codechartHead /^##.*/" -c "hi codechartNote ctermfg=black ctermbg=yellow guifg=black guibg=yellow" -c "hi link codechartHead Title"';
9093
9685
  var defaultEditor = (platform = process.platform) => platform === "win32" ? "notepad" : "vi";
9094
9686
  function withEditorArgs(editor) {
9095
9687
  const first = /^\s*(?:"([^"]*)"|(\S+))/.exec(editor);
9096
- const program = win324.basename(first?.[1] ?? first?.[2] ?? "").replace(/\.exe$/i, "").toLowerCase();
9688
+ const program = win326.basename(first?.[1] ?? first?.[2] ?? "").replace(/\.exe$/i, "").toLowerCase();
9097
9689
  return VI_FAMILY.has(program) ? `${editor} ${VI_ARGS}` : editor;
9098
9690
  }
9099
9691
  function editorInvocation(platform, command, file) {
@@ -9122,8 +9714,8 @@ async function review(o, opts) {
9122
9714
  const doc = buildDoc(r);
9123
9715
  const env = opts.env ?? process.env;
9124
9716
  if (o.print) return opts.stdout((opts.isTTY ?? process.stdout.isTTY === true) && !env.NO_COLOR ? colorDoc(doc) : doc);
9125
- const dir = mkdtempSync3(join28(tmpdir3(), "codechart-review-"));
9126
- const file = join28(dir, `${r.change.slug.replace(/\.flow$/, "").replace(/[^a-z0-9-]/g, "-").slice(0, 40) || "review"}.diff`);
9717
+ const dir = mkdtempSync4(join30(tmpdir4(), "codechart-review-"));
9718
+ const file = join30(dir, `${r.change.slug.replace(/\.flow$/, "").replace(/[^a-z0-9-]/g, "-").slice(0, 40) || "review"}.diff`);
9127
9719
  let keep = false;
9128
9720
  try {
9129
9721
  const after = edit(file, doc, opts);
@@ -9147,35 +9739,35 @@ async function review(o, opts) {
9147
9739
  Tell your agent "review done" and it will pick up your notes.
9148
9740
  `);
9149
9741
  } finally {
9150
- if (!keep) rmSync6(dir, { recursive: true, force: true });
9742
+ if (!keep) rmSync7(dir, { recursive: true, force: true });
9151
9743
  }
9152
9744
  }
9153
9745
  function reviewCommand(opts) {
9154
- return new Command13("review").description("write review notes on the latest map in your editor; an agent reads them with 'codechart feedback'").option("--change <title>", "review the map with this title (or file name slug) instead of the newest one on this branch").option("--print", "print the review document instead of opening an editor").action((o) => guarded(opts, () => review(o, opts)));
9746
+ return new Command14("review").description("write review notes on the latest map in your editor; an agent reads them with 'codechart feedback'").option("--change <title>", "review the map with this title (or file name slug) instead of the newest one on this branch").option("--print", "print the review document instead of opening an editor").action((o) => guarded(opts, () => review(o, opts)));
9155
9747
  }
9156
9748
 
9157
9749
  // src/commands/schema.ts
9158
- import { Command as Command14 } from "commander";
9750
+ import { Command as Command15 } from "commander";
9159
9751
  function schemaCommand(opts) {
9160
- return new Command14("schema").description("print the spec JSON schema, the flow spec schema with --flow, the business map schema with --business, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").option("--business", "print the business map spec schema instead").action((o, cmd) => {
9161
- if ([o.config, o.flow, o.business].filter(Boolean).length > 1) cmd.error("--config, --flow and --business are mutually exclusive", { exitCode: 2 });
9162
- const schema = o.config ? configJsonSchema() : o.flow ? flowJsonSchema() : o.business ? businessSpecJsonSchema() : specJsonSchema();
9752
+ return new Command15("schema").description("print the spec JSON schema, the flow spec schema with --flow, the business map schema with --business, the release map schema with --release, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").option("--business", "print the business map spec schema instead").option("--release", "print the release map spec schema instead").action((o, cmd) => {
9753
+ if ([o.config, o.flow, o.business, o.release].filter(Boolean).length > 1) cmd.error("--config, --flow, --business and --release are mutually exclusive", { exitCode: 2 });
9754
+ const schema = o.config ? configJsonSchema() : o.flow ? flowJsonSchema() : o.business ? businessSpecJsonSchema() : o.release ? releaseSpecJsonSchema() : specJsonSchema();
9163
9755
  opts.stdout(JSON.stringify(schema, null, 2) + "\n");
9164
9756
  });
9165
9757
  }
9166
9758
 
9167
9759
  // src/commands/uninstall.ts
9168
- import { lstatSync as lstatSync11, readdirSync as readdirSync7, rmdirSync as rmdirSync2, unlinkSync as unlinkSync4 } from "fs";
9760
+ import { lstatSync as lstatSync11, readdirSync as readdirSync8, rmdirSync as rmdirSync2, unlinkSync as unlinkSync4 } from "fs";
9169
9761
  import { homedir as homedir6 } from "os";
9170
- import { join as join29 } from "path";
9171
- import { Command as Command15 } from "commander";
9762
+ import { join as join31 } from "path";
9763
+ import { Command as Command16 } from "commander";
9172
9764
  function removeSkill(dir, files) {
9173
9765
  const st = lstatSync11(dir, { throwIfNoEntry: false });
9174
9766
  if (!st) return void 0;
9175
9767
  if (!st.isDirectory()) return `left ${dir}: not a folder`;
9176
9768
  if (!isCodechartSkill(dir)) return `left ${dir}: not the codechart skill`;
9177
- for (const f of files) if (lstatSync11(join29(dir, f), { throwIfNoEntry: false })?.isFile()) unlinkSync4(join29(dir, f));
9178
- if (readdirSync7(dir).length > 0) return `removed skill files from ${dir} (kept your other files there)`;
9769
+ for (const f of files) if (lstatSync11(join31(dir, f), { throwIfNoEntry: false })?.isFile()) unlinkSync4(join31(dir, f));
9770
+ if (readdirSync8(dir).length > 0) return `removed skill files from ${dir} (kept your other files there)`;
9179
9771
  rmdirSync2(dir);
9180
9772
  return `removed skill: ${dir}`;
9181
9773
  }
@@ -9185,11 +9777,11 @@ function pluginLine(file) {
9185
9777
  return r === "removed" ? `removed plugin: ${file}` : void 0;
9186
9778
  }
9187
9779
  function uninstallCommand(opts) {
9188
- return new Command15("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").option("--plugin", "remove the codechart plugin file from the OpenCode plugins folder").action((o) => {
9780
+ return new Command16("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").option("--plugin", "remove the codechart plugin file from the OpenCode plugins folder").action((o) => {
9189
9781
  const home = opts.home ?? homedir6();
9190
9782
  const all = !o.skill && !o.reminder && !o.hook && !o.plugin;
9191
9783
  let did = false;
9192
- const step2 = (run2) => {
9784
+ const step3 = (run2) => {
9193
9785
  try {
9194
9786
  const line = run2();
9195
9787
  if (line) {
@@ -9204,23 +9796,23 @@ function uninstallCommand(opts) {
9204
9796
  }
9205
9797
  };
9206
9798
  if (all || o.skill) {
9207
- const files = readdirSync7(packageFile("skills/codechart"));
9208
- for (const folder of new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))) step2(() => removeSkill(join29(home, folder, "codechart"), files));
9799
+ const files = readdirSync8(packageFile("skills/codechart"));
9800
+ for (const folder of new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))) step3(() => removeSkill(join31(home, folder, "codechart"), files));
9209
9801
  }
9210
9802
  if (all || o.reminder) {
9211
9803
  for (const a of AGENTS) {
9212
9804
  if (!a.instructions) continue;
9213
- const file = join29(home, a.instructions);
9214
- step2(() => removeReminder(file) === "removed" ? `removed reminder: ${file}` : void 0);
9805
+ const file = join31(home, a.instructions);
9806
+ step3(() => removeReminder(file) === "removed" ? `removed reminder: ${file}` : void 0);
9215
9807
  }
9216
9808
  }
9217
9809
  if (all || o.hook) {
9218
- const file = join29(home, ".claude", "settings.json");
9219
- step2(() => removeClaudeHooks(file) === "removed" ? `removed hook: ${file}` : void 0);
9810
+ const file = join31(home, ".claude", "settings.json");
9811
+ step3(() => removeClaudeHooks(file) === "removed" ? `removed hook: ${file}` : void 0);
9220
9812
  }
9221
9813
  if (all || o.plugin) {
9222
9814
  const file = pluginFile(home, opts.env ?? process.env);
9223
- step2(() => pluginLine(file));
9815
+ step3(() => pluginLine(file));
9224
9816
  }
9225
9817
  if (!did && process.exitCode !== 1) opts.stdout("nothing to remove\n");
9226
9818
  });
@@ -9251,7 +9843,7 @@ function buildProgram(opts = {}) {
9251
9843
  const stdout = opts.stdout ?? ((s) => process.stdout.write(s));
9252
9844
  const rawStderr = opts.stderr ?? ((s) => process.stderr.write(s));
9253
9845
  const stderr = (s) => rawStderr(sanitizeText(s));
9254
- const program = new Command16().name("codechart").version(currentVersion());
9846
+ const program = new Command17().name("codechart").version(currentVersion());
9255
9847
  const cmdOpts = { ...opts, stdout, stderr, rawStderr: opts.rawStderr ?? rawStderr };
9256
9848
  program.addCommand(checkCommand(cmdOpts));
9257
9849
  program.addCommand(renderCommand(cmdOpts));
@@ -9265,6 +9857,7 @@ function buildProgram(opts = {}) {
9265
9857
  program.addCommand(setupPrMapsCommand(cmdOpts));
9266
9858
  program.addCommand(updateCommand(cmdOpts));
9267
9859
  program.addCommand(doctorCommand(cmdOpts));
9860
+ program.addCommand(releaseContextCommand(cmdOpts));
9268
9861
  program.addCommand(reviewCommand(cmdOpts));
9269
9862
  program.addCommand(commentCommand(cmdOpts));
9270
9863
  program.addCommand(feedbackCommand(cmdOpts));