mandrel 2.86.0 → 2.88.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 (165) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Refresh the bundle-size baseline via `refreshBaseline({ kind:
4
+ * 'bundle-size' })`: weigh every `gates['bundle-size'].bundles[]` artifact
5
+ * already on disk. Scope is always full — bundle names are not paths, so no
6
+ * diff can narrow it. Never builds the project.
7
+ */
8
+
9
+ // Must be the first import: fails fast before any third-party import loads.
10
+ import './lib/runtime-deps/ensure-installed.js';
11
+ import path from 'node:path';
12
+ import { refreshBaseline } from './lib/baselines/refresh-service.js';
13
+ import { runAsCli } from './lib/cli-utils.js';
14
+ import { getBaselineEpsilon } from './lib/config/quality.js';
15
+ import { getQuality, resolveConfig } from './lib/config-resolver.js';
16
+ import { Logger } from './lib/Logger.js';
17
+
18
+ const DEFAULT_BASELINE_PATH = 'baselines/bundle-size.json';
19
+
20
+ /** `runAsCli` answers `--help` before `main`, so a usage probe never writes. */
21
+ const USAGE = {
22
+ invocation: 'node .agents/scripts/update-bundle-size-baseline.js',
23
+ summary:
24
+ 'Weigh → write the bundle-size baseline: one row per `delivery.quality.gates.bundle-size.bundles[]` entry, with the raw and gzipped KB of every file its `path` glob matches. Always a full refresh.',
25
+ notes: [
26
+ 'Build the project first — this script never builds, and a declared bundle that matches no file fails the refresh rather than recording 0 KB.',
27
+ ],
28
+ };
29
+
30
+ async function main() {
31
+ const cwd = process.cwd();
32
+ const gate = getQuality(resolveConfig({ cwd })).gates?.['bundle-size'] ?? {};
33
+ const baselinePath = gate.baselinePath ?? DEFAULT_BASELINE_PATH;
34
+ const writePath = path.resolve(cwd, baselinePath);
35
+
36
+ Logger.info('[BundleSize] Updating baseline...');
37
+ const result = await refreshBaseline({
38
+ kind: 'bundle-size',
39
+ cwd,
40
+ fullScope: true,
41
+ writePath,
42
+ epsilon: getBaselineEpsilon('bundle-size'),
43
+ });
44
+ Logger.info(
45
+ `[BundleSize] ✅ Baseline updated: ${result.envelope.rows.length} bundle(s) recorded at ${baselinePath}, wrote=${result.wrote}.`,
46
+ );
47
+ }
48
+
49
+ runAsCli(import.meta.url, main, {
50
+ source: 'bundle-size-baseline',
51
+ usage: USAGE,
52
+ onError: (err) => {
53
+ Logger.error(`[BundleSize] ❌ Fatal error: ${err?.message ?? err}`);
54
+ process.exitCode = 1;
55
+ },
56
+ });
@@ -1,26 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Refresh the coverage baseline from the `coverage-final.json` on disk via
3
+ * Refresh the coverage baseline from the configured `coverage.coveragePath`
4
+ * artifact (Istanbul `coverage-final.json`) on disk via
4
5
  * `refreshBaseline({ kind: 'coverage' })`. Never runs the suite, so the
5
6
  * refresh is idempotent and the output can be inspected first.
6
7
  */
7
8
 
8
- import { createRequire } from 'node:module';
9
- import path from 'node:path';
10
9
  import { resolveUpdaterRefreshScope } from './lib/baselines/coverage-refresh-scope.js';
11
10
  import {
12
- buildCoverageUpdaterScorer,
11
+ buildCoverageRefreshOpts,
12
+ coverageUpdaterTargets,
13
+ loadC8ScopeConfig,
13
14
  resolveCoverageUpdaterScope,
14
15
  } from './lib/baselines/coverage-updater-cli.js';
15
16
  import { refreshBaseline } from './lib/baselines/refresh-service.js';
16
17
  import { runAsCli } from './lib/cli-utils.js';
17
- import { getBaselineEpsilon } from './lib/config/quality.js';
18
- import {
19
- buildScopePredicate,
20
- COVERAGE_BASELINE_PATH,
21
- readCoverageFinal,
22
- scoreCoverageFinal,
23
- } from './lib/coverage-baseline.js';
18
+ import { getQuality, resolveConfig } from './lib/config-resolver.js';
24
19
  import { Logger } from './lib/Logger.js';
25
20
 
26
21
  /** `runAsCli` answers `--help` before `main`, so a usage probe never writes. */
@@ -28,7 +23,7 @@ const USAGE = {
28
23
  invocation:
29
24
  'node .agents/scripts/update-coverage-baseline.js [--full-scope | --diff-scope <ref>]',
30
25
  summary:
31
- 'Score → write the coverage baseline from the coverage-final.json already on disk. With no scope flag the refresh is scoped to the files changed in `origin/main..HEAD`; out-of-scope rows are preserved verbatim.',
26
+ 'Score → write the coverage baseline from the coverage artifact (`delivery.quality.gates.coverage.coveragePath`, Istanbul coverage-final.json) already on disk. With no scope flag the refresh is scoped to the files changed in `origin/main..HEAD`; out-of-scope rows are preserved verbatim.',
32
27
  flags: [
33
28
  [
34
29
  '--full-scope',
@@ -45,49 +40,29 @@ const USAGE = {
45
40
  ],
46
41
  };
47
42
 
48
- /** CommonJS `require`, for the `.c8rc.cjs` scope config below. */
49
- const require = createRequire(import.meta.url);
50
-
51
- /**
52
- * Load the c8 include/exclude scope. Kept in the CLI rather than the extracted
53
- * scorer because it is the one genuinely environment-bound step — a CJS
54
- * `require` of a config file resolved against the working tree — and the
55
- * scorer takes it as a seam so a test never touches the real `.c8rc.cjs`.
56
- */
57
- function loadC8Scope(cwd) {
58
- return require(path.resolve(cwd, '.c8rc.cjs'));
59
- }
60
-
61
43
  function main() {
62
44
  const cwd = process.cwd();
63
45
  const { fullScope, diffScopeRef } = resolveCoverageUpdaterScope(
64
46
  process.argv.slice(2),
65
47
  );
66
- Logger.info('[Coverage] Updating baseline from coverage-final.json...');
67
-
68
- const absBaselinePath = path.resolve(cwd, COVERAGE_BASELINE_PATH);
69
- const refreshOpts = {
70
- kind: 'coverage',
71
- writePath: absBaselinePath,
72
- epsilon: getBaselineEpsilon('coverage'),
73
- scorer: buildCoverageUpdaterScorer(cwd, {
74
- readCoverage: readCoverageFinal,
75
- loadScope: loadC8Scope,
76
- buildScope: buildScopePredicate,
77
- score: scoreCoverageFinal,
78
- }),
79
- };
48
+ const targets = coverageUpdaterTargets(
49
+ getQuality(resolveConfig({ cwd })).coverage,
50
+ cwd,
51
+ );
52
+ Logger.info(`[Coverage] Updating baseline from ${targets.coveragePath}...`);
53
+ const refreshOpts = buildCoverageRefreshOpts(cwd, targets);
80
54
  // No flag and a full artifact -> the service derives the diff via
81
55
  // `origin/main..HEAD` (its default baseRef/headRef).
82
56
  return resolveUpdaterRefreshScope(cwd, {
83
57
  fullScope,
84
58
  diffScopeRef,
85
- loadScope: loadC8Scope,
59
+ loadScope: loadC8ScopeConfig,
60
+ readCoverage: targets.readCoverage,
86
61
  })
87
62
  .then((scope) => refreshBaseline({ ...refreshOpts, ...scope }))
88
63
  .then((result) => {
89
64
  Logger.info(
90
- `[Coverage] ✅ Baseline updated: ${result.envelope.rows.length} file(s) recorded at ${COVERAGE_BASELINE_PATH} (${absBaselinePath}). scope=${result.scope.mode}, wrote=${result.wrote}.`,
65
+ `[Coverage] ✅ Baseline updated: ${result.envelope.rows.length} file(s) recorded at ${targets.baselinePath} (${targets.absBaselinePath}). scope=${result.scope.mode}, wrote=${result.wrote}.`,
91
66
  );
92
67
  });
93
68
  }
@@ -1,7 +1,7 @@
1
1
  // Must be the first import: fails fast before any third-party import loads.
2
2
  import './lib/runtime-deps/ensure-installed.js';
3
3
  import {
4
- buildCrapUpdaterScorer,
4
+ buildCrapRefreshOptions,
5
5
  parseCrapUpdaterArgs,
6
6
  resolveCrapUpdaterOptions,
7
7
  seatCrapBaseline,
@@ -15,10 +15,7 @@ import {
15
15
  resolveConfig,
16
16
  } from './lib/config-resolver.js';
17
17
  import { loadCoverage } from './lib/coverage-utils.js';
18
- import {
19
- resolveEscomplexVersion,
20
- resolveTsTranspilerVersion,
21
- } from './lib/crap-utils.js';
18
+ import { resolveEscomplexVersion } from './lib/crap-utils.js';
22
19
 
23
20
  import { Logger } from './lib/Logger.js';
24
21
 
@@ -58,7 +55,7 @@ const USAGE = {
58
55
  ],
59
56
  ],
60
57
  notes: [
61
- 'Run `npm run test:coverage` first — without a coverage artifact every file is skipped.',
58
+ 'Run `npm run test:coverage` first — without a coverage artifact the refresh refuses (exit 1) and leaves the baseline untouched.',
62
59
  ],
63
60
  };
64
61
 
@@ -75,21 +72,15 @@ async function main() {
75
72
  `[CRAP] Coverage source: ${options.coveragePath}${options.requireCoverage ? ' (required)' : ' (optional)'}`,
76
73
  );
77
74
 
78
- const refreshOpts = {
79
- kind: 'crap',
80
- writePath: options.absBaselinePath,
81
- epsilon: getBaselineEpsilon('crap'),
82
- scorer: buildCrapUpdaterScorer(options, { loadCoverage }),
83
- };
84
- // No flag -> scopeFiles=null + fullScope=false -> the service derives the
85
- // diff via `origin/main..HEAD` (its default baseRef/headRef).
86
- if (options.fullScope) refreshOpts.fullScope = true;
87
- else if (options.diffScopeRef) refreshOpts.baseRef = options.diffScopeRef;
88
-
89
- const result = await refreshBaseline(refreshOpts);
75
+ const result = await refreshBaseline(
76
+ buildCrapRefreshOptions(options, {
77
+ loadCoverage,
78
+ epsilon: getBaselineEpsilon('crap'),
79
+ }),
80
+ );
90
81
 
91
82
  Logger.info(
92
- `[CRAP] ✅ Baseline updated (kernelVersion=${result.envelope.kernelVersion}, escomplexVersion=${resolveEscomplexVersion()}, tsTranspilerVersion=${resolveTsTranspilerVersion()}). Wrote to ${options.absBaselinePath}.`,
83
+ `[CRAP] ✅ Baseline updated (kernelVersion=${result.envelope.kernelVersion}, escomplexVersion=${resolveEscomplexVersion()}, tsTranspilerVersion=${result.envelope.tsTranspilerVersion}). Wrote to ${options.absBaselinePath}.`,
93
84
  );
94
85
  Logger.info(
95
86
  `[CRAP] Wrote ${result.envelope.rows.length} row(s). scope=${result.scope.mode}, wrote=${result.wrote}.`,
@@ -9,6 +9,7 @@
9
9
  import './lib/runtime-deps/ensure-installed.js';
10
10
  import path from 'node:path';
11
11
  import { parseDiffScopeFlag } from './lib/baselines/diff-scope-cli.js';
12
+ import { JSCPD_MISSING } from './lib/baselines/duplication-scanner.js';
12
13
  import { refreshBaseline } from './lib/baselines/refresh-service.js';
13
14
  import { runAsCli } from './lib/cli-utils.js';
14
15
  import { getBaselineEpsilon } from './lib/config/quality.js';
@@ -172,13 +173,22 @@ async function main() {
172
173
  );
173
174
  }
174
175
 
176
+ /**
177
+ * A missing optional peer is an install step, not a crash: no stack.
178
+ *
179
+ * @param {unknown} err
180
+ * @returns {string}
181
+ */
182
+ function fatalDetail(err) {
183
+ if (err?.code === JSCPD_MISSING) return err.message;
184
+ return err?.stack ?? err?.message ?? String(err);
185
+ }
186
+
175
187
  runAsCli(import.meta.url, main, {
176
188
  source: 'duplication-baseline',
177
189
  usage: USAGE,
178
190
  onError: (err) => {
179
- Logger.error(
180
- `[Duplication] ❌ Fatal error: ${err?.stack ?? err?.message ?? err}`,
181
- );
191
+ Logger.error(`[Duplication] ❌ Fatal error: ${fatalDetail(err)}`);
182
192
  process.exitCode = 1;
183
193
  },
184
194
  });
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  import { parseArgs } from 'node:util';
9
- import { respondToHelp } from './lib/cli-usage.js';
9
+ import { runAsCli } from './lib/cli-utils.js';
10
10
  import { resolveConfig } from './lib/config-resolver.js';
11
11
  import { Logger } from './lib/Logger.js';
12
12
  import { transitionTicketState } from './lib/orchestration/ticketing.js';
@@ -31,15 +31,10 @@ const USAGE = {
31
31
  notes: ['Exactly one of --state or --remove-label is required.'],
32
32
  };
33
33
 
34
- // ── CLI Main Block ────────────────────────────────────────────────────────
35
- // cli-opt-out: re-export shim with a DEBUG_MAIN escape hatch for tests; runAsCli's strict path-equality guard would block the env-flag entry path.
36
- if (
37
- (process.argv[1]?.endsWith('update-ticket-state.js') ||
38
- process.env.DEBUG_MAIN) &&
39
- !respondToHelp(process.argv.slice(2), USAGE)
40
- ) {
34
+ /** @param {string[]} argv */
35
+ function parseTicketStateArgs(argv) {
41
36
  const { values } = parseArgs({
42
- args: process.argv.slice(2),
37
+ args: argv,
43
38
  options: {
44
39
  ticket: { type: 'string' },
45
40
  state: { type: 'string' },
@@ -47,11 +42,9 @@ if (
47
42
  },
48
43
  strict: false,
49
44
  });
50
-
51
45
  const ticketId = Number.parseInt(values.ticket, 10);
52
46
  const state = values.state;
53
47
  const removeLabel = values['remove-label'];
54
-
55
48
  if (Number.isNaN(ticketId) || (!state && !removeLabel)) {
56
49
  throw new Error(
57
50
  'Usage: node update-ticket-state.js ' +
@@ -59,44 +52,50 @@ if (
59
52
  '[--state <state> | --remove-label <label>]',
60
53
  );
61
54
  }
55
+ return { ticketId, state, removeLabel };
56
+ }
62
57
 
63
- (async () => {
64
- const config = resolveConfig();
65
- const provider = createProvider(config);
66
-
67
- // Label-only mutation path — no state transition. Callers that just
68
- // need to drop a single label without flipping the agent::* state.
69
- if (removeLabel && !state) {
70
- Logger.info(
71
- `[State-Sync] Removing label \`${removeLabel}\` from ticket #${ticketId}...`,
72
- );
73
- await provider.updateTicket(ticketId, {
74
- labels: { remove: [removeLabel] },
75
- });
76
- Logger.info('[State-Sync] ✅ Success');
77
- return;
78
- }
58
+ /**
59
+ * @param {{ argv?: string[], provider?: object, transition?: typeof transitionTicketState }} [opts]
60
+ */
61
+ export async function runUpdateTicketState({
62
+ argv = process.argv.slice(2),
63
+ provider,
64
+ transition = transitionTicketState,
65
+ } = {}) {
66
+ const { ticketId, state, removeLabel } = parseTicketStateArgs(argv);
67
+ const ticketing = provider ?? createProvider(resolveConfig());
79
68
 
69
+ // Label-only mutation path — no state transition. Callers that just
70
+ // need to drop a single label without flipping the agent::* state.
71
+ if (removeLabel && !state) {
80
72
  Logger.info(
81
- `[State-Sync] Transitioning ticket #${ticketId} to ${state}...`,
73
+ `[State-Sync] Removing label \`${removeLabel}\` from ticket #${ticketId}...`,
82
74
  );
83
- // No explicit cascade: `transitionTicketState` already runs it.
84
- await transitionTicketState(provider, ticketId, state);
75
+ await ticketing.updateTicket(ticketId, {
76
+ labels: { remove: [removeLabel] },
77
+ });
78
+ Logger.info('[State-Sync] ✅ Success');
79
+ return { ticketId, state: null, removedLabel: removeLabel };
80
+ }
85
81
 
86
- // Optional secondary label removal alongside the state transition
87
- // (e.g. clear `status::blocked` when transitioning back to ready).
88
- if (removeLabel) {
89
- await provider.updateTicket(ticketId, {
90
- labels: { remove: [removeLabel] },
91
- });
92
- }
82
+ Logger.info(`[State-Sync] Transitioning ticket #${ticketId} to ${state}...`);
83
+ // No explicit cascade: `transitionTicketState` already runs it.
84
+ await transition(ticketing, ticketId, state);
93
85
 
94
- Logger.info('[State-Sync] ✅ Success');
95
- })().catch((err) => {
96
- // Re-throw as an unhandled rejection so Node exits with a non-zero
97
- // status. Per orchestration-error-handling rule, orchestrator CLIs MUST
98
- // surface failures via throw rather than Logger.fatal so a stubbed
99
- // process.exit (in tests) does not silently mask the error.
100
- throw new Error(err.message);
101
- });
86
+ // Optional secondary label removal alongside the state transition
87
+ // (e.g. clear `status::blocked` when transitioning back to ready).
88
+ if (removeLabel) {
89
+ await ticketing.updateTicket(ticketId, {
90
+ labels: { remove: [removeLabel] },
91
+ });
92
+ }
93
+
94
+ Logger.info('[State-Sync] ✅ Success');
95
+ return { ticketId, state, removedLabel: removeLabel ?? null };
102
96
  }
97
+
98
+ runAsCli(import.meta.url, () => runUpdateTicketState(), {
99
+ source: 'update-ticket-state',
100
+ usage: USAGE,
101
+ });
@@ -32,7 +32,7 @@ has to be settled here instead.
32
32
  Run each `audit-*` workflow with **no** `--paths` and no change-set filter, so
33
33
  the whole target-set union is audited rather than whatever a recent branch
34
34
  happened to touch. Each lens writes its report to
35
- `temp/audits/audit-<lens>-results.md`.
35
+ `temp/audits/audit-results/audit-<lens>-results.md`.
36
36
 
37
37
  A sweep scoped to a change set is not a sweep: it re-reports the same recent
38
38
  files every cycle and never reaches the code nobody has touched in a year,
@@ -11,7 +11,7 @@ concrete element and the success criterion it violates. Default to **static**
11
11
  detection over source; escalate to a **runtime** pass only when a live target is
12
12
  configured. The shared lens machinery lives in
13
13
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
14
- `{{auditOutputDir}}/audit-accessibility-results.md`. Extra finding fields:
14
+ `{{auditResultsDir}}/audit-accessibility-results.md`. Extra finding fields:
15
15
  **WCAG:** (the violated success criterion, e.g. `1.1.1 Non-text Content (A)`)
16
16
  and **Evidence:** (`measured | static` + the observable; single-run runtime
17
17
  numbers are tagged `provisional`). The report adds a **Runtime Verification**
@@ -18,7 +18,7 @@ That is this lens's central target; structural tidiness is the cheap part.
18
18
 
19
19
  The shared lens machinery lives in
20
20
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
21
- `{{auditOutputDir}}/audit-adrs-results.md`. Dimension values:
21
+ `{{auditResultsDir}}/audit-adrs-results.md`. Dimension values:
22
22
  `Decision Drift | Supersede-Chain Integrity | Structure & Status Hygiene |
23
23
  Missing Decision | Layout Conformance`; the report adds a **Decision Coverage**
24
24
  table.
@@ -8,7 +8,7 @@ You are a Staff Software Engineer & Architecture Reviewer performing a read-only
8
8
  review that prioritizes maintainability and readability without altering
9
9
  external APIs or business logic. The shared lens machinery lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-architecture-results.md`. Each finding carries an
11
+ `{{auditResultsDir}}/audit-architecture-results.md`. Each finding carries an
12
12
  **Impact:** and a **Category:** (`Quick Win | Structural Change`); the report
13
13
  adds a **Triage Summary** (Quick Wins / Structural Changes) and an
14
14
  **Architecture Guardrail Coverage** section.
@@ -12,7 +12,7 @@ the loop that burns the measured debt **down** and tightens the floors behind
12
12
  it, so a repo can hold a floor it cleared years ago and never notice. This lens
13
13
  is that loop's read-only entry point. The shared lens machinery lives in
14
14
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
15
- `{{auditOutputDir}}/audit-baselines-results.md`. Dimension values:
15
+ `{{auditResultsDir}}/audit-baselines-results.md`. Dimension values:
16
16
  `Dead Instrument | Staleness | Hotspot Cluster | Trend Drift | Tightening Headroom`.
17
17
 
18
18
  > **Value-free titles (mandatory).** A finding title MUST NOT embed a measured
@@ -252,7 +252,7 @@ shared finding skeleton, fingerprints each finding for dedupe, and groups the
252
252
  batch:
253
253
 
254
254
  ```bash
255
- node .agents/scripts/audit-to-stories.js --scan --glob temp/audits/audit-baselines-results.md --out temp/audits/audit-to-stories-plan.json
255
+ node .agents/scripts/audit-to-stories.js --scan --glob temp/audits/audit-results/audit-baselines-results.md --out temp/audits/audit-to-stories-plan.json
256
256
  ```
257
257
 
258
258
  Report the plan path and the group count; the converter owns everything
@@ -8,7 +8,7 @@ You are a Principal Software Engineer & Code Quality Lead auditing
8
8
  maintainability — code smells, technical debt, and clean-code violations (SOLID,
9
9
  DRY, KISS) that hinder long-term velocity. The shared lens machinery lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-clean-code-results.md`. The report adds a **Dead Code
11
+ `{{auditResultsDir}}/audit-clean-code-results.md`. The report adds a **Dead Code
12
12
  Inventory** table (File / Symbol / Type / Estimated LOC) and a **Technical Debt
13
13
  Backlog** section.
14
14
 
@@ -11,7 +11,7 @@ schema silently disagree, where an assumed invariant is not enforced by a
11
11
  constraint, where a migration is unsafe against a live database, and where
12
12
  schema exists that nothing uses. The shared lens machinery lives in
13
13
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
14
- `{{auditOutputDir}}/audit-data-model-results.md`. Dimension values:
14
+ `{{auditResultsDir}}/audit-data-model-results.md`. Dimension values:
15
15
  `Drift | Constraint Completeness | Migration Hygiene | Type Fidelity |
16
16
  Access-Pattern Fit | Dead Schema`. Extra finding field: **Evidence:** (a
17
17
  reference-count or introspection command plus a `measured`, `static`, or
@@ -8,7 +8,7 @@ You are a DevOps Engineer & Security Researcher managing the dependency
8
8
  lifecycle — outdated, vulnerable, or bloated packages and a safe upgrade path.
9
9
  The shared lens machinery lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-dependencies-results.md`. Dimension values:
11
+ `{{auditResultsDir}}/audit-dependencies-results.md`. Dimension values:
12
12
  `Security Fix | Removal | Engine Drift | Major Upgrade | Supply-chain`. The
13
13
  report adds a **Health Summary**, an **Upgrade Batches** section, and a
14
14
  **Recommended Removals/Replacements** list.
@@ -8,7 +8,7 @@ You are a Principal DevOps Engineer & Infrastructure Architect auditing this
8
8
  repo's DevOps infrastructure, DX tooling, and CI/CD pipelines for
9
9
  inefficiencies, security risks, and modernization opportunities. The shared lens machinery lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-devops-results.md`. The report adds a **Proposed
11
+ `{{auditResultsDir}}/audit-devops-results.md`. The report adds a **Proposed
12
12
  Implementation Roadmap** section (a logical, phased plan).
13
13
 
14
14
  ## Scope
@@ -12,7 +12,7 @@ mode) catch broken links and generator drift — they cannot tell whether the
12
12
  prose still describes how the code actually behaves. That semantic
13
13
  verification is this lens's job. The shared lens machinery lives in
14
14
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
15
- `{{auditOutputDir}}/audit-documentation-results.md`. Each finding carries a
15
+ `{{auditResultsDir}}/audit-documentation-results.md`. Each finding carries a
16
16
  **Category:** (`Broken Instruction | Stale Description | Missing Coverage |
17
17
  Generator Drift | Link Integrity | History Bloat | Contradiction | Authority
18
18
  Drift`); the report adds a **Target Set Coverage** table.
@@ -11,7 +11,7 @@ advisory, a skipped test, a `KNOWN_*` list. Nothing else checks whether they
11
11
  still earn their place, so they pile up unnoticed. This lens is that check,
12
12
  and it is read-only. The shared lens machinery lives in
13
13
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
14
- `{{auditOutputDir}}/audit-exceptions-results.md`. Dimension values:
14
+ `{{auditResultsDir}}/audit-exceptions-results.md`. Dimension values:
15
15
  `Dead | Expired | Orphaned | Unjustified | Fix Properly`.
16
16
 
17
17
  > **Value-free titles (mandatory).** A finding title MUST NOT embed a count,
@@ -199,7 +199,7 @@ substituting the envelope's own values for the angle-bracketed slots:
199
199
  ## Step 5: Hand off to `/audit-to-stories`
200
200
 
201
201
  ```bash
202
- node .agents/scripts/audit-to-stories.js --scan --glob temp/audits/audit-exceptions-results.md --out temp/audits/audit-to-stories-plan.json
202
+ node .agents/scripts/audit-to-stories.js --scan --glob temp/audits/audit-results/audit-exceptions-results.md --out temp/audits/audit-to-stories-plan.json
203
203
  ```
204
204
 
205
205
  Report the plan path and the group count; the converter owns everything
@@ -10,7 +10,7 @@ a phone and a tablet — and does anything in the suite actually verify that it
10
10
  does? Default to **static** detection over source; escalate to a **runtime**
11
11
  viewport pass only when a live target is configured. The shared lens machinery lives in
12
12
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
13
- `{{auditOutputDir}}/audit-mobile-results.md`. Dimension values:
13
+ `{{auditResultsDir}}/audit-mobile-results.md`. Dimension values:
14
14
  `Layout & Viewport | Touch Ergonomics | Responsive Assets | Mobile Verification`.
15
15
  Extra finding field: **Evidence:** (`measured | static` + the observable;
16
16
  single-run runtime numbers are tagged `provisional`).
@@ -18,7 +18,7 @@ not exist). This is **mechanism, not content**: the lens reads the consumer's
18
18
  configured route tree and nav-registry SSOT and is a **silent no-op when neither
19
19
  is configured**. The shared lens machinery lives in
20
20
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
21
- `{{auditOutputDir}}/audit-navigability-results.md`. Dimension values:
21
+ `{{auditResultsDir}}/audit-navigability-results.md`. Dimension values:
22
22
  `Orphaned Route | Dead Nav Href`; extra finding fields **Route / Door:** and
23
23
  **Persona(s):** (identifiers only — never full route bodies or persona PII).
24
24
 
@@ -13,7 +13,7 @@ only the dimensions that apply, declaring the rest inapplicable); and
13
13
  **interleaving correctness is a performance concern** (races have been the most
14
14
  expensive defects this repo shipped). The shared lens machinery lives in
15
15
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
16
- `{{auditOutputDir}}/audit-performance-results.md`. Extra finding field:
16
+ `{{auditResultsDir}}/audit-performance-results.md`. Extra finding field:
17
17
  **Evidence:** [a Step 0 repro command (or quoted code path) + a `measured` or
18
18
  `estimated` tag]. The report adds a **Low-Hanging Fruit** section.
19
19
 
@@ -8,7 +8,7 @@ You are a Data Privacy Officer & Security Engineer finding accidental logging,
8
8
  insecure storage, or unnecessary collection of PII, and checking GDPR/CCPA
9
9
  compliance. The shared lens machinery lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-privacy-results.md`. This lens labels the severity
11
+ `{{auditResultsDir}}/audit-privacy-results.md`. This lens labels the severity
12
12
  axis **Impact** and uses dimension values `Leaky Log | Insecure Storage | Data
13
13
  Over-collection`; its report adds a **Privacy Scorecard** section (Data
14
14
  Encryption / Logging Safety / Minimization: Pass/Fail/Partial).
@@ -9,7 +9,7 @@ infrastructure, coverage, flaky tests, mocking strategy, and test-pyramid
9
9
  balance — and, in Story-scoped mode, evaluating the implemented tests against
10
10
  the Story under audit. The shared lens machinery lives in
11
11
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
12
- `{{auditOutputDir}}/audit-quality-results.md`. Each finding carries a
12
+ `{{auditResultsDir}}/audit-quality-results.md`. Each finding carries a
13
13
  **Category:** (`Flakiness | Coverage | Performance | Mocking | Test Plans`); the
14
14
  report adds a **Test Strategy Assessment** table (Unit / Integration / E2E /
15
15
  Test Plans / Property-Based Testing: Healthy / Needs Work / Missing, or `N/A`
@@ -8,7 +8,7 @@ You are a Cybersecurity Architect conducting a comprehensive security review
8
8
  (OWASP Top 10, insecure configs, attack vectors). The shared lens machinery
9
9
  lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
- `{{auditOutputDir}}/audit-security-results.md`. Extra finding fields: **CWE
11
+ `{{auditResultsDir}}/audit-security-results.md`. Extra finding fields: **CWE
12
12
  ID:**, **Baseline MUST:** (the violated MUST, or `none — trust-boundary
13
13
  class`) and **Boundary:** (Step 2's six-clause gate). The report adds a
14
14
  **Defensive Recommendations** section (3–5 hardening headers/configs/
@@ -9,7 +9,7 @@ You are a Senior Technical SEO & Generative Engine Optimization (GEO) Specialist
9
9
  and content-level improvements that increase discoverability in both traditional
10
10
  search indexes and AI answer engines. The shared lens machinery lives in
11
11
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
12
- `{{auditOutputDir}}/audit-seo-results.md`. Each finding carries a **Category:**
12
+ `{{auditResultsDir}}/audit-seo-results.md`. Each finding carries a **Category:**
13
13
  (`SEO | GEO | Core Web Vitals | Crawlability`); the report adds a **Detailed
14
14
  Audit Table** (an at-a-glance index — not machine-parsed; every row MUST also
15
15
  have a full Detailed Findings entry) and a **GEO-Specific Recommendations**
@@ -9,7 +9,7 @@ a production release candidate — rollback & recovery paths, observability &
9
9
  instrumentation, resilience & failure handling, and runbooks & operational
10
10
  docs. The shared lens machinery lives in
11
11
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
12
- `{{auditOutputDir}}/audit-sre-results.md`. Each finding carries a **Category:**
12
+ `{{auditResultsDir}}/audit-sre-results.md`. Each finding carries a **Category:**
13
13
  (`Rollback & Recovery | Observability | Resilience | Runbooks`); the report adds
14
14
  a **Release Readiness Checklist** table (per-category ✅ Clear / ⚠️ Issues
15
15
  Found).