qatools-cli 1.2.23 → 1.2.25

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/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,164 @@
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. Just created the requirement? qatools brief refreshes the key list.",
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
+ // security.no-secrets-in-commits: the pre-commit hook; an existing one is kept as pre-commit.local and runs first
107
+ const PRE_MARK = "# qatools pre-commit hook";
108
+ function installPreCommitHook(cwd = process.cwd()) {
109
+ const dir = gitPath(cwd, "hooks");
110
+ if (!dir) return { installed: false, reason: "not a git repository" };
111
+ fs.mkdirSync(dir, { recursive: true });
112
+ const hook = path.join(dir, "pre-commit");
113
+ if (fs.existsSync(hook)) {
114
+ const cur = fs.readFileSync(hook, "utf8");
115
+ if (cur.includes(PRE_MARK)) return { installed: true, already: true, path: hook };
116
+ fs.renameSync(hook, path.join(dir, "pre-commit.local"));
117
+ }
118
+ fs.writeFileSync(hook, [
119
+ "#!/bin/sh",
120
+ PRE_MARK + " (security.no-secrets-in-commits) — written by qatools init",
121
+ 'HOOKS="$(dirname "$0")"',
122
+ 'if [ -x "$HOOKS/pre-commit.local" ]; then "$HOOKS/pre-commit.local" "$@" || exit $?; fi',
123
+ 'command -v qatools >/dev/null 2>&1 || exit 0',
124
+ '# Only the qa-tools check itself may refuse; an old CLI or any other failure lets the commit through',
125
+ 'OUT="$(qatools secret-check 2>&1)"; CODE=$?',
126
+ 'if [ $CODE -eq 1 ] && printf "%s" "$OUT" | grep -q "qa-tools: this commit adds a secret"; then printf "%s\\n" "$OUT" >&2; exit 1; fi',
127
+ 'exit 0',
128
+ "",
129
+ ].join("\n"));
130
+ try { fs.chmodSync(hook, 0o755); } catch {}
131
+ return { installed: true, path: hook };
132
+ }
133
+
134
+ // Which qa-tools hooks a repo has: { commitMsg, preCommit, sessionBrief }
135
+ function hookStatus(cwd = process.cwd()) {
136
+ const dir = gitPath(cwd, "hooks");
137
+ const has = (name, mark) => { try { return !!dir && fs.readFileSync(path.join(dir, name), "utf8").includes(mark); } catch { return false; } };
138
+ let sessionBrief = false;
139
+ try {
140
+ const s = JSON.parse(fs.readFileSync(path.join(cwd, ".claude", "settings.json"), "utf8"));
141
+ sessionBrief = (s.hooks?.SessionStart || []).some(m => (m.hooks || []).some(h => h.command === BRIEF_COMMAND));
142
+ } catch {}
143
+ return { commitMsg: has("commit-msg", MARK), preCommit: has("pre-commit", PRE_MARK), sessionBrief };
144
+ }
145
+
146
+ // Add the SessionStart hook to .claude/settings.json, keeping everything already there
147
+ const BRIEF_COMMAND = "qatools brief --hook";
148
+ function installSessionHook(cwd = process.cwd()) {
149
+ const dir = path.join(cwd, ".claude");
150
+ const file = path.join(dir, "settings.json");
151
+ let settings = {};
152
+ if (fs.existsSync(file)) {
153
+ try { settings = JSON.parse(fs.readFileSync(file, "utf8")); } catch { return { installed: false, reason: `${file} is not valid JSON — left untouched` }; }
154
+ }
155
+ settings.hooks = settings.hooks || {};
156
+ const list = settings.hooks.SessionStart = settings.hooks.SessionStart || [];
157
+ if (list.some(m => (m.hooks || []).some(h => h.command === BRIEF_COMMAND))) return { installed: true, already: true, path: file };
158
+ list.push({ hooks: [{ type: "command", command: BRIEF_COMMAND, timeout: 10 }] });
159
+ fs.mkdirSync(dir, { recursive: true });
160
+ fs.writeFileSync(file, JSON.stringify(settings, null, 2) + "\n");
161
+ return { installed: true, path: file };
162
+ }
163
+
164
+ module.exports = { checkMessage, suggestKeys, runCommitCheck, installCommitHook, installPreCommitHook, hookStatus, installSessionHook, writeKeyCache, readKeyCache, BRIEF_COMMAND, MARK, PRE_MARK };
package/impact.js CHANGED
@@ -183,4 +183,30 @@ function unmergedBranches({ cwd, main, knownKeys }) {
183
183
  return out.sort((x, y) => String(y.newest).localeCompare(String(x.newest)));
184
184
  }
185
185
 
186
- module.exports = { computeImpact, isGitRepo, baseForDate, keysIn, DEFAULT_IGNORE, mainRef, notOnMain, unmergedBranches, evidenceCommit };
186
+ // traceability.evidence-commit-backfill: for verified requirements without an evidence commit, the newest commit on
187
+ // main whose message names the key exactly (not just a longer key that starts the same way)
188
+ // A commit names a key as its own when the key is in the subject, or in the body as "key: …" at the start of a line,
189
+ // "(key)" or "[req:key]" — not when the body only mentions it, e.g. as a quoted example.
190
+ function namesAsOwn(subject, body, key, known) {
191
+ if (keysIn(subject, known).has(key)) return true;
192
+ const k = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
193
+ // …or as part of a list of keys that starts a line: "a.b, c.d, e.f. From …"
194
+ // …or "Implements / Fixes / Closes / Resolves / Refs <key>"
195
+ return new RegExp(`(^|\\n)\\s*[-*]?\\s*([a-z0-9][\\w-]*(\\.[\\w-]+)+\\s*,\\s*)*${k}(?![\\w-]|\\.[\\w-])\\s*[:,.]?(\\s|$)|\\(${k}\\)|\\[req:${k}\\]|\\b(implements|fixes|closes|resolves|refs)\\s+${k}(?![\\w-]|\\.[\\w-])`, "i").test(body);
196
+ }
197
+
198
+ function findKeyCommits({ cwd, requirements, main }) {
199
+ const known = new Set(requirements.map(r => r.key).filter(Boolean));
200
+ const found = [], none = [];
201
+ for (const r of requirements) {
202
+ if (r.status !== "implemented" && r.status !== "tested") continue;
203
+ if (evidenceCommit(r)) continue;
204
+ const log = git(cwd, ["log", main, "-F", `--grep=${r.key}`, "-n", "30", "--format=%x1e%H%x1f%cs%x1f%s%x1f%B"]);
205
+ const hit = log.split("\x1e").filter(Boolean).map(c => c.split("\x1f")).find(([, , subject, body]) => namesAsOwn(subject || "", body || "", r.key, known));
206
+ if (hit) found.push({ id: r.id, key: r.key, commit: hit[0].trim(), date: hit[1], subject: (hit[2] || "").trim() });
207
+ else none.push(r.key);
208
+ }
209
+ return { found, none };
210
+ }
211
+
212
+ module.exports = { computeImpact, isGitRepo, baseForDate, keysIn, DEFAULT_IGNORE, mainRef, notOnMain, unmergedBranches, evidenceCommit, findKeyCommits };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qatools-cli",
3
- "version": "1.2.23",
3
+ "version": "1.2.25",
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,10 @@
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",
19
+ "secrets.js"
17
20
  ],
18
21
  "keywords": [
19
22
  "qa",
package/qatools.js CHANGED
@@ -1,5 +1,10 @@
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
+ // security.no-secrets-in-commits: the git pre-commit hook calls this — no Firebase, no network
6
+ if (process.argv[2] === "secret-check") process.exit(require("./secrets").runSecretCheck());
7
+
3
8
  const { program } = require("commander");
4
9
  const { initializeApp } = require("@firebase/app");
5
10
  const { getAuth, signInWithEmailAndPassword, signInWithCustomToken } = require("@firebase/auth");
@@ -880,6 +885,115 @@ program
880
885
  process.exit(0);
881
886
  });
882
887
 
888
+ // security.repo-doctor: secrets in files and history, and the qa-tools hooks. No network; exit 1 when a secret is found.
889
+ program
890
+ .command("doctor")
891
+ .description("Check this repo: secrets in tracked files (and in history with --history), qa-tools hooks, the synced CLAUDE.md block")
892
+ .option("--history", "Also search the whole git history (slower)")
893
+ .option("--json", "Output as JSON")
894
+ .action((options) => {
895
+ const cwd = process.cwd();
896
+ const { isGitRepo } = require("./impact");
897
+ if (!isGitRepo(cwd)) { console.error("qatools doctor must run in a git repository"); process.exit(1); }
898
+ const sec = require("./secrets");
899
+ const hooks = require("./hooks");
900
+ const { BEGIN_MARKER } = require("./context-sync");
901
+ const tracked = sec.scanTracked(cwd);
902
+ const history = options.history ? sec.scanHistory(cwd) : null;
903
+ const h = hooks.hookStatus(cwd);
904
+ const mdPath = fs.existsSync(path.join(cwd, ".claude", "CLAUDE.md")) ? path.join(cwd, ".claude", "CLAUDE.md") : path.join(cwd, "CLAUDE.md");
905
+ let md = "";
906
+ try { md = fs.readFileSync(mdPath, "utf8"); } catch {}
907
+ const synced = md.match(/Last synced: (\S+)/);
908
+ const ageDays = synced ? Math.floor((Date.now() - Date.parse(synced[1])) / 86400000) : null;
909
+ const result = {
910
+ secretsInFiles: tracked, secretsInHistory: history,
911
+ hooks: h, claudeMd: { file: path.relative(cwd, mdPath), syncedBlock: md.includes(BEGIN_MARKER), lastSynced: synced ? synced[1] : null, ageDays },
912
+ };
913
+ const bad = tracked.length || (history && history.length);
914
+ if (options.json) { console.log(JSON.stringify(result, null, 2)); process.exit(bad ? 1 : 0); }
915
+ const warn = [];
916
+ if (tracked.length) {
917
+ console.log(`✗ ${tracked.length} secret(s) in tracked files — remove them, move them to a secret store, and rotate them if they were pushed:`);
918
+ for (const f of tracked.slice(0, 30)) console.log(` ${f.file}:${f.line} ${f.kind} (${f.masked})`);
919
+ }
920
+ if (history && history.length) {
921
+ console.log(`✗ ${history.length} secret(s) in git history — removing the line does not remove it from history: rotate each one:`);
922
+ for (const f of history.slice(0, 30)) console.log(` ${f.commit} ${f.date} ${f.file} ${f.kind} (${f.masked})`);
923
+ }
924
+ if (!h.commitMsg) warn.push("commit message check (feat(<key>) / fix(AVV-n))");
925
+ if (!h.preCommit) warn.push("secret check before commit");
926
+ if (!h.sessionBrief) warn.push("session brief for Claude Code");
927
+ if (warn.length) console.log(`⚠ Missing qa-tools hooks: ${warn.join(", ")}. Run: qatools init`);
928
+ if (!result.claudeMd.syncedBlock) console.log(`⚠ ${result.claudeMd.file} has no synced qa-tools block. Run: qatools sync`);
929
+ else if (ageDays !== null && ageDays > 14) console.log(`⚠ ${result.claudeMd.file} was synced ${ageDays} days ago. Run: qatools sync`);
930
+ if (!options.history) console.log(" (git history not searched — add --history)");
931
+ if (!bad && !warn.length && result.claudeMd.syncedBlock && !(ageDays > 14)) console.log("✓ All checks passed.");
932
+ process.exit(bad ? 1 : 0);
933
+ });
934
+
935
+ // context.session-brief: what a session starts with. --hook: for Claude Code's SessionStart hook — never blocks,
936
+ // prints nothing on any failure, gives up after 5 seconds.
937
+ program
938
+ .command("brief")
939
+ .description("A short brief of the project for the start of a session: in progress, flagged, agenda, hot requests, this branch")
940
+ .option("--hook", "For the SessionStart hook: silent on failure, at most 5 seconds")
941
+ .option("--project <id>", "Target project ID (overrides default)")
942
+ .action(async (options) => {
943
+ const hook = !!options.hook;
944
+ if (hook) setTimeout(() => process.exit(0), 5000).unref();
945
+ const quietExit = (msg) => { if (!hook && msg) console.error(msg); process.exit(hook ? 0 : 1); };
946
+ try {
947
+ if (hook && !getCredentials()) quietExit();
948
+ if (hook) {
949
+ // authenticate() exits the process on failure; in hook mode that must stay silent and successful
950
+ const realExit = process.exit;
951
+ process.exit = () => realExit(0);
952
+ const realErr = console.error;
953
+ console.error = () => {};
954
+ try { await authenticate(options); } finally { process.exit = realExit; console.error = realErr; }
955
+ } else {
956
+ await authenticate(options);
957
+ }
958
+ const creds = getCredentials();
959
+ const projectId = options.project || creds?.projectId;
960
+ if (!projectId) return quietExit("No project configured. Run: qatools setup, or pass --project <id>");
961
+ const call = (name, data) => httpsCallable(functions, name)(data).then(r => r.data).catch(() => null);
962
+ const [reqRes, agendaRes, reqsRes] = await Promise.all([
963
+ call("listRequirements", { projectId, status: null }),
964
+ call("getProjectAgenda", { projectId }),
965
+ call("listFeatureRequests", { projectId }),
966
+ ]);
967
+ if (!reqRes) return quietExit("Could not read the project's requirements");
968
+ const requirements = reqRes.requirements || [];
969
+ const hooks = require("./hooks");
970
+ try { hooks.writeKeyCache(process.cwd(), projectId, requirements.map(r => r.key).filter(Boolean)); } catch {}
971
+ // The current branch and the requirement keys its own commits name
972
+ let branch = "", main = "", branchKeys = [];
973
+ try {
974
+ const { isGitRepo, mainRef, keysIn } = require("./impact");
975
+ if (isGitRepo(process.cwd())) {
976
+ const { execFileSync } = require("child_process");
977
+ const git = (args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
978
+ branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
979
+ main = mainRef(process.cwd()) || "";
980
+ if (main && branch !== "HEAD") {
981
+ const known = new Set(requirements.map(r => r.key));
982
+ const found = new Set();
983
+ for (const m of git(["log", "--format=%B", "-n", "300", `${main}..HEAD`]).split("\n")) for (const k of keysIn(m, known)) found.add(k);
984
+ branchKeys = [...found].sort();
985
+ }
986
+ }
987
+ } catch {}
988
+ const { renderBrief } = require("./brief");
989
+ console.log(renderBrief({ projectName: creds?.projectName || "", requirements, agenda: agendaRes?.agenda || null,
990
+ requests: reqsRes?.requests || [], branch, main, branchKeys }));
991
+ process.exit(0);
992
+ } catch (e) {
993
+ quietExit("Failed: " + e.message);
994
+ }
995
+ });
996
+
883
997
  // signals.user-feature-requests: connect an app's own request page, and see what has arrived
884
998
  program
885
999
  .command("requests-integration-prompt")
@@ -1369,6 +1483,13 @@ program
1369
1483
  }
1370
1484
  }
1371
1485
  console.log(`\n\nDone. ${created} created, ${skipped} skipped (exact dup), ${similar} blocked (semantically similar).`);
1486
+ // traceability.commit-names-requirement: new keys are committable right away
1487
+ if (created) {
1488
+ try {
1489
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
1490
+ require("./hooks").writeKeyCache(process.cwd(), projectId, requirements.map(r => r.key).filter(Boolean));
1491
+ } catch {}
1492
+ }
1372
1493
  if (similar > 0) {
1373
1494
  console.log(`\nSimilar matches found — review before deciding:\n`);
1374
1495
  for (const rep of similarReports) {
@@ -1504,6 +1625,7 @@ async function renderSyncedContext(ctx, projectId, systemAiRules) {
1504
1625
  httpsCallable(functions, "listEpics")({ projectId }),
1505
1626
  ]);
1506
1627
  const { renderToolsSection } = require("./context-sync");
1628
+ try { require("./hooks").writeKeyCache(process.cwd(), projectId, (reqRes.data.requirements || []).map(r => r.key).filter(Boolean)); } catch {}
1507
1629
  return renderAppContextMarkdown(ctx, projectId, systemAiRules) + "\n" + renderToolsSection() + "\n" + renderBuiltSection(reqRes.data.requirements || [], epicRes.data.epics || []);
1508
1630
  }
1509
1631
 
@@ -2541,10 +2663,11 @@ program
2541
2663
  console.error(" ✗ Login failed:", e.message);
2542
2664
  process.exit(1);
2543
2665
  }
2544
- } else if (existingCreds?.projectId) {
2545
- console.log(`Step 1/5: Already logged in: ${existingCreds.projectName || existingCreds.projectId}`);
2546
- // Ensure Firebase auth is initialized
2666
+ } else if (existingCreds?.projectId || process.env.QATOOLS_API_KEY) {
2667
+ // Ensure Firebase auth is initialized; with QATOOLS_API_KEY that also picks the key's project for this run
2547
2668
  try { await authenticate(options); } catch (e) { /* best effort */ }
2669
+ const now = getCredentials(); // AVV-38: name the project this run actually uses
2670
+ console.log(`Step 1/5: ${process.env.QATOOLS_API_KEY ? "Logged in with QATOOLS_API_KEY" : "Already logged in"}: ${now?.projectName || now?.projectId || existingCreds?.projectName || ""}`);
2548
2671
  } else {
2549
2672
  console.log("Step 1/5: No API key provided. Run: qatools init --api-key <key>");
2550
2673
  console.log(" Get your key from: qa-tools.com → your project → Members → Claude AI Integration");
@@ -3190,7 +3313,8 @@ If the verification fails: do NOT mark tested. Go back to step 1, find the discr
3190
3313
  }
3191
3314
 
3192
3315
  // 3. Update or create CLAUDE.md
3193
- const claudeMdPath = path.join(cwd, "CLAUDE.md");
3316
+ // AVV-39: a repo that keeps its CLAUDE.md in .claude/ gets the section there, not a second CLAUDE.md in the root
3317
+ const claudeMdPath = fs.existsSync(path.join(cwd, ".claude", "CLAUDE.md")) ? path.join(cwd, ".claude", "CLAUDE.md") : path.join(cwd, "CLAUDE.md");
3194
3318
  const qaSection = `
3195
3319
  ## QA-Tools Integration
3196
3320
 
@@ -3198,9 +3322,7 @@ This project uses qa-tools (https://qa-tools.com) for requirement-driven AI deve
3198
3322
 
3199
3323
  **Read \`.claude/skills/qa-purpose.md\` before doing anything in this project.** It explains what qa-tools expects from the AI: not a coding assistant, a substitute for the developer.
3200
3324
 
3201
- \`\`\`bash
3202
- export QATOOLS_API_KEY=${apiKey || "<din-nyckel>"}
3203
- \`\`\`
3325
+ The CLI is already logged in on this machine (\`qatools init\`). Never write an API key into this file or anywhere in the repo — it is a secret (AVV-18). In CI, give it as a secret environment variable QATOOLS_API_KEY.
3204
3326
 
3205
3327
  ### Commands
3206
3328
  - \`qatools context\` — read the project's rule book (App Context)
@@ -3229,13 +3351,13 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3229
3351
  const existing = fs.readFileSync(claudeMdPath, "utf8");
3230
3352
  if (!existing.includes("QA-Tools Integration")) {
3231
3353
  fs.appendFileSync(claudeMdPath, "\n" + qaSection);
3232
- console.log("\n✓ Added QA-Tools section to CLAUDE.md");
3354
+ console.log(`\n✓ Added QA-Tools section to ${path.relative(cwd, claudeMdPath)}`);
3233
3355
  } else {
3234
- console.log("\n⚠ CLAUDE.md already has QA-Tools section (skipped)");
3356
+ console.log(`\n⚠ ${path.relative(cwd, claudeMdPath)} already has QA-Tools section (skipped)`);
3235
3357
  }
3236
3358
  } else {
3237
3359
  fs.writeFileSync(claudeMdPath, "# Project\n" + qaSection);
3238
- console.log("\n✓ Created CLAUDE.md with QA-Tools section");
3360
+ console.log(`\n✓ Created ${path.relative(cwd, claudeMdPath)} with QA-Tools section`);
3239
3361
  }
3240
3362
 
3241
3363
  // Step 4/5: Sync App Context into CLAUDE.md
@@ -3282,6 +3404,19 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3282
3404
  console.log(` ⚠ Sync skipped (${e.message})`);
3283
3405
  }
3284
3406
 
3407
+ // context.session-brief + traceability.commit-names-requirement: the hooks that keep the memory current
3408
+ try {
3409
+ const hooks = require("./hooks");
3410
+ const sh = hooks.installSessionHook(cwd);
3411
+ 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}`);
3412
+ const ch = hooks.installCommitHook(cwd);
3413
+ console.log(ch.installed ? ` ✓ Commit message check ${ch.already ? "already installed" : "installed"} (${path.relative(cwd, ch.path)})` : ` ⚠ Commit message check not installed: ${ch.reason}`);
3414
+ const pc = hooks.installPreCommitHook(cwd);
3415
+ console.log(pc.installed ? ` ✓ Secret check ${pc.already ? "already installed" : "installed"} (${path.relative(cwd, pc.path)})` : ` ⚠ Secret check not installed: ${pc.reason}`);
3416
+ } catch (e) {
3417
+ console.log(` ⚠ Hooks skipped (${e.message})`);
3418
+ }
3419
+
3285
3420
  // Step 5/5: Show agenda
3286
3421
  console.log("\nStep 5/5: Project agenda\n");
3287
3422
  try {
@@ -4757,6 +4892,44 @@ async function runImpact({ projectId, since, sprint, flag, main, cwd = process.c
4757
4892
  return result;
4758
4893
  }
4759
4894
 
4895
+ // traceability.evidence-commit-backfill: give verified requirements without an evidence commit the commit that built them
4896
+ program
4897
+ .command("evidence-backfill")
4898
+ .description("Verified requirements without an evidence commit: find the newest commit on main naming the key (run in the repo). --apply records it as a commit link — not a new verification")
4899
+ .option("--apply", "Record the commits in qa-tools (default: only show them)")
4900
+ .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
4901
+ .option("--project <id>", "Target project ID")
4902
+ .action(async (options) => {
4903
+ const { isGitRepo, mainRef, findKeyCommits } = require("./impact");
4904
+ const cwd = process.cwd();
4905
+ if (!isGitRepo(cwd)) { console.error("qatools evidence-backfill must run in the project's git repository"); process.exit(1); }
4906
+ const main = mainRef(cwd, options.main);
4907
+ if (!main) { console.error("No main branch found — pass --main <ref>"); process.exit(1); }
4908
+ await authenticate(options);
4909
+ const projectId = options.project || getCredentials()?.projectId;
4910
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4911
+ try {
4912
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4913
+ const latest = new Map();
4914
+ for (const r of requirements) {
4915
+ if (r.status === "superseded") continue;
4916
+ const cur = latest.get(r.key);
4917
+ if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
4918
+ }
4919
+ const { found, none } = findKeyCommits({ cwd, requirements: [...latest.values()], main });
4920
+ console.log(`${found.length} verified requirement(s) without an evidence commit have one on ${main}:\n`);
4921
+ for (const f of found) console.log(` ${f.key}: ${f.commit.slice(0, 8)} ${f.date} ${f.subject.slice(0, 70)}`);
4922
+ if (none.length) console.log(`\n${none.length} have no commit on ${main} that names their key: ${none.join(", ")}`);
4923
+ if (!options.apply) { if (found.length) console.log("\nAdd --apply to record these as commit links (not new verifications)."); process.exit(0); }
4924
+ if (!found.length) process.exit(0);
4925
+ const res = (await httpsCallable(functions, "linkEvidenceCommit")({ projectId, items: found.map(f => ({
4926
+ requirementId: f.id, commit: f.commit, how: `newest commit on ${main} naming ${f.key}: ${f.subject.slice(0, 120)} (${f.date})`,
4927
+ })) })).data;
4928
+ console.log(`\nRecorded ${res.linked.length} commit link(s)${res.skipped.length ? `, skipped ${res.skipped.length}` : ""}.`);
4929
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4930
+ process.exit(0);
4931
+ });
4932
+
4760
4933
  // requirements.done-means-merged: branches with requirement work that is not merged
4761
4934
  program
4762
4935
  .command("branches")
package/secrets.js ADDED
@@ -0,0 +1,115 @@
1
+ // security.no-secrets-in-commits and security.repo-doctor: find secrets in text, a staged commit, tracked files and
2
+ // history. Values are never returned whole — only their kind and last 4 characters. No dependencies, no network.
3
+ const { execFileSync } = require("child_process");
4
+
5
+ // Firebase web API keys (AIza…) are public by design and are deliberately not here.
6
+ const PATTERNS = [
7
+ { kind: "qa-tools API key", re: /\b(?:qa|qp|fr|wh)-[A-Za-z0-9]{32}\b/g },
8
+ { kind: "Anthropic API key", re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
9
+ { kind: "GitHub token", re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{60,}/g },
10
+ { kind: "npm token", re: /\bnpm_[A-Za-z0-9]{36}\b/g },
11
+ { kind: "AWS access key", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
12
+ { kind: "Stripe live key", re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}/g },
13
+ { kind: "SendGrid API key", re: /\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/g },
14
+ { kind: "private key", re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g },
15
+ ];
16
+ // One regex for git's -G/grep: the alternatives above, without JS-only syntax
17
+ const GIT_PATTERN = "(qa|qp|fr|wh)-[A-Za-z0-9]{32}|sk-ant-[A-Za-z0-9_-]{20,}|(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{60,}|npm_[A-Za-z0-9]{36}|(AKIA|ASIA)[0-9A-Z]{16}|(sk|rk)_live_[A-Za-z0-9]{20,}|SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43}|-----BEGIN [A-Z ]*PRIVATE KEY";
18
+
19
+ // Obvious placeholders are not secrets: alphabet or digit runs, a repeated character, or words like test/example
20
+ const SEQ = "abcdefghijklmnopqrstuvwxyz", DIG = "0123456789";
21
+ function isPlaceholder(value) {
22
+ const v = value.replace(/^(?:qa|qp|fr|wh|sk-ant|ghp|gho|ghu|ghs|ghr|github_pat|npm|sk_live|rk_live|SG)[-_.]?/i, "").toLowerCase();
23
+ if (/(test|example|sample|fake|dummy|placeholder|changeme|your|xxxx|redacted)/.test(v)) return true;
24
+ if (/(.)\1{5,}/.test(v)) return true;
25
+ for (let i = 0; i + 8 <= v.length; i++) {
26
+ const w = v.slice(i, i + 8);
27
+ if (SEQ.includes(w) || DIG.includes(w)) return true;
28
+ }
29
+ return false;
30
+ }
31
+ const ALLOW = "qatools-allow-secret";
32
+
33
+ const mask = (v) => v.startsWith("-----BEGIN") ? "-----BEGIN … PRIVATE KEY-----" : `…${v.slice(-4)}`;
34
+
35
+ // Secrets in one piece of text: [{ kind, masked, line }]
36
+ function scanText(text) {
37
+ const out = [];
38
+ const lines = String(text).split("\n");
39
+ lines.forEach((l, i) => {
40
+ if (l.includes(ALLOW)) return; // explicitly allowed line
41
+ for (const { kind, re } of PATTERNS) {
42
+ for (const m of l.matchAll(re)) {
43
+ if (kind !== "private key" && isPlaceholder(m[0])) continue;
44
+ out.push({ kind, masked: mask(m[0]), line: i + 1 });
45
+ }
46
+ }
47
+ });
48
+ return out;
49
+ }
50
+
51
+ const git = (cwd, args) => execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 512 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
52
+
53
+ // Secrets on the lines a staged commit adds: [{ file, line, kind, masked }]
54
+ function scanStaged(cwd = process.cwd()) {
55
+ const diff = git(cwd, ["diff", "--cached", "--no-color", "-U0", "--no-ext-diff"]);
56
+ const found = [];
57
+ let file = "", lineNo = 0;
58
+ for (const l of diff.split("\n")) {
59
+ if (l.startsWith("+++ ")) { file = l.slice(4).replace(/^b\//, ""); continue; }
60
+ const hunk = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)/);
61
+ if (hunk) { lineNo = Number(hunk[1]); continue; }
62
+ if (l.startsWith("+") && !l.startsWith("+++")) {
63
+ for (const s of scanText(l.slice(1))) found.push({ file, line: lineNo, kind: s.kind, masked: s.masked });
64
+ lineNo++;
65
+ }
66
+ }
67
+ return found;
68
+ }
69
+
70
+ // Secrets in tracked files now: [{ file, line, kind, masked }]
71
+ function scanTracked(cwd = process.cwd()) {
72
+ let out = "";
73
+ try { out = git(cwd, ["grep", "-n", "-I", "-E", GIT_PATTERN]); } catch { return []; } // exit 1 = nothing found
74
+ const found = [];
75
+ for (const l of out.split("\n").filter(Boolean)) {
76
+ const m = l.match(/^([^:]+):(\d+):(.*)$/);
77
+ if (!m) continue;
78
+ for (const s of scanText(m[3])) found.push({ file: m[1], line: Number(m[2]), kind: s.kind, masked: s.masked });
79
+ }
80
+ return found;
81
+ }
82
+
83
+ // Secrets anywhere in history, added by some commit: [{ commit, date, file, kind, masked }], one per secret
84
+ function scanHistory(cwd = process.cwd()) {
85
+ let out = "";
86
+ try { out = git(cwd, ["log", "--all", "-p", "--no-color", "-U0", "--extended-regexp", "--format=@@@%h %cs", "-G", GIT_PATTERN]); } catch { return []; }
87
+ const found = [], seen = new Set();
88
+ let commit = "", date = "", file = "";
89
+ for (const l of out.split("\n")) {
90
+ if (l.startsWith("@@@")) { [commit, date] = l.slice(3).split(" "); continue; }
91
+ if (l.startsWith("+++ ")) { file = l.slice(4).replace(/^b\//, ""); continue; }
92
+ if (l.startsWith("+") && !l.startsWith("+++")) {
93
+ for (const s of scanText(l.slice(1))) {
94
+ const id = s.kind + s.masked;
95
+ if (seen.has(id)) continue;
96
+ seen.add(id);
97
+ found.push({ commit, date, file, kind: s.kind, masked: s.masked });
98
+ }
99
+ }
100
+ }
101
+ return found;
102
+ }
103
+
104
+ // Runs inside the pre-commit hook: exit 1 refuses the commit
105
+ function runSecretCheck(cwd = process.cwd()) {
106
+ let found;
107
+ try { found = scanStaged(cwd); } catch { return 0; }
108
+ if (!found.length) return 0;
109
+ console.error("✗ qa-tools: this commit adds a secret. Remove it and keep it in a secret store or an environment variable:");
110
+ for (const f of found.slice(0, 20)) console.error(` ${f.file}:${f.line} ${f.kind} (${f.masked})`);
111
+ console.error(" If it was ever pushed or shared, rotate it.");
112
+ return 1;
113
+ }
114
+
115
+ module.exports = { isPlaceholder, scanText, scanStaged, scanTracked, scanHistory, runSecretCheck, PATTERNS, GIT_PATTERN };