codechart 0.4.0 → 0.5.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,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/program.ts
4
- import { Command as Command12, CommanderError } from "commander";
4
+ import { Command as Command13, CommanderError } from "commander";
5
5
 
6
6
  // src/commands/check.ts
7
7
  import path2 from "path";
8
8
  import { Command } from "commander";
9
9
 
10
10
  // src/config/load.ts
11
- import { existsSync, realpathSync } from "fs";
11
+ import { realpathSync } from "fs";
12
12
  import { homedir } from "os";
13
- import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
13
+ import { isAbsolute, join as join2, relative, resolve as resolve2, sep } from "path";
14
14
  import { parse } from "yaml";
15
15
 
16
16
  // src/read-regular.ts
@@ -29,6 +29,19 @@ function readRegularFile(path3, accept) {
29
29
  }
30
30
  }
31
31
 
32
+ // src/config/repo-root.ts
33
+ import { existsSync } from "fs";
34
+ import { dirname, join, resolve } from "path";
35
+ function findRepoRoot(cwd) {
36
+ let dir = resolve(cwd);
37
+ for (; ; ) {
38
+ if (existsSync(join(dir, ".git"))) return dir;
39
+ const parent = dirname(dir);
40
+ if (parent === dir) return void 0;
41
+ dir = parent;
42
+ }
43
+ }
44
+
32
45
  // src/config/builtin-rules.ts
33
46
  var MAP_RULES = [
34
47
  {
@@ -259,15 +272,6 @@ var BUILTIN = "built-in";
259
272
  var MAX_BYTES = 1024 * 1024;
260
273
  var BUILTIN_DEFAULTS = { output: "auto", context: "short", flows: "auto", terminalMaxNodes: 15 };
261
274
  var GLOBAL_ONLY = ["web.outDir", "web.keep", "web.maxAgeDays", "web.open", "updateCheck"];
262
- function findRepoRoot(cwd) {
263
- let dir = resolve(cwd);
264
- for (; ; ) {
265
- if (existsSync(join(dir, ".git"))) return dir;
266
- const parent = dirname(dir);
267
- if (parent === dir) return void 0;
268
- dir = parent;
269
- }
270
- }
271
275
  function readConfigFile(file, root) {
272
276
  let real;
273
277
  try {
@@ -310,22 +314,22 @@ function dropGlobalOnly(file, path3, warn) {
310
314
  if (ignored.length) warn?.(`${path3}: ${ignored.join(", ")} ${ignored.length === 1 ? "is" : "are"} global-only; ignored`);
311
315
  return file.web ? { ...rest, web } : rest;
312
316
  }
313
- function firstByName(items) {
317
+ function firstByName(items2) {
314
318
  const seen = /* @__PURE__ */ new Set();
315
- return items.filter(({ rule }) => !seen.has(rule.name) && seen.add(rule.name));
319
+ return items2.filter(({ rule }) => !seen.has(rule.name) && seen.add(rule.name));
316
320
  }
317
321
  function resolveOutDir(dir, home) {
318
- const expanded = dir === "~" ? home : dir.startsWith("~/") ? join(home, dir.slice(2)) : dir;
319
- return resolve(home, expanded);
322
+ const expanded = dir === "~" ? home : dir.startsWith("~/") ? join2(home, dir.slice(2)) : dir;
323
+ return resolve2(home, expanded);
320
324
  }
321
325
  function loadConfigWithSources(opts) {
322
326
  const env = opts.env ?? process.env;
323
327
  const home = opts.home ?? homedir();
324
328
  const xdg = env.XDG_CONFIG_HOME;
325
- const configHome = xdg && isAbsolute(xdg) ? xdg : home ? join(home, ".config") : void 0;
326
- const root = findRepoRoot(opts.cwd) ?? resolve(opts.cwd);
327
- const globalPath = configHome ? join(configHome, "codechart", "config.yaml") : void 0;
328
- const repoPath2 = join(root, ".codechart.yaml");
329
+ const configHome = xdg && isAbsolute(xdg) ? xdg : home ? join2(home, ".config") : void 0;
330
+ const root = findRepoRoot(opts.cwd) ?? resolve2(opts.cwd);
331
+ const globalPath = configHome ? join2(configHome, "codechart", "config.yaml") : void 0;
332
+ const repoPath2 = join2(root, ".codechart.yaml");
329
333
  const global = globalPath ? readConfigFile(globalPath) : void 0;
330
334
  const repo = dropGlobalOnly(readConfigFile(repoPath2, root), repoPath2, opts.warn);
331
335
  const globalSource = `global: ${globalPath}`;
@@ -504,7 +508,7 @@ function resolveRules(config, files, matched, root = process.cwd()) {
504
508
  // src/rules/git-files.ts
505
509
  import { execFileSync } from "child_process";
506
510
  import { existsSync as existsSync2, lstatSync } from "fs";
507
- import { join as join2, win32 } from "path";
511
+ import { join as join3, win32 } from "path";
508
512
  var MAX_REF = 200;
509
513
  function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
510
514
  if (platform !== "win32") return "git";
@@ -755,10 +759,10 @@ function gitDirtyHashes(cwd, max = Infinity) {
755
759
  const files = gitChangedFiles(cwd);
756
760
  if (files.length > max) return void 0;
757
761
  const out = {};
758
- const present2 = files.filter((f) => !f.includes("\n") && !f.startsWith('"') && lstatSync(join2(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
759
- const hashes = present2.length ? git(cwd, ["hash-object", "--no-filters", "--stdin-paths"], { input: present2.join("\n") }).trim().split("\n") : [];
760
- for (const f of files) out[f] = existsSync2(join2(cwd, f)) ? "present" : "deleted";
761
- present2.forEach((f, i) => out[f] = hashes[i] ?? "");
762
+ const present3 = files.filter((f) => !f.includes("\n") && !f.startsWith('"') && lstatSync(join3(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
763
+ const hashes = present3.length ? git(cwd, ["hash-object", "--no-filters", "--stdin-paths"], { input: present3.join("\n") }).trim().split("\n") : [];
764
+ for (const f of files) out[f] = existsSync2(join3(cwd, f)) ? "present" : "deleted";
765
+ present3.forEach((f, i) => out[f] = hashes[i] ?? "");
762
766
  return out;
763
767
  }
764
768
  function gitDiffFiles(cwd, from, to) {
@@ -903,7 +907,7 @@ function renderPieces(pieces) {
903
907
  }
904
908
  return merged.map((p) => p.item?.paint ? p.item.paint(p.text) : p.text).join("");
905
909
  }
906
- function wrapItems(head, items, width) {
910
+ function wrapItems(head, items2, width) {
907
911
  const indent = " ".repeat(columns(head));
908
912
  const lines = [];
909
913
  let line = [{ text: head }];
@@ -918,7 +922,7 @@ function wrapItems(head, items, width) {
918
922
  line = [{ text: indent }];
919
923
  fresh = true;
920
924
  };
921
- items.forEach((raw, i) => {
925
+ items2.forEach((raw, i) => {
922
926
  const item = typeof raw === "string" ? { text: raw } : raw;
923
927
  const sep6 = i === 0 ? "" : " \xB7 ";
924
928
  if (columns(sep6 + item.text) <= room()) {
@@ -1001,141 +1005,17 @@ function configCommand(opts) {
1001
1005
  });
1002
1006
  }
1003
1007
 
1004
- // src/commands/hook.ts
1005
- import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync, openSync as openSync2, readdirSync, readFileSync, readSync as readSync2, unlinkSync, writeFileSync } from "fs";
1006
- import { homedir as homedir2 } from "os";
1007
- import { join as join3 } from "path";
1008
- import { Argument, Command as Command3 } from "commander";
1009
-
1010
- // src/commands/stdin.ts
1011
- async function readStdin(max, overCap) {
1012
- const chunks2 = [];
1013
- let size = 0;
1014
- for await (const chunk of process.stdin) {
1015
- size += chunk.length;
1016
- if (size > max && overCap !== "stop") throw overCap;
1017
- chunks2.push(chunk);
1018
- if (size > max) break;
1019
- }
1020
- return Buffer.concat(chunks2).toString("utf8");
1021
- }
1008
+ // src/commands/doctor.ts
1009
+ import { homedir as homedir4 } from "os";
1010
+ import { Command as Command5 } from "commander";
1022
1011
 
1023
- // src/commands/hook.ts
1024
- var MIN_FILES = 3;
1025
- var MAX_INPUT = 1024 * 1024;
1026
- var MAX_TRANSCRIPT_TAIL = 8 * 1024 * 1024;
1027
- var MAX_DIRTY = 5e3;
1028
- var KEEP_DAYS = 7;
1029
- var SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
1030
- var DIAGRAM = /\*\*(Map|Flow)\*\*/;
1031
- function changedFiles(before, now, diff) {
1032
- const changed = /* @__PURE__ */ new Set();
1033
- for (const f of /* @__PURE__ */ new Set([...Object.keys(before.files), ...Object.keys(now.files)])) {
1034
- if (before.files[f] !== now.files[f]) changed.add(f);
1035
- }
1036
- if (now.head && before.head !== now.head) for (const f of diff(before.head, now.head)) changed.add(f);
1037
- return [...changed].sort();
1038
- }
1039
- var blocks = (e) => Array.isArray(e.message?.content) ? e.message.content : [];
1040
- var isPrompt = (e) => e.type === "user" && !e.isMeta && (typeof e.message?.content === "string" || blocks(e).length > 0 && !blocks(e).some((b) => b.type === "tool_result"));
1041
- var CODECHART_RUN = /\bcodechart\s+(check|render)\b/;
1042
- var showsCodechart = (b) => b.type === "text" && DIAGRAM.test(b.text ?? "") || b.type === "tool_use" && typeof b.input?.command === "string" && CODECHART_RUN.test(b.input.command);
1043
- function turnUsedCodechart(jsonl) {
1044
- let used = false;
1045
- for (const line of jsonl.split("\n")) {
1046
- let e;
1047
- try {
1048
- e = JSON.parse(line);
1049
- } catch {
1050
- continue;
1051
- }
1052
- if (isPrompt(e)) used = false;
1053
- else if (e.type === "assistant" && blocks(e).some(showsCodechart)) used = true;
1054
- }
1055
- return used;
1056
- }
1057
- function readTail(file, max) {
1058
- const fd = openSync2(file, "r");
1059
- try {
1060
- const st = fstatSync2(fd);
1061
- if (!st.isFile()) return "";
1062
- const size = Math.min(st.size, max);
1063
- const buf = Buffer.alloc(size);
1064
- readSync2(fd, buf, 0, size, st.size - size);
1065
- return buf.toString("utf8");
1066
- } finally {
1067
- closeSync2(fd);
1068
- }
1069
- }
1070
- async function readInput(stdin) {
1071
- const text = await stdin();
1072
- if (Buffer.byteLength(text) > MAX_INPUT) return {};
1073
- const v = JSON.parse(text);
1074
- return typeof v === "object" && v !== null ? v : {};
1075
- }
1076
- function snapshot(root) {
1077
- const files = gitDirtyHashes(root, MAX_DIRTY);
1078
- return files && { head: gitHead(root), files };
1079
- }
1080
- function prune(dir, now) {
1081
- for (const f of readdirSync(dir)) {
1082
- const p = join3(dir, f);
1083
- const st = lstatSync2(p);
1084
- if (st.isFile() && now - st.mtimeMs > KEEP_DAYS * 864e5) unlinkSync(p);
1085
- }
1086
- }
1087
- var nudge = (count) => `This turn changed ${count} files and your reply has no codechart diagram. Unless the user said no diagram, follow the codechart skill now (check, then render) and reply with what it prints; if it says no diagram applies, stop without mentioning it.`;
1088
- function onPrompt({ root, dir, file }, now) {
1089
- const snap = snapshot(root);
1090
- mkdirSync(dir, { recursive: true, mode: 448 });
1091
- prune(dir, now.getTime());
1092
- if (snap) writeFileSync(file, JSON.stringify({ root, ...snap }), { mode: 384 });
1093
- else unlinkSync(file);
1094
- }
1095
- function onStop({ root, file, input }) {
1096
- if (input.stop_hook_active === true) return void 0;
1097
- const before = JSON.parse(readFileSync(file, "utf8"));
1098
- if (before.root !== root) return void 0;
1099
- const now = snapshot(root);
1100
- if (!now) return void 0;
1101
- const files = changedFiles(before, now, (a, b) => a ? gitDiffFiles(root, a, b) : gitListFiles(root, b));
1102
- if (files.length < MIN_FILES) return void 0;
1103
- const last = input.last_assistant_message;
1104
- if (typeof last === "string" && DIAGRAM.test(last)) return void 0;
1105
- const transcript = input.transcript_path;
1106
- if (typeof transcript === "string" && turnUsedCodechart(readTail(transcript, MAX_TRANSCRIPT_TAIL))) return void 0;
1107
- return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "Stop", additionalContext: nudge(files.length) } })}
1108
- `;
1109
- }
1110
- async function runHook(event, opts) {
1111
- const input = await readInput(opts.stdin ?? (() => readStdin(MAX_INPUT, "stop")));
1112
- const id = input.session_id;
1113
- const cwd = input.cwd;
1114
- if (typeof id !== "string" || !SESSION_ID.test(id) || typeof cwd !== "string") return;
1115
- const root = findRepoRoot(cwd);
1116
- if (!root) return;
1117
- const dir = join3(opts.home ?? homedir2(), ".cache", "codechart", "turns");
1118
- const turn = { root, dir, file: join3(dir, `${id}.json`), input };
1119
- if (event === "prompt") onPrompt(turn, opts.now?.() ?? /* @__PURE__ */ new Date());
1120
- else {
1121
- const reminder = onStop(turn);
1122
- if (reminder) opts.stdout(reminder);
1123
- }
1124
- }
1125
- function hookCommand(opts) {
1126
- return new Command3("hook").description("Claude Code hook (install with install-skill --hook): asks for a diagram after a turn that changed 3+ files without one").addArgument(new Argument("<event>").choices(["prompt", "stop"])).action(async (event) => {
1127
- try {
1128
- await runHook(event, opts);
1129
- } catch (e) {
1130
- if ((opts.env ?? process.env).CODECHART_DEBUG) opts.stderr(`codechart: hook ${event}: ${e instanceof Error ? e.message : String(e)}
1131
- `);
1132
- }
1133
- });
1134
- }
1012
+ // src/commands/doctor-checks.ts
1013
+ import { accessSync, constants as constants3, existsSync as existsSync8, lstatSync as lstatSync7, statSync } from "fs";
1014
+ import { join as join13, posix, win32 as win322 } from "path";
1135
1015
 
1136
- // src/commands/init.ts
1137
- import { join as join5 } from "path";
1138
- import { Command as Command4 } from "commander";
1016
+ // src/update/check.ts
1017
+ import { readFileSync, writeFileSync as writeFileSync2 } from "fs";
1018
+ import { join as join7 } from "path";
1139
1019
 
1140
1020
  // src/assets.ts
1141
1021
  import { existsSync as existsSync3 } from "fs";
@@ -1151,85 +1031,1321 @@ function packageFile(relative4) {
1151
1031
  return join4(dir, relative4);
1152
1032
  }
1153
1033
 
1154
- // src/commands/copy-file.ts
1155
- import { constants as constants2, copyFileSync, existsSync as existsSync4, lstatSync as lstatSync3, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "fs";
1156
- import { dirname as dirname3 } from "path";
1157
- var isSymlink = (path3) => lstatSync3(path3, { throwIfNoEntry: false })?.isSymbolicLink() === true;
1158
- function copyFiles(pairs, force, opts) {
1034
+ // src/render/web/write.ts
1035
+ import { chmodSync, lstatSync as lstatSync3, mkdirSync, writeFileSync } from "fs";
1036
+ import { basename as basename2, dirname as dirname3 } from "path";
1037
+
1038
+ // src/render/output-path.ts
1039
+ import { createHash } from "crypto";
1040
+ import { basename, join as join5 } from "path";
1041
+ var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow)?)\.html$/;
1042
+ var pad = (n) => String(n).padStart(2, "0");
1043
+ function stamp(d) {
1044
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1045
+ }
1046
+ function parseStamp(s) {
1047
+ const n = (from, to) => Number(s.slice(from, to));
1048
+ return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
1049
+ }
1050
+ function slugify(title) {
1051
+ const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
1052
+ return slug || "map";
1053
+ }
1054
+ var fileSlug = (title, diagram) => diagram === "flow" ? `${slugify(title)}.flow` : slugify(title);
1055
+ function htmlOutputPath(config, repo, slug, now) {
1056
+ return join5(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
1057
+ }
1058
+ function repoFolder(root) {
1059
+ return `${basename(root)}-${createHash("sha256").update(root).digest("hex").slice(0, 8)}`;
1060
+ }
1061
+
1062
+ // src/render/prune.ts
1063
+ import { lstatSync as lstatSync2, readdirSync, rmSync } from "fs";
1064
+ import { join as join6 } from "path";
1065
+ var DAY_MS = 864e5;
1066
+ function pruneHtml(dir, opts) {
1067
+ let names;
1159
1068
  try {
1160
- const link = force ? void 0 : pairs.find(({ target }) => isSymlink(target));
1161
- if (link) {
1162
- opts.stderr(`codechart: ${link.target}: is a symlink (use --force to replace it)
1163
- `);
1164
- process.exitCode = 1;
1165
- return false;
1166
- }
1167
- const conflict2 = force ? void 0 : pairs.find(({ target }) => existsSync4(target));
1168
- if (conflict2) {
1169
- opts.stderr(`exists: ${conflict2.target} (use --force)
1170
- `);
1171
- process.exitCode = 1;
1172
- return false;
1173
- }
1174
- for (const { source, target } of pairs) {
1175
- mkdirSync2(dirname3(target), { recursive: true });
1176
- if (force && isSymlink(target)) unlinkSync2(target);
1177
- copyFileSync(source, target, force ? 0 : constants2.COPYFILE_EXCL);
1178
- opts.stdout(`wrote ${target}
1179
- `);
1069
+ if (lstatSync2(dir).isSymbolicLink()) return [];
1070
+ names = readdirSync(dir);
1071
+ } catch {
1072
+ return [];
1073
+ }
1074
+ const current = stamp(opts.now);
1075
+ const files = names.map((name) => ({ name, m: HTML_NAME.exec(name) })).filter((f) => f.m !== null).map(({ name, m }) => ({ name, stamp: m[1], slug: m[2] })).sort((a, b) => b.stamp.localeCompare(a.stamp));
1076
+ const doomed = /* @__PURE__ */ new Set();
1077
+ for (const f of files) if (f.slug === opts.replaceSlug && f.stamp < current) doomed.add(f.name);
1078
+ const cutoff = opts.now.getTime() - opts.maxAgeDays * DAY_MS;
1079
+ files.filter((f) => !doomed.has(f.name)).forEach((f, i) => {
1080
+ if (f.stamp !== current && i >= opts.keep && parseStamp(f.stamp).getTime() < cutoff) doomed.add(f.name);
1081
+ });
1082
+ const deleted = [];
1083
+ for (const name of doomed) {
1084
+ const file = join6(dir, name);
1085
+ try {
1086
+ rmSync(file);
1087
+ deleted.push(file);
1088
+ } catch {
1180
1089
  }
1181
- return true;
1182
- } catch (e) {
1183
- opts.stderr(`codechart: ${e.message}
1184
- `);
1185
- process.exitCode = 1;
1186
- return false;
1187
1090
  }
1091
+ return deleted;
1188
1092
  }
1189
1093
 
1190
- // src/commands/init.ts
1191
- function initCommand(opts) {
1192
- return new Command4("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
1193
- const root = findRepoRoot(opts.cwd ?? process.cwd());
1194
- if (!root) {
1195
- opts.stderr("codechart: not a git repository\n");
1196
- process.exitCode = 1;
1197
- return;
1198
- }
1199
- copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join5(root, ".codechart.yaml") }], o.force === true, opts);
1200
- });
1094
+ // src/render/web/write.ts
1095
+ function privateDir(dir) {
1096
+ if (lstatSync3(dir, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`${dir}: is a symlink; refusing to write`);
1097
+ mkdirSync(dir, { recursive: true, mode: 448 });
1098
+ chmodSync(dir, 448);
1099
+ }
1100
+ async function writeHtml(build, o) {
1101
+ const { config, now } = o;
1102
+ const file = htmlOutputPath(config, repoFolder(o.root), o.slug, now);
1103
+ const html = await build({ generatedAt: now, repo: basename2(o.root), repoKey: repoFolder(o.root), theme: o.theme, ...o.update && { update: o.update } });
1104
+ const dir = dirname3(file);
1105
+ privateDir(dir);
1106
+ writeFileSync(file, html, { mode: 384 });
1107
+ pruneHtml(dir, { ...config.web, now, replaceSlug: o.slug });
1108
+ const mode = config.web.open;
1109
+ if (!(o.forceOpen || mode === "always" || mode === "auto" && o.inEditor)) return { file, openFailed: false };
1110
+ const failed = o.open(file);
1111
+ if (failed) o.stderr(`codechart: could not open the browser (${failed})
1112
+ `);
1113
+ return { file, openFailed: Boolean(failed) };
1201
1114
  }
1202
1115
 
1203
- // src/commands/pr-sync.ts
1204
- import { randomUUID } from "crypto";
1205
- import { mkdtempSync, readFileSync as readFileSync4, rmSync as rmSync2 } from "fs";
1206
- import { tmpdir } from "os";
1207
- import { join as join11 } from "path";
1208
- import { Command as Command6 } from "commander";
1209
-
1210
- // src/render/terminal/check-lines.ts
1211
- var MAX_SHOWN = 5;
1212
- var UNCHECKED = "diff not checked";
1213
- var units = (n, unit) => `${n} ${unit}${n === 1 ? "" : "s"}`;
1214
- var uncoveredHead = (n) => `\u2717 ${n} changed ${n === 1 ? "file" : "files"} not on map`;
1215
- var flagged = (c) => Boolean(c?.mismatches.length || c?.uncovered?.length);
1216
- function checkTag(c) {
1217
- const unchecked = c?.diffUnchecked ? ` \xB7 ${UNCHECKED}` : "";
1218
- if (!c || c.checked === 0) return unchecked;
1219
- const total = c.unit === "node" ? String(c.checked) : units(c.checked, c.unit);
1220
- return ` \xB7 \u2713 ${c.mismatches.length ? `${c.checked - c.mismatches.length} of ` : ""}${total} checked${unchecked}`;
1116
+ // src/update/check.ts
1117
+ var REGISTRY = "https://registry.npmjs.org/codechart/latest";
1118
+ var DAY = 24 * 60 * 60 * 1e3;
1119
+ var VERSION = /^\d+\.\d+\.\d+$/;
1120
+ var currentVersion = () => JSON.parse(readFileSync(packageFile("package.json"), "utf8")).version;
1121
+ function isNewer(a, b) {
1122
+ if (!VERSION.test(a) || !VERSION.test(b)) return false;
1123
+ const [x, y] = [a, b].map((v) => v.split(".").map(Number));
1124
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
1125
+ return false;
1221
1126
  }
1222
- function itemsLine(head, all, width) {
1223
- const items = all.slice(0, MAX_SHOWN);
1224
- if (all.length > MAX_SHOWN) items.push(`+${all.length - MAX_SHOWN} more`);
1225
- if (columns(head) <= width / 2) return wrapItems(head, items, width);
1226
- return `${truncate(head.trimEnd(), width)}
1227
- ${wrapItems(" ", items, width)}`;
1127
+ async function fetchLatest(fetchFn, timeoutMs) {
1128
+ try {
1129
+ const res = await fetchFn(REGISTRY, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1130
+ if (!res.ok) return void 0;
1131
+ const version = (await res.json()).version;
1132
+ return typeof version === "string" && VERSION.test(version) ? version : void 0;
1133
+ } catch {
1134
+ return void 0;
1135
+ }
1228
1136
  }
1229
- function alertLine(c, width) {
1230
- if (!c) return "";
1231
- const lines = [];
1232
- const n = c.mismatches.length;
1137
+ var stateFile = (cacheDir) => join7(cacheDir, "update-check.json");
1138
+ function readState(cacheDir) {
1139
+ try {
1140
+ const raw = JSON.parse(readFileSync(stateFile(cacheDir), "utf8"));
1141
+ return typeof raw === "object" && raw !== null ? raw : {};
1142
+ } catch {
1143
+ return {};
1144
+ }
1145
+ }
1146
+ function writeState(cacheDir, state) {
1147
+ try {
1148
+ privateDir(cacheDir);
1149
+ writeFileSync2(stateFile(cacheDir), JSON.stringify(state), { mode: 384 });
1150
+ } catch {
1151
+ }
1152
+ }
1153
+ var skillDirs = (state) => Array.isArray(state.skillDirs) ? state.skillDirs.filter((d) => typeof d === "string") : [];
1154
+ function rememberSkillDir(cacheDir, dir) {
1155
+ const state = readState(cacheDir);
1156
+ const dirs = skillDirs(state);
1157
+ if (!dirs.includes(dir)) writeState(cacheDir, { ...state, skillDirs: [...dirs, dir] });
1158
+ }
1159
+ function knownUpdate(cacheDir, current = currentVersion()) {
1160
+ const { latest } = readState(cacheDir);
1161
+ return latest && isNewer(latest, current) ? latest : void 0;
1162
+ }
1163
+ function checkAllowed(c, installPath = packageFile("")) {
1164
+ const e = c.env;
1165
+ return c.enabled && !e.CODECHART_NO_UPDATE_CHECK && !e.NO_UPDATE_NOTIFIER && !e.CI && !/[\\/]_npx[\\/]/.test(installPath);
1166
+ }
1167
+ async function updateNotice(c) {
1168
+ if (!checkAllowed(c)) return void 0;
1169
+ const state = readState(c.cacheDir);
1170
+ let changed = false;
1171
+ if (!state.checkedAt || c.now - state.checkedAt >= DAY) {
1172
+ changed = true;
1173
+ const latest = await fetchLatest(c.fetch, 1e3);
1174
+ Object.assign(state, { checkedAt: c.now }, latest ? { latest } : {});
1175
+ }
1176
+ const current = c.current ?? currentVersion();
1177
+ const told = c.terminal ? "toldTerminal" : "toldAgent";
1178
+ let line;
1179
+ if (state.latest && isNewer(state.latest, current) && c.now - (state[told] ?? 0) >= DAY) {
1180
+ state[told] = c.now;
1181
+ changed = true;
1182
+ line = c.terminal ? `codechart ${state.latest} is available (you have ${current}): run codechart update` : `codechart ${state.latest} is available (you have ${current}). Tell the user once: run \`codechart update\`.`;
1183
+ }
1184
+ if (changed) writeState(c.cacheDir, state);
1185
+ return line;
1186
+ }
1187
+
1188
+ // src/commands/agents.ts
1189
+ import { lstatSync as lstatSync4 } from "fs";
1190
+ import { join as join8 } from "path";
1191
+ var SHARED = ".agents/skills";
1192
+ var AGENTS = [
1193
+ { name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [], instructions: ".claude/CLAUDE.md" },
1194
+ { name: "codex", label: "Codex", home: ".codex", skills: SHARED, reads: [], instructions: ".codex/AGENTS.md" },
1195
+ { name: "gemini", label: "Gemini CLI", home: ".gemini", skills: ".gemini/skills", reads: [SHARED], instructions: ".gemini/GEMINI.md" },
1196
+ { name: "copilot", label: "GitHub Copilot", home: ".copilot", skills: ".copilot/skills", reads: [SHARED] },
1197
+ { name: "cursor", label: "Cursor", home: ".cursor", skills: ".cursor/skills", reads: [SHARED, ".claude/skills", ".codex/skills"] },
1198
+ { name: "opencode", label: "OpenCode", home: ".config/opencode", skills: ".config/opencode/skills", reads: [SHARED, ".claude/skills"], instructions: ".config/opencode/AGENTS.md" },
1199
+ { name: "goose", label: "Goose", home: ".config/goose", skills: SHARED, reads: [".claude/skills"] },
1200
+ { name: "amp", label: "Amp", home: ".config/amp", skills: ".config/agents/skills", reads: [".claude/skills"] },
1201
+ { name: "windsurf", label: "Windsurf", home: ".codeium/windsurf", skills: ".codeium/windsurf/skills", reads: [SHARED] },
1202
+ { name: "cline", label: "Cline", home: ".cline", skills: ".cline/skills", reads: [] },
1203
+ { name: "roo", label: "Roo Code", home: ".roo", skills: ".roo/skills", reads: [SHARED] },
1204
+ { name: "kiro", label: "Kiro", home: ".kiro", skills: ".kiro/skills", reads: [] },
1205
+ { name: "junie", label: "Junie", home: ".junie", skills: ".junie/skills", reads: [] },
1206
+ { name: "droid", label: "Factory Droid", home: ".factory", skills: ".factory/skills", reads: [] }
1207
+ ];
1208
+ function skillFolders(agents) {
1209
+ const groups = [];
1210
+ for (const a of agents) {
1211
+ const shared = groups.find((g) => [a.skills, ...a.reads].includes(g.folder));
1212
+ if (shared) shared.agents.push(a);
1213
+ else groups.push({ folder: a.skills, agents: [a] });
1214
+ }
1215
+ return groups;
1216
+ }
1217
+ function isCodechartSkill(dir) {
1218
+ const skill = join8(dir, "SKILL.md");
1219
+ const text = lstatSync4(skill, { throwIfNoEntry: false })?.isFile() ? readRegularFile(skill, (s) => s.isFile()) : void 0;
1220
+ return text !== void 0 && /^---\r?\n(?:.*\r?\n)*?name: codechart\r?\n/.test(text);
1221
+ }
1222
+
1223
+ // src/commands/install-skill.ts
1224
+ import { existsSync as existsSync6, readdirSync as readdirSync2 } from "fs";
1225
+ import { homedir as homedir2 } from "os";
1226
+ import { join as join11, resolve as resolve3 } from "path";
1227
+ import { Command as Command3 } from "commander";
1228
+
1229
+ // src/commands/copy-file.ts
1230
+ import { constants as constants2, copyFileSync, existsSync as existsSync4, lstatSync as lstatSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync2, unlinkSync } from "fs";
1231
+ import { dirname as dirname4 } from "path";
1232
+ var isSymlink = (path3) => lstatSync5(path3, { throwIfNoEntry: false })?.isSymbolicLink() === true;
1233
+ function copyFiles(pairs, force, opts) {
1234
+ try {
1235
+ const link = force ? void 0 : pairs.find(({ target }) => isSymlink(target));
1236
+ if (link) {
1237
+ opts.stderr(`codechart: ${link.target}: is a symlink (use --force to replace it)
1238
+ `);
1239
+ process.exitCode = 1;
1240
+ return false;
1241
+ }
1242
+ const conflict2 = force ? void 0 : pairs.find(({ target }) => existsSync4(target));
1243
+ if (conflict2) {
1244
+ opts.stderr(`exists: ${conflict2.target} (use --force)
1245
+ `);
1246
+ process.exitCode = 1;
1247
+ return false;
1248
+ }
1249
+ for (const { source, target } of pairs) {
1250
+ mkdirSync2(dirname4(target), { recursive: true });
1251
+ if (force && isSymlink(target)) unlinkSync(target);
1252
+ copyFileSync(source, target, force ? 0 : constants2.COPYFILE_EXCL);
1253
+ opts.stdout(`wrote ${target}
1254
+ `);
1255
+ }
1256
+ return true;
1257
+ } catch (e) {
1258
+ opts.stderr(`codechart: ${e.message}
1259
+ `);
1260
+ process.exitCode = 1;
1261
+ return false;
1262
+ }
1263
+ }
1264
+ var hasAny = (paths) => paths.some((p) => {
1265
+ try {
1266
+ return lstatSync5(p, { throwIfNoEntry: false }) !== void 0;
1267
+ } catch {
1268
+ return false;
1269
+ }
1270
+ });
1271
+ var sameFile = ({ source, target }) => {
1272
+ try {
1273
+ return readRegularFile(target, (st) => st.isFile()) === readFileSync2(source, "utf8");
1274
+ } catch {
1275
+ return false;
1276
+ }
1277
+ };
1278
+ function installPairs(pairs, where, who, ours2, force, opts) {
1279
+ let update2 = force;
1280
+ if (!force && hasAny(pairs.map((p) => p.target))) {
1281
+ if (pairs.every(sameFile)) {
1282
+ opts.stdout(`up to date for ${who}: ${where}
1283
+ `);
1284
+ return true;
1285
+ }
1286
+ let mine;
1287
+ try {
1288
+ mine = ours2();
1289
+ } catch (e) {
1290
+ opts.stderr(`codechart: ${e.message}
1291
+ `);
1292
+ process.exitCode = 1;
1293
+ return false;
1294
+ }
1295
+ if (!mine) {
1296
+ opts.stdout(`already installed for ${who}: ${where} (--force to update)
1297
+ `);
1298
+ return false;
1299
+ }
1300
+ update2 = true;
1301
+ }
1302
+ if (!copyFiles(pairs, update2, { ...opts, stdout: () => {
1303
+ } })) return false;
1304
+ opts.stdout(`${update2 && !force ? "updated" : "installed"} for ${who}: ${where}
1305
+ `);
1306
+ return true;
1307
+ }
1308
+
1309
+ // src/commands/nudges.ts
1310
+ import { mkdirSync as mkdirSync3, realpathSync as realpathSync2, writeFileSync as writeFileSync3 } from "fs";
1311
+ import { dirname as dirname5 } from "path";
1312
+ var REMINDER = "Before summarizing or planning a change that touches 3+ files or adds behaviour with branches, use the codechart skill (skip it for small edits: typos, formatting, one-line fixes).";
1313
+ var START = "<!-- codechart -->";
1314
+ var END = "<!-- /codechart -->";
1315
+ var BLOCK = `${START}
1316
+ ${REMINDER}
1317
+ ${END}`;
1318
+ function readRegular(file) {
1319
+ let path3;
1320
+ try {
1321
+ path3 = realpathSync2(file);
1322
+ } catch (e) {
1323
+ if (e.code === "ENOENT") return { path: file };
1324
+ throw e;
1325
+ }
1326
+ const text = readRegularFile(path3, (st) => st.isFile());
1327
+ if (text === void 0) throw new Error(`${file}: not a regular file`);
1328
+ return { path: path3, text };
1329
+ }
1330
+ function blockAt(text) {
1331
+ const at = text.indexOf(START);
1332
+ const end = at < 0 ? -1 : text.indexOf(END, at);
1333
+ return end > at ? [at, end + END.length] : void 0;
1334
+ }
1335
+ function refreshReminder(file) {
1336
+ let text;
1337
+ try {
1338
+ text = readRegular(file).text;
1339
+ } catch {
1340
+ return "absent";
1341
+ }
1342
+ return text !== void 0 && blockAt(text) ? addReminder(file) === "updated" ? "updated" : "present" : "absent";
1343
+ }
1344
+ function addReminder(file) {
1345
+ const { path: path3, text = "" } = readRegular(file);
1346
+ const block = blockAt(text);
1347
+ if (block) {
1348
+ if (text.slice(...block) === BLOCK) return "present";
1349
+ writeFileSync3(path3, text.slice(0, block[0]) + BLOCK + text.slice(block[1]));
1350
+ return "updated";
1351
+ }
1352
+ mkdirSync3(dirname5(path3), { recursive: true });
1353
+ const gap = text === "" || text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
1354
+ writeFileSync3(path3, `${text}${gap}${BLOCK}
1355
+ `);
1356
+ return "added";
1357
+ }
1358
+ function reminderState(file) {
1359
+ let text;
1360
+ try {
1361
+ text = readRegular(file).text;
1362
+ } catch {
1363
+ return "missing";
1364
+ }
1365
+ const block = text === void 0 ? void 0 : blockAt(text);
1366
+ if (!text || !block) return "missing";
1367
+ return text.slice(...block) === BLOCK ? "present" : "outdated";
1368
+ }
1369
+ function removeReminder(file) {
1370
+ const { path: path3, text } = readRegular(file);
1371
+ const block = text === void 0 ? void 0 : blockAt(text);
1372
+ if (!text || !block) return "absent";
1373
+ const before = text.slice(0, block[0]).replace(/\n\n$/, "\n");
1374
+ const after = text.slice(block[1]).replace(/^\n/, "");
1375
+ writeFileSync3(path3, before + after);
1376
+ return "removed";
1377
+ }
1378
+ var HOOK_COMMANDS = { UserPromptSubmit: "codechart hook prompt", Stop: "codechart hook stop" };
1379
+ var TIMEOUTS = { UserPromptSubmit: 10, Stop: 30 };
1380
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1381
+ var isCodechartHook = (h) => isObject(h) && typeof h.command === "string" && h.command.startsWith("codechart hook ");
1382
+ var runs = (command) => (h) => isObject(h) && h.command === command;
1383
+ var hasHook = (groups, is) => groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(is));
1384
+ function withoutCodechart(groups) {
1385
+ let removed = false;
1386
+ const kept = groups.flatMap((g) => {
1387
+ if (!isObject(g) || !Array.isArray(g.hooks) || !g.hooks.some(isCodechartHook)) return [g];
1388
+ removed = true;
1389
+ const hooks = g.hooks.filter((h) => !isCodechartHook(h));
1390
+ return hooks.length ? [{ ...g, hooks }] : [];
1391
+ });
1392
+ return { kept, removed };
1393
+ }
1394
+ function readSettings(file) {
1395
+ const { path: path3, text } = readRegular(file);
1396
+ let settings;
1397
+ try {
1398
+ settings = text === void 0 || text.trim() === "" ? {} : JSON.parse(text);
1399
+ } catch {
1400
+ throw new Error(`${file}: not valid JSON; edit the hooks by hand: https://github.com/freeleex/codechart/blob/main/docs/install.md#help-agents-remember-it`);
1401
+ }
1402
+ if (!isObject(settings)) throw new Error(`${file}: not a JSON object`);
1403
+ settings.hooks ??= {};
1404
+ if (!isObject(settings.hooks)) throw new Error(`${file}: "hooks" is not an object`);
1405
+ return { path: path3, settings };
1406
+ }
1407
+ function installClaudeHooks(file) {
1408
+ const { path: path3, settings } = readSettings(file);
1409
+ let added = false;
1410
+ for (const [event, command] of Object.entries(HOOK_COMMANDS)) {
1411
+ const groups = settings.hooks[event] ??= [];
1412
+ if (!Array.isArray(groups)) throw new Error(`${file}: "hooks.${event}" is not a list`);
1413
+ if (hasHook(groups, runs(command))) continue;
1414
+ settings.hooks[event] = [...withoutCodechart(groups).kept, { hooks: [{ type: "command", command, timeout: TIMEOUTS[event] }] }];
1415
+ added = true;
1416
+ }
1417
+ if (!added) return "present";
1418
+ mkdirSync3(dirname5(path3), { recursive: true });
1419
+ writeFileSync3(path3, `${JSON.stringify(settings, null, 2)}
1420
+ `);
1421
+ return "added";
1422
+ }
1423
+ function claudeHookEvents(file) {
1424
+ const { settings } = readSettings(file);
1425
+ const state = { ok: [], wrong: [] };
1426
+ for (const [event, command] of Object.entries(HOOK_COMMANDS)) {
1427
+ const groups = settings.hooks[event];
1428
+ if (!Array.isArray(groups)) continue;
1429
+ if (hasHook(groups, runs(command))) state.ok.push(event);
1430
+ else if (hasHook(groups, isCodechartHook)) state.wrong.push(event);
1431
+ }
1432
+ return state;
1433
+ }
1434
+ function removeClaudeHooks(file) {
1435
+ const { path: path3, settings } = readSettings(file);
1436
+ let removed = false;
1437
+ for (const [event, groups] of Object.entries(settings.hooks)) {
1438
+ if (!Array.isArray(groups)) continue;
1439
+ const out = withoutCodechart(groups);
1440
+ removed ||= out.removed;
1441
+ if (out.kept.length) settings.hooks[event] = out.kept;
1442
+ else delete settings.hooks[event];
1443
+ }
1444
+ if (!removed) return "absent";
1445
+ const { hooks, ...rest } = settings;
1446
+ writeFileSync3(path3, `${JSON.stringify(Object.keys(hooks).length ? settings : rest, null, 2)}
1447
+ `);
1448
+ return "removed";
1449
+ }
1450
+
1451
+ // src/commands/opencode-plugin.ts
1452
+ import { existsSync as existsSync5, lstatSync as lstatSync6, unlinkSync as unlinkSync2 } from "fs";
1453
+ import { isAbsolute as isAbsolute2, join as join9 } from "path";
1454
+ var MARK = "codechart OpenCode plugin";
1455
+ function pluginFile(home, env) {
1456
+ const xdg = env.XDG_CONFIG_HOME;
1457
+ return join9(xdg && isAbsolute2(xdg) ? xdg : join9(home, ".config"), "opencode", "plugins", "codechart.js");
1458
+ }
1459
+ var pair = (file) => ({ source: packageFile("dist/server.js"), target: file });
1460
+ function isOurs(file) {
1461
+ try {
1462
+ return readRegularFile(file, (st) => st.isFile())?.includes(MARK) === true;
1463
+ } catch {
1464
+ return false;
1465
+ }
1466
+ }
1467
+ function pluginState(file) {
1468
+ if (lstatSync6(file, { throwIfNoEntry: false }) === void 0) return "missing";
1469
+ if (sameFile(pair(file))) return "current";
1470
+ return isOurs(file) ? "outdated" : "foreign";
1471
+ }
1472
+ var installPlugin = (file, force, opts) => installPairs([pair(file)], file, "OpenCode plugin", () => isOurs(file), force, opts);
1473
+ function removePlugin(file) {
1474
+ const state = pluginState(file);
1475
+ if (state === "missing") return "absent";
1476
+ if (state === "foreign") return "foreign";
1477
+ if (existsSync5(file)) unlinkSync2(file);
1478
+ return "removed";
1479
+ }
1480
+
1481
+ // src/commands/opencode-version.ts
1482
+ import { execFileSync as execFileSync2 } from "child_process";
1483
+ import { join as join10 } from "path";
1484
+ var run = (opts, command) => opts.tool ? opts.tool(command, ["--version"]) : execFileSync2(command, ["--version"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
1485
+ function opencodeVersion(opts, home) {
1486
+ for (const command of ["opencode", join10(home, ".opencode", "bin", "opencode")]) {
1487
+ try {
1488
+ const v = /(\d+\.\d+(?:\.\d+)?)/.exec(run(opts, command))?.[1];
1489
+ if (v) return v;
1490
+ } catch {
1491
+ continue;
1492
+ }
1493
+ }
1494
+ return void 0;
1495
+ }
1496
+ function pluginBlocker(opts, home) {
1497
+ const v = opencodeVersion(opts, home);
1498
+ if (v === void 0) return "needs OpenCode 2 (not found)";
1499
+ return Number(v.split(".")[0]) >= 2 ? void 0 : `needs OpenCode 2 (found ${v.split(".")[0]}.x)`;
1500
+ }
1501
+
1502
+ // src/commands/picker.ts
1503
+ import { emitKeypressEvents } from "readline";
1504
+ function pickerStep(s, key) {
1505
+ const n = s.checked.length;
1506
+ switch (key.ctrl ? `ctrl-${key.name}` : key.name ?? key.sequence) {
1507
+ case "up":
1508
+ case "k":
1509
+ return { ...s, cursor: (s.cursor + n - 1) % n };
1510
+ case "down":
1511
+ case "j":
1512
+ return { ...s, cursor: (s.cursor + 1) % n };
1513
+ case "space":
1514
+ return { ...s, checked: s.checked.map((c, i) => i === s.cursor ? !c : c) };
1515
+ case "a": {
1516
+ const all = s.checked.every(Boolean);
1517
+ return { ...s, checked: s.checked.map(() => !all) };
1518
+ }
1519
+ case "return":
1520
+ return { ...s, done: "ok" };
1521
+ case "escape":
1522
+ case "ctrl-c":
1523
+ return { ...s, done: "cancel" };
1524
+ default:
1525
+ return s;
1526
+ }
1527
+ }
1528
+ var cut = (text, max) => text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}\u2026`;
1529
+ var dim = (text) => text ? `\x1B[2m${text}\x1B[0m` : "";
1530
+ function pickerLines(title, items2, s, width = Infinity) {
1531
+ const pad2 = Math.max(...items2.map((i) => i.label.length));
1532
+ return [
1533
+ cut(title, width),
1534
+ ...items2.map((it, i) => {
1535
+ const head = cut(`${i === s.cursor ? "\u276F" : " "} ${s.checked[i] ? "\u25C9" : "\u25EF"} ${it.label.padEnd(pad2)} `, width);
1536
+ return head + dim(cut(it.hint, width - head.length));
1537
+ }),
1538
+ dim(cut("\u2191/\u2193 move \xB7 Space toggle \xB7 a all \xB7 Enter confirm \xB7 Esc cancel", width))
1539
+ ];
1540
+ }
1541
+ function terminalPicker(title, items2, checked = true) {
1542
+ const { stdin, stdout } = process;
1543
+ let s = { cursor: 0, checked: items2.map(() => checked) };
1544
+ let drawn = 0;
1545
+ const draw = () => {
1546
+ const lines = pickerLines(title, items2, s, (stdout.columns || 80) - 1);
1547
+ stdout.write((drawn ? `\x1B[${drawn}A\r\x1B[0J` : "") + lines.join("\n") + "\n");
1548
+ drawn = lines.length;
1549
+ };
1550
+ return new Promise((resolve11) => {
1551
+ emitKeypressEvents(stdin);
1552
+ stdin.setRawMode(true);
1553
+ stdin.resume();
1554
+ stdout.write("\x1B[?25l");
1555
+ draw();
1556
+ const onKey = (_, key) => {
1557
+ s = pickerStep(s, key ?? {});
1558
+ if (!s.done) return draw();
1559
+ stdin.off("keypress", onKey);
1560
+ stdin.setRawMode(false);
1561
+ stdin.pause();
1562
+ stdout.write("\x1B[?25h");
1563
+ resolve11(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
1564
+ };
1565
+ stdin.on("keypress", onKey);
1566
+ });
1567
+ }
1568
+
1569
+ // src/commands/install-skill.ts
1570
+ var NAMES = AGENTS.map((a) => a.name).join(", ");
1571
+ var terminalChoose = () => process.stdin.isTTY && process.stdout.isTTY ? terminalPicker : void 0;
1572
+ var skillFiles = () => readdirSync2(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
1573
+ var skillIsCurrent = (dir, files) => files.every((f) => sameFile({ source: packageFile(`skills/codechart/${f}`), target: join11(dir, f) }));
1574
+ var hasClaude = (agents) => agents.some((a) => a.name === "claude");
1575
+ var hasOpencode = (agents) => agents.some((a) => a.name === "opencode");
1576
+ async function chooseExtras(agents, opts) {
1577
+ const choose = opts.choose ?? terminalChoose();
1578
+ const files = agents.flatMap((a) => a.instructions ? [`~/${a.instructions}`] : []);
1579
+ const items2 = [];
1580
+ if (files.length) items2.push({ key: "reminder", label: "Reminder line", hint: `use codechart for 3+ file changes \u2192 ${files.join(", ")}` });
1581
+ if (hasClaude(agents)) {
1582
+ items2.push({ key: "hook", label: "Claude Code hook", hint: "ask for a diagram when a turn changed 3+ files \u2192 ~/.claude/settings.json" });
1583
+ }
1584
+ if (hasOpencode(agents)) {
1585
+ items2.push({ key: "plugin", label: "OpenCode plugin", hint: "ask for a diagram when a turn changed 3+ files \u2192 ~/.config/opencode/plugins/codechart.js" });
1586
+ }
1587
+ if (!choose || items2.length === 0) return { reminder: true, hook: hasClaude(agents), plugin: hasOpencode(agents) };
1588
+ const picked = await choose("Agents forget skills in long sessions; these help them remember codechart:", items2, true);
1589
+ const keys = new Set((picked ?? []).map((i) => items2[i].key));
1590
+ return { reminder: keys.has("reminder"), hook: keys.has("hook"), plugin: keys.has("plugin") };
1591
+ }
1592
+ async function pickExtras(o, agents, opts) {
1593
+ const plugin = hasOpencode(agents);
1594
+ if (o.reminder === true || o.hook === true || o.plugin === true) return { reminder: o.reminder === true, hook: o.hook === true, plugin: o.plugin === true && plugin };
1595
+ if (o.reminder === void 0 && o.hook === void 0 && o.plugin === void 0 && o.agent === void 0) return chooseExtras(agents, opts);
1596
+ return { reminder: o.reminder !== false, hook: o.hook !== false && hasClaude(agents), plugin: o.plugin !== false && plugin };
1597
+ }
1598
+ function installExtras(extras, agents, home, force, opts) {
1599
+ const report = (what, run2) => {
1600
+ try {
1601
+ opts.stdout(`${run2()}
1602
+ `);
1603
+ } catch (e) {
1604
+ opts.stderr(`codechart: ${what}: ${e.message}
1605
+ `);
1606
+ process.exitCode = 1;
1607
+ }
1608
+ };
1609
+ if (extras.reminder) {
1610
+ for (const a of agents) {
1611
+ if (!a.instructions) continue;
1612
+ const file = join11(home, a.instructions);
1613
+ report("reminder", () => {
1614
+ const r = addReminder(file);
1615
+ return r === "present" ? `reminder already in ${file}` : `reminder ${r}: ${file}`;
1616
+ });
1617
+ }
1618
+ }
1619
+ if (extras.hook) {
1620
+ const file = join11(home, ".claude", "settings.json");
1621
+ report("hook", () => installClaudeHooks(file) === "added" ? `hook added: ${file}` : `hook already in ${file}`);
1622
+ }
1623
+ if (extras.plugin) {
1624
+ const blocker = pluginBlocker(opts, home);
1625
+ if (blocker) opts.stdout(`OpenCode plugin skipped: ${blocker}
1626
+ `);
1627
+ else installPlugin(pluginFile(home, opts.env ?? process.env), force, opts);
1628
+ }
1629
+ }
1630
+ var YOUR_FOLDER = "your folder";
1631
+ function rememberOwn(installed, opts) {
1632
+ const own = installed.find((t) => t.who === YOUR_FOLDER);
1633
+ if (!own) return;
1634
+ try {
1635
+ rememberSkillDir(loadConfig({ cwd: opts.cwd ?? process.cwd(), home: opts.home, env: opts.env }).web.outDir, own.dir);
1636
+ } catch {
1637
+ }
1638
+ }
1639
+ function installCopy(dir, who, files, force, opts) {
1640
+ const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join11(dir, f) }));
1641
+ return installPairs(pairs, dir, who, () => isCodechartSkill(dir), force, opts);
1642
+ }
1643
+ function installSkillCommand(opts) {
1644
+ return new Command3("install-skill").description("install the skill for the agents found in your home folder (or --agent / --dir)").option("--agent <names...>", `install for these agents: ${NAMES}`).option("--dir <path>", "install into this skills folder").option("--force", "overwrite an install that is not an older codechart copy").option("--reminder", "only the reminder line in each agent's global instructions file (all extras are added by default)").option("--no-reminder", "skip the reminder line").option("--hook", "only the Claude Code hook that asks for a diagram after a turn that changed 3+ files without one").option("--no-hook", "skip the Claude Code hook").option("--plugin", "only the OpenCode plugin that asks for a diagram after a turn that changed 3+ files without one").option("--no-plugin", "skip the OpenCode plugin").action(async (o) => {
1645
+ const home = opts.home ?? homedir2();
1646
+ const names = o.agent?.flatMap((n) => n.split(",")).map((n) => n.trim().toLowerCase()).filter(Boolean);
1647
+ const unknown = names?.find((n) => !AGENTS.some((a) => a.name === n));
1648
+ if (unknown !== void 0) {
1649
+ opts.stderr(`codechart: unknown agent '${unknown}' (known: ${NAMES})
1650
+ `);
1651
+ process.exitCode = 1;
1652
+ return;
1653
+ }
1654
+ let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync6(join11(home, a.home))) : [];
1655
+ if (agents.length === 0 && o.dir === void 0) {
1656
+ opts.stderr(`codechart: no agent found in ${home}; use --agent <name> (${NAMES}) or --dir <path>
1657
+ `);
1658
+ process.exitCode = 1;
1659
+ return;
1660
+ }
1661
+ if (!names && agents.length > 0) {
1662
+ const choose = opts.choose ?? terminalChoose();
1663
+ if (choose && agents.length > 1) {
1664
+ const found = agents;
1665
+ const picked = await choose(
1666
+ "Install the codechart skill for:",
1667
+ found.map((a) => ({ label: a.label, hint: `~/${a.skills}` }))
1668
+ );
1669
+ if (picked === void 0) {
1670
+ opts.stderr("codechart: cancelled, nothing installed\n");
1671
+ process.exitCode = 1;
1672
+ return;
1673
+ }
1674
+ if (picked.length === 0) {
1675
+ opts.stdout("nothing selected, nothing installed\n");
1676
+ return;
1677
+ }
1678
+ agents = picked.map((i) => found[i]);
1679
+ } else {
1680
+ opts.stdout(`agents: ${agents.map((a) => a.label).join(", ")}
1681
+ `);
1682
+ }
1683
+ }
1684
+ const files = skillFiles();
1685
+ const groups = skillFolders(agents);
1686
+ for (const folder of new Set(agents.flatMap((a) => [a.skills, ...a.reads]))) {
1687
+ if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join11(home, folder, "codechart", f)))) continue;
1688
+ groups.push({ folder, agents: agents.filter((a) => [a.skills, ...a.reads].includes(folder)) });
1689
+ }
1690
+ const targets = groups.map((g) => ({ dir: join11(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", "), agents: g.agents }));
1691
+ if (o.dir !== void 0) targets.push({ dir: join11(resolve3(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: YOUR_FOLDER, agents: [] });
1692
+ const installed = targets.filter((t) => installCopy(t.dir, t.who, files, o.force === true, opts));
1693
+ rememberOwn(installed, opts);
1694
+ const ready = new Set(installed.flatMap((t) => t.agents));
1695
+ agents = agents.filter((a) => ready.has(a));
1696
+ if (agents.length) installExtras(await pickExtras(o, agents, opts), agents, home, o.force === true, opts);
1697
+ });
1698
+ }
1699
+
1700
+ // src/commands/update.ts
1701
+ import { execFileSync as execFileSync3, spawnSync } from "child_process";
1702
+ import { existsSync as existsSync7, realpathSync as realpathSync3 } from "fs";
1703
+ import { homedir as homedir3 } from "os";
1704
+ import { dirname as dirname6, join as join12, resolve as resolve4, sep as sep2 } from "path";
1705
+ import { Command as Command4 } from "commander";
1706
+ var RELEASES = "https://github.com/freeleex/codechart/releases";
1707
+ var spawnOptions = (command, platform = process.platform) => platform === "win32" && command === "npm" ? { shell: true, cwd: dirname6(process.execPath) } : { shell: false };
1708
+ var binary = (command) => command === "codechart" ? [process.execPath, [process.argv[1]]] : [command, []];
1709
+ var defaultRunner = {
1710
+ capture: (command, args) => execFileSync3(command, args, { encoding: "utf8", ...spawnOptions(command), stdio: ["ignore", "pipe", "ignore"], timeout: 3e4 }),
1711
+ show: (command, args) => {
1712
+ const [bin, pre] = binary(command);
1713
+ const r = spawnSync(bin, [...pre, ...args], { stdio: "inherit", ...spawnOptions(command) });
1714
+ if (r.status !== 0) throw new Error(`${command} ${args.join(" ")} failed${r.error ? `: ${r.error.message}` : ""}`);
1715
+ }
1716
+ };
1717
+ function installedBy(installDir, npmRoot) {
1718
+ const real = (p) => existsSync7(p) ? realpathSync3(p) : resolve4(p);
1719
+ if (npmRoot && real(installDir) === real(join12(npmRoot, "codechart"))) return { npm: true };
1720
+ if (/[\\/]_npx[\\/]/.test(installDir)) return { npm: false, hint: "npx runs the newest codechart already; nothing to update" };
1721
+ if (installDir.includes(`${sep2}pnpm${sep2}`) || installDir.includes("/pnpm/")) return { npm: false, hint: "update it with: pnpm add -g codechart@latest" };
1722
+ if (installDir.includes(".bun")) return { npm: false, hint: "update it with: bun add -g codechart@latest" };
1723
+ if (installDir.includes("yarn")) return { npm: false, hint: "update it with: yarn global add codechart@latest" };
1724
+ return { npm: false, hint: `it isn't npm's global copy (${installDir}); update it the way you installed it` };
1725
+ }
1726
+ var cacheDirOf = (opts) => loadConfig({ cwd: opts.cwd ?? process.cwd(), home: opts.home, env: opts.env }).web.outDir;
1727
+ function refreshInstalls(home, opts) {
1728
+ const files = skillFiles();
1729
+ const folders = [...new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))];
1730
+ const dirs = [
1731
+ ...folders.map((folder) => ({ dir: join12(home, folder, "codechart"), who: AGENTS.filter((a) => [a.skills, ...a.reads].includes(folder)).map((a) => a.label).join(", ") })),
1732
+ ...skillDirs(readState(cacheDirOf(opts))).map((dir) => ({ dir, who: "your folder" }))
1733
+ ];
1734
+ for (const { dir, who } of dirs) {
1735
+ let ours2 = false;
1736
+ try {
1737
+ ours2 = existsSync7(dir) && isCodechartSkill(dir);
1738
+ } catch {
1739
+ ours2 = false;
1740
+ }
1741
+ if (!ours2) continue;
1742
+ installCopy(dir, who, files, false, opts);
1743
+ }
1744
+ for (const a of AGENTS) {
1745
+ if (!a.instructions) continue;
1746
+ if (refreshReminder(join12(home, a.instructions)) === "updated") opts.stdout(`reminder updated: ${join12(home, a.instructions)}
1747
+ `);
1748
+ }
1749
+ const plugin = pluginFile(home, opts.env ?? process.env);
1750
+ if (pluginState(plugin) !== "outdated") return;
1751
+ const blocker = pluginBlocker(opts, home);
1752
+ if (blocker) opts.stdout(`OpenCode plugin skipped: ${blocker}
1753
+ `);
1754
+ else installPlugin(plugin, false, opts);
1755
+ }
1756
+ async function update(o, opts, runner) {
1757
+ const home = opts.home ?? homedir3();
1758
+ const current = currentVersion();
1759
+ const latest = await fetchLatest(opts.fetch ?? fetch, 1e4);
1760
+ if (!latest) throw new Error("couldn't reach the npm registry to look up the newest version");
1761
+ const cacheDir = cacheDirOf(opts);
1762
+ writeState(cacheDir, { ...readState(cacheDir), checkedAt: opts.now?.().getTime() ?? Date.now(), latest });
1763
+ if (!isNewer(latest, current)) {
1764
+ opts.stdout(`codechart ${current} is the newest version.
1765
+ `);
1766
+ if (!o.check) refreshInstalls(home, opts);
1767
+ return;
1768
+ }
1769
+ if (o.check) {
1770
+ opts.stdout(`codechart ${latest} is available (you have ${current}): run codechart update
1771
+ `);
1772
+ return;
1773
+ }
1774
+ let npmRoot;
1775
+ try {
1776
+ npmRoot = runner.capture("npm", ["root", "-g"]).trim();
1777
+ } catch {
1778
+ npmRoot = void 0;
1779
+ }
1780
+ const how = installedBy(packageFile(""), npmRoot);
1781
+ if (!how.npm) {
1782
+ opts.stdout(`codechart ${latest} is available (you have ${current}), but ${how.hint}.
1783
+ `);
1784
+ return;
1785
+ }
1786
+ opts.stdout(`Updating codechart ${current} \u2192 ${latest}: npm install -g codechart@${latest}
1787
+ `);
1788
+ runner.show("npm", ["install", "-g", `codechart@${latest}`]);
1789
+ runner.show("codechart", ["update", "--skills-only"]);
1790
+ opts.stdout(`codechart ${latest} installed. What changed: ${RELEASES}
1791
+ `);
1792
+ }
1793
+ async function runUpdate(o, opts) {
1794
+ const tool = opts.tool;
1795
+ await update(o, opts, tool ? { capture: tool, show: (c, a) => void tool(c, a) } : defaultRunner);
1796
+ }
1797
+ function updateCommand(opts) {
1798
+ return new Command4("update").description("install the newest codechart with npm and refresh the skill copies, reminder lines and OpenCode plugin copy you have").option("--check", "only say whether a newer version exists").option("--skills-only", "refresh installed skill copies, reminder lines and the OpenCode plugin copy to this version (run by update)").action(async (o) => {
1799
+ try {
1800
+ if (o.skillsOnly) return refreshInstalls(opts.home ?? homedir3(), opts);
1801
+ await runUpdate(o, opts);
1802
+ } catch (e) {
1803
+ opts.stderr(`codechart: ${e instanceof Error ? e.message : String(e)}
1804
+ `);
1805
+ process.exitCode = 1;
1806
+ }
1807
+ });
1808
+ }
1809
+
1810
+ // src/commands/doctor-checks.ts
1811
+ var runnable = (win) => (p) => {
1812
+ try {
1813
+ if (!statSync(p).isFile()) return false;
1814
+ if (!win) accessSync(p, constants3.X_OK);
1815
+ return true;
1816
+ } catch {
1817
+ return false;
1818
+ }
1819
+ };
1820
+ function findOnPath(env, platform = process.platform, usable = runnable(platform === "win32")) {
1821
+ const win = platform === "win32";
1822
+ const dirs = (win ? env.PATH ?? env.Path ?? "" : env.PATH ?? "").split(win ? ";" : ":");
1823
+ const names = win ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((e) => `codechart${e.toLowerCase()}`) : ["codechart"];
1824
+ for (const raw of dirs) {
1825
+ const dir = win ? raw.replace(/^"(.*)"$/, "$1") : raw;
1826
+ if (!dir) continue;
1827
+ for (const name of names) {
1828
+ const file = (win ? win322 : posix).join(dir, name);
1829
+ if (usable(file)) return file;
1830
+ }
1831
+ }
1832
+ return void 0;
1833
+ }
1834
+ var present = (p) => {
1835
+ try {
1836
+ return lstatSync7(p, { throwIfNoEntry: false }) !== void 0;
1837
+ } catch {
1838
+ return false;
1839
+ }
1840
+ };
1841
+ var ours = (dir) => {
1842
+ try {
1843
+ return isCodechartSkill(dir);
1844
+ } catch {
1845
+ return false;
1846
+ }
1847
+ };
1848
+ function skillProblem(a, dirs, seen, item) {
1849
+ const fresh = dirs.filter((d) => !seen.has(d));
1850
+ const owner = seen.get(dirs.find((d) => seen.has(d)) ?? "");
1851
+ for (const d of fresh) seen.set(d, a.label);
1852
+ return fresh.length ? item : { level: "bad", text: `skill: same copy as ${owner}`, same: true };
1853
+ }
1854
+ function skillItem(a, target, home, files, opts, seen) {
1855
+ const copies = [.../* @__PURE__ */ new Set([a.skills, ...a.reads])].map((f) => join13(home, f, "codechart")).filter(present);
1856
+ const own = copies.filter(ours);
1857
+ const install = `codechart install-skill --agent ${a.name}`;
1858
+ const stale = own.filter((d) => !skillIsCurrent(d, files));
1859
+ if (own.length && !stale.length) return { level: "ok", text: `skill: ${own.join(", ")} (current)` };
1860
+ if (stale.length) {
1861
+ const fresh = stale.filter((d) => !seen.has(d));
1862
+ return skillProblem(a, stale, seen, {
1863
+ level: "bad",
1864
+ text: `skill: outdated at ${fresh.join(", ")}`,
1865
+ fix: install,
1866
+ run: () => void fresh.forEach((d) => installCopy(d, a.label, files, false, opts))
1867
+ });
1868
+ }
1869
+ if (copies.length) {
1870
+ return skillProblem(a, copies, seen, { level: "bad", text: `skill: ${copies[0]} is not the codechart skill (left alone: move it aside first)`, fix: install });
1871
+ }
1872
+ const dir = join13(home, target, "codechart");
1873
+ return skillProblem(a, [dir], seen, { level: "bad", text: `skill: missing (${dir})`, fix: install, run: () => void installCopy(dir, a.label, files, false, opts) });
1874
+ }
1875
+ function reminderItem(a, home, opts) {
1876
+ const file = join13(home, a.instructions);
1877
+ const state = reminderState(file);
1878
+ if (state === "present") return { level: "ok", text: `reminder: ${file}` };
1879
+ const fix2 = `codechart install-skill --agent ${a.name} --reminder`;
1880
+ if (state === "missing") return { level: "warn", text: `reminder: missing in ${file}`, fix: fix2 };
1881
+ return { level: "bad", text: `reminder: outdated in ${file}`, fix: fix2, run: () => opts.stdout(`reminder ${addReminder(file)}: ${file}
1882
+ `) };
1883
+ }
1884
+ function hookItem(home, opts) {
1885
+ const file = join13(home, ".claude", "settings.json");
1886
+ let state;
1887
+ try {
1888
+ state = claudeHookEvents(file);
1889
+ } catch (e) {
1890
+ return { level: "bad", text: `hook: ${e.message}` };
1891
+ }
1892
+ if (state.ok.length === 2) return { level: "ok", text: `hook: Stop and prompt hooks in ${file}` };
1893
+ const fix2 = "codechart install-skill --agent claude --hook";
1894
+ if (!state.ok.length && !state.wrong.length) return { level: "warn", text: `hook: missing in ${file}`, fix: fix2 };
1895
+ const problems = ["Stop", "UserPromptSubmit"].filter((e) => !state.ok.includes(e)).map((e) => `${e} ${state.wrong.includes(e) ? "runs the wrong command" : "missing"}`);
1896
+ return {
1897
+ level: "bad",
1898
+ text: `hook: ${problems.join(", ")} in ${file}`,
1899
+ fix: fix2,
1900
+ run: () => opts.stdout(installClaudeHooks(file) === "added" ? `hook added: ${file}
1901
+ ` : `hook already in ${file}
1902
+ `)
1903
+ };
1904
+ }
1905
+ function pluginItem(home, opts) {
1906
+ const file = pluginFile(home, opts.env ?? process.env);
1907
+ const state = pluginState(file);
1908
+ if (state === "current") return { level: "ok", text: `plugin: ${file} (current)` };
1909
+ if (state === "foreign") return { level: "bad", text: `plugin: ${file} is not the codechart plugin (left alone: move it aside first)` };
1910
+ const blocker = pluginBlocker(opts, home);
1911
+ if (blocker) return { level: "warn", text: `plugin: skipped, ${blocker}` };
1912
+ if (state === "missing") return { level: "warn", text: `plugin: not added (${file})`, fix: "codechart install-skill --agent opencode --plugin" };
1913
+ return { level: "bad", text: `plugin: outdated at ${file}`, fix: "codechart install-skill --agent opencode", run: () => void installPlugin(file, false, opts) };
1914
+ }
1915
+ function agentSection(a, target, home, files, opts, seen) {
1916
+ const items2 = [skillItem(a, target, home, files, opts, seen)];
1917
+ if (a.instructions) items2.push(reminderItem({ ...a, instructions: a.instructions }, home, opts));
1918
+ if (a.name === "claude") items2.push(hookItem(home, opts));
1919
+ else if (a.name === "opencode") items2.push(pluginItem(home, opts));
1920
+ else items2.push({ level: "warn", text: `hook: no codechart hook for ${a.label} yet` });
1921
+ return { title: a.label, items: items2 };
1922
+ }
1923
+ function cliSection(opts) {
1924
+ const items2 = [];
1925
+ const found = findOnPath(opts.env ?? process.env);
1926
+ items2.push(
1927
+ found ? { level: "ok", text: `on PATH: ${found}` } : { level: "bad", text: "not on PATH, so agents can't run it", fix: "npm i -g codechart" }
1928
+ );
1929
+ const current = currentVersion();
1930
+ const latest = readState(cacheDirOf(opts)).latest;
1931
+ if (latest && isNewer(latest, current)) {
1932
+ items2.push({ level: "bad", text: `version ${current}, npm has ${latest}`, fix: "codechart update", run: () => runUpdate({}, opts) });
1933
+ } else {
1934
+ items2.push({ level: "ok", text: `version ${current}${latest ? " (newest known)" : " (npm not checked yet)"}` });
1935
+ }
1936
+ return { title: "codechart CLI", items: items2, first: true };
1937
+ }
1938
+ function runChecks(home, opts) {
1939
+ const agents = AGENTS.filter((a) => existsSync8(join13(home, a.home)));
1940
+ const files = skillFiles();
1941
+ const folders = skillFolders(agents);
1942
+ const seen = /* @__PURE__ */ new Map();
1943
+ const sections = agents.map((a) => agentSection(a, folders.find((g) => g.agents.includes(a)).folder, home, files, opts, seen));
1944
+ if (!agents.length) sections.push({ title: "Agents", items: [{ level: "bad", text: `no agent found in ${home}`, fix: "codechart install-skill --agent <name>" }] });
1945
+ return [...sections, cliSection(opts)];
1946
+ }
1947
+
1948
+ // src/commands/doctor-last.ts
1949
+ import { join as join16 } from "path";
1950
+
1951
+ // src/commands/hook-core.ts
1952
+ import { lstatSync as lstatSync8, mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as readFileSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync4 } from "fs";
1953
+ import { join as join14 } from "path";
1954
+
1955
+ // src/commands/transcript.ts
1956
+ var DIAGRAM = /\*\*(Map|Flow)\*\*/;
1957
+ var blocks = (e) => Array.isArray(e.message?.content) ? e.message.content : [];
1958
+ var isPrompt = (e) => e.type === "user" && !e.isMeta && (typeof e.message?.content === "string" || blocks(e).length > 0 && !blocks(e).some((b) => b.type === "tool_result"));
1959
+ var CODECHART_RUN = /\bcodechart\s+(check|render)\b/;
1960
+ var SKILL_FILE = /[\\/]skills[\\/]codechart[\\/]/;
1961
+ var showsDiagram = (b) => b.type === "text" && DIAGRAM.test(b.text ?? "");
1962
+ var runsCli = (b) => b.type === "tool_use" && typeof b.input?.command === "string" && CODECHART_RUN.test(b.input.command);
1963
+ var loadsSkill = (b) => b.type === "tool_use" && (b.name === "Skill" && typeof b.input?.skill === "string" && b.input.skill.split(":").pop() === "codechart" || typeof b.input?.file_path === "string" && SKILL_FILE.test(b.input.file_path));
1964
+ function scanTurn(jsonl) {
1965
+ let scan = { diagram: false, cli: false, skill: false };
1966
+ for (const line of jsonl.split("\n")) {
1967
+ let e;
1968
+ try {
1969
+ e = JSON.parse(line);
1970
+ } catch {
1971
+ continue;
1972
+ }
1973
+ if (isPrompt(e)) scan = { diagram: false, cli: false, skill: false };
1974
+ else if (e.type === "assistant") {
1975
+ const bs = blocks(e);
1976
+ scan = { diagram: scan.diagram || bs.some(showsDiagram), cli: scan.cli || bs.some(runsCli), skill: scan.skill || bs.some(loadsSkill) };
1977
+ }
1978
+ }
1979
+ return scan;
1980
+ }
1981
+
1982
+ // src/commands/hook-core.ts
1983
+ var MIN_FILES = 3;
1984
+ var MAX_DIRTY = 5e3;
1985
+ var KEEP_DAYS = 7;
1986
+ var SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
1987
+ function changedFiles(before, now, diff) {
1988
+ const changed = /* @__PURE__ */ new Set();
1989
+ for (const f of /* @__PURE__ */ new Set([...Object.keys(before.files), ...Object.keys(now.files)])) {
1990
+ if (before.files[f] !== now.files[f]) changed.add(f);
1991
+ }
1992
+ if (now.head && before.head !== now.head) for (const f of diff(before.head, now.head)) changed.add(f);
1993
+ return [...changed].sort();
1994
+ }
1995
+ function snapshot(root) {
1996
+ const files = gitDirtyHashes(root, MAX_DIRTY);
1997
+ return files && { head: gitHead(root), files };
1998
+ }
1999
+ function prune(dir, now) {
2000
+ for (const f of readdirSync3(dir)) {
2001
+ const p = join14(dir, f);
2002
+ const st = lstatSync8(p);
2003
+ if (st.isFile() && now - st.mtimeMs > KEEP_DAYS * 864e5) unlinkSync3(p);
2004
+ }
2005
+ }
2006
+ var nudge = (count) => `This turn changed ${count} files and your reply has no codechart diagram. Unless the user said no diagram, follow the codechart skill now (check, then render) and reply with what it prints; if it says no diagram applies, stop without mentioning it.`;
2007
+ function saveSnapshot(dir, file, root, now) {
2008
+ const snap = snapshot(root);
2009
+ mkdirSync4(dir, { recursive: true, mode: 448 });
2010
+ prune(dir, now.getTime());
2011
+ if (snap) writeFileSync4(file, JSON.stringify({ root, ...snap }), { mode: 384 });
2012
+ else unlinkSync3(file);
2013
+ }
2014
+ function readSnapshot(file) {
2015
+ try {
2016
+ return JSON.parse(readFileSync3(file, "utf8"));
2017
+ } catch {
2018
+ return void 0;
2019
+ }
2020
+ }
2021
+ function judgeTurn(root, file, reply, used) {
2022
+ const before = readSnapshot(file);
2023
+ if (!before) return { decision: "no-snapshot" };
2024
+ if (before.root !== root) return { decision: "other-root" };
2025
+ const now = snapshot(root);
2026
+ if (!now) return { decision: "no-snapshot" };
2027
+ const files = changedFiles(before, now, (a, b) => a ? gitDiffFiles(root, a, b) : gitListFiles(root, b));
2028
+ if (files.length < MIN_FILES) return { decision: "few-files", files };
2029
+ if (reply !== void 0 && DIAGRAM.test(reply)) return { decision: "diagram-in-reply", files };
2030
+ const seen = used();
2031
+ if (seen && (seen.diagram || seen.cli)) return { decision: "codechart-used", files };
2032
+ return { decision: "nudged", files };
2033
+ }
2034
+
2035
+ // src/commands/hook-record.ts
2036
+ import { mkdirSync as mkdirSync5, readdirSync as readdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5 } from "fs";
2037
+ import { join as join15 } from "path";
2038
+ var MAX_FILES = 500;
2039
+ var SUFFIX = ".turn.json";
2040
+ var turnsDir = (home) => join15(home, ".cache", "codechart", "turns");
2041
+ function writeRecord(dir, record2) {
2042
+ mkdirSync5(dir, { recursive: true, mode: 448 });
2043
+ const files = record2.files && record2.files.slice(0, MAX_FILES);
2044
+ writeFileSync5(join15(dir, `${record2.session}${SUFFIX}`), JSON.stringify({ ...record2, files }), { mode: 384 });
2045
+ }
2046
+ var activity = (r) => [r.at, r.pendingAt, r.quietAt].reduce((m, t) => t && t > m ? t : m, "");
2047
+ function readRecord(dir, session) {
2048
+ try {
2049
+ return JSON.parse(readFileSync4(join15(dir, `${session}${SUFFIX}`), "utf8"));
2050
+ } catch {
2051
+ return void 0;
2052
+ }
2053
+ }
2054
+ function recordPrompt(dir, root, session, at, agent) {
2055
+ const prev = readRecord(dir, session);
2056
+ writeRecord(dir, prev ? { ...prev, pendingAt: at } : { at, root, session, pendingAt: at, agent });
2057
+ }
2058
+ function recordStop(dir, rec) {
2059
+ const prev = readRecord(dir, rec.session);
2060
+ if (rec.decision === "stop_hook_active" && prev?.decision && !prev.pendingAt) return;
2061
+ if (rec.decision === "few-files" && !rec.files?.length && prev?.files?.length) {
2062
+ writeRecord(dir, { ...prev, pendingAt: void 0, quietAt: rec.at });
2063
+ return;
2064
+ }
2065
+ writeRecord(dir, rec);
2066
+ }
2067
+ function latestRecord(dir, root) {
2068
+ let names;
2069
+ try {
2070
+ names = readdirSync4(dir).filter((n) => n.endsWith(SUFFIX));
2071
+ } catch {
2072
+ return void 0;
2073
+ }
2074
+ let best;
2075
+ for (const name of names) {
2076
+ try {
2077
+ const r = JSON.parse(readFileSync4(join15(dir, name), "utf8"));
2078
+ if (r.root === root && typeof r.at === "string" && (!best || activity(r) > activity(best))) best = r;
2079
+ } catch {
2080
+ continue;
2081
+ }
2082
+ }
2083
+ return best;
2084
+ }
2085
+
2086
+ // src/commands/doctor-last.ts
2087
+ var WHY = {
2088
+ stop_hook_active: "the Stop hook had already asked once this turn, so it stayed quiet",
2089
+ "no-snapshot": "no snapshot of the files before the turn (too many changed files, or the prompt hook did not run first), so it could not tell what changed",
2090
+ "other-root": "the turn's snapshot was taken in a different repo",
2091
+ "few-files": `the turn changed fewer than ${MIN_FILES} files, so the hook did not ask for a diagram`,
2092
+ "diagram-in-reply": "the reply already had a codechart diagram",
2093
+ "codechart-used": "the agent already ran codechart this turn",
2094
+ nudged: "the hook sent the agent back to draw a diagram"
2095
+ };
2096
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2097
+ function rulesLines(rec, root, opts, home) {
2098
+ const files = rec.files ?? [];
2099
+ if (!files.length) return [];
2100
+ const config = loadConfig({ cwd: root, home, env: opts.env, warn: () => {
2101
+ } });
2102
+ const fired = resolveRules(config, files, void 0, root).pathMatches.filter((m) => m.output !== "none");
2103
+ const lines = fired.map((m) => `rule ${m.rule} fires (${m.diagram}) on ${m.files.slice(0, 3).join(", ")}${m.files.length > 3 ? ", \u2026" : ""}`);
2104
+ if (!fired.length) lines.push("no rule fires (e.g. only tests or generated files changed); the built-in rules are judged by the agent");
2105
+ if (fired.length && files.length < MIN_FILES) lines.push(`the hook and the rules disagree: a rule fires on ${plural(files.length, "file")}, but the hook only asks from ${MIN_FILES}`);
2106
+ if (!fired.length && rec.decision === "nudged") lines.push("a nudge here is expected: with no path rule matching, the agent judges related-files and behaviour-flow itself, and may answer that no diagram applies");
2107
+ return lines;
2108
+ }
2109
+ var attempt = (check) => {
2110
+ try {
2111
+ return check();
2112
+ } catch {
2113
+ return false;
2114
+ }
2115
+ };
2116
+ var hasClaudeHooks = (home) => attempt(() => claudeHookEvents(join16(home, ".claude", "settings.json")).ok.length === 2);
2117
+ var hasOpencodePlugin = (home, opts) => attempt(() => ["current", "outdated"].includes(pluginState(pluginFile(home, opts.env ?? process.env))));
2118
+ function explainLast(cwd, home, opts) {
2119
+ const say = (line) => opts.stdout(`${line}
2120
+ `);
2121
+ const root = findRepoRoot(cwd);
2122
+ if (!root) {
2123
+ opts.stderr("codechart: not in a git repo; run it from the repo where the diagram was missing\n");
2124
+ return false;
2125
+ }
2126
+ const claude = hasClaudeHooks(home);
2127
+ if (!claude && !hasOpencodePlugin(home, opts)) {
2128
+ say("The Claude Code hooks and the OpenCode plugin are not installed, so no turn was logged. `doctor --last` supports Claude Code and OpenCode.");
2129
+ say("Fix: codechart install-skill --agent claude --hook, or codechart install-skill --agent opencode --plugin");
2130
+ return true;
2131
+ }
2132
+ const rec = latestRecord(turnsDir(home), root);
2133
+ if (!rec) {
2134
+ say(`No turn logged for ${root}: the hooks never ran here.`);
2135
+ if (claude) say("Sessions hosted by the Claude Agent SDK sometimes load 0 hooks (anthropics/claude-code#87657). Run `codechart doctor` to check the hooks are installed, then start a new session.");
2136
+ else say("OpenCode loads plugins at startup: restart it after install, and make sure the repo is one the session runs in. Run `codechart doctor` to check the plugin.");
2137
+ return true;
2138
+ }
2139
+ const opencode = rec.agent === "opencode";
2140
+ const stop = opencode ? "plugin" : "Stop hook";
2141
+ say(`Last turn: ${rec.at}, session ${rec.session}${opencode ? " (OpenCode)" : ""}`);
2142
+ if (!rec.decision) {
2143
+ say(`The prompt hook ran, but the ${stop} left no decision: it did not run (or the turn is still going).`);
2144
+ return true;
2145
+ }
2146
+ if (rec.pendingAt) say(`A newer prompt (${rec.pendingAt}) has no ${opencode ? "idle" : "Stop"} decision yet: it is the current turn, or the ${stop} did not run for it. Showing the turn before it.`);
2147
+ if (rec.quietAt) say(`A later turn (${rec.quietAt}) changed no files, so there was nothing to map. Showing the last turn that did.`);
2148
+ say(`Decision: ${rec.decision}: ${WHY[rec.decision]}.`);
2149
+ say(`Changed files: ${rec.files?.length ?? 0}${rec.files?.length ? ` (${rec.files.slice(0, 5).join(", ")}${rec.files.length > 5 ? ", \u2026" : ""})` : ""}`);
2150
+ for (const line of rulesLines(rec, root, opts, home)) say(line);
2151
+ if (rec.skill !== void 0) say(rec.skill ? "The agent loaded the codechart skill." : "The agent did not load the codechart skill this turn.");
2152
+ return true;
2153
+ }
2154
+
2155
+ // src/commands/doctor.ts
2156
+ var MARK2 = { ok: "\u2713", warn: "\u26A0", bad: "\u2717" };
2157
+ var TEST_PROMPT = "Add a constant to one file, use it in two other files, then summarize what changed.";
2158
+ function show(sections, opts) {
2159
+ for (const { title, items: items2 } of sections) {
2160
+ opts.stdout(`${title}
2161
+ `);
2162
+ for (const i of items2) opts.stdout(` ${MARK2[i.level]} ${i.text}${i.fix ? `: run ${i.fix}` : ""}
2163
+ `);
2164
+ }
2165
+ opts.stdout(`
2166
+ To test, paste into your agent:
2167
+ ${TEST_PROMPT}
2168
+ A codechart map should follow the reply.
2169
+ `);
2170
+ }
2171
+ var items = (sections) => sections.flatMap((s) => s.items);
2172
+ var bad = (sections) => items(sections).filter((i) => i.level === "bad" && !i.same);
2173
+ async function fix(sections, opts) {
2174
+ const ordered = [...sections.filter((s) => s.first), ...sections.filter((s) => !s.first)];
2175
+ for (const item of bad(ordered)) {
2176
+ if (!item.run) continue;
2177
+ try {
2178
+ await item.run();
2179
+ } catch (e) {
2180
+ opts.stderr(`codechart: ${item.text}: ${e instanceof Error ? e.message : String(e)}
2181
+ `);
2182
+ }
2183
+ }
2184
+ for (const item of items(sections)) if (item.level === "warn" && item.fix) opts.stdout(`not added (opt-in): ${item.fix}
2185
+ `);
2186
+ }
2187
+ function doctorCommand(opts) {
2188
+ return new Command5("doctor").description("check that agents can find codechart (skill, reminder, hook or plugin, CLI); --fix repairs, --last explains the last turn").option("--fix", "repair what is missing or outdated (never overwrites a skill folder that is not codechart)").option("--last", "explain why the last turn in this repo did or didn't get a diagram (Claude Code, OpenCode)").action(async (o) => {
2189
+ const home = opts.home ?? homedir4();
2190
+ if (o.last) {
2191
+ if (!explainLast(opts.cwd ?? process.cwd(), home, opts)) process.exitCode = 1;
2192
+ return;
2193
+ }
2194
+ if (o.fix) await fix(runChecks(home, opts), opts);
2195
+ const sections = runChecks(home, opts);
2196
+ show(sections, opts);
2197
+ if (bad(sections).length) process.exitCode = 1;
2198
+ });
2199
+ }
2200
+
2201
+ // src/commands/hook.ts
2202
+ import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readSync as readSync2 } from "fs";
2203
+ import { homedir as homedir5 } from "os";
2204
+ import { join as join17 } from "path";
2205
+ import { Argument, Command as Command6 } from "commander";
2206
+
2207
+ // src/commands/stdin.ts
2208
+ async function readStdin(max, overCap) {
2209
+ const chunks2 = [];
2210
+ let size = 0;
2211
+ for await (const chunk of process.stdin) {
2212
+ size += chunk.length;
2213
+ if (size > max && overCap !== "stop") throw overCap;
2214
+ chunks2.push(chunk);
2215
+ if (size > max) break;
2216
+ }
2217
+ return Buffer.concat(chunks2).toString("utf8");
2218
+ }
2219
+
2220
+ // src/commands/hook.ts
2221
+ var MAX_INPUT = 1024 * 1024;
2222
+ var MAX_TRANSCRIPT_TAIL = 8 * 1024 * 1024;
2223
+ function readTail(file, max) {
2224
+ const fd = openSync2(file, "r");
2225
+ try {
2226
+ const st = fstatSync2(fd);
2227
+ if (!st.isFile()) return "";
2228
+ const size = Math.min(st.size, max);
2229
+ const buf = Buffer.alloc(size);
2230
+ readSync2(fd, buf, 0, size, st.size - size);
2231
+ return buf.toString("utf8");
2232
+ } finally {
2233
+ closeSync2(fd);
2234
+ }
2235
+ }
2236
+ async function readInput(stdin) {
2237
+ const text = await stdin();
2238
+ if (Buffer.byteLength(text) > MAX_INPUT) return {};
2239
+ const v = JSON.parse(text);
2240
+ return typeof v === "object" && v !== null ? v : {};
2241
+ }
2242
+ function onStop({ root, file, input, scan }) {
2243
+ if (input.stop_hook_active === true) return { decision: "stop_hook_active" };
2244
+ const last = input.last_assistant_message;
2245
+ const outcome = judgeTurn(root, file, typeof last === "string" ? last : void 0, scan);
2246
+ if (outcome.decision !== "nudged") return outcome;
2247
+ const reminder = `${JSON.stringify({ hookSpecificOutput: { hookEventName: "Stop", additionalContext: nudge(outcome.files?.length ?? 0) } })}
2248
+ `;
2249
+ return { ...outcome, reminder };
2250
+ }
2251
+ function record(turn, now, outcome) {
2252
+ const at = now.toISOString();
2253
+ const session = String(turn.input.session_id);
2254
+ try {
2255
+ if (!outcome) return recordPrompt(turn.dir, turn.root, session, at);
2256
+ let seen;
2257
+ if (outcome.files?.length) {
2258
+ try {
2259
+ seen = turn.scan();
2260
+ } catch {
2261
+ seen = void 0;
2262
+ }
2263
+ }
2264
+ recordStop(turn.dir, { at, root: turn.root, session, decision: outcome.decision, files: outcome.files, skill: seen?.skill, cli: seen?.cli });
2265
+ } catch {
2266
+ }
2267
+ }
2268
+ async function runHook(event, opts) {
2269
+ const input = await readInput(opts.stdin ?? (() => readStdin(MAX_INPUT, "stop")));
2270
+ const id = input.session_id;
2271
+ const cwd = input.cwd;
2272
+ if (typeof id !== "string" || !SESSION_ID.test(id) || typeof cwd !== "string") return;
2273
+ const root = findRepoRoot(cwd);
2274
+ if (!root) return;
2275
+ const dir = turnsDir(opts.home ?? homedir5());
2276
+ const path3 = input.transcript_path;
2277
+ let scanned;
2278
+ const scan = () => scanned ??= typeof path3 === "string" ? scanTurn(readTail(path3, MAX_TRANSCRIPT_TAIL)) : void 0;
2279
+ const turn = { root, dir, file: join17(dir, `${id}.json`), input, scan };
2280
+ const now = opts.now?.() ?? /* @__PURE__ */ new Date();
2281
+ if (event === "prompt") {
2282
+ try {
2283
+ saveSnapshot(dir, turn.file, root, now);
2284
+ } finally {
2285
+ record(turn, now);
2286
+ }
2287
+ return;
2288
+ }
2289
+ const outcome = onStop(turn);
2290
+ record(turn, now, outcome);
2291
+ if (outcome.reminder) opts.stdout(outcome.reminder);
2292
+ }
2293
+ function hookCommand(opts) {
2294
+ return new Command6("hook").description("Claude Code hook (install with install-skill --hook): asks for a diagram after a turn that changed 3+ files without one").addArgument(new Argument("<event>").choices(["prompt", "stop"])).action(async (event) => {
2295
+ try {
2296
+ await runHook(event, opts);
2297
+ } catch (e) {
2298
+ if ((opts.env ?? process.env).CODECHART_DEBUG) opts.stderr(`codechart: hook ${event}: ${e instanceof Error ? e.message : String(e)}
2299
+ `);
2300
+ }
2301
+ });
2302
+ }
2303
+
2304
+ // src/commands/init.ts
2305
+ import { join as join18 } from "path";
2306
+ import { Command as Command7 } from "commander";
2307
+ function initCommand(opts) {
2308
+ return new Command7("init").description("write a commented starter .codechart.yaml at the git root").option("--force", "overwrite an existing .codechart.yaml").action((o) => {
2309
+ const root = findRepoRoot(opts.cwd ?? process.cwd());
2310
+ if (!root) {
2311
+ opts.stderr("codechart: not a git repository\n");
2312
+ process.exitCode = 1;
2313
+ return;
2314
+ }
2315
+ copyFiles([{ source: packageFile("templates/codechart.yaml"), target: join18(root, ".codechart.yaml") }], o.force === true, opts);
2316
+ });
2317
+ }
2318
+
2319
+ // src/commands/pr-sync.ts
2320
+ import { randomUUID } from "crypto";
2321
+ import { mkdtempSync, readFileSync as readFileSync6, rmSync as rmSync2 } from "fs";
2322
+ import { tmpdir } from "os";
2323
+ import { join as join21 } from "path";
2324
+ import { Command as Command9 } from "commander";
2325
+
2326
+ // src/render/terminal/check-lines.ts
2327
+ var MAX_SHOWN = 5;
2328
+ var UNCHECKED = "diff not checked";
2329
+ var units = (n, unit) => `${n} ${unit}${n === 1 ? "" : "s"}`;
2330
+ var uncoveredHead = (n) => `\u2717 ${n} changed ${n === 1 ? "file" : "files"} not on map`;
2331
+ var flagged = (c) => Boolean(c?.mismatches.length || c?.uncovered?.length);
2332
+ function checkTag(c) {
2333
+ const unchecked = c?.diffUnchecked ? ` \xB7 ${UNCHECKED}` : "";
2334
+ if (!c || c.checked === 0) return unchecked;
2335
+ const total = c.unit === "node" ? String(c.checked) : units(c.checked, c.unit);
2336
+ return ` \xB7 \u2713 ${c.mismatches.length ? `${c.checked - c.mismatches.length} of ` : ""}${total} checked${unchecked}`;
2337
+ }
2338
+ function itemsLine(head, all, width) {
2339
+ const items2 = all.slice(0, MAX_SHOWN);
2340
+ if (all.length > MAX_SHOWN) items2.push(`+${all.length - MAX_SHOWN} more`);
2341
+ if (columns(head) <= width / 2) return wrapItems(head, items2, width);
2342
+ return `${truncate(head.trimEnd(), width)}
2343
+ ${wrapItems(" ", items2, width)}`;
2344
+ }
2345
+ function alertLine(c, width) {
2346
+ if (!c) return "";
2347
+ const lines = [];
2348
+ const n = c.mismatches.length;
1233
2349
  if (n) lines.push(itemsLine(`\u2717 ${n} ${n === 1 ? "claim doesn't" : "claims don't"} match the code: `, c.mismatches.map((m) => `${flat(m.label)} ${m.short}`), width));
1234
2350
  if (c.uncovered?.length) lines.push(itemsLine(`${uncoveredHead(c.uncovered.length)}: `, c.uncovered.map(flat), width));
1235
2351
  return lines.join("\n");
@@ -1268,7 +2384,7 @@ var kindLabel = (node) => KINDLESS.has(node.kind) ? flat(node.label) : `${node.k
1268
2384
  var gutter = (status) => `${marker(status) || " "} `;
1269
2385
 
1270
2386
  // src/render/web/page.ts
1271
- import { createHash } from "crypto";
2387
+ import { createHash as createHash2 } from "crypto";
1272
2388
 
1273
2389
  // src/render/web/styles.ts
1274
2390
  var DARK_VARS = "--bg:#0f1115;--panel:#161b22;--card:#161b22;--line:#30363d;--text:#c9d1d9;--muted:#8b949e;--edge:#79c0ff;--new:#3fb950;--new-t:#7ee787;--chg:#d29922;--chg-t:#f2cc60;--cfg:#a371f7;--cfg-t:#d2a8ff;--add:#7ee787;--rem:#ff7b72";
@@ -1306,6 +2422,9 @@ aside{width:clamp(300px,35vw,600px);min-width:300px;max-width:80vw;border-left:1
1306
2422
  aside h2{margin:0 0 6px;font-size:13px;overflow-wrap:anywhere}
1307
2423
  aside h3{margin:12px 0 4px;font-size:11px;text-transform:uppercase;color:var(--muted)}
1308
2424
  aside ul{margin:0;padding-left:18px}
2425
+ aside .tick-row{display:block;margin:0 0 6px;color:var(--muted)}
2426
+ aside .relations{list-style:none;padding:0}
2427
+ aside .rel{padding:1px 0;font:inherit;color:var(--edge);background:none;border:0;cursor:pointer;text-align:left;overflow-wrap:anywhere}aside .rel:hover{text-decoration:underline}
1309
2428
  aside .fields-note{color:var(--muted);font-size:11.5px;font-style:italic;margin:6px 0 0}
1310
2429
  aside code{font-family:ui-monospace,monospace;font-size:11px;font-style:normal}
1311
2430
  aside .path{font-family:ui-monospace,monospace;font-size:11px;overflow-wrap:anywhere;color:var(--muted)}
@@ -1326,6 +2445,19 @@ header .check{font-size:11px;color:var(--new-t)}header .check.bad{color:var(--re
1326
2445
  .edge-added path{stroke:var(--new)}.edge-added text{fill:var(--new-t)}#arrow-added path{fill:var(--new)}
1327
2446
  .edge-removed path{stroke:var(--rem);stroke-dasharray:5 3}.edge-removed text{fill:var(--rem)}#arrow-removed path{fill:var(--rem);stroke:none}
1328
2447
  .node{cursor:pointer}
2448
+ .node,.edge{opacity:calc(var(--base,1)*var(--fade,1)*var(--dim,1))}
2449
+ #toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;padding:4px 14px;min-height:24px;background:var(--bg);border-bottom:1px solid var(--line);font-size:11px}
2450
+ #chips{display:flex;flex-wrap:wrap;gap:4px;margin-right:auto}
2451
+ #review{display:flex;align-items:center;gap:8px;color:var(--muted)}
2452
+ #review-bar{width:60px;height:3px;border-radius:2px;background:var(--line);overflow:hidden}
2453
+ #review-bar i{display:block;height:100%;width:0;background:var(--new)}
2454
+ .chip{padding:0 7px;font:10.5px/16px system-ui,sans-serif;color:var(--muted);background:var(--panel);border:1px solid currentColor;border-radius:10px;cursor:pointer}
2455
+ .chip-new{color:var(--new-t)}.chip-changed{color:var(--chg-t)}.chip-removed{color:var(--rem)}.chip-planned,.chip-config{color:var(--cfg-t)}
2456
+ .chip-planned{border-style:dashed}.chip-delta{color:var(--text);border-color:var(--line)}
2457
+ .chip[aria-pressed="true"]{opacity:.5;text-decoration:line-through}
2458
+ .chip-delta[aria-pressed="true"]{opacity:1;text-decoration:none;border-color:var(--edge)}
2459
+ .node.faded,.edge.faded{--fade:.15}
2460
+ body.focus .node:not(.lit),body.focus .edge:not(.lit){--dim:.25}
1329
2461
  .node .card{fill:var(--card);stroke:var(--line);stroke-width:1}
1330
2462
  .node .fold{fill:none;stroke:var(--line);stroke-width:1}
1331
2463
  .node .head{stroke:var(--line);stroke-width:1}
@@ -1337,6 +2469,11 @@ header .check{font-size:11px;color:var(--new-t)}header .check.bad{color:var(--re
1337
2469
  .node .field-added{fill:var(--add)}
1338
2470
  .node .field-removed{fill:var(--rem);text-decoration:line-through}
1339
2471
  .node .field-modified{fill:var(--chg-t)}
2472
+ .tick{cursor:pointer}.tick-hit{fill:transparent}
2473
+ .tick-box{fill:var(--card);stroke:var(--muted);stroke-width:1}
2474
+ .tick-mark{display:none;fill:none;stroke:var(--card);stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
2475
+ .node.reviewed :is(.card,.fold,.shape){stroke:var(--muted)}
2476
+ .node.reviewed .tick-box{fill:var(--muted)}.node.reviewed .tick-mark{display:inline}
1340
2477
  .node.selected .card{stroke-width:2.5}
1341
2478
  .node:focus{outline:none}
1342
2479
  .node:focus-visible .card{stroke:var(--edge);stroke-width:3.5}
@@ -1344,18 +2481,36 @@ header .check{font-size:11px;color:var(--new-t)}header .check.bad{color:var(--re
1344
2481
  .status-changed :is(.card,.fold){stroke:var(--chg)}.status-changed .badge{fill:var(--chg-t)}
1345
2482
  .status-removed :is(.card,.fold){stroke:var(--rem)}.status-removed .badge{fill:var(--rem)}.status-removed .label{text-decoration:line-through}
1346
2483
  .status-config :is(.card,.fold){stroke:var(--cfg)}.status-config .badge{fill:var(--cfg-t)}
1347
- .status-context .card{stroke-dasharray:4 3}.status-context{opacity:.75}.status-context .badge{fill:var(--muted)}
2484
+ .status-context .card{stroke-dasharray:4 3}.status-context{--base:.75}.status-context .badge{fill:var(--muted)}
1348
2485
  .field-added-t{color:var(--add)}.field-removed-t{color:var(--muted);text-decoration:line-through}.field-modified-t{color:var(--chg-t)}
1349
2486
 
1350
2487
  #info-toggle[aria-expanded="true"]{border-color:var(--edge)}
1351
2488
  #info-toggle,#link-toggle,#theme-toggle{align-self:center;padding:4px 10px;font:11px system-ui,sans-serif;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:12px;cursor:pointer}
1352
- #info-toggle:hover,#link-toggle:hover,#theme-toggle:hover{border-color:var(--edge)}
2489
+ #info-toggle:hover,#link-toggle:hover,#theme-toggle:hover,#next-unreviewed:hover:not(:disabled){border-color:var(--edge)}
2490
+ #next-unreviewed{padding:0 8px;font:10.5px/16px system-ui,sans-serif;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:10px;cursor:pointer}
2491
+ #next-unreviewed:disabled{opacity:.4;cursor:default}
1353
2492
  `;
1354
2493
 
1355
2494
  // src/render/web/client.ts
1356
2495
  var CLIENT_JS = [
1357
2496
  "",
1358
2497
  "(function () {",
2498
+ "function load(key) {",
2499
+ " try {",
2500
+ " return localStorage.getItem(key);",
2501
+ " }",
2502
+ " catch (_a) {",
2503
+ " return null;",
2504
+ " }",
2505
+ "}",
2506
+ "function save(key, value) {",
2507
+ " try {",
2508
+ " localStorage.setItem(key, value);",
2509
+ " }",
2510
+ " catch (_a) {",
2511
+ " }",
2512
+ "}",
2513
+ "",
1359
2514
  "const entryOf = (s) => typeof s === 'object' && s !== null && typeof s.cc === 'number' ? s : null;",
1360
2515
  "const hashOf = (v) => (v === null ? '#info' : `#node=${encodeURIComponent(v)}`);",
1361
2516
  "function visitFromHash(hash) {",
@@ -1474,6 +2629,160 @@ var CLIENT_JS = [
1474
2629
  " };",
1475
2630
  "}",
1476
2631
  "",
2632
+ "function select(id) {",
2633
+ " document.querySelectorAll('.node.selected').forEach((g) => g.classList.remove('selected'));",
2634
+ " if (id === null)",
2635
+ " return;",
2636
+ " document.querySelectorAll(`.node[data-id=\"${CSS.escape(id)}\"]`).forEach((g) => g.classList.add('selected'));",
2637
+ "}",
2638
+ "function focus(id) {",
2639
+ " document.body.classList.toggle('focus', id !== null);",
2640
+ " document.querySelectorAll('.lit').forEach((el) => el.classList.remove('lit'));",
2641
+ " if (id === null)",
2642
+ " return;",
2643
+ " const near = new Set([id]);",
2644
+ " document.querySelectorAll('.edge').forEach((e) => {",
2645
+ " const from = e.getAttribute('data-from');",
2646
+ " const to = e.getAttribute('data-to');",
2647
+ " if (from !== id && to !== id)",
2648
+ " return;",
2649
+ " e.classList.add('lit');",
2650
+ " near.add(from).add(to);",
2651
+ " });",
2652
+ " document.querySelectorAll('.node').forEach((g) => g.classList.toggle('lit', near.has(g.getAttribute('data-id'))));",
2653
+ "}",
2654
+ "function dismissFocus(canvases, panned) {",
2655
+ " canvases.forEach((canvas) => canvas.addEventListener('click', (e) => {",
2656
+ " if (!e.target.closest('.node') && !panned())",
2657
+ " focus(null);",
2658
+ " }));",
2659
+ " window.addEventListener('keydown', (e) => {",
2660
+ " if (e.key === 'Escape')",
2661
+ " focus(null);",
2662
+ " });",
2663
+ "}",
2664
+ "",
2665
+ "const KEY = 'codechart.faded';",
2666
+ "function savedStatuses() {",
2667
+ " var _a;",
2668
+ " try {",
2669
+ " const v = JSON.parse((_a = load(KEY)) !== null && _a !== void 0 ? _a : '[]');",
2670
+ " return Array.isArray(v) ? v.filter((s) => typeof s === 'string') : [];",
2671
+ " }",
2672
+ " catch (_b) {",
2673
+ " return [];",
2674
+ " }",
2675
+ "}",
2676
+ "function initChips() {",
2677
+ " const chips = [...document.querySelectorAll('#chips .chip')];",
2678
+ " if (!chips.length)",
2679
+ " return;",
2680
+ " const present = chips.flatMap((c) => { var _a; return (_a = c.getAttribute('data-status')) !== null && _a !== void 0 ? _a : []; });",
2681
+ " const faded = new Set(savedStatuses().filter((s) => present.includes(s)));",
2682
+ " const statusOf = (c) => { var _a; return (_a = c.getAttribute('data-delta')) !== null && _a !== void 0 ? _a : c.getAttribute('data-status'); };",
2683
+ " const apply = () => {",
2684
+ " const nodeStatus = new Map();",
2685
+ " document.querySelectorAll('.node').forEach((g) => {",
2686
+ " const status = g.getAttribute('data-status');",
2687
+ " nodeStatus.set(g.getAttribute('data-id'), status);",
2688
+ " g.classList.toggle('faded', faded.has(status));",
2689
+ " });",
2690
+ " document.querySelectorAll('.edge').forEach((e) => {",
2691
+ " const ends = [e.getAttribute('data-from'), e.getAttribute('data-to')];",
2692
+ " e.classList.toggle('faded', ends.some((id) => { var _a; return faded.has((_a = nodeStatus.get(id)) !== null && _a !== void 0 ? _a : ''); }));",
2693
+ " });",
2694
+ " chips.forEach((c) => {",
2695
+ " const unchanged = c.getAttribute('data-delta');",
2696
+ " const on = unchanged === null ? faded.has(statusOf(c)) : faded.size === 1 && faded.has(unchanged);",
2697
+ " c.setAttribute('aria-pressed', String(on));",
2698
+ " });",
2699
+ " };",
2700
+ " chips.forEach((c) => c.addEventListener('click', () => {",
2701
+ " const status = statusOf(c);",
2702
+ " if (c.hasAttribute('data-delta')) {",
2703
+ " const was = faded.size === 1 && faded.has(status);",
2704
+ " faded.clear();",
2705
+ " if (!was)",
2706
+ " faded.add(status);",
2707
+ " }",
2708
+ " else if (!faded.delete(status))",
2709
+ " faded.add(status);",
2710
+ " save(KEY, JSON.stringify([...faded]));",
2711
+ " apply();",
2712
+ " }));",
2713
+ " apply();",
2714
+ "}",
2715
+ "",
2716
+ "function savedTicks(key) {",
2717
+ " var _a;",
2718
+ " try {",
2719
+ " const v = JSON.parse((_a = load(key)) !== null && _a !== void 0 ? _a : '[]');",
2720
+ " const pairs = Array.isArray(v) ? v.filter((p) => Array.isArray(p) && typeof p[0] === 'string' && typeof p[1] === 'string') : [];",
2721
+ " return new Map(pairs);",
2722
+ " }",
2723
+ " catch (_b) {",
2724
+ " return new Map();",
2725
+ " }",
2726
+ "}",
2727
+ "function initReview(repo, goTo) {",
2728
+ " const key = `codechart.reviewed:${repo}`;",
2729
+ " const revs = new Map();",
2730
+ " document.querySelectorAll('.node').forEach((g) => { var _a; return revs.set(g.getAttribute('data-id'), (_a = g.getAttribute('data-rev')) !== null && _a !== void 0 ? _a : ''); });",
2731
+ " const ids = [...revs.keys()];",
2732
+ " const saved = savedTicks(key);",
2733
+ " const done = new Set(ids.filter((id) => saved.get(id) === revs.get(id)));",
2734
+ " const count = document.getElementById('review-count');",
2735
+ " const bar = document.querySelector('#review-bar i');",
2736
+ " const next = document.getElementById('next-unreviewed');",
2737
+ " const paint = () => {",
2738
+ " document.querySelectorAll('.node').forEach((g) => g.classList.toggle('reviewed', done.has(g.getAttribute('data-id'))));",
2739
+ " document.querySelectorAll('#panel input[data-tick-for]').forEach((i) => {",
2740
+ " i.checked = done.has(i.getAttribute('data-tick-for'));",
2741
+ " });",
2742
+ " if (count)",
2743
+ " count.textContent = `${done.size}/${ids.length} reviewed`;",
2744
+ " if (bar)",
2745
+ " bar.style.width = `${(done.size / ids.length) * 100}%`;",
2746
+ " if (next)",
2747
+ " next.disabled = done.size === ids.length;",
2748
+ " };",
2749
+ " const toggle = (id) => {",
2750
+ " if (!done.delete(id))",
2751
+ " done.add(id);",
2752
+ " const all = savedTicks(key);",
2753
+ " if (done.has(id))",
2754
+ " all.set(id, revs.get(id));",
2755
+ " else",
2756
+ " all.delete(id);",
2757
+ " save(key, JSON.stringify([...all]));",
2758
+ " paint();",
2759
+ " };",
2760
+ " document.querySelectorAll('.tick').forEach((t) => {",
2761
+ " const id = t.closest('.node').getAttribute('data-id');",
2762
+ " t.addEventListener('pointerdown', (e) => e.stopPropagation());",
2763
+ " t.addEventListener('click', (e) => {",
2764
+ " e.stopPropagation();",
2765
+ " toggle(id);",
2766
+ " });",
2767
+ " });",
2768
+ " document.getElementById('panel').addEventListener('change', (e) => {",
2769
+ " const id = e.target.getAttribute('data-tick-for');",
2770
+ " if (id !== null)",
2771
+ " toggle(id);",
2772
+ " });",
2773
+ " if (next) {",
2774
+ " next.addEventListener('click', () => {",
2775
+ " var _a, _b;",
2776
+ " const at = ids.indexOf((_b = (_a = document.querySelector('.node.selected')) === null || _a === void 0 ? void 0 : _a.getAttribute('data-id')) !== null && _b !== void 0 ? _b : '');",
2777
+ " const to = ids.map((_, i) => ids[(at + 1 + i) % ids.length]).find((id) => !done.has(id));",
2778
+ " if (to !== undefined)",
2779
+ " goTo(to);",
2780
+ " });",
2781
+ " }",
2782
+ " paint();",
2783
+ " return { paint };",
2784
+ "}",
2785
+ "",
1477
2786
  "const THEMES = ['auto', 'light', 'dark'];",
1478
2787
  "const data = JSON.parse(document.getElementById('spec-data').textContent);",
1479
2788
  "const canvases = [...document.querySelectorAll('.canvas')];",
@@ -1486,21 +2795,7 @@ var CLIENT_JS = [
1486
2795
  "let last = 0;",
1487
2796
  "let drag = null;",
1488
2797
  "let moved = false;",
1489
- "function load(key) {",
1490
- " try {",
1491
- " return localStorage.getItem(key);",
1492
- " }",
1493
- " catch (_a) {",
1494
- " return null;",
1495
- " }",
1496
- "}",
1497
- "function save(key, value) {",
1498
- " try {",
1499
- " localStorage.setItem(key, value);",
1500
- " }",
1501
- " catch (_a) {",
1502
- " }",
1503
- "}",
2798
+ "let trail;",
1504
2799
  "function apply() {",
1505
2800
  " vps.forEach((vp, i) => {",
1506
2801
  " const t = ts[i];",
@@ -1571,12 +2866,6 @@ var CLIENT_JS = [
1571
2866
  " setLinked(load('codechart.panes.linked') !== '0', false);",
1572
2867
  " linkBtn.addEventListener('click', () => setLinked(!linked, true));",
1573
2868
  "}",
1574
- "function select(id) {",
1575
- " document.querySelectorAll('.node.selected').forEach((g) => g.classList.remove('selected'));",
1576
- " if (id === null)",
1577
- " return;",
1578
- " document.querySelectorAll(`.node[data-id=\"${CSS.escape(id)}\"]`).forEach((g) => g.classList.add('selected'));",
1579
- "}",
1580
2869
  "function setInfo(on) {",
1581
2870
  " info.hidden = !on;",
1582
2871
  " panel.hidden = on;",
@@ -1587,11 +2876,13 @@ var CLIENT_JS = [
1587
2876
  "function open(v) {",
1588
2877
  " const tpl = v === null ? null : panelFor(v);",
1589
2878
  " select(tpl ? v : null);",
2879
+ " focus(tpl ? v : null);",
1590
2880
  " if (tpl) {",
1591
2881
  " panel.textContent = '';",
1592
2882
  " panel.appendChild(tpl.content.cloneNode(true));",
1593
2883
  " }",
1594
2884
  " setInfo(!tpl);",
2885
+ " review.paint();",
1595
2886
  "}",
1596
2887
  "function reveal(v) {",
1597
2888
  " if (v === null)",
@@ -1608,6 +2899,16 @@ var CLIENT_JS = [
1608
2899
  " move(i, { x: t.x + (c.left + c.right - r.left - r.right) / 2, y: t.y + (c.top + c.bottom - r.top - r.bottom) / 2, k: t.k });",
1609
2900
  " });",
1610
2901
  "}",
2902
+ "function visit(id) {",
2903
+ " if (!panelFor(id))",
2904
+ " return;",
2905
+ " trail.go(id);",
2906
+ " focus(id);",
2907
+ "}",
2908
+ "function goTo(id) {",
2909
+ " visit(id);",
2910
+ " reveal(id);",
2911
+ "}",
1611
2912
  "function initPanel() {",
1612
2913
  " const backBtn = document.getElementById('nav-back');",
1613
2914
  " const forwardBtn = document.getElementById('nav-forward');",
@@ -1615,12 +2916,12 @@ var CLIENT_JS = [
1615
2916
  " const v = visitFromHash(location.hash);",
1616
2917
  " return v === undefined || (v !== null && !panelFor(v)) ? undefined : v;",
1617
2918
  " };",
1618
- " const visit = (v, travelled) => {",
2919
+ " const show = (v, travelled) => {",
1619
2920
  " open(v);",
1620
2921
  " if (travelled)",
1621
2922
  " reveal(v);",
1622
2923
  " };",
1623
- " const trail = startTrail(asked, visit, (back, forward) => {",
2924
+ " trail = startTrail(asked, show, (back, forward) => {",
1624
2925
  " backBtn.disabled = !back;",
1625
2926
  " forwardBtn.disabled = !forward;",
1626
2927
  " });",
@@ -1632,6 +2933,12 @@ var CLIENT_JS = [
1632
2933
  " if (e.key === 'ArrowLeft' ? trail.back() : trail.forward())",
1633
2934
  " e.preventDefault();",
1634
2935
  " });",
2936
+ " panel.addEventListener('click', (e) => {",
2937
+ " var _a;",
2938
+ " const to = (_a = e.target.closest('[data-goto]')) === null || _a === void 0 ? void 0 : _a.getAttribute('data-goto');",
2939
+ " if (to)",
2940
+ " goTo(to);",
2941
+ " });",
1635
2942
  " const showInfo = () => trail.go(null);",
1636
2943
  " if (infoBtn)",
1637
2944
  " infoBtn.addEventListener('click', showInfo);",
@@ -1639,10 +2946,7 @@ var CLIENT_JS = [
1639
2946
  " if (checkBtn)",
1640
2947
  " checkBtn.addEventListener('click', showInfo);",
1641
2948
  " document.querySelectorAll('.node').forEach((g) => {",
1642
- " const go = () => {",
1643
- " if (panelFor(g.getAttribute('data-id')))",
1644
- " trail.go(g.getAttribute('data-id'));",
1645
- " };",
2949
+ " const go = () => visit(g.getAttribute('data-id'));",
1646
2950
  " g.addEventListener('click', () => {",
1647
2951
  " if (!moved)",
1648
2952
  " go();",
@@ -1725,6 +3029,9 @@ var CLIENT_JS = [
1725
3029
  "initPanelResize();",
1726
3030
  "window.addEventListener('resize', fit);",
1727
3031
  "fit();",
3032
+ "dismissFocus(canvases, () => moved);",
3033
+ "initChips();",
3034
+ "const review = initReview(data.repoKey, goTo);",
1728
3035
  "initPanel();",
1729
3036
  "})();",
1730
3037
  ""
@@ -1740,8 +3047,8 @@ function jsonForScript(v) {
1740
3047
  var num = (n) => String(Math.round(n * 10) / 10);
1741
3048
  var arrowMarker = (id) => `<marker id="${id}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z"/></marker>`;
1742
3049
  var CHANGE_ARROWS = arrowMarker("arrow-added") + arrowMarker("arrow-removed");
1743
- function list(items) {
1744
- return `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>`;
3050
+ function list(items2) {
3051
+ return `<ul>${items2.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>`;
1745
3052
  }
1746
3053
  function midpoint(points) {
1747
3054
  let total = 0;
@@ -1762,10 +3069,10 @@ function midpoint(points) {
1762
3069
  return points[0] ?? { x: 0, y: 0 };
1763
3070
  }
1764
3071
  var keyHtml = (key) => key.map((k) => `<span class="k-${k.tone}">${esc(k.text)}</span>`).join(" \xB7 ");
1765
- var CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${createHash("sha256").update(CLIENT_JS).digest("base64")}'; img-src data:; base-uri 'none'; form-action 'none'`;
3072
+ var CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${createHash2("sha256").update(CLIENT_JS).digest("base64")}'; img-src data:; base-uri 'none'; form-action 'none'`;
1766
3073
  function renderPage(p) {
1767
3074
  const theme = p.meta.theme && THEMES.includes(p.meta.theme) ? p.meta.theme : "auto";
1768
- const data = { width: p.width, height: p.height };
3075
+ const data = { width: p.width, height: p.height, repoKey: p.meta.repoKey ?? p.meta.repo };
1769
3076
  const defs = `<defs>${arrowMarker("arrow")}${p.extraDefs ?? ""}</defs>`;
1770
3077
  const canvas = (viewport3, i) => `<div class="canvas"${p.panes ? "" : ' id="canvas"'}><svg>${i === 0 ? defs : ""}
1771
3078
  <g class="viewport">${viewport3}</g></svg></div>`;
@@ -1777,7 +3084,8 @@ function renderPage(p) {
1777
3084
  <style>${CSS}${p.extraCss ?? ""}</style></head>
1778
3085
  <body>
1779
3086
  <header><h1>${esc(p.title)}</h1>${p.headerNote ?? ""}<span class="meta">${esc(p.meta.repo)} \xB7 ${esc(p.meta.generatedAt.toISOString())}</span>${p.meta.update ? `<span class="update" title="A newer codechart is out">codechart ${esc(p.meta.update)} is out: run <code>codechart update</code></span>` : ""}${p.infoButton}${p.panes ? '<button id="link-toggle" type="button" title="Linked: panning or zooming one pane moves both"></button>' : ""}<button id="theme-toggle" type="button" title="Cycle theme: auto, light, dark"></button></header>
1780
- <main>
3087
+ ${p.toolbar ? `<div id="toolbar">${p.toolbar}</div>
3088
+ ` : ""}<main>
1781
3089
  ${body}
1782
3090
  <div id="resize" role="separator" aria-orientation="vertical" aria-label="Resize panel" tabindex="0" title="Drag to resize the panel"></div>
1783
3091
  <aside><nav id="panel-nav" aria-label="Panel history"><button id="nav-back" type="button" disabled aria-label="Back" title="Back (Alt+\u2190)">\u2190</button><button id="nav-forward" type="button" disabled aria-label="Forward" title="Forward (Alt+\u2192)">\u2192</button></nav>${p.aside}</aside>
@@ -1809,12 +3117,12 @@ function checkNote(c) {
1809
3117
  function checkSection(c) {
1810
3118
  let out = "";
1811
3119
  if (c?.mismatches.length) {
1812
- const items = c.mismatches.map((m) => `<li><b>${esc(m.label)}</b>: ${esc(m.detail)}<br><span class="mismatch-why">${esc(meaning(m))}</span></li>`).join("");
1813
- out += `<h3>Doesn't match the code</h3><p class="mismatch-why">${esc(CHECK_INTRO)}</p><ul>${items}</ul>`;
3120
+ const items2 = c.mismatches.map((m) => `<li><b>${esc(m.label)}</b>: ${esc(m.detail)}<br><span class="mismatch-why">${esc(meaning(m))}</span></li>`).join("");
3121
+ out += `<h3>Doesn't match the code</h3><p class="mismatch-why">${esc(CHECK_INTRO)}</p><ul>${items2}</ul>`;
1814
3122
  }
1815
3123
  if (c?.uncovered?.length) {
1816
- const items = c.uncovered.map((f) => `<li>${esc(f)}</li>`).join("");
1817
- out += `<h3>Changed, not on map</h3><p class="mismatch-why">${esc(UNCOVERED_WHY)}</p><ul>${items}</ul>`;
3124
+ const items2 = c.uncovered.map((f) => `<li>${esc(f)}</li>`).join("");
3125
+ out += `<h3>Changed, not on map</h3><p class="mismatch-why">${esc(UNCOVERED_WHY)}</p><ul>${items2}</ul>`;
1818
3126
  }
1819
3127
  return out;
1820
3128
  }
@@ -2208,7 +3516,48 @@ function fieldsOn(side, node) {
2208
3516
  return fields.filter((f) => f.change !== "added").map((f) => f.was === void 0 ? f : { ...f, type: f.was, was: void 0 });
2209
3517
  }
2210
3518
 
3519
+ // src/render/web/tools.ts
3520
+ import { createHash as createHash3 } from "crypto";
3521
+ var CHIP_ORDER = ["new", "changed", "removed", "planned", "config", "context", "existing"];
3522
+ var CHIP_MARK = { new: "+", changed: "~", removed: "\u2212", planned: "\u25CB", config: "\u25C6", context: "\xB7", existing: "\xB7" };
3523
+ var UNCHANGED = ["context", "existing"];
3524
+ function statusChips(statuses) {
3525
+ const counts = /* @__PURE__ */ new Map();
3526
+ for (const s of statuses) counts.set(s, (counts.get(s) ?? 0) + 1);
3527
+ const chips = CHIP_ORDER.filter((s) => counts.has(s)).map(
3528
+ (s) => `<button type="button" class="chip chip-${s}" data-status="${s}" aria-pressed="false" title="Fade ${s} nodes">${CHIP_MARK[s]}${counts.get(s)} ${s}</button>`
3529
+ );
3530
+ const unchanged = UNCHANGED.find((s) => counts.has(s));
3531
+ if (unchanged) {
3532
+ chips.unshift(
3533
+ `<button type="button" class="chip chip-delta" data-delta="${unchanged}" aria-pressed="false" title="Fade ${unchanged} nodes, leaving only the changes">\u0394 changes only</button>`
3534
+ );
3535
+ }
3536
+ return chips.length ? `<div id="chips" role="group" aria-label="Status filter">${chips.join("")}</div>` : "";
3537
+ }
3538
+ var reviewControls = (total) => `<div id="review"><span id="review-count">0/${total} reviewed</span><span id="review-bar" aria-hidden="true"><i></i></span><button id="next-unreviewed" type="button" title="Next unreviewed: select the next node not ticked as reviewed" aria-label="Next unreviewed">Next \u25B8</button></div>`;
3539
+ var diffRev = (p) => p ? createHash3("sha256").update(JSON.stringify(p)).digest("hex").slice(0, 12) : void 0;
3540
+ var tickSvg = (x, y) => `<g class="tick" aria-hidden="true"><rect class="tick-hit" x="${num(x - 9)}" y="${num(y - 9)}" width="18" height="18"/><rect class="tick-box" x="${num(x - 6)}" y="${num(y - 6)}" width="12" height="12" rx="2"/><path class="tick-mark" d="M${num(x - 3)},${num(y)} L${num(x - 1)},${num(y + 3)} L${num(x + 3.5)},${num(y - 3)}"/></g>`;
3541
+ var tickRow = (id) => `<label class="tick-row"><input type="checkbox" data-tick-for="${esc(id)}"> Reviewed</label>`;
3542
+ var note = (l) => l.label || (l.kind !== "other" ? l.kind : void 0);
3543
+ function relationsOf(id, links, labelOf2) {
3544
+ return links.flatMap((l) => {
3545
+ if (l.from !== id && l.to !== id) return [];
3546
+ const out = l.from === id;
3547
+ const other = out ? l.to : l.from;
3548
+ return [{ out, id: other, label: labelOf2(other), ...note(l) ? { kind: note(l) } : {} }];
3549
+ });
3550
+ }
3551
+ function relationsHtml(rels) {
3552
+ if (!rels.length) return "";
3553
+ const rows = rels.map(
3554
+ (r) => `<li><button type="button" class="rel" data-goto="${esc(r.id)}">${r.out ? "\u2192" : "\u2190"} ${esc(r.label)}${r.kind ? ` (${esc(r.kind)})` : ""}</button></li>`
3555
+ );
3556
+ return `<h3>Relations</h3><ul class="relations">${rows.join("")}</ul>`;
3557
+ }
3558
+
2211
3559
  // src/render/web/diagram.ts
3560
+ var edgeEnds = (from, to, labelOf2) => ({ from, to, title: `${labelOf2(from)} \u2192 ${labelOf2(to)}` });
2212
3561
  function renderEdgeSvg(e) {
2213
3562
  if (e.points.length < 2) return "";
2214
3563
  const d = e.points.map((p, i) => `${i ? "L" : "M"}${num(p.x)},${num(p.y)}`).join(" ");
@@ -2218,7 +3567,7 @@ function renderEdgeSvg(e) {
2218
3567
  const w = e.label.length * 5.6 + 6;
2219
3568
  out += `<rect x="${num(m.x - w / 2)}" y="${num(m.y - e.lift)}" width="${num(w)}" height="12" rx="2"/><text x="${num(m.x)}" y="${num(m.y + 9 - e.lift)}">${esc(e.label)}</text>`;
2220
3569
  }
2221
- return `<g class="${e.cls}">${out}</g>`;
3570
+ return `<g class="${e.cls}" data-from="${esc(e.ends.from)}" data-to="${esc(e.ends.to)}"><title>${esc(e.ends.title)}</title>${out}</g>`;
2222
3571
  }
2223
3572
  function infoButton(check, hasInfo, text) {
2224
3573
  const t = flagged(check) ? text.mismatch : hasInfo ? text.info : void 0;
@@ -2228,13 +3577,14 @@ function pageInfoSection(hint, sides2, check, ...notes) {
2228
3577
  const panes = sides2 ? '; while "Panes: linked", both panes move together' : "";
2229
3578
  return `<section id="page-info"><p>${hint}${panes}.</p>${checkSection(check)}${notes.join("")}</section>`;
2230
3579
  }
2231
- var gapsHtml = (heading, items) => items?.length ? `<h3>${heading}</h3>${list(items)}` : "";
3580
+ var gapsHtml = (heading, items2) => items2?.length ? `<h3>${heading}</h3>${list(items2)}` : "";
2232
3581
  function renderDiagramPage(p) {
2233
3582
  return renderPage({
2234
3583
  title: p.title,
2235
3584
  meta: p.meta,
2236
3585
  infoButton: p.infoButton,
2237
3586
  headerNote: checkNote(p.check),
3587
+ toolbar: statusChips(p.statuses) + reviewControls(p.statuses.length),
2238
3588
  viewport: p.sides ? "" : p.viewport(),
2239
3589
  ...p.sides ? { panes: SIDES.map((side) => ({ title: SIDE_TITLE[side], key: p.paneKey[side], viewport: p.viewport(side) })) } : {},
2240
3590
  aside: p.aside,
@@ -2403,10 +3753,11 @@ function renderStep(step, b, flag, side) {
2403
3753
  text += `<text class="label" x="${cx}" y="${num(y + 11)}">${esc(l)}</text>`;
2404
3754
  y += LINE_HEIGHT2;
2405
3755
  }
2406
- return `<g class="node type-${step.type} status-${status}" data-id="${esc(step.id)}" tabindex="0" role="button" aria-label="${esc(`${step.label} (${step.status} ${step.type}${flagged2 ? ", doesn't match the code" : ""})`)}">` + flag + shape(step, b) + text + (flagged2 ? flagMark(b.x + b.w, b.y) : "") + `</g>`;
3756
+ return `<g class="node type-${step.type} status-${status}" data-id="${esc(step.id)}" data-status="${step.status}" tabindex="0" role="button" aria-label="${esc(`${step.label} (${step.status} ${step.type}${flagged2 ? ", doesn't match the code" : ""})`)}">` + flag + shape(step, b) + text + tickSvg(b.x, b.y) + (flagged2 ? flagMark(b.x + b.w, b.y) : "") + `</g>`;
2407
3757
  }
2408
- function renderLink(link, e, tone) {
3758
+ function renderLink(link, e, tone, ends) {
2409
3759
  return renderEdgeSvg({
3760
+ ends,
2410
3761
  points: e.points,
2411
3762
  marker: `arrow${tone ? `-${tone}` : ""}`,
2412
3763
  cls: `edge${tone === "planned" ? " planned" : tone === "removed" ? " edge-removed" : ""}`,
@@ -2426,7 +3777,7 @@ function snippetHtml(s) {
2426
3777
  }
2427
3778
  var tag = (status) => `<span class="tag tag-${esc(status)}">${esc(status)}</span>`;
2428
3779
  function stepPanel(spec, step, snippets, byId, check) {
2429
- let out = `<h2>${esc(step.label)}</h2>`;
3780
+ let out = `<h2>${esc(step.label)}</h2>${tickRow(step.id)}`;
2430
3781
  out += `<div class="status">${tag(step.status)} ${esc(step.type)}</div>`;
2431
3782
  out += mismatchNote(check, step.id);
2432
3783
  const snip = snippets.steps.get(step.id);
@@ -2438,7 +3789,7 @@ function stepPanel(spec, step, snippets, byId, check) {
2438
3789
  else if (step.source) out += `<div class="path">${esc(step.source)}</div>`;
2439
3790
  const next = spec.links.map((l, i) => ({ l, i })).filter(({ l }) => l.from === step.id);
2440
3791
  if (next.length) {
2441
- const items = next.map(({ l, i }) => {
3792
+ const items2 = next.map(({ l, i }) => {
2442
3793
  const target = byId.get(l.to)?.label ?? l.to;
2443
3794
  let li = `${l.label ? `<b>${esc(l.label)}</b> \u2192 ` : "\u2192 "}${esc(target)}`;
2444
3795
  if (isRemovedLink(spec, l)) li += ` ${tag("removed")}`;
@@ -2448,8 +3799,10 @@ function stepPanel(spec, step, snippets, byId, check) {
2448
3799
  else if (l.source) li += `<div class="path">${esc(l.source)}</div>`;
2449
3800
  return `<li>${li}</li>`;
2450
3801
  });
2451
- out += `<h3>Next</h3><ul class="branches">${items.join("")}</ul>`;
3802
+ out += `<h3>Next</h3><ul class="branches">${items2.join("")}</ul>`;
2452
3803
  }
3804
+ const links = spec.links.map((l) => ({ from: l.from, to: l.to, label: l.label }));
3805
+ out += relationsHtml(relationsOf(step.id, links, (id) => byId.get(id)?.label ?? id));
2453
3806
  return `<template class="card-panel" data-for="${esc(step.id)}">${out}</template>`;
2454
3807
  }
2455
3808
  function pageInfo(spec, anyPlanned, sides2, check) {
@@ -2463,7 +3816,7 @@ function viewport(spec, layout, check, side) {
2463
3816
  const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
2464
3817
  const edges = spec.links.map((l, i) => {
2465
3818
  if (!layout.edges[i] || side && !linkOn(side, spec, l, byId)) return "";
2466
- return renderLink(l, layout.edges[i], linkTone(side, spec, l));
3819
+ return renderLink(l, layout.edges[i], linkTone(side, spec, l), edgeEnds(l.from, l.to, (id) => byId.get(id)?.label ?? id));
2467
3820
  }).join("");
2468
3821
  const nodes = spec.steps.filter((s) => !side || stepOn(side, s)).map((s) => {
2469
3822
  const b = boxes.get(s.id);
@@ -2483,6 +3836,7 @@ function renderFlowHtml(spec, layout, snippets, meta, check) {
2483
3836
  mismatch: { label: "Check / gaps", title: "Show what doesn't match the code and what the agent did not check" },
2484
3837
  info: { label: "Gaps", title: "Show what the agent did not check" }
2485
3838
  }),
3839
+ statuses: spec.steps.map((s) => s.status),
2486
3840
  sides: sides2,
2487
3841
  paneKey: FLOW_SIDE_KEY,
2488
3842
  viewport: (side) => viewport(spec, layout, check, side),
@@ -2505,8 +3859,9 @@ function fieldText(f) {
2505
3859
  const type = f.was !== void 0 ? `${f.was} \u2192 ${f.type ?? "?"}` : f.type;
2506
3860
  return `${f.change ? FIELD_MARK[f.change] : ""}${f.name}${type ? ": " + type : ""}${f.note ? " (" + f.note + ")" : ""}`;
2507
3861
  }
2508
- function renderEdge(e, change) {
3862
+ function renderEdge(e, change, ends) {
2509
3863
  return renderEdgeSvg({
3864
+ ends,
2510
3865
  points: e.points,
2511
3866
  marker: `arrow${change ? `-${change}` : ""}`,
2512
3867
  cls: `edge${change ? ` edge-${change}` : ""}`,
@@ -2534,7 +3889,7 @@ function cardShape(shape2, { x, y, w, h }, head) {
2534
3889
  const card = `<rect class="card" x="${x}" y="${y}" width="${w}" height="${h}"${shape2 === "symbol" ? "" : ' rx="6"'}/>`;
2535
3890
  return shape2 === "data" ? card + `<line class="head" x1="${x}" y1="${y + head - 3}" x2="${r}" y2="${y + head - 3}"/>` : card;
2536
3891
  }
2537
- function renderNode(n, box, flag, fields) {
3892
+ function renderNode(n, box, flag, fields, rev) {
2538
3893
  const flagged2 = flag !== "";
2539
3894
  const x = Math.round(box.x * 10) / 10;
2540
3895
  const y = Math.round(box.y * 10) / 10;
@@ -2553,7 +3908,7 @@ function renderNode(n, box, flag, fields) {
2553
3908
  const height = Math.max(row, Math.round(box.h * 10) / 10);
2554
3909
  const shape2 = SHAPE2[n.kind];
2555
3910
  const top = y + 18 + KIND_ROW;
2556
- return `<g class="node status-${n.status} shape-${shape2}" data-id="${esc(n.id)}" tabindex="0" role="button" aria-label="${esc(`${n.label} (${nodeWhat(n)}${flagged2 ? ", doesn't match the code" : ""})`)}">` + flag + cardShape(shape2, { x, y, w, h: height }, head) + `<line class="head" x1="${x}" y1="${y + head}" x2="${x + w}" y2="${y + head}"/>` + (n.kind === "other" ? "" : `<text class="kind" x="${x + 8}" y="${y + 12}">${n.kind}</text>`) + labelLines(n.label).map((l, i) => `<text class="label" x="${x + 8}" y="${top + i * LABEL_LINE_HEIGHT}">${esc(l)}</text>`).join("") + `<text class="badge" x="${x + w - 8}" y="${top}">${esc(n.status)}</text>` + lines.join("") + (flagged2 ? flagMark(shape2 === "file" ? x + w - FOLD - 6 : x + w, y) : "") + `</g>`;
3911
+ return `<g class="node status-${n.status} shape-${shape2}" data-id="${esc(n.id)}" data-status="${n.status}"${rev ? ` data-rev="${rev}"` : ""} tabindex="0" role="button" aria-label="${esc(`${n.label} (${nodeWhat(n)}${flagged2 ? ", doesn't match the code" : ""})`)}">` + flag + cardShape(shape2, { x, y, w, h: height }, head) + `<line class="head" x1="${x}" y1="${y + head}" x2="${x + w}" y2="${y + head}"/>` + (n.kind === "other" ? "" : `<text class="kind" x="${x + 8}" y="${y + 12}">${n.kind}</text>`) + labelLines(n.label).map((l, i) => `<text class="label" x="${x + 8}" y="${top + i * LABEL_LINE_HEIGHT}">${esc(l)}</text>`).join("") + `<text class="badge" x="${x + w - 8}" y="${top}">${esc(n.status)}</text>` + lines.join("") + tickSvg(x, y) + (flagged2 ? flagMark(shape2 === "file" ? x + w - FOLD - 6 : x + w, y) : "") + `</g>`;
2557
3912
  }
2558
3913
  var FIELDS_NOTE = "Only the fields the agent saw are listed. Set <code>defaults.context: full</code> in <code>.codechart.yaml</code> to let it read the full definition.";
2559
3914
  var DIFF_MARK = { add: "+", del: "-", ctx: " " };
@@ -2575,8 +3930,8 @@ function fieldsHtml(n, sides2) {
2575
3930
  if (JSON.stringify(now) === JSON.stringify(after)) return `<h3>Fields</h3>${fieldList(after)}`;
2576
3931
  return `<h3>Fields now</h3>${fieldList(now)}<h3>Fields after</h3>${fieldList(after)}`;
2577
3932
  }
2578
- function cardPanel(n, check, previews, sides2) {
2579
- let out = `<h2>${esc(`${n.label} (${nodeWhat(n)})`)}</h2>`;
3933
+ function cardPanel(spec, n, check, previews, sides2) {
3934
+ let out = `<h2>${esc(`${n.label} (${nodeWhat(n)})`)}</h2>${tickRow(n.id)}`;
2580
3935
  out += mismatchNote(check, n.id);
2581
3936
  const match = check?.matches.get(n.id);
2582
3937
  if (match) out += snippetHtml(match);
@@ -2589,30 +3944,32 @@ function cardPanel(n, check, previews, sides2) {
2589
3944
  if (n.fieldsComplete === false) out += `<p class="fields-note">${FIELDS_NOTE}</p>`;
2590
3945
  }
2591
3946
  if (n.notes?.length) out += `<h3>Notes</h3>${list(n.notes)}`;
3947
+ out += relationsHtml(relationsOf(n.id, spec.edges, labelOf(spec)));
2592
3948
  return `<template class="card-panel" data-for="${esc(n.id)}">${out}</template>`;
2593
3949
  }
3950
+ var labelOf = (spec) => (id) => spec.nodes.find((n) => n.id === id)?.label ?? id;
2594
3951
  function pageInfo2(spec, check, sides2) {
2595
3952
  const hint = "Click a node for details. Scroll to zoom, drag to pan";
2596
3953
  return pageInfoSection(hint, sides2, check, gapsHtml("Gaps", spec.gaps), gapsHtml("Not on map", spec.omitted));
2597
3954
  }
2598
- function viewport2(spec, layout, check, side) {
3955
+ function viewport2(spec, layout, check, side, previews) {
2599
3956
  const boxes = new Map(layout.nodes.map((n) => [n.id, n]));
2600
3957
  const statusOf = new Map(spec.nodes.map((n) => [n.id, n.status]));
2601
3958
  const shown = spec.nodes.filter((n) => !side || nodeOn(side, n.status));
2602
3959
  const layers = new Set(shown.map((n) => n.layer));
2603
- const present2 = new Set(shown.map((n) => n.id));
3960
+ const present3 = new Set(shown.map((n) => n.id));
2604
3961
  const groups = layout.groups.filter((g) => layers.has(g.layer)).map(
2605
3962
  (g) => `<g class="group"><rect x="${num(g.x)}" y="${num(g.y)}" width="${num(g.w)}" height="${num(g.h)}" rx="8"/><text x="${num(g.x + 10)}" y="${num(g.y + 16)}">${esc(g.layer)}</text></g>`
2606
3963
  ).join("");
2607
3964
  const nodes = shown.map((n) => {
2608
3965
  const b = boxes.get(n.id);
2609
- return b ? renderNode(n, b, flagTitle(check, n.id), side ? fieldsOn(side, n) : n.fields ?? []) : "";
3966
+ return b ? renderNode(n, b, flagTitle(check, n.id), side ? fieldsOn(side, n) : n.fields ?? [], diffRev(previews?.get(n.id))) : "";
2610
3967
  }).join("");
2611
3968
  const edges = layout.edges.map((e) => {
2612
3969
  const edge = spec.edges[e.index];
2613
3970
  const change = side ? edgeChange(edge, statusOf) : edge.change;
2614
- const drawn = !side || edgeOn(side, change) && present2.has(edge.from) && present2.has(edge.to);
2615
- return drawn ? renderEdge(e, change) : "";
3971
+ const drawn = !side || edgeOn(side, change) && present3.has(edge.from) && present3.has(edge.to);
3972
+ return drawn ? renderEdge(e, change, edgeEnds(edge.from, edge.to, labelOf(spec))) : "";
2616
3973
  }).join("");
2617
3974
  return `${groups}${edges}${nodes}`;
2618
3975
  }
@@ -2629,10 +3986,11 @@ function renderHtml(spec, layout, meta, check, previews) {
2629
3986
  },
2630
3987
  info: { label: "Not on map / gaps", title: "Show what is not on the map and what the agent did not read" }
2631
3988
  }),
3989
+ statuses: spec.nodes.map((n) => n.status),
2632
3990
  sides: sides2,
2633
3991
  paneKey: SIDE_KEY,
2634
- viewport: (side) => viewport2(spec, layout, check, side),
2635
- aside: `${pageInfo2(spec, check, sides2)}<div id="panel" hidden></div>${spec.nodes.map((n) => cardPanel(n, check, previews, sides2)).join("")}`,
3992
+ viewport: (side) => viewport2(spec, layout, check, side, previews),
3993
+ aside: `${pageInfo2(spec, check, sides2)}<div id="panel" hidden></div>${spec.nodes.map((n) => cardPanel(spec, n, check, previews, sides2)).join("")}`,
2636
3994
  width: layout.width,
2637
3995
  height: layout.height,
2638
3996
  extraDefs: CHANGE_ARROWS
@@ -2674,13 +4032,13 @@ function nodeDetail(n, check) {
2674
4032
  if (m) lines.push(`\u2717 ${md(m.detail)}`);
2675
4033
  if (n.summary) lines.push(md(n.summary));
2676
4034
  if (n.fields?.length) lines.push(`Fields: ${n.fields.map((f) => md(fieldText(f))).join(" \xB7 ")}${n.fieldsComplete === false ? " (only the ones the agent saw)" : ""}`);
2677
- for (const note of n.notes ?? []) lines.push(`Note: ${md(note)}`);
4035
+ for (const note2 of n.notes ?? []) lines.push(`Note: ${md(note2)}`);
2678
4036
  return [head, ...lines.map((l) => ` - ${l}`)].join("\n");
2679
4037
  }
2680
- var MAX_FILES = 8;
4038
+ var MAX_FILES2 = 8;
2681
4039
  var fileList = (files) => {
2682
- const shown = files.slice(0, MAX_FILES).map((f) => `\`${f.replace(/`/g, "")}\``);
2683
- return [...shown, ...files.length > MAX_FILES ? [`+${files.length - MAX_FILES} more`] : []].join(", ");
4040
+ const shown = files.slice(0, MAX_FILES2).map((f) => `\`${f.replace(/`/g, "")}\``);
4041
+ return [...shown, ...files.length > MAX_FILES2 ? [`+${files.length - MAX_FILES2} more`] : []].join(", ");
2684
4042
  };
2685
4043
  var STATUS_ORDER = ["new", "changed", "removed", "config", "context"];
2686
4044
  var KEY = STATUS_ORDER.map((s) => `${marker(s)} ${s}`.trimStart()).join(" \xB7 ");
@@ -2747,13 +4105,13 @@ function replaceSection(body, block) {
2747
4105
  }
2748
4106
 
2749
4107
  // src/pr/platforms.ts
2750
- import { readFileSync as readFileSync2 } from "fs";
4108
+ import { readFileSync as readFileSync5 } from "fs";
2751
4109
 
2752
4110
  // src/pr/git.ts
2753
- import { execFileSync as execFileSync2 } from "child_process";
4111
+ import { execFileSync as execFileSync4 } from "child_process";
2754
4112
  function gitRun(cwd, args, input, env) {
2755
4113
  try {
2756
- return execFileSync2(gitBinary(), args, { cwd, encoding: "utf8", input, env, stdio: ["pipe", "pipe", "pipe"], timeout: 6e4 }).trim();
4114
+ return execFileSync4(gitBinary(), args, { cwd, encoding: "utf8", input, env, stdio: ["pipe", "pipe", "pipe"], timeout: 6e4 }).trim();
2757
4115
  } catch (e) {
2758
4116
  const stderr = String(e.stderr ?? "").trim().split("\n")[0];
2759
4117
  throw new Error(`git ${args[0]} failed: ${stderr || e.message}`);
@@ -2772,7 +4130,7 @@ async function call(fetchFn, url, init, what) {
2772
4130
  return res;
2773
4131
  }
2774
4132
  function githubReview(env, cwd, fetchFn = fetch) {
2775
- const event = JSON.parse(readFileSync2(need(env, "GITHUB_EVENT_PATH"), "utf8"));
4133
+ const event = JSON.parse(readFileSync5(need(env, "GITHUB_EVENT_PATH"), "utf8"));
2776
4134
  const pr = event.pull_request;
2777
4135
  if (!pr) throw new Error("not a pull_request event");
2778
4136
  const repo = need(env, "GITHUB_REPOSITORY");
@@ -2831,16 +4189,16 @@ function reviewFromEnv(env, cwd, fetchFn = fetch) {
2831
4189
  }
2832
4190
 
2833
4191
  // src/commands/render.ts
2834
- import { constants as constants3, closeSync as closeSync3, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync3 } from "fs";
2835
- import { basename as basename3, dirname as dirname6, join as join10, resolve as resolve7 } from "path";
2836
- import { Command as Command5, Option } from "commander";
4192
+ import { constants as constants4, closeSync as closeSync3, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync3 } from "fs";
4193
+ import { basename as basename3, dirname as dirname8, join as join20, resolve as resolve10 } from "path";
4194
+ import { Command as Command8, Option } from "commander";
2837
4195
 
2838
4196
  // src/render/check.ts
2839
- import { relative as relative3, resolve as resolve5, sep as sep3 } from "path";
4197
+ import { relative as relative3, resolve as resolve8, sep as sep4 } from "path";
2840
4198
 
2841
4199
  // src/render/flow/anchors.ts
2842
- import { realpathSync as realpathSync2, statSync } from "fs";
2843
- import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2, sep as sep2 } from "path";
4200
+ import { realpathSync as realpathSync4, statSync as statSync2 } from "fs";
4201
+ import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep as sep3 } from "path";
2844
4202
 
2845
4203
  // src/render/clip.ts
2846
4204
  var MAX_CHARS = 300;
@@ -2850,8 +4208,8 @@ var clip2 = (l) => l.length > MAX_CHARS ? `${l.slice(0, MAX_CHARS)}\u2026` : l;
2850
4208
  var SNIPPET_MAX_LINES = 15;
2851
4209
  var MAX_BYTES2 = 5 * 1024 * 1024;
2852
4210
  var MAX_TOTAL_BYTES = 25 * 1024 * 1024;
2853
- var escapes = (rel) => rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel);
2854
- var inGit = (rel) => rel.split(sep2).some((s) => s.toLowerCase() === ".git");
4211
+ var escapes = (rel) => rel === ".." || rel.startsWith(`..${sep3}`) || isAbsolute3(rel);
4212
+ var inGit = (rel) => rel.split(sep3).some((s) => s.toLowerCase() === ".git");
2855
4213
  var toLines = (text) => {
2856
4214
  const lines = text.split(/\r?\n/);
2857
4215
  if (lines[lines.length - 1] === "") lines.pop();
@@ -2863,7 +4221,7 @@ var overBudget = (path3) => ({
2863
4221
  function readLinesAt(path3, rel, root, sha, budget) {
2864
4222
  try {
2865
4223
  if (budget.left <= 0) return overBudget(path3);
2866
- const r = gitFileAt(root, sha, rel.split(sep2).join("/"), MAX_BYTES2);
4224
+ const r = gitFileAt(root, sha, rel.split(sep3).join("/"), MAX_BYTES2);
2867
4225
  if (typeof r !== "string") return r;
2868
4226
  budget.left -= Buffer.byteLength(r);
2869
4227
  return budget.left < 0 ? overBudget(path3) : toLines(r);
@@ -2874,7 +4232,7 @@ function readLinesAt(path3, rel, root, sha, budget) {
2874
4232
  function readLines(path3, root, realRoot, budget) {
2875
4233
  let real;
2876
4234
  try {
2877
- real = realpathSync2(resolve2(root, path3));
4235
+ real = realpathSync4(resolve5(root, path3));
2878
4236
  } catch (e) {
2879
4237
  const code = e.code;
2880
4238
  return code === "ENOENT" || code === "ENOTDIR" ? null : { error: `${path3} cannot be read (${code})` };
@@ -2920,39 +4278,39 @@ function findMatch(path3, match, lines) {
2920
4278
  function anchorContext(root, at, cwd) {
2921
4279
  return {
2922
4280
  root,
2923
- realRoot: realpathSync2(root),
4281
+ realRoot: realpathSync4(root),
2924
4282
  at,
2925
4283
  budget: { left: MAX_TOTAL_BYTES },
2926
- cwd: cwd !== void 0 && resolve2(cwd) !== resolve2(root) ? resolve2(cwd) : void 0,
4284
+ cwd: cwd !== void 0 && resolve5(cwd) !== resolve5(root) ? resolve5(cwd) : void 0,
2927
4285
  cache: /* @__PURE__ */ new Map()
2928
4286
  };
2929
4287
  }
2930
4288
  function refused(path3, rel) {
2931
- if (isAbsolute2(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
4289
+ if (isAbsolute3(path3) || escapes(rel)) return { error: `${path3} is outside the repo` };
2932
4290
  if (inGit(rel)) return { error: `${path3} is inside .git` };
2933
4291
  return void 0;
2934
4292
  }
2935
4293
  function read(c, path3) {
2936
- const rel = relative2(c.root, resolve2(c.root, path3));
4294
+ const rel = relative2(c.root, resolve5(c.root, path3));
2937
4295
  const no = refused(path3, rel);
2938
4296
  if (no) return no;
2939
4297
  return c.at ? readLinesAt(path3, rel, c.root, c.at, c.budget) : readLines(path3, c.root, c.realRoot, c.budget);
2940
4298
  }
2941
- function present(c, path3) {
2942
- const rel = relative2(c.root, resolve2(c.root, path3));
4299
+ function present2(c, path3) {
4300
+ const rel = relative2(c.root, resolve5(c.root, path3));
2943
4301
  const no = refused(path3, rel);
2944
4302
  if (no) return no;
2945
4303
  if (c.at) {
2946
4304
  c.tree ??= new Set(gitListFiles(c.root, c.at));
2947
- const slashed = rel.split(sep2).join("/");
4305
+ const slashed = rel.split(sep3).join("/");
2948
4306
  if (slashed === "" || c.tree.has(slashed)) return true;
2949
4307
  for (const f of c.tree) if (f.startsWith(`${slashed}/`)) return true;
2950
4308
  return false;
2951
4309
  }
2952
4310
  try {
2953
- const real = realpathSync2(resolve2(c.root, path3));
4311
+ const real = realpathSync4(resolve5(c.root, path3));
2954
4312
  if (escapes(relative2(c.realRoot, real))) return { error: `${path3} is outside the repo` };
2955
- statSync(real);
4313
+ statSync2(real);
2956
4314
  return true;
2957
4315
  } catch (e) {
2958
4316
  const code = e.code;
@@ -2961,11 +4319,11 @@ function present(c, path3) {
2961
4319
  }
2962
4320
  function withCwd(c, path3, get, missing) {
2963
4321
  const direct = get(path3);
2964
- const outside = !isAbsolute2(path3) && escapes(relative2(c.root, resolve2(c.root, path3)));
4322
+ const outside = !isAbsolute3(path3) && escapes(relative2(c.root, resolve5(c.root, path3)));
2965
4323
  if (c.cwd && (missing(direct) || outside)) {
2966
- const rel = relative2(c.root, resolve2(c.cwd, path3));
4324
+ const rel = relative2(c.root, resolve5(c.cwd, path3));
2967
4325
  if (rel !== "" && !escapes(rel)) {
2968
- const alt = rel.split(sep2).join("/");
4326
+ const alt = rel.split(sep3).join("/");
2969
4327
  const value = get(alt);
2970
4328
  if (!missing(value)) return { path: alt, value };
2971
4329
  }
@@ -2981,13 +4339,13 @@ function load(c, path3) {
2981
4339
  return loaded;
2982
4340
  }
2983
4341
  function locate(c, path3) {
2984
- const { path: found, value } = withCwd(c, path3, (p) => present(c, p), (v) => v === false);
4342
+ const { path: found, value } = withCwd(c, path3, (p) => present2(c, p), (v) => v === false);
2985
4343
  return typeof value === "boolean" ? { path: found, found: value } : value;
2986
4344
  }
2987
4345
  var MAX_LISTED_FILES = 2e5;
2988
4346
  function likelyPath(c, path3) {
2989
4347
  const slashed = path3.replaceAll("\\", "/");
2990
- if (isAbsolute2(path3) || slashed.split("/").includes("..")) return "";
4348
+ if (isAbsolute3(path3) || slashed.split("/").includes("..")) return "";
2991
4349
  const tail = `/${slashed.replace(/^(\.\/)+/, "")}`;
2992
4350
  if (!c.listing) {
2993
4351
  try {
@@ -3081,9 +4439,9 @@ function checkFlowAnchors(spec, root, at, cwd) {
3081
4439
  }
3082
4440
 
3083
4441
  // src/render/markdown.ts
3084
- import { resolve as resolve3 } from "path";
4442
+ import { resolve as resolve6 } from "path";
3085
4443
  import { pathToFileURL } from "url";
3086
- var longestTicks = (s) => Math.max(0, ...(s.match(/`+/g) ?? []).map((run) => run.length));
4444
+ var longestTicks = (s) => Math.max(0, ...(s.match(/`+/g) ?? []).map((run2) => run2.length));
3087
4445
  function markdownBlock(header, body, htmlPath, lang = "text") {
3088
4446
  const lines = [header];
3089
4447
  if (body !== void 0) {
@@ -3093,14 +4451,14 @@ ${body.trimEnd()}
3093
4451
  ${fence}`);
3094
4452
  }
3095
4453
  if (htmlPath) {
3096
- const href = pathToFileURL(resolve3(htmlPath)).href;
4454
+ const href = pathToFileURL(resolve6(htmlPath)).href;
3097
4455
  lines.push("", `[Open full map](${href.replace(/\(/g, "%28").replace(/\)/g, "%29")})`);
3098
4456
  }
3099
4457
  return `${lines.join("\n")}
3100
4458
  `;
3101
4459
  }
3102
4460
  function openBlockedNote(htmlPath, md2) {
3103
- const href = pathToFileURL(resolve3(htmlPath)).href;
4461
+ const href = pathToFileURL(resolve6(htmlPath)).href;
3104
4462
  const say = "Your editor didn't let codechart open the page. Paste this into your browser's address bar:";
3105
4463
  return md2 ? `${say}
3106
4464
 
@@ -3113,7 +4471,7 @@ ${href}
3113
4471
  }
3114
4472
 
3115
4473
  // src/render/terminal/render.ts
3116
- import { resolve as resolve4 } from "path";
4474
+ import { resolve as resolve7 } from "path";
3117
4475
  import { pathToFileURL as pathToFileURL2 } from "url";
3118
4476
 
3119
4477
  // src/render/terminal/blocks.ts
@@ -3226,7 +4584,7 @@ var NOT_TTY_WIDTH = 80;
3226
4584
  var MAX_ENV_WIDTH = 300;
3227
4585
  var KEY_ORDER = ["new", "changed", "removed", "config"];
3228
4586
  var KEY2 = `key: ${KEY_ORDER.map((s) => `${marker(s)} ${s}`).join(" ")} \xB7 unmarked = unchanged`;
3229
- var fullMapLine = (htmlPath) => `full map \u2192 ${pathToFileURL2(resolve4(htmlPath)).href}`;
4587
+ var fullMapLine = (htmlPath) => `full map \u2192 ${pathToFileURL2(resolve7(htmlPath)).href}`;
3230
4588
  function defaultWidth(stdout = process.stdout, env = process.env) {
3231
4589
  if (stdout.isTTY) return Math.min(stdout.columns || MAX_WIDTH, MAX_WIDTH);
3232
4590
  const fromEnv = Math.floor(Number(env.COLUMNS));
@@ -3299,20 +4657,20 @@ function walkFlow(spec, budget) {
3299
4657
  return { kind: "ref", step, via };
3300
4658
  };
3301
4659
  const chain = (first, firstPaid) => {
3302
- const items = [];
4660
+ const items2 = [];
3303
4661
  let step = first;
3304
4662
  let via;
3305
4663
  for (let paid = firstPaid; ; paid = false) {
3306
- if (!paid && !take(step.id)) return { items: [...items, cut2(step.id, via)] };
4664
+ if (!paid && !take(step.id)) return { items: [...items2, cut2(step.id, via)] };
3307
4665
  const links = out.get(step.id) ?? [];
3308
4666
  if (step.type === "decision" || links.length > 1) {
3309
- return { items, branch: { head: step, arms: links.map((link) => ({ link, chain: arm(link.to) })) } };
4667
+ return { items: items2, branch: { head: step, arms: links.map((link) => ({ link, chain: arm(link.to) })) } };
3310
4668
  }
3311
- items.push({ kind: "step", step, via });
3312
- if (links.length === 0) return { items };
4669
+ items2.push({ kind: "step", step, via });
4670
+ if (links.length === 0) return { items: items2 };
3313
4671
  via = links[0];
3314
4672
  const next = byId.get(via.to);
3315
- if (shared.has(next.id)) return { items: [...items, ref(next, via)] };
4673
+ if (shared.has(next.id)) return { items: [...items2, ref(next, via)] };
3316
4674
  step = next;
3317
4675
  }
3318
4676
  };
@@ -3362,10 +4720,10 @@ function linkMark(link, ctx) {
3362
4720
  return link.planned === true && !endsAre(ctx.spec, link, "planned") ? "?" : "";
3363
4721
  }
3364
4722
  var endsAre = (spec, link, status) => spec.steps.some((s) => s.status === status && (s.id === link.from || s.id === link.to));
3365
- function runLines(items, first, rest, ctx) {
4723
+ function runLines(items2, first, rest, ctx) {
3366
4724
  const lines = [];
3367
4725
  let line = first;
3368
- items.forEach((item, i) => {
4726
+ items2.forEach((item, i) => {
3369
4727
  const segs = itemSegments(item, ctx);
3370
4728
  const mark = item.via ? linkMark(item.via, ctx) : "";
3371
4729
  const arrow = { text: `${mark}\u2192 `, paint: mark ? painter(mark === "-" ? "removed" : "planned", ctx) : void 0 };
@@ -3502,10 +4860,10 @@ function diffOf(files) {
3502
4860
  hasFile: (p) => set.has(p)
3503
4861
  };
3504
4862
  }
3505
- var repoPath = (root, path3) => relative3(root, resolve5(root, path3)).split(sep3).join("/");
4863
+ var repoPath = (root, path3) => relative3(root, resolve8(root, path3)).split(sep4).join("/");
3506
4864
  var mustExist = (spec, node) => spec.kind === "plan" ? node.status !== "new" : node.status !== "removed";
3507
4865
  var IN_DIFF = /* @__PURE__ */ new Set(["new", "changed", "removed"]);
3508
- var inDiff = (c, path3, diff) => diff.has(repoPath(c.root, path3)) || c.cwd !== void 0 && diff.has(repoPath(c.root, resolve5(c.cwd, path3)));
4866
+ var inDiff = (c, path3, diff) => diff.has(repoPath(c.root, path3)) || c.cwd !== void 0 && diff.has(repoPath(c.root, resolve8(c.cwd, path3)));
3509
4867
  function checkNode(c, spec, node, diff) {
3510
4868
  const needed = mustExist(spec, node);
3511
4869
  const where = locate(c, node.path);
@@ -3540,194 +4898,38 @@ function checkMapNodes(spec, root, opts = {}) {
3540
4898
  if (match) result.matches.set(node.id, match);
3541
4899
  if (problem) result.mismatches.push({ id: node.id, label: plainLabel(node), ...problem });
3542
4900
  }
3543
- if (opts.diff && spec.kind === "summary") {
3544
- const uncovered = uncoveredFiles(c, spec, opts.diff, result.found, opts.ignored);
3545
- if (uncovered.length) result.uncovered = uncovered;
3546
- }
3547
- return result;
3548
- }
3549
- var nodeRepoPaths = (c, path3) => c.cwd === void 0 ? [repoPath(c.root, path3)] : [repoPath(c.root, path3), repoPath(c.root, resolve5(c.cwd, path3))];
3550
- var under = (file, dir) => dir === "" || file === dir || file.startsWith(`${dir}/`);
3551
- var baseName = (p) => p.slice(p.lastIndexOf("/") + 1);
3552
- function covered(c, file, paths) {
3553
- if (paths.some((p) => under(file, p))) return true;
3554
- if (!paths.some((p) => baseName(p) === baseName(file))) return false;
3555
- const where = locate(c, file);
3556
- return "found" in where && !where.found;
3557
- }
3558
- function uncoveredFiles(c, spec, diff, found, ignored = () => false) {
3559
- const paths = spec.nodes.flatMap((n) => n.path === void 0 ? [] : found.has(n.id) ? [found.get(n.id)] : nodeRepoPaths(c, n.path));
3560
- const omitted = spec.omitted ?? [];
3561
- return diff.files.filter((f) => !ignored(f) && !omitted.some((o) => explains(o, f)) && !covered(c, f, paths));
3562
- }
3563
- function checkFlowDiff(spec, snippets, checked, root, diff) {
3564
- const mismatches = [];
3565
- if (diff && spec.kind === "summary") {
3566
- for (const step of spec.steps) {
3567
- const snippet = snippets.steps.get(step.id);
3568
- if (!snippet || step.status !== "new" && step.status !== "changed") continue;
3569
- const path3 = snippet.source.replace(/:\d+(-\d+)?$/, "");
3570
- if (diff.has(repoPath(root, path3))) continue;
3571
- mismatches.push({ id: step.id, label: stepLabel(step), short: "not in diff", detail: `marked ${step.status}, but ${path3} isn't in the diff` });
3572
- }
3573
- }
3574
- return { checked, mismatches, unit: "anchor" };
3575
- }
3576
-
3577
- // src/render/output-path.ts
3578
- import { createHash as createHash2 } from "crypto";
3579
- import { basename, join as join6 } from "path";
3580
- var HTML_NAME = /^(\d{8}-\d{6})-([a-z0-9-]+(?:\.flow)?)\.html$/;
3581
- var pad = (n) => String(n).padStart(2, "0");
3582
- function stamp(d) {
3583
- return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
3584
- }
3585
- function parseStamp(s) {
3586
- const n = (from, to) => Number(s.slice(from, to));
3587
- return new Date(n(0, 4), n(4, 6) - 1, n(6, 8), n(9, 11), n(11, 13), n(13, 15));
3588
- }
3589
- function slugify(title) {
3590
- const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "");
3591
- return slug || "map";
3592
- }
3593
- var fileSlug = (title, diagram) => diagram === "flow" ? `${slugify(title)}.flow` : slugify(title);
3594
- function htmlOutputPath(config, repo, slug, now) {
3595
- return join6(config.web.outDir, repo, `${stamp(now)}-${slug}.html`);
3596
- }
3597
- function repoFolder(root) {
3598
- return `${basename(root)}-${createHash2("sha256").update(root).digest("hex").slice(0, 8)}`;
3599
- }
3600
-
3601
- // src/render/web/write.ts
3602
- import { chmodSync, lstatSync as lstatSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
3603
- import { basename as basename2, dirname as dirname4 } from "path";
3604
-
3605
- // src/render/prune.ts
3606
- import { lstatSync as lstatSync4, readdirSync as readdirSync2, rmSync } from "fs";
3607
- import { join as join7 } from "path";
3608
- var DAY_MS = 864e5;
3609
- function pruneHtml(dir, opts) {
3610
- let names;
3611
- try {
3612
- if (lstatSync4(dir).isSymbolicLink()) return [];
3613
- names = readdirSync2(dir);
3614
- } catch {
3615
- return [];
3616
- }
3617
- const current = stamp(opts.now);
3618
- const files = names.map((name) => ({ name, m: HTML_NAME.exec(name) })).filter((f) => f.m !== null).map(({ name, m }) => ({ name, stamp: m[1], slug: m[2] })).sort((a, b) => b.stamp.localeCompare(a.stamp));
3619
- const doomed = /* @__PURE__ */ new Set();
3620
- for (const f of files) if (f.slug === opts.replaceSlug && f.stamp < current) doomed.add(f.name);
3621
- const cutoff = opts.now.getTime() - opts.maxAgeDays * DAY_MS;
3622
- files.filter((f) => !doomed.has(f.name)).forEach((f, i) => {
3623
- if (f.stamp !== current && i >= opts.keep && parseStamp(f.stamp).getTime() < cutoff) doomed.add(f.name);
3624
- });
3625
- const deleted = [];
3626
- for (const name of doomed) {
3627
- const file = join7(dir, name);
3628
- try {
3629
- rmSync(file);
3630
- deleted.push(file);
3631
- } catch {
3632
- }
3633
- }
3634
- return deleted;
3635
- }
3636
-
3637
- // src/render/web/write.ts
3638
- function privateDir(dir) {
3639
- if (lstatSync5(dir, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`${dir}: is a symlink; refusing to write`);
3640
- mkdirSync3(dir, { recursive: true, mode: 448 });
3641
- chmodSync(dir, 448);
3642
- }
3643
- async function writeHtml(build, o) {
3644
- const { config, now } = o;
3645
- const file = htmlOutputPath(config, repoFolder(o.root), o.slug, now);
3646
- const html = await build({ generatedAt: now, repo: basename2(o.root), theme: o.theme, ...o.update && { update: o.update } });
3647
- const dir = dirname4(file);
3648
- privateDir(dir);
3649
- writeFileSync2(file, html, { mode: 384 });
3650
- pruneHtml(dir, { ...config.web, now, replaceSlug: o.slug });
3651
- const mode = config.web.open;
3652
- if (!(o.forceOpen || mode === "always" || mode === "auto" && o.inEditor)) return { file, openFailed: false };
3653
- const failed = o.open(file);
3654
- if (failed) o.stderr(`codechart: could not open the browser (${failed})
3655
- `);
3656
- return { file, openFailed: Boolean(failed) };
3657
- }
3658
-
3659
- // src/update/check.ts
3660
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
3661
- import { join as join8 } from "path";
3662
- var REGISTRY = "https://registry.npmjs.org/codechart/latest";
3663
- var DAY = 24 * 60 * 60 * 1e3;
3664
- var VERSION = /^\d+\.\d+\.\d+$/;
3665
- var currentVersion = () => JSON.parse(readFileSync3(packageFile("package.json"), "utf8")).version;
3666
- function isNewer(a, b) {
3667
- if (!VERSION.test(a) || !VERSION.test(b)) return false;
3668
- const [x, y] = [a, b].map((v) => v.split(".").map(Number));
3669
- for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
3670
- return false;
3671
- }
3672
- async function fetchLatest(fetchFn, timeoutMs) {
3673
- try {
3674
- const res = await fetchFn(REGISTRY, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
3675
- if (!res.ok) return void 0;
3676
- const version = (await res.json()).version;
3677
- return typeof version === "string" && VERSION.test(version) ? version : void 0;
3678
- } catch {
3679
- return void 0;
3680
- }
3681
- }
3682
- var stateFile = (cacheDir) => join8(cacheDir, "update-check.json");
3683
- function readState(cacheDir) {
3684
- try {
3685
- const raw = JSON.parse(readFileSync3(stateFile(cacheDir), "utf8"));
3686
- return typeof raw === "object" && raw !== null ? raw : {};
3687
- } catch {
3688
- return {};
3689
- }
3690
- }
3691
- function writeState(cacheDir, state) {
3692
- try {
3693
- privateDir(cacheDir);
3694
- writeFileSync3(stateFile(cacheDir), JSON.stringify(state), { mode: 384 });
3695
- } catch {
3696
- }
3697
- }
3698
- var skillDirs = (state) => Array.isArray(state.skillDirs) ? state.skillDirs.filter((d) => typeof d === "string") : [];
3699
- function rememberSkillDir(cacheDir, dir) {
3700
- const state = readState(cacheDir);
3701
- const dirs = skillDirs(state);
3702
- if (!dirs.includes(dir)) writeState(cacheDir, { ...state, skillDirs: [...dirs, dir] });
4901
+ if (opts.diff && spec.kind === "summary") {
4902
+ const uncovered = uncoveredFiles(c, spec, opts.diff, result.found, opts.ignored);
4903
+ if (uncovered.length) result.uncovered = uncovered;
4904
+ }
4905
+ return result;
3703
4906
  }
3704
- function knownUpdate(cacheDir, current = currentVersion()) {
3705
- const { latest } = readState(cacheDir);
3706
- return latest && isNewer(latest, current) ? latest : void 0;
4907
+ var nodeRepoPaths = (c, path3) => c.cwd === void 0 ? [repoPath(c.root, path3)] : [repoPath(c.root, path3), repoPath(c.root, resolve8(c.cwd, path3))];
4908
+ var under = (file, dir) => dir === "" || file === dir || file.startsWith(`${dir}/`);
4909
+ var baseName = (p) => p.slice(p.lastIndexOf("/") + 1);
4910
+ function covered(c, file, paths) {
4911
+ if (paths.some((p) => under(file, p))) return true;
4912
+ if (!paths.some((p) => baseName(p) === baseName(file))) return false;
4913
+ const where = locate(c, file);
4914
+ return "found" in where && !where.found;
3707
4915
  }
3708
- function checkAllowed(c, installPath = packageFile("")) {
3709
- const e = c.env;
3710
- return c.enabled && !e.CODECHART_NO_UPDATE_CHECK && !e.NO_UPDATE_NOTIFIER && !e.CI && !/[\\/]_npx[\\/]/.test(installPath);
4916
+ function uncoveredFiles(c, spec, diff, found, ignored = () => false) {
4917
+ const paths = spec.nodes.flatMap((n) => n.path === void 0 ? [] : found.has(n.id) ? [found.get(n.id)] : nodeRepoPaths(c, n.path));
4918
+ const omitted = spec.omitted ?? [];
4919
+ return diff.files.filter((f) => !ignored(f) && !omitted.some((o) => explains(o, f)) && !covered(c, f, paths));
3711
4920
  }
3712
- async function updateNotice(c) {
3713
- if (!checkAllowed(c)) return void 0;
3714
- const state = readState(c.cacheDir);
3715
- let changed = false;
3716
- if (!state.checkedAt || c.now - state.checkedAt >= DAY) {
3717
- changed = true;
3718
- const latest = await fetchLatest(c.fetch, 1e3);
3719
- Object.assign(state, { checkedAt: c.now }, latest ? { latest } : {});
3720
- }
3721
- const current = c.current ?? currentVersion();
3722
- const told = c.terminal ? "toldTerminal" : "toldAgent";
3723
- let line;
3724
- if (state.latest && isNewer(state.latest, current) && c.now - (state[told] ?? 0) >= DAY) {
3725
- state[told] = c.now;
3726
- changed = true;
3727
- line = c.terminal ? `codechart ${state.latest} is available (you have ${current}): run codechart update` : `codechart ${state.latest} is available (you have ${current}). Tell the user once: run \`codechart update\`.`;
4921
+ function checkFlowDiff(spec, snippets, checked, root, diff) {
4922
+ const mismatches = [];
4923
+ if (diff && spec.kind === "summary") {
4924
+ for (const step of spec.steps) {
4925
+ const snippet = snippets.steps.get(step.id);
4926
+ if (!snippet || step.status !== "new" && step.status !== "changed") continue;
4927
+ const path3 = snippet.source.replace(/:\d+(-\d+)?$/, "");
4928
+ if (diff.has(repoPath(root, path3))) continue;
4929
+ mismatches.push({ id: step.id, label: stepLabel(step), short: "not in diff", detail: `marked ${step.status}, but ${path3} isn't in the diff` });
4930
+ }
3728
4931
  }
3729
- if (changed) writeState(c.cacheDir, state);
3730
- return line;
4932
+ return { checked, mismatches, unit: "anchor" };
3731
4933
  }
3732
4934
 
3733
4935
  // src/spec/schema.ts
@@ -3878,19 +5080,19 @@ function specJsonSchema() {
3878
5080
  }
3879
5081
 
3880
5082
  // src/commands/open.ts
3881
- import { spawn, spawnSync } from "child_process";
3882
- import { win32 as win322 } from "path";
5083
+ import { spawn, spawnSync as spawnSync2 } from "child_process";
5084
+ import { win32 as win323 } from "path";
3883
5085
  function openArgv(platform, file, env = process.env) {
3884
5086
  if (platform === "darwin") return ["open", [file]];
3885
5087
  if (platform === "win32") {
3886
- return [win322.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
5088
+ return [win323.join(env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"), ["url.dll,FileProtocolHandler", file]];
3887
5089
  }
3888
5090
  return ["xdg-open", [file]];
3889
5091
  }
3890
5092
  function inCodeEditor(env) {
3891
5093
  return Boolean(env.VSCODE_PID) || env.TERM_PROGRAM === "vscode";
3892
5094
  }
3893
- function openInBrowser(file, { platform = process.platform, run = spawnSync, detach = spawn } = {}) {
5095
+ function openInBrowser(file, { platform = process.platform, run: run2 = spawnSync2, detach = spawn } = {}) {
3894
5096
  const [cmd, args] = openArgv(platform, file);
3895
5097
  try {
3896
5098
  if (platform === "linux") {
@@ -3898,7 +5100,7 @@ function openInBrowser(file, { platform = process.platform, run = spawnSync, det
3898
5100
  }).unref();
3899
5101
  return void 0;
3900
5102
  }
3901
- const r = run(cmd, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 1e4, encoding: "utf8" });
5103
+ const r = run2(cmd, args, { stdio: ["ignore", "ignore", "pipe"], timeout: 1e4, encoding: "utf8" });
3902
5104
  if (r.error?.code === "ETIMEDOUT") return void 0;
3903
5105
  if (r.error) return r.error.message;
3904
5106
  if (r.status === 0) return void 0;
@@ -3943,11 +5145,11 @@ async function renderFlow(spec, anchors, ctx) {
3943
5145
  }
3944
5146
 
3945
5147
  // src/commands/render-map.ts
3946
- import { writeFileSync as writeFileSync4 } from "fs";
5148
+ import { writeFileSync as writeFileSync6 } from "fs";
3947
5149
 
3948
5150
  // src/render/preview.ts
3949
- import { lstatSync as lstatSync6, realpathSync as realpathSync3 } from "fs";
3950
- import { dirname as dirname5, join as join9, resolve as resolve6, sep as sep4 } from "path";
5151
+ import { lstatSync as lstatSync9, realpathSync as realpathSync5 } from "fs";
5152
+ import { dirname as dirname7, join as join19, resolve as resolve9, sep as sep5 } from "path";
3951
5153
  var MAX_HUNKS = 3;
3952
5154
  var MAX_LINES2 = 40;
3953
5155
  var MAX_BYTES3 = 5 * 1024 * 1024;
@@ -3989,7 +5191,7 @@ var TOO_LARGE2 = "diff is too large (over 5 MB)";
3989
5191
  var OVER_BUDGET = "not shown: the diffs pass 25 MB together";
3990
5192
  function untrackedPreview(root, rel, budget, max) {
3991
5193
  let size = 0;
3992
- const text = readRegularFile(join9(root, rel), (st) => st.isFile() && (size = st.size) <= max);
5194
+ const text = readRegularFile(join19(root, rel), (st) => st.isFile() && (size = st.size) <= max);
3993
5195
  if (text === void 0) return { note: size > MAX_BYTES3 ? TOO_LARGE2 : size > max ? OVER_BUDGET : "not a regular file" };
3994
5196
  if (text.includes("\0")) return { note: "binary file" };
3995
5197
  if (PRIVATE_KEY.test(text)) return SECRET;
@@ -4017,17 +5219,17 @@ var looksSecret = (rel) => {
4017
5219
  };
4018
5220
  var insideRoot = (root, path3) => {
4019
5221
  try {
4020
- const dir = realpathSync3(dirname5(path3));
4021
- const top = realpathSync3(root);
4022
- return dir === top || dir.startsWith(top + sep4);
5222
+ const dir = realpathSync5(dirname7(path3));
5223
+ const top = realpathSync5(root);
5224
+ return dir === top || dir.startsWith(top + sep5);
4023
5225
  } catch {
4024
5226
  return false;
4025
5227
  }
4026
5228
  };
4027
5229
  var noPrefetch = () => ({ sizes: /* @__PURE__ */ new Map(), blobs: /* @__PURE__ */ new Map(), diffs: /* @__PURE__ */ new Map(), untracked: /* @__PURE__ */ new Set(), untrackedKnown: /* @__PURE__ */ new Set() });
4028
5230
  var worktreeSize = (root, rel) => {
4029
- const path3 = join9(root, rel);
4030
- return insideRoot(root, path3) ? lstatSync6(path3, { throwIfNoEntry: false })?.size ?? 0 : 0;
5231
+ const path3 = join19(root, rel);
5232
+ return insideRoot(root, path3) ? lstatSync9(path3, { throwIfNoEntry: false })?.size ?? 0 : 0;
4031
5233
  };
4032
5234
  function prefetch(root, range, rels) {
4033
5235
  const pre = noPrefetch();
@@ -4074,16 +5276,16 @@ function sides(root, range, rel, budget, pre) {
4074
5276
  const sizes = keys.every((k) => pre.sizes.has(k)) ? keys.map((k) => pre.sizes.get(k)) : gitBlobSizes(root, keys);
4075
5277
  for (const [i, size] of sizes.entries()) {
4076
5278
  if (size === void 0) continue;
4077
- const note2 = take(size);
4078
- if (note2) return { note: note2 };
5279
+ const note3 = take(size);
5280
+ if (note3) return { note: note3 };
4079
5281
  texts.push(pre.blobs.get(keys[i]) ?? gitBlob(root, range.revs[i], rel));
4080
5282
  }
4081
- const path3 = join9(root, rel);
5283
+ const path3 = join19(root, rel);
4082
5284
  if (!range.worktree || !insideRoot(root, path3)) return texts;
4083
- let note;
5285
+ let note2;
4084
5286
  try {
4085
- const text = readRegularFile(path3, (st) => st.isFile() && !(note = take(st.size)));
4086
- if (note) return { note };
5287
+ const text = readRegularFile(path3, (st) => st.isFile() && !(note2 = take(st.size)));
5288
+ if (note2) return { note: note2 };
4087
5289
  if (text !== void 0) texts.push(text);
4088
5290
  } catch {
4089
5291
  }
@@ -4119,7 +5321,7 @@ function nodePreviews(spec, root, diff, range, found, cwd) {
4119
5321
  for (const node of spec.nodes) {
4120
5322
  if (node.path === void 0 || !IN_DIFF.has(node.status)) continue;
4121
5323
  const at = found.get(node.id);
4122
- const candidates2 = at !== void 0 ? [at] : [repoPath(root, node.path), ...cwd ? [repoPath(root, resolve6(cwd, node.path))] : []];
5324
+ const candidates2 = at !== void 0 ? [at] : [repoPath(root, node.path), ...cwd ? [repoPath(root, resolve9(cwd, node.path))] : []];
4123
5325
  const rel = candidates2.find((p) => diff.hasFile(p));
4124
5326
  if (rel !== void 0) rels.set(node.id, rel);
4125
5327
  }
@@ -4149,7 +5351,7 @@ async function renderMap(spec, ctx) {
4149
5351
  const { root, diff } = ctx;
4150
5352
  const check = { ...checkMapNodes(spec, root, { at: ctx.at, cwd: ctx.cwd, diff, ignored: ctx.unmapped }), ...ctx.diffUnchecked && { diffUnchecked: true } };
4151
5353
  if (ctx.pr) {
4152
- writeFileSync4(ctx.pr.svg, renderSvg(spec, await layoutSpec(spec, DESCRIPTION_CANVASES), check), { mode: 384 });
5354
+ writeFileSync6(ctx.pr.svg, renderSvg(spec, await layoutSpec(spec, DESCRIPTION_CANVASES), check), { mode: 384 });
4153
5355
  return { text: prBlock(spec, check, ctx.pr.imageUrl), check };
4154
5356
  }
4155
5357
  const { hidden } = selectTerminalNodes(spec, ctx.maxNodes);
@@ -4182,7 +5384,7 @@ var InvalidSpec = class extends Error {
4182
5384
  };
4183
5385
  var TOO_BIG = "spec is larger than 2 MB";
4184
5386
  function readSpecFile(file) {
4185
- const fd = openSync3(file, constants3.O_RDONLY | (constants3.O_NONBLOCK ?? 0));
5387
+ const fd = openSync3(file, constants4.O_RDONLY | (constants4.O_NONBLOCK ?? 0));
4186
5388
  try {
4187
5389
  if (!fstatSync3(fd).isFile()) throw new Error("not a regular file");
4188
5390
  const buf = Buffer.alloc(MAX_SPEC_BYTES + 1);
@@ -4204,7 +5406,7 @@ function specOutput(config, ruleNames, diagram) {
4204
5406
  return unionOutputs(outputs);
4205
5407
  }
4206
5408
  async function readSpec(arg, cwd, stdin) {
4207
- const source = arg === "-" ? "stdin" : resolve7(cwd, arg);
5409
+ const source = arg === "-" ? "stdin" : resolve10(cwd, arg);
4208
5410
  let raw;
4209
5411
  try {
4210
5412
  const text = arg === "-" ? await stdin() : readSpecFile(source);
@@ -4242,16 +5444,16 @@ function selectedDiff(o, repoRoot, root) {
4242
5444
  }
4243
5445
  function prTarget(o, cwd, cacheFile) {
4244
5446
  if (!o.pr) return void 0;
4245
- if (o.svg !== void 0) return { svg: resolve7(cwd, o.svg), imageUrl: o.imageUrl ?? basename3(o.svg) };
4246
- privateDir(dirname6(cacheFile));
5447
+ if (o.svg !== void 0) return { svg: resolve10(cwd, o.svg), imageUrl: o.imageUrl ?? basename3(o.svg) };
5448
+ privateDir(dirname8(cacheFile));
4247
5449
  return { svg: cacheFile, imageUrl: o.imageUrl ?? basename3(cacheFile) };
4248
5450
  }
4249
5451
  async function renderSpec(arg, o, opts, cwd) {
4250
5452
  const spec = await readSpec(arg, cwd, opts.stdin ?? (() => readStdin(MAX_SPEC_BYTES, new Error(TOO_BIG))));
4251
5453
  const repoRoot = findRepoRoot(cwd);
4252
- const root = repoRoot ?? resolve7(cwd);
5454
+ const root = repoRoot ?? resolve10(cwd);
4253
5455
  const at = resolveAt(o, repoRoot, root);
4254
- const target = targetOf(spec, root, at, resolve7(cwd), o.pr === true);
5456
+ const target = targetOf(spec, root, at, resolve10(cwd), o.pr === true);
4255
5457
  const diff = selectedDiff(o, repoRoot, root);
4256
5458
  const config = loadConfig({ cwd, home: opts.home, env: opts.env, warn: (l) => opts.stderr(`codechart: ${l}
4257
5459
  `) });
@@ -4273,9 +5475,9 @@ async function renderSpec(arg, o, opts, cwd) {
4273
5475
  width: defaultWidth({ isTTY: opts.isTTY ?? process.stdout.isTTY, columns: process.stdout.columns }, env),
4274
5476
  color: !o.md && (opts.isTTY ?? process.stdout.isTTY === true),
4275
5477
  md: o.md === true,
4276
- pr: prTarget(o, cwd, join10(config.web.outDir, repoFolder(root), `${slug}.svg`)),
5478
+ pr: prTarget(o, cwd, join20(config.web.outDir, repoFolder(root), `${slug}.svg`)),
4277
5479
  root,
4278
- cwd: resolve7(cwd),
5480
+ cwd: resolve10(cwd),
4279
5481
  at,
4280
5482
  diff,
4281
5483
  unmapped: unmappedFiles(config),
@@ -4303,7 +5505,7 @@ async function renderSpec(arg, o, opts, cwd) {
4303
5505
  }
4304
5506
  function renderCommand(opts) {
4305
5507
  const cwd = opts.cwd ?? process.cwd();
4306
- return new Command5("render").description("render a spec as a terminal map and/or a self-contained HTML map").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option("--theme <theme>", "HTML theme").choices(THEMES)).option("--open", "open the HTML file in the browser").option("--md", "print a paste-ready markdown block (no color)").option("--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("--strict", "exit 1 when a claim doesn't match the code").action(async (arg, o, cmd) => {
5508
+ return new Command8("render").description("render a spec as a terminal map and/or a self-contained HTML map").argument("<spec>", "spec JSON file, or '-' for stdin").addOption(new Option("--output <mode>", "override the output mode").choices(["auto", "cli", "web", "both"])).addOption(new Option("--theme <theme>", "HTML theme").choices(THEMES)).option("--open", "open the HTML file in the browser").option("--md", "print a paste-ready markdown block (no color)").option("--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("--strict", "exit 1 when a claim doesn't match the code").action(async (arg, o, cmd) => {
4307
5509
  const usage = renderSelectionError(o) ?? (!o.pr && (o.svg !== void 0 || o.imageUrl !== void 0) ? "--svg and --image-url need --pr" : void 0);
4308
5510
  if (usage) cmd.error(usage, { exitCode: 2 });
4309
5511
  try {
@@ -4321,8 +5523,8 @@ function renderCommand(opts) {
4321
5523
  // src/commands/pr-sync.ts
4322
5524
  var NOT_DRAWN = "no map drawn";
4323
5525
  async function render(spec, review, placeholder, opts, cwd) {
4324
- const dir = mkdtempSync(join11(tmpdir(), "codechart-pr-"));
4325
- const file = join11(dir, "map.svg");
5526
+ const dir = mkdtempSync(join21(tmpdir(), "codechart-pr-"));
5527
+ const file = join21(dir, "map.svg");
4326
5528
  let block = "";
4327
5529
  let errors = "";
4328
5530
  try {
@@ -4330,7 +5532,7 @@ async function render(spec, review, placeholder, opts, cwd) {
4330
5532
  await cmd.parseAsync(["-", "--since", review.base, "--head", review.head, "--at", review.head, "--pr", "--svg", file, "--image-url", placeholder], { from: "user" });
4331
5533
  if (!block && errors.includes(NOT_DRAWN)) return void 0;
4332
5534
  if (!block) throw new Error(errors.trim() || "render printed nothing");
4333
- return { block, svg: readFileSync4(file, "utf8") };
5535
+ return { block, svg: readFileSync6(file, "utf8") };
4334
5536
  } finally {
4335
5537
  rmSync2(dir, { recursive: true, force: true });
4336
5538
  }
@@ -4360,226 +5562,11 @@ async function syncReview(opts, cwd, deps = {}) {
4360
5562
  await review.setBody(replaceSection((await review.current()).body, block));
4361
5563
  say(`updated the map in ${review.name}`);
4362
5564
  }
4363
- function prSyncCommand(opts) {
4364
- const cwd = opts.cwd ?? process.cwd();
4365
- return new Command6("pr-sync").description("CI: re-render the map in this PR or MR's description against its latest commits").action(async () => {
4366
- try {
4367
- await syncReview(opts, cwd);
4368
- } catch (e) {
4369
- opts.stderr(`codechart: ${e instanceof Error ? e.message : String(e)}
4370
- `);
4371
- process.exitCode = 1;
4372
- }
4373
- });
4374
- }
4375
-
4376
- // src/commands/setup-pr-maps.ts
4377
- import { execFileSync as execFileSync3 } from "child_process";
4378
- import { closeSync as closeSync4, constants as constants4, lstatSync as lstatSync7, mkdirSync as mkdirSync4, openSync as openSync4, writeFileSync as writeFileSync5 } from "fs";
4379
- import { dirname as dirname7, join as join13 } from "path";
4380
- import { createInterface } from "readline/promises";
4381
- import { Command as Command7, Option as Option2 } from "commander";
4382
-
4383
- // src/pr/setup.ts
4384
- import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync5, rmSync as rmSync3 } from "fs";
4385
- import { tmpdir as tmpdir2 } from "os";
4386
- import { join as join12 } from "path";
4387
- var PATTERNS = [/^[\w.-]+@([^:/]+):(.+?)(?:\.git)?\/?$/, /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?\/?$/];
4388
- function parseRemote(url, host) {
4389
- for (const re of PATTERNS) {
4390
- const m = re.exec(url.trim());
4391
- if (!m) continue;
4392
- const server = m[1].toLowerCase();
4393
- const found = host ?? (server.includes("github") ? "github" : server.includes("gitlab") ? "gitlab" : void 0);
4394
- return found ? { host: found, server, path: m[2] } : void 0;
4395
- }
4396
- return void 0;
4397
- }
4398
- function pinnedTemplate(host, version) {
4399
- const file = host === "github" ? "templates/github-workflow.yml" : "templates/gitlab-ci.yml";
4400
- return readFileSync5(packageFile(file), "utf8").replace("codechart@latest", `codechart@${version}`);
4401
- }
4402
- var GITHUB_NOTES = [
4403
- "Runs on every push to a pull request that has a codechart map section in its description; others are left alone.",
4404
- "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.",
4405
- "Pull requests from forks are skipped: their token is read-only."
4406
- ];
4407
- function gitlabNotes(r) {
4408
- const base = `https://${r.server}`;
4409
- return [
4410
- "Runs in merge request pipelines whose description has a codechart map section; others are left alone.",
4411
- "Needs one masked CI/CD variable, CODECHART_GITLAB_TOKEN (GitLab\u2019s job token can\u2019t edit merge requests or upload files):",
4412
- ` 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`,
4413
- ` 2. Add it under Settings > CI/CD > Variables, masked: ${base}/${r.path}/-/settings/ci_cd`,
4414
- "Until the variable exists the job is skipped."
4415
- ];
4416
- }
4417
- function buildPlan(remote, version, read2) {
4418
- const added = pinnedTemplate(remote.host, version);
4419
- if (remote.host === "github") {
4420
- const file2 = ".github/workflows/codechart.yml";
4421
- const existing2 = read2(file2);
4422
- if (existing2 !== void 0) return existing2.includes("pr-sync") ? void 0 : conflict(file2);
4423
- return { remote, file: file2, content: added, added, appended: false, notes: GITHUB_NOTES };
4424
- }
4425
- const file = ".gitlab-ci.yml";
4426
- const existing = read2(file);
4427
- if (existing?.includes("pr-sync")) return void 0;
4428
- if (existing !== void 0 && /^codechart-map:/m.test(existing)) conflict(file);
4429
- const content = existing === void 0 ? added : `${existing.replace(/\n*$/, "\n")}
4430
- ${added}`;
4431
- return { remote, file, content, added, appended: existing !== void 0, notes: gitlabNotes(remote) };
4432
- }
4433
- function conflict(file) {
4434
- 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`);
4435
- }
4436
- var SETUP_BRANCH = "codechart/pr-maps";
4437
- var PR_TITLE = "Set up codechart PR maps";
4438
- var prBody = (plan) => [
4439
- `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\`.`,
4440
- "",
4441
- "**Merge to turn PR maps on; close to say no.** Nothing runs until this is merged.",
4442
- "",
4443
- ...plan.notes.map((n) => n.startsWith(" ") ? n : `- ${n}`)
4444
- ].join("\n");
4445
- function prepareSetupReview(root, version, remote) {
4446
- const defaultBranch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(gitRun(root, ["ls-remote", "--symref", "origin", "HEAD"]))?.[1];
4447
- if (!defaultBranch) throw new Error("couldn't find origin's default branch");
4448
- gitRun(root, ["fetch", "--quiet", "origin", `refs/heads/${defaultBranch}`]);
4449
- const base = gitRun(root, ["rev-parse", "FETCH_HEAD"]);
4450
- const plan = buildPlan(remote, version, (file) => {
4451
- try {
4452
- return gitRun(root, ["show", `${base}:${file}`]) + "\n";
4453
- } catch {
4454
- return void 0;
4455
- }
4456
- });
4457
- return { defaultBranch, base, plan };
4458
- }
4459
- function openSetupReview(root, { defaultBranch, base, plan }, tool) {
4460
- const dir = mkdtempSync2(join12(tmpdir2(), "codechart-setup-"));
4461
- try {
4462
- const env = { ...process.env, GIT_INDEX_FILE: join12(dir, "index") };
4463
- gitRun(root, ["read-tree", base], void 0, env);
4464
- const blob = gitRun(root, ["hash-object", "-w", "--stdin"], plan.content);
4465
- gitRun(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${plan.file}`], void 0, env);
4466
- const tree = gitRun(root, ["write-tree"], void 0, env);
4467
- const commit = gitRun(root, ["commit-tree", tree, "-p", base, "-m", PR_TITLE]);
4468
- gitRun(root, ["push", "origin", `${commit}:refs/heads/${SETUP_BRANCH}`]);
4469
- } finally {
4470
- rmSync3(dir, { recursive: true, force: true });
4471
- }
4472
- 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"]);
4473
- return out.trim().split("\n").pop() ?? "";
4474
- }
4475
-
4476
- // src/commands/setup-pr-maps.ts
4477
- function remoteOf(root, host) {
4478
- let url;
4479
- try {
4480
- url = gitRun(root, ["config", "--get", "remote.origin.url"]);
4481
- } catch {
4482
- throw new Error("no origin remote: PR maps need the repo on GitHub or GitLab");
4483
- }
4484
- const remote = parseRemote(url, host);
4485
- if (!remote) throw new Error(`can't tell whether ${url} is GitHub or GitLab; add --host github or --host gitlab`);
4486
- return remote;
4487
- }
4488
- function readWorkTree(root) {
4489
- return (file) => {
4490
- const path3 = join13(root, file);
4491
- let text;
4492
- try {
4493
- text = readRegularFile(path3, (st) => st.isFile() && lstatSync7(path3).isFile());
4494
- } catch (e) {
4495
- const code = e.code;
4496
- if (code === "ENOENT") return void 0;
4497
- if (code !== "ELOOP") throw e;
4498
- }
4499
- if (text === void 0) throw new Error(`${file}: not a regular file; refusing to write it`);
4500
- return text;
4501
- };
4502
- }
4503
- function writeWorkTree(root, plan) {
4504
- const path3 = join13(root, plan.file);
4505
- mkdirSync4(dirname7(path3), { recursive: true });
4506
- const flags = constants4.O_WRONLY | constants4.O_CREAT | constants4.O_TRUNC | (constants4.O_NOFOLLOW ?? 0) | (plan.appended ? 0 : constants4.O_EXCL);
4507
- let fd;
4508
- try {
4509
- fd = openSync4(path3, flags, 420);
4510
- } catch (e) {
4511
- const code = e.code;
4512
- if (code === "EEXIST" || code === "ELOOP") throw new Error(`${plan.file}: changed while codechart was running; run it again`);
4513
- throw e;
4514
- }
4515
- try {
4516
- writeFileSync5(fd, plan.content);
4517
- } finally {
4518
- closeSync4(fd);
4519
- }
4520
- }
4521
- function describe(plan, pr) {
4522
- const what = plan.appended ? `append this job to ${plan.file}` : `add ${plan.file}`;
4523
- const where = pr ? `open a ${plan.remote.host === "github" ? "pull" : "merge"} request on ${plan.remote.path} that would ${what}` : `${what} in your work tree (not committed)`;
4524
- const body = plan.added.trimEnd().split("\n").map((l) => ` ${l}`);
4525
- return [`codechart setup-pr-maps would ${where}:`, "", ...body, "", ...plan.notes, ""].join("\n") + "\n";
4526
- }
4527
- async function terminalConfirm(question) {
4528
- const rl = createInterface({ input: process.stdin, output: process.stdout });
4529
- try {
4530
- return /^y(es)?$/i.test((await rl.question(question)).trim());
4531
- } finally {
4532
- rl.close();
4533
- }
4534
- }
4535
- var defaultTool = (command, args) => {
4536
- try {
4537
- return execFileSync3(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 12e4 });
4538
- } catch (e) {
4539
- if (e.code === "ENOENT") throw new Error(`${command} is not installed; install it or run without --pr`);
4540
- throw new Error(`${command} failed: ${String(e.stderr ?? e.message).trim()}`);
4541
- }
4542
- };
4543
- async function agreed(o, opts) {
4544
- if (o.yes) return true;
4545
- const confirm = opts.confirm ?? (process.stdin.isTTY && process.stdout.isTTY ? terminalConfirm : void 0);
4546
- if (confirm) return confirm(o.pr ? "Open it? [y/N] " : "Write it? [y/N] ");
4547
- opts.stdout(`Nothing changed. To go ahead, run again with --yes${o.pr ? " --pr" : " (or --yes --pr to open a pull request instead)"}.
4548
- `);
4549
- return false;
4550
- }
4551
- async function setup(o, opts, root) {
4552
- const remote = remoteOf(root, o.host);
4553
- const v = currentVersion();
4554
- const done = () => opts.stdout(`codechart: PR maps are already set up in ${remote.path}.
4555
- `);
4556
- if (o.pr) {
4557
- const prepared = prepareSetupReview(root, v, remote);
4558
- if (!prepared.plan) return done();
4559
- opts.stdout(describe(prepared.plan, true));
4560
- if (!await agreed(o, opts)) return;
4561
- const url = openSetupReview(root, { ...prepared, plan: prepared.plan }, opts.tool ?? defaultTool);
4562
- opts.stdout(`codechart: opened ${url}
4563
- Merge it to turn PR maps on; close it to say no.
4564
- `);
4565
- return;
4566
- }
4567
- const plan = buildPlan(remote, v, readWorkTree(root));
4568
- if (!plan) return done();
4569
- opts.stdout(describe(plan, false));
4570
- if (!await agreed(o, opts)) return;
4571
- writeWorkTree(root, plan);
4572
- const next = remote.host === "gitlab" ? ", then add the CODECHART_GITLAB_TOKEN variable as above" : "";
4573
- opts.stdout(`codechart: wrote ${plan.file}. Review it, commit and push it${next}.
4574
- `);
4575
- }
4576
- function setupPrMapsCommand(opts) {
5565
+ function prSyncCommand(opts) {
4577
5566
  const cwd = opts.cwd ?? process.cwd();
4578
- return new Command7("setup-pr-maps").description("add the CI job that keeps codechart maps in PR/MR descriptions current; shows the change and asks first").option("--yes", "don't ask: needed when not run from a terminal").option("--pr", "open a pull or merge request with the change (needs gh or glab) instead of writing it to the work tree").addOption(new Option2("--host <host>", "when the origin URL names neither").choices(["github", "gitlab"])).action(async (o) => {
5567
+ return new Command9("pr-sync").description("CI: re-render the map in this PR or MR's description against its latest commits").action(async () => {
4579
5568
  try {
4580
- const root = findRepoRoot(cwd);
4581
- if (!root) throw new Error("not a git repository");
4582
- await setup(o, opts, root);
5569
+ await syncReview(opts, cwd);
4583
5570
  } catch (e) {
4584
5571
  opts.stderr(`codechart: ${e instanceof Error ? e.message : String(e)}
4585
5572
  `);
@@ -4588,480 +5575,213 @@ function setupPrMapsCommand(opts) {
4588
5575
  });
4589
5576
  }
4590
5577
 
4591
- // src/commands/update.ts
4592
- import { execFileSync as execFileSync4, spawnSync as spawnSync2 } from "child_process";
4593
- import { existsSync as existsSync6, readdirSync as readdirSync4, realpathSync as realpathSync5 } from "fs";
4594
- import { homedir as homedir4 } from "os";
4595
- import { dirname as dirname9, join as join16, resolve as resolve9, sep as sep5 } from "path";
4596
- import { Command as Command9 } from "commander";
4597
-
4598
- // src/commands/agents.ts
4599
- import { lstatSync as lstatSync8 } from "fs";
4600
- import { join as join14 } from "path";
4601
- var SHARED = ".agents/skills";
4602
- var AGENTS = [
4603
- { name: "claude", label: "Claude Code", home: ".claude", skills: ".claude/skills", reads: [], instructions: ".claude/CLAUDE.md" },
4604
- { name: "codex", label: "Codex", home: ".codex", skills: SHARED, reads: [], instructions: ".codex/AGENTS.md" },
4605
- { name: "gemini", label: "Gemini CLI", home: ".gemini", skills: ".gemini/skills", reads: [SHARED], instructions: ".gemini/GEMINI.md" },
4606
- { name: "copilot", label: "GitHub Copilot", home: ".copilot", skills: ".copilot/skills", reads: [SHARED] },
4607
- { name: "cursor", label: "Cursor", home: ".cursor", skills: ".cursor/skills", reads: [SHARED, ".claude/skills", ".codex/skills"] },
4608
- { name: "opencode", label: "OpenCode", home: ".config/opencode", skills: ".config/opencode/skills", reads: [SHARED, ".claude/skills"], instructions: ".config/opencode/AGENTS.md" },
4609
- { name: "goose", label: "Goose", home: ".config/goose", skills: SHARED, reads: [".claude/skills"] },
4610
- { name: "amp", label: "Amp", home: ".config/amp", skills: ".config/agents/skills", reads: [".claude/skills"] },
4611
- { name: "windsurf", label: "Windsurf", home: ".codeium/windsurf", skills: ".codeium/windsurf/skills", reads: [SHARED] },
4612
- { name: "cline", label: "Cline", home: ".cline", skills: ".cline/skills", reads: [] },
4613
- { name: "roo", label: "Roo Code", home: ".roo", skills: ".roo/skills", reads: [SHARED] },
4614
- { name: "kiro", label: "Kiro", home: ".kiro", skills: ".kiro/skills", reads: [] },
4615
- { name: "junie", label: "Junie", home: ".junie", skills: ".junie/skills", reads: [] },
4616
- { name: "droid", label: "Factory Droid", home: ".factory", skills: ".factory/skills", reads: [] }
4617
- ];
4618
- function skillFolders(agents) {
4619
- const groups = [];
4620
- for (const a of agents) {
4621
- const shared = groups.find((g) => [a.skills, ...a.reads].includes(g.folder));
4622
- if (shared) shared.agents.push(a);
4623
- else groups.push({ folder: a.skills, agents: [a] });
4624
- }
4625
- return groups;
4626
- }
4627
- function isCodechartSkill(dir) {
4628
- const skill = join14(dir, "SKILL.md");
4629
- const text = lstatSync8(skill, { throwIfNoEntry: false })?.isFile() ? readRegularFile(skill, (s) => s.isFile()) : void 0;
4630
- return text !== void 0 && /^---\r?\n(?:.*\r?\n)*?name: codechart\r?\n/.test(text);
4631
- }
4632
-
4633
- // src/commands/install-skill.ts
4634
- import { existsSync as existsSync5, lstatSync as lstatSync9, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "fs";
4635
- import { homedir as homedir3 } from "os";
4636
- import { join as join15, resolve as resolve8 } from "path";
4637
- import { Command as Command8 } from "commander";
5578
+ // src/commands/setup-pr-maps.ts
5579
+ import { execFileSync as execFileSync5 } from "child_process";
5580
+ import { closeSync as closeSync4, constants as constants5, lstatSync as lstatSync10, mkdirSync as mkdirSync6, openSync as openSync4, writeFileSync as writeFileSync7 } from "fs";
5581
+ import { dirname as dirname9, join as join23 } from "path";
5582
+ import { createInterface } from "readline/promises";
5583
+ import { Command as Command10, Option as Option2 } from "commander";
4638
5584
 
4639
- // src/commands/nudges.ts
4640
- import { mkdirSync as mkdirSync5, realpathSync as realpathSync4, writeFileSync as writeFileSync6 } from "fs";
4641
- import { dirname as dirname8 } from "path";
4642
- var REMINDER = "Before summarizing or planning a change that touches 3+ files or adds behaviour with branches, use the codechart skill (skip it for small edits: typos, formatting, one-line fixes).";
4643
- var START = "<!-- codechart -->";
4644
- var END = "<!-- /codechart -->";
4645
- var BLOCK = `${START}
4646
- ${REMINDER}
4647
- ${END}`;
4648
- function readRegular(file) {
4649
- let path3;
4650
- try {
4651
- path3 = realpathSync4(file);
4652
- } catch (e) {
4653
- if (e.code === "ENOENT") return { path: file };
4654
- throw e;
4655
- }
4656
- const text = readRegularFile(path3, (st) => st.isFile());
4657
- if (text === void 0) throw new Error(`${file}: not a regular file`);
4658
- return { path: path3, text };
4659
- }
4660
- function blockAt(text) {
4661
- const at = text.indexOf(START);
4662
- const end = at < 0 ? -1 : text.indexOf(END, at);
4663
- return end > at ? [at, end + END.length] : void 0;
4664
- }
4665
- function refreshReminder(file) {
4666
- let text;
4667
- try {
4668
- text = readRegular(file).text;
4669
- } catch {
4670
- return "absent";
4671
- }
4672
- return text !== void 0 && blockAt(text) ? addReminder(file) === "updated" ? "updated" : "present" : "absent";
4673
- }
4674
- function addReminder(file) {
4675
- const { path: path3, text = "" } = readRegular(file);
4676
- const block = blockAt(text);
4677
- if (block) {
4678
- if (text.slice(...block) === BLOCK) return "present";
4679
- writeFileSync6(path3, text.slice(0, block[0]) + BLOCK + text.slice(block[1]));
4680
- return "updated";
5585
+ // src/pr/setup.ts
5586
+ import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync7, rmSync as rmSync3 } from "fs";
5587
+ import { tmpdir as tmpdir2 } from "os";
5588
+ import { join as join22 } from "path";
5589
+ var PATTERNS = [/^[\w.-]+@([^:/]+):(.+?)(?:\.git)?\/?$/, /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+?)(?:\.git)?\/?$/];
5590
+ function parseRemote(url, host) {
5591
+ for (const re of PATTERNS) {
5592
+ const m = re.exec(url.trim());
5593
+ if (!m) continue;
5594
+ const server = m[1].toLowerCase();
5595
+ const found = host ?? (server.includes("github") ? "github" : server.includes("gitlab") ? "gitlab" : void 0);
5596
+ return found ? { host: found, server, path: m[2] } : void 0;
4681
5597
  }
4682
- mkdirSync5(dirname8(path3), { recursive: true });
4683
- const gap = text === "" || text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
4684
- writeFileSync6(path3, `${text}${gap}${BLOCK}
4685
- `);
4686
- return "added";
5598
+ return void 0;
4687
5599
  }
4688
- function removeReminder(file) {
4689
- const { path: path3, text } = readRegular(file);
4690
- const block = text === void 0 ? void 0 : blockAt(text);
4691
- if (!text || !block) return "absent";
4692
- const before = text.slice(0, block[0]).replace(/\n\n$/, "\n");
4693
- const after = text.slice(block[1]).replace(/^\n/, "");
4694
- writeFileSync6(path3, before + after);
4695
- return "removed";
5600
+ function pinnedTemplate(host, version) {
5601
+ const file = host === "github" ? "templates/github-workflow.yml" : "templates/gitlab-ci.yml";
5602
+ return readFileSync7(packageFile(file), "utf8").replace("codechart@latest", `codechart@${version}`);
4696
5603
  }
4697
- var HOOK_COMMANDS = { UserPromptSubmit: "codechart hook prompt", Stop: "codechart hook stop" };
4698
- var TIMEOUTS = { UserPromptSubmit: 10, Stop: 30 };
4699
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4700
- var isCodechartHook = (h) => isObject(h) && typeof h.command === "string" && h.command.startsWith("codechart hook ");
4701
- function readSettings(file) {
4702
- const { path: path3, text } = readRegular(file);
4703
- let settings;
4704
- try {
4705
- settings = text === void 0 || text.trim() === "" ? {} : JSON.parse(text);
4706
- } catch {
4707
- throw new Error(`${file}: not valid JSON; edit the hooks by hand: https://github.com/freeleex/codechart/blob/main/docs/install.md#help-agents-remember-it`);
4708
- }
4709
- if (!isObject(settings)) throw new Error(`${file}: not a JSON object`);
4710
- settings.hooks ??= {};
4711
- if (!isObject(settings.hooks)) throw new Error(`${file}: "hooks" is not an object`);
4712
- return { path: path3, settings };
5604
+ var GITHUB_NOTES = [
5605
+ "Runs on every push to a pull request that has a codechart map section in its description; others are left alone.",
5606
+ "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.",
5607
+ "Pull requests from forks are skipped: their token is read-only."
5608
+ ];
5609
+ function gitlabNotes(r) {
5610
+ const base = `https://${r.server}`;
5611
+ return [
5612
+ "Runs in merge request pipelines whose description has a codechart map section; others are left alone.",
5613
+ "Needs one masked CI/CD variable, CODECHART_GITLAB_TOKEN (GitLab\u2019s job token can\u2019t edit merge requests or upload files):",
5614
+ ` 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`,
5615
+ ` 2. Add it under Settings > CI/CD > Variables, masked: ${base}/${r.path}/-/settings/ci_cd`,
5616
+ "Until the variable exists the job is skipped."
5617
+ ];
4713
5618
  }
4714
- function installClaudeHooks(file) {
4715
- const { path: path3, settings } = readSettings(file);
4716
- let added = false;
4717
- for (const [event, command] of Object.entries(HOOK_COMMANDS)) {
4718
- const groups = settings.hooks[event] ??= [];
4719
- if (!Array.isArray(groups)) throw new Error(`${file}: "hooks.${event}" is not a list`);
4720
- if (groups.some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isCodechartHook))) continue;
4721
- groups.push({ hooks: [{ type: "command", command, timeout: TIMEOUTS[event] }] });
4722
- added = true;
5619
+ function buildPlan(remote, version, read2) {
5620
+ const added = pinnedTemplate(remote.host, version);
5621
+ if (remote.host === "github") {
5622
+ const file2 = ".github/workflows/codechart.yml";
5623
+ const existing2 = read2(file2);
5624
+ if (existing2 !== void 0) return existing2.includes("pr-sync") ? void 0 : conflict(file2);
5625
+ return { remote, file: file2, content: added, added, appended: false, notes: GITHUB_NOTES };
4723
5626
  }
4724
- if (!added) return "present";
4725
- mkdirSync5(dirname8(path3), { recursive: true });
4726
- writeFileSync6(path3, `${JSON.stringify(settings, null, 2)}
4727
- `);
4728
- return "added";
5627
+ const file = ".gitlab-ci.yml";
5628
+ const existing = read2(file);
5629
+ if (existing?.includes("pr-sync")) return void 0;
5630
+ if (existing !== void 0 && /^codechart-map:/m.test(existing)) conflict(file);
5631
+ const content = existing === void 0 ? added : `${existing.replace(/\n*$/, "\n")}
5632
+ ${added}`;
5633
+ return { remote, file, content, added, appended: existing !== void 0, notes: gitlabNotes(remote) };
4729
5634
  }
4730
- function removeClaudeHooks(file) {
4731
- const { path: path3, settings } = readSettings(file);
4732
- let removed = false;
4733
- for (const [event, groups] of Object.entries(settings.hooks)) {
4734
- if (!Array.isArray(groups)) continue;
4735
- const kept = groups.flatMap((g) => {
4736
- if (!isObject(g) || !Array.isArray(g.hooks) || !g.hooks.some(isCodechartHook)) return [g];
4737
- removed = true;
4738
- const hooks2 = g.hooks.filter((h) => !isCodechartHook(h));
4739
- return hooks2.length ? [{ ...g, hooks: hooks2 }] : [];
4740
- });
4741
- if (kept.length) settings.hooks[event] = kept;
4742
- else delete settings.hooks[event];
4743
- }
4744
- if (!removed) return "absent";
4745
- const { hooks, ...rest } = settings;
4746
- writeFileSync6(path3, `${JSON.stringify(Object.keys(hooks).length ? settings : rest, null, 2)}
4747
- `);
4748
- return "removed";
5635
+ function conflict(file) {
5636
+ 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`);
4749
5637
  }
4750
-
4751
- // src/commands/picker.ts
4752
- import { emitKeypressEvents } from "readline";
4753
- function pickerStep(s, key) {
4754
- const n = s.checked.length;
4755
- switch (key.ctrl ? `ctrl-${key.name}` : key.name ?? key.sequence) {
4756
- case "up":
4757
- case "k":
4758
- return { ...s, cursor: (s.cursor + n - 1) % n };
4759
- case "down":
4760
- case "j":
4761
- return { ...s, cursor: (s.cursor + 1) % n };
4762
- case "space":
4763
- return { ...s, checked: s.checked.map((c, i) => i === s.cursor ? !c : c) };
4764
- case "a": {
4765
- const all = s.checked.every(Boolean);
4766
- return { ...s, checked: s.checked.map(() => !all) };
5638
+ var SETUP_BRANCH = "codechart/pr-maps";
5639
+ var PR_TITLE = "Set up codechart PR maps";
5640
+ var prBody = (plan) => [
5641
+ `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\`.`,
5642
+ "",
5643
+ "**Merge to turn PR maps on; close to say no.** Nothing runs until this is merged.",
5644
+ "",
5645
+ ...plan.notes.map((n) => n.startsWith(" ") ? n : `- ${n}`)
5646
+ ].join("\n");
5647
+ function prepareSetupReview(root, version, remote) {
5648
+ const defaultBranch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(gitRun(root, ["ls-remote", "--symref", "origin", "HEAD"]))?.[1];
5649
+ if (!defaultBranch) throw new Error("couldn't find origin's default branch");
5650
+ gitRun(root, ["fetch", "--quiet", "origin", `refs/heads/${defaultBranch}`]);
5651
+ const base = gitRun(root, ["rev-parse", "FETCH_HEAD"]);
5652
+ const plan = buildPlan(remote, version, (file) => {
5653
+ try {
5654
+ return gitRun(root, ["show", `${base}:${file}`]) + "\n";
5655
+ } catch {
5656
+ return void 0;
4767
5657
  }
4768
- case "return":
4769
- return { ...s, done: "ok" };
4770
- case "escape":
4771
- case "ctrl-c":
4772
- return { ...s, done: "cancel" };
4773
- default:
4774
- return s;
4775
- }
4776
- }
4777
- var cut = (text, max) => text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}\u2026`;
4778
- var dim = (text) => text ? `\x1B[2m${text}\x1B[0m` : "";
4779
- function pickerLines(title, items, s, width = Infinity) {
4780
- const pad2 = Math.max(...items.map((i) => i.label.length));
4781
- return [
4782
- cut(title, width),
4783
- ...items.map((it, i) => {
4784
- const head = cut(`${i === s.cursor ? "\u276F" : " "} ${s.checked[i] ? "\u25C9" : "\u25EF"} ${it.label.padEnd(pad2)} `, width);
4785
- return head + dim(cut(it.hint, width - head.length));
4786
- }),
4787
- dim(cut("\u2191/\u2193 move \xB7 Space toggle \xB7 a all \xB7 Enter confirm \xB7 Esc cancel", width))
4788
- ];
4789
- }
4790
- function terminalPicker(title, items, checked = true) {
4791
- const { stdin, stdout } = process;
4792
- let s = { cursor: 0, checked: items.map(() => checked) };
4793
- let drawn = 0;
4794
- const draw = () => {
4795
- const lines = pickerLines(title, items, s, (stdout.columns || 80) - 1);
4796
- stdout.write((drawn ? `\x1B[${drawn}A\r\x1B[0J` : "") + lines.join("\n") + "\n");
4797
- drawn = lines.length;
4798
- };
4799
- return new Promise((resolve10) => {
4800
- emitKeypressEvents(stdin);
4801
- stdin.setRawMode(true);
4802
- stdin.resume();
4803
- stdout.write("\x1B[?25l");
4804
- draw();
4805
- const onKey = (_, key) => {
4806
- s = pickerStep(s, key ?? {});
4807
- if (!s.done) return draw();
4808
- stdin.off("keypress", onKey);
4809
- stdin.setRawMode(false);
4810
- stdin.pause();
4811
- stdout.write("\x1B[?25h");
4812
- resolve10(s.done === "ok" ? s.checked.flatMap((c, i) => c ? [i] : []) : void 0);
4813
- };
4814
- stdin.on("keypress", onKey);
4815
5658
  });
5659
+ return { defaultBranch, base, plan };
4816
5660
  }
4817
-
4818
- // src/commands/install-skill.ts
4819
- var NAMES = AGENTS.map((a) => a.name).join(", ");
4820
- var terminalChoose = () => process.stdin.isTTY && process.stdout.isTTY ? terminalPicker : void 0;
4821
- var hasAny = (paths) => paths.some((p) => {
5661
+ function openSetupReview(root, { defaultBranch, base, plan }, tool) {
5662
+ const dir = mkdtempSync2(join22(tmpdir2(), "codechart-setup-"));
4822
5663
  try {
4823
- return lstatSync9(p, { throwIfNoEntry: false }) !== void 0;
4824
- } catch {
4825
- return false;
5664
+ const env = { ...process.env, GIT_INDEX_FILE: join22(dir, "index") };
5665
+ gitRun(root, ["read-tree", base], void 0, env);
5666
+ const blob = gitRun(root, ["hash-object", "-w", "--stdin"], plan.content);
5667
+ gitRun(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${plan.file}`], void 0, env);
5668
+ const tree = gitRun(root, ["write-tree"], void 0, env);
5669
+ const commit = gitRun(root, ["commit-tree", tree, "-p", base, "-m", PR_TITLE]);
5670
+ gitRun(root, ["push", "origin", `${commit}:refs/heads/${SETUP_BRANCH}`]);
5671
+ } finally {
5672
+ rmSync3(dir, { recursive: true, force: true });
4826
5673
  }
4827
- });
4828
- var sameFile = ({ source, target }) => {
5674
+ 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"]);
5675
+ return out.trim().split("\n").pop() ?? "";
5676
+ }
5677
+
5678
+ // src/commands/setup-pr-maps.ts
5679
+ function remoteOf(root, host) {
5680
+ let url;
4829
5681
  try {
4830
- return readRegularFile(target, (st) => st.isFile()) === readFileSync6(source, "utf8");
5682
+ url = gitRun(root, ["config", "--get", "remote.origin.url"]);
4831
5683
  } catch {
4832
- return false;
4833
- }
4834
- };
4835
- var hasClaude = (agents) => agents.some((a) => a.name === "claude");
4836
- async function chooseExtras(agents, opts) {
4837
- const choose = opts.choose ?? terminalChoose();
4838
- const files = agents.flatMap((a) => a.instructions ? [`~/${a.instructions}`] : []);
4839
- const items = [];
4840
- if (files.length) items.push({ key: "reminder", label: "Reminder line", hint: `use codechart for 3+ file changes \u2192 ${files.join(", ")}` });
4841
- if (hasClaude(agents)) {
4842
- items.push({ key: "hook", label: "Claude Code hook", hint: "ask for a diagram when a turn changed 3+ files \u2192 ~/.claude/settings.json" });
5684
+ throw new Error("no origin remote: PR maps need the repo on GitHub or GitLab");
4843
5685
  }
4844
- if (!choose || items.length === 0) return { reminder: true, hook: hasClaude(agents) };
4845
- const picked = await choose("Agents forget skills in long sessions; these help them remember codechart:", items, true);
4846
- const keys = new Set((picked ?? []).map((i) => items[i].key));
4847
- return { reminder: keys.has("reminder"), hook: keys.has("hook") };
4848
- }
4849
- async function pickExtras(o, agents, opts) {
4850
- if (o.reminder === true || o.hook === true) return { reminder: o.reminder === true, hook: o.hook === true };
4851
- if (o.reminder === void 0 && o.hook === void 0 && o.agent === void 0) return chooseExtras(agents, opts);
4852
- return { reminder: o.reminder !== false, hook: o.hook !== false && hasClaude(agents) };
5686
+ const remote = parseRemote(url, host);
5687
+ if (!remote) throw new Error(`can't tell whether ${url} is GitHub or GitLab; add --host github or --host gitlab`);
5688
+ return remote;
4853
5689
  }
4854
- function installExtras(extras, agents, home, opts) {
4855
- const report = (what, run) => {
5690
+ function readWorkTree(root) {
5691
+ return (file) => {
5692
+ const path3 = join23(root, file);
5693
+ let text;
4856
5694
  try {
4857
- opts.stdout(`${run()}
4858
- `);
5695
+ text = readRegularFile(path3, (st) => st.isFile() && lstatSync10(path3).isFile());
4859
5696
  } catch (e) {
4860
- opts.stderr(`codechart: ${what}: ${e.message}
4861
- `);
4862
- process.exitCode = 1;
5697
+ const code = e.code;
5698
+ if (code === "ENOENT") return void 0;
5699
+ if (code !== "ELOOP") throw e;
4863
5700
  }
5701
+ if (text === void 0) throw new Error(`${file}: not a regular file; refusing to write it`);
5702
+ return text;
4864
5703
  };
4865
- if (extras.reminder) {
4866
- for (const a of agents) {
4867
- if (!a.instructions) continue;
4868
- const file = join15(home, a.instructions);
4869
- report("reminder", () => {
4870
- const r = addReminder(file);
4871
- return r === "present" ? `reminder already in ${file}` : `reminder ${r}: ${file}`;
4872
- });
4873
- }
4874
- }
4875
- if (extras.hook) {
4876
- const file = join15(home, ".claude", "settings.json");
4877
- report("hook", () => installClaudeHooks(file) === "added" ? `hook added: ${file}` : `hook already in ${file}`);
4878
- }
4879
5704
  }
4880
- var YOUR_FOLDER = "your folder";
4881
- function rememberOwn(installed, opts) {
4882
- const own = installed.find((t) => t.who === YOUR_FOLDER);
4883
- if (!own) return;
5705
+ function writeWorkTree(root, plan) {
5706
+ const path3 = join23(root, plan.file);
5707
+ mkdirSync6(dirname9(path3), { recursive: true });
5708
+ const flags = constants5.O_WRONLY | constants5.O_CREAT | constants5.O_TRUNC | (constants5.O_NOFOLLOW ?? 0) | (plan.appended ? 0 : constants5.O_EXCL);
5709
+ let fd;
4884
5710
  try {
4885
- rememberSkillDir(loadConfig({ cwd: opts.cwd ?? process.cwd(), home: opts.home, env: opts.env }).web.outDir, own.dir);
4886
- } catch {
5711
+ fd = openSync4(path3, flags, 420);
5712
+ } catch (e) {
5713
+ const code = e.code;
5714
+ if (code === "EEXIST" || code === "ELOOP") throw new Error(`${plan.file}: changed while codechart was running; run it again`);
5715
+ throw e;
4887
5716
  }
4888
- }
4889
- function installCopy(dir, who, files, force, opts) {
4890
- const pairs = files.map((f) => ({ source: packageFile(`skills/codechart/${f}`), target: join15(dir, f) }));
4891
- let update2 = force;
4892
- if (!force && hasAny(pairs.map((p) => p.target))) {
4893
- if (pairs.every(sameFile)) {
4894
- opts.stdout(`up to date for ${who}: ${dir}
4895
- `);
4896
- return true;
4897
- }
4898
- let ours;
4899
- try {
4900
- ours = isCodechartSkill(dir);
4901
- } catch (e) {
4902
- opts.stderr(`codechart: ${e.message}
4903
- `);
4904
- process.exitCode = 1;
4905
- return false;
4906
- }
4907
- if (!ours) {
4908
- opts.stdout(`already installed for ${who}: ${dir} (--force to update)
4909
- `);
4910
- return false;
4911
- }
4912
- update2 = true;
5717
+ try {
5718
+ writeFileSync7(fd, plan.content);
5719
+ } finally {
5720
+ closeSync4(fd);
4913
5721
  }
4914
- if (!copyFiles(pairs, update2, { ...opts, stdout: () => {
4915
- } })) return false;
4916
- opts.stdout(`${update2 && !force ? "updated" : "installed"} for ${who}: ${dir}
4917
- `);
4918
- return true;
4919
5722
  }
4920
- function installSkillCommand(opts) {
4921
- return new Command8("install-skill").description("install the skill for the agents found in your home folder (or --agent / --dir)").option("--agent <names...>", `install for these agents: ${NAMES}`).option("--dir <path>", "install into this skills folder").option("--force", "overwrite an install that is not an older codechart copy").option("--reminder", "only the reminder line in each agent's global instructions file (both extras are added by default)").option("--no-reminder", "skip the reminder line").option("--hook", "only the Claude Code hook that asks for a diagram after a turn that changed 3+ files without one").option("--no-hook", "skip the Claude Code hook").action(async (o) => {
4922
- const home = opts.home ?? homedir3();
4923
- const names = o.agent?.flatMap((n) => n.split(",")).map((n) => n.trim().toLowerCase()).filter(Boolean);
4924
- const unknown = names?.find((n) => !AGENTS.some((a) => a.name === n));
4925
- if (unknown !== void 0) {
4926
- opts.stderr(`codechart: unknown agent '${unknown}' (known: ${NAMES})
4927
- `);
4928
- process.exitCode = 1;
4929
- return;
4930
- }
4931
- let agents = names ? AGENTS.filter((a) => names.includes(a.name)) : o.dir === void 0 ? AGENTS.filter((a) => existsSync5(join15(home, a.home))) : [];
4932
- if (agents.length === 0 && o.dir === void 0) {
4933
- opts.stderr(`codechart: no agent found in ${home}; use --agent <name> (${NAMES}) or --dir <path>
4934
- `);
4935
- process.exitCode = 1;
4936
- return;
4937
- }
4938
- if (!names && agents.length > 0) {
4939
- const choose = opts.choose ?? terminalChoose();
4940
- if (choose && agents.length > 1) {
4941
- const found = agents;
4942
- const picked = await choose(
4943
- "Install the codechart skill for:",
4944
- found.map((a) => ({ label: a.label, hint: `~/${a.skills}` }))
4945
- );
4946
- if (picked === void 0) {
4947
- opts.stderr("codechart: cancelled, nothing installed\n");
4948
- process.exitCode = 1;
4949
- return;
4950
- }
4951
- if (picked.length === 0) {
4952
- opts.stdout("nothing selected, nothing installed\n");
4953
- return;
4954
- }
4955
- agents = picked.map((i) => found[i]);
4956
- } else {
4957
- opts.stdout(`agents: ${agents.map((a) => a.label).join(", ")}
4958
- `);
4959
- }
4960
- }
4961
- const files = readdirSync3(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
4962
- const groups = skillFolders(agents);
4963
- for (const folder of new Set(agents.flatMap((a) => [a.skills, ...a.reads]))) {
4964
- if (groups.some((g) => g.folder === folder) || !hasAny(files.map((f) => join15(home, folder, "codechart", f)))) continue;
4965
- groups.push({ folder, agents: agents.filter((a) => [a.skills, ...a.reads].includes(folder)) });
4966
- }
4967
- const targets = groups.map((g) => ({ dir: join15(home, g.folder, "codechart"), who: g.agents.map((a) => a.label).join(", "), agents: g.agents }));
4968
- if (o.dir !== void 0) targets.push({ dir: join15(resolve8(opts.cwd ?? process.cwd(), o.dir), "codechart"), who: YOUR_FOLDER, agents: [] });
4969
- const installed = targets.filter((t) => installCopy(t.dir, t.who, files, o.force === true, opts));
4970
- rememberOwn(installed, opts);
4971
- const ready = new Set(installed.flatMap((t) => t.agents));
4972
- agents = agents.filter((a) => ready.has(a));
4973
- if (agents.length) installExtras(await pickExtras(o, agents, opts), agents, home, opts);
4974
- });
5723
+ function describe(plan, pr) {
5724
+ const what = plan.appended ? `append this job to ${plan.file}` : `add ${plan.file}`;
5725
+ const where = pr ? `open a ${plan.remote.host === "github" ? "pull" : "merge"} request on ${plan.remote.path} that would ${what}` : `${what} in your work tree (not committed)`;
5726
+ const body = plan.added.trimEnd().split("\n").map((l) => ` ${l}`);
5727
+ return [`codechart setup-pr-maps would ${where}:`, "", ...body, "", ...plan.notes, ""].join("\n") + "\n";
4975
5728
  }
4976
-
4977
- // src/commands/update.ts
4978
- var RELEASES = "https://github.com/freeleex/codechart/releases";
4979
- var spawnOptions = (command, platform = process.platform) => platform === "win32" && command === "npm" ? { shell: true, cwd: dirname9(process.execPath) } : { shell: false };
4980
- var binary = (command) => command === "codechart" ? [process.execPath, [process.argv[1]]] : [command, []];
4981
- var defaultRunner = {
4982
- capture: (command, args) => execFileSync4(command, args, { encoding: "utf8", ...spawnOptions(command), stdio: ["ignore", "pipe", "ignore"], timeout: 3e4 }),
4983
- show: (command, args) => {
4984
- const [bin, pre] = binary(command);
4985
- const r = spawnSync2(bin, [...pre, ...args], { stdio: "inherit", ...spawnOptions(command) });
4986
- if (r.status !== 0) throw new Error(`${command} ${args.join(" ")} failed${r.error ? `: ${r.error.message}` : ""}`);
5729
+ async function terminalConfirm(question) {
5730
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
5731
+ try {
5732
+ return /^y(es)?$/i.test((await rl.question(question)).trim());
5733
+ } finally {
5734
+ rl.close();
4987
5735
  }
4988
- };
4989
- function installedBy(installDir, npmRoot) {
4990
- const real = (p) => existsSync6(p) ? realpathSync5(p) : resolve9(p);
4991
- if (npmRoot && real(installDir) === real(join16(npmRoot, "codechart"))) return { npm: true };
4992
- if (/[\\/]_npx[\\/]/.test(installDir)) return { npm: false, hint: "npx runs the newest codechart already; nothing to update" };
4993
- if (installDir.includes(`${sep5}pnpm${sep5}`) || installDir.includes("/pnpm/")) return { npm: false, hint: "update it with: pnpm add -g codechart@latest" };
4994
- if (installDir.includes(".bun")) return { npm: false, hint: "update it with: bun add -g codechart@latest" };
4995
- if (installDir.includes("yarn")) return { npm: false, hint: "update it with: yarn global add codechart@latest" };
4996
- return { npm: false, hint: `it isn't npm's global copy (${installDir}); update it the way you installed it` };
4997
5736
  }
4998
- var cacheDirOf = (opts) => loadConfig({ cwd: opts.cwd ?? process.cwd(), home: opts.home, env: opts.env }).web.outDir;
4999
- function refreshInstalls(home, opts) {
5000
- const files = readdirSync4(packageFile("skills/codechart")).sort((a, b) => Number(b === "SKILL.md") - Number(a === "SKILL.md"));
5001
- const folders = [...new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))];
5002
- const dirs = [
5003
- ...folders.map((folder) => ({ dir: join16(home, folder, "codechart"), who: AGENTS.filter((a) => [a.skills, ...a.reads].includes(folder)).map((a) => a.label).join(", ") })),
5004
- ...skillDirs(readState(cacheDirOf(opts))).map((dir) => ({ dir, who: "your folder" }))
5005
- ];
5006
- for (const { dir, who } of dirs) {
5007
- let ours = false;
5008
- try {
5009
- ours = existsSync6(dir) && isCodechartSkill(dir);
5010
- } catch {
5011
- ours = false;
5012
- }
5013
- if (!ours) continue;
5014
- installCopy(dir, who, files, false, opts);
5737
+ var defaultTool = (command, args) => {
5738
+ try {
5739
+ return execFileSync5(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 12e4 });
5740
+ } catch (e) {
5741
+ if (e.code === "ENOENT") throw new Error(`${command} is not installed; install it or run without --pr`);
5742
+ throw new Error(`${command} failed: ${String(e.stderr ?? e.message).trim()}`);
5015
5743
  }
5016
- for (const a of AGENTS) {
5017
- if (!a.instructions) continue;
5018
- if (refreshReminder(join16(home, a.instructions)) === "updated") opts.stdout(`reminder updated: ${join16(home, a.instructions)}
5744
+ };
5745
+ async function agreed(o, opts) {
5746
+ if (o.yes) return true;
5747
+ const confirm = opts.confirm ?? (process.stdin.isTTY && process.stdout.isTTY ? terminalConfirm : void 0);
5748
+ if (confirm) return confirm(o.pr ? "Open it? [y/N] " : "Write it? [y/N] ");
5749
+ opts.stdout(`Nothing changed. To go ahead, run again with --yes${o.pr ? " --pr" : " (or --yes --pr to open a pull request instead)"}.
5019
5750
  `);
5020
- }
5751
+ return false;
5021
5752
  }
5022
- async function update(o, opts, runner) {
5023
- const home = opts.home ?? homedir4();
5024
- const current = currentVersion();
5025
- const latest = await fetchLatest(opts.fetch ?? fetch, 1e4);
5026
- if (!latest) throw new Error("couldn't reach the npm registry to look up the newest version");
5027
- const cacheDir = cacheDirOf(opts);
5028
- writeState(cacheDir, { ...readState(cacheDir), checkedAt: opts.now?.().getTime() ?? Date.now(), latest });
5029
- if (!isNewer(latest, current)) {
5030
- opts.stdout(`codechart ${current} is the newest version.
5031
- `);
5032
- if (!o.check) refreshInstalls(home, opts);
5033
- return;
5034
- }
5035
- if (o.check) {
5036
- opts.stdout(`codechart ${latest} is available (you have ${current}): run codechart update
5753
+ async function setup(o, opts, root) {
5754
+ const remote = remoteOf(root, o.host);
5755
+ const v = currentVersion();
5756
+ const done = () => opts.stdout(`codechart: PR maps are already set up in ${remote.path}.
5037
5757
  `);
5038
- return;
5039
- }
5040
- let npmRoot;
5041
- try {
5042
- npmRoot = runner.capture("npm", ["root", "-g"]).trim();
5043
- } catch {
5044
- npmRoot = void 0;
5045
- }
5046
- const how = installedBy(packageFile(""), npmRoot);
5047
- if (!how.npm) {
5048
- opts.stdout(`codechart ${latest} is available (you have ${current}), but ${how.hint}.
5758
+ if (o.pr) {
5759
+ const prepared = prepareSetupReview(root, v, remote);
5760
+ if (!prepared.plan) return done();
5761
+ opts.stdout(describe(prepared.plan, true));
5762
+ if (!await agreed(o, opts)) return;
5763
+ const url = openSetupReview(root, { ...prepared, plan: prepared.plan }, opts.tool ?? defaultTool);
5764
+ opts.stdout(`codechart: opened ${url}
5765
+ Merge it to turn PR maps on; close it to say no.
5049
5766
  `);
5050
5767
  return;
5051
5768
  }
5052
- opts.stdout(`Updating codechart ${current} \u2192 ${latest}: npm install -g codechart@${latest}
5053
- `);
5054
- runner.show("npm", ["install", "-g", `codechart@${latest}`]);
5055
- runner.show("codechart", ["update", "--skills-only"]);
5056
- opts.stdout(`codechart ${latest} installed. What changed: ${RELEASES}
5769
+ const plan = buildPlan(remote, v, readWorkTree(root));
5770
+ if (!plan) return done();
5771
+ opts.stdout(describe(plan, false));
5772
+ if (!await agreed(o, opts)) return;
5773
+ writeWorkTree(root, plan);
5774
+ const next = remote.host === "gitlab" ? ", then add the CODECHART_GITLAB_TOKEN variable as above" : "";
5775
+ opts.stdout(`codechart: wrote ${plan.file}. Review it, commit and push it${next}.
5057
5776
  `);
5058
5777
  }
5059
- function updateCommand(opts) {
5060
- return new Command9("update").description("install the newest codechart with npm and refresh the skill copies and reminder lines you have").option("--check", "only say whether a newer version exists").option("--skills-only", "refresh installed skill copies and reminder lines to this version (run by update)").action(async (o) => {
5778
+ function setupPrMapsCommand(opts) {
5779
+ const cwd = opts.cwd ?? process.cwd();
5780
+ return new Command10("setup-pr-maps").description("add the CI job that keeps codechart maps in PR/MR descriptions current; shows the change and asks first").option("--yes", "don't ask: needed when not run from a terminal").option("--pr", "open a pull or merge request with the change (needs gh or glab) instead of writing it to the work tree").addOption(new Option2("--host <host>", "when the origin URL names neither").choices(["github", "gitlab"])).action(async (o) => {
5061
5781
  try {
5062
- if (o.skillsOnly) return refreshInstalls(opts.home ?? homedir4(), opts);
5063
- const tool = opts.tool;
5064
- await update(o, opts, tool ? { capture: tool, show: (c, a) => void tool(c, a) } : defaultRunner);
5782
+ const root = findRepoRoot(cwd);
5783
+ if (!root) throw new Error("not a git repository");
5784
+ await setup(o, opts, root);
5065
5785
  } catch (e) {
5066
5786
  opts.stderr(`codechart: ${e instanceof Error ? e.message : String(e)}
5067
5787
  `);
@@ -5071,37 +5791,42 @@ function updateCommand(opts) {
5071
5791
  }
5072
5792
 
5073
5793
  // src/commands/schema.ts
5074
- import { Command as Command10 } from "commander";
5794
+ import { Command as Command11 } from "commander";
5075
5795
  function schemaCommand(opts) {
5076
- return new Command10("schema").description("print the spec JSON schema, the flow spec schema with --flow, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").action((o) => {
5796
+ return new Command11("schema").description("print the spec JSON schema, the flow spec schema with --flow, or the config file schema with --config").option("--config", "print the config file schema instead").option("--flow", "print the flow spec schema instead").action((o) => {
5077
5797
  const schema = o.config ? configJsonSchema() : o.flow ? flowJsonSchema() : specJsonSchema();
5078
5798
  opts.stdout(JSON.stringify(schema, null, 2) + "\n");
5079
5799
  });
5080
5800
  }
5081
5801
 
5082
5802
  // src/commands/uninstall.ts
5083
- import { lstatSync as lstatSync10, readdirSync as readdirSync5, rmdirSync, unlinkSync as unlinkSync3 } from "fs";
5084
- import { homedir as homedir5 } from "os";
5085
- import { join as join17 } from "path";
5086
- import { Command as Command11 } from "commander";
5803
+ import { lstatSync as lstatSync11, readdirSync as readdirSync5, rmdirSync, unlinkSync as unlinkSync4 } from "fs";
5804
+ import { homedir as homedir6 } from "os";
5805
+ import { join as join24 } from "path";
5806
+ import { Command as Command12 } from "commander";
5087
5807
  function removeSkill(dir, files) {
5088
- const st = lstatSync10(dir, { throwIfNoEntry: false });
5808
+ const st = lstatSync11(dir, { throwIfNoEntry: false });
5089
5809
  if (!st) return void 0;
5090
5810
  if (!st.isDirectory()) return `left ${dir}: not a folder`;
5091
5811
  if (!isCodechartSkill(dir)) return `left ${dir}: not the codechart skill`;
5092
- for (const f of files) if (lstatSync10(join17(dir, f), { throwIfNoEntry: false })?.isFile()) unlinkSync3(join17(dir, f));
5812
+ for (const f of files) if (lstatSync11(join24(dir, f), { throwIfNoEntry: false })?.isFile()) unlinkSync4(join24(dir, f));
5093
5813
  if (readdirSync5(dir).length > 0) return `removed skill files from ${dir} (kept your other files there)`;
5094
5814
  rmdirSync(dir);
5095
5815
  return `removed skill: ${dir}`;
5096
5816
  }
5817
+ function pluginLine(file) {
5818
+ const r = removePlugin(file);
5819
+ if (r === "foreign") return `left ${file}: not the codechart plugin`;
5820
+ return r === "removed" ? `removed plugin: ${file}` : void 0;
5821
+ }
5097
5822
  function uninstallCommand(opts) {
5098
- return new Command11("uninstall").description("remove what install-skill added (all of it unless flags pick some); run before npm uninstall -g codechart").option("--skill", "remove the skill from every agent folder").option("--reminder", "remove the reminder line from agents' instructions files").option("--hook", "remove the codechart hooks from ~/.claude/settings.json").action((o) => {
5099
- const home = opts.home ?? homedir5();
5100
- const all = !o.skill && !o.reminder && !o.hook;
5823
+ return new Command12("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) => {
5824
+ const home = opts.home ?? homedir6();
5825
+ const all = !o.skill && !o.reminder && !o.hook && !o.plugin;
5101
5826
  let did = false;
5102
- const step = (run) => {
5827
+ const step = (run2) => {
5103
5828
  try {
5104
- const line = run();
5829
+ const line = run2();
5105
5830
  if (line) {
5106
5831
  opts.stdout(`${line}
5107
5832
  `);
@@ -5115,25 +5840,29 @@ function uninstallCommand(opts) {
5115
5840
  };
5116
5841
  if (all || o.skill) {
5117
5842
  const files = readdirSync5(packageFile("skills/codechart"));
5118
- for (const folder of new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))) step(() => removeSkill(join17(home, folder, "codechart"), files));
5843
+ for (const folder of new Set(AGENTS.flatMap((a) => [a.skills, ...a.reads]))) step(() => removeSkill(join24(home, folder, "codechart"), files));
5119
5844
  }
5120
5845
  if (all || o.reminder) {
5121
5846
  for (const a of AGENTS) {
5122
5847
  if (!a.instructions) continue;
5123
- const file = join17(home, a.instructions);
5848
+ const file = join24(home, a.instructions);
5124
5849
  step(() => removeReminder(file) === "removed" ? `removed reminder: ${file}` : void 0);
5125
5850
  }
5126
5851
  }
5127
5852
  if (all || o.hook) {
5128
- const file = join17(home, ".claude", "settings.json");
5853
+ const file = join24(home, ".claude", "settings.json");
5129
5854
  step(() => removeClaudeHooks(file) === "removed" ? `removed hook: ${file}` : void 0);
5130
5855
  }
5856
+ if (all || o.plugin) {
5857
+ const file = pluginFile(home, opts.env ?? process.env);
5858
+ step(() => pluginLine(file));
5859
+ }
5131
5860
  if (!did && process.exitCode !== 1) opts.stdout("nothing to remove\n");
5132
5861
  });
5133
5862
  }
5134
5863
 
5135
5864
  // src/program.ts
5136
- var NO_NOTICE = /* @__PURE__ */ new Set(["hook", "pr-sync", "update", "uninstall"]);
5865
+ var NO_NOTICE = /* @__PURE__ */ new Set(["hook", "pr-sync", "update", "uninstall", "doctor"]);
5137
5866
  async function noticeAfter(name, opts, stderr) {
5138
5867
  if (opts.updateCheck === false || NO_NOTICE.has(name)) return;
5139
5868
  try {
@@ -5157,7 +5886,7 @@ function buildProgram(opts = {}) {
5157
5886
  const stdout = opts.stdout ?? ((s) => process.stdout.write(s));
5158
5887
  const rawStderr = opts.stderr ?? ((s) => process.stderr.write(s));
5159
5888
  const stderr = (s) => rawStderr(sanitizeText(s));
5160
- const program = new Command12().name("codechart").version(currentVersion());
5889
+ const program = new Command13().name("codechart").version(currentVersion());
5161
5890
  const cmdOpts = { ...opts, stdout, stderr };
5162
5891
  program.addCommand(checkCommand(cmdOpts));
5163
5892
  program.addCommand(renderCommand(cmdOpts));
@@ -5170,6 +5899,7 @@ function buildProgram(opts = {}) {
5170
5899
  program.addCommand(prSyncCommand(cmdOpts));
5171
5900
  program.addCommand(setupPrMapsCommand(cmdOpts));
5172
5901
  program.addCommand(updateCommand(cmdOpts));
5902
+ program.addCommand(doctorCommand(cmdOpts));
5173
5903
  program.hook("postAction", (_program, action) => noticeAfter(action.name(), cmdOpts, stderr));
5174
5904
  for (const c of [program, ...program.commands]) {
5175
5905
  c.exitOverride().configureOutput({ writeOut: stdout, writeErr: stderr });