qatools-cli 1.2.23 → 1.2.24

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.
Files changed (4) hide show
  1. package/brief.js +51 -0
  2. package/hooks.js +124 -0
  3. package/package.json +4 -2
  4. package/qatools.js +77 -0
package/brief.js ADDED
@@ -0,0 +1,51 @@
1
+ // context.session-brief: the short brief a Claude session starts with. Pure: data in, text out (at most 30 lines).
2
+ const MAX_LINES = 30;
3
+
4
+ function renderBrief({ projectName = "", requirements = [], agenda = null, requests = [], branch = "", branchKeys = [], main = "" }) {
5
+ const lines = [`qa-tools brief${projectName ? ` — ${projectName}` : ""} (read this before you start)`];
6
+ const verified = (r) => r.status === "implemented" || r.status === "tested";
7
+ const who = (e) => /^claude@[^@]+\.qatools$/i.test(String(e || "")) ? "Claude" : (e || "nobody");
8
+
9
+ const inProgress = requirements.filter(r => r.status === "in_progress");
10
+ if (inProgress.length) {
11
+ lines.push(`In progress (${inProgress.length}):`);
12
+ for (const r of inProgress.slice(0, 6)) lines.push(`- ${r.key} — ${who(r.assignedTo)}`);
13
+ if (inProgress.length > 6) lines.push(`- … and ${inProgress.length - 6} more (qatools requirements --status in_progress)`);
14
+ }
15
+
16
+ const off = requirements.filter(r => verified(r) && r.notOnMain);
17
+ const risk = requirements.filter(r => verified(r) && r.regressionRisk);
18
+ if (off.length || risk.length) {
19
+ lines.push("Needs attention:");
20
+ for (const r of off.slice(0, 4)) lines.push(`- ${r.key}: done but NOT on ${r.notOnMain.main || "main"} — on ${r.notOnMain.branch || "a branch"} since ${String(r.notOnMain.since || "").slice(0, 10)}`);
21
+ for (const r of risk.slice(0, 4)) lines.push(`- ${r.key}: regression risk — other work changed its code; verify again`);
22
+ }
23
+
24
+ if (agenda) {
25
+ const a = agenda;
26
+ const parts = [
27
+ [a.pendingSessions, "sessions to analyse"], [a.approvedNoCoverage, "approved without tests"],
28
+ [a.sprintReqsNotTested, "sprint requirements not tested"], [a.draftReqs, "drafts to review"],
29
+ [a.continuousUnverified, "continuous requirements unverified this sprint"],
30
+ ].filter(([v]) => Array.isArray(v) && v.length).map(([v, t]) => `${v.length} ${t}`);
31
+ if (parts.length) lines.push(`Agenda: ${parts.join(", ")} (MCP get_agenda, or the project dashboard)`);
32
+ }
33
+
34
+ const hot = requests.filter(r => r.status === "new" || r.state === "new").sort((x, y) => (y.votes || 0) - (x.votes || 0)).slice(0, 3);
35
+ if (hot.length) {
36
+ lines.push("Hottest new user requests:");
37
+ for (const r of hot) lines.push(`- ▲${r.votes || 0} ${String(r.title || "").slice(0, 80)}`);
38
+ }
39
+
40
+ if (branch && main && branch !== main.replace(/^origin\//, "")) {
41
+ lines.push(branchKeys.length
42
+ ? `Branch ${branch} (not on ${main}) works on: ${branchKeys.slice(0, 8).join(", ")}${branchKeys.length > 8 ? " …" : ""}`
43
+ : `Branch ${branch} has no commits naming a requirement yet.`);
44
+ }
45
+
46
+ if (lines.length === 1) lines.push("Nothing in progress or flagged. Pick an approved requirement: qatools requirements --status approved");
47
+ lines.push("Commits name their requirement or signal: feat(<key>): … / fix(AVV-n): … / chore: …");
48
+ return lines.slice(0, MAX_LINES).join("\n");
49
+ }
50
+
51
+ module.exports = { renderBrief, MAX_LINES };
package/hooks.js ADDED
@@ -0,0 +1,124 @@
1
+ // traceability.commit-names-requirement and context.session-brief: the git commit-msg hook, the Claude Code
2
+ // SessionStart hook, and the requirement-key cache the commit hook reads. No dependencies, so the hook starts fast.
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { execFileSync } = require("child_process");
6
+
7
+ const HOUSEKEEPING = new Set(["chore", "docs", "ci", "build", "test", "style"]);
8
+ const MARK = "# qatools commit-msg hook";
9
+
10
+ const gitPath = (cwd, what) => {
11
+ try { return path.resolve(cwd, execFileSync("git", ["rev-parse", "--git-path", what], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()); }
12
+ catch { return null; }
13
+ };
14
+ const keyCachePath = (cwd = process.cwd()) => gitPath(cwd, "qatools-keys.json");
15
+
16
+ function writeKeyCache(cwd, projectId, keys) {
17
+ const p = keyCachePath(cwd);
18
+ if (!p) return false;
19
+ fs.writeFileSync(p, JSON.stringify({ projectId, keys: [...new Set(keys)].sort(), at: new Date().toISOString() }));
20
+ return true;
21
+ }
22
+ function readKeyCache(cwd = process.cwd()) {
23
+ try { return JSON.parse(fs.readFileSync(keyCachePath(cwd), "utf8")); } catch { return null; }
24
+ }
25
+
26
+ // Requirement keys that share a word with the message, best first
27
+ function suggestKeys(message, keys, max = 3) {
28
+ const words = new Set(String(message).toLowerCase().match(/[a-zåäö0-9]{4,}/g) || []);
29
+ const score = (k) => k.toLowerCase().split(/[.\-_]/).filter(seg => [...words].some(w => seg.startsWith(w) || w.startsWith(seg) && seg.length >= 4)).length;
30
+ return keys.map(k => [k, score(k)]).filter(([, s]) => s > 0).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, max).map(([k]) => k);
31
+ }
32
+
33
+ // Does a commit message name a requirement key or a signal? { ok, warning?, reason?, suggestions? }
34
+ function checkMessage(message, keys) {
35
+ const msg = String(message || "").replace(/^#.*$/gm, "").trim();
36
+ const first = msg.split("\n")[0];
37
+ if (!msg) return { ok: true }; // git refuses empty messages itself
38
+ if (/^(Merge|Revert|fixup!|squash!|amend!)\b/.test(first)) return { ok: true };
39
+ const type = first.match(/^([a-z]+)(\([^)]*\))?!?:/);
40
+ if (type && HOUSEKEEPING.has(type[1])) return { ok: true };
41
+ if (/\b[A-Z][A-Z_]{1,24}-\d+\b/.test(msg)) return { ok: true }; // a signal: AVV-15, GAP-3, DEF-7, IMP-2 (and older labels)
42
+ if (!keys) return { ok: true, warning: "qa-tools: requirement keys are not cached, so the commit message was not checked (run qatools brief or qatools sync)." };
43
+ const known = new Set(keys);
44
+ if (/\[req:([\w.\-/]+)\]/i.test(msg) && known.has(msg.match(/\[req:([\w.\-/]+)\]/i)[1])) return { ok: true };
45
+ const candidates = msg.match(/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g) || [];
46
+ if (candidates.some(c => known.has(c))) return { ok: true };
47
+ const unknown = candidates.filter(c => /^[a-z]/.test(c) && !/\.(ts|js|json|md|html|scss|css|cs|py|yml|yaml)$/i.test(c));
48
+ return {
49
+ ok: false,
50
+ reason: unknown.length
51
+ ? `${unknown[0]} is not a requirement key in this project.`
52
+ : "The message names no requirement key and no signal.",
53
+ suggestions: suggestKeys(msg, keys),
54
+ };
55
+ }
56
+
57
+ function refusalText(res) {
58
+ return [
59
+ "✗ qa-tools: name the requirement or signal this commit belongs to.",
60
+ ` ${res.reason}`,
61
+ " Examples: feat(reports.export): … fix(AVV-15): … chore: … (housekeeping)",
62
+ ...(res.suggestions?.length ? [` Keys that match words in your message: ${res.suggestions.join(", ")}`] : []),
63
+ " All keys: qatools requirement-keys",
64
+ ].join("\n");
65
+ }
66
+
67
+ // Runs inside the git hook: exit 1 refuses the commit
68
+ function runCommitCheck(file, cwd = process.cwd()) {
69
+ let message = "";
70
+ try { message = fs.readFileSync(file, "utf8"); } catch { return 0; }
71
+ const res = checkMessage(message, readKeyCache(cwd)?.keys || null);
72
+ if (res.warning) console.error(res.warning);
73
+ if (res.ok) return 0;
74
+ console.error(refusalText(res));
75
+ return 1;
76
+ }
77
+
78
+ // Install the commit-msg hook; an existing one is kept as commit-msg.local and runs first
79
+ function installCommitHook(cwd = process.cwd()) {
80
+ const dir = gitPath(cwd, "hooks");
81
+ if (!dir) return { installed: false, reason: "not a git repository" };
82
+ fs.mkdirSync(dir, { recursive: true });
83
+ const hook = path.join(dir, "commit-msg");
84
+ if (fs.existsSync(hook)) {
85
+ const cur = fs.readFileSync(hook, "utf8");
86
+ if (cur.includes(MARK)) return { installed: true, already: true, path: hook };
87
+ fs.renameSync(hook, path.join(dir, "commit-msg.local"));
88
+ }
89
+ fs.writeFileSync(hook, [
90
+ "#!/bin/sh",
91
+ MARK + " (traceability.commit-names-requirement) — written by qatools init",
92
+ 'HOOKS="$(dirname "$0")"',
93
+ 'if [ -x "$HOOKS/commit-msg.local" ]; then "$HOOKS/commit-msg.local" "$@" || exit $?; fi',
94
+ 'command -v qatools >/dev/null 2>&1 || exit 0',
95
+ '# Only the qa-tools check itself may refuse; an old CLI or any other failure lets the commit through',
96
+ 'OUT="$(qatools commit-check "$1" 2>&1)"; CODE=$?',
97
+ 'if [ $CODE -eq 1 ] && printf "%s" "$OUT" | grep -q "qa-tools: name the requirement"; then printf "%s\\n" "$OUT" >&2; exit 1; fi',
98
+ 'case "$OUT" in *qa-tools:*) printf "%s\\n" "$OUT" >&2 ;; esac',
99
+ 'exit 0',
100
+ "",
101
+ ].join("\n"));
102
+ try { fs.chmodSync(hook, 0o755); } catch {}
103
+ return { installed: true, path: hook };
104
+ }
105
+
106
+ // Add the SessionStart hook to .claude/settings.json, keeping everything already there
107
+ const BRIEF_COMMAND = "qatools brief --hook";
108
+ function installSessionHook(cwd = process.cwd()) {
109
+ const dir = path.join(cwd, ".claude");
110
+ const file = path.join(dir, "settings.json");
111
+ let settings = {};
112
+ if (fs.existsSync(file)) {
113
+ try { settings = JSON.parse(fs.readFileSync(file, "utf8")); } catch { return { installed: false, reason: `${file} is not valid JSON — left untouched` }; }
114
+ }
115
+ settings.hooks = settings.hooks || {};
116
+ const list = settings.hooks.SessionStart = settings.hooks.SessionStart || [];
117
+ if (list.some(m => (m.hooks || []).some(h => h.command === BRIEF_COMMAND))) return { installed: true, already: true, path: file };
118
+ list.push({ hooks: [{ type: "command", command: BRIEF_COMMAND, timeout: 10 }] });
119
+ fs.mkdirSync(dir, { recursive: true });
120
+ fs.writeFileSync(file, JSON.stringify(settings, null, 2) + "\n");
121
+ return { installed: true, path: file };
122
+ }
123
+
124
+ module.exports = { checkMessage, suggestKeys, runCommitCheck, installCommitHook, installSessionHook, writeKeyCache, readKeyCache, BRIEF_COMMAND, MARK };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qatools-cli",
3
- "version": "1.2.23",
3
+ "version": "1.2.24",
4
4
  "description": "CLI for QA Tools — requirements, epics, sprints, sessions, App Context sync, project agenda. The companion to qa-tools.com.",
5
5
  "scripts": {
6
6
  "release": "npm version patch --no-git-tag-version && npm publish",
@@ -13,7 +13,9 @@
13
13
  "files": [
14
14
  "qatools.js",
15
15
  "impact.js",
16
- "context-sync.js"
16
+ "context-sync.js",
17
+ "hooks.js",
18
+ "brief.js"
17
19
  ],
18
20
  "keywords": [
19
21
  "qa",
package/qatools.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // traceability.commit-names-requirement: the git commit-msg hook calls this — no Firebase, no network
4
+ if (process.argv[2] === "commit-check") process.exit(require("./hooks").runCommitCheck(process.argv[3]));
5
+
3
6
  const { program } = require("commander");
4
7
  const { initializeApp } = require("@firebase/app");
5
8
  const { getAuth, signInWithEmailAndPassword, signInWithCustomToken } = require("@firebase/auth");
@@ -880,6 +883,68 @@ program
880
883
  process.exit(0);
881
884
  });
882
885
 
886
+ // context.session-brief: what a session starts with. --hook: for Claude Code's SessionStart hook — never blocks,
887
+ // prints nothing on any failure, gives up after 5 seconds.
888
+ program
889
+ .command("brief")
890
+ .description("A short brief of the project for the start of a session: in progress, flagged, agenda, hot requests, this branch")
891
+ .option("--hook", "For the SessionStart hook: silent on failure, at most 5 seconds")
892
+ .option("--project <id>", "Target project ID (overrides default)")
893
+ .action(async (options) => {
894
+ const hook = !!options.hook;
895
+ if (hook) setTimeout(() => process.exit(0), 5000).unref();
896
+ const quietExit = (msg) => { if (!hook && msg) console.error(msg); process.exit(hook ? 0 : 1); };
897
+ try {
898
+ if (hook && !getCredentials()) quietExit();
899
+ if (hook) {
900
+ // authenticate() exits the process on failure; in hook mode that must stay silent and successful
901
+ const realExit = process.exit;
902
+ process.exit = () => realExit(0);
903
+ const realErr = console.error;
904
+ console.error = () => {};
905
+ try { await authenticate(options); } finally { process.exit = realExit; console.error = realErr; }
906
+ } else {
907
+ await authenticate(options);
908
+ }
909
+ const creds = getCredentials();
910
+ const projectId = options.project || creds?.projectId;
911
+ if (!projectId) return quietExit("No project configured. Run: qatools setup, or pass --project <id>");
912
+ const call = (name, data) => httpsCallable(functions, name)(data).then(r => r.data).catch(() => null);
913
+ const [reqRes, agendaRes, reqsRes] = await Promise.all([
914
+ call("listRequirements", { projectId, status: null }),
915
+ call("getProjectAgenda", { projectId }),
916
+ call("listFeatureRequests", { projectId }),
917
+ ]);
918
+ if (!reqRes) return quietExit("Could not read the project's requirements");
919
+ const requirements = reqRes.requirements || [];
920
+ const hooks = require("./hooks");
921
+ try { hooks.writeKeyCache(process.cwd(), projectId, requirements.map(r => r.key).filter(Boolean)); } catch {}
922
+ // The current branch and the requirement keys its own commits name
923
+ let branch = "", main = "", branchKeys = [];
924
+ try {
925
+ const { isGitRepo, mainRef, keysIn } = require("./impact");
926
+ if (isGitRepo(process.cwd())) {
927
+ const { execFileSync } = require("child_process");
928
+ const git = (args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
929
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
930
+ main = mainRef(process.cwd()) || "";
931
+ if (main && branch !== "HEAD") {
932
+ const known = new Set(requirements.map(r => r.key));
933
+ const found = new Set();
934
+ for (const m of git(["log", "--format=%B", "-n", "300", `${main}..HEAD`]).split("\n")) for (const k of keysIn(m, known)) found.add(k);
935
+ branchKeys = [...found].sort();
936
+ }
937
+ }
938
+ } catch {}
939
+ const { renderBrief } = require("./brief");
940
+ console.log(renderBrief({ projectName: creds?.projectName || "", requirements, agenda: agendaRes?.agenda || null,
941
+ requests: reqsRes?.requests || [], branch, main, branchKeys }));
942
+ process.exit(0);
943
+ } catch (e) {
944
+ quietExit("Failed: " + e.message);
945
+ }
946
+ });
947
+
883
948
  // signals.user-feature-requests: connect an app's own request page, and see what has arrived
884
949
  program
885
950
  .command("requests-integration-prompt")
@@ -1504,6 +1569,7 @@ async function renderSyncedContext(ctx, projectId, systemAiRules) {
1504
1569
  httpsCallable(functions, "listEpics")({ projectId }),
1505
1570
  ]);
1506
1571
  const { renderToolsSection } = require("./context-sync");
1572
+ try { require("./hooks").writeKeyCache(process.cwd(), projectId, (reqRes.data.requirements || []).map(r => r.key).filter(Boolean)); } catch {}
1507
1573
  return renderAppContextMarkdown(ctx, projectId, systemAiRules) + "\n" + renderToolsSection() + "\n" + renderBuiltSection(reqRes.data.requirements || [], epicRes.data.epics || []);
1508
1574
  }
1509
1575
 
@@ -3282,6 +3348,17 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3282
3348
  console.log(` ⚠ Sync skipped (${e.message})`);
3283
3349
  }
3284
3350
 
3351
+ // context.session-brief + traceability.commit-names-requirement: the hooks that keep the memory current
3352
+ try {
3353
+ const hooks = require("./hooks");
3354
+ const sh = hooks.installSessionHook(cwd);
3355
+ console.log(sh.installed ? ` ✓ Session brief hook ${sh.already ? "already in" : "added to"} .claude/settings.json (qatools brief --hook)` : ` ⚠ Session brief hook not added: ${sh.reason}`);
3356
+ const ch = hooks.installCommitHook(cwd);
3357
+ console.log(ch.installed ? ` ✓ Commit message check ${ch.already ? "already installed" : "installed"} (${path.relative(cwd, ch.path)})` : ` ⚠ Commit message check not installed: ${ch.reason}`);
3358
+ } catch (e) {
3359
+ console.log(` ⚠ Hooks skipped (${e.message})`);
3360
+ }
3361
+
3285
3362
  // Step 5/5: Show agenda
3286
3363
  console.log("\nStep 5/5: Project agenda\n");
3287
3364
  try {