qatools-cli 1.2.22 → 1.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/impact.js +62 -1
  2. package/package.json +1 -1
  3. package/qatools.js +91 -17
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.23",
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",
package/qatools.js CHANGED
@@ -1071,7 +1071,7 @@ program
1071
1071
  .command("plan-reject")
1072
1072
  .description("Reject (withdraw) a pending sprint-plan proposal — nothing gets planned. Approving is done in the web app only.")
1073
1073
  .requiredOption("-i, --id <proposalId>", "Proposal ID (see qatools plan-proposals)")
1074
- .option("--comment <text>", "Why it is rejected")
1074
+ .requiredOption("--comment <text>", "Why it is rejected (min 5 chars) — required")
1075
1075
  .option("--project <id>", "Target project ID (overrides default)")
1076
1076
  .option("-e, --email <email>", "Login email")
1077
1077
  .option("-p, --password <password>", "Login password")
@@ -1714,25 +1714,24 @@ program
1714
1714
  .option("--description <text>", "Set description")
1715
1715
  .option("--ac <text>", "Set acceptance criteria")
1716
1716
  .option("--points <n>", "Set size in points: 1, 2, 3, 5 or 8 (empty string clears). Not for non-functional requirements.")
1717
+ .option("--reason <text>", "REQUIRED when status=rejected: why it is rejected (min 5 chars), kept with the requirement")
1717
1718
  .option("--project <id>", "Target project ID (overrides default; requires access to that project)")
1718
1719
  .option("-e, --email <email>", "Login email")
1719
1720
  .option("-p, --password <password>", "Login password")
1720
1721
  .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
-
1722
+ // The checks below need no login, so a refused update never reaches the network
1726
1723
  let updates = {};
1727
1724
  let evidenceById = {}; // requirementId -> evidence text
1725
+ const reasonById = {}; // requirementId -> why it is rejected (requirements.reject-needs-reason)
1728
1726
  if (options.file) {
1729
1727
  updates = JSON.parse(fs.readFileSync(path.resolve(options.file), "utf8"));
1730
- // In file mode, evidence is per-update inline (e.g. { status: 'tested', evidence: '...' })
1728
+ // In file mode, evidence and reason are per-update inline (e.g. { status: 'tested', evidence: '...' })
1731
1729
  for (const [id, u] of Object.entries(updates)) {
1732
1730
  if (u.evidence) {
1733
1731
  evidenceById[id] = u.evidence;
1734
1732
  delete u.evidence; // separate from updates so backend handles via dedicated arg
1735
1733
  }
1734
+ if (u.reason) { reasonById[id] = u.reason; delete u.reason; }
1736
1735
  }
1737
1736
  } else if (options.id) {
1738
1737
  const u = {};
@@ -1747,11 +1746,19 @@ program
1747
1746
  if (options.points !== undefined) u.points = options.points === "" ? null : Number(options.points);
1748
1747
  updates[options.id] = u;
1749
1748
  if (options.evidence) evidenceById[options.id] = options.evidence;
1749
+ if (options.reason) reasonById[options.id] = options.reason;
1750
1750
  } else {
1751
1751
  console.error("Provide --file or --id");
1752
1752
  process.exit(1);
1753
1753
  }
1754
1754
 
1755
+ // Pre-flight: refuse status=rejected without a reason (requirements.reject-needs-reason)
1756
+ const noReason = Object.entries(updates).filter(([id, u]) => u.status === "rejected" && String(reasonById[id] || evidenceById[id] || "").trim().length < 5).map(([id]) => id);
1757
+ if (noReason.length) {
1758
+ console.error(`✗ Refusing status=rejected without --reason (min 5 chars): ${noReason.join(", ")}. Say why — it is kept with the requirement.`);
1759
+ process.exit(2);
1760
+ }
1761
+
1755
1762
  // Pre-flight: refuse status=implemented/tested without evidence (catch before round-trip)
1756
1763
  const violations = requirementEvidenceViolations(updates, evidenceById);
1757
1764
  if (violations.length > 0) {
@@ -1774,6 +1781,10 @@ program
1774
1781
  process.exit(2);
1775
1782
  }
1776
1783
 
1784
+ await authenticate(options);
1785
+ const projectId = options.project || getCredentials()?.projectId;
1786
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
1787
+
1777
1788
  const updateReq = httpsCallable(functions, "updateRequirement");
1778
1789
  let ok = 0, failed = 0;
1779
1790
  for (const [requirementId, fields] of Object.entries(updates)) {
@@ -1783,6 +1794,7 @@ program
1783
1794
  if (!evidenceById[requirementId]) throw new Error("--attach needs --evidence (images belong to an evidence entry)");
1784
1795
  payload.attachments = await uploadEvidenceFiles(projectId, options.attach);
1785
1796
  }
1797
+ if (reasonById[requirementId]) payload.reason = reasonById[requirementId];
1786
1798
  if (evidenceById[requirementId]) {
1787
1799
  payload.evidence = evidenceById[requirementId];
1788
1800
  const commit = options.commit === false ? null : (typeof options.commit === "string" ? options.commit : currentGitCommit());
@@ -3890,6 +3902,7 @@ const mcpTools = [
3890
3902
  description: mcpStr("Description"),
3891
3903
  acceptanceCriteria: mcpStr("Acceptance criteria"),
3892
3904
  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." },
3905
+ reason: mcpStr("Required for status rejected (min 5 chars): why it is rejected; kept with the requirement"),
3893
3906
  attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
3894
3907
  commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
3895
3908
  }, ["requirementId"]),
@@ -3900,7 +3913,10 @@ const mcpTools = [
3900
3913
  if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
3901
3914
  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
3915
  }
3903
- const payload = { projectId: a.projectId, requirementId: a.requirementId, updates };
3916
+ if (updates.status === "rejected" && String(a.reason || a.evidence || "").trim().length < 5) {
3917
+ throw new McpToolError("Refusing status=rejected without a reason (min 5 chars). Say why — it is kept with the requirement.");
3918
+ }
3919
+ const payload = { projectId: a.projectId, requirementId: a.requirementId, updates, ...(a.reason ? { reason: a.reason } : {}) };
3904
3920
  if (a.evidence) {
3905
3921
  payload.evidence = a.evidence;
3906
3922
  const commit = a.commit !== undefined ? a.commit : currentGitCommit();
@@ -4156,8 +4172,8 @@ const mcpTools = [
4156
4172
  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
4173
  inputSchema: mcpSchema({
4158
4174
  proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
4159
- comment: mcpStr("Why it is rejected"),
4160
- }, ["proposalId"]),
4175
+ comment: mcpStr("Why it is rejected (min 5 chars) — required, kept with the proposal"),
4176
+ }, ["proposalId", "comment"]),
4161
4177
  run: async (a) => {
4162
4178
  await mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "reject", comment: a.comment || "" });
4163
4179
  return { rejected: a.proposalId, planned: 0 };
@@ -4263,8 +4279,8 @@ const mcpTools = [
4263
4279
  {
4264
4280
  name: "requirement_impact",
4265
4281
  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 }),
4282
+ 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") }),
4283
+ run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag, main: a.main }),
4268
4284
  },
4269
4285
  {
4270
4286
  name: "list_feature_requests",
@@ -4689,8 +4705,8 @@ reqLibraryCmd
4689
4705
 
4690
4706
  // ==================== REGRESSION IMPACT (testing.regression-impact) ====================
4691
4707
  // 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");
4708
+ async function runImpact({ projectId, since, sprint, flag, main, cwd = process.cwd() }) {
4709
+ const { computeImpact, isGitRepo, baseForDate, mainRef, notOnMain } = require("./impact");
4694
4710
  if (!isGitRepo(cwd)) throw new Error("qatools impact must run in the project's git repository");
4695
4711
  let base = since || null, rangeLabel = since ? `${since}..HEAD` : "";
4696
4712
  if (!base && sprint) {
@@ -4702,7 +4718,6 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4702
4718
  rangeLabel = `since ${s.name} started (${s.startDate})`;
4703
4719
  if (!base) throw new Error(`No commit before ${s.startDate} — use --since <ref>`);
4704
4720
  }
4705
- if (!base) throw new Error("Give --since <ref> or --sprint <id|name>");
4706
4721
  const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4707
4722
  const latest = new Map();
4708
4723
  for (const r of requirements) {
@@ -4710,8 +4725,27 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4710
4725
  const cur = latest.get(r.key);
4711
4726
  if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
4712
4727
  }
4728
+ // requirements.done-means-merged: runs on every impact, with or without a range
4729
+ const mainBranch = mainRef(cwd, main);
4730
+ const merged = mainBranch ? notOnMain({ cwd, requirements: [...latest.values()], main: mainBranch }) : null;
4731
+ if (merged && flag) {
4732
+ const flaggedNow = new Set(requirements.filter(r => r.notOnMain).map(r => r.id));
4733
+ const res = (await httpsCallable(functions, "flagNotOnMain")({
4734
+ projectId, main: mainBranch,
4735
+ items: merged.off.map(o => ({ requirementId: o.id, commit: o.commit, branch: o.branch, since: o.since })),
4736
+ clearIds: merged.onMain.filter(id => flaggedNow.has(id)),
4737
+ })).data;
4738
+ merged.flagged = res.flagged;
4739
+ merged.cleared = res.cleared;
4740
+ }
4741
+ if (!base) {
4742
+ if (since || sprint) throw new Error("Could not find the start of the range");
4743
+ return { range: "", affected: [], commitsInRange: 0, mappedCommits: 0, notOnMain: merged, mainMissing: !mainBranch };
4744
+ }
4713
4745
  const result = computeImpact({ cwd, base, requirements: [...latest.values()] });
4714
4746
  result.range = rangeLabel;
4747
+ result.notOnMain = merged;
4748
+ result.mainMissing = !mainBranch;
4715
4749
  if (flag && result.affected.length) {
4716
4750
  const res = (await httpsCallable(functions, "flagRegressionRisk")({
4717
4751
  projectId, base, head: result.head,
@@ -4723,12 +4757,40 @@ async function runImpact({ projectId, since, sprint, flag, cwd = process.cwd() }
4723
4757
  return result;
4724
4758
  }
4725
4759
 
4760
+ // requirements.done-means-merged: branches with requirement work that is not merged
4761
+ program
4762
+ .command("branches")
4763
+ .description("Branches not merged into main whose commits name requirement keys (run in the project's repository)")
4764
+ .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
4765
+ .option("--json", "Output as JSON")
4766
+ .option("--project <id>", "Target project ID")
4767
+ .action(async (options) => {
4768
+ const { isGitRepo, mainRef, unmergedBranches } = require("./impact");
4769
+ const cwd = process.cwd();
4770
+ if (!isGitRepo(cwd)) { console.error("qatools branches must run in the project's git repository"); process.exit(1); }
4771
+ const main = mainRef(cwd, options.main);
4772
+ if (!main) { console.error("No main branch found — pass --main <ref>"); process.exit(1); }
4773
+ await authenticate(options);
4774
+ const projectId = options.project || getCredentials()?.projectId;
4775
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4776
+ try {
4777
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4778
+ const list = unmergedBranches({ cwd, main, knownKeys: new Set(requirements.map(r => r.key)) });
4779
+ if (options.json) { console.log(JSON.stringify({ main, branches: list }, null, 2)); process.exit(0); }
4780
+ if (!list.length) { console.log(`No unmerged branches with requirement work (compared with ${main}).`); process.exit(0); }
4781
+ console.log(`${list.length} branch(es) with requirement work not merged into ${main}:\n`);
4782
+ for (const b of list) console.log(` ${b.branch}: ${b.ahead} commit(s) ahead, newest ${String(b.newest).slice(0, 10)} — ${b.keys.join(", ")}`);
4783
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4784
+ process.exit(0);
4785
+ });
4786
+
4726
4787
  program
4727
4788
  .command("impact")
4728
4789
  .description("Verified requirements whose files changed in other work (run in the project's repository)")
4729
4790
  .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)")
4791
+ .option("--sprint <id>", "Range start: the sprint's start date (id or name). Without --since/--sprint only the main-branch check runs")
4731
4792
  .option("--flag", "Record the risk on the requirements in qa-tools (shown on cards, sprint view and agenda)")
4793
+ .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
4732
4794
  .option("--json", "Output as JSON")
4733
4795
  .option("--project <id>", "Target project ID")
4734
4796
  .action(async (options) => {
@@ -4737,8 +4799,20 @@ program
4737
4799
  const projectId = options.project || creds?.projectId;
4738
4800
  if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4739
4801
  try {
4740
- const r = await runImpact({ projectId, since: options.since, sprint: options.sprint, flag: options.flag });
4802
+ const r = await runImpact({ projectId, since: options.since, sprint: options.sprint, flag: options.flag, main: options.main });
4741
4803
  if (options.json) { console.log(JSON.stringify(r, null, 2)); process.exit(0); }
4804
+ // requirements.done-means-merged
4805
+ const m = r.notOnMain;
4806
+ if (r.mainMissing) console.log("\nNo main branch found — pass --main <ref> to check that verified work is on it.");
4807
+ else if (m) {
4808
+ if (m.off.length) {
4809
+ console.log(`\n${m.off.length} verified requirement(s) NOT on ${m.main} — the work is done but not in the product:\n`);
4810
+ 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)}`);
4811
+ } else console.log(`\nAll checked verified requirements are on ${m.main}.`);
4812
+ if (m.unchecked) console.log(`(${m.unchecked} verified requirement(s) could not be checked: their evidence names no commit known in this repo.)`);
4813
+ if (options.flag) console.log(`Recorded in qa-tools: ${(m.flagged || []).length} flagged, ${(m.cleared || []).length} cleared.`);
4814
+ }
4815
+ if (!r.range) { if (!options.flag && m?.off.length) console.log("\nAdd --flag to record this in qa-tools."); process.exit(0); }
4742
4816
  console.log(`\n${r.commitsInRange} commit(s) ${r.range}; ${r.mappedCommits} commit(s) linked to requirements through their messages and evidence.`);
4743
4817
  if (!r.affected.length) { console.log("No verified requirement had its files changed by other work."); process.exit(0); }
4744
4818
  console.log(`\n${r.affected.length} verified requirement(s) touched by other work — verify again:\n`);