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.
- package/LICENSE +21 -0
- package/README.md +183 -2
- package/package.json +48 -4
- package/packages/cli/dist/agents.js +106 -0
- package/packages/cli/dist/ai.js +93 -0
- package/packages/cli/dist/args.js +30 -0
- package/packages/cli/dist/attest.js +97 -0
- package/packages/cli/dist/cli.js +41 -0
- package/packages/cli/dist/commands/check.js +91 -0
- package/packages/cli/dist/commands/daily.js +184 -0
- package/packages/cli/dist/commands/hook.js +25 -0
- package/packages/cli/dist/commands/index.js +52 -0
- package/packages/cli/dist/commands/lesson.js +91 -0
- package/packages/cli/dist/commands/quickstart.js +72 -0
- package/packages/cli/dist/commands/scan.js +67 -0
- package/packages/cli/dist/commands/setup.js +145 -0
- package/packages/cli/dist/commands/team.js +76 -0
- package/packages/cli/dist/config.js +53 -0
- package/packages/cli/dist/context.js +32 -0
- package/packages/cli/dist/env.js +4 -0
- package/packages/cli/dist/git.js +229 -0
- package/packages/cli/dist/hooks.js +164 -0
- package/packages/cli/dist/lessons.js +83 -0
- package/packages/cli/dist/nudge.js +42 -0
- package/packages/cli/dist/quiz.js +104 -0
- package/packages/cli/dist/scan.js +87 -0
- package/packages/cli/dist/server.js +122 -0
- package/packages/cli/dist/stats.js +84 -0
- package/packages/cli/dist/team.js +128 -0
- package/packages/cli/dist/util.js +153 -0
- package/packages/cli/dist/version.js +15 -0
- package/packages/cli/package.json +49 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { explainDiff, AiError } from "./ai.js";
|
|
6
|
+
import { apiKey, loadGlobal, loadProject, projectDir } from "./config.js";
|
|
7
|
+
import { canonicalPath, diffForFiles, fileRevs, repoName, repoRoot } from "./git.js";
|
|
8
|
+
import { listLessons, newLessonId, pending, recordEdit, saveLesson, takeBuffer } from "./lessons.js";
|
|
9
|
+
import { pushRecords, toRecord } from "./team.js";
|
|
10
|
+
import { readJson, readStdin, toPosix, uid, writeJson } from "./util.js";
|
|
11
|
+
function parse(raw) {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(raw);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
20
|
+
/** PostToolUse: remember which files the agent touched. Must be fast and silent. */
|
|
21
|
+
export async function postToolHook() {
|
|
22
|
+
const input = parse(await readStdin());
|
|
23
|
+
if (!input.tool_name || !EDIT_TOOLS.has(input.tool_name))
|
|
24
|
+
return;
|
|
25
|
+
const file = input.tool_input?.file_path || input.tool_input?.notebook_path || input.tool_input?.path;
|
|
26
|
+
if (!file)
|
|
27
|
+
return;
|
|
28
|
+
const root = repoRoot(input.cwd || process.cwd());
|
|
29
|
+
if (!root)
|
|
30
|
+
return;
|
|
31
|
+
if (!fs.existsSync(projectDir(root)))
|
|
32
|
+
return; // Zevqi is not enabled in this repo
|
|
33
|
+
// Compare canonical paths so short names (C:\Users\RUNNER~1), case differences and symlinks cannot hide an edit.
|
|
34
|
+
const rel = toPosix(path.relative(canonicalPath(root), canonicalPath(path.resolve(input.cwd || root, file))));
|
|
35
|
+
if (rel.startsWith("..") || rel.startsWith(".zlearn") || rel.startsWith(".claude"))
|
|
36
|
+
return;
|
|
37
|
+
recordEdit(root, rel, input.session_id);
|
|
38
|
+
}
|
|
39
|
+
/** Stop: the agent finished a turn. Start the explanation in the background so Claude is never slowed down. */
|
|
40
|
+
export async function stopHook(cliPath) {
|
|
41
|
+
const input = parse(await readStdin());
|
|
42
|
+
const root = repoRoot(input.cwd || process.cwd());
|
|
43
|
+
if (!root || !fs.existsSync(projectDir(root)))
|
|
44
|
+
return;
|
|
45
|
+
// No API key means your coding agent writes the lessons (zevqi lesson add), so there is no background explanation to start.
|
|
46
|
+
if (!apiKey(loadGlobal()))
|
|
47
|
+
return;
|
|
48
|
+
const buf = takeBuffer(root);
|
|
49
|
+
if (!buf)
|
|
50
|
+
return;
|
|
51
|
+
const jobId = uid("job_");
|
|
52
|
+
writeJson(path.join(projectDir(root), "jobs", `${jobId}.json`), { root, sessionId: buf.sessionId, files: Object.keys(buf.files) });
|
|
53
|
+
const child = spawn(process.execPath, [cliPath, "explain", "--job", jobId, "--root", root], { detached: true, stdio: "ignore", windowsHide: true });
|
|
54
|
+
child.unref();
|
|
55
|
+
}
|
|
56
|
+
/** The background job: turn the changed files into a lesson. */
|
|
57
|
+
export async function explainJob(root, jobId) {
|
|
58
|
+
const jobFile = path.join(projectDir(root), "jobs", `${jobId}.json`);
|
|
59
|
+
const job = readJson(jobFile, null);
|
|
60
|
+
if (!job)
|
|
61
|
+
return null;
|
|
62
|
+
const cfg = loadProject(root);
|
|
63
|
+
const files = job.files.slice(0, cfg.maxFiles);
|
|
64
|
+
const { text, included } = diffForFiles(root, files);
|
|
65
|
+
try {
|
|
66
|
+
fs.rmSync(jobFile, { force: true });
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// ignore
|
|
70
|
+
}
|
|
71
|
+
if (!text.trim())
|
|
72
|
+
return null;
|
|
73
|
+
const repo = repoName(root);
|
|
74
|
+
const explanation = await explainDiff(text, included, repo);
|
|
75
|
+
const lesson = {
|
|
76
|
+
id: newLessonId(),
|
|
77
|
+
createdAt: new Date().toISOString(),
|
|
78
|
+
repo,
|
|
79
|
+
sessionId: job.sessionId,
|
|
80
|
+
changedFiles: included,
|
|
81
|
+
files: explanation.files,
|
|
82
|
+
summary: explanation.summary,
|
|
83
|
+
questions: explanation.questions,
|
|
84
|
+
status: "pending",
|
|
85
|
+
kind: "change",
|
|
86
|
+
revs: fileRevs(root, included),
|
|
87
|
+
decisions: explanation.decisions,
|
|
88
|
+
depends: explanation.depends,
|
|
89
|
+
risks: explanation.risks,
|
|
90
|
+
};
|
|
91
|
+
saveLesson(root, lesson);
|
|
92
|
+
await pushRecords([toRecord(lesson, cfg.share)]);
|
|
93
|
+
return lesson;
|
|
94
|
+
}
|
|
95
|
+
export { AiError };
|
|
96
|
+
/** PreToolUse on `git commit`: warn or block while AI changes are still un-reviewed. */
|
|
97
|
+
export async function commitGateHook() {
|
|
98
|
+
const input = parse(await readStdin());
|
|
99
|
+
const command = input.tool_input?.command ?? "";
|
|
100
|
+
if (input.tool_name !== "Bash" || !/\bgit\s+(?:-[^\s]+\s+)*commit\b/.test(command))
|
|
101
|
+
return;
|
|
102
|
+
const root = repoRoot(input.cwd || process.cwd());
|
|
103
|
+
if (!root || !fs.existsSync(projectDir(root)))
|
|
104
|
+
return;
|
|
105
|
+
const cfg = loadProject(root);
|
|
106
|
+
if (cfg.gate === "off")
|
|
107
|
+
return;
|
|
108
|
+
const open = pending(root);
|
|
109
|
+
if (open.length === 0)
|
|
110
|
+
return;
|
|
111
|
+
const files = new Set(open.flatMap((l) => l.changedFiles));
|
|
112
|
+
const message = `${open.length} AI change${open.length === 1 ? "" : "s"} touching ${files.size} file${files.size === 1 ? "" : "s"} not reviewed yet. Run "zevqi learn" in a terminal (about 2 minutes), then commit.`;
|
|
113
|
+
if (cfg.gate === "block") {
|
|
114
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: `zevqi: ${message} To skip once, run: zevqi gate off` } }));
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
process.stdout.write(JSON.stringify({ systemMessage: `zevqi: ${message}` }));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const MARK = "zevqi-learn";
|
|
121
|
+
export function settingsPath(root, scope) {
|
|
122
|
+
if (scope === "global")
|
|
123
|
+
return path.join(os.homedir(), ".claude", "settings.json");
|
|
124
|
+
return path.join(root, ".claude", scope === "shared" ? "settings.json" : "settings.local.json");
|
|
125
|
+
}
|
|
126
|
+
function ours(group) {
|
|
127
|
+
return group.hooks?.some((h) => h.args?.some((a) => /zevqi-learn|[\\/]dist[\\/]cli\.js/.test(a)) && h.args.includes("hook"));
|
|
128
|
+
}
|
|
129
|
+
export function installHooks(root, scope, cliPath) {
|
|
130
|
+
const file = settingsPath(root, scope);
|
|
131
|
+
const settings = readJson(file, {});
|
|
132
|
+
settings.hooks = settings.hooks ?? {};
|
|
133
|
+
const add = (event, group) => {
|
|
134
|
+
const groups = (settings.hooks[event] ?? []).filter((g) => !ours(g));
|
|
135
|
+
groups.push(group);
|
|
136
|
+
settings.hooks[event] = groups;
|
|
137
|
+
};
|
|
138
|
+
const cmd = (sub, timeout, extra = {}) => ({ type: "command", command: process.execPath, args: [cliPath, "hook", sub], timeout, ...extra });
|
|
139
|
+
add("PostToolUse", { matcher: "Edit|Write|MultiEdit|NotebookEdit", hooks: [cmd("post-tool", 10)] });
|
|
140
|
+
add("Stop", { hooks: [cmd("stop", 10)] });
|
|
141
|
+
add("PreToolUse", { matcher: "Bash", hooks: [cmd("commit-gate", 10, { if: "Bash(git commit*)" })] });
|
|
142
|
+
writeJson(file, settings);
|
|
143
|
+
return file;
|
|
144
|
+
}
|
|
145
|
+
export function uninstallHooks(root, scope) {
|
|
146
|
+
const file = settingsPath(root, scope);
|
|
147
|
+
const settings = readJson(file, {});
|
|
148
|
+
for (const event of Object.keys(settings.hooks ?? {})) {
|
|
149
|
+
settings.hooks[event] = settings.hooks[event].filter((g) => !ours(g));
|
|
150
|
+
if (settings.hooks[event].length === 0)
|
|
151
|
+
delete settings.hooks[event];
|
|
152
|
+
}
|
|
153
|
+
if (settings.hooks && Object.keys(settings.hooks).length === 0)
|
|
154
|
+
delete settings.hooks;
|
|
155
|
+
writeJson(file, settings);
|
|
156
|
+
return file;
|
|
157
|
+
}
|
|
158
|
+
export function hooksInstalled(root) {
|
|
159
|
+
return ["local", "shared", "global"].filter((scope) => {
|
|
160
|
+
const s = readJson(settingsPath(root, scope), {});
|
|
161
|
+
return Object.values(s.hooks ?? {}).some((groups) => groups.some(ours));
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
export { MARK, listLessons };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { projectDir } from "./config.js";
|
|
4
|
+
import { readJson, uid, writeJson } from "./util.js";
|
|
5
|
+
export const RESPONSES = { y: "understood", c: "clarify", i: "investigate" };
|
|
6
|
+
const lessonsDir = (root) => path.join(projectDir(root), "lessons");
|
|
7
|
+
const bufferFile = (root) => path.join(projectDir(root), "buffer.json");
|
|
8
|
+
export function recordEdit(root, file, sessionId) {
|
|
9
|
+
const buf = readJson(bufferFile(root), { files: {} });
|
|
10
|
+
buf.sessionId = sessionId || buf.sessionId;
|
|
11
|
+
buf.files[file] = new Date().toISOString();
|
|
12
|
+
writeJson(bufferFile(root), buf);
|
|
13
|
+
}
|
|
14
|
+
/** Take the edits recorded so far and clear the buffer (so the next turn starts fresh). */
|
|
15
|
+
export function takeBuffer(root) {
|
|
16
|
+
const buf = readJson(bufferFile(root), { files: {} });
|
|
17
|
+
if (Object.keys(buf.files).length === 0)
|
|
18
|
+
return null;
|
|
19
|
+
try {
|
|
20
|
+
fs.rmSync(bufferFile(root), { force: true });
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// ignore
|
|
24
|
+
}
|
|
25
|
+
return buf;
|
|
26
|
+
}
|
|
27
|
+
export function saveLesson(root, lesson) {
|
|
28
|
+
writeJson(path.join(lessonsDir(root), `${lesson.id}.json`), lesson);
|
|
29
|
+
}
|
|
30
|
+
export function newLessonId() {
|
|
31
|
+
return uid("l_");
|
|
32
|
+
}
|
|
33
|
+
export function listLessons(root) {
|
|
34
|
+
let names = [];
|
|
35
|
+
try {
|
|
36
|
+
names = fs.readdirSync(lessonsDir(root)).filter((n) => n.endsWith(".json"));
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
return names
|
|
42
|
+
.map((n) => readJson(path.join(lessonsDir(root), n), null))
|
|
43
|
+
.filter((l) => Boolean(l && l.id))
|
|
44
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
45
|
+
}
|
|
46
|
+
export function getLesson(root, id) {
|
|
47
|
+
if (!/^l_[a-f0-9]+$/.test(id))
|
|
48
|
+
return null;
|
|
49
|
+
return readJson(path.join(lessonsDir(root), `${id}.json`), null);
|
|
50
|
+
}
|
|
51
|
+
export function pending(root) {
|
|
52
|
+
return listLessons(root).filter((l) => l.status === "pending");
|
|
53
|
+
}
|
|
54
|
+
export function complete(root, lesson, correct, passRatio) {
|
|
55
|
+
const total = lesson.questions.length;
|
|
56
|
+
const next = { ...lesson, correct, total, status: total > 0 && correct / total >= passRatio - 1e-9 ? "passed" : "failed", completedAt: new Date().toISOString() };
|
|
57
|
+
saveLesson(root, next);
|
|
58
|
+
return next;
|
|
59
|
+
}
|
|
60
|
+
/** Records how the developer felt about a finished lesson. */
|
|
61
|
+
export function setResponse(root, lesson, response, note) {
|
|
62
|
+
const next = { ...lesson, response, ...(note ? { note: note.replace(/\s+/g, " ").trim().slice(0, 300) } : {}) };
|
|
63
|
+
saveLesson(root, next);
|
|
64
|
+
return next;
|
|
65
|
+
}
|
|
66
|
+
/** Per-file view: how often AI changed it and whether you have passed a lesson covering it. */
|
|
67
|
+
export function knowledgeMap(root) {
|
|
68
|
+
const map = new Map();
|
|
69
|
+
for (const lesson of listLessons(root)) {
|
|
70
|
+
for (const file of lesson.changedFiles) {
|
|
71
|
+
const entry = map.get(file) ?? { path: file, changes: 0, passed: 0, open: 0, lastChange: lesson.createdAt };
|
|
72
|
+
entry.changes += 1;
|
|
73
|
+
if (lesson.status === "passed")
|
|
74
|
+
entry.passed += 1;
|
|
75
|
+
else
|
|
76
|
+
entry.open += 1;
|
|
77
|
+
if (lesson.createdAt > entry.lastChange)
|
|
78
|
+
entry.lastChange = lesson.createdAt;
|
|
79
|
+
map.set(file, entry);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return [...map.values()].sort((a, b) => b.open - a.open || b.lastChange.localeCompare(a.lastChange));
|
|
83
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { loadGlobal, globalDir } from "./config.js";
|
|
3
|
+
import { contributorCount } from "./git.js";
|
|
4
|
+
import { c, readJson, writeJson } from "./util.js";
|
|
5
|
+
import { envVar } from "./env.js";
|
|
6
|
+
// A gentle, honest nudge: when a repo clearly has a team but you are not on a team plan, mention what teams get.
|
|
7
|
+
// Rules: interactive terminals only, at most once a week, never in --json, easy to turn off, never blocks anything.
|
|
8
|
+
const WEEK = 7 * 86_400_000;
|
|
9
|
+
export const NUDGE_MIN_CONTRIBUTORS = 3;
|
|
10
|
+
export function shouldNudge(i) {
|
|
11
|
+
if (i.disabled || i.onTeam || !i.interactive)
|
|
12
|
+
return false;
|
|
13
|
+
if (i.contributors < NUDGE_MIN_CONTRIBUTORS)
|
|
14
|
+
return false;
|
|
15
|
+
return i.lastNudgeAt === null || i.now - i.lastNudgeAt >= WEEK;
|
|
16
|
+
}
|
|
17
|
+
const stateFile = () => path.join(globalDir(), "state.json");
|
|
18
|
+
export function maybeNudge(root, opts = {}) {
|
|
19
|
+
try {
|
|
20
|
+
if (opts.json)
|
|
21
|
+
return;
|
|
22
|
+
const state = readJson(stateFile(), {});
|
|
23
|
+
const contributors = contributorCount(root, 90);
|
|
24
|
+
const ok = shouldNudge({
|
|
25
|
+
contributors,
|
|
26
|
+
onTeam: Boolean(loadGlobal().team),
|
|
27
|
+
lastNudgeAt: state.lastNudgeAt ?? null,
|
|
28
|
+
now: Date.now(),
|
|
29
|
+
interactive: Boolean(process.stdout.isTTY),
|
|
30
|
+
disabled: Boolean(envVar("NO_NUDGE")) || Boolean(process.env.CI),
|
|
31
|
+
});
|
|
32
|
+
if (!ok)
|
|
33
|
+
return;
|
|
34
|
+
console.log(`\n${c.bold("Tip:")} ${contributors} people committed here in the last 90 days. On your own, Zevqi shows what ${c.bold("you")} understand.\n` +
|
|
35
|
+
`Teams see shared coverage, blind spots and single points of knowledge: ${c.cyan("https://zevqi.com/trial")} ${c.dim("(7 days free, no card)")}\n` +
|
|
36
|
+
c.dim("Hide this tip: export ZEVQI_NO_NUDGE=1"));
|
|
37
|
+
writeJson(stateFile(), { ...state, lastNudgeAt: Date.now() });
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// a tip must never get in the way
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import readline from "node:readline/promises";
|
|
2
|
+
import { loadProject } from "./config.js";
|
|
3
|
+
import { complete, listLessons, RESPONSES, setResponse } from "./lessons.js";
|
|
4
|
+
import { maybeNudge } from "./nudge.js";
|
|
5
|
+
import { bar, computeStats } from "./stats.js";
|
|
6
|
+
import { pushRecords, toRecord } from "./team.js";
|
|
7
|
+
import { c } from "./util.js";
|
|
8
|
+
const LETTERS = ["A", "B", "C", "D"];
|
|
9
|
+
export function printLesson(lesson) {
|
|
10
|
+
console.log("\n" + c.bold(c.cyan("What your agent changed")) + (lesson.explainer === "agent" ? c.dim(" (explained by your coding agent)") : ""));
|
|
11
|
+
console.log(lesson.summary + "\n");
|
|
12
|
+
for (const f of lesson.files)
|
|
13
|
+
console.log(` ${c.bold(f.path)}\n ${c.dim(f.note)}`);
|
|
14
|
+
const section = (title, items) => {
|
|
15
|
+
if (items?.length)
|
|
16
|
+
console.log(`\n${c.bold(title)}\n${items.map((x) => ` - ${x}`).join("\n")}`);
|
|
17
|
+
};
|
|
18
|
+
section("Decisions in the code", lesson.decisions);
|
|
19
|
+
section("It depends on", lesson.depends);
|
|
20
|
+
section("What could break", lesson.risks);
|
|
21
|
+
}
|
|
22
|
+
/** Interactive terminal quiz. Returns the completed lesson. */
|
|
23
|
+
export async function runQuiz(root, lesson) {
|
|
24
|
+
const cfg = loadProject(root);
|
|
25
|
+
printLesson(lesson);
|
|
26
|
+
console.log("\n" + c.bold(`Quick check (${lesson.questions.length} questions, ${Math.round(cfg.passRatio * 100)}% to pass)`));
|
|
27
|
+
const before = computeStats(listLessons(root));
|
|
28
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
29
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
30
|
+
const ask = async (prompt) => {
|
|
31
|
+
process.stdout.write(prompt);
|
|
32
|
+
const next = await lines.next();
|
|
33
|
+
return next.done ? null : String(next.value);
|
|
34
|
+
};
|
|
35
|
+
let correct = 0;
|
|
36
|
+
let response;
|
|
37
|
+
let note;
|
|
38
|
+
try {
|
|
39
|
+
for (let i = 0; i < lesson.questions.length; i++) {
|
|
40
|
+
const q = lesson.questions[i];
|
|
41
|
+
console.log(`\n${c.bold(`${i + 1}. ${q.q}`)}${q.kind ? c.dim(` [${q.kind}]`) : ""}`);
|
|
42
|
+
q.options.forEach((o, n) => console.log(` ${LETTERS[n]}) ${o}`));
|
|
43
|
+
let pick = -1;
|
|
44
|
+
while (pick < 0) {
|
|
45
|
+
const answer = await ask(c.dim(" Your answer (A-D): "));
|
|
46
|
+
if (answer === null)
|
|
47
|
+
throw new Error("Input closed before the quiz was finished.");
|
|
48
|
+
const raw = answer.trim().toUpperCase();
|
|
49
|
+
const idx = LETTERS.indexOf(raw[0] ?? "");
|
|
50
|
+
if (idx >= 0 && idx < q.options.length)
|
|
51
|
+
pick = idx;
|
|
52
|
+
}
|
|
53
|
+
if (pick === q.answer) {
|
|
54
|
+
correct += 1;
|
|
55
|
+
console.log(c.green(" Correct. ") + c.dim(q.why));
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
console.log(c.red(` Not quite. Answer: ${LETTERS[q.answer]}. `) + c.dim(q.why));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// The developer's own call. A score is not the same as understanding, so they can say "not yet" and it will not count as evidence.
|
|
62
|
+
const call = await ask(c.dim("\nDo you feel you understand this change? [Y]es / [c]larification needed / [i]nvestigate further (Enter = yes): "));
|
|
63
|
+
if (call !== null) {
|
|
64
|
+
const key = call.trim().toLowerCase()[0] || "y";
|
|
65
|
+
response = RESPONSES[key] ?? "understood";
|
|
66
|
+
if (response !== "understood")
|
|
67
|
+
note = (await ask(c.dim("What is unclear? One line, optional: "))) ?? undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
rl.close();
|
|
72
|
+
}
|
|
73
|
+
let done = complete(root, lesson, correct, cfg.passRatio);
|
|
74
|
+
if (response)
|
|
75
|
+
done = setResponse(root, done, response, note);
|
|
76
|
+
console.log("\n" + (done.status === "passed" ? c.green(`Passed ${correct}/${done.total}.`) : c.yellow(`${correct}/${done.total}. Re-read the summary, then run zevqi learn again.`)));
|
|
77
|
+
if (response && response !== "understood") {
|
|
78
|
+
console.log(c.yellow("Noted. This will not count as evidence of understanding for your team until you follow up."));
|
|
79
|
+
console.log(c.dim(`When you have looked into it, run: zevqi review ${done.changedFiles[0] ?? "<file>"}`));
|
|
80
|
+
}
|
|
81
|
+
printProgress(before, computeStats(listLessons(root)), done.status === "passed" && response !== "clarify" && response !== "investigate");
|
|
82
|
+
await syncLesson(done, cfg.share);
|
|
83
|
+
maybeNudge(root);
|
|
84
|
+
return done;
|
|
85
|
+
}
|
|
86
|
+
export async function syncLesson(lesson, share) {
|
|
87
|
+
const result = await pushRecords([toRecord(lesson, share)]);
|
|
88
|
+
if (result.error)
|
|
89
|
+
console.log(c.dim(`(team sync queued: ${result.error})`));
|
|
90
|
+
}
|
|
91
|
+
/** Short reward line after a quiz: XP earned, streak and level. Rewards understanding, never guilt. */
|
|
92
|
+
function printProgress(before, after, passed) {
|
|
93
|
+
const gained = after.xp - before.xp;
|
|
94
|
+
const parts = [c.bold(`+${gained} XP`)];
|
|
95
|
+
if (after.streak > 0)
|
|
96
|
+
parts.push(c.yellow(`${after.streak}-day streak`));
|
|
97
|
+
parts.push(`Level ${after.level} ${after.levelName}`);
|
|
98
|
+
console.log(parts.join(c.dim(" · ")));
|
|
99
|
+
console.log(c.cyan(bar(after.levelProgress)) + c.dim(after.xpToNext ? ` ${after.xpToNext} XP to next level` : " top level"));
|
|
100
|
+
if (after.level > before.level)
|
|
101
|
+
console.log(c.green(`Level up! You are now a ${after.levelName}.`));
|
|
102
|
+
else if (passed && after.streak > before.streak && after.streak >= 3)
|
|
103
|
+
console.log(c.green(`${after.streak} days in a row. Keep it going.`));
|
|
104
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
// `zevqi scan`: a summary of git history per file. It needs no model and no developer action. Only counts, dates and pseudonymous
|
|
3
|
+
// author ids leave the machine: never code, never commit messages, never email addresses.
|
|
4
|
+
/** A commit that says an AI tool helped write it. Only some tools add such a mark, so this undercounts. */
|
|
5
|
+
export const AI_MARK = /co-authored-by:[^\n]*\b(claude|anthropic|copilot|cursor|codex|openai|gemini|aider)\b|generated with \[?claude code|🤖 generated with/i;
|
|
6
|
+
const BOT = /\[bot\]|dependabot|renovate|github-actions|greenkeeper|snyk-bot/i;
|
|
7
|
+
const SKIP = /(^|\/)(node_modules|vendor|dist|build|\.next|coverage|\.git)\/|(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock|go\.sum|composer\.lock)$|\.(min\.js|min\.css|map|snap|lock|svg|png|jpe?g|gif|ico|pdf|woff2?|ttf|zip|gz)$/i;
|
|
8
|
+
export const LIMITS = { files: 5000, authorsPerFile: 8, people: 500 };
|
|
9
|
+
/** A stable, anonymous id for a person: a hash of their email. It is pseudonymous, not anonymous: anyone who already knows an email can recompute it. */
|
|
10
|
+
export const authorId = (email) => "a_" + crypto.createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 10);
|
|
11
|
+
/** Parses `git log --name-only --format=%x1e%H%x1f%an%x1f%ae%x1f%aI%x1f%s%x1f%b%x1f`. */
|
|
12
|
+
export function parseLog(raw) {
|
|
13
|
+
const out = [];
|
|
14
|
+
for (const rec of raw.split("\x1e")) {
|
|
15
|
+
if (!rec.trim())
|
|
16
|
+
continue;
|
|
17
|
+
const parts = rec.split("\x1f");
|
|
18
|
+
if (parts.length < 7)
|
|
19
|
+
continue;
|
|
20
|
+
const [hash, name, email, date, subject, body, rest] = parts;
|
|
21
|
+
if (BOT.test(name) || BOT.test(email))
|
|
22
|
+
continue;
|
|
23
|
+
const files = rest.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
24
|
+
if (files.length === 0 || !/^\d{4}-\d{2}-\d{2}/.test(date))
|
|
25
|
+
continue;
|
|
26
|
+
out.push({ hash: hash.trim(), name: name.trim(), email: email.trim(), date: date.slice(0, 10), ai: AI_MARK.test(`${subject}\n${body}`), files });
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/** Rolls commits up per file. `tracked` (the files that exist now) drops deleted and renamed-away paths. */
|
|
31
|
+
export function buildScan(repo, commits, tracked, opts) {
|
|
32
|
+
const files = new Map();
|
|
33
|
+
const people = new Map();
|
|
34
|
+
let since = "";
|
|
35
|
+
for (const c of commits) {
|
|
36
|
+
const id = authorId(c.email);
|
|
37
|
+
if (!since || c.date < since)
|
|
38
|
+
since = c.date;
|
|
39
|
+
const p = people.get(id) ?? { name: c.name, nameDate: c.date, commits: 0, ai: 0, last: c.date };
|
|
40
|
+
p.commits++;
|
|
41
|
+
if (c.ai)
|
|
42
|
+
p.ai++;
|
|
43
|
+
if (c.date > p.last)
|
|
44
|
+
p.last = c.date;
|
|
45
|
+
if (c.date >= p.nameDate) {
|
|
46
|
+
p.name = c.name;
|
|
47
|
+
p.nameDate = c.date;
|
|
48
|
+
}
|
|
49
|
+
people.set(id, p);
|
|
50
|
+
for (const path of c.files) {
|
|
51
|
+
if (SKIP.test(path) || (tracked && !tracked.has(path)))
|
|
52
|
+
continue;
|
|
53
|
+
const f = files.get(path) ?? { commits: 0, ai: 0, first: c.date, last: c.date, authors: new Map() };
|
|
54
|
+
f.commits++;
|
|
55
|
+
if (c.ai)
|
|
56
|
+
f.ai++;
|
|
57
|
+
if (c.date < f.first)
|
|
58
|
+
f.first = c.date;
|
|
59
|
+
if (c.date > f.last)
|
|
60
|
+
f.last = c.date;
|
|
61
|
+
const a = f.authors.get(id) ?? { commits: 0, last: c.date };
|
|
62
|
+
a.commits++;
|
|
63
|
+
if (c.date > a.last)
|
|
64
|
+
a.last = c.date;
|
|
65
|
+
f.authors.set(id, a);
|
|
66
|
+
files.set(path, f);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const list = [...files.entries()]
|
|
70
|
+
.sort((a, b) => b[1].commits - a[1].commits || a[0].localeCompare(b[0]))
|
|
71
|
+
.slice(0, LIMITS.files)
|
|
72
|
+
.map(([path, f]) => ({
|
|
73
|
+
path, commits: f.commits, ai: f.ai, first: f.first, last: f.last,
|
|
74
|
+
authors: [...f.authors.entries()].sort((a, b) => b[1].commits - a[1].commits).slice(0, LIMITS.authorsPerFile).map(([id, a]) => ({ id, commits: a.commits, last: a.last })),
|
|
75
|
+
}));
|
|
76
|
+
const ppl = [...people.entries()]
|
|
77
|
+
.sort((a, b) => b[1].commits - a[1].commits)
|
|
78
|
+
.slice(0, LIMITS.people)
|
|
79
|
+
.map(([id, p]) => ({ id, ...(opts.names ? { name: p.name } : {}), commits: p.commits, ai: p.ai, last: p.last }));
|
|
80
|
+
return { repo, since, commits: commits.length, files: list, people: ppl };
|
|
81
|
+
}
|
|
82
|
+
/** A quick local read-out, using the same plain rules as the dashboard's first two. */
|
|
83
|
+
export function summarize(p) {
|
|
84
|
+
const sole = p.files.filter((f) => f.authors.length === 1 && f.commits >= 3).length;
|
|
85
|
+
const ai = p.people.reduce((a, x) => a + x.ai, 0);
|
|
86
|
+
return { commits: p.commits, files: p.files.length, people: p.people.length, soleAuthorFiles: sole, aiCommits: ai, aiShare: p.commits ? Math.round((ai / p.commits) * 100) : 0 };
|
|
87
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { loadProject } from "./config.js";
|
|
4
|
+
import { complete, getLesson, knowledgeMap, listLessons, setResponse } from "./lessons.js";
|
|
5
|
+
import { syncLesson } from "./quiz.js";
|
|
6
|
+
import { escapeHtml as h, timeAgo } from "./util.js";
|
|
7
|
+
const CSS = `
|
|
8
|
+
:root{--ink:#101216;--fog:#f4f5f7;--line:#e3e5ea;--violet:#5b4bff;--lime:#c8f135;--slate:#5b6270}
|
|
9
|
+
*{box-sizing:border-box}body{margin:0;background:var(--fog);color:var(--ink);font:16px/1.55 system-ui,Segoe UI,sans-serif}
|
|
10
|
+
main{max-width:860px;margin:0 auto;padding:28px 18px 80px}
|
|
11
|
+
h1{font-size:28px;margin:0 0 4px}h2{font-size:18px;margin:28px 0 10px}
|
|
12
|
+
nav{display:flex;gap:14px;margin:10px 0 22px}nav a{color:var(--slate);text-decoration:none;font-weight:600}nav a.on{color:var(--ink);border-bottom:3px solid var(--lime)}
|
|
13
|
+
.card{background:#fff;border:1px solid var(--line);border-radius:16px;padding:16px 18px;margin:10px 0}
|
|
14
|
+
.pill{display:inline-block;border-radius:99px;padding:2px 10px;font-size:12px;font-weight:700}
|
|
15
|
+
.p-pending{background:#fff1e6;color:#b45309}.p-passed{background:#e8f9c6;color:#3d5a00}.p-failed{background:#fde8e8;color:#9b1c1c}
|
|
16
|
+
.muted{color:var(--slate);font-size:14px}code{background:#eef0f3;border-radius:6px;padding:1px 6px;font-size:13px}
|
|
17
|
+
button{border:0;border-radius:99px;background:var(--violet);color:#fff;font-weight:700;padding:10px 20px;cursor:pointer;font-size:15px}
|
|
18
|
+
label.opt{display:block;border:1px solid var(--line);border-radius:12px;padding:10px 12px;margin:8px 0;cursor:pointer;background:#fff}
|
|
19
|
+
label.opt:hover{border-color:var(--violet)}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:8px 6px;border-bottom:1px solid var(--line);font-size:14px}
|
|
20
|
+
.kind{display:inline-block;background:var(--ink);color:#fff;border-radius:6px;padding:1px 7px;font-size:11px;font-weight:700;margin-right:6px;text-transform:uppercase;letter-spacing:.04em}ul.pts{margin:6px 0 0;padding-left:20px}.pts li{margin:3px 0}textarea,input[type=text]{width:100%;border:1px solid var(--line);border-radius:10px;padding:8px 10px;font:inherit}
|
|
21
|
+
.bar{height:8px;border-radius:99px;background:#e3e5ea;overflow:hidden}.bar i{display:block;height:100%;background:var(--lime)}
|
|
22
|
+
`;
|
|
23
|
+
function page(title, body, tab, token) {
|
|
24
|
+
const tabs = [["", "Lessons"], ["map", "Knowledge map"]];
|
|
25
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${h(title)} · Zevqi</title><style>${CSS}</style></head><body><main>
|
|
26
|
+
<h1>Zevqi</h1><div class="muted">Understand what your agent wrote.</div>
|
|
27
|
+
<nav>${tabs.map(([p, l]) => `<a class="${tab === p ? "on" : ""}" href="/${p}?t=${token}">${l}</a>`).join("")}</nav>${body}</main></body></html>`;
|
|
28
|
+
}
|
|
29
|
+
function badge(l) {
|
|
30
|
+
return `<span class="pill p-${l.status}">${l.status}${l.status !== "pending" && l.total ? ` ${l.correct}/${l.total}` : ""}</span>`;
|
|
31
|
+
}
|
|
32
|
+
function home(root, token) {
|
|
33
|
+
const lessons = listLessons(root);
|
|
34
|
+
if (lessons.length === 0)
|
|
35
|
+
return page("Lessons", `<div class="card">No lessons yet. After your agent edits files and finishes a turn, a lesson shows up here.</div>`, "", token);
|
|
36
|
+
const rows = lessons
|
|
37
|
+
.slice(0, 50)
|
|
38
|
+
.map((l) => `<div class="card"><div>${badge(l)} <span class="muted">${h(timeAgo(l.createdAt))} · ${h(l.repo)}</span></div>
|
|
39
|
+
<p style="margin:8px 0 6px">${h(l.summary.slice(0, 220))}${l.summary.length > 220 ? "…" : ""}</p>
|
|
40
|
+
<div class="muted">${l.changedFiles.slice(0, 4).map((f) => `<code>${h(f)}</code>`).join(" ")}${l.changedFiles.length > 4 ? ` +${l.changedFiles.length - 4} more` : ""}</div>
|
|
41
|
+
<p style="margin:10px 0 0"><a href="/lesson/${l.id}?t=${token}">${l.status === "pending" ? "Take the quiz →" : "Review →"}</a></p></div>`)
|
|
42
|
+
.join("");
|
|
43
|
+
const open = lessons.filter((l) => l.status === "pending").length;
|
|
44
|
+
return page("Lessons", `<p><b>${open}</b> waiting for review.</p>${rows}`, "", token);
|
|
45
|
+
}
|
|
46
|
+
function lessonPage(l, token) {
|
|
47
|
+
const files = l.files.map((f) => `<tr><td><code>${h(f.path)}</code></td><td>${h(f.note)}</td></tr>`).join("");
|
|
48
|
+
const points = (title, items) => (items?.length ? `<h2 style="margin-top:14px;font-size:15px">${h(title)}</h2><ul class="pts">${items.map((x) => `<li>${h(x)}</li>`).join("")}</ul>` : "");
|
|
49
|
+
const qs = l.questions
|
|
50
|
+
.map((q, i) => `<div class="card">${q.kind ? `<span class="kind">${h(q.kind)}</span>` : ""}<b>${i + 1}. ${h(q.q)}</b>${q.options.map((o, n) => `<label class="opt"><input type="radio" name="q${i}" value="${n}" ${l.status !== "pending" ? "disabled" : ""}> ${h(o)}</label>`).join("")}<div class="muted why" id="why${i}"></div></div>`)
|
|
51
|
+
.join("");
|
|
52
|
+
const script = `
|
|
53
|
+
const id=${JSON.stringify(l.id)},token=${JSON.stringify(token)},answers=${JSON.stringify(l.questions.map((q) => q.answer))},whys=${JSON.stringify(l.questions.map((q) => q.why))};
|
|
54
|
+
document.getElementById('go').onclick=async()=>{
|
|
55
|
+
const picks=answers.map((_,i)=>{const r=document.querySelector('input[name=q'+i+']:checked');return r?Number(r.value):-1});
|
|
56
|
+
if(picks.includes(-1)){alert('Answer every question first.');return}
|
|
57
|
+
let correct=0;picks.forEach((p,i)=>{const ok=p===answers[i];if(ok)correct++;document.getElementById('why'+i).innerHTML=(ok?'✅ Correct. ':'❌ Not quite. ')+whys[i]});
|
|
58
|
+
const r=await fetch('/api/answer?t='+token,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({id,correct,response:(document.querySelector('input[name=call]:checked')||{}).value||'understood',note:(document.getElementById('note')||{}).value||''})});
|
|
59
|
+
const j=await r.json();document.getElementById('result').textContent=j.status==='passed'?'Passed '+correct+'/'+answers.length+'.':correct+'/'+answers.length+'. Re-read the summary and try again from the terminal: zevqi learn';
|
|
60
|
+
document.getElementById('go').disabled=true};`;
|
|
61
|
+
return page("Lesson", `<p><a href="/?t=${token}">← All lessons</a></p><div class="card">${badge(l)} <span class="muted">${h(timeAgo(l.createdAt))}</span><h2 style="margin-top:8px">What changed</h2><p>${h(l.summary)}</p><table>${files}</table>${points("Decisions in the code", l.decisions)}${points("It depends on", l.depends)}${points("What could break", l.risks)}</div>
|
|
62
|
+
<h2>Quick check</h2>${qs}${l.status === "pending" ? `<div class="card" id="callbox"><b>Do you feel you understand this change?</b><p class="muted" style="margin:4px 0 8px">A score is not the same as understanding. If you are not sure, say so. It will not count as evidence for your team until you follow up.</p><label class="opt"><input type="radio" name="call" value="understood" checked> Yes, I understand it</label><label class="opt"><input type="radio" name="call" value="clarify"> I need clarification</label><label class="opt"><input type="radio" name="call" value="investigate"> I need to investigate further</label><input type="text" id="note" maxlength="300" placeholder="What is unclear? Optional" style="margin-top:6px"></div><p><button id="go">Check my answers</button></p><p id="result" class="muted"></p><script>${script}</script>` : `<p class="muted">Already completed.</p>`}`, "", token);
|
|
63
|
+
}
|
|
64
|
+
function mapPage(root, token) {
|
|
65
|
+
const rows = knowledgeMap(root)
|
|
66
|
+
.map((f) => {
|
|
67
|
+
const pct = f.changes ? Math.round((f.passed / f.changes) * 100) : 0;
|
|
68
|
+
return `<tr><td><code>${h(f.path)}</code></td><td>${f.changes}</td><td style="width:140px"><div class="bar"><i style="width:${pct}%"></i></div></td><td>${pct}%</td><td>${f.open ? `<span class="pill p-pending">${f.open} open</span>` : ""}</td></tr>`;
|
|
69
|
+
})
|
|
70
|
+
.join("");
|
|
71
|
+
return page("Knowledge map", `<p class="muted">How much of each AI-changed file you have actually reviewed. Files with open lessons are the ones nobody has checked yet.</p><div class="card"><table><tr><th>File</th><th>AI changes</th><th>Understood</th><th></th><th></th></tr>${rows || `<tr><td colspan=5 class="muted">Nothing yet.</td></tr>`}</table></div>`, "map", token);
|
|
72
|
+
}
|
|
73
|
+
export function startServer(root, port, onReady) {
|
|
74
|
+
const token = crypto.randomBytes(12).toString("hex"); // keeps other websites and local processes from posting answers
|
|
75
|
+
const server = http.createServer((req, res) => {
|
|
76
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
77
|
+
const host = (req.headers.host ?? "").split(":")[0];
|
|
78
|
+
if (host !== "127.0.0.1" && host !== "localhost") {
|
|
79
|
+
res.writeHead(403).end("Forbidden");
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (url.searchParams.get("t") !== token) {
|
|
83
|
+
res.writeHead(403, { "content-type": "text/plain" }).end("Open the link printed by `zevqi ui`.");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const send = (code, type, body) => res.writeHead(code, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff" }).end(body);
|
|
87
|
+
if (req.method === "POST" && url.pathname === "/api/answer") {
|
|
88
|
+
let raw = "";
|
|
89
|
+
req.on("data", (d) => (raw += d));
|
|
90
|
+
req.on("end", async () => {
|
|
91
|
+
try {
|
|
92
|
+
const { id, correct, response, note } = JSON.parse(raw);
|
|
93
|
+
const lesson = getLesson(root, id);
|
|
94
|
+
if (!lesson || lesson.status !== "pending")
|
|
95
|
+
return send(404, "application/json", JSON.stringify({ error: "not found" }));
|
|
96
|
+
const cfg = loadProject(root);
|
|
97
|
+
let done = complete(root, lesson, Math.max(0, Math.min(lesson.questions.length, Number(correct) || 0)), cfg.passRatio);
|
|
98
|
+
if (response === "understood" || response === "clarify" || response === "investigate")
|
|
99
|
+
done = setResponse(root, done, response, typeof note === "string" ? note : undefined);
|
|
100
|
+
await syncLesson(done, cfg.share);
|
|
101
|
+
send(200, "application/json", JSON.stringify({ status: done.status }));
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
send(400, "application/json", JSON.stringify({ error: "bad request" }));
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (url.pathname === "/")
|
|
110
|
+
return send(200, "text/html; charset=utf-8", home(root, token));
|
|
111
|
+
if (url.pathname === "/map")
|
|
112
|
+
return send(200, "text/html; charset=utf-8", mapPage(root, token));
|
|
113
|
+
const m = url.pathname.match(/^\/lesson\/(l_[a-f0-9]+)$/);
|
|
114
|
+
if (m) {
|
|
115
|
+
const lesson = getLesson(root, m[1]);
|
|
116
|
+
return lesson ? send(200, "text/html; charset=utf-8", lessonPage(lesson, token)) : send(404, "text/plain", "Not found");
|
|
117
|
+
}
|
|
118
|
+
send(404, "text/plain", "Not found");
|
|
119
|
+
});
|
|
120
|
+
server.listen(port, "127.0.0.1", () => onReady(`http://127.0.0.1:${port}/?t=${token}`));
|
|
121
|
+
return server;
|
|
122
|
+
}
|