qatools-cli 1.2.15 → 1.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ // context.sync-what-is-built: the part of the synced CLAUDE.md block that says what is already built,
2
+ // so a new session knows it from the start. Pure functions, unit-tested in test/context-sync.test.js.
3
+
4
+ const BEGIN_MARKER = "<!-- BEGIN qatools-context (auto-synced from qa-tools, do not edit by hand) -->";
5
+ const END_MARKER = "<!-- END qatools-context -->";
6
+
7
+ // One line per requirement: key, title, status. No descriptions or criteria, to keep CLAUDE.md short.
8
+ const clean = (s) => String(s || "").replace(/\s+/g, " ").replace(/-->/g, "--\\>").trim();
9
+
10
+ function renderBuiltSection(requirements, epics = []) {
11
+ const epicTitle = new Map(epics.map(e => [e.key, e.title || e.name || e.key]));
12
+ const built = requirements.filter(r => r.status === "implemented" || r.status === "tested");
13
+ const inProgress = requirements.filter(r => r.status === "in_progress");
14
+ const byKey = (a, b) => String(a.key || "").localeCompare(String(b.key || ""));
15
+ const lines = [];
16
+
17
+ lines.push("### What is already built");
18
+ lines.push("> Every implemented or tested requirement in qa-tools, grouped by epic. Before you build something or say it is missing, check this list and `qatools requirements` — work may exist on another branch or from before you. Synced from requirement statuses, which need evidence.");
19
+ lines.push("");
20
+ if (!built.length) {
21
+ lines.push("_No requirements are implemented or tested yet._");
22
+ lines.push("");
23
+ } else {
24
+ const groups = new Map();
25
+ for (const r of built) {
26
+ const g = r.epicKey || "";
27
+ if (!groups.has(g)) groups.set(g, []);
28
+ groups.get(g).push(r);
29
+ }
30
+ // Epics in the project's epic order, then any unknown epic keys, then requirements without an epic
31
+ const order = [...epics.map(e => e.key).filter(k => groups.has(k)),
32
+ ...[...groups.keys()].filter(k => k && !epicTitle.has(k)).sort()];
33
+ if (groups.has("")) order.push("");
34
+ for (const g of order) {
35
+ lines.push(g ? `#### ${clean(epicTitle.get(g) || g)} (${g})` : "#### No epic");
36
+ for (const r of groups.get(g).sort(byKey)) lines.push(`- \`${clean(r.key)}\` ${clean(r.title)} (${r.status})`);
37
+ lines.push("");
38
+ }
39
+ }
40
+
41
+ lines.push("### Being built now");
42
+ if (!inProgress.length) lines.push("_Nothing is in progress._");
43
+ // A Claude API-key account (claude@<projectid>.qatools) reads as "Claude"
44
+ const who = (email) => /^claude@[^@]+\.qatools$/i.test(String(email)) ? "Claude" : clean(email);
45
+ for (const r of inProgress.sort(byKey)) {
46
+ lines.push(`- \`${clean(r.key)}\` ${clean(r.title)}${r.assignedTo ? ` — ${who(r.assignedTo)}` : ""}`);
47
+ }
48
+ lines.push("");
49
+ return lines.join("\n");
50
+ }
51
+
52
+ // Replace the synced block in a file's text, or append it. Text outside the block is kept as is.
53
+ function spliceBlock(existing, md) {
54
+ const block = `${BEGIN_MARKER}\n${md}\n${END_MARKER}`;
55
+ const beginIdx = existing.indexOf(BEGIN_MARKER);
56
+ const endIdx = existing.indexOf(END_MARKER);
57
+ if (beginIdx >= 0 && endIdx > beginIdx) {
58
+ return existing.slice(0, beginIdx) + block + existing.slice(endIdx + END_MARKER.length);
59
+ }
60
+ const sep = existing && !existing.endsWith("\n") ? "\n\n" : (existing ? "\n" : "");
61
+ return existing + sep + block + "\n";
62
+ }
63
+
64
+ // The sync time changes on every run; it must not make --check report a change on its own.
65
+ const withoutSyncTime = (text) => String(text).replace(/<!-- Last synced: [^>]*-->/g, "<!-- Last synced -->").replace(/\r\n/g, "\n");
66
+ const sameContent = (a, b) => withoutSyncTime(a) === withoutSyncTime(b);
67
+
68
+ module.exports = { BEGIN_MARKER, END_MARKER, renderBuiltSection, spliceBlock, sameContent };
package/impact.js ADDED
@@ -0,0 +1,125 @@
1
+ // testing.regression-impact: which verified requirements does a range of commits touch?
2
+ // Line level: a commit puts requirement X at risk when it changes or deletes lines that X's commits wrote
3
+ // (found with git blame on the version before the commit). A commit's own requirements are not at risk
4
+ // from it, and pure additions put nobody at risk. A requirement's commits are those whose message names its
5
+ // key ("feat(key): …", "[req:key]") and those recorded on its evidence.
6
+ const { execFileSync } = require("child_process");
7
+
8
+ const DEFAULT_IGNORE = [
9
+ /(^|\/)package-lock\.json$/, /(^|\/)yarn\.lock$/, /(^|\/)pnpm-lock\.yaml$/, /(^|\/)packages\.lock\.json$/,
10
+ /(^|\/)version\.(json|ts)$/, /\.md$/i, /(^|\/)\.firebase\//,
11
+ ];
12
+
13
+ function git(cwd, args) {
14
+ return execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
15
+ }
16
+
17
+ function isGitRepo(cwd) {
18
+ try { return git(cwd, ["rev-parse", "--is-inside-work-tree"]).trim() === "true"; } catch { return false; }
19
+ }
20
+
21
+ // Commits as { sha, parent, message }, newest first. range: "a..b" or a ref; maxCommits limits history.
22
+ function readCommits(cwd, range, maxCommits) {
23
+ const args = ["log", "--no-merges", "--format=%x1e%H%x1f%P%x1f%B"];
24
+ if (maxCommits) args.push(`-n${maxCommits}`);
25
+ if (range) args.push(range);
26
+ return git(cwd, args).split("\x1e").filter(s => s.trim()).map(chunk => {
27
+ const [sha, parents, message] = chunk.split("\x1f");
28
+ return { sha: sha.trim(), parent: (parents || "").trim().split(" ")[0] || "", message: message || "" };
29
+ });
30
+ }
31
+
32
+ // Requirement keys named in a commit message, among the known keys.
33
+ function keysIn(message, knownKeys) {
34
+ const found = new Set();
35
+ for (const m of message.matchAll(/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g)) if (knownKeys.has(m[0])) found.add(m[0]);
36
+ for (const m of message.matchAll(/\[req:([\w.\-/]+)\]/gi)) if (knownKeys.has(m[1])) found.add(m[1]);
37
+ return found;
38
+ }
39
+
40
+ // Lines a commit changed or deleted, as ranges in its parent's version: { file → [[start, count], …] }.
41
+ function changedOldLines(cwd, sha, parent) {
42
+ const out = git(cwd, ["diff", "-U0", "--no-color", "--no-renames", parent, sha]);
43
+ const byFile = new Map();
44
+ let file = null, hunk = null;
45
+ const close = () => {
46
+ // A release bump of "version" in package.json is not a change to anyone's code.
47
+ const versionOnly = /(^|\/)package\.json$/.test(hunk?.file || "") && hunk.removed.every(l => /^\s*"version"\s*:/.test(l));
48
+ if (hunk && hunk.count > 0 && !versionOnly) {
49
+ if (!byFile.has(hunk.file)) byFile.set(hunk.file, []);
50
+ byFile.get(hunk.file).push([hunk.start, hunk.count]);
51
+ }
52
+ hunk = null;
53
+ };
54
+ for (const line of out.split("\n")) {
55
+ if (line.startsWith("--- ")) { close(); file = line === "--- /dev/null" ? null : line.slice(6); continue; }
56
+ const m = line.match(/^@@ -(\d+)(?:,(\d+))? \+/);
57
+ if (m) { close(); if (file) hunk = { file, start: +m[1], count: m[2] === undefined ? 1 : +m[2], removed: [] }; continue; }
58
+ if (hunk && line.startsWith("-")) hunk.removed.push(line.slice(1));
59
+ }
60
+ close();
61
+ return byFile;
62
+ }
63
+
64
+ // Which commits wrote the given line ranges of a file at a revision (one git blame call per file).
65
+ function blameCommits(cwd, rev, file, ranges) {
66
+ // --porcelain always prints full hashes (the default format shortens boundary commits to "^" + 39 chars).
67
+ const args = ["blame", "--porcelain"];
68
+ for (const [start, count] of ranges) args.push("-L", `${start},+${count}`);
69
+ args.push(rev, "--", file);
70
+ try {
71
+ const out = new Set();
72
+ for (const l of git(cwd, args).split("\n")) { const m = l.match(/^([0-9a-f]{40}) \d+ \d+/); if (m) out.add(m[1]); }
73
+ return out;
74
+ } catch { return new Set(); }
75
+ }
76
+
77
+ function baseForDate(cwd, date) {
78
+ return git(cwd, ["rev-list", "-1", `--before=${date}T00:00:00`, "HEAD"]).trim() || null;
79
+ }
80
+
81
+ /**
82
+ * @param {object} o
83
+ * @param {string} o.cwd repository
84
+ * @param {string} o.base range start (exclusive)
85
+ * @param {string} [o.head] range end, default HEAD
86
+ * @param {Array} o.requirements [{ id, key, status, evidenceLog }]
87
+ * @param {number} [o.maxCommits] history depth used to learn which commits belong to which requirement
88
+ * @param {RegExp[]} [o.ignore] files never considered
89
+ */
90
+ function computeImpact({ cwd, base, head = "HEAD", requirements, maxCommits = 5000, ignore = DEFAULT_IGNORE }) {
91
+ const known = new Set(requirements.map(r => r.key));
92
+ const keep = (f) => !ignore.some(rx => rx.test(f));
93
+ // commit sha → requirement keys it was made for
94
+ const keysByCommit = new Map();
95
+ const addKey = (sha, key) => { if (!keysByCommit.has(sha)) keysByCommit.set(sha, new Set()); keysByCommit.get(sha).add(key); };
96
+ for (const c of readCommits(cwd, head, maxCommits)) for (const k of keysIn(c.message, known)) addKey(c.sha, k);
97
+ for (const r of requirements) for (const e of r.evidenceLog || []) {
98
+ if (!e.commit) continue;
99
+ try { addKey(git(cwd, ["rev-parse", e.commit]).trim(), r.key); } catch { /* commit not in this clone */ }
100
+ }
101
+ const verified = new Map(requirements.filter(r => r.status === "implemented" || r.status === "tested").map(r => [r.key, r]));
102
+ const hits = new Map(); // key → { files:Set, commits:Set }
103
+ const range = readCommits(cwd, `${base}..${head}`, 0);
104
+ for (const c of range) {
105
+ if (!c.parent) continue;
106
+ const own = keysIn(c.message, known);
107
+ for (const [file, ranges] of changedOldLines(cwd, c.sha, c.parent)) {
108
+ if (!keep(file)) continue;
109
+ for (const author of blameCommits(cwd, c.parent, file, ranges)) {
110
+ for (const key of keysByCommit.get(author) || []) {
111
+ if (own.has(key) || !verified.has(key)) continue;
112
+ if (!hits.has(key)) hits.set(key, { files: new Set(), commits: new Set() });
113
+ hits.get(key).files.add(file); hits.get(key).commits.add(c.sha);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ const affected = [...hits].map(([key, h]) => {
119
+ const r = verified.get(key);
120
+ return { id: r.id, key, status: r.status, files: [...h.files].sort(), commits: [...h.commits] };
121
+ }).sort((a, b) => a.key.localeCompare(b.key));
122
+ return { base, head: git(cwd, ["rev-parse", head]).trim(), commitsInRange: range.length, mappedCommits: keysByCommit.size, affected };
123
+ }
124
+
125
+ module.exports = { computeImpact, isGitRepo, baseForDate, keysIn, DEFAULT_IGNORE };
package/package.json CHANGED
@@ -1,16 +1,19 @@
1
1
  {
2
2
  "name": "qatools-cli",
3
- "version": "1.2.15",
3
+ "version": "1.2.18",
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",
7
- "release:minor": "npm version minor --no-git-tag-version && npm publish"
7
+ "release:minor": "npm version minor --no-git-tag-version && npm publish",
8
+ "test": "node --test \"test/*.test.js\""
8
9
  },
9
10
  "bin": {
10
11
  "qatools": "qatools.js"
11
12
  },
12
13
  "files": [
13
- "qatools.js"
14
+ "qatools.js",
15
+ "impact.js",
16
+ "context-sync.js"
14
17
  ],
15
18
  "keywords": [
16
19
  "qa",
package/qatools.js CHANGED
@@ -687,12 +687,13 @@ const REQ_TAG = /\[req:([\w.\-/]+)\]/i;
687
687
 
688
688
  function parseJUnit(xml) {
689
689
  const out = [];
690
- for (const m of xml.matchAll(/<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)) {
690
+ // Attribute values may contain ">" (Node's JUnit reporter does not escape it), so quoted values are skipped whole.
691
+ for (const m of xml.matchAll(/<testcase\b((?:[^>"']|"[^"]*"|'[^']*')*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)) {
691
692
  const attrs = xmlAttrs(m[1]);
692
693
  const body = m[2] || "";
693
694
  const name = [attrs.classname, attrs.name].filter(Boolean).join(" › ") || "(unnamed test)";
694
695
  let requirementKey = "";
695
- for (const p of body.matchAll(/<property\b([^>]*?)\/?>/g)) {
696
+ for (const p of body.matchAll(/<property\b((?:[^>"']|"[^"]*"|'[^']*')*?)\/?>/g)) {
696
697
  const pa = xmlAttrs(p[1]);
697
698
  if (/^requirement[-_]?key$/i.test(pa.name || "")) requirementKey = pa.value || "";
698
699
  }
@@ -1253,27 +1254,24 @@ program
1253
1254
  process.exit(1);
1254
1255
  }
1255
1256
 
1256
- const md = renderAppContextMarkdown(ctx, projectId, systemAiRules);
1257
- const beginMarker = "<!-- BEGIN qatools-context (auto-synced from qa-tools, do not edit by hand) -->";
1258
- const endMarker = "<!-- END qatools-context -->";
1257
+ const { BEGIN_MARKER: beginMarker, END_MARKER: endMarker, spliceBlock, sameContent } = require("./context-sync");
1258
+ let md;
1259
+ try {
1260
+ md = await renderSyncedContext(ctx, projectId, systemAiRules);
1261
+ } catch (e) {
1262
+ console.error("Failed to fetch requirements:", e.message);
1263
+ process.exit(1);
1264
+ }
1259
1265
  const block = `${beginMarker}\n${md}\n${endMarker}`;
1260
1266
 
1261
1267
  const filePath = path.resolve(options.output);
1262
1268
  let existing = "";
1263
1269
  if (fs.existsSync(filePath)) existing = fs.readFileSync(filePath, "utf8");
1264
1270
 
1265
- let updated;
1266
- const beginIdx = existing.indexOf(beginMarker);
1267
- const endIdx = existing.indexOf(endMarker);
1268
- if (beginIdx >= 0 && endIdx > beginIdx) {
1269
- updated = existing.slice(0, beginIdx) + block + existing.slice(endIdx + endMarker.length);
1270
- } else {
1271
- const sep = existing && !existing.endsWith("\n") ? "\n\n" : (existing ? "\n" : "");
1272
- updated = existing + sep + block + "\n";
1273
- }
1271
+ const updated = spliceBlock(existing, md);
1274
1272
 
1275
1273
  if (options.check) {
1276
- if (existing === updated) {
1274
+ if (sameContent(existing, updated)) {
1277
1275
  console.log(`✓ ${options.output} is in sync with project ${projectId}`);
1278
1276
  process.exit(0);
1279
1277
  } else {
@@ -1283,7 +1281,7 @@ program
1283
1281
  }
1284
1282
 
1285
1283
  if (options.dryRun) {
1286
- if (existing === updated) {
1284
+ if (sameContent(existing, updated)) {
1287
1285
  console.log(`✓ ${options.output} already in sync — nothing would change.`);
1288
1286
  process.exit(0);
1289
1287
  }
@@ -1325,7 +1323,7 @@ program
1325
1323
  process.exit(0);
1326
1324
  }
1327
1325
 
1328
- if (existing === updated) {
1326
+ if (sameContent(existing, updated)) {
1329
1327
  console.log(`✓ ${options.output} already in sync (no changes)`);
1330
1328
  } else {
1331
1329
  fs.writeFileSync(filePath, updated);
@@ -1334,6 +1332,16 @@ program
1334
1332
  process.exit(0);
1335
1333
  });
1336
1334
 
1335
+ // context.sync-what-is-built: App Context plus what is already built, as one synced block
1336
+ async function renderSyncedContext(ctx, projectId, systemAiRules) {
1337
+ const { renderBuiltSection } = require("./context-sync");
1338
+ const [reqRes, epicRes] = await Promise.all([
1339
+ httpsCallable(functions, "listRequirements")({ projectId, status: null }),
1340
+ httpsCallable(functions, "listEpics")({ projectId }),
1341
+ ]);
1342
+ return renderAppContextMarkdown(ctx, projectId, systemAiRules) + "\n" + renderBuiltSection(reqRes.data.requirements || [], epicRes.data.epics || []);
1343
+ }
1344
+
1337
1345
  function renderAppContextMarkdown(ctx, projectId, systemAiRules) {
1338
1346
  const lines = [];
1339
1347
  const ts = new Date().toISOString();
@@ -2624,6 +2632,7 @@ App Context → Epics → Requirements → Sprint → Implementation → Test
2624
2632
  3. Implement according to acceptanceCriteria AND negativeCriteria.
2625
2633
  Every piece of code must be traceable to a requirementKey.
2626
2634
  When done and verified: \`--status implemented --evidence "<verification>"\`. If you stop without finishing, set it back to \`approved\` (clears the assignee).
2635
+ New requirements must not break old ones: when you changed shared code, run \`qatools impact --since <ref> --flag\` and verify the requirements it lists again.
2627
2636
 
2628
2637
  4. If you discover something unexpected during implementation:
2629
2638
  - Behavior doesn't match a requirement → create AVV: \`qatools backlog-create -d "..." -t bug --requirement-key <key>\`
@@ -3056,7 +3065,7 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3056
3065
  const systemRules = syncResult.data.systemAiRules || [];
3057
3066
  if (syncCtx) {
3058
3067
  // Use the same sync logic as qatools sync
3059
- const syncMd = renderAppContextMarkdown(syncCtx, creds.projectId, systemRules);
3068
+ const syncMd = await renderSyncedContext(syncCtx, creds.projectId, systemRules);
3060
3069
  const beginMarker = "<!-- BEGIN qatools-context (auto-synced from qa-tools, do not edit by hand) -->";
3061
3070
  const endMarker = "<!-- END qatools-context -->";
3062
3071
  const block = `${beginMarker}\n${syncMd}\n${endMarker}`;
@@ -3598,6 +3607,8 @@ const MCP_INSTRUCTIONS = `qa-tools: requirements-driven QA. Rules that apply to
3598
3607
  - Backlog flow: open → in_progress → ready_for_test → resolved. Set ready_for_test when you believe a fix is done; resolved needs evidence (min 10 chars) and, except GAP, a prior ready_for_test.
3599
3608
  - Requirement status implemented/tested needs evidence: test output, file:line, expected vs actual, or "no test applies because <reason>".
3600
3609
  - Requirement flow: approved → in_progress → implemented → tested. When you start implementing an approved requirement, set status in_progress and assignedTo "me" (update_requirement); if you stop without finishing, set it back to approved.
3610
+ - Requirements with a libraryId inherit from the account's requirement library: never try to change their title, description, criteria, type or category — only applicability, status, sprint, epic and assignee are the project's. When get_agenda lists libraryReverify, verify those requirements again against the new library text.
3611
+ - New requirements must not break old ones: before completing a sprint or release, and after building something that touched shared code, run requirement_impact (sprint or since) with flag: true, and verify the listed requirements again. Put their manual tests in a "Regression" section of the sprint's test protocol.
3601
3612
  - Sprint planning: plan approved, functional requirements only (update_requirement sprintId), never backlog items; non-functional requirements are continuous and never go into sprints. Gather facts first (list_sprints, sprint_velocity, list_epics, list_requirements), respect epic dependsOn, present the plan as a table (sprint | requirement | reason) and change NOTHING until the user approves it in this conversation. If the user isn't here or wants to decide later, save it with propose_sprint_plan instead — they approve in qa-tools. Full procedure: prompt plan_sprints.
3602
3613
  - Every tool takes an optional projectId; without it the configured project (qatools setup) is used.`;
3603
3614
 
@@ -4044,6 +4055,44 @@ const mcpTools = [
4044
4055
  return { updated: a.itemId, fields: Object.keys(u) };
4045
4056
  },
4046
4057
  },
4058
+ {
4059
+ name: "requirement_impact",
4060
+ 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).",
4061
+ 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" } }),
4062
+ run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag }),
4063
+ },
4064
+ {
4065
+ name: "list_requirement_library",
4066
+ description: "The account's requirement library (library.shared-requirements): requirements shared by all projects of the same owner, with key, title, category, type and version.",
4067
+ inputSchema: mcpSchema({ category: mcpStr("Only this category") }),
4068
+ run: async (a) => {
4069
+ const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
4070
+ return a.category ? entries.filter(e => (e.category || "").toLowerCase() === a.category.toLowerCase()) : entries;
4071
+ },
4072
+ },
4073
+ {
4074
+ name: "share_requirement_to_library",
4075
+ description: "Share a project requirement into the account's library; the requirement then inherits from it. Give generic wording in text and keep what is specific to this project in applicability. You cannot change a library entry afterwards — only the owner can.",
4076
+ inputSchema: mcpSchema({
4077
+ requirementId: mcpStr("Requirement document ID"),
4078
+ text: { type: "object", description: "Generic wording for the library", properties: { title: mcpStr("Title"), description: mcpStr("Description"), acceptanceCriteria: mcpStr("Given/When/Then"), negativeCriteria: mcpStr("Negative Given/When/Then"), category: mcpStr("Category") }, additionalProperties: false },
4079
+ applicability: mcpStr("What is specific to this project, e.g. 'Applies to Twilio, SendGrid, Auth0'"),
4080
+ }, ["requirementId"]),
4081
+ run: async (a) => mcpCall("shareRequirementToLibrary", { projectId: a.projectId, ...mcpPick(a, ["requirementId", "text", "applicability"]) }),
4082
+ },
4083
+ {
4084
+ name: "inherit_library_requirements",
4085
+ description: "Inherit library entries into the project, by keys or a whole category. What you inherit is created as drafts for a member to approve.",
4086
+ inputSchema: mcpSchema({ keys: mcpStrArray("Library keys"), category: mcpStr("Every entry in this category"), applicability: mcpStr("What they apply to in this project") }),
4087
+ run: async (a) => {
4088
+ let libraryIds;
4089
+ if (a.keys?.length) {
4090
+ const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
4091
+ libraryIds = entries.filter(e => a.keys.includes(e.key)).map(e => e.id);
4092
+ }
4093
+ return mcpCall("inheritLibraryRequirements", { projectId: a.projectId, libraryIds, category: a.category, applicability: a.applicability });
4094
+ },
4095
+ },
4047
4096
  {
4048
4097
  name: "create_test_protocol",
4049
4098
  description: "Create a sprint's manual test protocol after a plan was approved in this conversation (sprint.ai-planning-manual-tests). Only tests a person must perform — what you can verify yourself belongs in automated tests in the code. It is saved for review (pending_review); a project member approves it under Test protocols, never you.",
@@ -4169,7 +4218,7 @@ Follow these steps in order:
4169
4218
  4. STOP and ask the user: approve here, or save it as a proposal to decide later in qa-tools? Change nothing before that. Apply any adjustments the user asks for and show the table again.
4170
4219
  - If nobody is there to answer (an unattended run), or the user chooses "later": call propose_sprint_plan with the same rows, and report the result. Do not apply anything yourself.
4171
4220
  5. After approval in this conversation: create_sprint for any new sprints, then update_requirement with sprintId for each planned requirement. Report each change and any refusal verbatim — never retry a refused change in a different way.
4172
- 6. Manual tests, per sprint: draft a test protocol with the tests a person must perform because you can't verify them yourself — look and feel, real mobile devices, e-mail/SMS actually arriving, BankID/Freja, printing/PDF, flows between several parties. Each test has requirementKey (a requirement planned in that sprint) and a purpose saying why a person must do it. What you can verify yourself goes into automated tests in the code, not here. Show the tests with the plan. With propose_sprint_plan, pass them as testProtocols (approved together with the proposal). After approval in the conversation, save each with create_test_protocol (pending review — a member approves it). A sprint with nothing that needs a person gets no protocol; say so.
4221
+ 6. Manual tests, per sprint: draft a test protocol with the tests a person must perform because you can't verify them yourself — look and feel, real mobile devices, e-mail/SMS actually arriving, BankID/Freja, printing/PDF, flows between several parties. Each test has requirementKey (a requirement planned in that sprint) and a purpose saying why a person must do it. What you can verify yourself goes into automated tests in the code, not here. Show the tests with the plan. With propose_sprint_plan, pass them as testProtocols (approved together with the proposal). After approval in the conversation, save each with create_test_protocol (pending review — a member approves it). A sprint with nothing that needs a person gets no protocol; say so. Regression: run requirement_impact for the sprint; the approved manual tests of requirements it lists (or that get_agenda lists under regressionRisk) go into a section "Regression" of the same protocol.
4173
4222
  7. End with get_sprint_items for each affected sprint so the user can see the result.`,
4174
4223
  },
4175
4224
  {
@@ -4272,6 +4321,195 @@ program
4272
4321
  rl.on("close", () => process.exit(0));
4273
4322
  });
4274
4323
 
4324
+ // ==================== REQUIREMENT LIBRARY (library.shared-requirements, library.inheritance) ====================
4325
+ const reqLibraryCmd = program
4326
+ .command("library")
4327
+ .description("The account's requirement library: requirements shared by all projects of the same owner");
4328
+
4329
+ function libraryProject(options) {
4330
+ const creds = getCredentials();
4331
+ const projectId = options.project || creds?.projectId;
4332
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4333
+ return projectId;
4334
+ }
4335
+
4336
+ reqLibraryCmd
4337
+ .command("list")
4338
+ .description("List the library of the project owner's account")
4339
+ .option("--category <name>", "Only this category")
4340
+ .option("--json", "Output as JSON")
4341
+ .option("--project <id>", "Project whose owner's library to show (default: configured project)")
4342
+ .action(async (options) => {
4343
+ await authenticate(options);
4344
+ const projectId = libraryProject(options);
4345
+ try {
4346
+ const { data } = await httpsCallable(functions, "listRequirementLibrary")({ projectId });
4347
+ let entries = data.entries;
4348
+ if (options.category) entries = entries.filter(e => (e.category || "").toLowerCase() === options.category.toLowerCase());
4349
+ if (options.json) { console.log(JSON.stringify(entries, null, 2)); process.exit(0); }
4350
+ console.log(`\nRequirement library of ${data.owner} — ${entries.length} entr${entries.length === 1 ? "y" : "ies"}:\n`);
4351
+ for (const e of entries) console.log(` [${e.key}] v${e.version} ${e.title} (${e.category || "no category"}, ${e.type}) id: ${e.id}`);
4352
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4353
+ process.exit(0);
4354
+ });
4355
+
4356
+ reqLibraryCmd
4357
+ .command("share")
4358
+ .description("Share a project requirement into the library; the requirement then inherits from it")
4359
+ .requiredOption("-i, --id <requirementId>", "Requirement to share")
4360
+ .option("-f, --file <path>", "JSON with generic wording for the library: { title, description, acceptanceCriteria, negativeCriteria, category }")
4361
+ .option("--applicability <text>", "What is specific to this project (kept on the project's requirement)")
4362
+ .option("--project <id>", "Target project ID")
4363
+ .action(async (options) => {
4364
+ await authenticate(options);
4365
+ const projectId = libraryProject(options);
4366
+ const payload = { projectId, requirementId: options.id };
4367
+ if (options.file) payload.text = JSON.parse(fs.readFileSync(path.resolve(options.file), "utf8"));
4368
+ if (options.applicability !== undefined) payload.applicability = options.applicability;
4369
+ try {
4370
+ const { data } = await httpsCallable(functions, "shareRequirementToLibrary")(payload);
4371
+ console.log(`Shared ${data.key} to the library as v${data.version} (id ${data.libraryId}). The requirement now inherits from it.`);
4372
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4373
+ process.exit(0);
4374
+ });
4375
+
4376
+ reqLibraryCmd
4377
+ .command("inherit")
4378
+ .description("Inherit library entries into the project (by key or a whole category)")
4379
+ .option("--key <keys>", "Comma-separated library keys")
4380
+ .option("--category <name>", "Every entry in this category")
4381
+ .option("--applicability <text>", "What the requirements apply to in this project")
4382
+ .option("--project <id>", "Target project ID")
4383
+ .action(async (options) => {
4384
+ await authenticate(options);
4385
+ const projectId = libraryProject(options);
4386
+ if (!options.key && !options.category) { console.error("Give --key or --category"); process.exit(1); }
4387
+ try {
4388
+ let libraryIds;
4389
+ if (options.key) {
4390
+ const { data } = await httpsCallable(functions, "listRequirementLibrary")({ projectId });
4391
+ const keys = options.key.split(",").map(k => k.trim()).filter(Boolean);
4392
+ const unknown = keys.filter(k => !data.entries.some(e => e.key === k));
4393
+ if (unknown.length) { console.error(`Not in the library: ${unknown.join(", ")}`); process.exit(1); }
4394
+ libraryIds = data.entries.filter(e => keys.includes(e.key)).map(e => e.id);
4395
+ }
4396
+ const { data } = await httpsCallable(functions, "inheritLibraryRequirements")({ projectId, libraryIds, category: options.category, applicability: options.applicability });
4397
+ console.log(`Inherited ${data.inherited.length} as ${data.status}: ${data.inherited.join(", ") || "—"}`);
4398
+ for (const s of data.skipped) console.log(` skipped ${s.key}: ${s.reason}`);
4399
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4400
+ process.exit(0);
4401
+ });
4402
+
4403
+ reqLibraryCmd
4404
+ .command("update")
4405
+ .description("Change a library entry (owner only). The new text reaches every project that inherits it.")
4406
+ .requiredOption("--key <key>", "Library key")
4407
+ .option("--title <text>", "New title")
4408
+ .option("--description <text>", "New description")
4409
+ .option("--ac <text>", "New acceptance criteria")
4410
+ .option("--negative <text>", "New negative criteria")
4411
+ .option("--category <name>", "New category")
4412
+ .option("--project <id>", "A project of the owner (default: configured project)")
4413
+ .action(async (options) => {
4414
+ await authenticate(options);
4415
+ const projectId = libraryProject(options);
4416
+ const updates = {};
4417
+ if (options.title) updates.title = options.title;
4418
+ if (options.description) updates.description = options.description;
4419
+ if (options.ac) updates.acceptanceCriteria = options.ac;
4420
+ if (options.negative) updates.negativeCriteria = options.negative;
4421
+ if (options.category) updates.category = options.category;
4422
+ try {
4423
+ const list = (await httpsCallable(functions, "listRequirementLibrary")({ projectId })).data.entries;
4424
+ const entry = list.find(e => e.key === options.key);
4425
+ if (!entry) { console.error(`Not in the library: ${options.key}`); process.exit(1); }
4426
+ const { data } = await httpsCallable(functions, "updateLibraryRequirement")({ projectId, libraryId: entry.id, updates });
4427
+ console.log(`${options.key} is now v${data.version}; ${data.updatedRequirements} inheriting requirement(s) in ${data.projects} project(s) got the new text.`);
4428
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4429
+ process.exit(0);
4430
+ });
4431
+
4432
+ // ==================== REGRESSION IMPACT (testing.regression-impact) ====================
4433
+ // Runs in the project's repository: which verified requirements did a range of commits touch?
4434
+ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }) {
4435
+ const { computeImpact, isGitRepo, baseForDate } = require("./impact");
4436
+ if (!isGitRepo(cwd)) throw new Error("qatools impact must run in the project's git repository");
4437
+ let base = since || null, rangeLabel = since ? `${since}..HEAD` : "";
4438
+ if (!base && sprint) {
4439
+ const { sprints } = (await httpsCallable(functions, "listSprints")({ projectId })).data;
4440
+ const s = sprints.find(x => x.id === sprint || x.name === sprint);
4441
+ if (!s) throw new Error(`Sprint not found: ${sprint}`);
4442
+ if (!s.startDate) throw new Error(`Sprint "${s.name}" has no start date — use --since <ref>`);
4443
+ base = baseForDate(cwd, s.startDate);
4444
+ rangeLabel = `since ${s.name} started (${s.startDate})`;
4445
+ if (!base) throw new Error(`No commit before ${s.startDate} — use --since <ref>`);
4446
+ }
4447
+ if (!base) throw new Error("Give --since <ref> or --sprint <id|name>");
4448
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4449
+ const latest = new Map();
4450
+ for (const r of requirements) {
4451
+ if (r.status === "superseded") continue;
4452
+ const cur = latest.get(r.key);
4453
+ if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
4454
+ }
4455
+ const result = computeImpact({ cwd, base, requirements: [...latest.values()] });
4456
+ result.range = rangeLabel;
4457
+ if (flag && result.affected.length) {
4458
+ const res = (await httpsCallable(functions, "flagRegressionRisk")({
4459
+ projectId, base, head: result.head,
4460
+ items: result.affected.map(a => ({ requirementId: a.id, files: a.files })),
4461
+ })).data;
4462
+ result.flagged = res.flagged;
4463
+ result.skipped = res.skipped;
4464
+ }
4465
+ return result;
4466
+ }
4467
+
4468
+ program
4469
+ .command("impact")
4470
+ .description("Verified requirements whose files changed in other work (run in the project's repository)")
4471
+ .option("--since <ref>", "Range start: a git ref (commit, tag, branch)")
4472
+ .option("--sprint <id>", "Range start: the sprint's start date (id or name)")
4473
+ .option("--flag", "Record the risk on the requirements in qa-tools (shown on cards, sprint view and agenda)")
4474
+ .option("--json", "Output as JSON")
4475
+ .option("--project <id>", "Target project ID")
4476
+ .action(async (options) => {
4477
+ await authenticate(options);
4478
+ const creds = getCredentials();
4479
+ const projectId = options.project || creds?.projectId;
4480
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4481
+ try {
4482
+ const r = await runImpact({ projectId, since: options.since, sprint: options.sprint, flag: options.flag });
4483
+ if (options.json) { console.log(JSON.stringify(r, null, 2)); process.exit(0); }
4484
+ console.log(`\n${r.commitsInRange} commit(s) ${r.range}; ${r.mappedCommits} commit(s) linked to requirements through their messages and evidence.`);
4485
+ if (!r.affected.length) { console.log("No verified requirement had its files changed by other work."); process.exit(0); }
4486
+ console.log(`\n${r.affected.length} verified requirement(s) touched by other work — verify again:\n`);
4487
+ for (const a of r.affected) console.log(` ${a.key} (${a.status}): ${a.files.slice(0, 5).join(", ")}${a.files.length > 5 ? ` +${a.files.length - 5}` : ""}`);
4488
+ if (options.flag) console.log(`\nFlagged in qa-tools: ${(r.flagged || []).length}${(r.skipped || []).length ? `, skipped ${r.skipped.length}` : ""}.`);
4489
+ else console.log("\nAdd --flag to record this in qa-tools.");
4490
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4491
+ process.exit(0);
4492
+ });
4493
+
4494
+ program
4495
+ .command("audit")
4496
+ .description("The project's security log (owner or superadmin; log in with Google, not with an API key)")
4497
+ .option("--limit <n>", "Number of entries", "50")
4498
+ .option("--json", "Output as JSON")
4499
+ .option("--project <id>", "Target project ID")
4500
+ .action(async (options) => {
4501
+ await authenticate(options);
4502
+ const projectId = options.project || getCredentials()?.projectId;
4503
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4504
+ try {
4505
+ const { entries } = (await httpsCallable(functions, "listAuditLog")({ projectId, limit: Number(options.limit) || 50 })).data;
4506
+ if (options.json) { console.log(JSON.stringify(entries, null, 2)); process.exit(0); }
4507
+ for (const x of entries) console.log(` ${x.at.slice(0, 16).replace("T", " ")} ${x.actor.padEnd(32)} ${x.action.padEnd(30)} ${Object.entries(x.details || {}).map(([k, v]) => `${k}=${v}`).join(" ")}${x.ip ? " ip=" + x.ip : ""}`);
4508
+ if (!entries.length) console.log("No security events yet.");
4509
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4510
+ process.exit(0);
4511
+ });
4512
+
4275
4513
  program.hook("preAction", async (_root, cmd) => {
4276
4514
  if (cmd.name() === "mcp") return; // the MCP server reports through instructions and get_agenda
4277
4515
  for (const w of await staleWarnings({ skipSkills: cmd.name() === "init" })) console.error(`⚠ ${w}`);