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,91 @@
1
+ import fs from "node:fs";
2
+ import { changedSince, repoName } from "../git.js";
3
+ import { checkFiles, resolveTeam } from "../team.js";
4
+ import { c, fail } from "../util.js";
5
+ import { emit, flagStr, needRoot } from "../context.js";
6
+ const ICON = { blind: "✗", stale: "✗", single: "!", covered: "✓", unknown: "·" };
7
+ const RANK = { high: 3, medium: 2, low: 1, none: 0 };
8
+ const rank = (f) => RANK[f.level ?? "none"] ?? 0;
9
+ const reason = (f) => f.reasons?.[0];
10
+ /** Does this file break the chosen policy? */
11
+ function violates(f, failOn) {
12
+ if (failOn === "unreviewed")
13
+ return f.unreviewed;
14
+ if (failOn === "blind")
15
+ return f.status === "blind" || f.status === "stale"; // no current evidence: never reviewed, or changed since
16
+ return false;
17
+ }
18
+ export const check = {
19
+ name: "check",
20
+ group: "Teams",
21
+ summary: "Pull-request gate: which changed files have AI changes nobody has understood",
22
+ usage: "zevqi check [--base <ref>] [--files a.ts,b.ts] [--fail-on none|unreviewed|blind] [--strict] [--json]",
23
+ examples: [
24
+ "zevqi check --base origin/main",
25
+ "zevqi check --base origin/main --fail-on unreviewed # exit 1 if a changed file has un-reviewed AI changes",
26
+ "ZEVQI_TEAM_KEY=zlt_… zevqi check --fail-on blind # in CI, no `team join` needed",
27
+ ],
28
+ async run(ctx) {
29
+ const failOn = (flagStr(ctx.flags["fail-on"]) ?? "none");
30
+ if (!["none", "unreviewed", "blind"].includes(failOn))
31
+ fail("--fail-on must be none, unreviewed or blind", 2);
32
+ const strict = Boolean(ctx.flags.strict);
33
+ const root = needRoot();
34
+ const explicit = flagStr(ctx.flags.files);
35
+ const base = flagStr(ctx.flags.base) ?? (process.env.GITHUB_BASE_REF ? `origin/${process.env.GITHUB_BASE_REF}` : undefined);
36
+ const files = (explicit ? explicit.split(",").map((f) => f.trim()).filter(Boolean) : changedSince(root, base)).filter((f) => !f.startsWith(".zlearn/") && !f.startsWith(".claude/"));
37
+ if (files.length === 0)
38
+ return void emit(ctx, { files: [], totals: { files: 0 } }, () => console.log(`${c.green("✓")} No changed files to check.`));
39
+ const result = await checkFiles(files, repoName(root));
40
+ if ("error" in result) {
41
+ // An outage or a missing key should not silently pass a strict gate, but it must not break a normal pipeline either.
42
+ if (result.setup)
43
+ fail(result.error, 2, "Set ZEVQI_TEAM_KEY (and ZEVQI_SERVER if you self-host), or run: zevqi team join");
44
+ console.error(c.yellow(`zevqi check skipped: ${result.error}`));
45
+ if (strict)
46
+ process.exitCode = 3;
47
+ return;
48
+ }
49
+ const bad = result.files.filter((f) => violates(f, failOn));
50
+ const interesting = result.files.filter((f) => f.status !== "covered" && f.status !== "unknown");
51
+ const t = result.totals;
52
+ emit(ctx, { ...result, failOn, failed: bad.length > 0 }, () => {
53
+ console.log(`${c.bold("zevqi check")} · ${result.team.name} · ${t.files} changed file${t.files === 1 ? "" : "s"}`);
54
+ for (const f of interesting.sort((a, b) => Number(b.unreviewed) - Number(a.unreviewed) || rank(b) - rank(a))) {
55
+ const tag = f.unreviewed ? c.red("un-reviewed AI change") : f.status === "blind" ? c.red("never reviewed") : f.status === "stale" ? c.red("reviewed, but changed since") : c.yellow("only one person has reviewed this");
56
+ console.log(` ${f.status === "blind" || f.unreviewed ? c.red(ICON[f.status]) : c.yellow(ICON[f.status])} ${f.path} ${c.dim("·")} ${tag}`);
57
+ if (reason(f))
58
+ console.log(` ${c.dim(reason(f))}`);
59
+ }
60
+ console.log(`${c.dim(`${t.covered} covered · ${t.single} one reviewer · ${t.blind} never reviewed · ${t.stale ?? 0} out of date · ${t.unreviewed} un-reviewed · ${t.unknown} not AI-changed`)}`);
61
+ if (bad.length)
62
+ console.log(c.red(`\n✗ ${bad.length} file${bad.length === 1 ? " breaks" : "s break"} the "${failOn}" policy. Run zevqi learn and pass the lessons, then push again.`));
63
+ else
64
+ console.log(c.green(`\n✓ ${failOn === "none" ? "Report only" : `Passes the "${failOn}" policy`}.`));
65
+ const server = resolveTeam()?.server;
66
+ if (interesting.length && server)
67
+ console.log(c.dim(`Details and who can review these: ${server.replace(/\/$/, "")}/account`));
68
+ });
69
+ // GitHub Actions: inline annotations and a job summary.
70
+ if (process.env.GITHUB_ACTIONS === "true" && !ctx.json) {
71
+ for (const f of interesting) {
72
+ const level = violates(f, failOn) ? "error" : "warning";
73
+ const msg = reason(f) ?? (f.unreviewed ? "AI-written change has not been reviewed by anyone on the team" : f.status === "blind" ? "No one on the team has passed a lesson on this file" : "Only one person has reviewed this file");
74
+ console.log(`::${level} file=${f.path}::${msg}`);
75
+ }
76
+ }
77
+ const summaryFile = process.env.GITHUB_STEP_SUMMARY;
78
+ if (summaryFile) {
79
+ const rows = interesting.map((f) => `| \`${f.path}\` | ${f.unreviewed ? "un-reviewed AI change" : f.status === "blind" ? "never reviewed" : f.status === "stale" ? "out of date" : "one reviewer"} | ${f.level ?? ""} | ${reason(f) ?? ""} |`).join("\n");
80
+ const md = `### zevqi check\n\n**${t.files}** changed file(s): ${t.covered} covered, ${t.single} one reviewer, ${t.blind} never reviewed, ${t.stale ?? 0} out of date, ${t.unreviewed} un-reviewed.\n\n${interesting.length ? `| File | Evidence | Level | Why |\n|---|---|---|---|\n${rows}\n` : "Nothing needs attention.\n"}\n${bad.length ? `**Failed** the \`${failOn}\` policy.\n` : ""}`;
81
+ try {
82
+ fs.appendFileSync(summaryFile, md);
83
+ }
84
+ catch {
85
+ // the summary is a nicety
86
+ }
87
+ }
88
+ if (bad.length)
89
+ process.exitCode = 1;
90
+ },
91
+ };
@@ -0,0 +1,184 @@
1
+ import path from "node:path";
2
+ import { loadProject, projectDir } from "../config.js";
3
+ import { canonicalPath, changedFiles, diffForHistory, fileRevs, repoName } from "../git.js";
4
+ import { explainDiff } from "../ai.js";
5
+ import { attestReview } from "../attest.js";
6
+ import { apiKey, loadGlobal } from "../config.js";
7
+ import { newLessonId, saveLesson } from "../lessons.js";
8
+ import { pushRecords, toRecord } from "../team.js";
9
+ import { AiError, explainJob, hooksInstalled } from "../hooks.js";
10
+ import { getLesson, knowledgeMap, listLessons, pending } from "../lessons.js";
11
+ import { maybeNudge } from "../nudge.js";
12
+ import { runQuiz } from "../quiz.js";
13
+ import { startServer } from "../server.js";
14
+ import { bar, computeStats } from "../stats.js";
15
+ import { c, fail, timeAgo, uid, writeJson } from "../util.js";
16
+ import { emit, ensureAiNotice, flagStr, needEnabled, needRoot } from "../context.js";
17
+ export const explain = {
18
+ name: "explain",
19
+ group: "Daily use",
20
+ summary: "Explain your current uncommitted changes now",
21
+ usage: "zevqi explain",
22
+ async run(ctx) {
23
+ // Internal: the Stop hook launches `zevqi explain --job <id> --root <dir>` as a detached background process.
24
+ const job = flagStr(ctx.flags.job);
25
+ if (job) {
26
+ const root = flagStr(ctx.flags.root) ?? needRoot();
27
+ try {
28
+ await explainJob(root, job);
29
+ }
30
+ catch (e) {
31
+ writeJson(path.join(projectDir(root), "last-error.json"), { at: new Date().toISOString(), message: e instanceof Error ? e.message : String(e) });
32
+ }
33
+ return;
34
+ }
35
+ const root = needEnabled();
36
+ ensureAiNotice(root);
37
+ const files = changedFiles(root);
38
+ if (files.length === 0)
39
+ return void console.log("No uncommitted changes to explain.");
40
+ const jobId = uid("job_");
41
+ writeJson(path.join(projectDir(root), "jobs", `${jobId}.json`), { files });
42
+ console.log(c.dim(`Explaining ${files.length} changed file${files.length === 1 ? "" : "s"}…`));
43
+ try {
44
+ const lesson = await explainJob(root, jobId);
45
+ if (!lesson)
46
+ return void console.log("Nothing to explain.");
47
+ console.log(`${c.green("✓")} Lesson ready. Run: ${c.bold("zevqi learn")}`);
48
+ }
49
+ catch (e) {
50
+ fail(e instanceof AiError ? e.message : String(e));
51
+ }
52
+ },
53
+ };
54
+ export const learn = {
55
+ name: "learn",
56
+ aliases: ["quiz"],
57
+ group: "Daily use",
58
+ summary: "Take the quiz for the oldest un-reviewed change",
59
+ usage: "zevqi learn [lessonId]",
60
+ async run(ctx) {
61
+ const root = needEnabled();
62
+ const open = pending(root).reverse();
63
+ const id = ctx.args[0];
64
+ const lesson = id ? getLesson(root, id) : open[0];
65
+ if (!lesson)
66
+ return void console.log(id ? "No such lesson." : `${c.green("✓")} Nothing waiting. You are up to date.`);
67
+ await runQuiz(root, lesson);
68
+ const left = pending(root).length;
69
+ if (left)
70
+ console.log(c.dim(`${left} more waiting. Run zevqi learn again.`));
71
+ },
72
+ };
73
+ export const review = {
74
+ name: "review",
75
+ group: "Daily use",
76
+ summary: "Review recent committed changes to files (a teammate's, or your own from earlier) and add your evidence",
77
+ usage: "zevqi review <file...> [--commits 5] [--no-ai]",
78
+ examples: [
79
+ "zevqi review src/payments/refund.ts",
80
+ "zevqi review src/auth/session.ts src/auth/tokens.ts --commits 3",
81
+ ],
82
+ async run(ctx) {
83
+ const root = needEnabled();
84
+ ensureAiNotice(root);
85
+ const wanted = ctx.args.map((f) => f.trim()).filter(Boolean);
86
+ if (wanted.length === 0)
87
+ fail("Name the files to review.", 2, "Example: zevqi review src/payments/refund.ts");
88
+ const commits = Math.max(1, Math.min(20, Number(flagStr(ctx.flags.commits)) || 5));
89
+ const cfg = loadProject(root);
90
+ // Canonical paths on both sides: a Windows short name (RUNNER~1) or a symlinked cwd must not make a file look like it is outside the repo.
91
+ const files = wanted.slice(0, cfg.maxFiles).map((f) => path.relative(canonicalPath(root), canonicalPath(path.resolve(process.cwd(), f))).split(path.sep).join("/"));
92
+ const { text, included } = diffForHistory(root, files, commits);
93
+ if (!text.trim())
94
+ return void console.log("No git history found for those files. Check the paths, and that the changes are committed.");
95
+ // With a model key the review is AI-written questions. Without one (or with --no-ai) you read the change and describe it yourself.
96
+ if (ctx.flags["no-ai"] || !apiKey(loadGlobal())) {
97
+ try {
98
+ await attestReview(root, included, text, commits);
99
+ }
100
+ catch (e) {
101
+ fail(e instanceof Error ? e.message : String(e));
102
+ }
103
+ return;
104
+ }
105
+ console.log(c.dim(`Reading the last ${commits} commit${commits === 1 ? "" : "s"} for ${included.length} file${included.length === 1 ? "" : "s"}…`));
106
+ try {
107
+ const explanation = await explainDiff(text, included, repoName(root), "review");
108
+ const lesson = {
109
+ id: newLessonId(),
110
+ createdAt: new Date().toISOString(),
111
+ repo: repoName(root),
112
+ files: explanation.files,
113
+ changedFiles: included,
114
+ summary: explanation.summary,
115
+ questions: explanation.questions,
116
+ status: "pending",
117
+ kind: "review",
118
+ revs: fileRevs(root, included),
119
+ decisions: explanation.decisions,
120
+ depends: explanation.depends,
121
+ risks: explanation.risks,
122
+ };
123
+ saveLesson(root, lesson);
124
+ await pushRecords([toRecord(lesson, cfg.share)]);
125
+ await runQuiz(root, lesson);
126
+ }
127
+ catch (e) {
128
+ fail(e instanceof AiError ? e.message : String(e));
129
+ }
130
+ },
131
+ };
132
+ export const status = {
133
+ name: "status",
134
+ group: "Daily use",
135
+ summary: "What is waiting for review, and which files nobody has reviewed",
136
+ usage: "zevqi status [--json]",
137
+ run(ctx) {
138
+ const root = needEnabled();
139
+ const lessons = listLessons(root);
140
+ const open = lessons.filter((l) => l.status === "pending");
141
+ const cfg = loadProject(root);
142
+ const blind = knowledgeMap(root).filter((f) => f.open > 0 && f.passed === 0);
143
+ const hooks = hooksInstalled(root);
144
+ emit(ctx, { waiting: open.length, passed: lessons.filter((l) => l.status === "passed").length, gate: cfg.gate, hooks, waitingLessons: open.map((l) => ({ id: l.id, files: l.changedFiles, createdAt: l.createdAt })), blindSpots: blind.map((f) => f.path) }, () => {
145
+ console.log(`${c.bold(String(open.length))} waiting for review · ${lessons.filter((l) => l.status === "passed").length} passed · gate: ${cfg.gate} · hooks: ${hooks.join(", ") || c.red("not installed")}`);
146
+ for (const l of open.slice(0, 5))
147
+ console.log(` ${c.dim(timeAgo(l.createdAt).padEnd(8))} ${l.changedFiles.slice(0, 3).join(", ")}${l.changedFiles.length > 3 ? "…" : ""} ${c.dim(l.id)}`);
148
+ if (blind.length)
149
+ console.log(c.yellow("Not reviewed yet: ") + blind.slice(0, 5).map((f) => f.path).join(", "));
150
+ });
151
+ maybeNudge(root, { json: ctx.json });
152
+ },
153
+ };
154
+ export const stats = {
155
+ name: "stats",
156
+ group: "Daily use",
157
+ summary: "Your streak, XP and level for this project",
158
+ usage: "zevqi stats [--json]",
159
+ run(ctx) {
160
+ const root = needEnabled();
161
+ const s = computeStats(listLessons(root));
162
+ emit(ctx, s, () => {
163
+ console.log(`${c.bold(`Level ${s.level} · ${s.levelName}`)} ${c.cyan(bar(s.levelProgress))} ${s.xp} XP${s.xpToNext ? c.dim(` (${s.xpToNext} to next level)`) : c.dim(" (top level)")}`);
164
+ console.log(`${c.bold("Streak")} ${s.streak > 0 ? c.yellow(`${s.streak} day${s.streak === 1 ? "" : "s"}`) : c.dim("none yet")} ${c.dim(`best ${s.bestStreak}`)}`);
165
+ console.log(`${c.bold("Understood")} ${s.filesUnderstood} file${s.filesUnderstood === 1 ? "" : "s"} · ${s.passed} lesson${s.passed === 1 ? "" : "s"} passed · ${s.weekPassed} in the last 7 days`);
166
+ if (s.pending)
167
+ console.log(c.dim(`${s.pending} lesson${s.pending === 1 ? "" : "s"} waiting. Run zevqi learn.`));
168
+ else if (s.streak === 0)
169
+ console.log(c.dim("Pass a lesson today to start a streak."));
170
+ });
171
+ maybeNudge(root, { json: ctx.json });
172
+ },
173
+ };
174
+ export const ui = {
175
+ name: "ui",
176
+ group: "Daily use",
177
+ summary: "Open the local dashboard in your browser",
178
+ usage: "zevqi ui [--port 4317]",
179
+ run(ctx) {
180
+ const root = needEnabled();
181
+ const port = Number(flagStr(ctx.flags.port)) || 4317;
182
+ startServer(root, port, (url) => console.log(`zevqi dashboard: ${c.cyan(url)}\n${c.dim("Press Ctrl+C to stop.")}`));
183
+ },
184
+ };
@@ -0,0 +1,25 @@
1
+ import { commitGateHook, postToolHook, stopHook } from "../hooks.js";
2
+ /**
3
+ * Entry point for the Claude Code hooks (`zevqi hook post-tool | stop | commit-gate`).
4
+ * Hooks must never break the agent: every error is swallowed and the process always exits 0.
5
+ */
6
+ export const hook = {
7
+ name: "hook",
8
+ group: "hidden",
9
+ summary: "Internal: called by Claude Code hooks",
10
+ usage: "zevqi hook post-tool | stop | commit-gate",
11
+ async run(ctx) {
12
+ try {
13
+ const which = ctx.args[0];
14
+ if (which === "post-tool")
15
+ await postToolHook();
16
+ else if (which === "stop")
17
+ await stopHook(ctx.cliPath);
18
+ else if (which === "commit-gate")
19
+ await commitGateHook();
20
+ }
21
+ catch {
22
+ // intentionally silent
23
+ }
24
+ },
25
+ };
@@ -0,0 +1,52 @@
1
+ import { c } from "../util.js";
2
+ import { config, doctor, gate, init, uninstall } from "./setup.js";
3
+ import { explain, learn, review, stats, status, ui } from "./daily.js";
4
+ import { team } from "./team.js";
5
+ import { check } from "./check.js";
6
+ import { lesson } from "./lesson.js";
7
+ import { scan } from "./scan.js";
8
+ import { setup } from "./quickstart.js";
9
+ import { hook } from "./hook.js";
10
+ export const COMMANDS = [setup, init, uninstall, config, doctor, learn, review, lesson, scan, explain, status, stats, ui, gate, team, check, hook];
11
+ export function findCommand(name) {
12
+ return COMMANDS.find((cmd) => cmd.name === name || cmd.aliases?.includes(name));
13
+ }
14
+ const GROUPS = ["Setup", "Daily use", "Teams"];
15
+ export function renderHelp(version) {
16
+ const lines = [`${c.bold("Zevqi")} ${version} understand the code your AI agent writes, as fast as it writes it.`, "", `${c.bold("Usage")} zevqi <command> [options]`];
17
+ for (const group of GROUPS) {
18
+ lines.push("", c.bold(group));
19
+ for (const cmd of COMMANDS.filter((x) => x.group === group))
20
+ lines.push(` ${cmd.name.padEnd(10)} ${cmd.summary}`);
21
+ }
22
+ lines.push("", c.dim("Run `zevqi help <command>` for details. Add --json to status, stats, doctor and team status for scripts."), c.dim("Docs: https://zevqi.com/docs"));
23
+ return lines.join("\n");
24
+ }
25
+ export function renderCommandHelp(cmd) {
26
+ const lines = [`${c.bold(`zevqi ${cmd.name}`)} ${cmd.summary}`, "", `${c.bold("Usage")} ${cmd.usage}`];
27
+ if (cmd.examples?.length)
28
+ lines.push("", c.bold("Examples"), ...cmd.examples.map((e) => ` ${e}`));
29
+ return lines.join("\n");
30
+ }
31
+ /** Closest known command for a typo, or undefined. */
32
+ export function suggest(input) {
33
+ const names = COMMANDS.filter((x) => x.group !== "hidden").flatMap((x) => [x.name, ...(x.aliases ?? [])]);
34
+ let best;
35
+ for (const name of names) {
36
+ const d = distance(input, name);
37
+ if (d <= 2 && (!best || d < best.d))
38
+ best = { name, d };
39
+ }
40
+ return best?.name;
41
+ }
42
+ function distance(a, b) {
43
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
44
+ for (let j = 1; j <= b.length; j++)
45
+ dp[0][j] = j;
46
+ for (let i = 1; i <= a.length; i++) {
47
+ for (let j = 1; j <= b.length; j++) {
48
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
49
+ }
50
+ }
51
+ return dp[a.length][b.length];
52
+ }
@@ -0,0 +1,91 @@
1
+ import { loadProject } from "../config.js";
2
+ import { AiError, validate } from "../ai.js";
3
+ import { changedFiles, fileRevs, filesInCommit, repoName } from "../git.js";
4
+ import { newLessonId, saveLesson } from "../lessons.js";
5
+ import { pushRecords, toRecord } from "../team.js";
6
+ import { c, fail, readStdin } from "../util.js";
7
+ import { emit, flagStr, needEnabled } from "../context.js";
8
+ const SCHEMA = `{
9
+ "summary": "3 to 5 plain sentences: what changed and why it matters",
10
+ "files": [{ "path": "src/a.ts", "note": "one sentence: what this file's change does" }],
11
+ "decisions": ["up to 3 design decisions visible in the code"],
12
+ "depends": ["up to 3 things this code relies on"],
13
+ "risks": ["up to 2 ways this could break or surprise someone"],
14
+ "questions": [
15
+ { "kind": "Why | Failure case | Assumption | Dependency", "q": "...", "options": ["...", "...", "...", "..."], "answer": 0, "why": "..." }
16
+ ]
17
+ }`;
18
+ /**
19
+ * `zevqi lesson add`: save a lesson that the developer's own coding agent wrote (Codex, Cursor, Claude Code, anything that can run
20
+ * a shell command). It replaces the separate model call, so no API key is needed. The files come from git, not from the agent,
21
+ * so a lesson can only describe files that really changed.
22
+ */
23
+ export const lesson = {
24
+ name: "lesson",
25
+ group: "Daily use",
26
+ summary: "Save a lesson your coding agent wrote (JSON on stdin), so no API key is needed",
27
+ usage: "zevqi lesson add [--files a.ts,b.ts] [--commit <ref>] [--json] | zevqi lesson schema",
28
+ examples: ["zevqi lesson schema", "cat lesson.json | zevqi lesson add", "cat lesson.json | zevqi lesson add --commit HEAD"],
29
+ async run(ctx) {
30
+ const sub = ctx.args[0];
31
+ if (sub === "schema")
32
+ return void console.log(SCHEMA);
33
+ if (sub !== "add")
34
+ fail("Usage: zevqi lesson add (lesson JSON on stdin) | zevqi lesson schema", 2);
35
+ const root = needEnabled();
36
+ const raw = await readStdin();
37
+ if (!raw.trim())
38
+ fail("Pipe the lesson JSON on stdin.", 2, "See the format: zevqi lesson schema");
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(raw);
42
+ }
43
+ catch {
44
+ fail("The lesson is not valid JSON.", 2, "See the format: zevqi lesson schema");
45
+ }
46
+ // Which files does this lesson cover? Explicit, a commit, or what is changed right now (falling back to the last commit).
47
+ // Files Zevqi itself manages are never "the change" when detected automatically. An explicit --files list is always respected.
48
+ const own = new Set(["AGENTS.md", "CLAUDE.md", ".gitignore"]);
49
+ const hidden = (f) => f.startsWith(".zlearn/") || f.startsWith(".claude/") || own.has(f);
50
+ const explicit = flagStr(ctx.flags.files);
51
+ const commit = flagStr(ctx.flags.commit);
52
+ let files = explicit ? explicit.split(",").map((f) => f.trim()).filter(Boolean) : commit ? filesInCommit(root, commit) : changedFiles(root);
53
+ if (!explicit && !commit && files.filter((f) => !hidden(f)).length === 0)
54
+ files = filesInCommit(root, "HEAD");
55
+ const cfg = loadProject(root);
56
+ files = (explicit ? files : files.filter((f) => !hidden(f))).slice(0, cfg.maxFiles);
57
+ if (files.length === 0)
58
+ fail("There are no changed files to attach this lesson to.", 1, "Pass --files a.ts,b.ts or --commit <ref>.");
59
+ let explanation;
60
+ try {
61
+ explanation = validate(parsed, files);
62
+ }
63
+ catch (e) {
64
+ fail(e instanceof AiError ? e.message : String(e), 2, "See the format: zevqi lesson schema");
65
+ }
66
+ const repo = repoName(root);
67
+ const made = {
68
+ id: newLessonId(),
69
+ createdAt: new Date().toISOString(),
70
+ repo,
71
+ files: explanation.files,
72
+ changedFiles: files,
73
+ summary: explanation.summary,
74
+ questions: explanation.questions,
75
+ status: "pending",
76
+ kind: "change",
77
+ explainer: "agent",
78
+ revs: fileRevs(root, files),
79
+ decisions: explanation.decisions,
80
+ depends: explanation.depends,
81
+ risks: explanation.risks,
82
+ };
83
+ saveLesson(root, made);
84
+ const sync = await pushRecords([toRecord(made, cfg.share)]);
85
+ emit(ctx, { id: made.id, files, questions: made.questions.length, synced: sync.sent > 0, queued: sync.queued }, () => {
86
+ console.log(`${c.green("✓")} Lesson ${made.id} saved for ${files.length} file${files.length === 1 ? "" : "s"} (${made.questions.length} questions). Take it with: ${c.bold("zevqi learn")}`);
87
+ if (sync.error)
88
+ console.log(c.dim(`(team sync queued: ${sync.error})`));
89
+ });
90
+ },
91
+ };
@@ -0,0 +1,72 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { loadGlobal } from "../config.js";
3
+ import { repoRoot } from "../git.js";
4
+ import { checkTeamKey, joinTeam, resolveTeam } from "../team.js";
5
+ import { c, fail } from "../util.js";
6
+ import { flagStr } from "../context.js";
7
+ import { init } from "./setup.js";
8
+ import { scan } from "./scan.js";
9
+ import { envVar } from "../env.js";
10
+ const gitEmail = () => {
11
+ try {
12
+ return execFileSync("git", ["config", "user.email"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || undefined;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ };
18
+ /** The page a person lands on after setup. Signing in with an email code takes them to their dashboard. */
19
+ export const dashboardUrl = (server) => `${server.replace(/\/$/, "")}/account`;
20
+ /**
21
+ * `zevqi setup`: the whole first run in one command. Joins the team, turns Zevqi on in this repository and uploads the first
22
+ * git knowledge map. Each step says what it did and what is next; a failing step never undoes the ones before it.
23
+ */
24
+ export const setup = {
25
+ name: "setup",
26
+ group: "Setup",
27
+ summary: "One command: join your team, turn Zevqi on here, and scan this repository",
28
+ usage: "zevqi setup --key <teamKey> [--email <you>] [--server <url>] [--name <you>] [--names] [--skip-scan]",
29
+ examples: ["zevqi setup --key zlt_… --email you@company.com", "ZEVQI_TEAM_KEY=zlt_… zevqi setup # the email comes from git config"],
30
+ async run(ctx) {
31
+ const key = flagStr(ctx.flags.key) ?? envVar("TEAM_KEY") ?? loadGlobal().team?.key;
32
+ if (!key)
33
+ fail("A team key is needed.", 2, "Pass --key <teamKey> (your team admin has it), or set ZEVQI_TEAM_KEY.");
34
+ const server = flagStr(ctx.flags.server) ?? envVar("SERVER") ?? loadGlobal().team?.server ?? "https://zevqi.com";
35
+ const email = flagStr(ctx.flags.email) ?? loadGlobal().team?.email ?? gitEmail();
36
+ if (!email)
37
+ fail("Your email is needed.", 2, "Pass --email you@company.com (or set it once with: git config --global user.email you@company.com).");
38
+ const steps = ctx.flags["skip-scan"] ? 2 : 3;
39
+ // 1. join the team
40
+ console.log(c.bold(`\n1/${steps} Joining your team`));
41
+ const check = await checkTeamKey(server, key);
42
+ if (!check.ok && check.reason === "invalid")
43
+ fail(check.message, 1, "Nothing was saved. Ask your team admin for the key, or rotate it in the dashboard under Settings.");
44
+ joinTeam(server, key, email, flagStr(ctx.flags.name));
45
+ console.log(check.ok ? `${c.green("✓")} Joined ${check.teamName ? c.bold(check.teamName) : "the team"} as ${email}` : `${c.yellow("!")} Saved your team, but ${server} did not answer just now (${check.message}). Everything will queue and sync later.`);
46
+ // 2. turn it on in this repository
47
+ const root = repoRoot(process.cwd());
48
+ if (!root) {
49
+ console.log(`\n${c.yellow("!")} You are not inside a git repository, so the team is joined but nothing else was set up.`);
50
+ console.log(` Next: ${c.bold("cd your-project")} then run ${c.bold("zevqi setup")} again (it remembers your team).`);
51
+ return;
52
+ }
53
+ console.log(c.bold(`\n2/${steps} Turning Zevqi on in this repository`));
54
+ const sub = (flags) => ({ ...ctx, args: [], flags, json: false });
55
+ await init.run(sub({ "no-prompt": true, ...(ctx.flags.agents ? { agents: true } : {}), ...(ctx.flags["no-agents"] ? { "no-agents": true } : {}) }));
56
+ // 3. the first knowledge map
57
+ if (!ctx.flags["skip-scan"]) {
58
+ console.log(c.bold(`\n3/${steps} Mapping who holds the knowledge of each file (from git history)`));
59
+ try {
60
+ await scan.run(sub({ ...(ctx.flags.names ? { names: true } : {}) }));
61
+ }
62
+ catch (e) {
63
+ console.log(`${c.yellow("!")} The scan did not finish: ${e instanceof Error ? e.message : String(e)}. Run ${c.bold("zevqi scan")} again later.`);
64
+ }
65
+ }
66
+ const t = resolveTeam();
67
+ console.log(`\n${c.green("✓ Setup complete.")}`);
68
+ console.log(` See your knowledge map: ${c.cyan(dashboardUrl(t?.server ?? server))} ${c.dim("(sign in with your email, then Open dashboard)")}`);
69
+ console.log(` Understand a file: ${c.bold("zevqi review <file>")}`);
70
+ console.log(` What is waiting: ${c.bold("zevqi status")}`);
71
+ },
72
+ };
@@ -0,0 +1,67 @@
1
+ import { repoName, scanLog, trackedFiles } from "../git.js";
2
+ import { buildScan, parseLog, summarize } from "../scan.js";
3
+ import { pushScan, resolveTeam } from "../team.js";
4
+ import { c, fail } from "../util.js";
5
+ import { emit, flagStr, needRoot } from "../context.js";
6
+ /**
7
+ * `zevqi scan`: a map of who has changed which files, from git history. It needs no model, no API key and no setup by your
8
+ * teammates. Only counts, dates and pseudonymous author ids leave your machine: no code, no commit messages, no emails.
9
+ */
10
+ export const scan = {
11
+ name: "scan",
12
+ group: "Teams",
13
+ summary: "Map who holds the knowledge of each file, from git history (no key needed)",
14
+ usage: "zevqi scan [--months 12] [--names] [--dry-run] [--json]",
15
+ examples: [
16
+ "zevqi scan --dry-run # see exactly what would be sent, and send nothing",
17
+ "zevqi scan # upload to your team dashboard",
18
+ "zevqi scan --names # also share author names (never emails)",
19
+ ],
20
+ async run(ctx) {
21
+ const root = needRoot();
22
+ const months = Math.max(1, Math.min(60, Number(flagStr(ctx.flags.months)) || 12));
23
+ const names = Boolean(ctx.flags.names);
24
+ const dry = Boolean(ctx.flags["dry-run"]);
25
+ const commits = parseLog(scanLog(root, months));
26
+ if (commits.length === 0)
27
+ return void console.log(`No commits found in the last ${months} months.`);
28
+ const payload = buildScan(repoName(root), commits, trackedFiles(root), { names });
29
+ if (payload.files.length === 0)
30
+ return void console.log("No source files in that history.");
31
+ const s = summarize(payload);
32
+ if (dry) {
33
+ return void emit(ctx, { dryRun: true, summary: s, sample: { ...payload, files: payload.files.slice(0, 3), people: payload.people.slice(0, 3) } }, () => {
34
+ console.log(`${c.bold("Dry run")}: nothing is sent. This is what a scan of ${c.bold(payload.repo)} would upload.\n`);
35
+ console.log(JSON.stringify({ ...payload, files: payload.files.slice(0, 3), people: payload.people.slice(0, 3) }, null, 2));
36
+ console.log(c.dim(`\n…and ${Math.max(0, payload.files.length - 3)} more files and ${Math.max(0, payload.people.length - 3)} more people in the same format (${Math.round(JSON.stringify(payload).length / 1024)} KB in total).`));
37
+ console.log(c.dim(`Never included: source code, commit messages, email addresses${names ? "" : ", author names"}.`));
38
+ });
39
+ }
40
+ const team = resolveTeam();
41
+ if (!team) {
42
+ emit(ctx, { uploaded: false, summary: s }, () => {
43
+ printSummary(s);
44
+ console.log(c.yellow("\nNot uploaded: you are not on a team yet.") + c.dim(" Run: zevqi team join --server <url> --key <key> --email <you>"));
45
+ });
46
+ return;
47
+ }
48
+ let res;
49
+ try {
50
+ res = await pushScan(payload);
51
+ }
52
+ catch (e) {
53
+ fail(e instanceof Error ? e.message : String(e), 1, "Your scan was not uploaded. Try again, or use --dry-run to inspect it.");
54
+ }
55
+ emit(ctx, { uploaded: true, ...res, summary: s }, () => {
56
+ printSummary(s);
57
+ console.log(`\n${c.green("✓")} Uploaded ${res.saved} files and ${res.people} people to your team dashboard (Knowledge map).`);
58
+ console.log(c.dim(`Shared: paths, commit counts, dates and pseudonymous author ids${names ? ", and author names" : ""}. Not shared: code, commit messages, emails.`));
59
+ console.log(`See your knowledge map: ${c.cyan(`${team.server.replace(/\/$/, "")}/account`)}`);
60
+ });
61
+ },
62
+ };
63
+ function printSummary(s) {
64
+ console.log(`${c.bold(`${s.commits} commits`)} · ${s.files} files · ${s.people} people`);
65
+ console.log(`${s.soleAuthorFiles} file${s.soleAuthorFiles === 1 ? "" : "s"} with a single author across 3+ commits · ${s.aiCommits} commit${s.aiCommits === 1 ? "" : "s"} marked AI-assisted (${s.aiShare}%)`);
66
+ console.log(c.dim("AI-assisted is only counted when the commit says so, so the real share is probably higher."));
67
+ }