codechart 0.3.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/README.md +100 -133
- package/config.schema.json +4 -0
- package/dist/cli.js +4394 -2194
- package/dist/server.js +349 -0
- package/package.json +9 -3
- package/skills/codechart/SKILL.md +14 -4
- package/skills/codechart/example.md +3 -5
- package/skills/codechart/flow-guide.md +1 -1
- package/skills/codechart/pr-maps.md +13 -0
- package/skills/codechart/spec-guide.md +2 -2
- package/templates/codechart.yaml +1 -0
- package/templates/github-workflow.yml +29 -0
- package/templates/gitlab-ci.yml +15 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/opencode/handlers.ts
|
|
4
|
+
import { homedir } from "os";
|
|
5
|
+
import { join as join5, resolve as resolve2 } from "path";
|
|
6
|
+
|
|
7
|
+
// src/config/repo-root.ts
|
|
8
|
+
import { existsSync } from "fs";
|
|
9
|
+
import { dirname, join, resolve } from "path";
|
|
10
|
+
function findRepoRoot(cwd) {
|
|
11
|
+
let dir = resolve(cwd);
|
|
12
|
+
for (; ; ) {
|
|
13
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
14
|
+
const parent = dirname(dir);
|
|
15
|
+
if (parent === dir) return void 0;
|
|
16
|
+
dir = parent;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/commands/hook-core.ts
|
|
21
|
+
import { lstatSync as lstatSync2, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
|
|
22
|
+
import { join as join3 } from "path";
|
|
23
|
+
|
|
24
|
+
// src/rules/git-files.ts
|
|
25
|
+
import { execFileSync } from "child_process";
|
|
26
|
+
import { existsSync as existsSync2, lstatSync } from "fs";
|
|
27
|
+
import { join as join2, win32 } from "path";
|
|
28
|
+
|
|
29
|
+
// src/render/strip.ts
|
|
30
|
+
var EXTRA = "\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180e\\u3164\\ufe00-\\ufe0e\\uffa0\\ufff9-\\ufffb\\u{e0000}-\\u{e007f}\\u{e0100}-\\u{e01ef}";
|
|
31
|
+
var INVISIBLE = new RegExp(`[\\u200b\\u200c\\u200e\\u200f\\u202a-\\u202e\\u2060-\\u2069\\ufeff${EXTRA}]`, "gu");
|
|
32
|
+
var JSON_ESCAPE = new RegExp(`[\\u007f-\\u009f\\u200b-\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2060-\\u2069\\ufeff${EXTRA}]`, "gu");
|
|
33
|
+
var HIDDEN = new RegExp(`[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2069\\ufeff${EXTRA}]`, "u");
|
|
34
|
+
|
|
35
|
+
// src/rules/git-files.ts
|
|
36
|
+
function gitBinary(platform = process.platform, env = process.env, exists = existsSync2) {
|
|
37
|
+
if (platform !== "win32") return "git";
|
|
38
|
+
for (const raw of (env.PATH ?? env.Path ?? "").split(";")) {
|
|
39
|
+
const dir = raw.replace(/^"(.*)"$/, "$1");
|
|
40
|
+
if (!win32.isAbsolute(dir)) continue;
|
|
41
|
+
const file = win32.join(dir, "git.exe");
|
|
42
|
+
if (exists(file)) return file;
|
|
43
|
+
}
|
|
44
|
+
throw new Error("git not found on PATH");
|
|
45
|
+
}
|
|
46
|
+
var gitPath;
|
|
47
|
+
var SAFE_ARGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never"];
|
|
48
|
+
var OutputTooLarge = class extends Error {
|
|
49
|
+
};
|
|
50
|
+
function git(cwd, args, { config = [], input, maxBuffer = 256 * 1024 * 1024, binary } = {}) {
|
|
51
|
+
try {
|
|
52
|
+
gitPath ??= gitBinary();
|
|
53
|
+
const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
|
|
54
|
+
const env = { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_CONFIG_COUNT: String(n + config.length) };
|
|
55
|
+
config.forEach(([k, v], i) => {
|
|
56
|
+
env[`GIT_CONFIG_KEY_${n + i}`] = k;
|
|
57
|
+
env[`GIT_CONFIG_VALUE_${n + i}`] = v;
|
|
58
|
+
});
|
|
59
|
+
return execFileSync(gitPath, [...SAFE_ARGS, `--work-tree=${cwd}`, ...args], {
|
|
60
|
+
cwd,
|
|
61
|
+
env,
|
|
62
|
+
timeout: 3e4,
|
|
63
|
+
...binary ? {} : { encoding: "utf8" },
|
|
64
|
+
// -uall on big trees can exceed the 1 MiB default
|
|
65
|
+
maxBuffer,
|
|
66
|
+
...input === void 0 ? { stdio: ["ignore", "pipe", "pipe"] } : { input, stdio: ["pipe", "pipe", "pipe"] }
|
|
67
|
+
});
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (e.code === "ENOBUFS") throw new OutputTooLarge(`git output over ${maxBuffer} bytes`);
|
|
70
|
+
const stderr = String(e.stderr ?? "").trim().split("\n")[0];
|
|
71
|
+
throw new Error(`git ${args.find((a) => !a.startsWith("-"))} failed: ${stderr || e.message}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function repoFilterOverrides(cwd) {
|
|
75
|
+
const keys = /* @__PURE__ */ new Set();
|
|
76
|
+
const drivers = /* @__PURE__ */ new Set();
|
|
77
|
+
for (const key of repoConfigKeys(cwd).filter((k) => /^filter\./i.test(k))) {
|
|
78
|
+
const m = /^(filter\..+)\.(clean|process)$/i.exec(key);
|
|
79
|
+
if (m) {
|
|
80
|
+
keys.add(key);
|
|
81
|
+
drivers.add(m[1]);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return [...[...keys].map((k) => [k, ""]), ...[...drivers].map((d) => [`${d}.required`, "false"])];
|
|
85
|
+
}
|
|
86
|
+
var configKeys = /* @__PURE__ */ new Map();
|
|
87
|
+
function repoConfigKeys(cwd) {
|
|
88
|
+
const hit = configKeys.get(cwd);
|
|
89
|
+
if (hit) return hit;
|
|
90
|
+
const keys = [];
|
|
91
|
+
try {
|
|
92
|
+
const recs = git(cwd, ["config", "--show-scope", "--includes", "-z", "--name-only", "--get-regexp", "^(filter|diff)\\."]).split("\0");
|
|
93
|
+
for (let i = 0; i + 1 < recs.length; i += 2) {
|
|
94
|
+
if (recs[i] === "local" || recs[i] === "worktree") keys.push(recs[i + 1]);
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
}
|
|
98
|
+
configKeys.set(cwd, keys);
|
|
99
|
+
return keys;
|
|
100
|
+
}
|
|
101
|
+
var nulList = (out) => out.split("\0").filter(Boolean);
|
|
102
|
+
function gitChangedFiles(cwd, renameSources = false) {
|
|
103
|
+
const records = git(cwd, ["status", "--porcelain=v1", "-z", "-uall", "--ignore-submodules=dirty"], { config: repoFilterOverrides(cwd) }).split("\0");
|
|
104
|
+
const files = [];
|
|
105
|
+
for (let i = 0; i < records.length; i++) {
|
|
106
|
+
const rec = records[i];
|
|
107
|
+
if (!rec || rec.length < 4) continue;
|
|
108
|
+
files.push(rec.slice(3));
|
|
109
|
+
if (rec[0] === "R" || rec[0] === "C" || rec[1] === "R" || rec[1] === "C") {
|
|
110
|
+
i++;
|
|
111
|
+
if (renameSources && (rec[0] === "R" || rec[1] === "R") && records[i]) files.push(records[i]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return files;
|
|
115
|
+
}
|
|
116
|
+
function gitListFiles(cwd, sha) {
|
|
117
|
+
return nulList(
|
|
118
|
+
sha ? git(cwd, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", sha]) : git(cwd, ["ls-files", "-z", "--cached", "--full-name"])
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
function gitHead(cwd) {
|
|
122
|
+
try {
|
|
123
|
+
return git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]).trim() || void 0;
|
|
124
|
+
} catch {
|
|
125
|
+
return void 0;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function gitDirtyHashes(cwd, max = Infinity) {
|
|
129
|
+
const files = gitChangedFiles(cwd);
|
|
130
|
+
if (files.length > max) return void 0;
|
|
131
|
+
const out = {};
|
|
132
|
+
const present = files.filter((f) => !f.includes("\n") && !f.startsWith('"') && lstatSync(join2(cwd, f), { throwIfNoEntry: false })?.isFile() === true);
|
|
133
|
+
const hashes = present.length ? git(cwd, ["hash-object", "--no-filters", "--stdin-paths"], { input: present.join("\n") }).trim().split("\n") : [];
|
|
134
|
+
for (const f of files) out[f] = existsSync2(join2(cwd, f)) ? "present" : "deleted";
|
|
135
|
+
present.forEach((f, i) => out[f] = hashes[i] ?? "");
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
function gitDiffFiles(cwd, from, to) {
|
|
139
|
+
return nulList(git(cwd, ["diff", "--no-renames", "--name-only", "-z", from, to, "--"]));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/commands/transcript.ts
|
|
143
|
+
var DIAGRAM = /\*\*(Map|Flow)\*\*/;
|
|
144
|
+
var CODECHART_RUN = /\bcodechart\s+(check|render)\b/;
|
|
145
|
+
|
|
146
|
+
// src/commands/hook-core.ts
|
|
147
|
+
var MIN_FILES = 3;
|
|
148
|
+
var MAX_DIRTY = 5e3;
|
|
149
|
+
var KEEP_DAYS = 7;
|
|
150
|
+
var SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
151
|
+
function changedFiles(before, now, diff) {
|
|
152
|
+
const changed = /* @__PURE__ */ new Set();
|
|
153
|
+
for (const f of /* @__PURE__ */ new Set([...Object.keys(before.files), ...Object.keys(now.files)])) {
|
|
154
|
+
if (before.files[f] !== now.files[f]) changed.add(f);
|
|
155
|
+
}
|
|
156
|
+
if (now.head && before.head !== now.head) for (const f of diff(before.head, now.head)) changed.add(f);
|
|
157
|
+
return [...changed].sort();
|
|
158
|
+
}
|
|
159
|
+
function snapshot(root) {
|
|
160
|
+
const files = gitDirtyHashes(root, MAX_DIRTY);
|
|
161
|
+
return files && { head: gitHead(root), files };
|
|
162
|
+
}
|
|
163
|
+
function prune(dir, now) {
|
|
164
|
+
for (const f of readdirSync(dir)) {
|
|
165
|
+
const p = join3(dir, f);
|
|
166
|
+
const st = lstatSync2(p);
|
|
167
|
+
if (st.isFile() && now - st.mtimeMs > KEEP_DAYS * 864e5) unlinkSync(p);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
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.`;
|
|
171
|
+
function saveSnapshot(dir, file, root, now) {
|
|
172
|
+
const snap = snapshot(root);
|
|
173
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
174
|
+
prune(dir, now.getTime());
|
|
175
|
+
if (snap) writeFileSync(file, JSON.stringify({ root, ...snap }), { mode: 384 });
|
|
176
|
+
else unlinkSync(file);
|
|
177
|
+
}
|
|
178
|
+
function readSnapshot(file) {
|
|
179
|
+
try {
|
|
180
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
181
|
+
} catch {
|
|
182
|
+
return void 0;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function judgeTurn(root, file, reply, used) {
|
|
186
|
+
const before = readSnapshot(file);
|
|
187
|
+
if (!before) return { decision: "no-snapshot" };
|
|
188
|
+
if (before.root !== root) return { decision: "other-root" };
|
|
189
|
+
const now = snapshot(root);
|
|
190
|
+
if (!now) return { decision: "no-snapshot" };
|
|
191
|
+
const files = changedFiles(before, now, (a, b) => a ? gitDiffFiles(root, a, b) : gitListFiles(root, b));
|
|
192
|
+
if (files.length < MIN_FILES) return { decision: "few-files", files };
|
|
193
|
+
if (reply !== void 0 && DIAGRAM.test(reply)) return { decision: "diagram-in-reply", files };
|
|
194
|
+
const seen = used();
|
|
195
|
+
if (seen && (seen.diagram || seen.cli)) return { decision: "codechart-used", files };
|
|
196
|
+
return { decision: "nudged", files };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/commands/hook-record.ts
|
|
200
|
+
import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
201
|
+
import { join as join4 } from "path";
|
|
202
|
+
var MAX_FILES = 500;
|
|
203
|
+
var SUFFIX = ".turn.json";
|
|
204
|
+
var turnsDir = (home) => join4(home, ".cache", "codechart", "turns");
|
|
205
|
+
function writeRecord(dir, record) {
|
|
206
|
+
mkdirSync2(dir, { recursive: true, mode: 448 });
|
|
207
|
+
const files = record.files && record.files.slice(0, MAX_FILES);
|
|
208
|
+
writeFileSync2(join4(dir, `${record.session}${SUFFIX}`), JSON.stringify({ ...record, files }), { mode: 384 });
|
|
209
|
+
}
|
|
210
|
+
function readRecord(dir, session) {
|
|
211
|
+
try {
|
|
212
|
+
return JSON.parse(readFileSync2(join4(dir, `${session}${SUFFIX}`), "utf8"));
|
|
213
|
+
} catch {
|
|
214
|
+
return void 0;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function recordPrompt(dir, root, session, at, agent) {
|
|
218
|
+
const prev = readRecord(dir, session);
|
|
219
|
+
writeRecord(dir, prev ? { ...prev, pendingAt: at } : { at, root, session, pendingAt: at, agent });
|
|
220
|
+
}
|
|
221
|
+
function recordStop(dir, rec) {
|
|
222
|
+
const prev = readRecord(dir, rec.session);
|
|
223
|
+
if (rec.decision === "stop_hook_active" && prev?.decision && !prev.pendingAt) return;
|
|
224
|
+
if (rec.decision === "few-files" && !rec.files?.length && prev?.files?.length) {
|
|
225
|
+
writeRecord(dir, { ...prev, pendingAt: void 0, quietAt: rec.at });
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
writeRecord(dir, rec);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/opencode/turn.ts
|
|
232
|
+
var runsCodechart = (command) => typeof command === "string" && CODECHART_RUN.test(command);
|
|
233
|
+
var textOf = (m) => (m.content ?? []).filter((b) => b.type === "text").map((b) => b.text ?? "");
|
|
234
|
+
function viewTurn(messages) {
|
|
235
|
+
const at = messages.map((m) => m.type).lastIndexOf("user");
|
|
236
|
+
const user = messages[at];
|
|
237
|
+
if (!user?.id) return void 0;
|
|
238
|
+
const turn = messages.slice(at + 1);
|
|
239
|
+
const assistants = turn.filter((m) => m.type === "assistant");
|
|
240
|
+
const texts = assistants.flatMap(textOf);
|
|
241
|
+
const lastReply = assistants.at(-1);
|
|
242
|
+
return {
|
|
243
|
+
userID: user.id,
|
|
244
|
+
nudged: turn.some((m) => m.type === "synthetic" && m.metadata?.codechart !== void 0),
|
|
245
|
+
reply: lastReply && textOf(lastReply).join("\n"),
|
|
246
|
+
diagram: texts.some((t) => DIAGRAM.test(t)),
|
|
247
|
+
cli: turn.some((m) => m.type === "shell" && runsCodechart(m.command)) || assistants.some((m) => (m.content ?? []).some((b) => b.type === "tool" && runsCodechart(b.state?.input?.command))),
|
|
248
|
+
outcome: turn.filter((m) => m.type === "idle").at(-1)?.outcome,
|
|
249
|
+
providerID: assistants.at(-1)?.model?.providerID
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// src/opencode/handlers.ts
|
|
254
|
+
var CLAUDE_PROVIDER = "claude-code";
|
|
255
|
+
var MAX_HANDLED = 500;
|
|
256
|
+
var skipped = (s, providerID) => Boolean(s.parentID) || (s.model?.providerID ?? providerID) === CLAUDE_PROVIDER;
|
|
257
|
+
var rootOf = (s) => findRepoRoot(join5(s.location.directory, s.subpath ?? ""));
|
|
258
|
+
var sameLocation = (a, b) => resolve2(a.directory) === resolve2(b.directory) && a.workspaceID === b.workspaceID;
|
|
259
|
+
var turnFile = (s, sessionID) => join5(s.dir, `${sessionID}.json`);
|
|
260
|
+
async function onPrompt(s, sessionID) {
|
|
261
|
+
if (!SESSION_ID.test(sessionID)) return;
|
|
262
|
+
const session = await s.ctx.session.get({ sessionID });
|
|
263
|
+
const root = skipped(session) ? void 0 : rootOf(session);
|
|
264
|
+
if (!root) return;
|
|
265
|
+
const at = s.now();
|
|
266
|
+
try {
|
|
267
|
+
saveSnapshot(s.dir, turnFile(s, sessionID), root, at);
|
|
268
|
+
} finally {
|
|
269
|
+
try {
|
|
270
|
+
recordPrompt(s.dir, root, sessionID, at.toISOString(), "opencode");
|
|
271
|
+
} catch (e) {
|
|
272
|
+
s.fail("record", e);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function check(s, sessionID, succeeded) {
|
|
277
|
+
if (!SESSION_ID.test(sessionID)) return;
|
|
278
|
+
const session = await s.ctx.session.get({ sessionID });
|
|
279
|
+
if (skipped(session) || !sameLocation(session.location, s.ctx.location)) return;
|
|
280
|
+
const turn = viewTurn(await s.ctx.session.context({ sessionID }));
|
|
281
|
+
if (!turn || !(succeeded || (turn.outcome ?? session.outcome) === "succeeded")) return;
|
|
282
|
+
if (skipped(session, turn.providerID)) return;
|
|
283
|
+
const key = `${sessionID}:${turn.userID}`;
|
|
284
|
+
if (turn.nudged || s.handled.has(key)) return;
|
|
285
|
+
if (s.handled.size >= MAX_HANDLED) s.handled.clear();
|
|
286
|
+
s.handled.add(key);
|
|
287
|
+
const root = rootOf(session);
|
|
288
|
+
if (!root) return;
|
|
289
|
+
const outcome = judgeTurn(root, turnFile(s, sessionID), turn.reply, () => turn);
|
|
290
|
+
if (outcome.decision === "nudged") {
|
|
291
|
+
await s.ctx.session.synthetic({ sessionID, text: nudge(outcome.files?.length ?? 0), metadata: { codechart: "nudge" }, resume: true });
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
recordStop(s.dir, { at: s.now().toISOString(), root, session: sessionID, decision: outcome.decision, files: outcome.files, cli: turn.cli, agent: "opencode" });
|
|
295
|
+
} catch (e) {
|
|
296
|
+
s.fail("record", e);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function onIdle(s, sessionID, succeeded) {
|
|
300
|
+
if (s.running.has(sessionID)) return;
|
|
301
|
+
s.running.add(sessionID);
|
|
302
|
+
try {
|
|
303
|
+
await check(s, sessionID, succeeded);
|
|
304
|
+
} catch (e) {
|
|
305
|
+
s.fail("idle", e);
|
|
306
|
+
} finally {
|
|
307
|
+
s.running.delete(sessionID);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function createHandlers(ctx, env = {}) {
|
|
311
|
+
const s = {
|
|
312
|
+
ctx,
|
|
313
|
+
dir: turnsDir(env.home ?? homedir()),
|
|
314
|
+
now: () => env.now?.() ?? /* @__PURE__ */ new Date(),
|
|
315
|
+
fail: (what, e) => {
|
|
316
|
+
if (env.debug) console.error(`codechart: opencode ${what}: ${e instanceof Error ? e.message : String(e)}`);
|
|
317
|
+
},
|
|
318
|
+
handled: /* @__PURE__ */ new Set(),
|
|
319
|
+
running: /* @__PURE__ */ new Set()
|
|
320
|
+
};
|
|
321
|
+
return { onPrompt: (id) => onPrompt(s, id), onIdle: (id, succeeded = false) => onIdle(s, id, succeeded), fail: s.fail };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/opencode/server.ts
|
|
325
|
+
async function setup(ctx) {
|
|
326
|
+
const abort = new AbortController();
|
|
327
|
+
const handlers = createHandlers(ctx, { debug: Boolean(process.env.CODECHART_DEBUG) });
|
|
328
|
+
let registration;
|
|
329
|
+
try {
|
|
330
|
+
registration = await ctx.session.hook("prompt", (event) => handlers.onPrompt(event.sessionID).catch((e) => handlers.fail("prompt", e)));
|
|
331
|
+
void (async () => {
|
|
332
|
+
for await (const event of ctx.event.subscribe({ types: ["session.idle", "session.execution.succeeded"], signal: abort.signal })) {
|
|
333
|
+
if (event.data?.sessionID) void handlers.onIdle(event.data.sessionID, event.type === "session.execution.succeeded");
|
|
334
|
+
}
|
|
335
|
+
})().catch((e) => handlers.fail("events", e));
|
|
336
|
+
} catch (e) {
|
|
337
|
+
handlers.fail("setup", e);
|
|
338
|
+
}
|
|
339
|
+
return async () => {
|
|
340
|
+
abort.abort();
|
|
341
|
+
await registration?.dispose().catch(() => {
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
var server_default = { id: "codechart", setup };
|
|
346
|
+
export {
|
|
347
|
+
server_default as default
|
|
348
|
+
};
|
|
349
|
+
/*! codechart OpenCode plugin: install-skill copies this file to ~/.config/opencode/plugins/codechart.js */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codechart",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Agent skill + CLI: maps and flowcharts of code changes for AI coding agents, in terminal, chat and HTML",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,11 +52,15 @@
|
|
|
52
52
|
"lint": "eslint .",
|
|
53
53
|
"measure": "tsx scripts/measure.ts",
|
|
54
54
|
"bench:tokens": "tsx scripts/token-bench.ts",
|
|
55
|
-
"gen:config-schema": "tsx scripts/gen-config-schema.ts"
|
|
55
|
+
"gen:config-schema": "tsx scripts/gen-config-schema.ts",
|
|
56
|
+
"complexity": "node scripts/complexity.mjs",
|
|
57
|
+
"dup": "jscpd src --threshold 1 && jscpd tests --threshold 3",
|
|
58
|
+
"knip": "knip",
|
|
59
|
+
"gen:client": "tsx scripts/gen-client.ts"
|
|
56
60
|
},
|
|
57
61
|
"dependencies": {
|
|
58
62
|
"commander": "15.0.0",
|
|
59
|
-
"elkjs": "0.12.
|
|
63
|
+
"elkjs": "0.12.1",
|
|
60
64
|
"picomatch": "4.0.7",
|
|
61
65
|
"yaml": "2.9.1",
|
|
62
66
|
"zod": "4.6.7"
|
|
@@ -67,6 +71,8 @@
|
|
|
67
71
|
"eslint": "^10.13.0",
|
|
68
72
|
"fast-check": "4.10.2",
|
|
69
73
|
"happy-dom": "21.0.4",
|
|
74
|
+
"jscpd": "5.4.2",
|
|
75
|
+
"knip": "6.44.1",
|
|
70
76
|
"tsup": "^9.0.0",
|
|
71
77
|
"tsx": "4.23.15",
|
|
72
78
|
"typescript": "^6.0.3",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: codechart
|
|
3
|
-
description: 'Use
|
|
3
|
+
description: 'Use this skill before you write any summary, wrap-up, PR description or plan of a code change, including your own final report after implementing something. Rule: finished a task that touched 3+ files or added branches, or about to plan one, or asked "what changed", "summarize the changes", "recap", "explain this diff/commit/branch", "write the PR description", "make a plan", "how would you implement", "show me the flow", "how does this work", "what are the edge cases"? Then run this skill FIRST and put its verified map or flow in your reply instead of a list of changed files. Skip only for a single-file text, comment, formatting, typo or version-bump change (look at the diff first).'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# codechart
|
|
@@ -9,6 +9,8 @@ Renders maps and flows from JSON specs you write, for a **plan** or **change sum
|
|
|
9
9
|
|
|
10
10
|
A flow the user asked for ("show me the flow"): skip step 1, write a flow spec without `rules` (`summary`, unchanged code `existing`), render as in step 2 with `--output both`.
|
|
11
11
|
|
|
12
|
+
The user asks why no map appeared: run `codechart doctor --last` and relay its output.
|
|
13
|
+
|
|
12
14
|
Skip it for a trivial change (see description), a question not about code changes or behaviour, or if the user said no diagram. If `codechart` is "not found", say once "the codechart CLI is not installed (`npm i -g codechart`), so no map" and go on; never install it.
|
|
13
15
|
|
|
14
16
|
## 1. Check
|
|
@@ -40,7 +42,7 @@ codechart render --md - <<'EOF'
|
|
|
40
42
|
EOF
|
|
41
43
|
```
|
|
42
44
|
|
|
43
|
-
For a change summary, add the same `--git`/`--since`/`--commit`/`--head` you gave `check`. Commit or branch not checked out: add `--at '<sha or branch>'` so anchors are read from it. On errors, fix the spec and rerun. A `✗` line is a claim that doesn't match the code: if your spec was wrong (status, path), fix it and rerender; if the change really differs from what you said, keep the `✗` and say so. Stderr `no map drawn`/`no flow drawn`: skip it silently. Rare cases: [spec-guide.md](spec-guide.md), [flow-guide.md](flow-guide.md), `codechart schema [--flow]`.
|
|
45
|
+
For a change summary, add the same `--git`/`--since`/`--commit`/`--head` you gave `check`. Commit or branch not checked out: add `--at '<sha or branch>'` so anchors are read from it. On errors, fix the spec and rerun. A `✗` line is a claim that doesn't match the code: if your spec was wrong (status, path), fix it and rerender; if the change really differs from what you said, keep the `✗` and say so. `✗ … not on map`: add a node or name the file in `omitted`. A summary footer saying `diff not checked`: you left out the flag, rerender with it. Stderr `no map drawn`/`no flow drawn`: skip it silently. Stderr `codechart <version> is available`: tell the user in one line at the end of your reply, once. Rare cases: [spec-guide.md](spec-guide.md), [flow-guide.md](flow-guide.md), `codechart schema [--flow]`.
|
|
44
46
|
|
|
45
47
|
### Flow (one behaviour each)
|
|
46
48
|
|
|
@@ -81,12 +83,12 @@ Draw only branches you saw in the code or (plan) will build; unverified ones go
|
|
|
81
83
|
"gaps": ["users: columns not read"] }
|
|
82
84
|
```
|
|
83
85
|
|
|
84
|
-
- One node per table, model, file, service or endpoint, never merged: `new`, `changed`, `removed`, `config` (config/env), `context` (untouched neighbour the reader needs). Under 15; tests and docs go in `omitted
|
|
86
|
+
- One node per table, model, file, service or endpoint, never merged: `new`, `changed`, `removed`, `config` (config/env), `context` (untouched neighbour the reader needs). Under 15; tests and docs go in `omitted`, naming each changed file by path, file name, `folder/` or glob (`"tests: test_teams.py"`); lockfiles and generated files need neither.
|
|
85
87
|
- Infrastructure: one node per resource, module or Kubernetes object, labelled as the code names it (`aws_s3_bucket.logs`, `module.vpc`, `Deployment api`), `kind` `other`, `path` the file that declares it; variables and values `config`; `terraform plan not run` goes in `gaps`. See [spec-guide.md](spec-guide.md#infrastructure).
|
|
86
88
|
- `layer` required, from a small set. `kind`: `table` `enum` `model` `service` `endpoint` `component` `file` (default with `path`) `config` `other`. Migration label: `migration: <what it does>`.
|
|
87
89
|
- `fields`: all you read, `change`: `added`/`removed`/`modified`; `fieldsComplete: true` only if you read the whole definition.
|
|
88
90
|
- Optional on a `new`/`changed` node with `path`: `match`, a distinctive piece of one line from the diff, as proof (shown in the HTML).
|
|
89
|
-
- Edges: dependent → dependency, labelled with the column, method or key; only ones you saw or will build. `kind`: `fk` `calls` `imports` `reads` `writes` `renders` `configures` `other`. Plan: a link moved between existing nodes gets `"change": "added"`/`"removed"`; a field whose type changes gets `was` (old type).
|
|
91
|
+
- Edges: dependent → dependency, labelled in plain words with the column, method or key (`team_id`, `additional_training (now a list)`), never pasted code (`_l(["rag"])` fails the render); only ones you saw or will build. `kind`: `fk` `calls` `imports` `reads` `writes` `renders` `configures` `other`. Plan: a link moved between existing nodes gets `"change": "added"`/`"removed"`; a field whose type changes gets `was` (old type).
|
|
90
92
|
- Context `short`: only what you read in this task, unread goes in `gaps`; `full`: also read the definitions of entities on the map.
|
|
91
93
|
|
|
92
94
|
## 3. Reply
|
|
@@ -96,3 +98,11 @@ Draw only branches you saw in the code or (plan) will build; unverified ones go
|
|
|
96
98
|
3. Prose: plan steps, tests, risks, open questions. The map replaces a list of changed files.
|
|
97
99
|
|
|
98
100
|
Every diagram in the reply is the exact text of one successful render: never typed, redrawn or edited by hand. Copy every character, line break and space, the key too (keep entries that don't apply, like `? planned`). Never re-wrap, trim, unescape or summarise, and add no `**Map**`/`**Flow**` line of your own. Looks wrong or render fails: fix the spec and rerender; if you can't, say there is no diagram.
|
|
101
|
+
|
|
102
|
+
## 4. PR or MR description
|
|
103
|
+
|
|
104
|
+
Writing or updating one for a change you mapped: check whether the repo redraws maps in CI (`grep -rls 'pr-sync' .github/workflows .gitlab-ci.yml`).
|
|
105
|
+
- Found: render the summary map spec again with the same diff flags and `--pr` instead of `--md` (`codechart render --pr - <<'EOF'`), and paste the printed section verbatim at the end of the description, from `<!-- codechart:start -->` to `<!-- codechart:end -->`. CI publishes the image and redraws the section on every push, so its image link starts as a placeholder. To change the map later, render again and replace that whole section; never edit inside it.
|
|
106
|
+
- Not found: paste the `--md` map as in step 3, and once per conversation add one line to your reply (not the description): "codechart can keep this map current in the PR: ask me to set up PR maps."
|
|
107
|
+
|
|
108
|
+
`--pr` draws maps only: a flow goes in as its `--md` text. Never put a plan's Now/After map in a PR. The user asks to set up PR maps: follow [pr-maps.md](pr-maps.md).
|
|
@@ -9,12 +9,10 @@ $ git diff '9c1e2a0..HEAD'; codechart check --since '9c1e2a0'
|
|
|
9
9
|
<the diff>
|
|
10
10
|
{
|
|
11
11
|
"pathMatches": [
|
|
12
|
-
{
|
|
13
|
-
|
|
14
|
-
{ "rule": "orm-schema", "diagram": "map", "output": "auto", "context": "short",
|
|
15
|
-
"files": ["app/models/team.py"] }
|
|
12
|
+
{"rule":"migrations","diagram":"map","output":"auto","context":"short","files":["migrations/versions/7f3d_add_teams.py"]},
|
|
13
|
+
{"rule":"orm-schema","diagram":"map","output":"auto","context":"short","files":["app/models/team.py"]}
|
|
16
14
|
],
|
|
17
|
-
"judgeBuiltins": ["related-files",
|
|
15
|
+
"judgeBuiltins": ["related-files","behaviour-flow"]
|
|
18
16
|
}
|
|
19
17
|
```
|
|
20
18
|
|
|
@@ -14,7 +14,7 @@ An invented branch is the worst failure: it destroys the user's trust in the too
|
|
|
14
14
|
## Steps
|
|
15
15
|
|
|
16
16
|
- `type`: `step` (does something), `decision` (a question the code branches on, label ends in `?`), `end` (returns, raises, exits). Leave it out and it is inferred from the outgoing links: none → `end`, one → `step`, two or more → `decision`. A label ending in `?` with fewer than 2 links fails the render. `diagram: "flow"` is inferred from `steps` too.
|
|
17
|
-
- `label`: verb + object, aim for 30 characters or fewer (`look up invite by token`, `expired?`), not a sentence or a function name. Longer labels are cut at the terminal width; details belong in your prose or the anchored code. One action per step: ` / ` or ` + ` fails validation.
|
|
17
|
+
- `label`: verb + object, aim for 30 characters or fewer (`look up invite by token`, `expired?`), not a sentence or a function name. Longer labels are cut at the terminal width; details belong in your prose or the anchored code. One action per step: ` / ` or ` + ` fails validation. Step and link labels are plain words, never code: quotes, a call with arguments, `[...]` with something inside, `=` or `...` fails validation (`reads as code`); rename it and render again.
|
|
18
18
|
- **No hidden decisions:** a label with "if", "else", "or" or `;` hides a branch. Make it a decision with labelled branches, or put it in `gaps` if you didn't verify it.
|
|
19
19
|
- Decision labels are unique: one decision per question; if two really differ, say how (`map spec?`, `flow anchors valid?`).
|
|
20
20
|
- `start`: the id of the first step.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Setting up PR maps
|
|
2
|
+
|
|
3
|
+
Only when the user asks for it ("set up codechart PR maps", "keep the map in my PRs current"). Never set this up on your own: it adds a CI file to their repo.
|
|
4
|
+
|
|
5
|
+
1. From the repo root, run `codechart setup-pr-maps` (no `--yes`). It changes nothing: it prints the file it would add (or the job it would append to `.gitlab-ci.yml`), the token it uses and what runs on each push.
|
|
6
|
+
2. Show the user that plan in full and ask whether to go ahead, and how:
|
|
7
|
+
- write the file into their work tree, uncommitted (`codechart setup-pr-maps --yes`), for them to review and commit;
|
|
8
|
+
- or open a pull/merge request with it (`codechart setup-pr-maps --yes --pr`, needs `gh` or `glab` signed in), which they merge to turn it on or close to say no.
|
|
9
|
+
3. Run what they chose. Never commit or push the file yourself unless they ask.
|
|
10
|
+
4. GitLab: the job needs a masked CI/CD variable `CODECHART_GITLAB_TOKEN`. Give the user the two links the command printed (create an access token with `api` scope, then add it under Settings > CI/CD > Variables). Never ask for the token or set it yourself.
|
|
11
|
+
5. Say what happens next: from then on, PR/MR descriptions you write for a mapped change get the map section (SKILL.md step 4), and CI redraws it on every push.
|
|
12
|
+
|
|
13
|
+
Output `PR maps are already set up`: tell the user, nothing to do. `can't tell whether … is GitHub or GitLab`: ask which, then add `--host github` or `--host gitlab`. `… already exists and is not codechart's`: show the message; the user sets it up by hand: https://github.com/freeleex/codechart/blob/main/docs/pr-maps.md#by-hand
|
|
@@ -23,7 +23,7 @@ Rules:
|
|
|
23
23
|
{ "id": "legacy-roles", "label": "legacy_roles", "kind": "table", "status": "removed", "layer": "database" }
|
|
24
24
|
```
|
|
25
25
|
with `users` as `changed` (its `legacy_role_id` field `"change": "removed"`) and the old edge `users → legacy-roles` kept.
|
|
26
|
-
- Leave out tests, docs and lock files; list them in `omitted` instead (`"tests: test_teams.py"`).
|
|
26
|
+
- Leave out tests, docs and lock files; list them in `omitted` instead (`"tests: test_teams.py"`). With a diff flag, `render` flags every changed file that no node's `path` covers (a folder path covers the files under it) and no `omitted` entry names by repo path, file name, `folder/` or glob. Lockfiles, generated files and files a map rule sends to output `none` are never flagged.
|
|
27
27
|
- Don't add a node you can't describe from what you read. Put it in `gaps`.
|
|
28
28
|
- In a plan, name files the repo's way (look at neighbouring files for naming and numbering); they are shown as `new`.
|
|
29
29
|
- Aim for under 15 nodes. More than that: drop the least connected `context` nodes and mention them in `omitted`.
|
|
@@ -101,7 +101,7 @@ Warnings, not failures (`--strict` makes them exit 1). Each mismatch is named in
|
|
|
101
101
|
```
|
|
102
102
|
|
|
103
103
|
- Direction: from the thing that depends to the thing it depends on (FK holder → referenced table; caller → callee; reader → config).
|
|
104
|
-
- `label`: the column, method or key that makes the link (`team_id`, `list_projects()`, `reads DEFAULT_CURRENCY`). Short.
|
|
104
|
+
- `label`: the column, method or key that makes the link, in plain words (`team_id`, `list_projects()`, `reads DEFAULT_CURRENCY`, `additional_training (now a list)`). Short. Never a code expression from the diff: a node or edge label with quotes, a call with arguments, `[...]` with something inside, `=` or `...` fails validation (`reads as code`); rename it and render again.
|
|
105
105
|
- `kind`: fk, calls, imports, reads, writes, renders, configures, other. Use `writes` for a migration that creates or alters a table, and `other` for a model's `maps` edge to its table.
|
|
106
106
|
- Only edges you saw in code, or (in a plan) ones you are committing to build.
|
|
107
107
|
- In a plan, `change` marks a link that moves between nodes existing before and after: `"added"` for one the plan builds, `"removed"` for one it drops. Leave it out on edges to a `new` or `removed` node; their status already says it. The HTML then shows the plan as Now and After side by side.
|
package/templates/codechart.yaml
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
# minNodes: 8 # auto output: write HTML from this many nodes on, or when the map cuts text
|
|
14
14
|
# Only in ~/.config/codechart/config.yaml (ignored here): web: outDir: ~/.cache/codechart (relative to home), keep: 20, maxAgeDays: 7 (HTML cleanup),
|
|
15
15
|
# open: auto (auto | always | never; auto opens new HTML in your browser inside VS Code-based editors, whose links show the source)
|
|
16
|
+
# Also global only: updateCheck: true (look up the newest codechart on npm at most once a day; false turns it off)
|
|
16
17
|
|
|
17
18
|
# useBuiltinRules: true # common migration and model paths, "more than 2 changed files depend on each other", and behaviour-flow
|
|
18
19
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# codechart PR maps (written by `codechart setup-pr-maps`, or copy to .github/workflows/codechart.yml).
|
|
2
|
+
# On every push to a PR, redraws the codechart map in its description against the PR's latest commits.
|
|
3
|
+
# Does nothing for PRs without a codechart section.
|
|
4
|
+
name: codechart map
|
|
5
|
+
on:
|
|
6
|
+
pull_request:
|
|
7
|
+
types: [opened, synchronize, reopened]
|
|
8
|
+
# A newer push cancels the run still drawing the older one; pr-sync also skips saving if the PR moved on.
|
|
9
|
+
concurrency:
|
|
10
|
+
group: codechart-map-${{ github.event.pull_request.number }}
|
|
11
|
+
cancel-in-progress: true
|
|
12
|
+
permissions:
|
|
13
|
+
contents: write # pushes the map image to refs/codechart/pr-<n>, not to a branch
|
|
14
|
+
pull-requests: write
|
|
15
|
+
jobs:
|
|
16
|
+
map:
|
|
17
|
+
# A fork's token is read-only: it can neither push the image nor edit the PR.
|
|
18
|
+
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
19
|
+
runs-on: ubuntu-latest
|
|
20
|
+
steps:
|
|
21
|
+
- uses: actions/checkout@v5
|
|
22
|
+
with:
|
|
23
|
+
fetch-depth: 0
|
|
24
|
+
- uses: actions/setup-node@v5
|
|
25
|
+
with:
|
|
26
|
+
node-version: 22
|
|
27
|
+
- run: npx --yes codechart@latest pr-sync
|
|
28
|
+
env:
|
|
29
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# codechart PR maps (added by `codechart setup-pr-maps`, or add it to .gitlab-ci.yml yourself).
|
|
2
|
+
# On every push to an MR, redraws the codechart map in its description against the MR's latest commits.
|
|
3
|
+
# Does nothing for MRs without a codechart section.
|
|
4
|
+
# Needs a masked CI/CD variable CODECHART_GITLAB_TOKEN: an access token with api scope and at least
|
|
5
|
+
# Developer role (CI_JOB_TOKEN can't edit MRs or upload files).
|
|
6
|
+
codechart-map:
|
|
7
|
+
image: node:22
|
|
8
|
+
# A newer pipeline cancels this one (with "Auto-cancel redundant pipelines", on by default); pr-sync also skips saving if the MR moved on.
|
|
9
|
+
interruptible: true
|
|
10
|
+
variables:
|
|
11
|
+
GIT_DEPTH: 0
|
|
12
|
+
rules:
|
|
13
|
+
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CODECHART_GITLAB_TOKEN
|
|
14
|
+
script:
|
|
15
|
+
- npx --yes codechart@latest pr-sync
|