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
@@ -0,0 +1,791 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 1.22.1 (OXB-221-09): Strangler Fig Slice 1 — ALM, Refine, Traceability, Metrics and `uiCardGaps`
5
+ * extracted from `bin/lib/oxe-operational.cjs` with explicit dependency injection (zero circular require).
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ const NON_UI_DOMAIN_LABEL_RE = /^(?:area-(?:desempenho|performance|perf|backend|infra(?:estrutura)?|dados|db|database|seguran[cç]a|security|arquitetura|architecture|ipc|runtime|terminal|git|ci|build|cli|core|engine)|desempenho|performance|perf|backend|infra(?:estrutura)?|seguran[cç]a|security|arquitetura|database|db)$/i;
12
+
13
+ /** A whole-word, accent-aware, case-insensitive match of `word` (glossary synonyms). */
14
+ function wholeWord(word) {
15
+ const esc = String(word).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
16
+ return new RegExp(`(^|[^\\p{L}\\p{N}])${esc}(?=$|[^\\p{L}\\p{N}])`, 'iu');
17
+ }
18
+
19
+ const refineLibCriteria = (md) => {
20
+ try { return require('../oxe-alm-refine.cjs').parseCriteria(md); } catch { return []; }
21
+ };
22
+
23
+ /** G34: what a UI card's spec still lacks (BRD-n, target, measures in the CAs, both themes, both densities). */
24
+ function criteriaOnlyReadSharedLocales(crit) {
25
+ if (!Array.isArray(crit) || !crit.length) return false;
26
+ const combined = crit.map((c) => String((c && c.text) || '')).join('\n');
27
+ if (!/\bshared\/locales(?:\/[^\s`'",)*]+)?/i.test(combined)) return false;
28
+ const PATH_RE = /\b(?:src|shared|app|mobile|packages|desktop|web|client|server)\/[\w./*{}-]+/gi;
29
+ const TEST_FILE_RE = /(^|\/)(?:tests?|__tests__|specs?|e2e|playwright)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/i;
30
+ for (const m of combined.matchAll(PATH_RE)) {
31
+ const p = m[0];
32
+ if (TEST_FILE_RE.test(p)) continue;
33
+ if (!/^shared\/locales(?:\/|$)/i.test(p)) return false;
34
+ }
35
+ const NON_LOCALE_EXT_RE = /\b[\w.-]+\.(?:tsx|jsx|css|scss|less|kt)\b/gi;
36
+ for (const m of combined.matchAll(NON_LOCALE_EXT_RE)) {
37
+ if (!/\.(?:test|spec)\.[cm]?[jt]sx?$/i.test(m[0])) return false;
38
+ }
39
+ return true;
40
+ }
41
+
42
+ function uiCardGaps(md, collected = {}, options = {}) {
43
+ const text = String(md || '');
44
+ const labels = (collected.labels || []).map((l) => String(l).toLowerCase());
45
+ const hasMarca = labels.includes('area-marca');
46
+ const hasVisualLabel = labels.some((l) => /^(?:area-marca|visual|polish|ui|design)$/i.test(l));
47
+ if (collected.kind === 'epic' && !hasMarca) return { isUi: false, gaps: [], epic_exempt: true };
48
+ let brandStrict = false;
49
+ if (options && options.projectRoot) {
50
+ const presetCfg = require('../oxe-presets.cjs').resolvePresetConfig(options.projectRoot);
51
+ const hasDesignTargets = fs.existsSync(path.join(options.projectRoot, 'src', 'design', 'targets'));
52
+ brandStrict = Boolean(presetCfg.ui && presetCfg.ui.brandGate);
53
+ if (!hasMarca && !hasVisualLabel && !brandStrict) {
54
+ const uiDirs = ['src/ui', 'src/styles', 'src/design', 'src/renderer', 'src/components', 'mobile/android'];
55
+ const hasUiTree = uiDirs.some((d) => fs.existsSync(path.join(options.projectRoot, d)));
56
+ if (!hasUiTree) return { isUi: false, gaps: [], no_ui_tree_exempt: true };
57
+ }
58
+ if (!hasMarca && !hasDesignTargets && !brandStrict) {
59
+ return { isUi: false, gaps: [], brand_gate_disabled_exempt: true };
60
+ }
61
+ }
62
+ const hasExplicitNonUiLabel = !hasMarca && labels.some((l) => NON_UI_DOMAIN_LABEL_RE.test(l));
63
+ const crit = refineLibCriteria(text);
64
+ const critText = crit.map((c) => String((c && c.text) || '')).join('\n');
65
+ const UI_PATHS = /\b(src\/(renderer|ui|styles|design|components)\/|mobile\/android\/[\w/.-]*\/ui\/)/;
66
+ const STRICT_UI_PATHS = /\b(src\/(ui|styles|design)\/|mobile\/android\/[\w/.-]*\/ui\/)/;
67
+ const isUi = hasMarca || (hasExplicitNonUiLabel ? STRICT_UI_PATHS.test(critText) : UI_PATHS.test(text));
68
+ if (!isUi) return { isUi: false, gaps: [] };
69
+ if (criteriaOnlyReadSharedLocales(crit)) return { isUi: false, gaps: [], locale_only_exempt: true };
70
+ const declaresNoBrd = /\b(?:sem BRD|BRD:\s*(?:nenhum|n\/a|—|-))\b/i.test(text);
71
+ const touchesStyleOrTokens = /\.(?:css|scss|less)\b|var\(--[\w-]+\)|--(?:bar|row|control|fs|radius|space)-|src\/(?:styles|design)\//i.test(text);
72
+ if (collected.kind === 'bug' && !hasVisualLabel && declaresNoBrd && !touchesStyleOrTokens) {
73
+ return { isUi: false, gaps: [], bug_non_visual_exempt: true };
74
+ }
75
+ if (!hasMarca && !brandStrict && !hasVisualLabel && !/\b(src\/(renderer|ui|styles|design)\/|mobile\/android\/[\w/.-]*\/ui\/)/.test(text)) {
76
+ const VISUAL_RE = /\b\d+(?:[.,]\d+)?\s*(?:px|dp|sp|rem|em)\b|var\(--[\w-]+\)|\.(?:css|scss|less)\b|\b(?:raio|altura|largura|fonte|espa[cç]amento|padding|margem|margin|borda|sombra|temas?|densidades?|alinhamento|geometria|tokens?|cores?|contraste|tamanho)\b|\bBRD-\d+\b/i;
77
+ if (!VISUAL_RE.test(text)) return { isUi: false, gaps: [], behavior_component_exempt: true };
78
+ }
79
+ const gaps = [];
80
+ if (!/\bBRD-\d+\b/.test(text) && !/\bsem BRD\b|\bBRD:\s*(nenhum|n\/a|—|-)|\bfun[cç][aã]o nova\b|\bnova fun[cç][aã]o\b/i.test(text)) gaps.push('qual é o BRD-n deste card? (a referência do rebranding; sem BRD, escreva "BRD: nenhum (função nova)")');
81
+ const target = /(\.brand-audit\/|playground|src\/[\w/.-]+\.(tsx?|css|kt|json)|mobile\/android\/[\w/.-]+\.kt|[\w/.-]+\.(png|fig|html)|https?:\/\/claude\.ai\/[\w/-]*artifact\/[\w-]+|\bartefato\s+[A-Za-z0-9]{12,})/.test(text);
82
+ if (!target) gaps.push('qual é o alvo aprovado (arquivo, playground ou artefato da marca)?');
83
+ const measured = crit.filter((c) => (
84
+ /\b\d+(?:[.,]\d+)?\s*(?:px|dp|sp|ms)\b|var\(--[\w-]+\)|--[a-z][\w-]+|Oxe(?:Radius|Theme|Space)\.\w+|\b(?:raio|altura|fonte|peso)\s+\d+|\bforced-colors\b/i.test(c.text)
85
+ || /\b(?:Highlight(?:Text)?|Canvas(?:Text)?)\b/.test(c.text)
86
+ ));
87
+ if (!crit.length || !measured.length) gaps.push('quais medidas os critérios conferem (altura, fonte, raio, cor como token)?');
88
+ if (!/(dois temas|ambos os temas|claro e (o )?escuro|escuro e (o )?claro|noite e (o )?dia|light and dark|dark and light)/i.test(text)) gaps.push('as medidas valem nos dois temas (claro e escuro)?');
89
+ if (!/(duas densidades|compacta e (a )?confortável|confortável e (a )?compacta|data-density|densidade)/i.test(text)) gaps.push('as medidas valem nas duas densidades (compacta e confortável)?');
90
+ return { isUi: true, gaps };
91
+ }
92
+
93
+ /** The refine moves its own stages (when mapped and in alm.track): refinement while writing, then ready or back to grooming. */
94
+ async function refineMove(lib, cfg, key, stage, options) {
95
+ if (!cfg.states[stage] || !cfg.track.includes(stage)) return { stage, skipped: true, why: !cfg.states[stage] ? `etapa "${stage}" sem estado em alm.states: nada movido` : `etapa "${stage}" fora de alm.track: nada movido` };
96
+ try {
97
+ const prov = lib.provider(cfg, options);
98
+ if (typeof prov.status === 'function') {
99
+ const live = await prov.status(key);
100
+ const liveStage = lib.STAGES.find((s) => cfg.states[s] && live && String(cfg.states[s]).toLowerCase() === String(live).toLowerCase()) || null;
101
+ const movable = ['intake', 'grooming', 'refinement'];
102
+ if (!liveStage || !movable.includes(liveStage)) return { stage, skipped: true, state: live, why: liveStage ? `o card está em "${live}" (${liveStage}): o refine só move cards antes de "pronto"` : `estado "${live}" sem etapa mapeada: nada movido` };
103
+ if (String(live).toLowerCase() === String(cfg.states[stage]).toLowerCase()) return { stage, state: live, changed: false };
104
+ if (options.dryRun) return { stage, planned: true, from: live, state: cfg.states[stage] };
105
+ } else if (options.dryRun) return { stage, planned: true, state: cfg.states[stage] };
106
+ const r = await prov.transition(key, cfg.states[stage]);
107
+ return { stage, state: r.status, changed: r.changed };
108
+ } catch (err) { return { stage, error: err.message }; }
109
+ }
110
+
111
+ function createAlmRefineRuntime(deps) {
112
+ const {
113
+ readProjectConfig,
114
+ resolveRuntimeArtifactPaths,
115
+ readTextIfExists,
116
+ writeTextAtomic,
117
+ appendEvent,
118
+ readEvents,
119
+ readRunState,
120
+ readPlanJsonDoc,
121
+ activeProgramPhase,
122
+ prdPathFor,
123
+ grillPaths,
124
+ runtimeProgramPhaseEdit,
125
+ detectMergedPrs,
126
+ } = deps;
127
+
128
+ /**
129
+ * `oxe-cc alm status|push|sync|move|link|defect`. Async (network). With `dryRun` nothing is written anywhere.
130
+ */
131
+ async function runtimeAlm(projectRoot, activeSession, options = {}) {
132
+ const lib = require('../oxe-alm.cjs');
133
+ const config = readProjectConfig(projectRoot) || {};
134
+ const cfg = lib.almConfig(config, { defaultProgram: path.basename(path.resolve(projectRoot)) });
135
+ const paths = resolveRuntimeArtifactPaths(projectRoot, activeSession);
136
+ const programDir = paths.programDir || path.join(projectRoot, '.oxe', 'program');
137
+ const env = options.env || process.env;
138
+ const problems = lib.checkConfig(cfg, env);
139
+ if ((options.action === 'status' || !options.action) && options.ref) {
140
+ if (!cfg) return { configured: false, key: options.ref, why: 'ALM não configurado aqui' };
141
+ const item = lib.resolveItem(programDir, cfg, options.ref);
142
+ if (!item) throw new Error(`${options.ref}: não é uma chave deste projeto (${cfg.provider === 'jira' ? `${cfg.p.project}-n` : 'número'})`);
143
+ const prov = lib.provider(cfg, { http: options.http, env, sleep: options.sleep, readOnly: true });
144
+ const state = typeof prov.status === 'function' && !prov.deferred ? await prov.status(item.key) : null;
145
+ const stage = lib.STAGES.find((s) => cfg.states[s] && state && String(cfg.states[s]).toLowerCase() === String(state).toLowerCase()) || null;
146
+ return { configured: true, key: item.key, ref: item.direct ? null : item.ref, state, stage };
147
+ }
148
+ if (options.action === 'status' || !options.action) {
149
+ const st = lib.readState(programDir);
150
+ return { configured: Boolean(cfg), provider: cfg ? cfg.provider : 'none', transport: cfg ? cfg.transport : null, problems, links: lib.links(programDir).size, pending: (st.pending || []).length, queue: lib.readQueue(programDir).ops.length, last_sync: st.last_sync || null, auto: cfg ? cfg.auto : false };
151
+ }
152
+ if (options.action === 'queue') {
153
+ return { provider: cfg ? cfg.provider : 'none', transport: cfg ? cfg.transport : null, ops: lib.pendingOps(programDir) };
154
+ }
155
+ if (!cfg) throw new Error('ALM não configurado: defina "alm": { "provider": "jira" | "azure-devops", … } no .oxe/config.json (sem ALM, o OXE segue normalmente)');
156
+ if (options.action === 'list') {
157
+ const states = String(options.state || '').split(',').map((s) => s.trim()).filter(Boolean);
158
+ if (!states.length) throw new Error('uso: oxe-cc alm list --state "<estado do quadro>"[,…] [--with-prs] [--json]');
159
+ if (problems.length) throw new Error(`ALM: ${problems.join('; ')}`);
160
+ const prov = lib.provider(cfg, { http: options.http, env, sleep: options.sleep, readOnly: true });
161
+ if (prov.deferred) throw new Error('alm list lê o quadro pela API REST; com alm.transport "mcp", consulte pela ferramenta MCP da sessão');
162
+ if (typeof prov.searchByStates !== 'function') throw new Error(`${cfg.provider}: alm list ainda não suportado`);
163
+ const cards = await prov.searchByStates(states);
164
+ if (options.withPrs) {
165
+ const byKey = require('../oxe-alm-prs.cjs').mergedPrsByKey(projectRoot, cfg, { ghSpawn: options.ghSpawn, repo: options.repo });
166
+ for (const card of cards) card.prs = byKey.get(String(card.key).toUpperCase()) || [];
167
+ }
168
+ return { states, count: cards.length, cards, with_prs: Boolean(options.withPrs) };
169
+ }
170
+ if (options.action === 'pr-merged' && !options.apply) options = { ...options, dryRun: true };
171
+ const dryRun = lib.isDry(cfg, options);
172
+ if (problems.length && !dryRun) throw new Error(`ALM: ${problems.join('; ')}`);
173
+ const net = { http: options.http, env, sleep: options.sleep, provider: options.provider, retries: options.retries, dryRun, apply: options.apply, readOnlyLookup: dryRun && !problems.length };
174
+ const phase = activeProgramPhase(projectRoot, activeSession);
175
+ const WRITES = ['push', 'sync', 'move', 'defect', 'ack', 'link', 'label', 'version', 'summary', 'supersede', 'pr-merged'];
176
+ const writes = WRITES.includes(options.action) || (options.action === 'pending' && options.sub === 'apply');
177
+ if ((writes || options.action === 'comment') && !dryRun && !options.auto) lib.warnApply(cfg, options);
178
+ if (writes && !dryRun) {
179
+ if (!lib.isWriter(cfg, env)) throw lib.writerError(cfg);
180
+ if (['push', 'sync', 'defect', 'pr-merged'].includes(options.action) && !options.noLock) {
181
+ return lib.withWriteLock(programDir, () => runtimeAlm(projectRoot, activeSession, { ...options, noLock: true }));
182
+ }
183
+ }
184
+ if (options.action === 'comment') {
185
+ const ref = /^T\d+$/i.test(options.ref || '') ? lib.taskRef(phase ? phase.id : null, options.ref.toUpperCase()) : options.ref;
186
+ return lib.comment(programDir, cfg, ref, options.text || options.comment, net);
187
+ }
188
+ if (options.action === 'pr-merged') {
189
+ const prsLib = require('../oxe-alm-prs.cjs');
190
+ const out = await prsLib.prMerged(projectRoot, programDir, cfg, lib, { pr: options.pr, repo: options.repo, ghSpawn: options.ghSpawn, apply: !dryRun, net, prData: options.prData });
191
+ if (!out.dry_run) appendEvent(projectRoot, activeSession, { type: 'AlmPrMerged', payload: { pr: out.pr, moved: out.moved.map((m) => m.key), commented: out.commented, bare: out.bare, errors: out.errors } });
192
+ return out;
193
+ }
194
+ if (options.action === 'ack') {
195
+ if (!options.ref) throw new Error('uso: oxe-cc alm ack <id-da-operação|US-n|Fn-Tn> [--key <chave>] [--url <url>] [--error "…"]');
196
+ const ref = /^T\d+$/i.test(options.ref) ? lib.taskRef(phase ? phase.id : null, options.ref.toUpperCase()) : options.ref;
197
+ const out = lib.ack(programDir, cfg, ref, { key: options.key, url: options.url, error: options.error, adopted: options.adopted });
198
+ if (out.done) appendEvent(projectRoot, activeSession, { type: 'AlmAcked', payload: { id: out.id, key: options.key || null } });
199
+ return out;
200
+ }
201
+ if (options.action === 'push') {
202
+ const prdFile = prdPathFor(projectRoot, activeSession);
203
+ const prd = fs.existsSync(prdFile) ? require('../oxe-prd.cjs').readPrd(prdFile) : null;
204
+ const doc = readPlanJsonDoc(projectRoot, activeSession).doc;
205
+ const wantStories = options.stories !== false;
206
+ const wantTasks = options.tasks !== false;
207
+ const title = (() => { const m = prd && /^#\s+(?:PRD\s+[—-]\s+)?(.+)$/m.exec(readTextIfExists(prdFile) || ''); return m ? m[1].trim() : null; })();
208
+ const out = await lib.push(programDir, cfg, {
209
+ stories: wantStories && prd ? prd.stories : [],
210
+ tasks: wantTasks && doc ? doc.tasks || [] : [],
211
+ phase: phase ? phase.id : (doc && doc.phase) || null,
212
+ epicTitle: title && !/^\(/.test(title) ? title : null,
213
+ dryRun,
214
+ rebuild: Boolean(options.rebuildLedger),
215
+ firstPush: Boolean(options.firstPush),
216
+ }, net);
217
+ if (!dryRun) appendEvent(projectRoot, activeSession, { type: 'AlmPushed', payload: { created: out.created.length, reused: out.reused.length, failed: out.failed.length } });
218
+ return { provider: cfg.provider, dry_run: dryRun, ...out };
219
+ }
220
+ if (options.action === 'sync') {
221
+ if (!dryRun) { try { detectMergedPrs(projectRoot, activeSession, readEvents(projectRoot, activeSession), options); } catch { /* sem gh: segue */ } }
222
+ const events = readEvents(projectRoot, activeSession);
223
+ const links = lib.links(programDir);
224
+ const doc = readPlanJsonDoc(projectRoot, activeSession).doc;
225
+ const phaseId = phase ? phase.id : (doc && doc.phase) || null;
226
+ const refsOfPhase = (ph) => [...links.keys()].filter((ref) => (ph ? ref.startsWith(`${ph}-`) : /^(F\d+-)?T\d+/.test(ref)) || /^US-/.test(ref));
227
+ const releasedEnv = config.alm && typeof config.alm.released_env === 'string' ? config.alm.released_env : null;
228
+ const out = await lib.sync(programDir, cfg, events, { phase: phaseId, refsOfPhase, releasedEnv }, net);
229
+ return { provider: cfg.provider, dry_run: dryRun, ...out };
230
+ }
231
+ if (options.action === 'move') {
232
+ const ref = /^T\d+$/i.test(options.ref || '') ? lib.taskRef(phase ? phase.id : null, options.ref.toUpperCase()) : options.ref;
233
+ return lib.move(programDir, cfg, ref, options.stage, { ...net, comment: options.comment });
234
+ }
235
+ if (options.action === 'label') return lib.labelItem(programDir, cfg, options.ref, options.add, { ...net, remove: options.remove });
236
+ if (options.action === 'pending') {
237
+ if (options.sub !== 'apply') return { pending: lib.listPending(projectRoot) };
238
+ const out = await lib.applyPending(projectRoot, programDir, cfg, net);
239
+ if (!dryRun) appendEvent(projectRoot, activeSession, { type: 'AlmPendingApplied', payload: { applied: out.applied.length, failed: out.failed.length } });
240
+ let synced = null;
241
+ try { synced = await runtimeAlm(projectRoot, activeSession, { ...options, action: 'sync', noLock: false }); } catch (err) { synced = { error: err.message }; }
242
+ return { dry_run: dryRun, ...out, sync: synced };
243
+ }
244
+ if (options.action === 'supersede') {
245
+ const out = await lib.supersede(programDir, cfg, options.ref, options.newKeys, { ...net, comment: options.comment, closeTo: options['close-to'] || options.closeTo, noClose: Boolean(options.noClose) });
246
+ if (out.applied) appendEvent(projectRoot, activeSession, { type: 'AlmSuperseded', payload: { key: out.key, by: out.by, link_type: out.link_type, status: out.status } });
247
+ return { dry_run: dryRun, ...out };
248
+ }
249
+ if (options.action === 'summary') return { dry_run: dryRun, ...(await lib.setItemSummary(programDir, cfg, options.ref, options.summary, { ...net, comment: options.comment })) };
250
+ if (options.action === 'version') return { dry_run: dryRun, ...(await lib.setItemVersion(programDir, cfg, options.ref, options.version, { ...net, comment: options.comment })) };
251
+ if (options.action === 'link' && options.relates) return lib.relateItems(programDir, cfg, options.ref, options.relates, net);
252
+ if (options.action === 'link' && options.pr) {
253
+ return lib.linkPr(programDir, cfg, options.ref, { pr: options.pr, repo: options.repo || (config.alm && config.alm.docs && config.alm.docs.repo) || null, title: options.title }, net);
254
+ }
255
+ if (options.action === 'link') {
256
+ if (!options.ref || !options.key) throw new Error('uso: oxe-cc alm link <US-n|Tn> <chave> · oxe-cc alm link <chave> --pr <n> [--repo <url>]');
257
+ const ref = /^T\d+$/i.test(options.ref) ? lib.taskRef(phase ? phase.id : null, options.ref.toUpperCase()) : options.ref;
258
+ let prev = null;
259
+ try {
260
+ for (const line of fs.readFileSync(path.join(programDir, 'alm-links.ndjson'), 'utf8').split(/\r?\n/)) {
261
+ let r = null;
262
+ try { r = JSON.parse(line); } catch { r = null; }
263
+ if (r && r.ref === ref) prev = { ...(prev || {}), ...r };
264
+ }
265
+ } catch { prev = null; }
266
+ if (prev) delete prev.at;
267
+ if (options.kind && !['bug', 'task', 'story', 'epic'].includes(String(options.kind))) throw new Error(`--kind ${options.kind}: use bug | task | story | epic`);
268
+ if (options.cr && !require('../oxe-change.cjs').listChanges(programDir).some((c) => c.id === options.cr)) throw new Error(`${options.cr}: CR inexistente (oxe-cc runtime feedback list)`);
269
+ const kind = options.kind ? String(options.kind) : prev && prev.kind ? prev.kind : /^US-/.test(ref) ? 'story' : 'task';
270
+ const rec = { ...(prev || {}), ref, key: options.key, kind, provider: cfg.provider, manual: true, ...(options.cr ? { cr: String(options.cr) } : {}) };
271
+ if (!dryRun) { lib.addLink(programDir, rec); lib.dropEnsure(programDir, ref); }
272
+ return { ref, key: options.key, kind: rec.kind, ...(rec.cr ? { cr: rec.cr } : {}), dry_run: dryRun };
273
+ }
274
+ if (options.action === 'defect') {
275
+ const ref = options.ref || `BUG-${Date.now().toString(36).toUpperCase()}`;
276
+ if (options.cr && !require('../oxe-change.cjs').listChanges(programDir).some((c) => c.id === options.cr)) throw new Error(`${options.cr}: CR inexistente (oxe-cc runtime feedback list)`);
277
+ return lib.reportDefect(programDir, cfg, { ref, title: options.title || 'defeito', description: options.description, origin: options.origin, cr: options.cr }, net);
278
+ }
279
+ throw new Error(`alm ${options.action}: ação desconhecida (status | push | sync | move | link | defect | comment | queue | ack)`);
280
+ }
281
+
282
+ /** `oxe-cc alm refine import <KEY…> [--risk P2] [--phase Fn] [--dry-run] --by <papel>`. */
283
+ function runtimeAlmRefineImport(projectRoot, activeSession, options = {}) {
284
+ const refine = require('../oxe-alm-refine.cjs');
285
+ const specEdit = require('../oxe-spec-edit.cjs');
286
+ const changeLib = require('../oxe-change.cjs');
287
+ const keysAll = (options.keys || []).map((k) => String(k).toUpperCase());
288
+ const d = refine.dirs(projectRoot);
289
+ const catalog = refine.discoverProgramCatalog(projectRoot, { activeSession, programRoots: options.programRoots || null });
290
+ let targetRoot = projectRoot;
291
+ let targetSession = activeSession;
292
+ let targetSlug = null;
293
+ let explicitTarget = null;
294
+ if (options.spec) {
295
+ explicitTarget = refine.resolveProgramSpec(projectRoot, activeSession, options.spec, { catalogCache: catalog, programRoots: options.programRoots || null });
296
+ if (!explicitTarget || !explicitTarget.specPath) {
297
+ throw new Error(`--spec "${options.spec}" não encontrado ou sem SPEC.md`);
298
+ }
299
+ targetRoot = explicitTarget.root;
300
+ targetSession = targetRoot === path.resolve(projectRoot) ? activeSession : null;
301
+ targetSlug = targetRoot !== path.resolve(projectRoot) ? explicitTarget.slug : null;
302
+ } else if (keysAll.length) {
303
+ const resolvedTargets = [];
304
+ for (const key of keysAll) {
305
+ const mdPath = path.join(d.specs, `${key}.md`);
306
+ if (!fs.existsSync(mdPath)) continue;
307
+ const mdText = fs.readFileSync(mdPath, 'utf8');
308
+ const r = refine.resolveCardProgram(projectRoot, activeSession, { key, md: mdText, catalogCache: catalog, programRoots: options.programRoots || null });
309
+ if (r && r.entry && r.matchedBy !== 'dir_default') resolvedTargets.push(r.entry);
310
+ }
311
+ const distinctRoots = [...new Set(resolvedTargets.map((e) => e.root))];
312
+ if (distinctRoots.length > 1) {
313
+ throw new Error(`os cards pertencem a programas diferentes (${[...new Set(resolvedTargets.map((e) => e.slug))].join(', ')}): informe --spec <programa|caminho> ou rode por card`);
314
+ }
315
+ if (distinctRoots.length === 1 && distinctRoots[0] !== path.resolve(projectRoot)) {
316
+ explicitTarget = resolvedTargets[0];
317
+ targetRoot = explicitTarget.root;
318
+ targetSession = null;
319
+ targetSlug = explicitTarget.slug;
320
+ }
321
+ }
322
+ const paths = resolveRuntimeArtifactPaths(targetRoot, targetSession);
323
+ const specPath = (explicitTarget && explicitTarget.specPath) || paths.spec;
324
+ if (!specPath || !fs.existsSync(specPath)) throw new Error('SPEC.md ausente: o import leva os critérios do card para a SPEC do programa (/oxe-spec primeiro)');
325
+ if (!options.dryRun && !options.by) throw new Error('o import emenda a SPEC: informe --by <papel>');
326
+ let specText = fs.readFileSync(specPath, 'utf8');
327
+ const programDir = (explicitTarget && explicitTarget.programDir) || paths.programDir || path.join(targetRoot, '.oxe', 'program');
328
+ const results = [];
329
+ let program = null;
330
+ try { program = require('../oxe-program.cjs').readProgram(programDir); } catch { program = null; }
331
+ const phases = (program && program.phases) || [];
332
+ const frozen = (ph) => Boolean(ph) && (['executing', 'verifying', 'closed'].includes(ph.status) || Boolean(ph.run_id));
333
+ const phaseOfA = (a) => phases.find((ph) => (ph.acceptance || []).includes(a)) || null;
334
+ const activePh = program && program.active_phase ? phases.find((ph) => ph.id === String(program.active_phase).toUpperCase()) || null : null;
335
+ const relSpec = path.relative(projectRoot, specPath).replace(/\\/g, '/');
336
+ if (options.phase) {
337
+ const target = phases.find((ph) => ph.id === String(options.phase).toUpperCase());
338
+ if (target && frozen(target)) {
339
+ const cas = keysAll.join(', ');
340
+ return {
341
+ dry_run: true,
342
+ refused: true,
343
+ spec: relSpec,
344
+ ...(targetSlug ? { program: targetSlug } : {}),
345
+ reason: `a fase ${target.id} está ${target.status}${target.run_id ? ' (com run)' : ''}: os arquivos dela estão congelados e nada foi escrito. Critério novo entra por CR nesta fase ou numa fase posterior`,
346
+ commands: [
347
+ `oxe-cc runtime feedback --class new_scope --summary "critérios dos cards refinados ${cas}" --by <papel>`,
348
+ `oxe-cc alm refine import ${keysAll.join(' ')}${options.spec ? ` --spec ${options.spec}` : ''} --phase <fase ainda não iniciada> --by <papel>`,
349
+ ],
350
+ results: [],
351
+ };
352
+ }
353
+ }
354
+ const specCriteria = new Map(require('../oxe-spec-check.cjs').criteria(specText).list.map((c) => [c.id, c]));
355
+ const norm = (t) => String(t || '').replace(/\([A-Z][A-Z0-9]+-\d+\)/g, '').replace(/[`*_]/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
356
+ for (const key of keysAll) {
357
+ const specFile = path.join(d.specs, `${key}.md`);
358
+ if (!fs.existsSync(specFile)) { results.push({ key, error: `sem spec refinado: oxe-cc alm refine ${key}` }); continue; }
359
+ let md = fs.readFileSync(specFile, 'utf8');
360
+ const criteria = refine.parseCriteria(md);
361
+ const existing = specEdit.criteriaIds(specText);
362
+ const added = new Map();
363
+ const out = { key, criteria_count: criteria.length, added: [], linked: [], problems: [] };
364
+ if (!criteria.length) {
365
+ out.problems.push(`0 critérios lidos em ${key}.md (esperado "1. **CA-n** — Dado … · Teste: …" ou "- CA-n — …")`);
366
+ }
367
+ for (const c of criteria) {
368
+ if (c.spec_id) {
369
+ if (c.spec_program) {
370
+ const critProg = refine.resolveProgramSpec(projectRoot, activeSession, c.spec_program, { catalogCache: catalog, programRoots: options.programRoots || null });
371
+ if (!critProg || path.resolve(critProg.root) !== path.resolve(targetRoot)) {
372
+ out.linked.push({ ca: c.id, a: `${c.spec_program}:${c.spec_id}` });
373
+ continue;
374
+ }
375
+ }
376
+ if (!existing.includes(c.spec_id)) out.problems.push(`${c.id} aponta para ${c.spec_id}, que não existe na SPEC${targetSlug ? ` de ${targetSlug}` : ''}`);
377
+ else {
378
+ const row = String(specText).split(/\r?\n/).find((l) => new RegExp(`^\\|\\s*\\**${c.spec_id}\\**\\s*\\|`).test(l)) || '';
379
+ const ph = phaseOfA(c.spec_id);
380
+ const isFrozen = frozen(ph);
381
+ if (!row.includes(key)) {
382
+ out.problems.push(isFrozen
383
+ ? `${c.spec_id} (de ${c.id}) não cita ${key}, e a fase ${ph.id} está ${ph.status}: registre a ligação por CR — oxe-cc runtime feedback --class spec_gap --criteria ${c.spec_id} --summary "${c.spec_id} é o ${c.id} de ${key}" --additive --by <papel>`
384
+ : `${c.spec_id} (de ${c.id}) não cita ${key} na SPEC — emende com oxe-cc spec amend ${c.spec_id} --append "(${key})"`);
385
+ }
386
+ const a = specCriteria.get(c.spec_id);
387
+ if (a && norm(a.text) && norm(c.text) && norm(a.text) !== norm(c.text)) {
388
+ out.proposals = out.proposals || [];
389
+ out.proposals.push(isFrozen
390
+ ? { ca: c.id, a: c.spec_id, frozen: true, command: `oxe-cc runtime feedback --class spec_gap --criteria ${c.spec_id} --amend-to <N> --summary "${key} ${c.id}: ${c.text.slice(0, 80)}" --by <papel>`, why: `${c.spec_id} pertence à fase ${ph.id} (${ph.status}): o teste congelado dela ganha uma versão nova (vN), não é trocado` }
391
+ : { ca: c.id, a: c.spec_id, frozen: false, command: `oxe-cc spec amend ${c.spec_id} --text "${c.text.replace(/"/g, '\\"').slice(0, 160)} (${key})" --by <papel> --reason "alm refine ${key} ${c.id}"`, why: `o ${c.id} do card diz outra coisa que o ${c.spec_id} da SPEC` });
392
+ }
393
+ out.linked.push({ ca: c.id, a: c.spec_id });
394
+ }
395
+ continue;
396
+ }
397
+ if (!c.test || refine.TBC_RE.test(c.test)) { out.problems.push(`${c.id} sem teste: não vira critério da SPEC (rode o lint do refine)`); continue; }
398
+ const max = [...existing, ...added.values()].filter((x) => /^A\d+$/.test(x)).reduce((m, x) => Math.max(m, Number(x.slice(1))), 0);
399
+ const id = `A${max + 1}`;
400
+ try {
401
+ const edit = specEdit.addCriterion(specText, id, { text: `${c.text} (${key})`, verify: c.test, risk: c.risk || options.risk });
402
+ specText = edit.text;
403
+ added.set(c.id, id);
404
+ out.added.push({ ca: c.id, a: id, row: edit.after });
405
+ } catch (err) { out.problems.push(`${c.id}: ${err.message}`); }
406
+ }
407
+ if (!options.dryRun && added.size) {
408
+ md = refine.setSpecIds(md, added, targetSlug ? { program: targetSlug } : {});
409
+ fs.writeFileSync(specFile, md);
410
+ for (const a of out.added) changeLib.appendNdjson(changeLib.changesFile(programDir), { kind: 'spec_edit', action: 'add_criterion', id: a.a, by: options.by, reason: `alm refine import ${key} ${a.ca}`, origin: 'alm_refine', at: new Date().toISOString(), after: a.row });
411
+ }
412
+ results.push(out);
413
+ }
414
+ let assignedPhase = null;
415
+ let phaseWarning = null;
416
+ const addedIds = results.flatMap((r) => (r.added || []).map((a) => a.a));
417
+ if (!options.dryRun && addedIds.length) {
418
+ writeTextAtomic(specPath, specText);
419
+ appendEvent(targetRoot, targetSession, { type: 'SpecEdited', payload: { action: 'alm_refine_import', keys: results.map((r) => r.key), added: addedIds } });
420
+ const targetPhaseId = options.phase
421
+ ? String(options.phase).toUpperCase()
422
+ : (activePh && !frozen(activePh) ? activePh.id : null);
423
+ if (targetPhaseId) {
424
+ try {
425
+ runtimeProgramPhaseEdit(targetRoot, targetSession, { phase: targetPhaseId, addAcceptance: addedIds.join(','), by: options.by, reason: `alm refine import ${results.map((r) => r.key).join(', ')}` });
426
+ assignedPhase = targetPhaseId;
427
+ } catch (err) {
428
+ if (options.phase) {
429
+ results.push({ key: '(fase)', problems: [`os critérios entraram na SPEC, mas não na fase ${targetPhaseId}: ${err.message}`], added: [], linked: [] });
430
+ } else {
431
+ phaseWarning = `critério(s) ${addedIds.join(', ')} adicionado(s) na SPEC sem fase ("fase -"): ${err.message}`;
432
+ }
433
+ }
434
+ } else if (program) {
435
+ phaseWarning = `critério(s) ${addedIds.join(', ')} adicionado(s) na SPEC sem fase ("fase -")${activePh ? ` porque a fase ativa ${activePh.id} está ${activePh.status}` : ''} — vincule à fase (oxe-cc runtime program phase edit ${activePh ? activePh.id : '<Fn>'} --add-acceptance ${addedIds.join(',')} --by ${options.by || '<papel>'} --reason "…" ou via --phase <Fn> / CR) antes de plan append`;
436
+ }
437
+ }
438
+ return {
439
+ dry_run: Boolean(options.dryRun),
440
+ spec: relSpec,
441
+ ...(targetSlug ? { program: targetSlug } : {}),
442
+ ...(assignedPhase ? { phase: assignedPhase } : {}),
443
+ ...(phaseWarning ? { phase_warning: phaseWarning } : {}),
444
+ results,
445
+ };
446
+ }
447
+
448
+ /** The snapshot oxe-trace.cjs builds the graph from: every artifact's own ids and references, read-only. */
449
+ function traceSnapshot(projectRoot, activeSession) {
450
+ const paths = resolveRuntimeArtifactPaths(projectRoot, activeSession);
451
+ const config = readProjectConfig(projectRoot) || {};
452
+ const programDir = paths.programDir || path.join(projectRoot, '.oxe', 'program');
453
+ const prdLib = require('../oxe-prd.cjs');
454
+ const specCheck = require('../oxe-spec-check.cjs');
455
+ const refine = require('../oxe-alm-refine.cjs');
456
+ const almLib = require('../oxe-alm.cjs');
457
+ const prdFile = prdPathFor(projectRoot, activeSession);
458
+ const prd = fs.existsSync(prdFile) ? prdLib.readPrd(prdFile) : null;
459
+ const specText = readTextIfExists(paths.spec) || '';
460
+ let doc = null;
461
+ try { doc = readPlanJsonDoc(projectRoot, activeSession).doc; } catch { doc = null; }
462
+ const cardSpecs = new Map();
463
+ const specsDir = refine.dirs(projectRoot).specs;
464
+ if (fs.existsSync(specsDir)) for (const f of fs.readdirSync(specsDir).filter((x) => /\.md$/.test(x))) cardSpecs.set(f.replace(/\.md$/, ''), refine.parseCriteria(fs.readFileSync(path.join(specsDir, f), 'utf8')));
465
+ let almCfg = null;
466
+ try { almCfg = almLib.almConfig(config, { defaultProgram: path.basename(path.resolve(projectRoot)) }); } catch { almCfg = null; }
467
+ let run = null;
468
+ try { run = readRunState(projectRoot, activeSession); } catch { run = null; }
469
+ const phase = activeProgramPhase(projectRoot, activeSession);
470
+ return {
471
+ stories: prd ? prd.stories : [],
472
+ criteria: specCheck.criteria(specText).list,
473
+ requirements: specCheck.requirements(specText),
474
+ decisions: require('../oxe-decisions.cjs').list(programDir),
475
+ rfcs: require('../oxe-rfc.cjs').list(projectRoot),
476
+ tasks: (doc && doc.tasks) || [],
477
+ tests: (doc && doc.acceptance_tests) || [],
478
+ changes: require('../oxe-change.cjs').listChanges(programDir),
479
+ links: almLib.links(programDir),
480
+ knownFailureItems: (() => { try { return new Set(require('../oxe-known-failures.cjs').listAll(projectRoot, programDir).filter((k) => !k.expired).map((k) => String(k.item).toUpperCase())); } catch { return new Set(); } })(),
481
+ cardSpecs,
482
+ checks: (run && run.verification_check_results) || [],
483
+ phase: phase ? phase.id : (doc && doc.phase) || null,
484
+ phaseCriteria: phase && Array.isArray(phase.acceptance) && phase.acceptance.length ? [...phase.acceptance, ...require('../oxe-criteria-ids.cjs').standingAcceptance(projectRoot)] : null,
485
+ almConfigured: Boolean(almCfg),
486
+ storiesSource: almCfg ? almCfg.stories_source : 'prd',
487
+ cardKeysOf: prdLib.cardKeys,
488
+ _cfg: almCfg,
489
+ _config: config,
490
+ _programDir: programDir,
491
+ };
492
+ }
493
+
494
+ /** alm.trace_gate: the traceability orphans in the gates. */
495
+ function traceGateFindings(projectRoot, activeSession, stage) {
496
+ const config = readProjectConfig(projectRoot) || {};
497
+ const mode = config.alm && ['warn', 'close', 'strict'].includes(config.alm.trace_gate) ? config.alm.trace_gate : null;
498
+ if (!mode) return { errors: [], warnings: [], mode: null };
499
+ const graph = require('../oxe-trace.cjs').build(traceSnapshot(projectRoot, activeSession));
500
+ const blocking = mode === 'strict' || (mode === 'close' && stage === 'close');
501
+ const lines = graph.orphans.map((o) => `rastreabilidade: ${o.kind} ${o.id}: ${o.why} — ${o.fix}`);
502
+ return blocking ? { errors: lines, warnings: [], mode } : { errors: [], warnings: lines, mode };
503
+ }
504
+
505
+ /** `oxe-cc alm intake | doctor | version ensure | usage`. */
506
+ async function runtimeAlmAdmin(projectRoot, activeSession, options = {}) {
507
+ const lib = require('../oxe-alm.cjs');
508
+ const admin = require('../oxe-alm-admin.cjs');
509
+ if (options.action === 'usage') return admin.usageReport(projectRoot);
510
+ const config = readProjectConfig(projectRoot) || {};
511
+ const cfg = lib.almConfig(config, { defaultProgram: path.basename(path.resolve(projectRoot)) });
512
+ if (!cfg) throw new Error('ALM não configurado: veja o exemplo em oxe/templates/CONFIG.md (seção ALM) ou rode /oxe-alm setup');
513
+ if (cfg.provider !== 'jira') throw new Error(`alm ${options.action}: por enquanto só Jira`);
514
+ const env = options.env || process.env;
515
+ const problems = lib.checkConfig(cfg, env);
516
+ const offlineIntake = options.action === 'intake' && lib.isDry(cfg, options) && problems.length > 0;
517
+ if (problems.length && !offlineIntake) throw new Error(`ALM: ${problems.join('; ')}`);
518
+ if (offlineIntake) options = { ...options, offline: true };
519
+ if (options.action === 'doctor') return admin.doctor(lib.jiraRest(cfg, { ...options, readOnly: true }), cfg);
520
+ options = { ...options, dryRun: lib.isDry(cfg, options) };
521
+ const rest = lib.jiraRest(cfg, options);
522
+ if (!options.dryRun && !lib.isWriter(cfg, env)) throw lib.writerError(cfg);
523
+ if (!options.dryRun) lib.warnApply(cfg, options);
524
+ const paths = resolveRuntimeArtifactPaths(projectRoot, activeSession);
525
+ const programDir = paths.programDir || path.join(projectRoot, '.oxe', 'program');
526
+ if (options.action === 'version') return admin.versionEnsure(rest, cfg, options.name, options);
527
+ if (options.action === 'priority') {
528
+ const out = await admin.setPriority(rest, cfg, options.key, options.name, options);
529
+ if (!out.planned) appendEvent(projectRoot, activeSession, { type: 'AlmPrioritySet', payload: { key: out.key, priority: out.priority, confirmed: out.confirmed } });
530
+ return out;
531
+ }
532
+ if (options.action === 'intake') {
533
+ let fromText = null;
534
+ if (options.from && !/^https?:\/\//i.test(options.from)) {
535
+ const f = path.resolve(projectRoot, options.from);
536
+ if (!fs.existsSync(f)) throw new Error(`--from ${options.from}: arquivo não encontrado`);
537
+ fromText = fs.readFileSync(f, 'utf8');
538
+ }
539
+ const out = await admin.intake(rest, cfg, { ...options, fromText }, { programDir, options: { ...options, env } });
540
+ if (out.created) appendEvent(projectRoot, activeSession, { type: 'AlmIntake', payload: { ref: out.ref, key: out.key, type: options.type } });
541
+ return out;
542
+ }
543
+ throw new Error(`alm ${options.action}: ação desconhecida`);
544
+ }
545
+
546
+ /** `oxe-cc trace` and `oxe-cc trace publish [--apply]`. */
547
+ async function runtimeTrace(projectRoot, activeSession, options = {}) {
548
+ const snap = traceSnapshot(projectRoot, activeSession);
549
+ const graph = require('../oxe-trace.cjs').build(snap);
550
+ fs.mkdirSync(path.join(projectRoot, '.oxe'), { recursive: true });
551
+ fs.writeFileSync(path.join(projectRoot, '.oxe', 'trace.json'), JSON.stringify({ at: new Date().toISOString(), ...graph }, null, 2));
552
+ if (options.action !== 'publish') return { file: '.oxe/trace.json', ...graph };
553
+ const lib = require('../oxe-alm.cjs');
554
+ const cfg = snap._cfg;
555
+ if (!cfg) throw new Error('trace publish escreve nos cards: configure alm.provider');
556
+ const docs = snap._config.alm && snap._config.alm.docs && typeof snap._config.alm.docs === 'object' ? snap._config.alm.docs : null;
557
+ const dirRel = (docs && docs.dir) || (snap._config.docs_publish && snap._config.docs_publish.dir) || 'docs';
558
+ const docsBase = docs && docs.repo ? `${String(docs.repo).replace(/\/+$/, '')}/blob/${docs.branch || 'main'}/${dirRel}` : null;
559
+ const adrDirAbs = path.join(projectRoot, require('../oxe-adr.cjs').adrDir(snap._config) || 'docs/adr');
560
+ const adrFiles = fs.existsSync(adrDirAbs) ? fs.readdirSync(adrDirAbs) : [];
561
+ const adrFile = (id) => adrFiles.find((f) => f.startsWith(`${id}-`)) || null;
562
+ const trace = require('../oxe-trace.cjs');
563
+ const posts = [];
564
+ for (const st of graph.stories.filter((x) => x.card)) posts.push({ key: st.card, text: trace.cardDocs({ story: st.id, criteria: st.criteria, decisions: st.decisions }, { docsBase, adrFile }) });
565
+ const critById = new Map(graph.criteria.map((c) => [c.id, c]));
566
+ const decTitle = new Map(snap.decisions.map((d) => [d.id, d.title]));
567
+ for (const t of graph.tasks.filter((x) => x.card)) {
568
+ const crit = t.criteria.map((a) => ({ id: a, evidence: critById.get(a) ? critById.get(a).evidence : null, tests: critById.get(a) ? critById.get(a).tests : [], changes: critById.get(a) ? critById.get(a).changes : [] }));
569
+ const decs = [...new Set([...t.decisions, ...t.criteria.flatMap((a) => (critById.get(a) ? critById.get(a).decisions : []))])].map((id) => ({ id, title: decTitle.get(id) || null }));
570
+ posts.push({ key: t.card, text: trace.cardDocs({ criteria: crit, decisions: decs }, { docsBase, adrFile }) });
571
+ }
572
+ if (!options.apply) return { file: '.oxe/trace.json', dry_run: true, publish: posts.map((p) => ({ key: p.key, lines: p.text.split('\n').length, text: p.text })), ...graph };
573
+ const env = options.env || process.env;
574
+ if (!lib.isWriter(cfg, env)) throw lib.writerError(cfg);
575
+ if (cfg.transport === 'mcp') {
576
+ lib.enqueue(snap._programDir, posts.map((p) => ({ id: `docs:${p.key}`, op: 'comment', ref: p.key, key: p.key, upsert_marker: 'Documentos (OXE)', comments: [p.text] })));
577
+ return { file: '.oxe/trace.json', queued: posts.length, ...graph };
578
+ }
579
+ const problems = lib.checkConfig(cfg, env);
580
+ if (problems.length) throw new Error(`ALM: ${problems.join('; ')}`);
581
+ const rest = lib.jiraRest(cfg, options);
582
+ const refine = require('../oxe-alm-refine.cjs');
583
+ const done = [];
584
+ for (const p of posts) {
585
+ try {
586
+ const r = await rest.request('GET', `${rest.site}/rest/api/3/issue/${p.key}/comment?maxResults=100`);
587
+ const mine = ((r && r.comments) || []).find((c) => refine.adfToText(c.body).trim().startsWith('Documentos (OXE)'));
588
+ const body = { body: refine.mdToAdf(p.text) };
589
+ if (mine) await rest.request('PUT', `${rest.site}/rest/api/3/issue/${p.key}/comment/${mine.id}`, body);
590
+ else await rest.request('POST', `${rest.site}/rest/api/3/issue/${p.key}/comment`, body);
591
+ done.push({ key: p.key, updated: Boolean(mine) });
592
+ } catch (err) { done.push({ key: p.key, error: err.message }); }
593
+ }
594
+ appendEvent(projectRoot, activeSession, { type: 'TracePublished', payload: { cards: done.length, failed: done.filter((d) => d.error).length } });
595
+ return { file: '.oxe/trace.json', published: done, ...graph };
596
+ }
597
+
598
+ /** `oxe-cc alm metrics [--jql "…"] [--max N]`. */
599
+ async function runtimeAlmMetrics(projectRoot, activeSession, options = {}) {
600
+ const lib = require('../oxe-alm.cjs');
601
+ const metrics = require('../oxe-alm-metrics.cjs');
602
+ const config = readProjectConfig(projectRoot) || {};
603
+ const cfg = lib.almConfig(config, { defaultProgram: path.basename(path.resolve(projectRoot)) });
604
+ if (!cfg || cfg.provider !== 'jira') throw new Error('alm metrics: precisa de alm.provider "jira"');
605
+ const env = options.env || process.env;
606
+ const problems = lib.checkConfig(cfg, env);
607
+ if (problems.length) throw new Error(`ALM: ${problems.join('; ')}`);
608
+ const rest = lib.jiraRest(cfg, options);
609
+ const jql = options.jql || `project = "${cfg.p.project}" AND updated >= -90d ORDER BY created ASC`;
610
+ const max = Number(options.max) > 0 ? Number(options.max) : 300;
611
+ const issues = [];
612
+ let token = null;
613
+ do {
614
+ const r = await rest.request('GET', `${rest.site}/rest/api/3/search/jql?jql=${encodeURIComponent(jql)}&fields=status,created,issuetype,summary&expand=changelog&maxResults=100${token ? `&nextPageToken=${encodeURIComponent(token)}` : ''}`);
615
+ for (const i of (r && r.issues) || []) issues.push({ key: i.key, created: i.fields.created, status: i.fields.status ? i.fields.status.name : null, statusId: i.fields.status ? i.fields.status.id : null, summary: i.fields.summary, changes: metrics.changesFromJira(i) });
616
+ token = r && !r.isLast ? r.nextPageToken : null;
617
+ } while (token && issues.length < max);
618
+ metrics.renameByStatusId(issues);
619
+ const out = metrics.compute(issues.slice(0, max), { states: cfg.states, wip: cfg.wip, stages: lib.STAGES }, { now: options.now });
620
+ const dir = path.join(projectRoot, '.oxe', 'alm');
621
+ fs.mkdirSync(dir, { recursive: true });
622
+ fs.writeFileSync(path.join(dir, 'metrics.json'), JSON.stringify({ jql, at: new Date().toISOString(), ...out }, null, 2));
623
+ fs.writeFileSync(path.join(dir, 'metrics.md'), metrics.renderMarkdown(out, { project: cfg.p.project, jql, doneName: cfg.states.released || cfg.states.integrated }));
624
+ return { jql, file: '.oxe/alm/metrics.md', ...out };
625
+ }
626
+
627
+ /** `oxe-cc alm refine <KEY…> | --jql "…" [--max-cards N]` · `lint` · `apply`. */
628
+ async function runtimeAlmRefine(projectRoot, activeSession, options = {}) {
629
+ const lib = require('../oxe-alm.cjs');
630
+ const refine = require('../oxe-alm-refine.cjs');
631
+ const config = readProjectConfig(projectRoot) || {};
632
+ const cfg = lib.almConfig(config, { defaultProgram: path.basename(path.resolve(projectRoot)) });
633
+ if (!cfg) throw new Error('ALM não configurado: alm refine lê os cards do Jira (alm.provider: "jira")');
634
+ if (cfg.provider !== 'jira') throw new Error('alm refine: por enquanto só Jira');
635
+ const env = options.env || process.env;
636
+ const d = refine.dirs(projectRoot);
637
+ const action = options.action || 'collect';
638
+ let keys = (options.keys || []).map((k) => String(k).toUpperCase());
639
+ if (action === 'lint' || action === 'apply') {
640
+ if (!keys.length) keys = fs.existsSync(d.specs) ? fs.readdirSync(d.specs).filter((f) => /\.md$/.test(f)).map((f) => f.replace(/\.md$/, '')) : [];
641
+ const catalogCache = refine.discoverProgramCatalog(projectRoot, { activeSession, programRoots: options.programRoots || null });
642
+ const out = [];
643
+ for (const key of keys) {
644
+ const specFile = path.join(d.specs, `${key}.md`);
645
+ const dataFile = path.join(d.data, `${key}.json`);
646
+ if (!fs.existsSync(specFile) || !fs.existsSync(dataFile)) { out.push({ key, error: `sem coleta: rode oxe-cc alm refine ${key}` }); continue; }
647
+ const collected = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
648
+ const md = fs.readFileSync(specFile, 'utf8');
649
+ let resolvedProgram = null;
650
+ try {
651
+ resolvedProgram = refine.resolveCardProgram(projectRoot, activeSession, {
652
+ key,
653
+ md,
654
+ spec: options.spec || null,
655
+ catalogCache,
656
+ programRoots: options.programRoots || null,
657
+ });
658
+ } catch (err) {
659
+ if (action === 'lint') {
660
+ out.push({ key, kind: collected.kind, ok: false, errors: [err.message], warnings: [], questions: [], criteria: [], needs_info: false });
661
+ continue;
662
+ }
663
+ out.push({ key, error: err.message });
664
+ continue;
665
+ }
666
+ const targetEntry = resolvedProgram ? resolvedProgram.entry : null;
667
+ if (action === 'lint') {
668
+ const artRoot = targetEntry ? targetEntry.root : projectRoot;
669
+ const artSess = artRoot === path.resolve(projectRoot) ? activeSession : null;
670
+ const artifacts = (collected && collected.project_artifacts && collected.project_artifacts.has_any)
671
+ ? collected.project_artifacts
672
+ : refine.discoverProjectArtifacts(artRoot, artSess, key);
673
+ const l = refine.lintSpec(md, collected.kind, { artifacts, projectRoot: artRoot });
674
+ const ui = uiCardGaps(md, collected, { projectRoot: artRoot });
675
+ if (ui.isUi && ui.gaps.length) {
676
+ for (const g of ui.gaps) { l.warnings.push(`interface: ${g}`); l.questions.push(`MARCA: ${g}`); }
677
+ l.needs_info = true;
678
+ }
679
+ const cross = refine.lintCardCriteriaAgainstPrograms(md, key, targetEntry, {
680
+ projectRoot,
681
+ activeSession,
682
+ catalog: catalogCache,
683
+ programRoots: options.programRoots || null,
684
+ });
685
+ if (cross.errors.length) { l.errors.push(...cross.errors); l.ok = false; }
686
+ if (cross.warnings.length) l.warnings.push(...cross.warnings);
687
+ try {
688
+ const glRoot = targetEntry ? targetEntry.root : projectRoot;
689
+ const glSess = glRoot === path.resolve(projectRoot) ? activeSession : null;
690
+ const gl = require('../oxe-grill.cjs').readGlossary(grillPaths(glRoot, glSess).glossary);
691
+ for (const t of gl) for (const syn of t.synonyms || []) {
692
+ if (syn.length >= 3 && wholeWord(syn).test(md)) l.warnings.push(`glossário: "${syn}" é sinônimo proibido de "${t.term}" — use "${t.term}"`);
693
+ }
694
+ } catch { /* sem glossário */ }
695
+ out.push({
696
+ key,
697
+ kind: collected.kind,
698
+ ...(targetEntry && targetEntry.root !== path.resolve(projectRoot) ? { program: targetEntry.slug, spec: path.relative(path.dirname(path.resolve(projectRoot)), targetEntry.specPath || targetEntry.planPath || targetEntry.root).replace(/\\/g, '/') } : {}),
699
+ ...l,
700
+ });
701
+ continue;
702
+ }
703
+ if (options.spec || (resolvedProgram && resolvedProgram.matchedBy !== 'dir_default')) {
704
+ const crossApply = refine.lintCardCriteriaAgainstPrograms(md, key, targetEntry, {
705
+ projectRoot,
706
+ activeSession,
707
+ catalog: catalogCache,
708
+ programRoots: options.programRoots || null,
709
+ });
710
+ if (crossApply.errors.length) {
711
+ out.push({ key, error: `spec reprovado no lint (SPEC/PLAN):\n - ${crossApply.errors.join('\n - ')}`, lint: { ok: false, errors: crossApply.errors, warnings: crossApply.warnings } });
712
+ continue;
713
+ }
714
+ }
715
+ const dry = lib.isDry(cfg, options);
716
+ if (!dry && !lib.isWriter(cfg, env)) throw lib.writerError(cfg);
717
+ if (!dry) lib.warnApply(cfg, options);
718
+ const problems = lib.checkConfig(cfg, env);
719
+ if (problems.length) throw new Error(`ALM: ${problems.join('; ')}`);
720
+ const applyRoot = targetEntry ? targetEntry.root : projectRoot;
721
+ try {
722
+ const r = await refine.apply(lib.jiraRest(cfg, { ...options, dryRun: dry }), collected, md, {
723
+ confirmOverwrite: options.confirmOverwrite,
724
+ dryRun: dry,
725
+ projectRoot: applyRoot,
726
+ });
727
+ const target = r.questions ? 'grooming' : 'ready';
728
+ if (options.keepStatus) r.moved = { skipped: true, why: '--keep-status: o card fica na coluna em que está' };
729
+ else if (r.applied) r.moved = await refineMove(lib, cfg, key, target, { ...options, env });
730
+ else if (r.dry_run) r.moved = await refineMove(lib, cfg, key, target, { ...options, env, dryRun: true });
731
+ if (r.dry_run && cfg.require_apply && !options.dryRun && !options.apply) r.why_dry = 'alm.require_apply: gravar exige --apply';
732
+ if (!dry) appendEvent(projectRoot, activeSession, { type: 'AlmRefined', payload: { key, sha: r.sha || null, applied: Boolean(r.applied) } });
733
+ out.push(r);
734
+ } catch (err) { out.push({ key, error: err.message, ...(err.lint ? { lint: err.lint } : {}) }); }
735
+ }
736
+ return { action, results: out };
737
+ }
738
+ const problems = lib.checkConfig(cfg, env);
739
+ if (problems.length) throw new Error(`ALM: ${problems.join('; ')} — o refine lê o card pela API do Jira`);
740
+ const rest = lib.jiraRest(cfg, options);
741
+ if (options.jql) {
742
+ const r = await rest.request('GET', `${rest.site}/rest/api/3/search/jql?jql=${encodeURIComponent(options.jql)}&fields=summary&maxResults=${Math.min(100, Number(options.maxCards) || 20)}`);
743
+ keys = [...keys, ...((r && r.issues) || []).map((i) => i.key)];
744
+ }
745
+ const max = Number(options.maxCards) > 0 ? Number(options.maxCards) : 15;
746
+ if (keys.length > max) throw new Error(`${keys.length} card(s) passam do teto --max-cards ${max}: refine em lote só com o OK do usuário (aumente --max-cards de propósito)`);
747
+ fs.mkdirSync(d.data, { recursive: true });
748
+ fs.mkdirSync(d.specs, { recursive: true });
749
+ const out = [];
750
+ for (const key of keys) {
751
+ try {
752
+ const c = await refine.collect(rest, key, { projectRoot, activeSession });
753
+ fs.writeFileSync(path.join(d.data, `${key}.json`), JSON.stringify(c, null, 2));
754
+ const specFile = path.join(d.specs, `${key}.md`);
755
+ const kept = fs.existsSync(specFile) && !options.reset;
756
+ if (!kept) fs.writeFileSync(specFile, refine.skeleton(c));
757
+ const claimDry = lib.isDry(cfg, options);
758
+ if (options.claim && !claimDry && lib.isWriter(cfg, env)) lib.warnApply(cfg, options);
759
+ const claimed = !options.claim ? null
760
+ : !lib.isWriter(cfg, env) && !claimDry ? { stage: 'refinement', skipped: true, why: lib.writerError(cfg).message }
761
+ : await refineMove(lib, cfg, key, 'refinement', { ...options, env, dryRun: claimDry });
762
+ out.push({ key, ...(claimed ? { moved: claimed } : {}), kind: c.kind, type: c.type, status: c.status, summary: c.summary, comments: c.comments.length, links: c.links.length, code_refs: c.code_refs.length, already_refined: c.already_refined, spec: path.relative(projectRoot, specFile).replace(/\\/g, '/'), kept });
763
+ } catch (err) { out.push({ key, error: err.message }); }
764
+ }
765
+ return { action: 'collect', dry_run: !options.claim || lib.isDry(cfg, options), claim: Boolean(options.claim), results: out };
766
+ }
767
+
768
+ return {
769
+ runtimeAlm,
770
+ runtimeAlmRefineImport,
771
+ traceGateFindings,
772
+ runtimeAlmAdmin,
773
+ traceSnapshot,
774
+ runtimeTrace,
775
+ runtimeAlmMetrics,
776
+ runtimeAlmRefine,
777
+ uiCardGaps,
778
+ wholeWord,
779
+ refineMove,
780
+ criteriaOnlyReadSharedLocales,
781
+ };
782
+ }
783
+
784
+ module.exports = {
785
+ NON_UI_DOMAIN_LABEL_RE,
786
+ wholeWord,
787
+ criteriaOnlyReadSharedLocales,
788
+ uiCardGaps,
789
+ refineMove,
790
+ createAlmRefineRuntime,
791
+ };