qatools-cli 1.2.22 → 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.
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/impact.js CHANGED
@@ -122,4 +122,65 @@ function computeImpact({ cwd, base, head = "HEAD", requirements, maxCommits = 50
122
122
  return { base, head: git(cwd, ["rev-parse", head]).trim(), commitsInRange: range.length, mappedCommits: keysByCommit.size, affected };
123
123
  }
124
124
 
125
- module.exports = { computeImpact, isGitRepo, baseForDate, keysIn, DEFAULT_IGNORE };
125
+ // ---- requirements.done-means-merged: is a requirement's evidence commit on the main branch? ----
126
+ const gitOk = (cwd, args) => { try { git(cwd, args); return true; } catch { return false; } };
127
+
128
+ // The main branch: an explicit ref, else origin/HEAD, else the first of origin/main, origin/master, main, master.
129
+ function mainRef(cwd, explicit) {
130
+ if (explicit) return explicit;
131
+ try {
132
+ const head = git(cwd, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]).trim();
133
+ if (head) return head.replace(/^refs\/remotes\//, "");
134
+ } catch {}
135
+ return ["origin/main", "origin/master", "main", "master"].find(r => gitOk(cwd, ["rev-parse", "--verify", "--quiet", r + "^{commit}"])) || null;
136
+ }
137
+
138
+ // The newest commit recorded on a requirement's evidence
139
+ function evidenceCommit(req) {
140
+ const log = Array.isArray(req.evidenceLog) ? req.evidenceLog : [];
141
+ for (let i = log.length - 1; i >= 0; i--) if (log[i]?.commit) return String(log[i].commit);
142
+ return "";
143
+ }
144
+
145
+ // Verified requirements whose evidence commit is not on main. A commit counts as on main when it is an
146
+ // ancestor of main, or when main has a later commit naming the requirement's key (a squash or a rebase).
147
+ function notOnMain({ cwd, requirements, main }) {
148
+ const off = [], onMain = [];
149
+ let unchecked = 0;
150
+ for (const r of requirements) {
151
+ if (r.status !== "implemented" && r.status !== "tested") continue;
152
+ const commit = evidenceCommit(r);
153
+ if (!commit || !gitOk(cwd, ["cat-file", "-e", `${commit}^{commit}`])) { unchecked++; continue; }
154
+ if (gitOk(cwd, ["merge-base", "--is-ancestor", commit, main])) { onMain.push(r.id); continue; }
155
+ const since = git(cwd, ["show", "-s", "--format=%cI", commit]).trim();
156
+ const squashed = git(cwd, ["log", main, `--since=${since}`, "-F", `--grep=${r.key}`, "--format=%H", "-n1"]).trim();
157
+ if (squashed) { onMain.push(r.id); continue; }
158
+ const branches = git(cwd, ["branch", "-a", "--contains", commit, "--format=%(refname:short)"]).split("\n").map(s => s.trim())
159
+ .filter(b => b && b !== main && !b.endsWith("/HEAD") && b !== "HEAD");
160
+ off.push({ id: r.id, key: r.key, status: r.status, commit, branch: branches.find(b => !b.startsWith("origin/")) || branches[0] || "", since });
161
+ }
162
+ return { main, off, onMain, unchecked };
163
+ }
164
+
165
+ // Branches not merged into main whose commits name requirement keys, newest first
166
+ function unmergedBranches({ cwd, main, knownKeys }) {
167
+ const refs = git(cwd, ["for-each-ref", "refs/heads", "refs/remotes", "--format=%(refname:short)\x1f%(committerdate:iso-strict)"])
168
+ .split("\n").filter(Boolean).map(l => { const [name, date] = l.split("\x1f"); return { name, date }; })
169
+ .filter(b => b.name !== main && !b.name.endsWith("/HEAD") && b.name !== "origin");
170
+ const seen = new Set();
171
+ const out = [];
172
+ for (const b of refs.sort((x, y) => (x.name.startsWith("origin/") ? 1 : 0) - (y.name.startsWith("origin/") ? 1 : 0))) {
173
+ const short = b.name.replace(/^origin\//, "");
174
+ if (seen.has(short) || short === main.replace(/^origin\//, "")) continue;
175
+ const ahead = Number(git(cwd, ["rev-list", "--count", `${main}..${b.name}`]).trim());
176
+ if (!ahead) continue;
177
+ const keys = new Set();
178
+ for (const c of readCommits(cwd, `${main}..${b.name}`, 500)) for (const k of keysIn(c.message, knownKeys)) keys.add(k);
179
+ if (!keys.size) continue;
180
+ seen.add(short);
181
+ out.push({ branch: b.name, ahead, newest: b.date, keys: [...keys].sort() });
182
+ }
183
+ return out.sort((x, y) => String(y.newest).localeCompare(String(x.newest)));
184
+ }
185
+
186
+ module.exports = { computeImpact, isGitRepo, baseForDate, keysIn, DEFAULT_IGNORE, mainRef, notOnMain, unmergedBranches, evidenceCommit };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qatools-cli",
3
- "version": "1.2.22",
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")
@@ -1071,7 +1136,7 @@ program
1071
1136
  .command("plan-reject")
1072
1137
  .description("Reject (withdraw) a pending sprint-plan proposal — nothing gets planned. Approving is done in the web app only.")
1073
1138
  .requiredOption("-i, --id <proposalId>", "Proposal ID (see qatools plan-proposals)")
1074
- .option("--comment <text>", "Why it is rejected")
1139
+ .requiredOption("--comment <text>", "Why it is rejected (min 5 chars) — required")
1075
1140
  .option("--project <id>", "Target project ID (overrides default)")
1076
1141
  .option("-e, --email <email>", "Login email")
1077
1142
  .option("-p, --password <password>", "Login password")
@@ -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
 
@@ -1714,25 +1780,24 @@ program
1714
1780
  .option("--description <text>", "Set description")
1715
1781
  .option("--ac <text>", "Set acceptance criteria")
1716
1782
  .option("--points <n>", "Set size in points: 1, 2, 3, 5 or 8 (empty string clears). Not for non-functional requirements.")
1783
+ .option("--reason <text>", "REQUIRED when status=rejected: why it is rejected (min 5 chars), kept with the requirement")
1717
1784
  .option("--project <id>", "Target project ID (overrides default; requires access to that project)")
1718
1785
  .option("-e, --email <email>", "Login email")
1719
1786
  .option("-p, --password <password>", "Login password")
1720
1787
  .action(async (options) => {
1721
- await authenticate(options);
1722
- const creds = getCredentials();
1723
- const projectId = options.project || creds?.projectId;
1724
- if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
1725
-
1788
+ // The checks below need no login, so a refused update never reaches the network
1726
1789
  let updates = {};
1727
1790
  let evidenceById = {}; // requirementId -> evidence text
1791
+ const reasonById = {}; // requirementId -> why it is rejected (requirements.reject-needs-reason)
1728
1792
  if (options.file) {
1729
1793
  updates = JSON.parse(fs.readFileSync(path.resolve(options.file), "utf8"));
1730
- // In file mode, evidence is per-update inline (e.g. { status: 'tested', evidence: '...' })
1794
+ // In file mode, evidence and reason are per-update inline (e.g. { status: 'tested', evidence: '...' })
1731
1795
  for (const [id, u] of Object.entries(updates)) {
1732
1796
  if (u.evidence) {
1733
1797
  evidenceById[id] = u.evidence;
1734
1798
  delete u.evidence; // separate from updates so backend handles via dedicated arg
1735
1799
  }
1800
+ if (u.reason) { reasonById[id] = u.reason; delete u.reason; }
1736
1801
  }
1737
1802
  } else if (options.id) {
1738
1803
  const u = {};
@@ -1747,11 +1812,19 @@ program
1747
1812
  if (options.points !== undefined) u.points = options.points === "" ? null : Number(options.points);
1748
1813
  updates[options.id] = u;
1749
1814
  if (options.evidence) evidenceById[options.id] = options.evidence;
1815
+ if (options.reason) reasonById[options.id] = options.reason;
1750
1816
  } else {
1751
1817
  console.error("Provide --file or --id");
1752
1818
  process.exit(1);
1753
1819
  }
1754
1820
 
1821
+ // Pre-flight: refuse status=rejected without a reason (requirements.reject-needs-reason)
1822
+ const noReason = Object.entries(updates).filter(([id, u]) => u.status === "rejected" && String(reasonById[id] || evidenceById[id] || "").trim().length < 5).map(([id]) => id);
1823
+ if (noReason.length) {
1824
+ console.error(`✗ Refusing status=rejected without --reason (min 5 chars): ${noReason.join(", ")}. Say why — it is kept with the requirement.`);
1825
+ process.exit(2);
1826
+ }
1827
+
1755
1828
  // Pre-flight: refuse status=implemented/tested without evidence (catch before round-trip)
1756
1829
  const violations = requirementEvidenceViolations(updates, evidenceById);
1757
1830
  if (violations.length > 0) {
@@ -1774,6 +1847,10 @@ program
1774
1847
  process.exit(2);
1775
1848
  }
1776
1849
 
1850
+ await authenticate(options);
1851
+ const projectId = options.project || getCredentials()?.projectId;
1852
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
1853
+
1777
1854
  const updateReq = httpsCallable(functions, "updateRequirement");
1778
1855
  let ok = 0, failed = 0;
1779
1856
  for (const [requirementId, fields] of Object.entries(updates)) {
@@ -1783,6 +1860,7 @@ program
1783
1860
  if (!evidenceById[requirementId]) throw new Error("--attach needs --evidence (images belong to an evidence entry)");
1784
1861
  payload.attachments = await uploadEvidenceFiles(projectId, options.attach);
1785
1862
  }
1863
+ if (reasonById[requirementId]) payload.reason = reasonById[requirementId];
1786
1864
  if (evidenceById[requirementId]) {
1787
1865
  payload.evidence = evidenceById[requirementId];
1788
1866
  const commit = options.commit === false ? null : (typeof options.commit === "string" ? options.commit : currentGitCommit());
@@ -3270,6 +3348,17 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3270
3348
  console.log(` ⚠ Sync skipped (${e.message})`);
3271
3349
  }
3272
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
+
3273
3362
  // Step 5/5: Show agenda
3274
3363
  console.log("\nStep 5/5: Project agenda\n");
3275
3364
  try {
@@ -3890,6 +3979,7 @@ const mcpTools = [
3890
3979
  description: mcpStr("Description"),
3891
3980
  acceptanceCriteria: mcpStr("Acceptance criteria"),
3892
3981
  points: { type: ["integer", "null"], enum: [1, 2, 3, 5, 8, null], description: "Size in points (null clears). Split anything bigger than 8. Not for non-functional requirements." },
3982
+ reason: mcpStr("Required for status rejected (min 5 chars): why it is rejected; kept with the requirement"),
3893
3983
  attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
3894
3984
  commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
3895
3985
  }, ["requirementId"]),
@@ -3900,7 +3990,10 @@ const mcpTools = [
3900
3990
  if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
3901
3991
  throw new McpToolError(`Refusing status=${updates.status} without evidence (min 10 chars). Cite the verification, or use a status that does not claim done.`);
3902
3992
  }
3903
- const payload = { projectId: a.projectId, requirementId: a.requirementId, updates };
3993
+ if (updates.status === "rejected" && String(a.reason || a.evidence || "").trim().length < 5) {
3994
+ throw new McpToolError("Refusing status=rejected without a reason (min 5 chars). Say why — it is kept with the requirement.");
3995
+ }
3996
+ const payload = { projectId: a.projectId, requirementId: a.requirementId, updates, ...(a.reason ? { reason: a.reason } : {}) };
3904
3997
  if (a.evidence) {
3905
3998
  payload.evidence = a.evidence;
3906
3999
  const commit = a.commit !== undefined ? a.commit : currentGitCommit();
@@ -4156,8 +4249,8 @@ const mcpTools = [
4156
4249
  description: "Reject (withdraw) a pending sprint-plan proposal, e.g. one you created that is superseded. Nothing gets planned. There is no approve tool: approval is a human decision in the qa-tools web app.",
4157
4250
  inputSchema: mcpSchema({
4158
4251
  proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
4159
- comment: mcpStr("Why it is rejected"),
4160
- }, ["proposalId"]),
4252
+ comment: mcpStr("Why it is rejected (min 5 chars) — required, kept with the proposal"),
4253
+ }, ["proposalId", "comment"]),
4161
4254
  run: async (a) => {
4162
4255
  await mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "reject", comment: a.comment || "" });
4163
4256
  return { rejected: a.proposalId, planned: 0 };
@@ -4263,8 +4356,8 @@ const mcpTools = [
4263
4356
  {
4264
4357
  name: "requirement_impact",
4265
4358
  description: "Regression check (testing.regression-impact): which implemented/tested requirements had their files changed by other work in a range of commits. Runs in the server's working directory, which must be the project's git repository. Use before completing a sprint or a release, and after building a requirement that touched shared code. flag: true records the risk in qa-tools; then verify those requirements again (tests, a session, or new evidence).",
4266
- inputSchema: mcpSchema({ since: mcpStr("Range start: a git ref"), sprint: mcpStr("Range start: this sprint's start date (id or name)"), flag: { type: "boolean", description: "Record the risk in qa-tools" } }),
4267
- run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag }),
4359
+ inputSchema: mcpSchema({ since: mcpStr("Range start: a git ref"), sprint: mcpStr("Range start: this sprint's start date (id or name)"), flag: { type: "boolean", description: "Record the risk in qa-tools" }, main: mcpStr("The main branch, if not origin/HEAD / main / master") }),
4360
+ run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag, main: a.main }),
4268
4361
  },
4269
4362
  {
4270
4363
  name: "list_feature_requests",
@@ -4689,8 +4782,8 @@ reqLibraryCmd
4689
4782
 
4690
4783
  // ==================== REGRESSION IMPACT (testing.regression-impact) ====================
4691
4784
  // Runs in the project's repository: which verified requirements did a range of commits touch?
4692
- async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }) {
4693
- const { computeImpact, isGitRepo, baseForDate } = require("./impact");
4785
+ async function runImpact({ projectId, since, sprint, flag, main, cwd = process.cwd() }) {
4786
+ const { computeImpact, isGitRepo, baseForDate, mainRef, notOnMain } = require("./impact");
4694
4787
  if (!isGitRepo(cwd)) throw new Error("qatools impact must run in the project's git repository");
4695
4788
  let base = since || null, rangeLabel = since ? `${since}..HEAD` : "";
4696
4789
  if (!base && sprint) {
@@ -4702,7 +4795,6 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4702
4795
  rangeLabel = `since ${s.name} started (${s.startDate})`;
4703
4796
  if (!base) throw new Error(`No commit before ${s.startDate} — use --since <ref>`);
4704
4797
  }
4705
- if (!base) throw new Error("Give --since <ref> or --sprint <id|name>");
4706
4798
  const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4707
4799
  const latest = new Map();
4708
4800
  for (const r of requirements) {
@@ -4710,8 +4802,27 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4710
4802
  const cur = latest.get(r.key);
4711
4803
  if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
4712
4804
  }
4805
+ // requirements.done-means-merged: runs on every impact, with or without a range
4806
+ const mainBranch = mainRef(cwd, main);
4807
+ const merged = mainBranch ? notOnMain({ cwd, requirements: [...latest.values()], main: mainBranch }) : null;
4808
+ if (merged && flag) {
4809
+ const flaggedNow = new Set(requirements.filter(r => r.notOnMain).map(r => r.id));
4810
+ const res = (await httpsCallable(functions, "flagNotOnMain")({
4811
+ projectId, main: mainBranch,
4812
+ items: merged.off.map(o => ({ requirementId: o.id, commit: o.commit, branch: o.branch, since: o.since })),
4813
+ clearIds: merged.onMain.filter(id => flaggedNow.has(id)),
4814
+ })).data;
4815
+ merged.flagged = res.flagged;
4816
+ merged.cleared = res.cleared;
4817
+ }
4818
+ if (!base) {
4819
+ if (since || sprint) throw new Error("Could not find the start of the range");
4820
+ return { range: "", affected: [], commitsInRange: 0, mappedCommits: 0, notOnMain: merged, mainMissing: !mainBranch };
4821
+ }
4713
4822
  const result = computeImpact({ cwd, base, requirements: [...latest.values()] });
4714
4823
  result.range = rangeLabel;
4824
+ result.notOnMain = merged;
4825
+ result.mainMissing = !mainBranch;
4715
4826
  if (flag && result.affected.length) {
4716
4827
  const res = (await httpsCallable(functions, "flagRegressionRisk")({
4717
4828
  projectId, base, head: result.head,
@@ -4723,12 +4834,40 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4723
4834
  return result;
4724
4835
  }
4725
4836
 
4837
+ // requirements.done-means-merged: branches with requirement work that is not merged
4838
+ program
4839
+ .command("branches")
4840
+ .description("Branches not merged into main whose commits name requirement keys (run in the project's repository)")
4841
+ .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
4842
+ .option("--json", "Output as JSON")
4843
+ .option("--project <id>", "Target project ID")
4844
+ .action(async (options) => {
4845
+ const { isGitRepo, mainRef, unmergedBranches } = require("./impact");
4846
+ const cwd = process.cwd();
4847
+ if (!isGitRepo(cwd)) { console.error("qatools branches must run in the project's git repository"); process.exit(1); }
4848
+ const main = mainRef(cwd, options.main);
4849
+ if (!main) { console.error("No main branch found — pass --main <ref>"); process.exit(1); }
4850
+ await authenticate(options);
4851
+ const projectId = options.project || getCredentials()?.projectId;
4852
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4853
+ try {
4854
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4855
+ const list = unmergedBranches({ cwd, main, knownKeys: new Set(requirements.map(r => r.key)) });
4856
+ if (options.json) { console.log(JSON.stringify({ main, branches: list }, null, 2)); process.exit(0); }
4857
+ if (!list.length) { console.log(`No unmerged branches with requirement work (compared with ${main}).`); process.exit(0); }
4858
+ console.log(`${list.length} branch(es) with requirement work not merged into ${main}:\n`);
4859
+ for (const b of list) console.log(` ${b.branch}: ${b.ahead} commit(s) ahead, newest ${String(b.newest).slice(0, 10)} — ${b.keys.join(", ")}`);
4860
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4861
+ process.exit(0);
4862
+ });
4863
+
4726
4864
  program
4727
4865
  .command("impact")
4728
4866
  .description("Verified requirements whose files changed in other work (run in the project's repository)")
4729
4867
  .option("--since <ref>", "Range start: a git ref (commit, tag, branch)")
4730
- .option("--sprint <id>", "Range start: the sprint's start date (id or name)")
4868
+ .option("--sprint <id>", "Range start: the sprint's start date (id or name). Without --since/--sprint only the main-branch check runs")
4731
4869
  .option("--flag", "Record the risk on the requirements in qa-tools (shown on cards, sprint view and agenda)")
4870
+ .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
4732
4871
  .option("--json", "Output as JSON")
4733
4872
  .option("--project <id>", "Target project ID")
4734
4873
  .action(async (options) => {
@@ -4737,8 +4876,20 @@ program
4737
4876
  const projectId = options.project || creds?.projectId;
4738
4877
  if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4739
4878
  try {
4740
- const r = await runImpact({ projectId, since: options.since, sprint: options.sprint, flag: options.flag });
4879
+ const r = await runImpact({ projectId, since: options.since, sprint: options.sprint, flag: options.flag, main: options.main });
4741
4880
  if (options.json) { console.log(JSON.stringify(r, null, 2)); process.exit(0); }
4881
+ // requirements.done-means-merged
4882
+ const m = r.notOnMain;
4883
+ if (r.mainMissing) console.log("\nNo main branch found — pass --main <ref> to check that verified work is on it.");
4884
+ else if (m) {
4885
+ if (m.off.length) {
4886
+ console.log(`\n${m.off.length} verified requirement(s) NOT on ${m.main} — the work is done but not in the product:\n`);
4887
+ for (const o of m.off) console.log(` ${o.key} (${o.status}): commit ${o.commit.slice(0, 8)} on ${o.branch || "no branch"} since ${o.since.slice(0, 10)}`);
4888
+ } else console.log(`\nAll checked verified requirements are on ${m.main}.`);
4889
+ if (m.unchecked) console.log(`(${m.unchecked} verified requirement(s) could not be checked: their evidence names no commit known in this repo.)`);
4890
+ if (options.flag) console.log(`Recorded in qa-tools: ${(m.flagged || []).length} flagged, ${(m.cleared || []).length} cleared.`);
4891
+ }
4892
+ if (!r.range) { if (!options.flag && m?.off.length) console.log("\nAdd --flag to record this in qa-tools."); process.exit(0); }
4742
4893
  console.log(`\n${r.commitsInRange} commit(s) ${r.range}; ${r.mappedCommits} commit(s) linked to requirements through their messages and evidence.`);
4743
4894
  if (!r.affected.length) { console.log("No verified requirement had its files changed by other work."); process.exit(0); }
4744
4895
  console.log(`\n${r.affected.length} verified requirement(s) touched by other work — verify again:\n`);