bmad-method-test-architecture-enterprise 4.4.0 → 4.4.2

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.4.0",
34
+ "version": "4.4.2",
35
35
  "author": {
36
36
  "name": "Murat K Ozcan (TEA Creator) & Brian (BMad) Madison"
37
37
  },
@@ -13,12 +13,18 @@
13
13
  * writes on the writable paths and their parents, and ALWAYS restores in a
14
14
  * finally from a permission-bit snapshot taken before the lock, so the tree
15
15
  * comes back with its exact original modes. A restore failure prints a loud
16
- * warning but never masks the run result.
16
+ * warning but never masks the run result. Root ignores permission bits, so
17
+ * the fallback is never chosen for uid 0: there it would isolate nothing.
18
+ * While locked, SIGINT, SIGTERM and SIGHUP cannot end the process before
19
+ * that restore, and a lock
20
+ * marker in the temp directory lets the next isolated run restore a tree
21
+ * that a SIGKILL left locked.
17
22
  *
18
23
  * TEA_TEST_REVIEW_ISOLATION (sandbox-exec|bwrap|chmod|none) overrides backend
19
24
  * selection; it exists so tests can force the chmod fallback on any platform.
20
25
  */
21
26
 
27
+ const crypto = require('node:crypto');
22
28
  const fs = require('node:fs');
23
29
  const os = require('node:os');
24
30
  const path = require('node:path');
@@ -27,6 +33,11 @@ const { spawnSync } = require('node:child_process');
27
33
  const { assertProfileSafePath, executableOnPath, isInside } = require('./isolation-primitives');
28
34
 
29
35
  const BACKEND_OVERRIDE_ENV = 'TEA_TEST_REVIEW_ISOLATION';
36
+ const CHMOD_SNAPSHOT_VERSION = 1;
37
+ const PERMISSION_BITS = 0o7777n;
38
+ // Node does not export these platform-specific flags.
39
+ const DARWIN_NOFOLLOW_ANY = 0x20_00_00_00;
40
+ const LINUX_PATH_ONLY = 0o1000_0000;
30
41
 
31
42
  function isolationError(message) {
32
43
  const error = new Error(message);
@@ -34,14 +45,24 @@ function isolationError(message) {
34
45
  return error;
35
46
  }
36
47
 
48
+ /** The effective uid, or null where the platform has none (win32). */
49
+ function currentUid() {
50
+ return typeof process.getuid === 'function' ? process.getuid() : null;
51
+ }
52
+
53
+ /** Why chmod cannot isolate a run as root, for the messages that would otherwise name it as an option. */
54
+ const CHMOD_ROOT_REASON =
55
+ 'chmod cannot isolate a run as root, because root ignores permission bits; install bubblewrap (bwrap) or run as a non-root user';
56
+
37
57
  /**
38
58
  * Pick the isolation backend for this platform.
39
59
  *
40
60
  * @param {object} [env] - Environment to read the override/PATH from.
41
61
  * @param {string} [platform] - Platform override for tests.
62
+ * @param {number|null} [uid] - Effective uid override for tests; root (0) never gets the chmod fallback.
42
63
  * @returns {'sandbox-exec'|'bwrap'|'chmod'|null}
43
64
  */
44
- function selectBackend(env = process.env, platform = process.platform) {
65
+ function selectBackend(env = process.env, platform = process.platform, uid = currentUid()) {
45
66
  const override = env[BACKEND_OVERRIDE_ENV];
46
67
  if (override) {
47
68
  if (override === 'none') {
@@ -54,6 +75,10 @@ function selectBackend(env = process.env, platform = process.platform) {
54
75
  return 'bwrap';
55
76
  }
56
77
  if (override === 'chmod' && platform !== 'win32') {
78
+ if (uid === 0) {
79
+ // Forcing a backend that cannot hold must fail, like a wrong platform, not run the agent unrestricted.
80
+ throw isolationError(`${BACKEND_OVERRIDE_ENV}=chmod: ${CHMOD_ROOT_REASON}.`);
81
+ }
57
82
  return 'chmod';
58
83
  }
59
84
  // A typo (e.g. "chmodd") or a backend name that is real but wrong for this
@@ -71,12 +96,26 @@ function selectBackend(env = process.env, platform = process.platform) {
71
96
  if (platform === 'linux' && executableOnPath('bwrap', env) !== null) {
72
97
  return 'bwrap';
73
98
  }
74
- if (platform !== 'win32') {
99
+ if (platform !== 'win32' && uid !== 0) {
75
100
  return 'chmod';
76
101
  }
77
102
  return null;
78
103
  }
79
104
 
105
+ /**
106
+ * Why no backend is available, for the warning or the exit 2 that follows: the root case names its own fix.
107
+ *
108
+ * @param {string} [platform] - Platform override for tests.
109
+ * @param {number|null} [uid] - Effective uid override for tests.
110
+ * @returns {string}
111
+ */
112
+ function noBackendReason(platform = process.platform, uid = currentUid()) {
113
+ if (platform !== 'win32' && uid === 0) {
114
+ return `no isolation backend is available: ${CHMOD_ROOT_REASON}`;
115
+ }
116
+ return 'no isolation backend (sandbox-exec, bwrap, chmod) is available on this platform';
117
+ }
118
+
80
119
  /**
81
120
  * Whether any isolation backend can run on this machine. Propagates
82
121
  * selectBackend's ISOLATION_ERROR for an invalid override rather than
@@ -172,8 +211,8 @@ function lockedParents(writablePath, projectRoot) {
172
211
 
173
212
  /**
174
213
  * Walk a tree depth-first without following symlinks (matching `chmod -R`), and
175
- * visit every entry. Unreadable entries are skipped rather than aborting: a
176
- * partial snapshot still restores more than a blanket `chmod -R u+w`.
214
+ * visit every entry that still exists. A tree we cannot read cannot be locked
215
+ * with a complete permission snapshot.
177
216
  */
178
217
  function walkTree(root, visit) {
179
218
  const stack = [root];
@@ -181,8 +220,9 @@ function walkTree(root, visit) {
181
220
  const current = stack.pop();
182
221
  let stats;
183
222
  try {
184
- stats = fs.lstatSync(current);
185
- } catch {
223
+ stats = fs.lstatSync(current, { bigint: true });
224
+ } catch (error) {
225
+ if (error.code !== 'ENOENT') throw isolationError(`cannot snapshot permissions for ${current}: ${error.message}`);
186
226
  continue;
187
227
  }
188
228
  if (stats.isSymbolicLink()) {
@@ -193,7 +233,8 @@ function walkTree(root, visit) {
193
233
  let names;
194
234
  try {
195
235
  names = fs.readdirSync(current);
196
- } catch {
236
+ } catch (error) {
237
+ if (error.code !== 'ENOENT') throw isolationError(`cannot snapshot permissions under ${current}: ${error.message}`);
197
238
  continue;
198
239
  }
199
240
  for (const name of names) {
@@ -203,41 +244,351 @@ function walkTree(root, visit) {
203
244
  }
204
245
  }
205
246
 
247
+ /** Record the permission bits and identity of each entry before locking it. */
248
+ function snapshotModes(projectRoot) {
249
+ const modes = new Map();
250
+ walkTree(projectRoot, (entry, stats) => {
251
+ const saved = {
252
+ mode: Number(stats.mode & PERMISSION_BITS),
253
+ dev: stats.dev.toString(),
254
+ ino: stats.ino.toString(),
255
+ birth: stats.birthtimeNs.toString(),
256
+ };
257
+ // Check procfs before locking on Linux. On macOS, make sure every writable entry can still be opened after the lock.
258
+ if ((process.platform === 'linux' && entry === projectRoot) || (process.platform === 'darwin' && (saved.mode & 0o222) !== 0)) {
259
+ try {
260
+ fs.closeSync(openChmodEntry(entry, saved));
261
+ } catch (error) {
262
+ throw isolationError(`cannot safely recover permissions for ${entry}: ${error.message}`);
263
+ }
264
+ }
265
+ modes.set(entry, saved);
266
+ });
267
+ if (modes.size === 0) throw isolationError(`cannot take a permission snapshot of ${projectRoot}`);
268
+ return modes;
269
+ }
270
+
271
+ function matchesSnapshot(stats, saved) {
272
+ return (
273
+ !stats.isSymbolicLink() &&
274
+ stats.dev.toString() === saved.dev &&
275
+ stats.ino.toString() === saved.ino &&
276
+ stats.birthtimeNs.toString() === saved.birth
277
+ );
278
+ }
279
+
280
+ function changedEntry(entry) {
281
+ return new Error(`${entry} no longer names the recorded file or directory`);
282
+ }
283
+
284
+ /** Pin the object before changing its permissions. On Linux O_PATH also covers unreadable files and special entries. */
285
+ function openChmodEntry(entry, saved) {
286
+ const flags =
287
+ process.platform === 'linux'
288
+ ? LINUX_PATH_ONLY | fs.constants.O_NOFOLLOW
289
+ : fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (process.platform === 'darwin' ? DARWIN_NOFOLLOW_ANY : fs.constants.O_NOFOLLOW);
290
+ const descriptor = fs.openSync(entry, flags);
291
+ try {
292
+ if (!matchesSnapshot(fs.fstatSync(descriptor, { bigint: true }), saved)) throw changedEntry(entry);
293
+ // Linux's leaf-only no-follow flag allows intermediate symlinks. Verify the kernel's path for the pinned object.
294
+ if (process.platform === 'linux' && fs.readlinkSync(`/proc/self/fd/${descriptor}`) !== entry) throw changedEntry(entry);
295
+ return descriptor;
296
+ } catch (error) {
297
+ fs.closeSync(descriptor);
298
+ throw error;
299
+ }
300
+ }
301
+
302
+ /** Restore only the recorded objects. A missing entry needs no restoration. */
303
+ function restoreModes(modes) {
304
+ let firstError;
305
+ for (const [entry, saved] of modes) {
306
+ try {
307
+ const current = fs.lstatSync(entry, { bigint: true });
308
+ if (!matchesSnapshot(current, saved)) throw changedEntry(entry);
309
+ if (Number(current.mode & PERMISSION_BITS) === saved.mode) continue;
310
+ const descriptor = openChmodEntry(entry, saved);
311
+ try {
312
+ if (process.platform === 'linux') fs.chmodSync(`/proc/self/fd/${descriptor}`, saved.mode);
313
+ else fs.fchmodSync(descriptor, saved.mode);
314
+ } finally {
315
+ fs.closeSync(descriptor);
316
+ }
317
+ } catch (error) {
318
+ // A missing procfs descriptor or a failed chmod is an incomplete restore, not a removed project entry.
319
+ if (error.code !== 'ENOENT' || error.path !== entry) firstError ??= error;
320
+ }
321
+ }
322
+ if (firstError) throw firstError;
323
+ }
324
+
325
+ // Signals that end a run from outside (Ctrl-C, a cancelled CI job, a closed terminal). Node's default for each is
326
+ // to exit at once, which would skip the restore and leave the whole tree, .git included, read-only.
327
+ const STOP_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
328
+
329
+ /** The locks this process holds now: project root to restore function. */
330
+ const heldLocks = new Map();
331
+ let stopHandlersInstalled = false;
332
+
206
333
  /**
207
- * Record every entry's permission bits so the lock can be undone exactly.
208
- * `chmod -R u+w` is not an inverse of `chmod -R a-w`: it drops group/other write
209
- * bits permanently and makes deliberately read-only files writable, so a local
210
- * run would silently rewrite the permissions of the tree it was protecting.
211
- *
212
- * @returns {Map<string, number>|null} Path to mode, or null when the snapshot
213
- * could not be taken (the caller then falls back to the blanket restore).
334
+ * Keep a stop signal from killing the process while a tree is locked. The agent runs under spawnSync, so a handler
335
+ * runs only once that returns: by then the supervisor, which gets the same signal, has stopped the agent and
336
+ * withIsolation's finally has restored the tree. If a lock is still held when the handler runs, it restores it.
337
+ * Either way it then re-raises the signal with Node's default action, so the process ends as the signal asked.
214
338
  */
215
- function snapshotModes(projectRoot) {
339
+ function installStopHandlers() {
340
+ if (stopHandlersInstalled) return;
341
+ stopHandlersInstalled = true;
342
+ const onStop = (signal) => {
343
+ for (const restore of heldLocks.values()) restore();
344
+ for (const name of STOP_SIGNALS) process.removeListener(name, onStop);
345
+ stopHandlersInstalled = false;
346
+ process.kill(process.pid, signal);
347
+ };
348
+ for (const name of STOP_SIGNALS) process.on(name, onStop);
349
+ }
350
+
351
+ /** The real path of projectRoot, so a project reached through a symlink has one identity and one marker. */
352
+ function canonicalRoot(projectRoot) {
353
+ const resolved = path.resolve(projectRoot);
216
354
  try {
217
- const modes = new Map();
218
- walkTree(path.resolve(projectRoot), (entry, stats) => modes.set(entry, stats.mode & 0o7777));
219
- return modes.size > 0 ? modes : null;
355
+ return fs.realpathSync(resolved);
356
+ } catch {
357
+ return resolved;
358
+ }
359
+ }
360
+
361
+ /** The per-user directory the lock markers live in: in the temp directory, but only this user can enter it. */
362
+ function markerDirectory() {
363
+ const uid = currentUid();
364
+ return path.join(os.tmpdir(), `tea-test-review-${uid === null ? 'user' : uid}`);
365
+ }
366
+
367
+ /**
368
+ * Whether the marker directory is one this user owns and nobody else can write: a directory (not a link), owned by
369
+ * this uid, with no group or other permission bits. Anything else in its place may have been planted.
370
+ */
371
+ function markerDirectoryTrusted(directory) {
372
+ let stats;
373
+ try {
374
+ stats = fs.lstatSync(directory);
375
+ } catch {
376
+ return false;
377
+ }
378
+ const uid = currentUid();
379
+ return stats.isDirectory() && !stats.isSymbolicLink() && (uid === null || stats.uid === uid) && (stats.mode & 0o077) === 0;
380
+ }
381
+
382
+ /** Create the marker directory owner-only, or refuse one that is not; a planted directory must never hold a marker. */
383
+ function ensureMarkerDirectory() {
384
+ const directory = markerDirectory();
385
+ try {
386
+ fs.mkdirSync(directory, { mode: 0o700 });
387
+ } catch (error) {
388
+ if (error.code !== 'EEXIST') throw isolationError(`cannot create the chmod lock directory ${directory}: ${error.message}`);
389
+ }
390
+ if (!markerDirectoryTrusted(directory)) {
391
+ throw isolationError(
392
+ `the chmod lock directory ${directory} is not a directory owned by this user with mode 0700; remove it and rerun.`,
393
+ );
394
+ }
395
+ return directory;
396
+ }
397
+
398
+ /** Where the lock marker for projectRoot lives: outside the locked tree, one per project, in the per-user directory. */
399
+ function lockMarkerPath(projectRoot) {
400
+ const digest = crypto.createHash('sha256').update(canonicalRoot(projectRoot)).digest('hex').slice(0, 16);
401
+ return path.join(markerDirectory(), `lock-${digest}.json`);
402
+ }
403
+
404
+ function processAlive(pid) {
405
+ if (!Number.isInteger(pid) || pid <= 0) return false;
406
+ try {
407
+ process.kill(pid, 0);
408
+ return true;
409
+ } catch (error) {
410
+ return error.code === 'EPERM';
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Read a marker-format file, or null: only a regular file this user owns (never through a link), holding a complete
416
+ * record for this project. A marker is only ever published whole, so anything unparseable is not ours to act on.
417
+ */
418
+ function readMarkerFile(file, root) {
419
+ let text;
420
+ try {
421
+ const stats = fs.lstatSync(file);
422
+ const uid = currentUid();
423
+ if (!stats.isFile() || (uid !== null && stats.uid !== uid)) return null;
424
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
425
+ try {
426
+ text = fs.readFileSync(descriptor, 'utf8');
427
+ } finally {
428
+ fs.closeSync(descriptor);
429
+ }
430
+ const record = JSON.parse(text);
431
+ return record && typeof record === 'object' && record.projectRoot === root ? record : null;
220
432
  } catch {
221
433
  return null;
222
434
  }
223
435
  }
224
436
 
437
+ /** Read the lock marker at markerPath, or null; it is read only from a trusted marker directory. */
438
+ function readMarker(markerPath, root) {
439
+ if (!markerDirectoryTrusted(path.dirname(markerPath))) return null;
440
+ return readMarkerFile(markerPath, root);
441
+ }
442
+
443
+ /** A private name beside the marker, unique to this call: a file there is this process's alone. */
444
+ function privateName(marker, kind) {
445
+ return `${marker}.${kind}.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
446
+ }
447
+
448
+ /** Write a complete marker record to a new private file (never an existing one), flushed to disk. */
449
+ function writeRecordFile(file, root, record) {
450
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
451
+ const descriptor = fs.openSync(file, flags, 0o600);
452
+ try {
453
+ fs.writeFileSync(descriptor, JSON.stringify({ projectRoot: root, pid: process.pid, ...record }), 'utf8');
454
+ fs.fsyncSync(descriptor);
455
+ } finally {
456
+ fs.closeSync(descriptor);
457
+ }
458
+ }
459
+
460
+ /** Decode a snapshot only when every entry has an identity and names a path inside the project. */
461
+ function markerSnapshot(record, root) {
462
+ if (!Array.isArray(record.modes) || record.modes.length === 0) return false;
463
+ const modes = new Map();
464
+ for (const item of record.modes) {
465
+ if (!Array.isArray(item) || item.length !== 2) return false;
466
+ const [entry, saved] = item;
467
+ if (typeof entry !== 'string' || !path.isAbsolute(entry) || path.resolve(entry) !== entry || !isInside(root, entry)) return false;
468
+ if (saved === null || typeof saved !== 'object' || !Number.isInteger(saved.mode) || saved.mode < 0 || saved.mode > 0o7777) return false;
469
+ if (![saved.dev, saved.ino, saved.birth].every((id) => typeof id === 'string' && /^-?\d+$/.test(id))) return false;
470
+ modes.set(entry, saved);
471
+ }
472
+ return modes;
473
+ }
474
+
225
475
  /**
226
- * Undo the lock. With a snapshot, every recorded entry goes back to its exact
227
- * mode; entries created during the run were never locked and are left alone.
476
+ * Restore a tree an earlier chmod-isolated run left locked: it was killed in a way no handler could catch (SIGKILL,
477
+ * a lost container). Its marker holds the permission snapshot. A marker of a process still running is left alone,
478
+ * and one that names a path outside the project is refused rather than applied.
479
+ *
480
+ * @returns {boolean} Whether a lock was found and restored.
228
481
  */
229
- function restoreModes(projectRoot, modes) {
230
- if (modes === null) {
231
- runChmod(['-R', 'u+w', projectRoot]);
232
- return;
482
+ function recoverInterruptedLock(projectRoot) {
483
+ const root = canonicalRoot(projectRoot);
484
+ const marker = lockMarkerPath(root);
485
+ const record = readMarker(marker, root);
486
+ if (record === null || processAlive(record.pid)) return false;
487
+ // Serialize stale recovery separately while leaving the original marker at
488
+ // its canonical name. Acquirers must keep seeing it until restoration is done.
489
+ const claim = `${marker}.recover`;
490
+ try {
491
+ fs.mkdirSync(claim, { mode: 0o700 });
492
+ } catch (error) {
493
+ if (error.code === 'EEXIST') return false;
494
+ throw isolationError(`cannot claim chmod lock recovery for ${root}: ${error.message}`);
233
495
  }
234
- for (const [entry, mode] of modes) {
496
+ try {
497
+ // The lock may have been recovered or acquired by another process since
498
+ // the first read. Never restore based on a record read before the claim.
499
+ const claimed = readMarker(marker, root);
500
+ if (claimed === null || processAlive(claimed.pid)) return false;
501
+ if (claimed.locked !== true) {
502
+ fs.rmSync(marker, { force: true });
503
+ return false;
504
+ }
505
+ if (claimed.snapshotVersion !== CHMOD_SNAPSHOT_VERSION) {
506
+ console.error(
507
+ `tea-test-review WARNING: cannot automatically restore ${root} from the older chmod lock marker ${marker}: it lacks file identities. ` +
508
+ 'Review the recorded paths and restore their permissions manually before removing the marker.',
509
+ );
510
+ return false;
511
+ }
512
+ const snapshot = markerSnapshot(claimed, root);
513
+ if (snapshot === false) {
514
+ console.error(
515
+ `tea-test-review WARNING: ignoring the chmod lock marker ${marker}: it names a path outside ${root} or has an invalid permission snapshot. ` +
516
+ 'Review the recorded paths and restore their permissions manually before removing the marker.',
517
+ );
518
+ return false;
519
+ }
235
520
  try {
236
- fs.chmodSync(entry, mode);
237
- } catch {
238
- // entry was removed during the run; nothing to restore
521
+ restoreModes(snapshot);
522
+ } catch (error) {
523
+ console.error(
524
+ `tea-test-review WARNING: a previous run left ${root} read-only and restoring it failed: ${error.message}. ` +
525
+ 'Review the recorded paths and restore their permissions manually before removing the marker.',
526
+ );
527
+ return false;
528
+ }
529
+ fs.rmSync(marker, { force: true });
530
+ console.error(`tea-test-review: restored the write permissions an interrupted run (pid ${claimed.pid}) left on ${root}.`);
531
+ return true;
532
+ } finally {
533
+ fs.rmdirSync(claim);
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Take the lock marker for root before anything is snapshotted or locked. The record is written whole to a private
539
+ * file and published with an exclusive hard link, so the marker either does not exist or is complete: no run ever
540
+ * sees an empty one, and a second run on the same project cannot record the first run's locked modes as its own.
541
+ * A live holder fails this run; a dead holder's lock is recovered first.
542
+ *
543
+ * @returns {{ write: (record: object) => void, remove: () => void }}
544
+ */
545
+ function acquireLockMarker(root) {
546
+ ensureMarkerDirectory();
547
+ const marker = lockMarkerPath(root);
548
+ const initial = privateName(marker, 'new');
549
+ writeRecordFile(initial, root, { locked: false, modes: null });
550
+ try {
551
+ for (let attempt = 0; ; attempt += 1) {
552
+ try {
553
+ fs.linkSync(initial, marker);
554
+ break;
555
+ } catch (error) {
556
+ if (error.code !== 'EEXIST') throw isolationError(`cannot take the chmod lock for ${root}: ${error.message}`);
557
+ const holder = readMarker(marker, root);
558
+ if (holder !== null && processAlive(holder.pid)) {
559
+ throw isolationError(
560
+ `another tea-test-review run (pid ${holder.pid}) holds the chmod lock on ${root}; wait for it to finish and rerun.`,
561
+ );
562
+ }
563
+ if (attempt > 0) {
564
+ const claim = `${marker}.recover`;
565
+ if (fs.existsSync(claim)) {
566
+ throw isolationError(
567
+ `chmod lock recovery for ${root} is already claimed at ${claim}; wait for it to finish. ` +
568
+ 'If the recovering process was killed, make sure no recovery is running, then remove only the empty .recover directory and retry.',
569
+ );
570
+ }
571
+ throw isolationError(`a chmod lock marker ${marker} could not be recovered; check ${root} and remove the marker.`);
572
+ }
573
+ recoverInterruptedLock(root);
574
+ }
239
575
  }
576
+ } finally {
577
+ fs.rmSync(initial, { force: true });
240
578
  }
579
+ // Each update is written whole beside the marker and renamed over it, so a run killed mid-write leaves the previous
580
+ // complete record, never a torn one.
581
+ const write = (record) => {
582
+ const temporary = privateName(marker, 'tmp');
583
+ try {
584
+ writeRecordFile(temporary, root, record);
585
+ fs.renameSync(temporary, marker);
586
+ } finally {
587
+ fs.rmSync(temporary, { force: true });
588
+ }
589
+ };
590
+ const remove = () => fs.rmSync(marker, { force: true });
591
+ return { write, remove };
241
592
  }
242
593
 
243
594
  /**
@@ -245,7 +596,7 @@ function restoreModes(projectRoot, modes) {
245
596
  * writable. Only paths inside the project root need unlocking; the root itself
246
597
  * stays locked so the agent cannot create new top-level entries.
247
598
  */
248
- function prepareChmodLock(projectRoot, writablePaths) {
599
+ function prepareChmodLock(projectRoot, writablePaths, marker, onSnapshot = () => {}) {
249
600
  const root = path.resolve(projectRoot);
250
601
  const insidePaths = writablePaths.map((entry) => path.resolve(entry)).filter((entry) => entry !== root && isInside(root, entry));
251
602
  // Snapshot phase: the artifact parent directories must exist before the tree
@@ -264,6 +615,10 @@ function prepareChmodLock(projectRoot, writablePaths) {
264
615
  }
265
616
  }
266
617
  const modes = snapshotModes(projectRoot);
618
+ // The snapshot is in the marker before the lock, so no moment exists where the tree is locked and nothing records
619
+ // how to undo it.
620
+ marker.write({ locked: true, snapshotVersion: CHMOD_SNAPSHOT_VERSION, modes: [...modes] });
621
+ onSnapshot(modes);
267
622
  runChmod(['-R', 'a-w', projectRoot]);
268
623
  for (const entry of insidePaths) {
269
624
  if (fs.existsSync(entry)) {
@@ -287,6 +642,7 @@ function prepareChmodLock(projectRoot, writablePaths) {
287
642
  * @returns {any} fn's return value.
288
643
  */
289
644
  function withIsolation(projectRoot, writablePaths, fn) {
645
+ recoverInterruptedLock(projectRoot);
290
646
  const backend = selectBackend();
291
647
  if (backend === null) {
292
648
  return fn({ agentCwd: projectRoot, spawnPrefix: [] });
@@ -312,24 +668,56 @@ function withIsolation(projectRoot, writablePaths, fn) {
312
668
  }
313
669
  }
314
670
 
315
- const modes = prepareChmodLock(projectRoot, writablePaths);
316
- try {
317
- return fn({ agentCwd: projectRoot, spawnPrefix: [] });
318
- } finally {
671
+ // The lock works on the project's real path, so the marker, the snapshot and the restore agree on one identity.
672
+ const root = canonicalRoot(projectRoot);
673
+ const resolved = path.resolve(projectRoot);
674
+ const lockedWritable = writablePaths.map((entry) => {
675
+ const absolute = path.resolve(entry);
676
+ return isInside(resolved, absolute) ? path.join(root, path.relative(resolved, absolute)) : absolute;
677
+ });
678
+ let released = false;
679
+ let marker = null;
680
+ let locking = false;
681
+ let modes = null;
682
+ const release = () => {
683
+ if (released) return;
684
+ released = true;
685
+ heldLocks.delete(root);
686
+ if (marker === null) return; // the lock was never taken
687
+ if (!locking) {
688
+ marker.remove(); // nothing was locked, so there is nothing to undo
689
+ return;
690
+ }
319
691
  try {
320
- restoreModes(projectRoot, modes);
692
+ restoreModes(modes);
693
+ marker.remove();
321
694
  } catch (error) {
322
695
  console.error(
323
- `tea-test-review WARNING: failed to restore write permissions under ${projectRoot}: ${error.message}. ` +
324
- 'Restore manually with: chmod -R u+w <path>',
696
+ `tea-test-review WARNING: failed to restore write permissions under ${root}: ${error.message}. ` +
697
+ 'Review the recorded paths and restore their permissions manually before removing the marker.',
325
698
  );
326
699
  }
700
+ };
701
+ installStopHandlers();
702
+ heldLocks.set(root, release);
703
+ try {
704
+ marker = acquireLockMarker(root);
705
+ prepareChmodLock(root, lockedWritable, marker, (snapshot) => {
706
+ modes = snapshot;
707
+ locking = true;
708
+ });
709
+ return fn({ agentCwd: projectRoot, spawnPrefix: [] });
710
+ } finally {
711
+ release();
327
712
  }
328
713
  }
329
714
 
330
715
  module.exports = {
331
716
  withIsolation,
717
+ lockMarkerPath,
718
+ recoverInterruptedLock,
332
719
  isolationAvailable,
720
+ noBackendReason,
333
721
  selectBackend,
334
722
  buildSandboxProfile,
335
723
  buildBwrapPrefix,
@@ -304,9 +304,13 @@ function agentAnswer({ outcome, stdout, stderr }, { command: spawned, agentComma
304
304
  }
305
305
  const error = new Error(`Agent "${command}" ${ending}${stopped}.`);
306
306
  error.code = 'AGENT_FAILED';
307
+ // The signal that asked the agent's group to stop, so a caller can tell a cancelled run from a failed one.
308
+ if (typeof outcome.stoppedBy === 'string') error.stoppedBy = outcome.stoppedBy;
307
309
  throw withStreams(error);
308
310
  }
309
311
 
312
+ // An agent that exits 0 after a stop still ran under one: a caller must not retry what was cancelled.
313
+ if (typeof outcome.stoppedBy === 'string') return { stdout: stdout || '', stderr: stderr || '', stoppedBy: outcome.stoppedBy };
310
314
  return { stdout: stdout || '', stderr: stderr || '' };
311
315
  }
312
316
 
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
4
6
  const { spawnSync } = require('node:child_process');
5
7
 
6
8
  const normalizedSha = (value) => {
@@ -15,10 +17,39 @@ const shaMatches = (left, right) => {
15
17
  };
16
18
  const asString = (value) => (typeof value === 'string' ? value.trim() : '');
17
19
 
20
+ const REPOSITORY_ENV = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR'];
21
+
22
+ /**
23
+ * The `safe.directory` entries of the user's system and global Git config, in the order Git reads them. Git honors
24
+ * this key only from protected config, so a checkout owned by another user (a container job, where
25
+ * `actions/checkout` adds the entry globally) is refused once that config is hidden. Read in the user's normal
26
+ * environment, outside any repository, so the repository's own config cannot add one, and through the files those
27
+ * scopes include, as Git reads them.
28
+ */
29
+ function safeDirectories() {
30
+ const env = { ...process.env };
31
+ for (const key of REPOSITORY_ENV) delete env[key];
32
+ const values = [];
33
+ for (const scope of ['--system', '--global']) {
34
+ // --includes: a scoped read skips include.path files unless asked, and plain Git reads them. -z: a value may hold
35
+ // a newline, so values are NUL-terminated; an empty value (which resets the list) is kept.
36
+ const result = spawnSync('git', ['config', scope, '--includes', '-z', '--get-all', 'safe.directory'], {
37
+ encoding: 'utf8',
38
+ env,
39
+ cwd: os.tmpdir(),
40
+ });
41
+ if (result.status === 0 && result.stdout) values.push(...result.stdout.split('\0').slice(0, -1));
42
+ }
43
+ return values;
44
+ }
45
+
18
46
  function git(projectRoot, ...args) {
47
+ // The user's config stays out (aliases, hooks and the like), except `safe.directory`, passed on the command line,
48
+ // which Git also honors, so Trace reads HEAD wherever plain `git` can.
49
+ const trusted = safeDirectories().flatMap((value) => ['-c', `safe.directory=${value}`]);
19
50
  const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
20
- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']) delete env[key];
21
- return spawnSync('git', ['-C', projectRoot, ...args], { encoding: 'utf8', env });
51
+ for (const key of REPOSITORY_ENV) delete env[key];
52
+ return spawnSync('git', [...trusted, '-C', projectRoot, ...args], { encoding: 'utf8', env });
22
53
  }
23
54
 
24
55
  /** The project's own full Git object ID for HEAD, or '' when Git does not resolve one. */
@@ -32,7 +63,26 @@ function gitHead(projectRoot) {
32
63
  function currentSourceSha(projectRoot) {
33
64
  const head = gitHead(projectRoot);
34
65
  if (head) return head;
35
- return git(projectRoot, 'rev-parse', '--is-inside-work-tree').status === 0 ? '' : normalizedSha(process.env.GITHUB_SHA);
66
+ const location = git(projectRoot, 'rev-parse', '--is-inside-work-tree');
67
+ // An unreadable or untrusted checkout is not a source archive. Refuse the
68
+ // CI fallback if Git failed or if checkout metadata is still present.
69
+ if (location.error || location.status !== 128) return '';
70
+ let directory;
71
+ try {
72
+ directory = fs.realpathSync(projectRoot);
73
+ } catch {
74
+ return '';
75
+ }
76
+ for (; ; directory = path.dirname(directory)) {
77
+ try {
78
+ fs.lstatSync(path.join(directory, '.git'));
79
+ return '';
80
+ } catch (error) {
81
+ if (error.code !== 'ENOENT') return '';
82
+ }
83
+ if (directory === path.dirname(directory)) break;
84
+ }
85
+ return normalizedSha(process.env.GITHUB_SHA);
36
86
  }
37
87
 
38
88
  /**
@@ -154,6 +204,7 @@ module.exports = {
154
204
  normalizedSha,
155
205
  gitHead,
156
206
  currentSourceSha,
207
+ safeDirectories,
157
208
  captureLiveResults,
158
209
  assertLiveSourceRevision,
159
210
  liveAliasMap,
@@ -82,7 +82,7 @@ const { loadRegistryRowSeverities } = require('./lib/registry-rows');
82
82
  const { runAgent } = require('./lib/run-agent');
83
83
  const { neutralizeWorkflowCommands } = require('./lib/safe-log');
84
84
  const { AGENT_ADAPTERS, resolveModel, resolvedModelFromAnswer, agentAnswerText } = require('./lib/agent-adapters');
85
- const { withIsolation, selectBackend } = require('./lib/isolate');
85
+ const { withIsolation, selectBackend, noBackendReason, recoverInterruptedLock } = require('./lib/isolate');
86
86
  const { resolveTeaConfig, PACT_MCP_VALUES, EXECUTION_MODE_VALUES } = require('./lib/resolve-tea-config');
87
87
  const { RUBRIC_VERSION, TEA_CLI_VERSION, buildReviewProvenance, skillRubricVersion } = require('./lib/review-provenance');
88
88
  const { validInterval } = require('./lib/heartbeat');
@@ -1366,6 +1366,10 @@ async function runReview(session) {
1366
1366
  }
1367
1367
  }
1368
1368
 
1369
+ // A chmod-isolated run killed by SIGKILL left the tree read-only; restore it from its marker before the output
1370
+ // checks below, which would otherwise fail on the locked directories (#514).
1371
+ recoverInterruptedLock(projectRoot);
1372
+
1369
1373
  // An output the agent cannot write fails every attempt after the paid agent run,
1370
1374
  // so the directories are made and checked once, up front, as an environment error.
1371
1375
  for (const artifact of [outputPath, jsonPath]) {
@@ -1409,9 +1413,9 @@ async function runReview(session) {
1409
1413
  if (backend !== null) {
1410
1414
  isolationActive = true;
1411
1415
  } else if (isolateExplicit) {
1412
- fail(EXIT.ENV_ERROR, '--isolate was requested but no isolation backend (sandbox-exec, bwrap, chmod) is available on this platform.');
1416
+ fail(EXIT.ENV_ERROR, `--isolate was requested but ${noBackendReason()}.`);
1413
1417
  } else {
1414
- console.error('tea-test-review: CI requested isolation but no backend is available on this platform; continuing without it.');
1418
+ console.error(`tea-test-review: CI requested isolation but ${noBackendReason()}; continuing without it.`);
1415
1419
  }
1416
1420
  }
1417
1421
 
@@ -1485,6 +1489,8 @@ async function runReview(session) {
1485
1489
  runId: randomUUID(),
1486
1490
  });
1487
1491
 
1492
+ // The stop signal an agent that exited 0 ran under: a report it left incomplete is a stopped run, not a retry.
1493
+ let agentStoppedBy = null;
1488
1494
  const executeAgent = ({ agentCwd, spawnPrefix }) => {
1489
1495
  const stopHeartbeat = startHeartbeat();
1490
1496
  let agentResult;
@@ -1505,6 +1511,7 @@ async function runReview(session) {
1505
1511
  stopHeartbeat();
1506
1512
  }
1507
1513
 
1514
+ agentStoppedBy = agentResult.stoppedBy ?? null;
1508
1515
  const ranModel = resolvedModelFromAnswer(options.agent, agentResult.stdout);
1509
1516
  if (ranModel !== null) {
1510
1517
  resolvedModel = ranModel;
@@ -1793,6 +1800,10 @@ async function runReview(session) {
1793
1800
  }
1794
1801
  processReport();
1795
1802
  return gateFailures;
1803
+ } catch (error) {
1804
+ // A complete report written before the stop still counts; a missing or broken one is not retried.
1805
+ if (agentStoppedBy !== null && error && error.stoppedBy === undefined) error.stoppedBy = agentStoppedBy;
1806
+ throw error;
1796
1807
  } finally {
1797
1808
  cleanupRunArtifacts();
1798
1809
  }
@@ -1813,7 +1824,9 @@ async function runReview(session) {
1813
1824
  }
1814
1825
  if (error.code === 'AGENT_FAILED' || error.code === 'REPORT_MISSING' || error.code === 'REPORT_UNPARSEABLE') {
1815
1826
  if (error.code === 'AGENT_FAILED') printAgentFailureDiagnostics(error, options.agent);
1816
- if (attempt < retries) {
1827
+ // A run someone stopped (Ctrl-C, a cancelled CI job) is not a transient failure: a retry would start the agent again.
1828
+ const stopped = typeof error.stoppedBy === 'string';
1829
+ if (attempt < retries && !stopped) {
1817
1830
  console.error(`tea-test-review: ${error.message}`);
1818
1831
  const retryNotice = `attempt ${attempt + 1} of ${retries + 1} failed (exit 3); retrying.`;
1819
1832
  console.error(`tea-test-review: ${retryNotice}`);
@@ -1824,7 +1837,7 @@ async function runReview(session) {
1824
1837
  }
1825
1838
  continue;
1826
1839
  }
1827
- fail(EXIT.AGENT_OR_PARSE_ERROR, error.message);
1840
+ fail(EXIT.AGENT_OR_PARSE_ERROR, stopped ? `${error.message} Not retried: the run was stopped.` : error.message);
1828
1841
  }
1829
1842
  if (error.code === 'ISOLATION_ERROR' || error.code === 'AGENT_NOT_FOUND') {
1830
1843
  fail(EXIT.ENV_ERROR, error.message);
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.4.0",
4
+ "version": "4.4.2",
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.4.0"
5
+ version = "4.4.2"
6
6
  update_source = "github:bmad-code-org/bmad-method-test-architecture-enterprise/skills"
7
7
  skills = [
8
8
  "bmad-tea",