oxe-cc 1.22.0 → 1.22.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.
Files changed (145) hide show
  1. package/.cursor/commands/oxe-discuss.md +45 -45
  2. package/.cursor/commands/oxe-execute.md +52 -52
  3. package/.cursor/commands/oxe-help.md +44 -44
  4. package/.cursor/commands/oxe-next.md +44 -44
  5. package/.cursor/commands/oxe-plan.md +49 -49
  6. package/.cursor/commands/oxe-quick.md +49 -49
  7. package/.cursor/commands/oxe-review-pr.md +47 -47
  8. package/.cursor/commands/oxe-scan.md +47 -47
  9. package/.cursor/commands/oxe-ship.md +47 -47
  10. package/.cursor/commands/oxe-spec.md +49 -49
  11. package/.cursor/commands/oxe-verify.md +50 -50
  12. package/.cursor/commands/oxe.md +51 -51
  13. package/.github/prompts/oxe-alm.prompt.md +47 -47
  14. package/.github/prompts/oxe-ask.prompt.md +47 -47
  15. package/.github/prompts/oxe-capabilities.prompt.md +47 -47
  16. package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
  17. package/.github/prompts/oxe-compact.prompt.md +46 -46
  18. package/.github/prompts/oxe-dashboard.prompt.md +47 -47
  19. package/.github/prompts/oxe-debug.prompt.md +47 -47
  20. package/.github/prompts/oxe-discuss.prompt.md +47 -47
  21. package/.github/prompts/oxe-execute.prompt.md +52 -52
  22. package/.github/prompts/oxe-forensics.prompt.md +47 -47
  23. package/.github/prompts/oxe-help.prompt.md +46 -46
  24. package/.github/prompts/oxe-loop.prompt.md +47 -47
  25. package/.github/prompts/oxe-milestone.prompt.md +47 -47
  26. package/.github/prompts/oxe-next.prompt.md +46 -46
  27. package/.github/prompts/oxe-obs.prompt.md +47 -47
  28. package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
  29. package/.github/prompts/oxe-plan.prompt.md +49 -49
  30. package/.github/prompts/oxe-project.prompt.md +47 -47
  31. package/.github/prompts/oxe-quick.prompt.md +49 -49
  32. package/.github/prompts/oxe-research.prompt.md +47 -47
  33. package/.github/prompts/oxe-retro.prompt.md +47 -47
  34. package/.github/prompts/oxe-review-pr.prompt.md +47 -47
  35. package/.github/prompts/oxe-route.prompt.md +47 -47
  36. package/.github/prompts/oxe-scan.prompt.md +47 -47
  37. package/.github/prompts/oxe-security.prompt.md +47 -47
  38. package/.github/prompts/oxe-session.prompt.md +47 -47
  39. package/.github/prompts/oxe-ship.prompt.md +47 -47
  40. package/.github/prompts/oxe-skill.prompt.md +47 -47
  41. package/.github/prompts/oxe-spec.prompt.md +49 -49
  42. package/.github/prompts/oxe-ui-review.prompt.md +47 -47
  43. package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
  44. package/.github/prompts/oxe-update.prompt.md +46 -46
  45. package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
  46. package/.github/prompts/oxe-verify.prompt.md +50 -50
  47. package/.github/prompts/oxe-workstream.prompt.md +47 -47
  48. package/.github/prompts/oxe.prompt.md +51 -51
  49. package/.github/workflows/release.yml +31 -0
  50. package/CHANGELOG.md +88 -0
  51. package/README.md +1 -1
  52. package/bin/lib/commands/ops-commands.cjs +751 -0
  53. package/bin/lib/commands/spec-program-commands.cjs +337 -0
  54. package/bin/lib/operational/alm-refine-runtime.cjs +791 -0
  55. package/bin/lib/operational/child-env.cjs +52 -0
  56. package/bin/lib/operational/promote-runtime.cjs +1187 -0
  57. package/bin/lib/oxe-agent-coord.cjs +246 -0
  58. package/bin/lib/oxe-alm-refine.cjs +97 -1
  59. package/bin/lib/oxe-ci-adapter.cjs +304 -0
  60. package/bin/lib/oxe-complexity.cjs +1 -1
  61. package/bin/lib/oxe-decisions.cjs +9 -3
  62. package/bin/lib/oxe-dir-info.cjs +20 -1
  63. package/bin/lib/oxe-env-sanitize.cjs +6 -1
  64. package/bin/lib/oxe-git-root.cjs +97 -0
  65. package/bin/lib/oxe-grill.cjs +90 -1
  66. package/bin/lib/oxe-onboard.cjs +640 -0
  67. package/bin/lib/oxe-operational.cjs +14481 -15949
  68. package/bin/lib/oxe-origin.cjs +4 -1
  69. package/bin/lib/oxe-phase-gates.cjs +139 -2
  70. package/bin/lib/oxe-plan-build.cjs +62 -2
  71. package/bin/lib/oxe-plan-mutate.cjs +108 -2
  72. package/bin/lib/oxe-preflight.cjs +9 -3
  73. package/bin/lib/oxe-presets.cjs +216 -0
  74. package/bin/lib/oxe-project-env.cjs +79 -0
  75. package/bin/lib/oxe-project-health.cjs +2 -0
  76. package/bin/lib/oxe-reevaluate.cjs +198 -0
  77. package/bin/lib/oxe-release-ops.cjs +51 -15
  78. package/bin/lib/oxe-scorecard.cjs +394 -1
  79. package/bin/lib/oxe-ship-pr.cjs +72 -4
  80. package/bin/lib/oxe-spec-check.cjs +32 -0
  81. package/bin/lib/oxe-suite-impact.cjs +1160 -1145
  82. package/bin/lib/oxe-sync.cjs +99 -2
  83. package/bin/lib/oxe-verify-cache.cjs +132 -0
  84. package/bin/lib/oxe-vitest-batch.cjs +10 -3
  85. package/bin/lib/oxe-worktree-gc.cjs +655 -170
  86. package/bin/oxe-cc.js +10042 -10669
  87. package/commands/oxe/alm.md +54 -54
  88. package/commands/oxe/ask.md +55 -55
  89. package/commands/oxe/capabilities.md +50 -50
  90. package/commands/oxe/checkpoint.md +53 -53
  91. package/commands/oxe/compact.md +47 -47
  92. package/commands/oxe/dashboard.md +51 -51
  93. package/commands/oxe/debug.md +58 -58
  94. package/commands/oxe/discuss.md +58 -58
  95. package/commands/oxe/execute.md +63 -63
  96. package/commands/oxe/forensics.md +53 -53
  97. package/commands/oxe/help.md +48 -48
  98. package/commands/oxe/loop.md +54 -54
  99. package/commands/oxe/milestone.md +53 -53
  100. package/commands/oxe/next.md +49 -49
  101. package/commands/oxe/obs.md +53 -53
  102. package/commands/oxe/oxe.md +55 -55
  103. package/commands/oxe/plan-agent.md +57 -57
  104. package/commands/oxe/plan.md +59 -59
  105. package/commands/oxe/project.md +53 -53
  106. package/commands/oxe/quick.md +53 -53
  107. package/commands/oxe/research.md +53 -53
  108. package/commands/oxe/retro.md +53 -53
  109. package/commands/oxe/review-pr.md +53 -53
  110. package/commands/oxe/route.md +48 -48
  111. package/commands/oxe/scan.md +58 -58
  112. package/commands/oxe/security.md +53 -53
  113. package/commands/oxe/session.md +53 -53
  114. package/commands/oxe/ship.md +53 -53
  115. package/commands/oxe/skill.md +53 -53
  116. package/commands/oxe/spec.md +59 -59
  117. package/commands/oxe/ui-review.md +53 -53
  118. package/commands/oxe/ui-spec.md +53 -53
  119. package/commands/oxe/update.md +53 -53
  120. package/commands/oxe/validate-gaps.md +53 -53
  121. package/commands/oxe/verify-audit.md +50 -50
  122. package/commands/oxe/verify.md +60 -60
  123. package/commands/oxe/workflow-authoring.md +50 -50
  124. package/commands/oxe/workstream.md +53 -53
  125. package/docs/RELEASE-READINESS.md +7 -1
  126. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -29
  127. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -29
  128. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -29
  129. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -29
  130. package/docs/adr/D-5-core-agnostico-vs-presets-declarativos-de-dominio.md +29 -0
  131. package/docs/adr/D-6-decomposicao-strangler-fig-de-oxe-cc-e-oxe-operational.md +29 -0
  132. package/docs/adr/D-7-paridade-pre-push-com-phase-gates-path-aware-json-compacto-e.md +28 -0
  133. package/docs/adr/D-F1F4-1-paridade-pre-push-compactacao-json-sync-version-pins-e-quali.md +44 -0
  134. package/docs/adr/README.md +18 -14
  135. package/lib/runtime/verification/verification-compiler.d.ts +12 -1
  136. package/lib/runtime/verification/verification-compiler.js +235 -65
  137. package/oxe/templates/CONFIG.md +14 -1
  138. package/oxe/workflows/help.md +3 -0
  139. package/oxe/workflows/lean/execute.md +2 -1
  140. package/oxe/workflows/ship.md +4 -2
  141. package/package.json +4 -4
  142. package/packages/runtime/package.json +1 -1
  143. package/packages/runtime/src/verification/verification-compiler.ts +193 -25
  144. package/packages/runtime/tsconfig.json +1 -0
  145. package/vscode-extension/package.json +1 -1
@@ -42,6 +42,7 @@ function originConfig(config = {}) {
42
42
  problems: Array.isArray(ex.commits) ? ex.commits.filter((c) => !(c && /^[0-9a-f]{40}$/i.test(String(c.sha || '')) && String(c.reason || '').trim().length >= 8 && String(c.by || '').trim())).map((c) => `origin.exempt.commits: entrada recusada ${JSON.stringify(c)} — exige sha completo (40 hex), reason (uma frase) e by`) : [],
43
43
  commit_msg: ['require', 'append', 'off'].includes(o.commit_msg) ? o.commit_msg : 'require',
44
44
  require_card: o.require_card != null ? o.require_card === true : almOn,
45
+ allow_no_alm_quick: o.allow_no_alm_quick === true,
45
46
  base: typeof o.base === 'string' && o.base ? o.base : null,
46
47
  // G19: the cut — only commits after it are charged (a date, or a commit: what it already contains is history)
47
48
  since: typeof o.since === 'string' && o.since.trim() ? o.since.trim() : null,
@@ -186,8 +187,10 @@ function classify(commit, ocfg, ctx = {}) {
186
187
  const q = QUICK_RE.exec(msg);
187
188
  if (q) {
188
189
  const card = CARD_RE.exec(msg);
189
- if (ocfg.require_card && !card) return { ...base, ok: false, kind: 'quick', quick: q[1], reason: 'OXE-Quick sem OXE-Card (com ALM, o quick nomeia o card)' };
190
190
  const known = typeof ctx.quickExists === 'function' ? ctx.quickExists(q[1]) : null;
191
+ if (ocfg.require_card && !card && !(ocfg.allow_no_alm_quick && known === true)) {
192
+ return { ...base, ok: false, kind: 'quick', quick: q[1], reason: 'OXE-Quick sem OXE-Card (com ALM, o quick nomeia o card)' };
193
+ }
191
194
  // OxeSpace 15/11 (#854, coordination): a commit made by `quick commit` (its trailers) whose local record was lost —
192
195
  // the commit is OLDER than the first record this checkout keeps, and the quick id's date is not after the commit.
193
196
  // A distinct, audited status: neither a pass nor a fail, listed in every report.
@@ -23,14 +23,20 @@ const { spawnSync } = require('child_process');
23
23
  const WHEN = new Set(['phase_verify', 'program_close']);
24
24
  /** A full typecheck or governance suite takes minutes, not the verify's 60 s per check. */
25
25
  const DEFAULT_GATE_TIMEOUT_MS = 15 * 60 * 1000;
26
- const GOVERNANCE_TEST_RE = /(^|[\\/._-])(lint|allowlist|catalog|coverage|governance|ratchet|boundar(y|ies)|budget)[^\\/]*\.test\.[cm]?[jt]sx?$/i;
26
+ const GOVERNANCE_TEST_RE = /(^|[\\/._-])(lint|allowlist|catalog|coverage|governance|ratchet|boundar(y|ies)|budget|guard|contract|copy|tokens?|schema-pin|migration|i18n|policy)[^\\/]*\.test\.[cm]?[jt]sx?$/i;
27
27
  const GATE_SCRIPT_NAMES = ['typecheck', 'type-check', 'lint', 'check', 'test:governance'];
28
28
 
29
29
  const BUILTIN_KINDS = new Set(['command', 'ci', 'deploy', 'signoff', 'script']);
30
30
 
31
+ function normalizeGatePaths(raw) {
32
+ const src = Array.isArray(raw && raw.paths) ? raw.paths : (Array.isArray(raw && raw.globs) ? raw.globs : []);
33
+ return [...new Set(src.map((p) => String(p || '').replace(/\\/g, '/').replace(/^\.\//, '').trim()).filter(Boolean))];
34
+ }
35
+
31
36
  function normalizeGate(raw, plugins = {}) {
32
37
  if (!raw || typeof raw !== 'object') return null;
33
38
  const id = String(raw.id || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
39
+ const paths = normalizeGatePaths(raw);
34
40
  // OXB-107: signoff / script are built in; another kind is a plugin from config gate_plugins.
35
41
  if (raw.kind === 'signoff' || raw.kind === 'script' || (raw.kind && !BUILTIN_KINDS.has(raw.kind))) {
36
42
  const pluginModule = raw.kind === 'script' ? raw.module : raw.kind === 'signoff' ? null : plugins && plugins[raw.kind];
@@ -48,6 +54,7 @@ function normalizeGate(raw, plugins = {}) {
48
54
  runner: null,
49
55
  when: WHEN.has(raw.when) ? raw.when : raw.kind === 'signoff' ? 'program_close' : 'phase_verify',
50
56
  repo: null,
57
+ paths,
51
58
  description: typeof raw.description === 'string' ? raw.description.trim() : '',
52
59
  timeout_ms: Number(raw.timeout_ms) > 0 ? Number(raw.timeout_ms) : DEFAULT_GATE_TIMEOUT_MS,
53
60
  };
@@ -70,6 +77,7 @@ function normalizeGate(raw, plugins = {}) {
70
77
  runner: typeof raw.runner === 'string' && raw.runner.trim() ? raw.runner.trim() : null,
71
78
  when,
72
79
  repo: typeof raw.repo === 'string' && raw.repo.trim() ? raw.repo.trim() : null,
80
+ paths,
73
81
  description: typeof raw.description === 'string' ? raw.description.trim() : '',
74
82
  timeout_ms: Number(raw.timeout_ms) > 0 ? Number(raw.timeout_ms) : DEFAULT_GATE_TIMEOUT_MS,
75
83
  };
@@ -155,9 +163,18 @@ function alreadyWrapped(runner, command) {
155
163
  }
156
164
 
157
165
  /** Verification checks (same shape as the runtime's AcceptanceCheck) for the gates of one moment. */
166
+ function gateMatchesChangedFiles(gate, changedFiles) {
167
+ const patterns = Array.isArray(gate && gate.paths) ? gate.paths : [];
168
+ if (!patterns.length) return true;
169
+ if (!Array.isArray(changedFiles)) return true; // safe fallback: never false green without diff
170
+ const { globMatch } = require('./oxe-preflight.cjs');
171
+ const normFiles = changedFiles.map((f) => String(f || '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean);
172
+ return normFiles.some((file) => patterns.some((pat) => globMatch(file, pat)));
173
+ }
174
+
158
175
  function gateChecks(gates, when, options = {}) {
159
176
  return gates
160
- .filter((gate) => gate.when === when)
177
+ .filter((gate) => gate.when === when && gateMatchesChangedFiles(gate, options.changedFiles))
161
178
  .map((gate) => ({
162
179
  id: `gate-${gate.id}`,
163
180
  type: 'policy',
@@ -170,6 +187,53 @@ function gateChecks(gates, when, options = {}) {
170
187
  }));
171
188
  }
172
189
 
190
+ /**
191
+ * OXB-222-01: Converts matched `config.preflight.triggers` entries into runtime verify checks so
192
+ * path-scoped contract/UI/schema guards run locally before the first push.
193
+ */
194
+ function preflightTriggerChecks(config, changedFiles, options = {}) {
195
+ const pf = config && config.preflight && typeof config.preflight === 'object' ? config.preflight : null;
196
+ const triggers = pf && Array.isArray(pf.triggers) ? pf.triggers : [];
197
+ if (!triggers.length) return [];
198
+ const { globMatch } = require('./oxe-preflight.cjs');
199
+ const normFiles = Array.isArray(changedFiles)
200
+ ? changedFiles.map((f) => String(f || '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean)
201
+ : null;
202
+ const out = [];
203
+ for (let i = 0; i < triggers.length; i += 1) {
204
+ const tr = triggers[i];
205
+ if (!tr || typeof tr !== 'object' || !tr.command) continue;
206
+ const patterns = Array.isArray(tr.globs) && tr.globs.length
207
+ ? tr.globs
208
+ : (Array.isArray(tr.paths) ? tr.paths : []);
209
+ if (!patterns.length) continue;
210
+ if (normFiles !== null) {
211
+ const hit = normFiles.some((f) => patterns.some((g) => globMatch(f, g)));
212
+ if (!hit) continue;
213
+ }
214
+ const slug = String(tr.name || `trigger-${i + 1}`).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
215
+ const gate = {
216
+ id: `trigger-${slug}`,
217
+ kind: 'command',
218
+ command: String(tr.command).trim(),
219
+ runner: typeof tr.runner === 'string' && tr.runner.trim() ? tr.runner.trim() : null,
220
+ when: 'phase_verify',
221
+ timeout_ms: Number(tr.timeout_ms || tr.timeoutMs) > 0 ? Number(tr.timeout_ms || tr.timeoutMs) : DEFAULT_GATE_TIMEOUT_MS,
222
+ };
223
+ out.push({
224
+ id: `gate-${gate.id}`,
225
+ type: 'policy',
226
+ command: gateCommand(gate, options),
227
+ evidence_type_expected: 'stdout',
228
+ acceptance_ref: null,
229
+ description: `[preflight trigger] ${tr.name || slug}`,
230
+ phase_gate: gate.id,
231
+ timeout_ms: gate.timeout_ms,
232
+ });
233
+ }
234
+ return out;
235
+ }
236
+
173
237
  /**
174
238
  * OXB-070: the lines that make the gate FAIL, never the head of the stream. CR-16 (lint) quoted the first of 217
175
239
  * warnings ("285:3 warning … Error: Cannot access refs during render") — a case-insensitive /error/ matched a warning —
@@ -525,6 +589,76 @@ if (require.main === module && process.argv.includes('--signoff-gate')) {
525
589
  process.exitCode = runDeployGateCli(process.argv.slice(2));
526
590
  }
527
591
 
592
+ /**
593
+ * OXB-222-01: Suggests agnostic, declarative `phase_gates` entries with optional `paths` globs
594
+ * derived solely from generic filenames and package.json scripts present in `projectRoot`.
595
+ */
596
+ function suggestPathGates(projectRoot) {
597
+ const candidates = detectGateCandidates(projectRoot);
598
+ const suggestions = [];
599
+ let pkg = null;
600
+ try {
601
+ pkg = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));
602
+ } catch {
603
+ pkg = null;
604
+ }
605
+ const deps = { ...((pkg && pkg.dependencies) || {}), ...((pkg && pkg.devDependencies) || {}) };
606
+ const testRunnerFor = (files) => {
607
+ if (files.every((f) => /\.cjs$/i.test(f))) return `node --test ${files.join(' ')}`;
608
+ if (deps.vitest || files.some((f) => /\.tsx?$/i.test(f))) return `npx vitest run ${files.join(' ')}`;
609
+ if (deps.jest) return `npx jest ${files.join(' ')}`;
610
+ return `node --test ${files.join(' ')}`;
611
+ };
612
+
613
+ for (const cand of candidates) {
614
+ if (cand.command) {
615
+ suggestions.push({
616
+ id: cand.id,
617
+ command: cand.command,
618
+ paths: [],
619
+ source: cand.source,
620
+ description: `script ${cand.id} do package.json`,
621
+ });
622
+ } else if (Array.isArray(cand.files) && cand.files.length) {
623
+ const buckets = [
624
+ {
625
+ id: 'ui-tokens-copy',
626
+ re: /(copy|tokens?|css|i18n|design-lint)/i,
627
+ paths: ['**/*.css', '**/*.scss', '**/*.tsx', '**/*.jsx', '**/locales/**'],
628
+ description: 'guardas de UI, tokens, copy e i18n',
629
+ },
630
+ {
631
+ id: 'db-schema-migrations',
632
+ re: /(schema-pin|migration)/i,
633
+ paths: ['**/migrations/**', '**/db/**', '**/schema*'],
634
+ description: 'guardas de schema e numeração de migrations',
635
+ },
636
+ {
637
+ id: 'contracts-governance',
638
+ re: /(guard|contract|policy|allowlist|catalog|coverage|governance|ratchet|boundar|budget|lint)/i,
639
+ paths: ['src/**', 'lib/**', 'bin/**', 'shared/**'],
640
+ description: 'guardas de contrato, política e governança',
641
+ },
642
+ ];
643
+ const assigned = new Set();
644
+ for (const bucket of buckets) {
645
+ const matched = cand.files.filter((f) => !assigned.has(f) && bucket.re.test(f));
646
+ if (!matched.length) continue;
647
+ for (const f of matched) assigned.add(f);
648
+ suggestions.push({
649
+ id: bucket.id,
650
+ command: testRunnerFor(matched),
651
+ paths: bucket.paths,
652
+ files: matched,
653
+ source: 'tests',
654
+ description: bucket.description,
655
+ });
656
+ }
657
+ }
658
+ }
659
+ return suggestions;
660
+ }
661
+
528
662
  module.exports = {
529
663
  unknownGateKinds,
530
664
  signoffGateStatus,
@@ -534,10 +668,13 @@ module.exports = {
534
668
  readPhaseGates,
535
669
  gateCommand,
536
670
  gateChecks,
671
+ gateMatchesChangedFiles,
672
+ preflightTriggerChecks,
537
673
  recordGateFailures,
538
674
  isInfraFailure,
539
675
  detectGateCandidates,
540
676
  findGovernanceTests,
677
+ suggestPathGates,
541
678
  lintPhaseGates,
542
679
  attachCiRun,
543
680
  attachDeploy,
@@ -250,6 +250,22 @@ function importedSymbols(root, testFile, files) {
250
250
  const file = resolve(m[2]);
251
251
  if (file) for (const n of m[1].split(',').map((x) => x.trim().split(':')[0].trim()).filter(Boolean)) out.push({ name: n, path: norm(file) });
252
252
  }
253
+ // OXB-222-06 / OXB-222-11: infer CJS namespace require() member accesses (`const mod = require('./a.cjs'); mod.fn()`)
254
+ // Strip comments and string literals before scanning member accesses so e.g. `'.../oxe-alm-refine.cjs'` never matches `refine.cjs`.
255
+ const codeOnly = text
256
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
257
+ .replace(/\/\/[^\r\n]*/g, ' ')
258
+ .replace(/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g, ' ');
259
+ const BUILTIN_PROPS = new Set(['prototype', 'constructor', 'toString', 'valueOf', 'hasOwnProperty', 'keys', 'values', 'entries', 'length', 'cjs', 'mjs', 'js', 'ts', 'json', 'md']);
260
+ for (const m of text.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g)) {
261
+ const alias = m[1];
262
+ const file = resolve(m[2]);
263
+ if (!file) continue;
264
+ const accessRe = new RegExp(`(?<![A-Za-z0-9_$-])${alias.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.([A-Za-z_$][\\w$]*)\\b`, 'g');
265
+ for (const am of codeOnly.matchAll(accessRe)) {
266
+ if (am[1] && !BUILTIN_PROPS.has(am[1])) out.push({ name: am[1], path: norm(file) });
267
+ }
268
+ }
253
269
  return out;
254
270
  }
255
271
 
@@ -286,7 +302,17 @@ function packEntry(root, task, role, frozenFiles, frozenTests) {
286
302
  const moves = Array.isArray(role.moves) ? role.moves.map((m) => ({ from: norm(m.from), to: norm(m.to) })) : [];
287
303
  const exact = uniq([...(task.files || []).map(norm), ...deleted, ...created, ...edited, ...moves.flatMap((m) => [m.from, m.to])]).filter((f) => !frozenFiles.has(f));
288
304
  const symbols = [];
289
- for (const t of frozenTests) for (const s of importedSymbols(root, t, exact)) if (!symbols.some((x) => x.name === s.name && x.path === s.path)) symbols.push(s);
305
+ const pushSymbol = (s) => {
306
+ if (!s || typeof s !== 'object' || !s.name || !s.path) return;
307
+ const entrySym = { ...(s.kind ? { kind: String(s.kind) } : {}), name: String(s.name), path: norm(s.path) };
308
+ if (!symbols.some((x) => x.name === entrySym.name && x.path === entrySym.path)) symbols.push(entrySym);
309
+ };
310
+ for (const t of frozenTests) for (const s of importedSymbols(root, t, exact)) pushSymbol(s);
311
+ // OXB-222-06: preserve explicit symbols declared on tasks in role.json
312
+ for (const s of Array.isArray(task.symbols) ? task.symbols : []) pushSymbol(s);
313
+ for (const rt of Array.isArray(role.rawTasks) ? role.rawTasks : []) {
314
+ for (const s of Array.isArray(rt && rt.symbols) ? rt.symbols : []) pushSymbol(s);
315
+ }
290
316
  const editedClean = edited.filter((f) => !frozenFiles.has(f));
291
317
  const symbolsRemoved = [];
292
318
  for (const rt of Array.isArray(role.rawTasks) ? role.rawTasks : []) {
@@ -1162,7 +1188,20 @@ function expandRolePaths(root, ref, list) {
1162
1188
  return uniq(expanded);
1163
1189
  }
1164
1190
 
1165
- function build(inputs, ctx = {}) {
1191
+ function build(first, second = {}, third = {}) {
1192
+ let rawInputs = first;
1193
+ let ctx = second || {};
1194
+ if (typeof first === 'string' && Array.isArray(second)) {
1195
+ rawInputs = second;
1196
+ ctx = { ...(third || {}), root: first };
1197
+ }
1198
+ const inputs = (Array.isArray(rawInputs) ? rawInputs : []).map((entry, idx) => {
1199
+ if (entry && typeof entry === 'object' && entry.doc && typeof entry.file === 'string') return entry;
1200
+ if (entry && typeof entry === 'object' && Array.isArray(entry.tasks)) {
1201
+ return { file: `${entry.role || `role-${idx + 1}`}.role.json`, doc: entry };
1202
+ }
1203
+ return entry;
1204
+ });
1166
1205
  const root = ctx.root || process.cwd();
1167
1206
  const ref = ctx.ref || 'HEAD';
1168
1207
  const coupledRules = loadCoupledScope(root, ctx);
@@ -1380,6 +1419,27 @@ function build(inputs, ctx = {}) {
1380
1419
  warnings.push(...fsg.fileSizeHeadroomMessages(annotated.findings).warnings);
1381
1420
  }
1382
1421
  } catch { /* */ }
1422
+ // OXB-222-21: annotate empirical/heuristic `suggested_model_hint` + `routing_reason` while preserving any explicit `model_hint`.
1423
+ try {
1424
+ const scorecardMod = require('./oxe-scorecard.cjs');
1425
+ const histEvents = [];
1426
+ const evCandidates = [
1427
+ path.join(root, '.oxe', 'events', 'events.ndjson'),
1428
+ path.join(root, '.oxe', 'OXE-EVENTS.ndjson'),
1429
+ ];
1430
+ for (const evFile of evCandidates) {
1431
+ if (!fs.existsSync(evFile)) continue;
1432
+ for (const line of fs.readFileSync(evFile, 'utf8').split(/\r?\n/).filter(Boolean)) {
1433
+ try { histEvents.push(JSON.parse(line)); } catch { /* skip corrupt */ }
1434
+ }
1435
+ }
1436
+ const routingStats = scorecardMod.computeModelRoutingStats(histEvents);
1437
+ for (const t of plan.tasks) {
1438
+ const suggestion = scorecardMod.suggestModelHint(t, routingStats);
1439
+ t.suggested_model_hint = suggestion.suggested_model_hint;
1440
+ t.routing_reason = suggestion.routing_reason;
1441
+ }
1442
+ } catch { /* sugestão de roteamento auxiliar */ }
1383
1443
  // OXB-C25: the preflight needs `ready: true`; without it, execute stopped on execution_rationality:not_ready with an
1384
1444
  // empty gap list while plan lint said ok. The build's own checks decide it.
1385
1445
  pack.ready = errors.length === 0;
@@ -29,6 +29,105 @@ function spread(list, n) {
29
29
  return Array.from({ length: n }, (_, i) => list[Math.floor(((i + 0.5) * list.length) / n)]);
30
30
  }
31
31
 
32
+ /**
33
+ * OXB-222-07: Prioritizes mutants inside changed diff lines and declared task symbols before falling back
34
+ * to evenly spread sampling across the rest of the file.
35
+ */
36
+ function findSymbolLineRanges(source, symbolNames) {
37
+ const names = [...new Set((Array.isArray(symbolNames) ? symbolNames : []).map((s) => String(s || '').trim()).filter(Boolean))];
38
+ if (!names.length) return [];
39
+ const lines = String(source || '').split(/\r?\n/);
40
+ const ranges = [];
41
+ for (const name of names) {
42
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
43
+ const declRe = new RegExp(`(?:^|[^\\w$])(?:(?:async\\s+)?function\\s+${esc}\\b|(?:const|let|var)\\s+${esc}\\s*=|class\\s+${esc}\\b|${esc}\\s*:\\s*(?:async\\s+)?function\\b|${esc}\\s*\\([^)]*\\)\\s*\\{)`);
44
+ for (let i = 0; i < lines.length; i += 1) {
45
+ if (!declRe.test(lines[i])) continue;
46
+ let depth = 0;
47
+ let sawBrace = false;
48
+ let end = Math.min(lines.length - 1, i + 60);
49
+ for (let j = i; j < lines.length; j += 1) {
50
+ for (const ch of lines[j]) {
51
+ if (ch === '{') { depth += 1; sawBrace = true; }
52
+ else if (ch === '}') depth -= 1;
53
+ }
54
+ if (sawBrace && depth <= 0) { end = j; break; }
55
+ }
56
+ ranges.push([i + 1, end + 1]);
57
+ }
58
+ }
59
+ return ranges;
60
+ }
61
+
62
+ function prioritizeMutants(mutants, original, hints = {}) {
63
+ const list = Array.isArray(mutants) ? mutants : [];
64
+ const limit = Number(hints.limit) > 0 ? Math.floor(Number(hints.limit)) : list.length;
65
+ if (!list.length || limit <= 0) return [];
66
+ const changedSet = new Set((Array.isArray(hints.changedLines) ? hints.changedLines : []).map((n) => Number(n)).filter(Number.isFinite));
67
+ const ranges = findSymbolLineRanges(original, hints.symbols);
68
+ const inRange = (line) => ranges.some(([a, b]) => line >= a && line <= b);
69
+
70
+ const tier1 = []; // exact changed lines
71
+ const tier2 = []; // inside declared task symbol bodies
72
+ const tier3 = []; // rest of the file
73
+ for (const m of list) {
74
+ if (changedSet.has(m.line)) tier1.push(m);
75
+ else if (inRange(m.line)) tier2.push(m);
76
+ else tier3.push(m);
77
+ }
78
+ const picked = [];
79
+ for (const bucket of [tier1, tier2, tier3]) {
80
+ const remaining = limit - picked.length;
81
+ if (remaining <= 0) break;
82
+ if (!bucket.length) continue;
83
+ picked.push(...spread(bucket, remaining));
84
+ }
85
+ return picked;
86
+ }
87
+
88
+ function changedLinesByFile(root, baseRef = 'HEAD') {
89
+ const byFile = new Map();
90
+ try {
91
+ const r = spawnSync('git', ['diff', '-U0', baseRef], { cwd: root, encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
92
+ if (r.status !== 0 || !r.stdout) return byFile;
93
+ let cur = null;
94
+ for (const line of r.stdout.split(/\r?\n/)) {
95
+ if (line.startsWith('+++ b/')) { cur = norm(line.slice(6).trim()); continue; }
96
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
97
+ if (cur && hunk) {
98
+ const start = Number(hunk[1]);
99
+ const count = hunk[2] == null ? 1 : Number(hunk[2]);
100
+ if (!byFile.has(cur)) byFile.set(cur, []);
101
+ for (let k = 0; k < count; k += 1) byFile.get(cur).push(start + k);
102
+ }
103
+ }
104
+ } catch { /* ignore */ }
105
+ return byFile;
106
+ }
107
+
108
+ function packSymbolsByFile(root, options = {}) {
109
+ const byFile = new Map();
110
+ const addSym = (s) => {
111
+ if (!s || typeof s !== 'object' || !s.name || !s.path) return;
112
+ const f = norm(s.path);
113
+ if (!byFile.has(f)) byFile.set(f, []);
114
+ byFile.get(f).push(String(s.name));
115
+ };
116
+ if (Array.isArray(options.symbols)) for (const s of options.symbols) addSym(s);
117
+ const packPaths = [options.packPath, path.join(root, '.oxe', 'IMPLEMENTATION-PACK.json')].filter(Boolean);
118
+ for (const p of packPaths) {
119
+ try {
120
+ if (!fs.existsSync(p)) continue;
121
+ const pack = JSON.parse(fs.readFileSync(p, 'utf8'));
122
+ for (const t of Array.isArray(pack && pack.tasks) ? pack.tasks : []) {
123
+ for (const s of Array.isArray(t && t.symbols) ? t.symbols : []) addSym(s);
124
+ }
125
+ break;
126
+ } catch { /* ignore */ }
127
+ }
128
+ return byFile;
129
+ }
130
+
32
131
  function declares(declared, file) {
33
132
  return declared.some((d) => {
34
133
  if (d === file) return true;
@@ -145,6 +244,8 @@ async function measure(root, doc, options = {}) {
145
244
  const measurable = rows.filter((r) => !r.unmeasured).sort((a, b) => Number(b.risk === 'P0') - Number(a.risk === 'P0'));
146
245
  const files = [...new Set(measurable.flatMap((r) => r.targets))];
147
246
  const perFile = Math.max(1, Math.floor(max / Math.max(1, files.length)));
247
+ const diffLinesMap = changedLinesByFile(root, options.diffBase || 'HEAD');
248
+ const symbolsMap = packSymbolsByFile(root, options);
148
249
  const survived = [];
149
250
  let total = 0;
150
251
  for (const file of files) {
@@ -154,7 +255,12 @@ async function measure(root, doc, options = {}) {
154
255
  const original = fs.readFileSync(abs, 'utf8');
155
256
  const lines = original.split('\n');
156
257
  const usable = [];
157
- for (const m of spread(mutantsOf(original, Infinity), perFile * 2)) {
258
+ const candidates = prioritizeMutants(mutantsOf(original, Infinity), original, {
259
+ limit: perFile * 2,
260
+ symbols: symbolsMap.get(norm(file)) || [],
261
+ changedLines: diffLinesMap.get(norm(file)) || [],
262
+ });
263
+ for (const m of candidates) {
158
264
  if (usable.length >= perFile || total + usable.length >= max) break;
159
265
  const text = lines.map((l, i) => (i === m.line - 1 ? m.after : l)).join('\n');
160
266
  // A mutant that does not parse would be "killed" by any test.
@@ -211,4 +317,4 @@ async function measure(root, doc, options = {}) {
211
317
  }
212
318
  }
213
319
 
214
- module.exports = { measure, targetsOf, spread };
320
+ module.exports = { measure, targetsOf, spread, prioritizeMutants };
@@ -348,9 +348,13 @@ function runPreflight(projectRoot, options = {}) {
348
348
  const wantE2e = options.e2eImpact === true || options.e2eImpactOnly === true || pf.e2eImpact === true;
349
349
  const e2eImpact = wantE2e ? detectE2eImpact(rootAbs, { base, spawn, diffText: options.diffText }) : null;
350
350
 
351
- // 4. Design target CSS geometry risk alert (OXB-G14)
352
- const wantCssTargets = options.cssTargets !== false && pf.cssTargetCheck !== false && !options.e2eImpactOnly;
353
- const cssTargets = wantCssTargets ? detectCssTargetRisk(rootAbs, { base, spawn, diffText: options.diffText, targetsDir: pf.designTargetsDir }) : null;
351
+ // 4. Design target CSS geometry risk alert (OXB-G14, preset-aware via OXB-221-05)
352
+ const presetCfg = require('./oxe-presets.cjs').resolvePresetConfig(cfg);
353
+ const resolvedTargetsDir = pf.designTargetsDir || pf.cssTargetsDir
354
+ || (presetCfg.preflight && presetCfg.preflight.cssTargetsDir)
355
+ || (presetCfg.hasExplicitPreset ? null : path.join('src', 'design', 'targets'));
356
+ const wantCssTargets = options.cssTargets !== false && pf.cssTargetCheck !== false && !options.e2eImpactOnly && Boolean(resolvedTargetsDir);
357
+ const cssTargets = wantCssTargets ? detectCssTargetRisk(rootAbs, { base, spawn, diffText: options.diffText, targetsDir: resolvedTargetsDir }) : null;
354
358
 
355
359
  const checksOk = checkResults.every((r) => r.ok);
356
360
  const triggersOk = triggerResults.every((r) => r.ok);
@@ -372,6 +376,8 @@ function runPreflight(projectRoot, options = {}) {
372
376
 
373
377
  module.exports = {
374
378
  globMatch,
379
+ resolveDiffBase,
380
+ getChangedFiles,
375
381
  detectE2eImpact,
376
382
  detectCssTargetRisk,
377
383
  runPreflight,