mandrel 2.93.0 → 2.95.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.
Files changed (130) hide show
  1. package/.agents/docs/configuration.md +8 -3
  2. package/.agents/runtime-deps.json +6 -6
  3. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  4. package/.agents/schemas/story-deliver-terminal.schema.json +1 -0
  5. package/.agents/scripts/agents-bootstrap-github.js +1 -1
  6. package/.agents/scripts/board-backfill.js +1 -1
  7. package/.agents/scripts/boot-sweep.js +1 -1
  8. package/.agents/scripts/check-arch-cycles.js +69 -41
  9. package/.agents/scripts/check-doc-links.js +5 -7
  10. package/.agents/scripts/check-gherkin-corpus.js +2 -11
  11. package/.agents/scripts/clean-temp.js +1 -1
  12. package/.agents/scripts/cleanup-repo-test-temp.js +1 -1
  13. package/.agents/scripts/diagnose-friction.js +1 -1
  14. package/.agents/scripts/generate-lens-checklists.js +4 -4
  15. package/.agents/scripts/generate-skills-index.js +3 -2
  16. package/.agents/scripts/generate-workflows-doc.js +2 -1
  17. package/.agents/scripts/lib/audit-baselines/read.js +2 -1
  18. package/.agents/scripts/lib/audit-exceptions/adapters/tool-config.js +13 -3
  19. package/.agents/scripts/lib/audit-exceptions/globs.js +12 -1
  20. package/.agents/scripts/lib/audit-exceptions/probe.js +24 -2
  21. package/.agents/scripts/lib/audit-exceptions/read.js +2 -2
  22. package/.agents/scripts/lib/audit-to-stories/group-findings.js +77 -67
  23. package/.agents/scripts/lib/baselines/components.js +21 -19
  24. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -8
  25. package/.agents/scripts/lib/baselines/kinds/maintainability.js +2 -3
  26. package/.agents/scripts/lib/baselines/preview-gates.js +2 -2
  27. package/.agents/scripts/lib/baselines/refresh-service.js +4 -7
  28. package/.agents/scripts/lib/baselines/writer.js +2 -7
  29. package/.agents/scripts/lib/bdd-runner-detect.js +2 -2
  30. package/.agents/scripts/lib/bdd-step-index.js +3 -7
  31. package/.agents/scripts/lib/bootstrap/baseline-merge-driver.js +11 -7
  32. package/.agents/scripts/lib/bootstrap/install-ledger.js +19 -4
  33. package/.agents/scripts/lib/bootstrap/json-io.js +14 -0
  34. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +20 -44
  35. package/.agents/scripts/lib/bootstrap/quality-bootstrap.js +38 -54
  36. package/.agents/scripts/lib/branch-name-guard.js +2 -3
  37. package/.agents/scripts/lib/claude/agents-projection.js +1 -12
  38. package/.agents/scripts/lib/codex/agents-projection.js +2 -5
  39. package/.agents/scripts/lib/codex/skills-projection.js +4 -12
  40. package/.agents/scripts/lib/config/defaults.js +2 -1
  41. package/.agents/scripts/lib/config/qa.js +4 -5
  42. package/.agents/scripts/lib/config-schema.js +1 -8
  43. package/.agents/scripts/lib/config-settings-schema.js +0 -3
  44. package/.agents/scripts/lib/coverage-baseline.js +2 -3
  45. package/.agents/scripts/lib/coverage-utils.js +2 -1
  46. package/.agents/scripts/lib/cpu-pool.js +0 -1
  47. package/.agents/scripts/lib/cyclomatic-scope.js +2 -1
  48. package/.agents/scripts/lib/doc-tiers.js +2 -1
  49. package/.agents/scripts/lib/duplicate-search.js +52 -18
  50. package/.agents/scripts/lib/feedback-loop/prior-feedback-fetcher.js +47 -20
  51. package/.agents/scripts/lib/gh-exec.js +115 -25
  52. package/.agents/scripts/lib/gh-pr-rest.js +371 -0
  53. package/.agents/scripts/lib/git/sync-from-base.js +1 -1
  54. package/.agents/scripts/lib/import-graph.js +13 -28
  55. package/.agents/scripts/lib/json-utils.js +11 -0
  56. package/.agents/scripts/lib/label-constants.js +7 -1
  57. package/.agents/scripts/lib/maintainability-utils.js +14 -22
  58. package/.agents/scripts/lib/observability/runtime-friction.js +37 -1
  59. package/.agents/scripts/lib/orchestration/board-graphql-latch.js +75 -0
  60. package/.agents/scripts/lib/orchestration/check-baselines/phases/parse-args.js +25 -1
  61. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +82 -41
  62. package/.agents/scripts/lib/orchestration/code-review.js +1 -6
  63. package/.agents/scripts/lib/orchestration/column-sync.js +23 -21
  64. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  65. package/.agents/scripts/lib/orchestration/git-cleanup/phases/fast-forward.js +7 -14
  66. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +2 -21
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +11 -20
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/phase-drivers.js +65 -86
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/prompts.js +2 -2
  70. package/.agents/scripts/lib/orchestration/git-cleanup/phases/stashes.js +15 -6
  71. package/.agents/scripts/lib/orchestration/lifecycle/emit-merge-unlanded.js +5 -2
  72. package/.agents/scripts/lib/orchestration/merge-block-class.js +48 -47
  73. package/.agents/scripts/lib/orchestration/merge-queue.js +49 -4
  74. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +20 -1
  75. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +2 -2
  76. package/.agents/scripts/lib/orchestration/required-checks.js +72 -12
  77. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +2 -3
  78. package/.agents/scripts/lib/orchestration/review-providers/parse-findings.js +4 -2
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +132 -58
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +92 -9
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/graphql-preflight.js +41 -18
  82. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -2
  83. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +3 -3
  84. package/.agents/scripts/lib/orchestration/story-handoff.js +18 -5
  85. package/.agents/scripts/lib/orchestration/ticketing/transition.js +18 -22
  86. package/.agents/scripts/lib/runtime-deps/dep-resolution.js +19 -5
  87. package/.agents/scripts/lib/runtime-deps/scan-imports.js +4 -10
  88. package/.agents/scripts/lib/skills/parse-skill.js +2 -2
  89. package/.agents/scripts/lib/skills/walk-skill-files.js +7 -23
  90. package/.agents/scripts/lib/story-body/story-body.js +4 -14
  91. package/.agents/scripts/lib/util/atomic-write.js +14 -3
  92. package/.agents/scripts/lib/util/regex.js +4 -0
  93. package/.agents/scripts/notify.js +1 -1
  94. package/.agents/scripts/plan-context.js +1 -1
  95. package/.agents/scripts/plan-critics.js +3 -11
  96. package/.agents/scripts/providers/github/auth.js +0 -4
  97. package/.agents/scripts/providers/github/board-add.js +3 -3
  98. package/.agents/scripts/providers/github/compose.js +2 -0
  99. package/.agents/scripts/providers/github/errors.js +41 -0
  100. package/.agents/scripts/providers/github/project-board.js +0 -1
  101. package/.agents/scripts/providers/github/sub-issues-rest.js +55 -0
  102. package/.agents/scripts/providers/github/sub-issues.js +9 -1
  103. package/.agents/scripts/providers/github/tickets.js +0 -2
  104. package/.agents/scripts/resync-status-column.js +1 -1
  105. package/.agents/scripts/run-tests.js +1 -1
  106. package/.agents/scripts/single-story-confirm-merge.js +2 -0
  107. package/.agents/scripts/test-wrapper.js +1 -1
  108. package/.agents/scripts/update-ticket-state.js +4 -3
  109. package/.agents/scripts/validate-skills.js +2 -1
  110. package/.agents/skills/core/gates-and-baselines/reference.md +1 -0
  111. package/.agents/workflows/audit-baselines.md +21 -9
  112. package/.agents/workflows/clean-git.md +1 -1
  113. package/.agents/workflows/helpers/audit-lens-core.md +1 -1
  114. package/.agents/workflows/helpers/code-quality-guardrails.md +3 -3
  115. package/README.md +1 -1
  116. package/docs/CHANGELOG.md +46 -0
  117. package/lib/cli/claude-code-version.js +13 -7
  118. package/lib/cli/doctor-checks/llm-review.js +12 -5
  119. package/lib/cli/doctor-checks/merge-driver.js +10 -6
  120. package/lib/cli/doctor-checks/project-access.js +21 -8
  121. package/lib/cli/doctor-checks/read-json.js +2 -15
  122. package/lib/cli/doctor-checks/spawn.js +29 -9
  123. package/lib/cli/doctor-checks/test-credit-path.js +2 -1
  124. package/lib/cli/doctor-checks/toolchain.js +16 -12
  125. package/lib/cli/doctor.js +31 -8
  126. package/lib/cli/registry.js +7 -10
  127. package/lib/cli/sync.js +46 -10
  128. package/lib/cli/uninstall.js +259 -175
  129. package/lib/cli/update.js +3 -3
  130. package/package.json +23 -20
@@ -22,7 +22,8 @@
22
22
  */
23
23
 
24
24
  import { getCiDelivery } from '../../../config/ci.js';
25
- import { createGh } from '../../../gh-exec.js';
25
+ import { createGh, prTransportOf } from '../../../gh-exec.js';
26
+ import { REST_MERGE_ON_GREEN } from '../../../gh-pr-rest.js';
26
27
  import {
27
28
  confirmStoryMerged as defaultConfirmStoryMerged,
28
29
  readPrMergeState as defaultReadPrMergeState,
@@ -56,7 +57,11 @@ import {
56
57
  readRunSummary,
57
58
  resolveAdvisoryGateVerdict,
58
59
  } from '../../merge-poll.js';
59
- import { readMergeQueueState } from '../../merge-queue.js';
60
+ import {
61
+ MERGE_QUEUE_REST_BLOCK_CLASS,
62
+ MERGE_QUEUE_REST_REMEDY,
63
+ readMergeQueueState,
64
+ } from '../../merge-queue.js';
60
65
  import { readProbeRunEvidence } from '../../required-checks.js';
61
66
  import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
62
67
  import {
@@ -64,7 +69,7 @@ import {
64
69
  STATE_LABELS,
65
70
  transitionTicketState,
66
71
  } from '../../ticketing.js';
67
- import { disarmAutoMerge } from './auto-merge.js';
72
+ import { disarmAutoMerge, mergeOnGreen } from './auto-merge.js';
68
73
  import {
69
74
  maybeRearmPr,
70
75
  mergeWaitRecoverySeams,
@@ -1283,6 +1288,8 @@ async function recoverOpenPr(ctx, decision, probe) {
1283
1288
  if (advisory) {
1284
1289
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1285
1290
  }
1291
+ const landed = await maybeMergeOnGreen(ctx, decision, probe);
1292
+ if (landed) return { state: decision.state, outcome: landed };
1286
1293
  await maybeRearmPr(ctx, probe);
1287
1294
  const updated = await maybeUpdateBehindPr({
1288
1295
  probe,
@@ -1299,6 +1306,67 @@ async function recoverOpenPr(ctx, decision, probe) {
1299
1306
  return { state, outcome: null };
1300
1307
  }
1301
1308
 
1309
+ /**
1310
+ * Close owns the merge when the CCR route would not arm it: the arm said so,
1311
+ * or (a `--wait` resume, which has no arm outcome) the PR transport is REST
1312
+ * and GitHub holds no auto-merge request. Only a PR close itself armed.
1313
+ *
1314
+ * @returns {Promise<boolean>}
1315
+ */
1316
+ async function closeOwnsMerge(ctx, probe) {
1317
+ if (ctx.closeArmed !== true) return false;
1318
+ if (ctx.autoMergeReason === REST_MERGE_ON_GREEN) return true;
1319
+ return (
1320
+ probe.autoMergeArmed !== true &&
1321
+ (await prTransportOf(ctx.waitGh)) === 'rest'
1322
+ );
1323
+ }
1324
+
1325
+ function isCleanAndGreen(probe) {
1326
+ return (
1327
+ probe?.state === 'OPEN' &&
1328
+ !probe?.mergedAt &&
1329
+ probe?.inMergeQueue !== true &&
1330
+ probe?.mergeStateStatus === 'CLEAN' &&
1331
+ probe?.checksStatus === 'success' &&
1332
+ Boolean(probe?.headSha)
1333
+ );
1334
+ }
1335
+
1336
+ /**
1337
+ * Merge-on-green: squash-merge a CLEAN, green PR pinned to the head SHA this
1338
+ * poll saw, and settle it as merged. A refused merge (the head moved, GitHub
1339
+ * still recomputing) is not a terminal; the next poll re-reads.
1340
+ *
1341
+ * @returns {Promise<object|null>} the landed outcome, or null to keep polling.
1342
+ */
1343
+ async function maybeMergeOnGreen(ctx, decision, probe) {
1344
+ if (!isCleanAndGreen(probe) || !(await closeOwnsMerge(ctx, probe))) {
1345
+ return null;
1346
+ }
1347
+ const merge = await ctx.mergeOnGreenFn({
1348
+ prNumber: ctx.prNumber,
1349
+ headSha: probe.headSha,
1350
+ gh: ctx.waitGh,
1351
+ });
1352
+ if (!merge.merged) {
1353
+ ctx.progress?.(
1354
+ 'CONFIRM',
1355
+ `⚠️ PR #${ctx.prNumber} is CLEAN and green but the merge was refused (${merge.detail}) — still waiting.`,
1356
+ );
1357
+ return null;
1358
+ }
1359
+ ctx.progress?.(
1360
+ 'CONFIRM',
1361
+ `🔀 PR #${ctx.prNumber} was CLEAN and green — squash-merged at ${probe.headSha.slice(0, 7)}.`,
1362
+ );
1363
+ return settleMerged(ctx, decision, {
1364
+ ...probe,
1365
+ state: 'MERGED',
1366
+ mergedAt: new Date(ctx.nowMsFn()).toISOString(),
1367
+ });
1368
+ }
1369
+
1302
1370
  /** The provisional verdict's own ending: budget block, `pending`, or none. */
1303
1371
  async function settleVerdict(ctx, decision, probe) {
1304
1372
  if (decision.verdict === 'budget-exhausted') {
@@ -1379,15 +1447,27 @@ function blockNeverArmed({
1379
1447
  progress,
1380
1448
  classifyMergeBlockFn,
1381
1449
  emitMergeUnlandedFn,
1382
- ...(autoMergeReason === 'advisory-gate-red'
1383
- ? {
1384
- blockClassOverride: advisoryGate?.blockClass ?? 'advisory-gate-red',
1385
- reasonOverride: advisoryGate?.reason,
1386
- }
1387
- : {}),
1450
+ ...neverArmedOverride(autoMergeReason, advisoryGate),
1388
1451
  });
1389
1452
  }
1390
1453
 
1454
+ /** An arm refusal that names its own class rather than a generic `arm-failure`. */
1455
+ function neverArmedOverride(autoMergeReason, advisoryGate) {
1456
+ if (autoMergeReason === 'advisory-gate-red') {
1457
+ return {
1458
+ blockClassOverride: advisoryGate?.blockClass ?? 'advisory-gate-red',
1459
+ reasonOverride: advisoryGate?.reason,
1460
+ };
1461
+ }
1462
+ if (autoMergeReason === MERGE_QUEUE_REST_BLOCK_CLASS) {
1463
+ return {
1464
+ blockClassOverride: MERGE_QUEUE_REST_BLOCK_CLASS,
1465
+ reasonOverride: MERGE_QUEUE_REST_REMEDY,
1466
+ };
1467
+ }
1468
+ return {};
1469
+ }
1470
+
1391
1471
  /**
1392
1472
  * Poll an armed Story PR to merge confirmation, a resumable `pending`
1393
1473
  * expiry, or a classified `agent::blocked` terminal.
@@ -1417,6 +1497,7 @@ function blockNeverArmed({
1417
1497
  * @param {Function} [args.runPostLandTailFn]
1418
1498
  * @param {Function} [args.disarmAutoMergeFn]
1419
1499
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1500
+ * @param {Function} [args.mergeOnGreenFn] The merge-on-green squash-merge (`auto-merge.js#mergeOnGreen`).
1420
1501
  * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1421
1502
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1422
1503
  * @param {() => number} [args.nowMsFn]
@@ -1436,6 +1517,7 @@ export async function runConfirmMergePhase({
1436
1517
  runPostLandTailFn = defaultRunPostLandTail,
1437
1518
  disarmAutoMergeFn = disarmAutoMerge,
1438
1519
  recordRequiredRedFn = defaultRecordRequiredRed,
1520
+ mergeOnGreenFn = mergeOnGreen,
1439
1521
  sleepFn = defaultSleep,
1440
1522
  nowMsFn = Date.now,
1441
1523
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
@@ -1483,6 +1565,7 @@ export async function runConfirmMergePhase({
1483
1565
  runPostLandTailFn,
1484
1566
  disarmAutoMergeFn,
1485
1567
  recordRequiredRedFn,
1568
+ mergeOnGreenFn,
1486
1569
  nowMsFn,
1487
1570
  ghTimeoutMs,
1488
1571
  waitGh: args.injectedGh ?? defaultGh,
@@ -1,13 +1,15 @@
1
1
  /**
2
- * phases/graphql-preflight.js — refuse the close during `init` when GitHub
3
- * GraphQL (which all of `gh pr` needs) is unreachable, before any gate runs
4
- * or anything is pushed. It must never fail a healthy close: ambiguous or
5
- * throwing probes are fail-open.
2
+ * phases/graphql-preflight.js — pick the close's PR transport during `init`,
3
+ * before any gate runs or anything is pushed. GraphQL unreachable (the proxy
4
+ * 403) seeds the `gh-exec` latch so every `gh pr` call goes over repo-scoped
5
+ * REST; only an auth fault, which REST would hit too, refuses the close. It
6
+ * must never fail a healthy close: ambiguous or throwing probes are fail-open.
6
7
  */
7
8
 
8
9
  import {
9
10
  describeGraphqlPreflight,
10
11
  probeGraphqlAvailability,
12
+ setGraphqlAvailability,
11
13
  } from '../../../gh-exec.js';
12
14
  import { Logger } from '../../../Logger.js';
13
15
  import {
@@ -31,8 +33,8 @@ async function announcePreflightBlock({ provider, storyId, reason, progress }) {
31
33
  reason,
32
34
  '',
33
35
  'Nothing was validated, committed, or pushed — the preflight runs before the',
34
- 'gate chain, so re-running close from a session that can reach GraphQL starts',
35
- 'from exactly where this Story stands now:',
36
+ 'gate chain, so re-running close once `gh` is authenticated starts from',
37
+ 'exactly where this Story stands now:',
36
38
  '',
37
39
  '```bash',
38
40
  `node .agents/scripts/single-story-close.js --story ${storyId}`,
@@ -56,6 +58,33 @@ async function announcePreflightBlock({ provider, storyId, reason, progress }) {
56
58
  }
57
59
  }
58
60
 
61
+ /** The probe's verdict, or `null` when the (injected) probe threw. */
62
+ async function readVerdict({ probe, ghFacade, progress }) {
63
+ try {
64
+ return await probe(ghFacade ? { ghFacade } : undefined);
65
+ } catch (err) {
66
+ progress(
67
+ 'PREFLIGHT',
68
+ `⚠️ GraphQL preflight could not run (close continues): ${err?.message ?? err}`,
69
+ );
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /** The line a proceeding verdict prints, keyed by its transport. */
75
+ const PROCEED_LINES = Object.freeze({
76
+ graphql: (verdict) => `✅ GitHub GraphQL reachable (${verdict?.reason}).`,
77
+ rest: () =>
78
+ '↪ GitHub GraphQL is unavailable in this session (HTTP 403) — the pull-request ' +
79
+ 'surface runs over repo-scoped REST for this close.',
80
+ });
81
+
82
+ /** @returns {'graphql'|'rest'|null} the transport to proceed on, or null to refuse. */
83
+ function proceedingTransport(verdict) {
84
+ if (verdict?.available !== false) return 'graphql';
85
+ return verdict.verdict === 'unavailable' ? 'rest' : null;
86
+ }
87
+
59
88
  /**
60
89
  * A throwing (injected) probe is treated as available.
61
90
  *
@@ -75,18 +104,12 @@ export async function runGraphqlPreflight({
75
104
  ghFacade,
76
105
  probe = probeGraphqlAvailability,
77
106
  }) {
78
- let verdict;
79
- try {
80
- verdict = await probe(ghFacade ? { ghFacade } : undefined);
81
- } catch (err) {
82
- progress(
83
- 'PREFLIGHT',
84
- `⚠️ GraphQL preflight could not run (close continues): ${err?.message ?? err}`,
85
- );
86
- return null;
87
- }
88
- if (verdict?.available !== false) {
89
- progress('PREFLIGHT', `✅ GitHub GraphQL reachable (${verdict?.reason}).`);
107
+ const verdict = await readVerdict({ probe, ghFacade, progress });
108
+ if (verdict === null) return null;
109
+ setGraphqlAvailability(verdict ?? null);
110
+ const transport = proceedingTransport(verdict);
111
+ if (transport) {
112
+ progress('PREFLIGHT', PROCEED_LINES[transport](verdict));
90
113
  return null;
91
114
  }
92
115
  const reason = describeGraphqlPreflight(verdict);
@@ -15,7 +15,6 @@
15
15
  */
16
16
 
17
17
  import path from 'node:path';
18
-
19
18
  import {
20
19
  compare as compareMaintainability,
21
20
  projectRow as projectMaintainabilityRow,
@@ -32,6 +31,7 @@ import { getQuality } from '../../config-resolver.js';
32
31
  import { gitSync as defaultGitSync } from '../../git-utils.js';
33
32
  import { Logger as DefaultLogger } from '../../Logger.js';
34
33
  import { isScorableSourceFile } from '../../source-extensions.js';
34
+ import { toPosix } from '../../util/paths.js';
35
35
  import {
36
36
  currentBranch,
37
37
  listChangedFiles,
@@ -325,7 +325,7 @@ export async function runBaselineUpwardWriteback({
325
325
  }).filter(isScorableSourceFile);
326
326
 
327
327
  const writePath = resolveWritePath({ cwd: workTree });
328
- const relPath = path.relative(workTree, writePath).split(path.sep).join('/');
328
+ const relPath = toPosix(path.relative(workTree, writePath));
329
329
 
330
330
  const blocked = precheck({
331
331
  gate,
@@ -11,7 +11,6 @@
11
11
 
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
-
15
14
  import {
16
15
  diffRows as defaultDiffDeadExportRows,
17
16
  loadBaseline as loadJsonBaseline,
@@ -31,6 +30,7 @@ import {
31
30
  import { resolveDeadExportsMode } from '../../dead-exports-mode.js';
32
31
  import { gitSync as defaultGitSync } from '../../git-utils.js';
33
32
  import { Logger as DefaultLogger } from '../../Logger.js';
33
+ import { toPosix } from '../../util/paths.js';
34
34
  import { currentBranch, listDirtyPaths } from './format-autofix.js';
35
35
 
36
36
  const TAG = '[ratchet-shrink]';
@@ -81,7 +81,7 @@ function planDeadExportShrink({
81
81
  diffRows = defaultDiffDeadExportRows,
82
82
  }) {
83
83
  const { baseline } = resolveDeadExportsMode(production);
84
- const relPath = baseline.split(path.sep).join('/');
84
+ const relPath = toPosix(baseline);
85
85
  const committed = loadJsonBaseline(path.join(workTree, baseline));
86
86
  if (!Array.isArray(committed?.rows))
87
87
  return { relPath, reason: 'no-baseline' };
@@ -291,7 +291,7 @@ export function runRatchetShrinkWriteback({
291
291
  resolveDeadExportsMode(false).baseline,
292
292
  resolveDeadExportsMode(true).baseline,
293
293
  DEFAULT_CYCLOMATIC_BASELINE,
294
- ].map((p) => p.split(path.sep).join('/'));
294
+ ].map(toPosix);
295
295
  try {
296
296
  if (currentBranch(workTree, git) !== storyBranch) {
297
297
  return skip(logger, 'wrong-branch');
@@ -45,6 +45,7 @@ import { getStoryBranch, gitSpawn } from '../git-utils.js';
45
45
  import { readPackageScripts } from '../npm-scripts.js';
46
46
  import { TIMEOUT_EXIT_CODE } from '../process-group.js';
47
47
  import { describeBlocking } from '../suite-admission.js';
48
+ import { writeFileAtomic } from '../util/atomic-write.js';
48
49
  import { defaultSleep } from '../util/sleep.js';
49
50
  import { runStreamed } from './evidence-stream.js';
50
51
  import { probeHeldReviewDiff } from './review-deposit.js';
@@ -817,15 +818,28 @@ function precheck(ctx) {
817
818
  }
818
819
 
819
820
  /**
821
+ * `{}` when absent or corrupt; a corrupt file is reported.
822
+ *
820
823
  * @param {string} statePath
824
+ * @param {(tag: string, msg: string) => void} progress
821
825
  * @returns {{ preflightHead?: string, creditHead?: string, seatHead?: string }}
822
826
  */
823
- function readState(statePath) {
827
+ function readState(statePath, progress) {
828
+ let raw;
824
829
  try {
825
- return JSON.parse(fs.readFileSync(statePath, 'utf8'))?.state ?? {};
830
+ raw = fs.readFileSync(statePath, 'utf8');
826
831
  } catch {
827
832
  return {};
828
833
  }
834
+ try {
835
+ return JSON.parse(raw)?.state ?? {};
836
+ } catch (err) {
837
+ progress(
838
+ 'STATE',
839
+ `⚠️ ignoring corrupt ${statePath} (${err.message}) — every step re-runs`,
840
+ );
841
+ return {};
842
+ }
829
843
  }
830
844
 
831
845
  /**
@@ -945,7 +959,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
945
959
  sleep,
946
960
  lockPollMs,
947
961
  env,
948
- state: readState(statePath),
962
+ state: readState(statePath, progress),
949
963
  review: null,
950
964
  reviewPath: storyReviewDepositPath(storyId, config),
951
965
  depositor: selectCreditedDepositor({
@@ -1008,10 +1022,9 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1008
1022
  }
1009
1023
  : {}),
1010
1024
  };
1011
- fs.writeFileSync(
1025
+ writeFileAtomic(
1012
1026
  statePath,
1013
1027
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
1014
- 'utf8',
1015
1028
  );
1016
1029
  return { envelope, exitCode: EXIT_CODES[status] };
1017
1030
  }
@@ -9,12 +9,14 @@
9
9
 
10
10
  import { extractEpicIdFromBody } from '../../dependency-parser.js';
11
11
  import { Logger } from '../../Logger.js';
12
+ import { AGENT_LABELS } from '../../label-constants.js';
12
13
  import {
13
14
  eventSeverity,
14
15
  renderTransitionMessage,
15
16
  } from '../../notifications/notifier.js';
16
17
  import {
17
18
  emitBlockRecoveredFriction,
19
+ emitInvalidTransitionFriction,
18
20
  emitRuntimeFriction,
19
21
  RUNTIME_FRICTION_CATEGORIES,
20
22
  } from '../../observability/runtime-friction.js';
@@ -76,26 +78,22 @@ function validateTransitionInputs(newState) {
76
78
  */
77
79
  const BLOCK_RECOVERY_TARGETS = [STATE_LABELS.EXECUTING, STATE_LABELS.READY];
78
80
 
81
+ /** The observer also reads a `review-spec` origin; a lifecycle state wins. */
82
+ const OBSERVED_STATES = Object.values(AGENT_LABELS);
83
+
79
84
  /**
80
- * Resolve the pre-transition snapshot, honoring `opts.ticketSnapshot`. Loaded
81
- * only when `notify` needs `fromState` or `needFromState` is set (recovery
82
- * detection must read the prior label before `updateTicket` overwrites it).
83
- * Returns `null` on transient failure.
85
+ * Resolve the pre-transition snapshot, honoring `opts.ticketSnapshot`; the
86
+ * provider's label merge reuses it instead of its own read. Returns `null`
87
+ * on transient failure.
84
88
  *
85
89
  * @param {object} provider
86
- * @param {{ notify?: Function, ticketSnapshot?: object|null }} opts
90
+ * @param {{ ticketSnapshot?: object|null }} opts
87
91
  * @param {number} ticketId
88
- * @param {boolean} [needFromState]
89
92
  * @returns {Promise<object|null>}
90
93
  */
91
- async function loadTicketSnapshot(provider, opts, ticketId, needFromState) {
94
+ async function loadTicketSnapshot(provider, opts, ticketId) {
92
95
  if (opts.ticketSnapshot) return opts.ticketSnapshot;
93
- if (
94
- (!opts.notify && !needFromState) ||
95
- typeof provider.getTicket !== 'function'
96
- ) {
97
- return null;
98
- }
96
+ if (typeof provider.getTicket !== 'function') return null;
99
97
  try {
100
98
  return await provider.getTicket(ticketId);
101
99
  } catch (err) {
@@ -111,7 +109,7 @@ const BOARD_SYNC_REMEDIES = Object.freeze({
111
109
  'not-on-project': 'node .agents/scripts/board-backfill.js',
112
110
  });
113
111
 
114
- const SILENT_BOARD_SKIPS = new Set(['no-project']);
112
+ const SILENT_BOARD_SKIPS = new Set(['no-project', 'graphql-blocked']);
115
113
 
116
114
  /** Warns on every flip, never latched: agents read the flip's own output. */
117
115
  function reportBoardSync(ticketId, newState, boardSync) {
@@ -285,14 +283,11 @@ export async function transitionTicketState(
285
283
 
286
284
  const toRemove = ALL_STATES.filter((state) => state !== newState);
287
285
 
288
- const ticketSnapshot = await loadTicketSnapshot(
289
- provider,
290
- opts,
291
- ticketId,
292
- BLOCK_RECOVERY_TARGETS.includes(newState),
293
- );
294
- const fromState =
295
- ticketSnapshot?.labels?.find((l) => ALL_STATES.includes(l)) ?? null;
286
+ const ticketSnapshot = await loadTicketSnapshot(provider, opts, ticketId);
287
+ const priorLabels = ticketSnapshot?.labels ?? [];
288
+ const fromState = priorLabels.find((l) => ALL_STATES.includes(l)) ?? null;
289
+ const observedFrom =
290
+ fromState ?? priorLabels.find((l) => OBSERVED_STATES.includes(l)) ?? null;
296
291
 
297
292
  const isDone = newState === STATE_LABELS.DONE;
298
293
 
@@ -307,6 +302,7 @@ export async function transitionTicketState(
307
302
  _ticketSnapshot: ticketSnapshot,
308
303
  });
309
304
 
305
+ await emitInvalidTransitionFriction(ticketId, observedFrom, newState, opts);
310
306
  await emitBlockedFriction(ticketId, fromState, newState, opts);
311
307
 
312
308
  const boardSync = await syncProjectStatusColumn(
@@ -2,8 +2,8 @@
2
2
  * runtime-deps/dep-resolution — is a declared runtime dependency present and
3
3
  * the right major. Deps resolve from the consumer's `node_modules`, so a
4
4
  * declared range is only enforced by comparing it to what resolved.
5
- * Major-only and semver-free on purpose: every range is `^`, and a semver
6
- * dependency would grow the very closure this guards.
5
+ * Major-only and semver-free on purpose: every range is `^` or a `||` union
6
+ * of them, and a semver dependency would grow the very closure this guards.
7
7
  *
8
8
  * @module lib/runtime-deps/dep-resolution
9
9
  */
@@ -21,6 +21,20 @@ function majorOf(spec) {
21
21
  return match ? Number(match[1]) : null;
22
22
  }
23
23
 
24
+ /**
25
+ * The majors a range admits, one per `||` alternative — or none (not
26
+ * range-checked) when any alternative is unreadable, the same conservative
27
+ * miss as a single unreadable range.
28
+ *
29
+ * @param {string|null|undefined} range
30
+ * @returns {number[]}
31
+ */
32
+ function wantedMajors(range) {
33
+ if (typeof range !== 'string') return [];
34
+ const majors = range.split('||').map(majorOf);
35
+ return majors.includes(null) ? [] : majors;
36
+ }
37
+
24
38
  /**
25
39
  * `false` when either side is unreadable. `0.x` minors are not separated —
26
40
  * accepted, since the range this enforces is `@babel/parser`'s `^7`.
@@ -30,11 +44,11 @@ function majorOf(spec) {
30
44
  * @returns {boolean}
31
45
  */
32
46
  function majorMismatch(range, resolved) {
33
- const want = majorOf(range);
34
- if (want === null) return false;
47
+ const wanted = wantedMajors(range);
48
+ if (wanted.length === 0) return false;
35
49
  const got = majorOf(resolved);
36
50
  if (got === null) return false;
37
- return want !== got;
51
+ return !wanted.includes(got);
38
52
  }
39
53
 
40
54
  /**
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import { builtinModules } from 'node:module';
11
11
  import path from 'node:path';
12
12
  import { stripJsComments } from '../source-text/strip-js-comments.js';
13
+ import { walkFiles } from '../util/paths.js';
13
14
 
14
15
  const BUILTIN_MODULES = new Set([
15
16
  ...builtinModules,
@@ -117,16 +118,9 @@ export function extractThirdPartyImports(source) {
117
118
  * @returns {string[]}
118
119
  */
119
120
  export function listJsFiles(dir) {
120
- const out = [];
121
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
122
- const full = path.join(dir, entry.name);
123
- if (entry.isDirectory()) {
124
- out.push(...listJsFiles(full));
125
- } else if (entry.isFile() && entry.name.endsWith('.js')) {
126
- out.push(full);
127
- }
128
- }
129
- return out;
121
+ return walkFiles(dir, {
122
+ filter: (abs, dirent) => dirent.isFile() && abs.endsWith('.js'),
123
+ });
130
124
  }
131
125
 
132
126
  /**
@@ -6,7 +6,7 @@
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import yaml from 'js-yaml';
9
+ import { load } from 'js-yaml';
10
10
  import { toPosix } from '../util/paths.js';
11
11
 
12
12
  const FRONTMATTER_DELIMITER = '---';
@@ -116,7 +116,7 @@ export function parseSkill(absolutePath, options = {}) {
116
116
 
117
117
  let frontmatter;
118
118
  try {
119
- frontmatter = yaml.load(yamlText);
119
+ frontmatter = load(yamlText);
120
120
  } catch (err) {
121
121
  throw new Error(
122
122
  `SKILL.md frontmatter is not valid YAML at ${absolutePath}: ${err.message}`,
@@ -8,6 +8,7 @@
8
8
 
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import { toPosix, walkFiles } from '../util/paths.js';
11
12
 
12
13
  const TIERS = Object.freeze(['core', 'stack']);
13
14
 
@@ -35,27 +36,10 @@ export const SKILL_ID_RE = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)+$/;
35
36
  * @returns {string[]} absolute paths
36
37
  */
37
38
  function walkSkillFiles(rootDir) {
38
- const out = [];
39
- if (!fs.existsSync(rootDir)) return out;
40
- const stack = [rootDir];
41
- while (stack.length > 0) {
42
- const dir = stack.pop();
43
- let entries;
44
- try {
45
- entries = fs.readdirSync(dir, { withFileTypes: true });
46
- } catch {
47
- continue;
48
- }
49
- for (const entry of entries) {
50
- const full = path.join(dir, entry.name);
51
- if (entry.isDirectory()) {
52
- stack.push(full);
53
- } else if (entry.isFile() && entry.name === 'SKILL.md') {
54
- out.push(full);
55
- }
56
- }
57
- }
58
- return out;
39
+ return walkFiles(rootDir, {
40
+ filter: (_abs, dirent) => dirent.isFile() && dirent.name === 'SKILL.md',
41
+ onError: () => {},
42
+ });
59
43
  }
60
44
 
61
45
  /**
@@ -65,8 +49,8 @@ function walkSkillFiles(rootDir) {
65
49
  */
66
50
  function sortByRepoRelative(files, repoRoot) {
67
51
  return [...files].sort((a, b) => {
68
- const ra = path.relative(repoRoot, a).split(path.sep).join('/');
69
- const rb = path.relative(repoRoot, b).split(path.sep).join('/');
52
+ const ra = toPosix(path.relative(repoRoot, a));
53
+ const rb = toPosix(path.relative(repoRoot, b));
70
54
  return ra < rb ? -1 : ra > rb ? 1 : 0;
71
55
  });
72
56
  }
@@ -8,6 +8,7 @@
8
8
  * @module story-body
9
9
  */
10
10
 
11
+ import { isObject } from '../json-utils.js';
11
12
  import { FILE_ASSUMPTION_VALUES } from '../orchestration/file-assumption-enum.js';
12
13
  import {
13
14
  isProseBullet,
@@ -258,17 +259,6 @@ function pathEntryFixIt(raw) {
258
259
  return ` — Suggested fix: ${suggestion} (adjust the assumption to creates|deletes if this is a new file or a removal).`;
259
260
  }
260
261
 
261
- /**
262
- * Delegates to footer-block.js so the body and dispatch-edge parsers cannot
263
- * disagree about what declares an edge.
264
- *
265
- * @param {string} footerBlock
266
- * @returns {string[]}
267
- */
268
- function extractBlockedBy(footerBlock) {
269
- return parseFooterBlockedByRefs(footerBlock);
270
- }
271
-
272
262
  /**
273
263
  * Split markdown into named sections plus the footer block; content after
274
264
  * the footer separator is not parsed as sections.
@@ -391,7 +381,7 @@ function parseUnstructuredBody(input, preamble, footer) {
391
381
  verify: [],
392
382
  references: [],
393
383
  non_goals: [],
394
- depends_on: extractBlockedBy(footer),
384
+ depends_on: parseFooterBlockedByRefs(footer),
395
385
  };
396
386
  return {
397
387
  body,
@@ -492,7 +482,7 @@ export function parse(input) {
492
482
  });
493
483
  }
494
484
 
495
- if (typeof input === 'object' && !Array.isArray(input)) {
485
+ if (isObject(input)) {
496
486
  return parseStructuredObject(input);
497
487
  }
498
488
 
@@ -543,7 +533,7 @@ export function parse(input) {
543
533
  warnings,
544
534
  );
545
535
  const non_goals = parseTextListSection(sections.get('non_goals') ?? []);
546
- const dependsOn = extractBlockedBy(footer);
536
+ const dependsOn = parseFooterBlockedByRefs(footer);
547
537
 
548
538
  const body = {
549
539
  goal,