bmad-method-test-architecture-enterprise 4.0.1 → 4.1.0

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.
@@ -31,7 +31,7 @@
31
31
  "name": "bmad-method-test-architecture-enterprise",
32
32
  "source": "./",
33
33
  "description": "Master Test Architect module for quality strategy, test generation in red and expand modes with automatic run-and-heal, combined framework and CI setup, CI/CD quality gates, and structured testing education. Existing CI and ATDD customizations can be migrated to the new skill names. Part of the BMad Method ecosystem.",
34
- "version": "4.0.1",
34
+ "version": "4.1.0",
35
35
  "author": {
36
36
  "name": "Murat K Ozcan (TEA Creator) & Brian (BMad) Madison"
37
37
  },
package/cli/framework.js CHANGED
@@ -8,7 +8,7 @@ const { Command } = require('commander');
8
8
  const { resolveModel } = require('./lib/agent-adapters');
9
9
  const { agentOptions, WorkflowError } = require('./lib/workflow-cli');
10
10
  const { resolveTeaConfig } = require('./lib/resolve-tea-config');
11
- const { addAgentOptions, resolveWorkflowSkill, runWithEvidence } = require('./lib/workflow-cli');
11
+ const { RUN_FAILURE_CLASSES, addAgentOptions, resolveWorkflowSkill, runWithEvidence } = require('./lib/workflow-cli');
12
12
  const {
13
13
  SKILL_NAME,
14
14
  SCOPES,
@@ -182,7 +182,7 @@ function main(argv = process.argv) {
182
182
  process.stdout.write(serialized);
183
183
  }
184
184
  process.stderr.write(`tea-framework: ${error.message}${error.runDir ? `\nRetained evidence: ${error.runDir}` : ''}\n`);
185
- return ['environment-transport', 'environment-timeout', 'environment-parser'].includes(error.failureClass) ? 3 : 2;
185
+ return RUN_FAILURE_CLASSES.includes(error.failureClass) ? 3 : 2;
186
186
  }
187
187
  }
188
188
 
@@ -5,8 +5,8 @@ const path = require('node:path');
5
5
  const yaml = require('js-yaml');
6
6
  const MarkdownIt = require('markdown-it');
7
7
  const TOML = require('smol-toml');
8
- const { readInput } = require('./workflow-cli');
9
- const { liveAliasMap, liveReference, localId } = require('./trace-live');
8
+ const { WorkflowError, readInput } = require('./workflow-cli');
9
+ const { normalizedSha, liveAliasMap, liveReference, localId } = require('./trace-live');
10
10
 
11
11
  const GATE_TYPES = ['story', 'epic', 'release', 'hotfix'];
12
12
  const COLLECTION_MODES = [
@@ -43,6 +43,16 @@ function slug(value) {
43
43
  .replace(/-$/, '');
44
44
  }
45
45
 
46
+ /**
47
+ * The one coverage percentage rule: the integer floor of covered * 100 / total, and 100 for an
48
+ * empty bucket. The validator checks every summary pct with it and the prompt states PCT_RULE.
49
+ */
50
+ function coveragePct(covered, total) {
51
+ return total === 0 ? 100 : Math.floor((covered * 100) / total);
52
+ }
53
+ // The worked values come from coveragePct itself, so a changed rule changes the sentence the agent reads.
54
+ const PCT_RULE = `Every coverage pct is the integer floor of covered * 100 / total (2 of 3 covered is ${coveragePct(2, 3)}, 199 of 200 is ${coveragePct(199, 200)}), and ${coveragePct(0, 0)} when total is 0.`;
55
+
46
56
  function inputError(message) {
47
57
  return Object.assign(new Error(message), { code: 'TRACE_INPUT_INVALID' });
48
58
  }
@@ -259,7 +269,13 @@ function tracePaths(artifactRoot, runKey) {
259
269
  }
260
270
 
261
271
  function readJson(file) {
262
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
272
+ let value;
273
+ try {
274
+ value = JSON.parse(fs.readFileSync(file, 'utf8'));
275
+ } catch (error) {
276
+ if (!(error instanceof SyntaxError)) throw error;
277
+ throw new Error(`${file} is not valid JSON: ${error.message}`, { cause: error });
278
+ }
263
279
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${file} must contain a JSON object.`);
264
280
  return value;
265
281
  }
@@ -960,7 +976,9 @@ function requirementAggregation(matrix, ledger, criteria) {
960
976
  }
961
977
  if (
962
978
  !Array.isArray(row.contributors) ||
963
- row.contributors.map((contributor) => contributor?.id).join('\n') !== saved.contributors.join('\n')
979
+ row.contributors.length !== saved.contributors.length ||
980
+ row.contributors.some((contributor) => !contributor || typeof contributor !== 'object') ||
981
+ row.contributors.map((contributor) => contributor.id).join('\n') !== saved.contributors.join('\n')
964
982
  )
965
983
  throw new Error(`Trace Step 3 requirement ${saved.id} contributors must be the oracleLedger contributors, in order.`);
966
984
  for (const contributor of row.contributors)
@@ -1021,7 +1039,9 @@ function reconcileRequirementRows(summary, ledger, criteria, statuses, tables, a
1021
1039
  throw new Error(`Trace summary row ${saved.id} must list missing_behaviors as strings.`);
1022
1040
  if (
1023
1041
  !Array.isArray(row.contributors) ||
1024
- row.contributors.map((contributor) => contributor?.id).join('\n') !== saved.contributors.join('\n')
1042
+ row.contributors.length !== saved.contributors.length ||
1043
+ row.contributors.some((contributor) => !contributor || typeof contributor !== 'object') ||
1044
+ row.contributors.map((contributor) => contributor.id).join('\n') !== saved.contributors.join('\n')
1025
1045
  )
1026
1046
  throw new Error(`Trace summary row ${saved.id} contributors must be the oracleLedger contributors, in order.`);
1027
1047
  for (const contributor of row.contributors) {
@@ -1249,7 +1269,13 @@ function validateTraceOutputs({
1249
1269
  const matrix = fs.readFileSync(paths.matrix, 'utf8');
1250
1270
  const match = matrix.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
1251
1271
  if (!match) throw new Error('Trace matrix is missing progress frontmatter.');
1252
- const progress = yaml.load(match[1]);
1272
+ let progress;
1273
+ try {
1274
+ progress = yaml.load(match[1]);
1275
+ } catch (error) {
1276
+ if (error.name !== 'YAMLException') throw error;
1277
+ throw new Error(`Trace matrix progress frontmatter is not valid YAML: ${error.message}`, { cause: error });
1278
+ }
1253
1279
  if (progress?.runKey !== target.runKey || progress?.runScope !== target.runScope)
1254
1280
  throw new Error('Trace matrix has a different run identity.');
1255
1281
  if (progress.workflowStatus !== 'completed' || progress.lastStep !== 'step-05-gate-decision')
@@ -1310,8 +1336,8 @@ function validateTraceOutputs({
1310
1336
  ) {
1311
1337
  throw new Error(`Trace coverage ${name} has invalid counts.`);
1312
1338
  }
1313
- const expected = bucket.total === 0 ? 100 : Math.floor((bucket.covered * 100) / bucket.total);
1314
- if (bucket.pct !== expected) throw new Error(`Trace coverage ${name} percentage does not match its counts.`);
1339
+ if (bucket.pct !== coveragePct(bucket.covered, bucket.total))
1340
+ throw new Error(`Trace coverage ${name} percentage does not match its counts.`);
1315
1341
  }
1316
1342
  const priorities = ['P0', 'P1', 'P2', 'P3'].map((key) => summary.coverage.priority_breakdown[key]);
1317
1343
  const requirements = requirementOracle(target, oracleLedger);
@@ -1477,6 +1503,46 @@ function validateTraceOutputs({
1477
1503
  return { matrix, summary, gate };
1478
1504
  }
1479
1505
 
1506
+ /** File-system codes that mean the agent left a path absent, the wrong kind of entry, or a link loop. */
1507
+ const AGENT_PATH_CODES = new Set(['ENOENT', 'ENOTDIR', 'EISDIR', 'ELOOP']);
1508
+
1509
+ /**
1510
+ * Class a Trace validation failure for the retry decision. A file-system fault anywhere in the
1511
+ * cause chain, other than an absent, wrong-kind or looping artifact, and a ReferenceError (a defect in the
1512
+ * validator itself) are environment-parser, which never retries: the agent cannot correct either.
1513
+ * Everything else is rejected agent output, including a TypeError the validator raised on a
1514
+ * malformed value the agent wrote. A parser failure quotes agent-written text, so its `rejection`,
1515
+ * the message the next prompt and the public result carry, keeps only the CLI's own prefix and
1516
+ * the parser's location.
1517
+ */
1518
+ function classifyTraceRejection(error) {
1519
+ const chain = [];
1520
+ for (let each = error; each && chain.length < 8; each = each.cause) chain.push(each);
1521
+ const fault = chain.find((each) => each.syscall && !AGENT_PATH_CODES.has(each.code));
1522
+ if (fault || error instanceof ReferenceError) return new WorkflowError('environment-parser', error.message, { cause: error });
1523
+ const failure = new WorkflowError('agent-output', error.message, { cause: error });
1524
+ const parse = chain.find((each) => each instanceof SyntaxError || each.name === 'YAMLException');
1525
+ if (parse) {
1526
+ const at = error.message.indexOf(parse.message);
1527
+ const prefix = (
1528
+ at > 0 ? error.message.slice(0, at) : `Trace output is not valid ${parse.name === 'YAMLException' ? 'YAML' : 'JSON'}`
1529
+ ).replace(/[\s:]+$/, '');
1530
+ const location = parse.mark ? ` at line ${parse.mark.line + 1}, column ${parse.mark.column + 1}` : '';
1531
+ failure.rejection = `${prefix}${location}.`;
1532
+ }
1533
+ return failure;
1534
+ }
1535
+
1536
+ /**
1537
+ * A summary whose source_sha abbreviates the project HEAD, with the full HEAD in its place.
1538
+ * Any other value, including unknown or a different commit, is returned unchanged.
1539
+ */
1540
+ function withFullSourceSha(summary, head) {
1541
+ const recorded = typeof summary.source_sha === 'string' ? normalizedSha(summary.source_sha) : '';
1542
+ if (!head || !recorded || summary.source_sha === head || !head.startsWith(recorded)) return summary;
1543
+ return { ...summary, source_sha: head };
1544
+ }
1545
+
1480
1546
  /** Publish only the validated current attempt, updating the moved report link. */
1481
1547
  function publishTraceOutputs(value, destinations, io = fs) {
1482
1548
  const links = { ...value.summary.links, trace_report_path: destinations.matrix };
@@ -1548,6 +1614,8 @@ function publishTraceOutputs(value, destinations, io = fs) {
1548
1614
  }
1549
1615
 
1550
1616
  module.exports = {
1617
+ coveragePct,
1618
+ PCT_RULE,
1551
1619
  sourceOracleLedger,
1552
1620
  epicTicketSources,
1553
1621
  requirementOracle,
@@ -1556,5 +1624,7 @@ module.exports = {
1556
1624
  resolveTraceTarget,
1557
1625
  tracePaths,
1558
1626
  validateTraceOutputs,
1627
+ classifyTraceRejection,
1628
+ withFullSourceSha,
1559
1629
  publishTraceOutputs,
1560
1630
  };
@@ -15,18 +15,31 @@ const shaMatches = (left, right) => {
15
15
  };
16
16
  const asString = (value) => (typeof value === 'string' ? value.trim() : '');
17
17
 
18
- /** Resolve the consuming working tree independently of agent-authored metadata. */
19
- function currentSourceSha(projectRoot) {
18
+ function git(projectRoot, ...args) {
20
19
  const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
21
20
  for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']) delete env[key];
22
- const git = (...args) => spawnSync('git', ['-C', projectRoot, ...args], { encoding: 'utf8', env });
23
- const head = git('rev-parse', '--verify', 'HEAD');
24
- if (head.status === 0) return normalizedSha(head.stdout);
25
- return git('rev-parse', '--is-inside-work-tree').status === 0 ? '' : normalizedSha(process.env.GITHUB_SHA);
21
+ return spawnSync('git', ['-C', projectRoot, ...args], { encoding: 'utf8', env });
22
+ }
23
+
24
+ /** The project's own full Git object ID for HEAD, or '' when Git does not resolve one. */
25
+ function gitHead(projectRoot) {
26
+ const head = git(projectRoot, 'rev-parse', '--verify', 'HEAD');
27
+ const sha = head.status === 0 ? normalizedSha(head.stdout) : '';
28
+ return sha.length === 40 || sha.length === 64 ? sha : '';
26
29
  }
27
30
 
28
- /** Hold the original manifest before the vendor runs. Invalid evidence stays unreadable. */
29
- function captureLiveResults(file, projectRoot, enabled) {
31
+ /** Resolve the consuming working tree independently of agent-authored metadata; outside Git, the CI revision. */
32
+ function currentSourceSha(projectRoot) {
33
+ const head = gitHead(projectRoot);
34
+ if (head) return head;
35
+ return git(projectRoot, 'rev-parse', '--is-inside-work-tree').status === 0 ? '' : normalizedSha(process.env.GITHUB_SHA);
36
+ }
37
+
38
+ /**
39
+ * Hold the original manifest before the vendor runs. Invalid evidence stays unreadable. Pass
40
+ * currentSha when the caller already sampled the revision, so every check reuses one snapshot.
41
+ */
42
+ function captureLiveResults(file, projectRoot, enabled, currentSha = currentSourceSha(projectRoot)) {
30
43
  if (!enabled || !fs.existsSync(file)) return;
31
44
  let manifest;
32
45
  try {
@@ -42,12 +55,13 @@ function captureLiveResults(file, projectRoot, enabled) {
42
55
  } catch {
43
56
  manifest = null;
44
57
  }
45
- return { manifest, currentSha: currentSourceSha(projectRoot) };
58
+ return { manifest, currentSha };
46
59
  }
47
60
 
48
- function assertLiveSourceRevision(capture, projectRoot) {
61
+ /** Fail when HEAD moved since capture; pass head when the caller already read it. */
62
+ function assertLiveSourceRevision(capture, projectRoot, head) {
49
63
  if (!capture) return;
50
- if (currentSourceSha(projectRoot) !== capture.currentSha)
64
+ if ((head ?? currentSourceSha(projectRoot)) !== capture.currentSha)
51
65
  throw new Error('Trace source revision changed during the run; rerun with current live evidence.');
52
66
  }
53
67
 
@@ -136,4 +150,13 @@ function liveReference(capture, aliases) {
136
150
  };
137
151
  }
138
152
 
139
- module.exports = { captureLiveResults, assertLiveSourceRevision, liveAliasMap, liveReference, localId };
153
+ module.exports = {
154
+ normalizedSha,
155
+ gitHead,
156
+ currentSourceSha,
157
+ captureLiveResults,
158
+ assertLiveSourceRevision,
159
+ liveAliasMap,
160
+ liveReference,
161
+ localId,
162
+ };
@@ -15,6 +15,38 @@ class WorkflowError extends Error {
15
15
  this.failureClass = failureClass;
16
16
  }
17
17
  }
18
+ /**
19
+ * Failure classes that end a run after the agent was invoked; the public CLIs exit 3 for each.
20
+ * `agent-output` marks agent-written output a workflow validator rejected. Only a workflow whose
21
+ * attempts are independent opts in by throwing it, because the next attempt corrects that output.
22
+ */
23
+ const RUN_FAILURE_CLASSES = ['environment-transport', 'environment-timeout', 'environment-parser', 'agent-output'];
24
+ const RETRYABLE_FAILURE_CLASSES = ['environment-transport', 'environment-timeout', 'agent-output'];
25
+ /** Bytes of each agent stream kept in a failed attempt record. */
26
+ const AGENT_TAIL_BYTES = 2048;
27
+ /** The last bytes of one agent stream, trimmed to whole characters. */
28
+ function streamTail(text) {
29
+ const bytes = Buffer.from(String(text ?? ''), 'utf8');
30
+ if (bytes.length <= AGENT_TAIL_BYTES) return bytes.toString('utf8');
31
+ let start = bytes.length - AGENT_TAIL_BYTES;
32
+ while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
33
+ return bytes.subarray(start).toString('utf8');
34
+ }
35
+ /** Characters of a rejection message handed to the next attempt. */
36
+ const REJECTION_CHARS = 300;
37
+ /**
38
+ * A failure message safe to repeat outside local evidence: its first line only, so a parser's
39
+ * quoted snippet of agent-written text never travels, control characters removed, and a fixed
40
+ * length cap. Given attemptDir, the rejected attempt's own directory is named generically, for a
41
+ * prompt that must not send the next attempt back into it.
42
+ */
43
+ function rejectionSummary(message, attemptDir) {
44
+ const firstLine = String(message ?? '').split(/[\n\r\u2028\u2029]/, 1)[0];
45
+ const text = (attemptDir ? firstLine.split(attemptDir).join('<rejected attempt directory>') : firstLine)
46
+ .replaceAll(/[\p{Cc}\p{Cf}]/gu, ' ')
47
+ .trim();
48
+ return text.length > REJECTION_CHARS ? `${text.slice(0, REJECTION_CHARS - 3)}...` : text;
49
+ }
18
50
  const collect = (value, previous) => [...previous, value];
19
51
  /** Parse a bounded whole decimal without accepting partial or unsafe values. */
20
52
  function integer(value, name, { min = 1, max = Number.MAX_SAFE_INTEGER } = {}) {
@@ -24,7 +56,7 @@ function integer(value, name, { min = 1, max = Number.MAX_SAFE_INTEGER } = {}) {
24
56
  return Number(value);
25
57
  }
26
58
  /** Add the shared vendor, model, environment and execution controls. */
27
- function addAgentOptions(program) {
59
+ function addAgentOptions(program, { retryHelp = 'additional attempts for transport failures or timeouts, from 0 to 3' } = {}) {
28
60
  return program
29
61
  .requiredOption(
30
62
  '--agent <name>',
@@ -35,7 +67,7 @@ function addAgentOptions(program) {
35
67
  .option('--env-pass <NAME>', 'extra environment name passed to the agent (repeatable)', collect, [])
36
68
  .option('--model <name>', 'model override; defaults to the adapter pin')
37
69
  .option('--timeout-ms <n>', 'wall-clock timeout per attempt in milliseconds', '1200000')
38
- .option('--retries <n>', 'additional attempts for transport failures or timeouts, from 0 to 3', '1');
70
+ .option('--retries <n>', retryHelp, '1');
39
71
  }
40
72
  /** Validate command-line controls and resolve the requested adapter invocation. */
41
73
  function agentOptions(options, projectRoot) {
@@ -142,9 +174,18 @@ function jsonFile(target, value) {
142
174
  }
143
175
  /**
144
176
  * Execute one workflow with fresh, retained per-attempt evidence.
145
- * prepare({attemptDir,attempt}) returns {prompt,...context}.
146
- * validate({attemptDir,attempt,stdout,stderr,...context}) returns any caller result.
177
+ * prepare({attemptDir,attempt,previousRejection}) returns {prompt,...context}. previousRejection is
178
+ * {attempt,message} for the latest earlier attempt rejected as agent-output, kept across later
179
+ * transport failures and timeouts, with message reduced by rejectionSummary; otherwise undefined.
180
+ * afterAgent({attemptDir,attempt,...context}), when given, runs after every agent exit, failed or not,
181
+ * before the exit is classified; it throws a non-retryable WorkflowError when the agent broke run
182
+ * integrity, so a transport failure or timeout cannot hide a changed input from the retry decision.
183
+ * validate({attemptDir,attempt,stdout,stderr,...context}) returns any caller result. A thrown
184
+ * agent-output WorkflowError may carry `rejection`, a CLI-authored message the next prompt quotes
185
+ * in place of the raw one, which then stays in attempt evidence only.
147
186
  * Callbacks are synchronous. The result includes value, context, runDir, attemptDir, attempts and dryRun.
187
+ * A thrown failure carries runDir, attemptDir (the final attempt), attempts, and agentTail
188
+ * ({stdout,stderr}, the last bytes of the final attempt).
148
189
  */
149
190
  function runWithEvidence({
150
191
  name,
@@ -152,6 +193,7 @@ function runWithEvidence({
152
193
  evidenceRoot = '.tea-runs',
153
194
  options,
154
195
  prepare,
196
+ afterAgent,
155
197
  validate,
156
198
  capabilities = ['scoped-artifact-writes'],
157
199
  }) {
@@ -169,6 +211,7 @@ function runWithEvidence({
169
211
  const startedAt = new Date().toISOString();
170
212
  const attempts = [];
171
213
  let lastError;
214
+ let previousRejection;
172
215
  for (let attempt = 1; attempt <= invocation.retries + 1; attempt++) {
173
216
  const attemptDir = path.join(runDir, `attempt-${attempt}`);
174
217
  fs.mkdirSync(attemptDir);
@@ -179,18 +222,21 @@ function runWithEvidence({
179
222
  let failure;
180
223
  const started = Date.now();
181
224
  try {
182
- context = prepare({ attemptDir, attempt });
225
+ context = prepare({ attemptDir, attempt, previousRejection });
183
226
  if (!context || typeof context.prompt !== 'string' || !context.prompt.trim())
184
227
  throw new WorkflowError('usage', 'prepare must return a nonempty prompt');
185
228
  fs.writeFileSync(path.join(attemptDir, 'prompt.txt'), context.prompt, { flag: 'wx' });
186
229
  if (invocation.agent !== 'none') {
230
+ let agentFailure;
187
231
  try {
188
232
  ({ stdout, stderr } = runAgent(context.prompt, { ...invocation, capabilities }));
189
233
  } catch (error) {
190
234
  stdout = error.stdout || '';
191
235
  stderr = error.stderr || '';
192
- throw new WorkflowError(classOfAgentError(error), error.message, { cause: error });
236
+ agentFailure = new WorkflowError(classOfAgentError(error), error.message, { cause: error });
193
237
  }
238
+ afterAgent?.({ ...context, attemptDir, attempt });
239
+ if (agentFailure) throw agentFailure;
194
240
  try {
195
241
  value = validate({ ...context, attemptDir, attempt, stdout, stderr });
196
242
  } catch (error) {
@@ -208,6 +254,10 @@ function runWithEvidence({
208
254
  elapsedMs: Date.now() - started,
209
255
  status: failure ? 'failed' : invocation.agent === 'none' ? 'prompt-only' : 'completed',
210
256
  ...failure,
257
+ // The bounded message a public result may repeat; the raw one stays in this local record.
258
+ diagnostic: failure ? rejectionSummary(lastError.rejection ?? failure.message) : undefined,
259
+ // Undefined on success or silence, so JSON records omit it.
260
+ agentTail: failure && (stdout || stderr) ? { stdout: streamTail(stdout), stderr: streamTail(stderr) } : undefined,
211
261
  ...(context?.prompt ? { promptSha256: crypto.createHash('sha256').update(context.prompt).digest('hex') } : {}),
212
262
  };
213
263
  attempts.push(record);
@@ -226,7 +276,12 @@ function runWithEvidence({
226
276
  });
227
277
  return { value, context, runDir, attemptDir, attempts, dryRun: invocation.agent === 'none' };
228
278
  }
229
- if (!['environment-transport', 'environment-timeout'].includes(failure.failureClass) || attempt > invocation.retries) break;
279
+ lastError.agentTail = record.agentTail ?? { stdout: '', stderr: '' };
280
+ lastError.attemptDir = attemptDir;
281
+ lastError.attempts = attempts;
282
+ if (!RETRYABLE_FAILURE_CLASSES.includes(failure.failureClass) || attempt > invocation.retries) break;
283
+ if (failure.failureClass === 'agent-output')
284
+ previousRejection = { attempt, message: rejectionSummary(lastError.rejection ?? failure.message, attemptDir) };
230
285
  process.stderr.write(`${name}: attempt ${attempt} failed as ${failure.failureClass}; retrying in a fresh artifact directory\n`);
231
286
  }
232
287
  jsonFile(path.join(runDir, 'run.json'), {
@@ -247,10 +302,15 @@ function runWithEvidence({
247
302
  /** Print a retained-evidence diagnostic and map failures to public CLI codes. */
248
303
  function mainError(name, error) {
249
304
  process.stderr.write(`${name}: ${error.message}${error.runDir ? `; evidence: ${error.runDir}` : ''}\n`);
250
- return ['environment-transport', 'environment-timeout', 'environment-parser'].includes(error.failureClass) ? 3 : 2;
305
+ return RUN_FAILURE_CLASSES.includes(error.failureClass) ? 3 : 2;
251
306
  }
252
307
  module.exports = {
253
308
  WorkflowError,
309
+ RUN_FAILURE_CLASSES,
310
+ RETRYABLE_FAILURE_CLASSES,
311
+ AGENT_TAIL_BYTES,
312
+ REJECTION_CHARS,
313
+ rejectionSummary,
254
314
  integer,
255
315
  addAgentOptions,
256
316
  agentOptions,
package/cli/trace.js CHANGED
@@ -5,9 +5,20 @@ const fs = require('node:fs');
5
5
  const path = require('node:path');
6
6
  const { Command } = require('commander');
7
7
  const { resolveTeaConfig } = require('./lib/resolve-tea-config');
8
- const { captureLiveResults, assertLiveSourceRevision } = require('./lib/trace-live');
9
- const { addAgentOptions, projectPath, readInput, resolveWorkflowSkill, headlessPrompt, runWithEvidence } = require('./lib/workflow-cli');
8
+ const { captureLiveResults, currentSourceSha, gitHead } = require('./lib/trace-live');
9
+ const { neutralizeWorkflowCommands } = require('./lib/safe-log');
10
10
  const {
11
+ WorkflowError,
12
+ RUN_FAILURE_CLASSES,
13
+ addAgentOptions,
14
+ projectPath,
15
+ readInput,
16
+ resolveWorkflowSkill,
17
+ headlessPrompt,
18
+ runWithEvidence,
19
+ } = require('./lib/workflow-cli');
20
+ const {
21
+ PCT_RULE,
11
22
  sourceOracleLedger,
12
23
  epicTicketSources,
13
24
  requirementOracle,
@@ -16,6 +27,8 @@ const {
16
27
  resolveTraceTarget,
17
28
  tracePaths,
18
29
  validateTraceOutputs,
30
+ classifyTraceRejection,
31
+ withFullSourceSha,
19
32
  publishTraceOutputs,
20
33
  } = require('./lib/trace-command');
21
34
 
@@ -23,7 +36,9 @@ const NAME = 'tea-trace';
23
36
 
24
37
  function parser() {
25
38
  const command = new Command().name(NAME).description('Trace requirements to existing tests and emit a coverage gate.');
26
- addAgentOptions(command);
39
+ addAgentOptions(command, {
40
+ retryHelp: 'additional attempts after a transport failure, a timeout, or rejected agent output, from 0 to 3',
41
+ });
27
42
  return command
28
43
  .option('--project-root <path>', 'consuming project root', process.cwd())
29
44
  .option('--target <path>', 'story, epic, or requirements document, relative to project root')
@@ -101,11 +116,42 @@ function execute(options, registerOutputGuard = () => {}) {
101
116
  if (!stat.isFile()) throw new Error(`Trace input must be a regular file: ${file}`);
102
117
  return { file, real: fs.realpathSync(file), mode: stat.mode, dev: stat.dev, ino: stat.ino, bytes: fs.readFileSync(file) };
103
118
  });
119
+ // One revision snapshot serves live evidence and every integrity check. Git's own HEAD wins when
120
+ // it resolves, so a lost .git can never pass by matching a CI fallback revision.
121
+ const startGitHead = gitHead(projectRoot);
122
+ const startRevision = startGitHead || currentSourceSha(projectRoot);
104
123
  const liveCapture = captureLiveResults(
105
124
  liveResults,
106
125
  projectRoot,
107
126
  levels.includes('live') || options.collectionMode === 'runtime_manifest',
127
+ startRevision,
108
128
  );
129
+ // A moved revision or a changed input compromises the run itself; no retry can repair either.
130
+ const assertRunIntegrity = () => {
131
+ if (startGitHead ? gitHead(projectRoot) !== startGitHead : currentSourceSha(projectRoot) !== startRevision)
132
+ throw new WorkflowError(
133
+ 'environment-parser',
134
+ liveCapture
135
+ ? 'Trace source revision changed during the run; rerun with current live evidence.'
136
+ : 'Trace source revision changed during the run; the agent must not move the project HEAD.',
137
+ );
138
+ for (const input of heldInputs) {
139
+ const changed = input.missing
140
+ ? fs.existsSync(input.file)
141
+ : !fs.existsSync(input.file) ||
142
+ (() => {
143
+ const stat = fs.statSync(input.file);
144
+ return (
145
+ fs.realpathSync(input.file) !== input.real ||
146
+ stat.mode !== input.mode ||
147
+ stat.dev !== input.dev ||
148
+ stat.ino !== input.ino ||
149
+ !fs.readFileSync(input.file).equals(input.bytes)
150
+ );
151
+ })();
152
+ if (changed) throw new WorkflowError('environment-parser', `Trace agent changed a supplied input: ${input.file}`);
153
+ }
154
+ };
109
155
  const assertOutputPaths = () => {
110
156
  for (const [name, file] of Object.entries(destinations)) {
111
157
  projectPath(projectRoot, file, `trace ${name}`);
@@ -129,20 +175,36 @@ function execute(options, registerOutputGuard = () => {}) {
129
175
  fs.mkdirSync(path.dirname(options.json), { recursive: true });
130
176
  if (options.agent !== 'none' && fs.existsSync(options.json)) fs.unlinkSync(options.json);
131
177
  }
132
- const result = runWithEvidence({
178
+ const run = {
133
179
  name: NAME,
134
180
  projectRoot,
135
181
  evidenceRoot: options.evidenceDir,
136
182
  options,
137
- prepare({ attemptDir }) {
183
+ prepare({ attemptDir, previousRejection }) {
138
184
  const paths = tracePaths(attemptDir, target.runKey);
185
+ // An empty frozen ledger would tell the agent to preserve nothing, which the validator rejects.
186
+ const ledgerLines =
187
+ oracleLedger.length > 0
188
+ ? [
189
+ `Frozen source oracle ledger: ${JSON.stringify(oracleLedger)}. Preserve its requirement text, source references, identities, and explicit priorities in Step 1 and the final matrix.`,
190
+ ]
191
+ : [
192
+ 'No source oracle ledger is frozen for this run. Build the Step 1 oracleLedger from the source documents, or from the selected tests for a synthetic oracle. It must contain at least one entry.',
193
+ ];
194
+ // The CLI's own check message, reduced to one line; this attempt writes to its own directory below.
195
+ const retryLines = previousRejection
196
+ ? [
197
+ `The CLI rejected attempt ${previousRejection.attempt}'s output with this validation message: ${JSON.stringify(previousRejection.message)}. Write this attempt's artifacts so they pass that check.`,
198
+ ]
199
+ : [];
139
200
  const prompt = headlessPrompt({
140
201
  skillRoot,
141
202
  projectRoot,
142
203
  resolvedConfig,
143
204
  requestLines: [
144
205
  'Execute both trace phases, finishing Step 5. Use deterministic gate decisions.',
145
- `Frozen source oracle ledger: ${JSON.stringify(oracleLedger)}. Preserve its requirement text, source references, identities, and explicit priorities in Step 1 and the final matrix.`,
206
+ ...retryLines,
207
+ ...ledgerLines,
146
208
  'Persist Step 1 oracleLedger in matrix YAML frontmatter as an array of {id, requirement, priority, source} records. Assign priorities only where the source leaves them unspecified.',
147
209
  ...requirementLines,
148
210
  `The only trace target for this run is ${target.document ? JSON.stringify(target.document) : `the project (${target.runScope})`}.`,
@@ -154,6 +216,7 @@ function execute(options, registerOutputGuard = () => {}) {
154
216
  `Resolve {live_results_input} to ${JSON.stringify(liveResults)} and {waiver_register_input} to ${JSON.stringify(waiverRegister)}. These are inputs in the original project artifact root.`,
155
217
  `Resolve {collection_mode} to ${JSON.stringify(options.collectionMode)}, {coverage_levels} to ${JSON.stringify([...new Set(levels)].join(','))}, {allow_gate} to ${allowGate}, and {decision_mode} to "deterministic".`,
156
218
  'Resolve {coverage_basis} and {summary_confidence} to auto, then persist the concrete values selected by Step 1.',
219
+ PCT_RULE,
157
220
  `Write the matrix to ${JSON.stringify(paths.matrix)} and the schema 0.3.x summary to ${JSON.stringify(paths.summary)}.`,
158
221
  `Resolve {outputFile} and {default_output_file} to ${JSON.stringify(paths.matrix)}, {e2e_trace_summary_output} to ${JSON.stringify(paths.summary)}, and {gate_decision_output} to ${JSON.stringify(paths.gate)}.`,
159
222
  'Write the gate JSON when this run is eligible. Omit gate fields and the gate file when this run evaluates no gate.',
@@ -164,45 +227,54 @@ function execute(options, registerOutputGuard = () => {}) {
164
227
  });
165
228
  return { prompt, paths };
166
229
  },
230
+ afterAgent: assertRunIntegrity,
167
231
  validate({ paths }) {
168
- assertLiveSourceRevision(liveCapture, projectRoot);
169
- for (const input of heldInputs) {
170
- const changed = input.missing
171
- ? fs.existsSync(input.file)
172
- : !fs.existsSync(input.file) ||
173
- (() => {
174
- const stat = fs.statSync(input.file);
175
- return (
176
- fs.realpathSync(input.file) !== input.real ||
177
- stat.mode !== input.mode ||
178
- stat.dev !== input.dev ||
179
- stat.ino !== input.ino ||
180
- !fs.readFileSync(input.file).equals(input.bytes)
181
- );
182
- })();
183
- if (changed) throw new Error(`Trace agent changed a supplied input: ${input.file}`);
232
+ try {
233
+ return validateTraceOutputs({
234
+ paths,
235
+ target,
236
+ collectionMode: options.collectionMode,
237
+ allowGate,
238
+ oracleLedger,
239
+ requireOracleLedger: true,
240
+ liveCapture,
241
+ requireLiveManifest: true,
242
+ tickets,
243
+ });
244
+ } catch (error) {
245
+ throw classifyTraceRejection(error);
184
246
  }
185
- return validateTraceOutputs({
186
- paths,
187
- target,
188
- collectionMode: options.collectionMode,
189
- allowGate,
190
- oracleLedger,
191
- requireOracleLedger: true,
192
- liveCapture,
193
- requireLiveManifest: true,
194
- tickets,
195
- });
196
247
  },
197
- });
248
+ };
249
+ let result;
250
+ try {
251
+ result = runWithEvidence(run);
252
+ } catch (error) {
253
+ // Whatever the exit class, an absent matrix or summary means the agent's own words explain the failure.
254
+ if (error.attemptDir) {
255
+ const written = tracePaths(error.attemptDir, target.runKey);
256
+ error.missingArtifacts = ['matrix', 'summary'].filter((name) => {
257
+ try {
258
+ fs.lstatSync(written[name]);
259
+ return false;
260
+ } catch (statError) {
261
+ return statError.code === 'ENOENT';
262
+ }
263
+ });
264
+ }
265
+ throw error;
266
+ }
198
267
  if (result.dryRun) return { exitCode: 0, prompt: result.context.prompt, evidence: result.runDir };
199
268
  let summary;
200
269
  try {
201
270
  assertOutputPaths();
202
- assertLiveSourceRevision(liveCapture, projectRoot);
203
- summary = publishTraceOutputs(result.value, destinations);
271
+ assertRunIntegrity();
272
+ // Only the verified start snapshot of Git's own HEAD may replace an abbreviation; a CI fallback never does.
273
+ const value = { ...result.value, summary: withFullSourceSha(result.value.summary, startGitHead) };
274
+ summary = publishTraceOutputs(value, destinations);
204
275
  } catch (error) {
205
276
  error.runDir = result.runDir;
277
+ error.attempts = result.attempts;
206
278
  throw error;
207
279
  }
208
280
  const status = summary.gate_status ?? null;
@@ -220,9 +292,49 @@ function execute(options, registerOutputGuard = () => {}) {
220
292
  evidence: result.runDir,
221
293
  attempts: result.attempts.length,
222
294
  },
295
+ attemptRecords: result.attempts,
223
296
  };
224
297
  }
225
298
 
299
+ /** A failed command result; attempt records, when an agent ran, carry only bounded diagnostics. */
300
+ function failedPayload(reason, evidence, attempts) {
301
+ return {
302
+ schema_version: '0.1.0',
303
+ status: 'failed',
304
+ reason,
305
+ evidence,
306
+ ...(attempts
307
+ ? {
308
+ attempts: attempts.length,
309
+ attempt_results: attempts.map((record) => ({
310
+ attempt: record.attempt,
311
+ status: record.status,
312
+ failure_class: record.failureClass ?? null,
313
+ message: record.diagnostic ?? null,
314
+ })),
315
+ }
316
+ : {}),
317
+ };
318
+ }
319
+
320
+ /** JSON whose console copy cannot issue a CI workflow command; parsing it recovers the exact text. */
321
+ function consoleJson(text) {
322
+ return text.replaceAll('::', String.raw`:\u003a`).replaceAll('##[', String.raw`#\u0023[`);
323
+ }
324
+
325
+ /** The failure message, plus the agent's own last words when it never wrote a required artifact. */
326
+ function failureReason(error) {
327
+ // A parser rejection quotes agent-written text; its CLI-authored form stands in for it outside evidence.
328
+ const message = error.rejection ?? error.message;
329
+ if (!error.missingArtifacts?.length || !error.agentTail) return message;
330
+ const { stdout, stderr } = error.agentTail;
331
+ return [
332
+ message.replace(/\.$/, ''),
333
+ stdout.trim() ? `agent stdout tail: ${stdout.trim()}` : 'agent stdout was empty',
334
+ ...(stderr.trim() ? [`agent stderr tail: ${stderr.trim()}`] : []),
335
+ ].join('; ');
336
+ }
337
+
226
338
  function main(argv = process.argv) {
227
339
  const command = parser();
228
340
  command.exitOverride();
@@ -239,12 +351,14 @@ function main(argv = process.argv) {
239
351
  });
240
352
  } catch (error) {
241
353
  if (error.code === 'commander.helpDisplayed' || error.code === 'commander.version') return 0;
242
- const failedRun = ['environment-parser', 'environment-transport', 'environment-timeout'].includes(error.failureClass);
354
+ const failedRun = RUN_FAILURE_CLASSES.includes(error.failureClass);
243
355
  result = {
244
356
  exitCode: failedRun ? 3 : 2,
245
- payload: { schema_version: '0.1.0', status: 'failed', reason: error.message, evidence: error.runDir ?? null },
357
+ payload: failedPayload(failureReason(error), error.runDir ?? null, error.attempts),
358
+ attemptRecords: error.attempts,
246
359
  };
247
- process.stderr.write(`${NAME}: ${error.message}\n`);
360
+ // A parser rejection's raw message quotes agent-written text; attempt.json keeps it.
361
+ process.stderr.write(`${NAME}: ${neutralizeWorkflowCommands(error.rejection ?? error.message)}\n`);
248
362
  }
249
363
  if (result.prompt) {
250
364
  process.stdout.write(`${result.prompt}\n`);
@@ -256,13 +370,14 @@ function main(argv = process.argv) {
256
370
  } catch (error) {
257
371
  result = {
258
372
  exitCode: 2,
259
- payload: { schema_version: '0.1.0', status: 'failed', reason: error.message, evidence: result.payload?.evidence ?? null },
373
+ payload: failedPayload(error.message, result.payload?.evidence ?? null, result.attemptRecords),
260
374
  };
261
- process.stderr.write(`${NAME}: ${error.message}\n`);
375
+ process.stderr.write(`${NAME}: ${neutralizeWorkflowCommands(error.message)}\n`);
262
376
  }
263
377
  const text = `${JSON.stringify(result.payload, null, 2)}\n`;
264
378
  if (options?.json && (result.exitCode !== 2 || outputGuardPassed)) fs.writeFileSync(options.json, text, 'utf8');
265
- process.stdout.write(text);
379
+ // The saved result keeps exact diagnostics; the console copy cannot issue CI workflow commands.
380
+ process.stdout.write(consoleJson(text));
266
381
  }
267
382
  return result.exitCode;
268
383
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "bmad-method-test-architecture-enterprise",
4
- "version": "4.0.1",
4
+ "version": "4.1.0",
5
5
  "description": "Master Test Architect for quality strategy, test automation, and release gates",
6
6
  "keywords": [
7
7
  "bmad",
@@ -21,7 +21,7 @@ This is an **isolated subagent** running in parallel with E2E red-phase test gen
21
21
 
22
22
  **When `use_playwright_utils` is `true`, `playwright-utils-mandate.md` binds this worker.** A red-phase scaffold is real test code; generate it in the playwright-utils style without being asked.
23
23
 
24
- **If `use_pactjs_utils` is enabled AND the relevance gate opened in Step 1 AND `@seontechnologies/pactjs-utils` is installed:** Also generate consumer contract tests alongside API tests. All three are required. The flag on its own means "write Pact this way when you write it", never "this story needs a contract test", and scaffolding against an uninstalled package produces imports that do not resolve. When any of the three is false, generate the API tests and say in the output which condition was missing. `pactjs-utils-mandate.md` binds them: `.given(...createProviderState({ name, params }))`, `setJsonContent` / `setJsonBody` for builder callbacks, `createRequestFilter` for auth injection, `zodToPactMatchers` where a Zod schema exists, and the `pact-consumer-di.md` injection so `executeTest` exercises the real client instead of raw `fetch`. A red-phase contract test is still the file the developer keeps. Use the loaded pactjs-utils fragments (`pactjs-utils-overview`, `pactjs-utils-consumer-helpers`, `pactjs-utils-provider-verifier`, `pactjs-utils-request-filter`, `pact-consumer-di`, `pact-consumer-framework-setup`) for patterns. When generating consumer tests, enforce **one `pact.addInteraction()` per `it()` block** (see `pactjs-utils-consumer-helpers.md` Example 6) — PactV4's Rust FFI non-deterministically drops interactions if multiple are chained in one test. Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. When it is `true`, use the SmartBear MCP tools (Fetch Provider States, Generate Pact Tests). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Step 1 probed once; do not probe again.
24
+ **If `use_pactjs_utils` is enabled AND the relevance gate opened in Step 1 AND `@seontechnologies/pactjs-utils` is installed:** Also generate consumer contract tests alongside API tests. All three are required. The flag on its own means "write Pact this way when you write it", never "this story needs a contract test", and scaffolding against an uninstalled package produces imports that do not resolve. When any of the three is false, generate the API tests and say in the output which condition was missing. `pactjs-utils-mandate.md` binds them: `.given(...createProviderState({ name, params }))`, `setJsonContent` / `setJsonBody` for builder callbacks, `createRequestFilter` for auth injection, `zodToPactMatchers` where a Zod schema exists, and the `pact-consumer-di.md` injection so `executeTest` exercises the real client instead of raw `fetch`. A red-phase contract test is still the file the developer keeps. Use the loaded pactjs-utils fragments (`pactjs-utils-overview`, `pactjs-utils-consumer-helpers`, `pactjs-utils-provider-verifier`, `pactjs-utils-request-filter`, `pact-consumer-di`, `pact-consumer-framework-setup`) for patterns. When generating consumer tests, enforce **one `pact.addInteraction()` per `it()` block** (see `pactjs-utils-consumer-helpers.md` Example 6) — PactV4's Rust FFI non-deterministically drops interactions if multiple are chained in one test. Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. When it is `true`, use the read-only SmartBear MCP tools (`contract-testing_get_provider_states`, `contract-testing_list_pacticipants`). Call `contract-testing_generate_pact_tests` only when the user asked for PactFlow AI output: it sends code to the hosted service and spends workspace credits (`pact-mcp.md` § PactFlow AI tools need an explicit request). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Step 1 probed once; do not probe again.
25
25
 
26
26
  **Your task:** Generate API test scaffolds for the feature's expected behavior. They stay in `test.skip()` until the developer activates them for the current task (TDD RED PHASE).
27
27
 
@@ -177,7 +177,7 @@ When generating Pact consumer contract tests in the ATDD red phase, provider scr
177
177
  **Graceful degradation when provider source is inaccessible:**
178
178
 
179
179
  1. **OpenAPI/Swagger spec available**: Use the spec as the source of truth for response shapes, status codes, and field names
180
- 2. **Pact Broker available** (when `pact_mcp` is `"mcp"`): Use SmartBear MCP tools to fetch existing provider states and verified interactions as reference
180
+ 2. **Pact Broker available** (when `pact_mcp_reachable` is `true`): Use the read-only SmartBear MCP tools to fetch existing provider states and verified interactions as reference
181
181
  3. **Neither available**: For new endpoints, use acceptance criteria; for existing endpoints, use consumer-side types. Mark with `// Provider endpoint: TODO — provider source not accessible, verify manually` and set `provider_scrutiny: "pending"` in output JSON
182
182
  4. **Never silently guess**: Document all assumptions in the scrutiny evidence block
183
183
 
@@ -32,7 +32,7 @@ Apply pactjs-utils conventions from the loaded fragments (`pactjs-utils-overview
32
32
  - **Consumer `package.json`**: generate both `test:pact:consumer` (determinism gate calling `scripts/check-pact-determinism.sh`) and `test:pact:consumer:run` (inner vitest invocation).
33
33
  - **Publish script**: `scripts/publish-pact.sh` normalizes interactions with `jq -S '.interactions |= sort_by(...)'` before `pact-broker publish`.
34
34
 
35
- Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. The mode says the user allows a broker; the probe result says whether one answered. When `pact_mcp_reachable` is `true`, use the SmartBear MCP tools (Fetch Provider States, Generate Pact Tests) to inform generation. When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Do not probe again: Step 1 already did, once.
35
+ Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. The mode says the user allows a broker; the probe result says whether one answered. When `pact_mcp_reachable` is `true`, use the read-only SmartBear MCP tools (`contract-testing_get_provider_states`, `contract-testing_list_pacticipants`) to inform generation. Call `contract-testing_generate_pact_tests` only when the user asked for PactFlow AI output: it sends code to the hosted service and spends workspace credits (`pact-mcp.md` § PactFlow AI tools need an explicit request). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Do not probe again: Step 1 already did, once.
36
36
 
37
37
  ---
38
38
 
@@ -218,7 +218,7 @@ The seven points to verify for each interaction:
218
218
 
219
219
  6. **Graceful degradation** when provider source is not accessible (follows the canonical four-step protocol from `contract-testing.md`):
220
220
  1. **OpenAPI/Swagger spec available**: Use the spec as the source of truth for response shapes, status codes, and field names
221
- 2. **Pact Broker available** (when `pact_mcp` is `"mcp"` in `subagentContext.config`): Use SmartBear MCP tools to fetch existing provider states and verified interactions as reference
221
+ 2. **Pact Broker available** (when `pact_mcp_reachable` is `true` in `subagentContext.config`): Use the read-only SmartBear MCP tools to fetch existing provider states and verified interactions as reference
222
222
  3. **Neither available**: Generate from consumer types but use the TODO form of the mandatory comment: `// Provider endpoint: TODO — provider source not accessible, verify manually`. Set `provider_scrutiny: "pending"` in output JSON
223
223
  4. **Never silently guess**: Document all assumptions in the scrutiny evidence block
224
224
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  [bmod]
4
4
  code = "tea"
5
- version = "4.0.1"
5
+ version = "4.1.0"
6
6
  update_source = "github:bmad-code-org/bmad-method-test-architecture-enterprise/skills"
7
7
  skills = [
8
8
  "bmad-tea",
@@ -20,16 +20,16 @@ For a release gate, the order is: `bmad-tea-test-review` (optional), `bmad-tea-n
20
20
 
21
21
  TEA works on its own. When the method module is installed too, these routes add testing to its flow. Name a method skill only when it is installed, and a TEA skill only when it is installed; otherwise give the route without the missing step, and say which TEA skill would fill it once installed. Depth follows risk: a small, low-risk change needs none of this beyond the checks its build runs.
22
22
 
23
- | The user is | Recommend | Because |
24
- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
25
- | Planning an initiative whose risk, compliance or reach calls for a test strategy | `bmad-tea-test-design` at system level, once the PRD and architecture exist | Testability concerns reach the architecture while it can still change. |
26
- | About to build the stories of an epic | `bmad-tea-test-design` at epic level, then `bmad-tea-framework` when the project has no test framework | The epic's plan sets priorities for every story in it. |
27
- | About to build one story with settled criteria, and wants test-first work | `bmad-tea-automate` in red mode, then `bmad-build` | The builder turns the red tests green; the checklist lists them for the story's plan. Red mode takes the story's ref (`1.2`), its title, or its leaf file, and reads the ticket through the method's ticket tools; on v6 it takes the story file. |
28
- | Done with `bmad-build` and wants a maintained test suite for the work | `bmad-tea-automate` in expand mode | It writes tests that follow the project's framework and fixtures, runs them, and heals test defects. `bmad-qa-generate-e2e-tests` remains the fit for a quick, one-off set of end-to-end tests. |
29
- | Upgraded a v6 project with `bmad migrate method` and has TEA checklists, matrices or reports from before | `bmad migrate tea`, after the method migration | It moves each story output onto its v7 ticket's key from exact evidence, keeps historical citations, and lists anything it cannot map. |
30
- | Has `bmad-tea-atdd` or `bmad-tea-ci` customizations, or `bmad setup` cleanup listed them as unused | `bmad migrate tea` (migration 3), before cleanup when you can | It moves red settings into `[workflow.red]` of `bmad-tea-automate.toml` and CI settings into `[workflow.ci]` of `bmad-tea-framework.toml`, reading the cleanup backup when cleanup already removed a file. Keep the `.v6-v7-migration-backup-*` folder until it has run. |
31
- | Has tests whose quality is in doubt | `bmad-tea-test-review` | A scored audit names the flaky, slow or weak tests. |
32
- | Closing an epic or preparing a release | The release-gate order above | Trace gives the gate decision; Test Review and NFR are added when risk calls for them. |
23
+ | The user is | Recommend | Because |
24
+ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
25
+ | Planning an initiative whose risk, compliance or reach calls for a test strategy | `bmad-tea-test-design` at system level, once the PRD and architecture exist | Testability concerns reach the architecture while it can still change. |
26
+ | About to build the stories of an epic | `bmad-tea-test-design` at epic level, then `bmad-tea-framework` when the project has no test framework | The epic's plan sets priorities for every story in it. |
27
+ | About to build one story with settled criteria, and wants test-first work | `bmad-tea-automate` in red mode, then `bmad-build` | The builder turns the red tests green; the checklist lists them for the story's plan. Red mode takes the story's ref (`1.2`), its title, or its leaf file, and reads the ticket through the method's ticket tools; on v6 it takes the story file. When the ticket has only a `Verify:` line, the criteria come from the build's plan: stop `bmad-build` at its plan checkpoint with Approve and stop, run red mode, then run `bmad-build` again. A team that wants this in every build sets `bmad-build`'s `before_implement` hook to run red mode. |
28
+ | Done with `bmad-build` and wants a maintained test suite for the work | `bmad-tea-automate` in expand mode | It writes tests that follow the project's framework and fixtures, runs them, and heals test defects. `bmad-qa-generate-e2e-tests` remains the fit for a quick, one-off set of end-to-end tests. |
29
+ | Upgraded a v6 project with `bmad migrate method` and has TEA checklists, matrices or reports from before | `bmad migrate tea`, after the method migration | It moves each story output onto its v7 ticket's key from exact evidence, keeps historical citations, and lists anything it cannot map. |
30
+ | Has `bmad-tea-atdd` or `bmad-tea-ci` customizations, or `bmad setup` cleanup listed them as unused | `bmad migrate tea` (migration 3), before cleanup when you can | It moves red settings into `[workflow.red]` of `bmad-tea-automate.toml` and CI settings into `[workflow.ci]` of `bmad-tea-framework.toml`, reading the cleanup backup when cleanup already removed a file. Keep the `.v6-v7-migration-backup-*` folder until it has run. |
31
+ | Has tests whose quality is in doubt | `bmad-tea-test-review` | A scored audit names the flaky, slow or weak tests. |
32
+ | Closing an epic or preparing a release | The release-gate order above | Trace gives the gate decision; Test Review and NFR are added when risk calls for them. |
33
33
 
34
34
  The story's status is never TEA's to change. Red mode hands its tests to the builder, the builder records the work in the story's plan, and the user or an orchestrator marks the ticket done.
35
35
 
@@ -2,36 +2,68 @@
2
2
 
3
3
  ## Principle
4
4
 
5
- Use the SmartBear MCP server to enable AI agent interaction with PactFlow/Pact Broker during contract testing workflows. The MCP server provides tools for generating pact tests, fetching provider states, reviewing test quality, and checking deployment safety — all accessible through the Model Context Protocol.
5
+ Use the SmartBear MCP server to give TEA live, read-only knowledge of a PactFlow or Pact Broker workspace: which provider states exist, which pacticipants depend on a provider, what the verification matrix says, and whether a version can deploy. TEA writes, reviews and gates contract tests itself; the broker supplies facts those decisions rest on.
6
6
 
7
7
  ## Rationale
8
8
 
9
9
  ### Why MCP for contract testing?
10
10
 
11
- - **Live broker queries**: AI agents can fetch existing provider states, verification results, and deployment status directly from PactFlow
12
- - **Test generation assistance**: MCP tools generate consumer and provider tests based on existing contracts, OpenAPI specs, or templates
13
- - **Automated review**: MCP-powered review checks tests against best practices without manual inspection
14
- - **Deployment safety**: `can-i-deploy` checks integrated into agent workflows for real-time compatibility verification
11
+ - **Live broker queries**: provider states, verification results, deployed versions and the integration network come straight from the workspace instead of being guessed from consumer code
12
+ - **Deployment safety**: `can-i-deploy` and the matrix can be queried while designing a pipeline or diagnosing a failed gate
13
+ - **Blast radius**: the pacticipant network shows every consumer of a provider, which feeds risk scoring in test design
15
14
 
16
15
  ### When TEA uses it
17
16
 
18
- - **test-design workflow**: Fetch existing provider states to understand current contract landscape
19
- - **automate workflow**: Generate pact tests using broker knowledge and existing contracts
20
- - **test-review workflow**: Review pact tests against best practices with automated feedback
21
- - **ci workflow**: Reference can-i-deploy and matrix tools for pipeline guidance
17
+ - **test-design workflow**: provider states and the pacticipant network inform contract scope and risk
18
+ - **automate workflow**: existing provider states and exact pacticipant names shape generated consumer tests
19
+ - **test-review workflow**: provider states and verification results check that reviewed tests match the broker
20
+ - **ci workflow**: can-i-deploy, matrix and deployed-version queries inform pipeline gates and failure diagnosis
22
21
 
23
- ## Available Tools
22
+ ## Tool Names
24
23
 
25
- | # | Tool | Description | When Used |
26
- | --- | ------------------------- | ----------------------------------------------------------------------- | --------------------- |
27
- | 1 | **Generate Pact Tests** | Create consumer/provider tests from code, OpenAPI, or templates | automate workflow |
28
- | 2 | **Fetch Provider States** | List all provider states from broker for a given consumer-provider pair | test-design, automate |
29
- | 3 | **Review Pact Tests** | Analyze tests against contract testing best practices | test-review |
30
- | 4 | **Can I Deploy** | Check deployment safety via broker verification matrix | ci workflow |
31
- | 5 | **Matrix** | Query consumer-provider verification matrix | ci, test-design |
32
- | 6 | **PactFlow AI Status** | Check AI credits and permissions (PactFlow Cloud only) | diagnostics |
33
- | 7 | **Metrics - All** | Workspace-wide contract testing metrics | reporting |
34
- | 8 | **Metrics - Team** | Team-level adoption statistics (PactFlow Cloud only) | reporting |
24
+ Every Pact tool the server registers carries the `contract-testing_` prefix. Clients add their own server prefix in front, so Claude Code shows `mcp__smartbear__contract-testing_can_i_deploy` for a server registered as `smartbear`. Match on the `contract-testing_` part.
25
+
26
+ `@smartbear/mcp` 0.44.0 registers 104 `contract-testing_*` tools. 60 carry `readOnlyHint: true`, 15 carry `destructiveHint: true`, and the rest write to the workspace: publishing, recording deployments, webhooks, secrets, labels, environments, and an `admin_*` family that manages users, roles, teams, system accounts and API tokens. Names change between server releases, so read them from the session's tool list rather than from memory.
27
+
28
+ ## Tools TEA Calls
29
+
30
+ All of these are read-only.
31
+
32
+ | Tool | Purpose | Used in |
33
+ | ------------------------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------- |
34
+ | `contract-testing_get_provider_states` | Provider states already defined for a provider | test-design, automate, test-review |
35
+ | `contract-testing_list_pacticipants` | Exact pacticipant names as registered | automate, ci |
36
+ | `contract-testing_get_pacticipant_network` | Every consumer and provider connected to a pacticipant | test-design (risk, blast radius) |
37
+ | `contract-testing_list_integrations` | All consumer-provider pairs in the workspace | test-design |
38
+ | `contract-testing_get_pacts_for_verification` | Pacts a provider build would verify for given selectors | ci, test-review |
39
+ | `contract-testing_can_i_deploy` | Whether a version is safe to deploy to an environment | ci |
40
+ | `contract-testing_matrix` | Verification results between consumer and provider versions | ci, test-review |
41
+ | `contract-testing_list_environments` | Environment names and UUIDs | ci |
42
+ | `contract-testing_get_currently_deployed_versions` | What runs in an environment now | ci |
43
+ | `contract-testing_get_currently_supported_versions` | Released versions still supported (mobile apps, libraries) | ci |
44
+ | `contract-testing_get_metrics`, `contract-testing_get_team_metrics` | Workspace and team adoption figures (team metrics are PactFlow Cloud only) | reporting |
45
+
46
+ List tools page their results: `contract-testing_get_provider_states`, `contract-testing_get_pacticipant_network` and `contract-testing_get_currently_deployed_versions` return 5 rows per page by default. Raise `pageSize` or follow `pageNumber` until a page comes back short; reading only the first page silently drops provider states and consumers. `contract-testing_matrix` takes `latestby: "cvpv"` for a two-selector query and `"cvp"` for one.
47
+
48
+ ## Safety Rules
49
+
50
+ ### Read-only by default
51
+
52
+ TEA calls only tools whose `readOnlyHint` is true. Publishing contracts, recording deployments or releases, creating or deleting pacticipants, branches, environments, webhooks, secrets or labels, executing webhooks, and every `admin_*` tool change shared state that other teams' pipelines depend on. Those belong in CI, driven by the Pact CLI or the pipeline the ci workflow generates.
53
+
54
+ TEA calls a write tool only when the user asks for that specific change in the current conversation, names the target, and confirms. A workflow step never decides to write on its own, and a headless run never writes.
55
+
56
+ Recommend a read-only API token for agent use. A read/write token exposes every write and `admin_*` tool to the agent session.
57
+
58
+ ### PactFlow AI tools need an explicit request
59
+
60
+ `contract-testing_generate_pact_tests` and `contract-testing_review_pact_tests` are PactFlow Cloud features. Each call sends the supplied code, specs or test files to the hosted service and spends the workspace's PactFlow AI credits. TEA generates and reviews contract tests with its own knowledge fragments, so it does not call either tool unless the user asks for PactFlow AI output.
61
+
62
+ When the user does ask:
63
+
64
+ - Fetch provider states first and pass them in, so generated tests reuse existing state names.
65
+ - Treat the output as a draft. It must still pass the provider scrutiny checklist in `contract-testing.md` and, when `tea_use_pactjs_utils` is active, the substitutions in `pactjs-utils-mandate.md`.
66
+ - On a 401 or a credit error, call `contract-testing_check_pactflow_ai_entitlements` once and report what it says.
35
67
 
36
68
  ## Installation
37
69
 
@@ -132,49 +164,54 @@ Add to `.vscode/mcp.json` (note: uses `servers` key, not `mcpServers`):
132
164
 
133
165
  ## Pattern Examples
134
166
 
135
- ### Example 1: Fetching Provider States During Test Design
136
-
137
- When designing contract tests, use MCP to query existing provider states:
167
+ ### Example 1: Provider States During Test Design
138
168
 
139
169
  ```text
140
- # Agent queries SmartBear MCP during test-design workflow:
141
- # → Fetch Provider States for consumer="movie-web", provider="SampleMoviesAPI"
142
- # ← Returns: ["movie with id 1 exists", "no movies exist", "user is authenticated"]
170
+ # → contract-testing_get_provider_states provider="SampleMoviesAPI"
171
+ # ← ["movie with id 1 exists", "no movies exist", "user is authenticated"]
143
172
  #
144
- # Agent uses this to generate comprehensive consumer tests covering all states
173
+ # Consumer tests reuse these names exactly; a new state is proposed to the provider team, never invented silently.
145
174
  ```
146
175
 
147
- ### Example 2: Reviewing Pact Tests
148
-
149
- During test-review workflow, use MCP to evaluate test quality:
176
+ ### Example 2: Blast Radius for Risk Scoring
150
177
 
151
178
  ```text
152
- # Agent submits test file to SmartBear MCP Review tool:
153
- # → Review Pact Tests with test file content
154
- # ← Returns: feedback on matcher usage, state coverage, interaction naming
179
+ # → contract-testing_get_pacticipant_network pacticipantName="SampleMoviesAPI"
180
+ # ← consumers: movie-web, movie-mobile, recommendations-service
155
181
  #
156
- # Agent incorporates feedback into review report
182
+ # A breaking change to this provider touches three consumers; impact scores reflect that.
157
183
  ```
158
184
 
159
- ### Example 3: Can I Deploy Check in CI
160
-
161
- During CI workflow design, reference the can-i-deploy tool:
185
+ ### Example 3: Diagnosing a Failed can-i-deploy
162
186
 
163
187
  ```text
164
- # Agent generates CI pipeline with can-i-deploy gate:
165
- # → Can I Deploy: pacticipant="SampleMoviesAPI", version="${GITHUB_SHA}", to="production"
166
- # ← Returns: { ok: true/false, reason: "..." }
188
+ # → contract-testing_can_i_deploy pacticipant="movie-web" version="${GITHUB_SHA}" environment="production"
189
+ # ← ok: false, "no verified pact between movie-web and the version of SampleMoviesAPI in production"
167
190
  #
168
- # Agent designs pipeline to block deployment if can-i-deploy fails
191
+ # → contract-testing_list_environments (find the production UUID)
192
+ # → contract-testing_get_currently_deployed_versions environmentId=<uuid>
193
+ # → contract-testing_matrix q=[{pacticipant:"movie-web", version:"${GITHUB_SHA}"},
194
+ # {pacticipant:"SampleMoviesAPI", environment:"production"}]
195
+ # latestby="cvpv"
169
196
  ```
170
197
 
198
+ Read the matrix result:
199
+
200
+ | Matrix result | Meaning | Fix |
201
+ | ------------------------------------------------------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
202
+ | No row, consumer version is new | No provider build has verified this pact yet | Trigger verification on pact publish with a `contract_requiring_verification_published` webhook (`pact-broker-webhooks.md`), and make the provider's selectors include the consumer's branch |
203
+ | No row, provider is the one deploying | The provider never verified the consumer versions already in the environment | Add `{ deployedOrReleased: true }` to the provider's consumer version selectors |
204
+ | Row whose verification result is `success: false` | Verification ran and failed: a real contract break | Fix the consumer expectation or the provider |
205
+ | Row whose verification result is `success: true`, gate still fails | Another integration of the same pacticipant is unverified | Repeat the matrix query for each integration |
206
+ | Provider version absent from the environment | The deployment was never recorded | Record it from the deploy pipeline with `pact-broker record-deployment` |
207
+
171
208
  ## When the Tools Are Not Reachable
172
209
 
173
210
  `tea_pact_mcp` defaults to `"mcp"`, so every contract-testing step reaches this fragment on a normal install. Most installs have no broker. That is expected, and it must cost nothing.
174
211
 
175
212
  ### The probe is a tool-list check, never a broker call
176
213
 
177
- Reachability means **the SmartBear MCP tools are present in this session's tool list**. Nothing else. Do not call `Can I Deploy`, `Matrix`, or any other tool to discover whether the broker answers: a missing server is instant and free to detect, while a misconfigured or unreachable broker is a network round trip that can hang the step. The two failure modes have very different costs and only the free one is worth probing for.
214
+ Reachability means **at least one tool whose name contains `contract-testing_` is present in this session's tool list**. Nothing else. Do not call `contract-testing_can_i_deploy`, `contract-testing_matrix`, or any other tool to discover whether the broker answers: a missing server is instant and free to detect, while a misconfigured or unreachable broker is a network round trip that can hang the step. The two failure modes have very different costs and only the free one is worth probing for.
178
215
 
179
216
  Credentials are likewise not probed. `PACT_BROKER_BASE_URL` and `PACT_BROKER_TOKEN` being unset is a reason the first real tool call will fail, not a reason to make one.
180
217
 
@@ -210,14 +247,15 @@ Everything above applies to the tools in this fragment only. It has no bearing o
210
247
  - **Per-project install recommended**: Different projects may target different PactFlow tenants — match TEA's per-project config philosophy
211
248
  - **Env vars are project-specific**: `PACT_BROKER_BASE_URL` and `PACT_BROKER_TOKEN` vary by project/team
212
249
  - **Node.js 20+ required**: SmartBear MCP server requires Node.js 20 or higher
213
- - **PactFlow Cloud features**: Some tools (AI Status, Team Metrics) are only available with PactFlow Cloud, not self-hosted Pact Broker
250
+ - **PactFlow Cloud features**: PactFlow AI generation and review, bi-directional contract testing queries, team metrics and the `admin_*` tools need PactFlow Cloud; a self-hosted Pact Broker exposes the rest
251
+ - **Read-only token for agents**: a read/write token hands every write and admin tool to the session
214
252
  - **Complements pactjs-utils**: MCP provides broker interaction during design/review; pactjs-utils provides runtime utilities for test code
215
253
 
216
254
  ## Related Fragments
217
255
 
218
256
  - `pactjs-utils-overview.md` — runtime utilities that pact tests import
219
257
  - `pactjs-utils-provider-verifier.md` — verifier options that reference broker config
220
- - `pact-broker-webhooks.md` — PactFlow → GitHub webhook auth pattern and staleness monitoring; `Metrics - All` / `Matrix` MCP tools are useful here for dashboards
258
+ - `pact-broker-webhooks.md` — PactFlow → GitHub webhook auth pattern and staleness monitoring; `contract-testing_get_metrics` and `contract-testing_matrix` are useful here for dashboards
221
259
  - `contract-testing.md` — foundational contract testing patterns
222
260
 
223
261
  ## Anti-Patterns
@@ -234,9 +272,16 @@ Everything above applies to the tools in this fragment only. It has no bearing o
234
272
  ```text
235
273
  # ✅ Use MCP during planning and review:
236
274
  # - Fetch provider states to inform test design
237
- # - Generate test scaffolds from existing contracts
238
- # - Review tests for best practice compliance
239
- # - Check can-i-deploy during CI pipeline design
275
+ # - Map the pacticipant network for risk scoring
276
+ # - Check can-i-deploy and the matrix during CI pipeline design and failure diagnosis
277
+ ```
278
+
279
+ ### Wrong: Letting an agent write to the broker
280
+
281
+ ```text
282
+ # ❌ Agent calls contract-testing_publish_consumer_contracts or contract-testing_record_deployment
283
+ # from a workstation. The broker now holds a version no pipeline built, and can-i-deploy answers for it.
284
+ # ✅ Publishing and deployment records come from CI, with the commit SHA and branch of the build.
240
285
  ```
241
286
 
242
- _Source: SmartBear MCP documentation, PactFlow developer docs._
287
+ _Source: SmartBear MCP documentation, PactFlow developer docs, and the tool list of `@smartbear/mcp` 0.44.0 read over MCP `tools/list`._
@@ -40,7 +40,7 @@ pactjs-utils-zod-to-pact,Pact.js Utils Zod to Pact,"zodToPactMatchers for consum
40
40
  pactjs-utils-consumer-helpers,Pact.js Utils Consumer Helpers,"createProviderState, toJsonMap, setJsonContent, setJsonBody; PactV4 one-interaction-per-it() determinism rule","pactjs-utils,consumer,contract-testing,pact,api,determinism,pactv4",specialized,pactjs-utils-consumer-helpers.md
41
41
  pactjs-utils-provider-verifier,Pact.js Utils Provider Verifier,"Verifier builders, scoped consumerBranch selectors, provider revision metadata, isBreakingChangeTolerantBranch, and FFI-safe Vitest config","pactjs-utils,provider,consumer,contract-testing,pact,api,backend,ci,vitest,ffi,consumer-branch,provider-branch,short-lived-branch,selectors,release-branch,breaking-change",specialized,pactjs-utils-provider-verifier.md
42
42
  pactjs-utils-request-filter,Pact.js Utils Request Filter,"createRequestFilter, noOpRequestFilter for auth injection","pactjs-utils,auth,contract-testing,pact",specialized,pactjs-utils-request-filter.md
43
- pact-mcp,Pact MCP Server,"SmartBear MCP for PactFlow: generate tests, review, can-i-deploy, provider states","pact,mcp,pactflow,contract-testing,broker",specialized,pact-mcp.md
43
+ pact-mcp,Pact MCP Server,"SmartBear MCP for PactFlow: verified contract-testing_ tool names, read-only use, provider states, pacticipant network, can-i-deploy diagnosis, paging, PactFlow AI opt-in","pact,mcp,pactflow,contract-testing,broker",specialized,pact-mcp.md
44
44
  pact-consumer-framework-setup,Pact Consumer CDC Framework Setup,"Directory structure, FFI-safe vitest config, deterministic publishing, PR-only provider branch detection, and additive branch-aware can-i-deploy","pactjs-utils,consumer,contract-testing,pact,ci,framework,setup,vitest,shell-scripts,jq,pactv4,ffi,file-organization,one-file-per-pair,provider-branch,can-i-deploy,short-lived-branch",specialized,pact-consumer-framework-setup.md
45
45
  pact-broker-webhooks,Pact Broker Webhooks,"PactFlow → GitHub repository_dispatch auth, exact registered provider target checkout, staleness monitoring, and PAT rotation","pact,pactflow,broker,webhooks,github,auth,pat,ci,operations,security,provider-branch,short-lived-branch",specialized,pact-broker-webhooks.md
46
46
  adr-quality-readiness-checklist,ADR Quality Readiness Checklist,"8-category 29-criteria framework for ADR testability and NFR evidence audit","nfr,testability,adr,quality,assessment,checklist",extended,adr-quality-readiness-checklist.md