zevqi 0.0.0-stage → 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.
@@ -0,0 +1,145 @@
1
+ import fs from "node:fs";
2
+ import { apiKey, ensureGitignore, globalConfigPath, loadGlobal, loadProject, projectDir, providerOf, saveGlobal, saveProject } from "../config.js";
3
+ import { agentBlockInstalled, installAgentBlock, removeAgentBlock } from "../agents.js";
4
+ import { repoRoot } from "../git.js";
5
+ import { hooksInstalled, installHooks, settingsPath, uninstallHooks } from "../hooks.js";
6
+ import { aiDisclosure, askLine, c, fail, mask, readSecret } from "../util.js";
7
+ import { emit, flagStr, needEnabled, needRoot } from "../context.js";
8
+ const scopeOf = (ctx) => (ctx.flags.global ? "global" : ctx.flags.shared ? "shared" : "local");
9
+ const GATES = ["off", "warn", "block"];
10
+ export const init = {
11
+ name: "init",
12
+ group: "Setup",
13
+ summary: "Turn Zevqi on in this repo (installs the Claude Code hooks)",
14
+ usage: "zevqi init [--shared | --global] [--gate off|warn|block] [--agents | --no-agents] [--no-prompt | --yes]",
15
+ examples: ["zevqi init", "zevqi init --shared --gate block"],
16
+ async run(ctx) {
17
+ const root = needRoot();
18
+ const gate = flagStr(ctx.flags.gate);
19
+ if (gate && !GATES.includes(gate))
20
+ fail(`--gate must be one of: ${GATES.join(", ")}`, 2);
21
+ const existing = loadProject(root);
22
+ if (!existing.aiNotice) {
23
+ console.log(c.bold(aiDisclosure(providerOf(loadGlobal()), existing.maxFiles, Boolean(apiKey(loadGlobal())))) + "\n");
24
+ // Only a configured model key sends anything to a provider, so only then is a confirmation needed.
25
+ if (apiKey(loadGlobal()) && process.stdin.isTTY && !ctx.flags["no-prompt"] && !ctx.flags.yes) {
26
+ const answer = await askLine("Continue? [Y/n] ");
27
+ if (/^n/i.test(answer.trim()))
28
+ fail("Nothing was installed.", 1, "Run zevqi init again when you are ready.");
29
+ }
30
+ }
31
+ saveProject(root, { ...existing, ...(gate ? { gate: gate } : {}), aiNotice: existing.aiNotice ?? new Date().toISOString() });
32
+ ensureGitignore(root);
33
+ const file = installHooks(root, scopeOf(ctx), ctx.cliPath);
34
+ console.log(`${c.green("✓")} Zevqi is on. Hooks added to ${c.dim(file)}`);
35
+ if (!apiKey(loadGlobal())) {
36
+ if (process.stdin.isTTY && !ctx.flags["no-prompt"]) {
37
+ console.log("\nzlearn uses your own model key. It is stored on this machine only (owner-readable file).");
38
+ const key = await readSecret("Paste your API key (input hidden, Enter to skip): ");
39
+ if (key) {
40
+ saveGlobal({ ...loadGlobal(), apiKey: key });
41
+ console.log(`${c.green("✓")} Saved ${c.dim(mask(key))} to ${c.dim(globalConfigPath())}`);
42
+ }
43
+ }
44
+ }
45
+ // No key (or --agents): let the coding agent that wrote the change write the lesson too. Works with Codex, Cursor and Claude Code.
46
+ if (ctx.flags.agents || (!apiKey(loadGlobal()) && !ctx.flags["no-agents"])) {
47
+ const r = installAgentBlock(root);
48
+ console.log(`${c.green("✓")} Your coding agent will write the lessons, so no API key is needed. Instructions ${r.agentsMd} in ${c.dim("AGENTS.md")}${r.claudeMd !== "none" ? `, import ${r.claudeMd} in ${c.dim("CLAUDE.md")}` : ""}.`);
49
+ console.log(c.dim("Commit those files so every agent on the project sees them. Works with Codex, Cursor and Claude Code. Prefer Zevqi to explain changes itself? Run: zevqi config set apiKey"));
50
+ console.log(c.dim("Also no key needed: zevqi scan (who holds the knowledge of each file, from git) and zevqi review <file> (you describe a change in your own words)."));
51
+ }
52
+ console.log(c.dim("\nRestart Claude Code (or open /hooks) so it picks up the hooks. After your agent finishes a turn, run: zevqi learn"));
53
+ },
54
+ };
55
+ export const uninstall = {
56
+ name: "uninstall",
57
+ group: "Setup",
58
+ summary: "Remove the hooks (your lessons stay in .zlearn/)",
59
+ usage: "zevqi uninstall [--shared | --global]",
60
+ run(ctx) {
61
+ const root = needRoot();
62
+ const file = uninstallHooks(root, scopeOf(ctx));
63
+ const removed = removeAgentBlock(root);
64
+ console.log(`Removed zevqi hooks from ${file}${removed.agentsMd ? ", and the lesson instructions from AGENTS.md" : ""}. Your lessons stay in ${projectDir(root)}.`);
65
+ },
66
+ };
67
+ export const gate = {
68
+ name: "gate",
69
+ group: "Daily use",
70
+ summary: "What happens when you commit with un-reviewed AI changes",
71
+ usage: "zevqi gate <off|warn|block>",
72
+ examples: ["zevqi gate warn"],
73
+ run(ctx) {
74
+ const root = needEnabled();
75
+ const mode = ctx.args[0];
76
+ if (!GATES.includes(mode))
77
+ fail("Use: zevqi gate off|warn|block", 2);
78
+ saveProject(root, { ...loadProject(root), gate: mode });
79
+ console.log(`Commit gate: ${c.bold(mode)}`);
80
+ },
81
+ };
82
+ export const config = {
83
+ name: "config",
84
+ group: "Setup",
85
+ summary: "Show or change settings (API key, provider, model)",
86
+ usage: "zevqi config show | zevqi config set <apiKey|provider|model|baseUrl> [value]",
87
+ examples: ["zevqi config show", "zevqi config set apiKey # prompts, input hidden", "zevqi config set model claude-haiku-4-5-20251001"],
88
+ async run(ctx) {
89
+ const cfg = loadGlobal();
90
+ const [sub, key, value] = ctx.args;
91
+ if (!sub || sub === "show") {
92
+ const k = apiKey(cfg);
93
+ const view = { provider: providerOf(cfg), model: cfg.model ?? "(default)", baseUrl: cfg.baseUrl ?? "(default)", apiKey: mask(k), team: cfg.team ? { server: cfg.team.server, email: cfg.team.email } : null, file: globalConfigPath() };
94
+ return void console.log(JSON.stringify(view, null, 2));
95
+ }
96
+ if (sub === "set" && key) {
97
+ if (!["apiKey", "provider", "model", "baseUrl"].includes(key))
98
+ fail("Settable keys: apiKey, provider, model, baseUrl", 2);
99
+ let v = value;
100
+ if (!v && key === "apiKey")
101
+ v = await readSecret("API key (input hidden): ");
102
+ if (!v)
103
+ fail(`Give a value: zevqi config set ${key} <value>`, 2);
104
+ if (key === "provider" && !["anthropic", "openai"].includes(v))
105
+ fail("provider must be anthropic or openai", 2);
106
+ cfg[key] = v;
107
+ saveGlobal(cfg);
108
+ console.log(`${c.green("✓")} Saved ${key}${key === "apiKey" ? ` (${mask(v)})` : ""}.`);
109
+ return;
110
+ }
111
+ fail("Usage: zevqi config show | zevqi config set <key> [value]", 2);
112
+ },
113
+ };
114
+ export const doctor = {
115
+ name: "doctor",
116
+ group: "Setup",
117
+ summary: "Check that everything is wired up",
118
+ usage: "zevqi doctor [--json]",
119
+ run(ctx) {
120
+ const root = repoRoot(process.cwd());
121
+ const cfg = loadGlobal();
122
+ const checks = [];
123
+ const add = (ok, label, fix) => checks.push({ ok, label, fix });
124
+ add(Number(process.versions.node.split(".")[0]) >= 20, `Node ${process.versions.node}`, "Node 20 or newer is required");
125
+ add(Boolean(root), "Inside a git repository", "run this in your project");
126
+ if (root) {
127
+ add(fs.existsSync(projectDir(root)), "Zevqi enabled in this repo", "zevqi init");
128
+ const where = hooksInstalled(root);
129
+ add(where.length > 0, `Claude Code hooks installed${where.length ? ` (${where.join(", ")})` : ""}`, "zevqi init");
130
+ }
131
+ const agentMode = Boolean(root && agentBlockInstalled(root));
132
+ // A key is optional: scan, attested review and agent-written lessons all work without one.
133
+ add(true, apiKey(cfg) ? `API key found (${providerOf(cfg)}), so Zevqi can write questions itself` : agentMode ? "No API key: your coding agent writes lessons (AGENTS.md instructions installed)" : "No API key: zevqi scan and zevqi review work without one (add a key for AI-written questions)");
134
+ add(true, cfg.team ? `Team: ${cfg.team.server}` : "Team: not connected (optional)");
135
+ emit(ctx, { ok: checks.every((x) => x.ok), checks }, () => {
136
+ for (const x of checks)
137
+ console.log(`${x.ok ? c.green("✓") : c.red("✗")} ${x.label}${x.ok || !x.fix ? "" : c.dim(` → ${x.fix}`)}`);
138
+ if (root)
139
+ for (const s of hooksInstalled(root))
140
+ console.log(c.dim(` ${settingsPath(root, s)}`));
141
+ });
142
+ if (checks.some((x) => !x.ok))
143
+ process.exitCode = 1;
144
+ },
145
+ };
@@ -0,0 +1,76 @@
1
+ import { loadGlobal, loadProject } from "../config.js";
2
+ import { listLessons } from "../lessons.js";
3
+ import { checkTeamKey, createTeam, joinTeam, leaveTeam, pushRecords, teamSummary, toRecord } from "../team.js";
4
+ import { c, fail } from "../util.js";
5
+ import { emit, flagStr, needEnabled } from "../context.js";
6
+ const server = (flags) => flagStr(flags.server) ?? loadGlobal().team?.server ?? "https://zevqi.com";
7
+ export const team = {
8
+ name: "team",
9
+ group: "Teams",
10
+ summary: "Share scores with your team (create, join, status, sync, leave)",
11
+ usage: [
12
+ "zevqi team join --server <url> --key <teamKey> --email <you> [--name <you>]",
13
+ "zevqi team status [--json]",
14
+ "zevqi team sync | leave",
15
+ "zevqi team create --server <url> --name <team> [--secret <s>] (self-hosted servers)",
16
+ ].join("\n "),
17
+ examples: ["zevqi team join --server https://zevqi.com --key zlt_… --email you@company.com"],
18
+ async run(ctx) {
19
+ const sub = ctx.args[0];
20
+ const url = server(ctx.flags);
21
+ if (sub === "create") {
22
+ const name = flagStr(ctx.flags.name);
23
+ if (!name)
24
+ fail("Usage: zevqi team create --server <url> --name <team> [--secret <s>]", 2);
25
+ const res = await createTeam(url, name, flagStr(ctx.flags.secret)).catch((e) => fail(e.message));
26
+ console.log(c.green("Team created."));
27
+ console.log(` Team key (share with teammates, keep private): ${c.bold(res.teamKey)}`);
28
+ console.log(` Dashboard (admins only): ${c.cyan(res.dashboardUrl)}`);
29
+ console.log(c.dim(` Teammates join with: zevqi team join --server ${url} --key ${res.teamKey} --email <their email>`));
30
+ return;
31
+ }
32
+ if (sub === "join") {
33
+ const key = flagStr(ctx.flags.key);
34
+ const email = flagStr(ctx.flags.email);
35
+ if (!key || !email)
36
+ fail("Usage: zevqi team join --server <url> --key <teamKey> --email <you> [--name <you>]", 2);
37
+ const check = await checkTeamKey(url, key);
38
+ if (!check.ok && check.reason === "invalid")
39
+ fail(check.message, 1, "Nothing was saved.");
40
+ joinTeam(url, key, email, flagStr(ctx.flags.name));
41
+ if (check.ok) {
42
+ console.log(`${c.green("✓")} Joined ${check.teamName ? c.bold(check.teamName) : "the team"}. Results sync to ${url}. By default only scores and file names are shared, never code.`);
43
+ console.log(c.dim(`Next: zevqi scan (maps who holds the knowledge of each file) or zevqi setup (does it all in this repo).`));
44
+ }
45
+ else
46
+ console.log(`${c.yellow("!")} Saved, but could not reach ${url} just now (${check.message}). Lessons will queue locally and sync later.`);
47
+ return;
48
+ }
49
+ if (sub === "leave") {
50
+ leaveTeam();
51
+ console.log("Left the team on this machine.");
52
+ return;
53
+ }
54
+ if (sub === "sync") {
55
+ const root = needEnabled();
56
+ const cfg = loadProject(root);
57
+ const r = await pushRecords(listLessons(root).map((l) => toRecord(l, cfg.share)));
58
+ if (r.error)
59
+ fail(`Sync failed: ${r.error}`);
60
+ console.log(`${c.green("✓")} Synced ${r.sent} lesson${r.sent === 1 ? "" : "s"}.`);
61
+ return;
62
+ }
63
+ if (sub === "status") {
64
+ const s = await teamSummary().catch((e) => fail(e.message));
65
+ emit(ctx, s, () => {
66
+ console.log(c.bold(s.team?.name ?? "Team"));
67
+ for (const m of s.members ?? [])
68
+ console.log(` ${String(m.email).padEnd(30)} ${m.passed} passed · ${m.pending} waiting · ${m.passRate}% pass rate`);
69
+ if (s.blindSpots?.length)
70
+ console.log(c.yellow("Blind spots (changed by AI, nobody has passed a lesson on them): ") + s.blindSpots.slice(0, 8).map((b) => b.path).join(", "));
71
+ });
72
+ return;
73
+ }
74
+ fail("Usage: zevqi team create|join|status|sync|leave", 2);
75
+ },
76
+ };
@@ -0,0 +1,53 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { readJson, writeJson } from "./util.js";
5
+ import { envVar } from "./env.js";
6
+ export const DEFAULT_PROJECT = { gate: "warn", share: "scores", passRatio: 2 / 3, maxFiles: 12 };
7
+ export function globalDir() {
8
+ return envVar("HOME") || path.join(os.homedir(), ".zlearn");
9
+ }
10
+ export function globalConfigPath() {
11
+ return path.join(globalDir(), "config.json");
12
+ }
13
+ export function loadGlobal() {
14
+ return readJson(globalConfigPath(), {});
15
+ }
16
+ export function saveGlobal(cfg) {
17
+ writeJson(globalConfigPath(), cfg, 0o600);
18
+ }
19
+ export function projectDir(root) {
20
+ return path.join(root, ".zlearn");
21
+ }
22
+ export function loadProject(root) {
23
+ return { ...DEFAULT_PROJECT, ...readJson(path.join(projectDir(root), "config.json"), {}) };
24
+ }
25
+ export function saveProject(root, cfg) {
26
+ writeJson(path.join(projectDir(root), "config.json"), cfg);
27
+ }
28
+ export function apiKey(cfg) {
29
+ return envVar("API_KEY") || (cfg.provider === "openai" ? process.env.OPENAI_API_KEY : process.env.ANTHROPIC_API_KEY) || cfg.apiKey || process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY;
30
+ }
31
+ export function providerOf(cfg) {
32
+ if (cfg.provider)
33
+ return cfg.provider;
34
+ if (envVar("PROVIDER") === "openai")
35
+ return "openai";
36
+ if (!process.env.ANTHROPIC_API_KEY && process.env.OPENAI_API_KEY)
37
+ return "openai";
38
+ return "anthropic";
39
+ }
40
+ export function ensureGitignore(root) {
41
+ const file = path.join(root, ".gitignore");
42
+ const line = ".zlearn/";
43
+ let text = "";
44
+ try {
45
+ text = fs.readFileSync(file, "utf8");
46
+ }
47
+ catch {
48
+ // no .gitignore yet
49
+ }
50
+ if (!text.split(/\r?\n/).some((l) => l.trim() === line || l.trim() === ".zlearn")) {
51
+ fs.writeFileSync(file, text + (text && !text.endsWith("\n") ? "\n" : "") + line + "\n");
52
+ }
53
+ }
@@ -0,0 +1,32 @@
1
+ import fs from "node:fs";
2
+ import { apiKey, loadProject, projectDir, providerOf, loadGlobal, saveProject } from "./config.js";
3
+ import { repoRoot } from "./git.js";
4
+ import { aiDisclosure, c, fail } from "./util.js";
5
+ export const flagStr = (v) => (typeof v === "string" ? v : undefined);
6
+ export function needRoot() {
7
+ const root = repoRoot(process.cwd());
8
+ if (!root)
9
+ fail("Run this inside a git repository.", 2, "cd into your project first.");
10
+ return root;
11
+ }
12
+ export function needEnabled() {
13
+ const root = needRoot();
14
+ if (!fs.existsSync(projectDir(root)))
15
+ fail("Zevqi is not enabled here yet.", 2, "Run: zevqi init");
16
+ return root;
17
+ }
18
+ /** Print machine-readable JSON when `--json` is set, otherwise run the human renderer. */
19
+ export function emit(ctx, data, human) {
20
+ if (ctx.json)
21
+ console.log(JSON.stringify(data, null, 2));
22
+ else
23
+ human();
24
+ }
25
+ /** Installs from before the disclosure existed see it once, then it is recorded. Never blocks. */
26
+ export function ensureAiNotice(root) {
27
+ const cfg = loadProject(root);
28
+ if (cfg.aiNotice)
29
+ return;
30
+ console.log(c.dim(aiDisclosure(providerOf(loadGlobal()), cfg.maxFiles, Boolean(apiKey(loadGlobal())))) + "\n");
31
+ saveProject(root, { ...cfg, aiNotice: new Date().toISOString() });
32
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Reads a setting named ZEVQI_<NAME>, falling back to the older ZLEARN_<NAME>, so setups made before the rename keep working.
3
+ */
4
+ export const envVar = (name) => process.env[`ZEVQI_${name}`] || process.env[`ZLEARN_${name}`] || undefined;
@@ -0,0 +1,229 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { toPosix } from "./util.js";
5
+ function git(cwd, args) {
6
+ return execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 32 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
7
+ }
8
+ /**
9
+ * The real, canonical form of a path: resolves symlinks, Windows 8.3 short names (RUNNER~1) and case differences.
10
+ * Works for files that do not exist yet (a new file the agent is about to write) by canonicalising the nearest existing parent.
11
+ * Used so an edited file can always be matched to the repository root that git reports.
12
+ */
13
+ export function canonicalPath(p) {
14
+ const abs = path.resolve(p);
15
+ try {
16
+ return fs.realpathSync.native(abs);
17
+ }
18
+ catch {
19
+ const parent = path.dirname(abs);
20
+ if (parent === abs)
21
+ return abs;
22
+ return path.join(canonicalPath(parent), path.basename(abs));
23
+ }
24
+ }
25
+ export function repoRoot(cwd) {
26
+ try {
27
+ return path.resolve(git(cwd, ["rev-parse", "--show-toplevel"]).trim());
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ export function repoName(root) {
34
+ try {
35
+ const url = git(root, ["config", "--get", "remote.origin.url"]).trim();
36
+ const m = url.match(/([^/:]+\/[^/]+?)(?:\.git)?$/);
37
+ if (m)
38
+ return m[1];
39
+ }
40
+ catch {
41
+ // no remote
42
+ }
43
+ return path.basename(root);
44
+ }
45
+ export function hasHead(root) {
46
+ try {
47
+ git(root, ["rev-parse", "--verify", "HEAD"]);
48
+ return true;
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ const PER_FILE = 12_000;
55
+ const TOTAL = 60_000;
56
+ /** Unified diff of the given files against HEAD; untracked files are included as additions. Truncated for the AI call. */
57
+ export function diffForFiles(root, files) {
58
+ let total = 0;
59
+ const parts = [];
60
+ const included = [];
61
+ const head = hasHead(root);
62
+ for (const file of files) {
63
+ if (total >= TOTAL)
64
+ break;
65
+ const rel = toPosix(path.relative(root, path.resolve(root, file)));
66
+ if (rel.startsWith(".."))
67
+ continue;
68
+ let chunk = "";
69
+ try {
70
+ chunk = head ? git(root, ["diff", "HEAD", "--", rel]) : git(root, ["diff", "--cached", "--", rel]);
71
+ }
72
+ catch {
73
+ chunk = "";
74
+ }
75
+ if (!chunk.trim()) {
76
+ // untracked or already committed: show current content as an addition
77
+ try {
78
+ const abs = path.join(root, rel);
79
+ const stat = fs.statSync(abs);
80
+ if (stat.isFile() && stat.size < 2_000_000) {
81
+ const body = fs.readFileSync(abs, "utf8");
82
+ if (!body.includes("\u0000"))
83
+ chunk = `diff --git a/${rel} b/${rel}\nnew file\n--- /dev/null\n+++ b/${rel}\n` + body.split("\n").map((l) => "+" + l).join("\n");
84
+ }
85
+ }
86
+ catch {
87
+ chunk = "";
88
+ }
89
+ }
90
+ if (!chunk.trim())
91
+ continue;
92
+ if (chunk.length > PER_FILE)
93
+ chunk = chunk.slice(0, PER_FILE) + "\n[... truncated ...]\n";
94
+ parts.push(chunk);
95
+ included.push(rel);
96
+ total += chunk.length;
97
+ }
98
+ return { text: parts.join("\n"), included };
99
+ }
100
+ /**
101
+ * Content fingerprint (git blob hash, 12 hex characters) of each file as it is on disk right now. The team server compares these
102
+ * to learn whether a file changed after someone reviewed it. Unreadable or deleted files are left out.
103
+ */
104
+ export function fileRevs(root, files) {
105
+ const out = {};
106
+ for (const f of files) {
107
+ try {
108
+ const h = git(root, ["hash-object", "--", f]).trim();
109
+ if (/^[a-f0-9]{40,64}$/.test(h))
110
+ out[f] = h.slice(0, 12);
111
+ }
112
+ catch {
113
+ // deleted or unreadable: no fingerprint
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+ /**
119
+ * The recent history of some files as patches: the last `commits` commits that touched each file, plus any uncommitted change.
120
+ * Used by `zevqi review`, so a developer can understand changes they did not write (or wrote long ago). Truncated for the AI call.
121
+ */
122
+ export function diffForHistory(root, files, commits = 5) {
123
+ const parts = [];
124
+ const included = [];
125
+ let total = 0;
126
+ for (const file of files) {
127
+ if (total >= TOTAL)
128
+ break;
129
+ const rel = toPosix(path.relative(root, path.resolve(root, file)));
130
+ if (rel.startsWith(".."))
131
+ continue;
132
+ let chunk = "";
133
+ try {
134
+ if (hasHead(root))
135
+ chunk += git(root, ["diff", "HEAD", "--", rel]);
136
+ }
137
+ catch {
138
+ // ignore
139
+ }
140
+ try {
141
+ chunk += git(root, ["log", "-p", "--no-color", `-n${commits}`, "--format=commit %h %an: %s", "--", rel]);
142
+ }
143
+ catch {
144
+ // ignore
145
+ }
146
+ if (!chunk.trim())
147
+ continue;
148
+ if (chunk.length > PER_FILE * 2)
149
+ chunk = chunk.slice(0, PER_FILE * 2) + "\n[... truncated ...]\n";
150
+ parts.push(`### ${rel}\n${chunk}`);
151
+ included.push(rel);
152
+ total += chunk.length;
153
+ }
154
+ return { text: parts.join("\n"), included };
155
+ }
156
+ /** Raw history for `zevqi scan`: one record per non-merge commit with its author, date, subject, body and changed files. */
157
+ export function scanLog(root, months = 12, maxCommits = 30000) {
158
+ try {
159
+ return git(root, ["-c", "core.quotepath=off", "log", "--no-merges", `--since=${months}.months`, `-n${maxCommits}`, "--name-only", "--format=%x1e%H%x1f%an%x1f%ae%x1f%aI%x1f%s%x1f%b%x1f"]);
160
+ }
161
+ catch {
162
+ return "";
163
+ }
164
+ }
165
+ /** Files in the repository right now (tracked by git), so a scan ignores files that were deleted or renamed away. */
166
+ export function trackedFiles(root) {
167
+ try {
168
+ return new Set(git(root, ["-c", "core.quotepath=off", "ls-files"]).split("\n").map((l) => l.trim()).filter(Boolean).map(toPosix));
169
+ }
170
+ catch {
171
+ return null;
172
+ }
173
+ }
174
+ /** Files touched by one commit (default HEAD). Empty when the ref does not exist or the repository has no commits. */
175
+ export function filesInCommit(root, ref = "HEAD") {
176
+ if (!/^[A-Za-z0-9._\/~^@{}-]{1,100}$/.test(ref))
177
+ return [];
178
+ try {
179
+ return git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "--root", ref]).split("\n").map((l) => l.trim()).filter(Boolean).map(toPosix);
180
+ }
181
+ catch {
182
+ return [];
183
+ }
184
+ }
185
+ /** Files with uncommitted changes (modified, staged or untracked), for a manual `zevqi explain`. */
186
+ export function changedFiles(root) {
187
+ const out = new Set();
188
+ const run = (args) => {
189
+ try {
190
+ for (const line of git(root, args).split("\n"))
191
+ if (line.trim())
192
+ out.add(toPosix(line.trim()));
193
+ }
194
+ catch {
195
+ // ignore
196
+ }
197
+ };
198
+ if (hasHead(root))
199
+ run(["diff", "--name-only", "HEAD"]);
200
+ run(["ls-files", "--others", "--exclude-standard"]);
201
+ return [...out].filter((f) => !f.startsWith(".zlearn/") && !f.startsWith(".claude/"));
202
+ }
203
+ /** Distinct committers (by name and email) on the current branch in the last N days. 0 if git cannot say. */
204
+ export function contributorCount(root, days = 90) {
205
+ try {
206
+ const out = git(root, ["shortlog", "-sne", "HEAD", `--since=${days}.days`]);
207
+ return out.split("\n").filter((l) => l.trim()).length;
208
+ }
209
+ catch {
210
+ return 0;
211
+ }
212
+ }
213
+ /**
214
+ * Files changed on this branch compared with a base ref (merge-base diff, like a pull request shows).
215
+ * Falls back through origin/main, main and the previous commit so it works in most CI checkouts.
216
+ */
217
+ export function changedSince(root, base) {
218
+ const candidates = [base, "origin/main", "origin/master", "main", "master", "HEAD~1"].filter((b) => Boolean(b));
219
+ for (const ref of candidates) {
220
+ try {
221
+ const out = git(root, ["diff", "--name-only", "--diff-filter=ACMR", `${ref}...HEAD`]);
222
+ return out.split("\n").map((l) => l.trim()).filter(Boolean).map(toPosix);
223
+ }
224
+ catch {
225
+ // try the next candidate
226
+ }
227
+ }
228
+ return [];
229
+ }