qatools-cli 1.2.17 → 1.2.19

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/context-sync.js +154 -0
  2. package/package.json +3 -2
  3. package/qatools.js +237 -29
@@ -0,0 +1,154 @@
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
+ // What qa-tools offers that a session would not think of by itself. Short on purpose: each line names
53
+ // the command that gives the full instructions.
54
+ function renderToolsSection() {
55
+ return [
56
+ "### qa-tools tools for this project",
57
+ "- Code exists that no requirement covers (built before qa-tools, or on the side): `qatools baseline-prompt` — reconstruct requirements from the code; a member approves them as built.",
58
+ "- The app has a page where users request features and vote: `qatools requests-integration-prompt` — connect it, so requests and votes reach qa-tools and their status (planned / released / declined) goes back to the app. See what has arrived: `qatools feature-requests`.",
59
+ "- Something more important must go into a sprint in progress: propose a swap (MCP `propose_sprint_plan` swaps) instead of overfilling it; a member approves.",
60
+ "",
61
+ ].join("\n");
62
+ }
63
+
64
+ // Instructions for connecting an app's own feature-request page to qa-tools (signals.user-feature-requests)
65
+ const FEATURE_REQUESTS_URL = "https://us-central1-qatools-app.cloudfunctions.net/featureRequests";
66
+ const FENCE = "```";
67
+ function requestsIntegrationPrompt(projectName) {
68
+ return [
69
+ `# Connect this app's feature requests to qa-tools${projectName ? ` (project "${projectName}")` : ""}`,
70
+ "",
71
+ "The app has (or should have) a page where users request features and vote on each other's requests. qa-tools gets",
72
+ "the requests and votes, members link them to requirements, and the app reads back what happened to each request —",
73
+ "so users see that their votes matter. The app keeps its own page and voting; you add a sync.",
74
+ "",
75
+ "## Procedure",
76
+ "1. Find where the app keeps requests and votes (collection/table, fields, how votes are counted) and the page that",
77
+ " shows them. Read the code. If the app has no such page, stop and tell the user — building one is a requirement",
78
+ " of its own.",
79
+ "2. Ask the user for the feature-request key. The project owner creates it in qa-tools: Members → Requests from the",
80
+ " app → Create key. It starts with `fr-`, is shown once, and can only send requests and read their status.",
81
+ " Keep it server-side as a secret named QATOOLS_FEATURE_REQUEST_KEY. Never in client code, never in the repo.",
82
+ "3. Add a scheduled server job (every 15 minutes is enough) that:",
83
+ " - sends every request with its current votes: action \"upsert\", at most 200 per call. The app's own id",
84
+ " identifies a request, so sending all of them every time is fine — it updates, it does not duplicate;",
85
+ " - reads the status of the same ids: action \"status\", at most 500 per call;",
86
+ " - stores each status on the app's own request record (e.g. a field qaStatus).",
87
+ "4. Show the status on the request page, in the app's language: planned → the release name and its end date;",
88
+ " released → released; declined → the reason (members write it for the users); new → nothing or \"received\".",
89
+ "5. Verify it yourself before you say it works: run the job once (or call its function directly); then",
90
+ " `qatools feature-requests` must list the requests with their votes, and the stored statuses must be \"new\".",
91
+ " Report what you saw. The user then links one request to a planned requirement in qa-tools; after the next run",
92
+ " its status must be \"planned\".",
93
+ "6. If the app's requirements in qa-tools do not cover the request page or this sync, say so — the user decides",
94
+ " whether to add requirements.",
95
+ "",
96
+ "## API",
97
+ `POST ${FEATURE_REQUESTS_URL}`,
98
+ "Headers: Content-Type: application/json, Authorization: Bearer <fr- key>",
99
+ "",
100
+ "Send requests:",
101
+ ' { "action": "upsert", "requests": [ { "id": "42", "title": "Dark mode", "description": "…", "votes": 15, "url": "https://…" } ] }',
102
+ ' → { "created": 1, "updated": 0, "refused": [] } (refused: [{ "id": "", "reason": "id and title are required" }])',
103
+ "",
104
+ "Read status:",
105
+ ' { "action": "status", "ids": ["42", "43"] }',
106
+ ' → { "statuses": [ { "id": "42", "status": "planned", "sprint": "Release 4.1", "releaseDate": "2026-11-18" },',
107
+ ' { "id": "43", "status": "declined", "reason": "…" } ] }',
108
+ " status is one of: new, planned, released, declined, unknown (never sent)",
109
+ "",
110
+ "Errors: 401 missing key, 403 wrong or revoked key, 400 bad body, 429 more than 60 calls a minute from one IP.",
111
+ "",
112
+ "## Example (Node, Firebase scheduled function — adapt names to the app)",
113
+ FENCE + "js",
114
+ 'const { onSchedule } = require("firebase-functions/v2/scheduler");',
115
+ 'const { defineSecret } = require("firebase-functions/params");',
116
+ 'const KEY = defineSecret("QATOOLS_FEATURE_REQUEST_KEY");',
117
+ `const QA = "${FEATURE_REQUESTS_URL}";`,
118
+ "",
119
+ 'exports.syncRequestsToQaTools = onSchedule({ schedule: "every 15 minutes", secrets: [KEY] }, async () => {',
120
+ " const call = async (body) => {",
121
+ ' const res = await fetch(QA, { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + KEY.value() }, body: JSON.stringify(body) });',
122
+ ' if (!res.ok) throw new Error("qa-tools " + res.status + ": " + (await res.json()).error);',
123
+ " return res.json();",
124
+ " };",
125
+ ' const snap = await db.collection("featureRequests").get();',
126
+ ' const reqs = snap.docs.map(d => ({ id: d.id, title: d.data().title, description: d.data().description || "", votes: d.data().votes || 0 }));',
127
+ ' for (let i = 0; i < reqs.length; i += 200) await call({ action: "upsert", requests: reqs.slice(i, i + 200) });',
128
+ " for (let i = 0; i < reqs.length; i += 500) {",
129
+ ' const { statuses } = await call({ action: "status", ids: reqs.slice(i, i + 500).map(r => r.id) });',
130
+ ' await Promise.all(statuses.map(s => db.doc("featureRequests/" + s.id).update({ qaStatus: s })));',
131
+ " }",
132
+ "});",
133
+ FENCE,
134
+ "",
135
+ ].join("\n");
136
+ }
137
+
138
+ // Replace the synced block in a file's text, or append it. Text outside the block is kept as is.
139
+ function spliceBlock(existing, md) {
140
+ const block = `${BEGIN_MARKER}\n${md}\n${END_MARKER}`;
141
+ const beginIdx = existing.indexOf(BEGIN_MARKER);
142
+ const endIdx = existing.indexOf(END_MARKER);
143
+ if (beginIdx >= 0 && endIdx > beginIdx) {
144
+ return existing.slice(0, beginIdx) + block + existing.slice(endIdx + END_MARKER.length);
145
+ }
146
+ const sep = existing && !existing.endsWith("\n") ? "\n\n" : (existing ? "\n" : "");
147
+ return existing + sep + block + "\n";
148
+ }
149
+
150
+ // The sync time changes on every run; it must not make --check report a change on its own.
151
+ const withoutSyncTime = (text) => String(text).replace(/<!-- Last synced: [^>]*-->/g, "<!-- Last synced -->").replace(/\r\n/g, "\n");
152
+ const sameContent = (a, b) => withoutSyncTime(a) === withoutSyncTime(b);
153
+
154
+ module.exports = { BEGIN_MARKER, END_MARKER, renderBuiltSection, renderToolsSection, requestsIntegrationPrompt, spliceBlock, sameContent };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qatools-cli",
3
- "version": "1.2.17",
3
+ "version": "1.2.19",
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",
@@ -12,7 +12,8 @@
12
12
  },
13
13
  "files": [
14
14
  "qatools.js",
15
- "impact.js"
15
+ "impact.js",
16
+ "context-sync.js"
16
17
  ],
17
18
  "keywords": [
18
19
  "qa",
package/qatools.js CHANGED
@@ -873,6 +873,106 @@ program
873
873
  process.exit(0);
874
874
  });
875
875
 
876
+ // signals.user-feature-requests: connect an app's own request page, and see what has arrived
877
+ program
878
+ .command("requests-integration-prompt")
879
+ .description("Print the procedure for connecting this app's feature-request page to qa-tools (requests and votes in, status back)")
880
+ .option("--project <id>", "Project ID (default: the configured one)")
881
+ .action((options) => {
882
+ // No login needed — it only prints text. Same text as the MCP tool requests_integration_prompt.
883
+ const creds = getCredentials();
884
+ const name = options.project ? "" : (creds?.projectName || "");
885
+ console.log(require("./context-sync").requestsIntegrationPrompt(name));
886
+ process.exit(0);
887
+ });
888
+
889
+ program
890
+ .command("feature-requests")
891
+ .description("List the requests from the app's users that have reached qa-tools, most votes first")
892
+ .option("--state <state>", "Only new, linked or declined")
893
+ .option("--json", "Output as JSON")
894
+ .option("--project <id>", "Target project ID (overrides default)")
895
+ .option("-e, --email <email>", "Login email")
896
+ .option("-p, --password <password>", "Login password")
897
+ .action(async (options) => {
898
+ await authenticate(options);
899
+ const projectId = options.project || getCredentials()?.projectId;
900
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
901
+ try {
902
+ let { requests } = (await httpsCallable(functions, "listFeatureRequests")({ projectId })).data;
903
+ if (options.state) requests = requests.filter(r => r.state === options.state);
904
+ if (options.json) { console.log(JSON.stringify(requests, null, 2)); process.exit(0); }
905
+ if (!requests.length) { console.log("No requests from users yet. Connect the app: qatools requests-integration-prompt"); process.exit(0); }
906
+ console.log(`${requests.length} request(s):\n`);
907
+ for (const r of requests) {
908
+ console.log(` ▲ ${String(r.votes || 0).padStart(4)} [${r.state}] ${r.title} (app id ${r.externalId}${r.requirementId ? `, requirement ${r.requirementId}` : ""})`);
909
+ }
910
+ process.exit(0);
911
+ } catch (e) {
912
+ console.error("Failed to list requests:", e.message);
913
+ process.exit(1);
914
+ }
915
+ });
916
+
917
+ // requirements.baseline-from-code: reconstruct requirements for what is already built
918
+ program
919
+ .command("baseline-prompt")
920
+ .description("Print the procedure for reconstructing requirements from existing code, with the project's language and all existing requirements")
921
+ .option("--project <id>", "Target project ID (overrides default)")
922
+ .option("-e, --email <email>", "Login email")
923
+ .option("-p, --password <password>", "Login password")
924
+ .action(async (options) => {
925
+ await authenticate(options);
926
+ const projectId = options.project || getCredentials()?.projectId;
927
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
928
+ try {
929
+ const { data } = await httpsCallable(functions, "getBaselinePrompt")({ projectId });
930
+ console.log(data.prompt);
931
+ process.exit(0);
932
+ } catch (e) {
933
+ console.error("Failed to get the baseline prompt:", e.message);
934
+ process.exit(1);
935
+ }
936
+ });
937
+
938
+ program
939
+ .command("baseline-upload")
940
+ .description("Upload requirements reconstructed from code (JSON array with key, title, acceptanceCriteria, files, commits). They are saved as drafts for a member to approve as built.")
941
+ .requiredOption("-f, --file <path>", "JSON file: an array of reconstructed requirements")
942
+ .option("--project <id>", "Target project ID (overrides default)")
943
+ .option("-e, --email <email>", "Login email")
944
+ .option("-p, --password <password>", "Login password")
945
+ .action(async (options) => {
946
+ let requirements;
947
+ try {
948
+ requirements = JSON.parse(fs.readFileSync(options.file, "utf8"));
949
+ } catch (e) {
950
+ console.error(`Could not read ${options.file}: ${e.message}`);
951
+ process.exit(1);
952
+ }
953
+ if (!Array.isArray(requirements)) { console.error("The file must hold a JSON array of requirements"); process.exit(1); }
954
+ await authenticate(options);
955
+ const projectId = options.project || getCredentials()?.projectId;
956
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
957
+ try {
958
+ const { data } = await httpsCallable(functions, "uploadBaselineRequirements")({ projectId, requirements });
959
+ console.log(`Saved ${data.saved.length} reconstructed requirement(s) as drafts.`);
960
+ if (data.duplicates.length) {
961
+ console.log(`Skipped ${data.duplicates.length} duplicate(s):`);
962
+ for (const d of data.duplicates) console.log(` - ${d.key} (same ${d.matchedOn} as ${d.matches})`);
963
+ }
964
+ if (data.refused.length) {
965
+ console.log(`Refused ${data.refused.length}:`);
966
+ for (const r of data.refused) console.log(` - ${r.key}: ${r.reason}`);
967
+ }
968
+ if (data.saved.length) console.log("A member approves them as built in the web app: Requirements → filter panel → Reconstructed from code.");
969
+ process.exit(data.refused.length ? 2 : 0);
970
+ } catch (e) {
971
+ console.error("Upload failed:", e.message);
972
+ process.exit(1);
973
+ }
974
+ });
975
+
876
976
  program
877
977
  .command("plan-proposals")
878
978
  .description("List sprint-plan proposals (pending ones are approved in the web app: Sprints → Plan proposals)")
@@ -1254,27 +1354,24 @@ program
1254
1354
  process.exit(1);
1255
1355
  }
1256
1356
 
1257
- const md = renderAppContextMarkdown(ctx, projectId, systemAiRules);
1258
- const beginMarker = "<!-- BEGIN qatools-context (auto-synced from qa-tools, do not edit by hand) -->";
1259
- const endMarker = "<!-- END qatools-context -->";
1357
+ const { BEGIN_MARKER: beginMarker, END_MARKER: endMarker, spliceBlock, sameContent } = require("./context-sync");
1358
+ let md;
1359
+ try {
1360
+ md = await renderSyncedContext(ctx, projectId, systemAiRules);
1361
+ } catch (e) {
1362
+ console.error("Failed to fetch requirements:", e.message);
1363
+ process.exit(1);
1364
+ }
1260
1365
  const block = `${beginMarker}\n${md}\n${endMarker}`;
1261
1366
 
1262
1367
  const filePath = path.resolve(options.output);
1263
1368
  let existing = "";
1264
1369
  if (fs.existsSync(filePath)) existing = fs.readFileSync(filePath, "utf8");
1265
1370
 
1266
- let updated;
1267
- const beginIdx = existing.indexOf(beginMarker);
1268
- const endIdx = existing.indexOf(endMarker);
1269
- if (beginIdx >= 0 && endIdx > beginIdx) {
1270
- updated = existing.slice(0, beginIdx) + block + existing.slice(endIdx + endMarker.length);
1271
- } else {
1272
- const sep = existing && !existing.endsWith("\n") ? "\n\n" : (existing ? "\n" : "");
1273
- updated = existing + sep + block + "\n";
1274
- }
1371
+ const updated = spliceBlock(existing, md);
1275
1372
 
1276
1373
  if (options.check) {
1277
- if (existing === updated) {
1374
+ if (sameContent(existing, updated)) {
1278
1375
  console.log(`✓ ${options.output} is in sync with project ${projectId}`);
1279
1376
  process.exit(0);
1280
1377
  } else {
@@ -1284,7 +1381,7 @@ program
1284
1381
  }
1285
1382
 
1286
1383
  if (options.dryRun) {
1287
- if (existing === updated) {
1384
+ if (sameContent(existing, updated)) {
1288
1385
  console.log(`✓ ${options.output} already in sync — nothing would change.`);
1289
1386
  process.exit(0);
1290
1387
  }
@@ -1326,7 +1423,7 @@ program
1326
1423
  process.exit(0);
1327
1424
  }
1328
1425
 
1329
- if (existing === updated) {
1426
+ if (sameContent(existing, updated)) {
1330
1427
  console.log(`✓ ${options.output} already in sync (no changes)`);
1331
1428
  } else {
1332
1429
  fs.writeFileSync(filePath, updated);
@@ -1335,6 +1432,17 @@ program
1335
1432
  process.exit(0);
1336
1433
  });
1337
1434
 
1435
+ // context.sync-what-is-built: App Context plus what is already built, as one synced block
1436
+ async function renderSyncedContext(ctx, projectId, systemAiRules) {
1437
+ const { renderBuiltSection } = require("./context-sync");
1438
+ const [reqRes, epicRes] = await Promise.all([
1439
+ httpsCallable(functions, "listRequirements")({ projectId, status: null }),
1440
+ httpsCallable(functions, "listEpics")({ projectId }),
1441
+ ]);
1442
+ const { renderToolsSection } = require("./context-sync");
1443
+ return renderAppContextMarkdown(ctx, projectId, systemAiRules) + "\n" + renderToolsSection() + "\n" + renderBuiltSection(reqRes.data.requirements || [], epicRes.data.epics || []);
1444
+ }
1445
+
1338
1446
  function renderAppContextMarkdown(ctx, projectId, systemAiRules) {
1339
1447
  const lines = [];
1340
1448
  const ts = new Date().toISOString();
@@ -1541,6 +1649,7 @@ program
1541
1649
  .option("--title <text>", "Set title")
1542
1650
  .option("--description <text>", "Set description")
1543
1651
  .option("--ac <text>", "Set acceptance criteria")
1652
+ .option("--points <n>", "Set size in points: 1, 2, 3, 5 or 8 (empty string clears). Not for non-functional requirements.")
1544
1653
  .option("--project <id>", "Target project ID (overrides default; requires access to that project)")
1545
1654
  .option("-e, --email <email>", "Login email")
1546
1655
  .option("-p, --password <password>", "Login password")
@@ -1571,6 +1680,7 @@ program
1571
1680
  if (options.title) u.title = options.title;
1572
1681
  if (options.description) u.description = options.description;
1573
1682
  if (options.ac) u.acceptanceCriteria = options.ac;
1683
+ if (options.points !== undefined) u.points = options.points === "" ? null : Number(options.points);
1574
1684
  updates[options.id] = u;
1575
1685
  if (options.evidence) evidenceById[options.id] = options.evidence;
1576
1686
  } else {
@@ -2648,6 +2758,11 @@ App Context → Epics → Requirements → Sprint → Implementation → Test
2648
2758
  - Implement EXACTLY what the requirement says — ask if unclear
2649
2759
  - If the requirement is ambiguous, create a GAP — don't guess
2650
2760
  - Include commitId when uploading analysis
2761
+
2762
+ ## Tools you may not think of
2763
+ - Code exists that no requirement covers (built before qa-tools, or on the side): \`qatools baseline-prompt\` — reconstruct requirements from the code; a member approves them as built.
2764
+ - The app has a page where users request features and vote: \`qatools requests-integration-prompt\` — connect it, so requests and votes reach qa-tools and their status goes back to the app. See what has arrived: \`qatools feature-requests\`.
2765
+ - Something more important must go into a sprint in progress: propose a swap instead of overfilling it; a member approves.
2651
2766
  `,
2652
2767
 
2653
2768
  "qa-test-generator.md": `---
@@ -2775,7 +2890,7 @@ If the qa-tools MCP server (\`qatools mcp\`) is available, use its tools and the
2775
2890
  \`qatools sprints\`
2776
2891
  \`qatools epics -o epics.json\` (dependsOn = build order)
2777
2892
  \`qatools requirements --status approved --json\`
2778
- Capacity: count how many requirements reached implemented/tested in each completed sprint (MCP: \`sprint_velocity\`). If there is no history, say so and propose a conservative number.
2893
+ Capacity (MCP: \`sprint_velocity\` → capacity): the average done points of the last three completed sprints with points; without that history it is counted in requirements, and you say so. With no history at all, say so and propose a conservative number.
2779
2894
 
2780
2895
  2. Draft a proposal:
2781
2896
  - Only approved, functional requirements without a sprint are candidates. Continuous (non-functional) requirements are never planned — they are checked against every sprint.
@@ -2783,10 +2898,10 @@ If the qa-tools MCP server (\`qatools mcp\`) is available, use its tools and the
2783
2898
  - Carry-over: approved or in-progress requirements in an overdue sprint (end date passed, not completed) may be proposed for a move to an open sprint — they keep status and assignee. Never move requirements out of a sprint that has not passed its end date.
2784
2899
  - An epic's requirements never go before the requirements of the epics it dependsOn.
2785
2900
  - Priority 1 first, then epic priority.
2786
- - Per sprint: roughly the capacity average, counting requirements already in the sprint.
2901
+ - Per sprint: up to the capacity, counting what is already in the sprint. Requirements without points get proposed points (1, 2, 3, 5 or 8 — propose splitting anything bigger); mark them as proposed.
2787
2902
  - If existing sprints don't fit, propose new ones (name + end date) — don't create them yet.
2788
2903
 
2789
- 3. Present the proposal and WAIT: a table of sprint | requirement key | title | reason (priority / epic dependency / capacity), plus what you left out and why, and any dependency conflicts. Change nothing until the user approves.
2904
+ 3. Present the proposal and WAIT: a table of sprint | requirement key | title | points | reason (priority / epic dependency / capacity), with each sprint's total points against the capacity, plus what you left out and why, and any dependency conflicts. Change nothing until the user approves.
2790
2905
 
2791
2906
  4. Apply after approval:
2792
2907
  \`qatools sprint-create --name "Release 4.1" --end 2026-12-15\`
@@ -3058,7 +3173,7 @@ See \`.claude/skills/\` for role-specific instructions. Start with \`qa-purpose.
3058
3173
  const systemRules = syncResult.data.systemAiRules || [];
3059
3174
  if (syncCtx) {
3060
3175
  // Use the same sync logic as qatools sync
3061
- const syncMd = renderAppContextMarkdown(syncCtx, creds.projectId, systemRules);
3176
+ const syncMd = await renderSyncedContext(syncCtx, creds.projectId, systemRules);
3062
3177
  const beginMarker = "<!-- BEGIN qatools-context (auto-synced from qa-tools, do not edit by hand) -->";
3063
3178
  const endMarker = "<!-- END qatools-context -->";
3064
3179
  const block = `${beginMarker}\n${syncMd}\n${endMarker}`;
@@ -3691,9 +3806,10 @@ const mcpTools = [
3691
3806
  sprintId: mcpStr("Sprint ID to plan it in"),
3692
3807
  status: mcpStr("Initial status (default draft)", { enum: MCP_REQ_STATUSES }),
3693
3808
  force: mcpBool("Skip the semantic similarity check"),
3809
+ points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Size in points. Split anything bigger than 8. Not for non-functional requirements." },
3694
3810
  version: mcpInt("New version of an existing key (e.g. 2). Then set the old version to superseded with update_requirement."),
3695
3811
  }, ["key", "title"]),
3696
- run: async (a) => mcpCall("createRequirement", { projectId: a.projectId, ...mcpPick(a, ["key", "title", "description", "acceptanceCriteria", "negativeCriteria", "type", "priority", "category", "epicKey", "sprintId", "status", "force", "version"]) }),
3812
+ run: async (a) => mcpCall("createRequirement", { projectId: a.projectId, ...mcpPick(a, ["key", "title", "description", "acceptanceCriteria", "negativeCriteria", "type", "priority", "category", "epicKey", "sprintId", "status", "force", "version", "points"]) }),
3697
3813
  },
3698
3814
  {
3699
3815
  name: "update_requirement",
@@ -3709,11 +3825,12 @@ const mcpTools = [
3709
3825
  title: mcpStr("Title"),
3710
3826
  description: mcpStr("Description"),
3711
3827
  acceptanceCriteria: mcpStr("Acceptance criteria"),
3828
+ 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." },
3712
3829
  attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
3713
3830
  commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
3714
3831
  }, ["requirementId"]),
3715
3832
  run: async (a) => {
3716
- const updates = mcpPick(a, ["status", "assignedTo", "epicKey", "sprintId", "type", "title", "description", "acceptanceCriteria"]);
3833
+ const updates = mcpPick(a, ["status", "assignedTo", "epicKey", "sprintId", "type", "title", "description", "acceptanceCriteria", "points"]);
3717
3834
  if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
3718
3835
  const evidenceById = a.evidence ? { [a.requirementId]: a.evidence } : {};
3719
3836
  if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
@@ -3783,7 +3900,7 @@ const mcpTools = [
3783
3900
  },
3784
3901
  {
3785
3902
  name: "sprint_velocity",
3786
- description: "Planning capacity: per completed sprint, how many requirements were planned and done, plus what is already planned in each open sprint. Completed sprints use the numbers stored when they were completed (fromSnapshot true); older ones are counted from today's statuses (fromSnapshot false). averageCompletionRate = average share of planned requirements that got done.",
3903
+ description: "Planning capacity: per completed sprint, how many requirements were planned and done, plus what is already planned in each open sprint. Completed sprints use the numbers stored when they were completed (fromSnapshot true); older ones are counted from today's statuses (fromSnapshot false). averageCompletionRate = average share of planned requirements that got done. capacity (sprint.requirement-points) = average done points of the last three completed sprints with points, or — without such history — done requirements; plan each sprint up to it, counting what it already holds (openSprints[].points).",
3787
3904
  inputSchema: mcpSchema(),
3788
3905
  run: async (a) => {
3789
3906
  const [{ sprints }, { requirements }] = await Promise.all([
@@ -3796,21 +3913,35 @@ const mcpTools = [
3796
3913
  const base = { id: s.id, name: s.name, status: s.status, startDate: s.startDate || "", releaseDate: s.releaseDate || "" };
3797
3914
  // sprint.completion-snapshot: completing moves the unfinished out, so only the stored numbers show what was planned.
3798
3915
  if (s.status === "completed" && s.completionStats) {
3799
- return { ...base, planned: s.completionStats.planned, done: s.completionStats.done, moved: s.completionStats.moved, fromSnapshot: true };
3916
+ const cs = s.completionStats;
3917
+ return { ...base, planned: cs.planned, done: cs.done, moved: cs.moved, fromSnapshot: true, completedAt: cs.completedAt || "",
3918
+ ...(typeof cs.donePoints === "number" ? { plannedPoints: cs.plannedPoints, donePoints: cs.donePoints } : {}) };
3800
3919
  }
3801
3920
  const reqs = active.filter(r => r.sprintId === s.id);
3802
- return { ...base, planned: reqs.length, done: reqs.filter(r => DONE.has(r.status)).length, ...(s.status === "completed" ? { fromSnapshot: false } : {}) };
3921
+ return { ...base, planned: reqs.length, done: reqs.filter(r => DONE.has(r.status)).length,
3922
+ points: reqs.reduce((n, r) => n + (r.points || 0), 0), withoutPoints: reqs.filter(r => !r.points).length,
3923
+ ...(s.status === "completed" ? { fromSnapshot: false } : {}) };
3803
3924
  };
3804
3925
  const completed = sprints.filter(s => s.status === "completed").map(row);
3805
3926
  const withWork = completed.filter(s => s.planned > 0);
3806
3927
  const avg = withWork.length ? withWork.reduce((n, s) => n + s.done, 0) / withWork.length : null;
3807
3928
  const rate = withWork.length ? withWork.reduce((n, s) => n + s.done / s.planned, 0) / withWork.length : null;
3929
+ // Same rule as the web app (sprint-capacity.ts): last three completed sprints with points, else done requirements
3930
+ const recent = [...completed].filter(s => s.fromSnapshot).sort((x, y) => (y.completedAt || "").localeCompare(x.completedAt || ""));
3931
+ const pointed = recent.filter(s => typeof s.donePoints === "number").slice(0, 3);
3932
+ const basis = pointed.length ? pointed : recent.slice(0, 3);
3933
+ const capacity = basis.length
3934
+ ? { unit: pointed.length ? "points" : "requirements", value: Math.round(basis.reduce((n, s) => n + (pointed.length ? s.donePoints : s.done), 0) / basis.length), basedOn: basis.length,
3935
+ ...(pointed.length ? {} : { note: "No completed sprint has points yet — capacity is counted in requirements" }) }
3936
+ : null;
3808
3937
  return {
3938
+ capacity,
3809
3939
  completedSprints: completed,
3810
3940
  averageDonePerCompletedSprint: avg === null ? null : Math.round(avg * 10) / 10,
3811
3941
  averageCompletionRate: rate === null ? null : Math.round(rate * 100) / 100,
3812
3942
  openSprints: sprints.filter(s => s.status !== "completed").map(row),
3813
3943
  unplannedApprovedRequirements: active.filter(r => r.status === "approved" && !r.sprintId).length,
3944
+ unplannedApprovedWithoutPoints: active.filter(r => r.status === "approved" && !r.sprintId && r.type !== "non-functional" && !r.points).length,
3814
3945
  };
3815
3946
  },
3816
3947
  },
@@ -3832,6 +3963,7 @@ const mcpTools = [
3832
3963
  reason: mcpStr("Why this requirement goes in this sprint"),
3833
3964
  selfVerification: mcpStr("How you will verify it yourself, e.g. 'unit tests for X + API call Y' (sprint.ai-planning-self-verification)"),
3834
3965
  manualOnly: { type: "boolean", description: "true when you cannot verify it yourself at all — then testProtocols must have a test for it" },
3966
+ points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Proposed size for a requirement that has no points yet (ignored when it has); approving the row sets it" },
3835
3967
  },
3836
3968
  required: ["requirementId", "reason"],
3837
3969
  additionalProperties: false,
@@ -3899,9 +4031,25 @@ const mcpTools = [
3899
4031
  additionalProperties: false,
3900
4032
  },
3901
4033
  },
3902
- }, ["items"]),
4034
+ swaps: {
4035
+ type: "array",
4036
+ description: "sprint.mid-release-swap: take a requirement into a sprint that is in progress and move not-started (approved) requirements out to the next open sprint so it fits its capacity. Never move out one that is in progress or done, or one a staying requirement depends on through its epic. outRequirementIds may be empty to keep the sprint over capacity — say why. A requirement may appear in items or in one swap, not both.",
4037
+ items: {
4038
+ type: "object",
4039
+ properties: {
4040
+ sprintId: mcpStr("Sprint in progress to take the requirement into"),
4041
+ inRequirementId: mcpStr("Requirement taken in (approved or in progress)"),
4042
+ outRequirementIds: mcpStrArray("Requirements moved out (approved, in that sprint)"),
4043
+ reason: mcpStr("Why the change is worth it"),
4044
+ },
4045
+ required: ["sprintId", "inRequirementId", "outRequirementIds", "reason"],
4046
+ additionalProperties: false,
4047
+ },
4048
+ },
4049
+ }, []),
3903
4050
  run: async (a) => {
3904
- const r = await mcpCall("createPlanProposal", { projectId: a.projectId, ...mcpPick(a, ["goal", "summary", "items", "newSprints", "omitted", "testProtocols"]) });
4051
+ if (!a.items?.length && !a.swaps?.length) throw new McpToolError("Give items, swaps or both.");
4052
+ const r = await mcpCall("createPlanProposal", { projectId: a.projectId, ...mcpPick(a, ["goal", "summary", "items", "newSprints", "omitted", "testProtocols", "swaps"]) });
3905
4053
  return { ...r, next: "Pending. A project member approves or rejects it in qa-tools under Sprints → Plan proposals." };
3906
4054
  },
3907
4055
  },
@@ -4054,6 +4202,44 @@ const mcpTools = [
4054
4202
  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" } }),
4055
4203
  run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag }),
4056
4204
  },
4205
+ {
4206
+ name: "list_feature_requests",
4207
+ description: "Requests from the app's users (signals.user-feature-requests), most votes first: title, votes, state (new / linked / declined) and the linked requirementId. Linked requirements also carry requestVotes in list_requirements. Members act on them in the web app.",
4208
+ inputSchema: mcpSchema(),
4209
+ run: async (a) => (await mcpCall("listFeatureRequests", { projectId: a.projectId })).requests,
4210
+ },
4211
+ {
4212
+ name: "requests_integration_prompt",
4213
+ description: "Procedure, API and example code for connecting this app's own feature-request page to qa-tools: requests and votes in, status (planned / released / declined) back to the app. Use when the app has a page where users request features or vote.",
4214
+ inputSchema: mcpSchema(),
4215
+ run: async () => require("./context-sync").requestsIntegrationPrompt(getCredentials()?.projectName || ""),
4216
+ },
4217
+ {
4218
+ name: "baseline_prompt",
4219
+ description: "Procedure for reconstructing requirements for what is already built (requirements.baseline-from-code), with the project's language, its epics and all existing requirements. Use when code exists that qa-tools has no requirements for.",
4220
+ inputSchema: mcpSchema(),
4221
+ run: async (a) => (await mcpCall("getBaselinePrompt", { projectId: a.projectId })).prompt,
4222
+ },
4223
+ {
4224
+ name: "upload_baseline",
4225
+ description: "Upload requirements reconstructed from code. Each needs key, title, acceptanceCriteria (Given/When/Then in the project's language) and at least one file or commit where it is built. Saved as drafts marked as reconstructed; duplicates of existing requirements are skipped. A member approves them as built in the web app — you never approve them yourself.",
4226
+ inputSchema: mcpSchema({
4227
+ requirements: {
4228
+ type: "array", description: "Reconstructed requirements (at most 100)",
4229
+ items: {
4230
+ type: "object",
4231
+ properties: {
4232
+ key: mcpStr("Semantic key, e.g. keys.search"), title: mcpStr("Title"), description: mcpStr("Description"),
4233
+ acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"), negativeCriteria: mcpStr("Negative scenario(s)"),
4234
+ type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }), epicKey: mcpStr("Epic key"),
4235
+ files: mcpStrArray("Files where it is built, e.g. src/app/x.ts:40-88"), commits: mcpStrArray("Commits where it was built"),
4236
+ },
4237
+ required: ["key", "title", "acceptanceCriteria"],
4238
+ },
4239
+ },
4240
+ }, ["requirements"]),
4241
+ run: async (a) => mcpCall("uploadBaselineRequirements", { projectId: a.projectId, requirements: a.requirements }),
4242
+ },
4057
4243
  {
4058
4244
  name: "list_requirement_library",
4059
4245
  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.",
@@ -4204,10 +4390,13 @@ Follow these steps in order:
4204
4390
  - Only status=approved, functional requirements without a sprint are candidates. Non-functional (compliance) requirements are continuous — never plan them. Never touch completed sprints or the requirements in them. Requirements in other sprints stay where they are, except carry-over from overdue sprints (below).
4205
4391
  - An epic's requirements never go into an earlier sprint than the requirements of the epics it dependsOn.
4206
4392
  - Order by priority (1 first), then epic priority.
4207
- - Per sprint, plan roughly averageDonePerCompletedSprint requirements (from sprint_velocity), counting what is already planned there. If there is no history, say so and propose a conservative number. Mention averageCompletionRate (the share of planned requirements that usually gets done) in the proposal.
4393
+ - Per sprint, plan up to sprint_velocity's capacity (points, or requirements when no completed sprint has points — say so), counting what is already planned there (openSprints[].points). If there is no history, say so and propose a conservative number. Mention averageCompletionRate (the share of planned requirements that usually gets done) in the proposal.
4394
+ - User demand (signals.user-feature-requests): requirements carry requestVotes, the votes of the users' requests linked to them. Among requirements of the same priority, plan the ones with more votes first, and name the votes in the reason when they decided the order.
4395
+ - Points (sprint.requirement-points): a requirement without points gets proposed points, 1, 2, 3, 5 or 8 — anything bigger should be split, say so instead. Pass them as points on the propose_sprint_plan row; approving the row sets them. Non-functional requirements have no points.
4208
4396
  - Carry-over: a sprint is overdue when its end date (releaseDate) is before today and it is not completed. Requirements in an overdue sprint that are approved or in progress are candidates to MOVE to an open sprint; they keep their status and assignee, and the reason names the overdue sprint. Never move requirements out of a sprint that has not passed its end date.
4209
4397
  - If the requirements don't fit in the existing sprints, propose new sprints (name + end date) — don't create them yet.
4210
- 3. Present the proposal as a table: sprint | requirement key | title | reason (priority / epic dependency / capacity) | Claude verifies by (how you will verify it yourself — unit/integration tests, an API call, a build check — or "manual tests only" when you can't). Pass the same text as selfVerification on each propose_sprint_plan row, and manualOnly true for the "manual tests only" ones (the protocol must then have a test for them). Show moves out of overdue sprints as their own rows, marked as moves, separate from newly planned requirements. Also list what you deliberately left out and why, and any dependency conflicts you found.
4398
+ - Mid-release change (sprint.mid-release-swap): when the user wants something taken into a sprint that is in progress (start date passed, end date not), don't overfill it silently — propose a swap (propose_sprint_plan swaps): the requirement in, and not-started (approved) requirements of about the same points out to the next open sprint, lowest priority first, never one a staying requirement depends on through its epic. Show it as its own table: sprint | in | out | points freed | reason.
4399
+ 3. Present the proposal as a table: sprint | requirement key | title | points (mark proposed ones) | reason (priority / epic dependency / capacity) | Claude verifies by (how you will verify it yourself — unit/integration tests, an API call, a build check — or "manual tests only" when you can't). Pass the same text as selfVerification on each propose_sprint_plan row, and manualOnly true for the "manual tests only" ones (the protocol must then have a test for them). Show moves out of overdue sprints as their own rows, marked as moves, separate from newly planned requirements. Also list what you deliberately left out and why, and any dependency conflicts you found.
4211
4400
  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.
4212
4401
  - 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.
4213
4402
  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.
@@ -4266,7 +4455,7 @@ async function mcpHandle(msg, defaultProjectId) {
4266
4455
  if (!args.projectId) throw new McpToolError("No project configured. Pass projectId, or run: qatools setup");
4267
4456
  }
4268
4457
  const data = await tool.run(args);
4269
- return { content: [{ type: "text", text: JSON.stringify(data ?? null, null, 2) }] };
4458
+ return { content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data ?? null, null, 2) }] };
4270
4459
  } catch (e) {
4271
4460
  // Tool failures (refusals, backend permission errors) go back as tool results the model can read.
4272
4461
  return { content: [{ type: "text", text: e.message || String(e) }], isError: true };
@@ -4484,6 +4673,25 @@ program
4484
4673
  process.exit(0);
4485
4674
  });
4486
4675
 
4676
+ program
4677
+ .command("audit")
4678
+ .description("The project's security log (owner or superadmin; log in with Google, not with an API key)")
4679
+ .option("--limit <n>", "Number of entries", "50")
4680
+ .option("--json", "Output as JSON")
4681
+ .option("--project <id>", "Target project ID")
4682
+ .action(async (options) => {
4683
+ await authenticate(options);
4684
+ const projectId = options.project || getCredentials()?.projectId;
4685
+ if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
4686
+ try {
4687
+ const { entries } = (await httpsCallable(functions, "listAuditLog")({ projectId, limit: Number(options.limit) || 50 })).data;
4688
+ if (options.json) { console.log(JSON.stringify(entries, null, 2)); process.exit(0); }
4689
+ 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 : ""}`);
4690
+ if (!entries.length) console.log("No security events yet.");
4691
+ } catch (e) { console.error("Failed:", e.message); process.exit(1); }
4692
+ process.exit(0);
4693
+ });
4694
+
4487
4695
  program.hook("preAction", async (_root, cmd) => {
4488
4696
  if (cmd.name() === "mcp") return; // the MCP server reports through instructions and get_agenda
4489
4697
  for (const w of await staleWarnings({ skipSkills: cmd.name() === "init" })) console.error(`⚠ ${w}`);