bmad-method-test-architecture-enterprise 4.0.2 → 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.2",
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.2",
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",
@@ -2,7 +2,7 @@
2
2
 
3
3
  [bmod]
4
4
  code = "tea"
5
- version = "4.0.2"
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",