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,246 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 1.22.2 (OXB-222-17): IDE-agnostic multi-agent local coordination ledger.
5
+ * Stores active agent leases in `<git-common-dir>/oxe/active-agents.json` and cross-worktree
6
+ * messages in `<git-common-dir>/oxe/agent-messages.ndjson`, visible to every worktree of the repo
7
+ * (Antigravity, Claude Code, Cursor, Codex, Copilot, etc.).
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const crypto = require('crypto');
13
+ const { spawnSync } = require('child_process');
14
+ const { resolveProjectGitRoot, normPath } = require('./oxe-git-root.cjs');
15
+
16
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
17
+
18
+ function normRelFile(f) {
19
+ return String(f || '').trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');
20
+ }
21
+
22
+ function isPidAlive(pid) {
23
+ const num = Number(pid);
24
+ if (!Number.isInteger(num) || num <= 0) return true;
25
+ try {
26
+ process.kill(num, 0);
27
+ return true;
28
+ } catch (err) {
29
+ return Boolean(err && err.code === 'EPERM');
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Resolves the shared `<git-common-dir>/oxe` directory for all worktrees of `projectRoot`.
35
+ * When `options.readOnly === true`, never creates directories on disk.
36
+ */
37
+ function coordDirOf(projectRoot, options = {}) {
38
+ const rootAbs = path.resolve(projectRoot || process.cwd());
39
+ const spawn = options.spawn || spawnSync;
40
+ const gitRoot = resolveProjectGitRoot(rootAbs, { spawn });
41
+ let dir = null;
42
+ if (gitRoot) {
43
+ const res = spawn('git', ['rev-parse', '--git-common-dir'], { cwd: rootAbs, encoding: 'utf8', windowsHide: true });
44
+ if (res && res.status === 0 && String(res.stdout || '').trim()) {
45
+ dir = path.join(path.resolve(rootAbs, String(res.stdout).trim()), 'oxe');
46
+ }
47
+ }
48
+ if (!dir) dir = path.join(rootAbs, '.oxe', 'agents');
49
+ if (!options.readOnly) {
50
+ fs.mkdirSync(dir, { recursive: true });
51
+ }
52
+ return dir;
53
+ }
54
+
55
+ function leasesFileOf(projectRoot, options = {}) {
56
+ return path.join(coordDirOf(projectRoot, options), 'active-agents.json');
57
+ }
58
+
59
+ function messagesFileOf(projectRoot, options = {}) {
60
+ return path.join(coordDirOf(projectRoot, options), 'agent-messages.ndjson');
61
+ }
62
+
63
+ function readLeasesRaw(file) {
64
+ try {
65
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
66
+ if (doc && Array.isArray(doc.agents)) return doc.agents;
67
+ } catch { /* absent or corrupt */ }
68
+ return [];
69
+ }
70
+
71
+ function writeLeasesAtomic(file, agents) {
72
+ fs.mkdirSync(path.dirname(file), { recursive: true });
73
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
74
+ fs.writeFileSync(tmp, `${JSON.stringify({ schema: 1, updated_at: new Date().toISOString(), agents }, null, 2)}\n`, 'utf8');
75
+ fs.renameSync(tmp, file);
76
+ }
77
+
78
+ function pruneExpiredLeases(agents, options = {}) {
79
+ const now = options.now != null ? Number(options.now) : Date.now();
80
+ const checkPid = options.checkPid !== false;
81
+ return (Array.isArray(agents) ? agents : []).filter((a) => {
82
+ if (!a || !a.agent_id) return false;
83
+ const exp = Date.parse(String(a.expires_at || ''));
84
+ if (Number.isFinite(exp) && exp < now) return false;
85
+ if (checkPid && a.pid != null && !isPidAlive(a.pid)) return false;
86
+ return true;
87
+ });
88
+ }
89
+
90
+ function detectBranch(projectRoot, spawn = spawnSync) {
91
+ try {
92
+ const r = spawn('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: projectRoot, encoding: 'utf8', windowsHide: true });
93
+ if (r && r.status === 0) return String(r.stdout || '').trim() || null;
94
+ } catch { /* ignore */ }
95
+ return null;
96
+ }
97
+
98
+ function registerAgentLease(projectRoot, lease = {}, options = {}) {
99
+ const rootAbs = path.resolve(projectRoot || process.cwd());
100
+ const file = leasesFileOf(rootAbs, { ...options, readOnly: false });
101
+ const now = options.now != null ? Number(options.now) : Date.now();
102
+ const ttlMs = Number.isFinite(Number(lease.ttl_ms)) ? Number(lease.ttl_ms) : DEFAULT_TTL_MS;
103
+ const agentId = String(lease.agent_id || lease.id || `agent-${crypto.randomBytes(4).toString('hex')}`).trim();
104
+ const writeSet = [...new Set((Array.isArray(lease.write_set) ? lease.write_set : []).map(normRelFile).filter(Boolean))];
105
+ const worktree = path.resolve(lease.worktree || rootAbs);
106
+ const record = {
107
+ agent_id: agentId,
108
+ provider: String(lease.provider || 'unknown'),
109
+ role: String(lease.role || 'executor'),
110
+ worktree,
111
+ worktree_norm: normPath(worktree),
112
+ branch: lease.branch || detectBranch(worktree, options.spawn),
113
+ task: lease.task ? String(lease.task) : null,
114
+ write_set: writeSet,
115
+ pid: lease.pid === null ? null : (lease.pid != null ? Number(lease.pid) : process.pid),
116
+ started_at: new Date(now).toISOString(),
117
+ last_seen: new Date(now).toISOString(),
118
+ expires_at: new Date(now + ttlMs).toISOString(),
119
+ };
120
+ const existing = pruneExpiredLeases(readLeasesRaw(file), { now, checkPid: options.checkPid }).filter((a) => a.agent_id !== agentId);
121
+ existing.push(record);
122
+ writeLeasesAtomic(file, existing);
123
+ return record;
124
+ }
125
+
126
+ function heartbeatAgentLease(projectRoot, agentId, updates = {}, options = {}) {
127
+ const rootAbs = path.resolve(projectRoot || process.cwd());
128
+ const file = leasesFileOf(rootAbs, { ...options, readOnly: false });
129
+ const now = options.now != null ? Number(options.now) : Date.now();
130
+ const ttlMs = Number.isFinite(Number(updates.ttl_ms)) ? Number(updates.ttl_ms) : DEFAULT_TTL_MS;
131
+ const list = pruneExpiredLeases(readLeasesRaw(file), { now, checkPid: options.checkPid });
132
+ const idx = list.findIndex((a) => a.agent_id === String(agentId));
133
+ if (idx < 0) return null;
134
+ const cur = list[idx];
135
+ const next = {
136
+ ...cur,
137
+ ...(updates.task !== undefined ? { task: updates.task ? String(updates.task) : null } : {}),
138
+ ...(updates.role !== undefined ? { role: String(updates.role) } : {}),
139
+ ...(Array.isArray(updates.write_set) ? { write_set: [...new Set(updates.write_set.map(normRelFile).filter(Boolean))] } : {}),
140
+ last_seen: new Date(now).toISOString(),
141
+ expires_at: new Date(now + ttlMs).toISOString(),
142
+ };
143
+ list[idx] = next;
144
+ writeLeasesAtomic(file, list);
145
+ return next;
146
+ }
147
+
148
+ function releaseAgentLease(projectRoot, agentId, options = {}) {
149
+ const rootAbs = path.resolve(projectRoot || process.cwd());
150
+ const file = leasesFileOf(rootAbs, { ...options, readOnly: true });
151
+ if (!fs.existsSync(file)) return { released: false, agent_id: String(agentId) };
152
+ const before = readLeasesRaw(file);
153
+ const after = before.filter((a) => a && a.agent_id !== String(agentId));
154
+ writeLeasesAtomic(file, after);
155
+ return { released: after.length < before.length, agent_id: String(agentId) };
156
+ }
157
+
158
+ function listActiveAgents(projectRoot, options = {}) {
159
+ const rootAbs = path.resolve(projectRoot || process.cwd());
160
+ const file = leasesFileOf(rootAbs, { ...options, readOnly: true });
161
+ if (!fs.existsSync(file)) return [];
162
+ const raw = readLeasesRaw(file);
163
+ const active = pruneExpiredLeases(raw, options);
164
+ if (!options.readOnly && active.length !== raw.length) {
165
+ try { writeLeasesAtomic(file, active); } catch { /* read-only fallback */ }
166
+ }
167
+ return active;
168
+ }
169
+
170
+ function detectWriteSetCollisions(projectRoot, candidateFiles = [], options = {}) {
171
+ const rootAbs = path.resolve(projectRoot || process.cwd());
172
+ const active = listActiveAgents(rootAbs, { ...options, readOnly: true });
173
+ const wanted = [...new Set((Array.isArray(candidateFiles) ? candidateFiles : []).map(normRelFile).filter(Boolean))];
174
+ const excludeAgent = options.excludeAgentId ? String(options.excludeAgentId) : null;
175
+ const excludeWtNorm = options.excludeWorktree ? normPath(options.excludeWorktree) : null;
176
+
177
+ const collisions = [];
178
+ for (const agent of active) {
179
+ if (excludeAgent && agent.agent_id === excludeAgent) continue;
180
+ if (excludeWtNorm && normPath(agent.worktree) === excludeWtNorm) continue;
181
+ const agentFiles = Array.isArray(agent.write_set) ? agent.write_set.map(normRelFile) : [];
182
+ for (const f of wanted) {
183
+ const hit = agentFiles.some((af) => af === f || f.startsWith(`${af}/`) || af.startsWith(`${f}/`));
184
+ if (hit) {
185
+ collisions.push({
186
+ file: f,
187
+ agent_id: agent.agent_id,
188
+ provider: agent.provider,
189
+ worktree: agent.worktree,
190
+ branch: agent.branch,
191
+ task: agent.task,
192
+ });
193
+ }
194
+ }
195
+ }
196
+ return { ok: collisions.length === 0, collisions, active_agents: active.length };
197
+ }
198
+
199
+ function postAgentMessage(projectRoot, msg = {}, options = {}) {
200
+ const rootAbs = path.resolve(projectRoot || process.cwd());
201
+ const file = messagesFileOf(rootAbs, { ...options, readOnly: false });
202
+ const entry = {
203
+ id: `msg-${crypto.randomBytes(4).toString('hex')}`,
204
+ at: new Date().toISOString(),
205
+ from: String(msg.from || 'agent'),
206
+ to: String(msg.to || 'all'),
207
+ topic: msg.topic ? String(msg.topic) : 'general',
208
+ body: String(msg.body || '').trim(),
209
+ worktree: path.resolve(msg.worktree || rootAbs),
210
+ };
211
+ fs.mkdirSync(path.dirname(file), { recursive: true });
212
+ fs.appendFileSync(file, `${JSON.stringify(entry)}\n`, 'utf8');
213
+ return entry;
214
+ }
215
+
216
+ function readAgentMessages(projectRoot, options = {}) {
217
+ const rootAbs = path.resolve(projectRoot || process.cwd());
218
+ const file = messagesFileOf(rootAbs, { ...options, readOnly: true });
219
+ if (!fs.existsSync(file)) return [];
220
+ const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
221
+ let msgs = [];
222
+ for (const l of lines) {
223
+ try { msgs.push(JSON.parse(l)); } catch { /* skip corrupt */ }
224
+ }
225
+ if (options.to) {
226
+ const target = String(options.to);
227
+ msgs = msgs.filter((m) => m.to === target || m.to === 'all');
228
+ }
229
+ if (options.since) {
230
+ const sinceMs = Date.parse(String(options.since));
231
+ if (Number.isFinite(sinceMs)) msgs = msgs.filter((m) => Date.parse(String(m.at || '')) >= sinceMs);
232
+ }
233
+ const limit = Number(options.limit) > 0 ? Number(options.limit) : 50;
234
+ return msgs.slice(-limit);
235
+ }
236
+
237
+ module.exports = {
238
+ coordDirOf,
239
+ registerAgentLease,
240
+ heartbeatAgentLease,
241
+ releaseAgentLease,
242
+ listActiveAgents,
243
+ detectWriteSetCollisions,
244
+ postAgentMessage,
245
+ readAgentMessages,
246
+ };
@@ -588,6 +588,99 @@ function lintSpec(md, kind, options = {}) {
588
588
  warnings.push('arquitetura: o projeto possui SYSTEM-DESIGN.md mas a história não traz a seção "Arquitetura e fluxo" nem referencia o documento');
589
589
  }
590
590
  }
591
+
592
+ // OXB-222-11: mechanical repo path validation, existing-symbol verification and anti-combo cohesion checks.
593
+ const rootAbs = options.projectRoot ? path.resolve(options.projectRoot) : null;
594
+ const NEW_PATH_HINT_RE = /\b(?:novo|nova|criar|a\s+criar|gerado|new|to\s+be\s+created)\b/i;
595
+ const EPHEMERAL_OXE_RE = /^\.oxe\/(?:grill|alm\/grill|runs|tmp|evidence|quick|checkpoints|archive)(?:\/|$)/i;
596
+ const PLACEHOLDER_SEG_RE = /(?:^|\/)(?:KEY|ID|CARD|SLUG|RUN_ID|SESSION|PHASE|Fn|Tn)(?:\/|$)/;
597
+ const REPO_PATH_RE = /`((?:\.oxe|docs|bin|oxe|src|packages|scripts|lib|tests?|e2e|shared|electron|mobile|app|config)\/[^`\r\n]+)`/g;
598
+ if (rootAbs) {
599
+ const checkedPaths = new Set();
600
+ for (const secName of ['Referências', 'Arquitetura e fluxo']) {
601
+ const secBody = sec.get(secName);
602
+ if (!secBody) continue;
603
+ for (const line of secBody.split('\n')) {
604
+ let pm;
605
+ const re = new RegExp(REPO_PATH_RE.source, 'g');
606
+ while ((pm = re.exec(line))) {
607
+ const raw = pm[1].trim();
608
+ const clean = raw.replace(/#.*$/, '').replace(/:\d+(?::\d+)?$/, '').trim();
609
+ if (!clean || /[*<>]|\.\.|^https?:/i.test(clean)) continue;
610
+ if (EPHEMERAL_OXE_RE.test(clean) || PLACEHOLDER_SEG_RE.test(clean)) continue;
611
+ const after = line.slice(pm.index + pm[0].length, pm.index + pm[0].length + 40);
612
+ if (NEW_PATH_HINT_RE.test(after)) continue;
613
+ if (checkedPaths.has(clean)) continue;
614
+ checkedPaths.add(clean);
615
+ const abs = path.join(rootAbs, clean);
616
+ if (!fs.existsSync(abs)) {
617
+ errors.push(`referência inexistente no repositório: \`${clean}\` (confira o caminho real ou marque "(novo)" se será criado)`);
618
+ }
619
+ }
620
+ }
621
+ }
622
+
623
+ // Verify `file.ext` (`symbol`) pairs against existing files (skip creation verbs)
624
+ const CREATE_VERB_RE = /\b(?:criar|adicionar|implementar|exportar|introduzir|novo|nova|add|create|implement|export|new)\b/i;
625
+ const FILE_SYM_RE = /`([A-Za-z0-9_.\-/]+\.(?:[cm]?js|tsx?|jsx?|py|go|rs))`\s*\(\s*`([A-Za-z_$][\w$]*)`\s*\)/g;
626
+ const fileCache = new Map();
627
+ const checkedSyms = new Set();
628
+ for (const secName of ['Regras técnicas', 'Critérios de aceite', 'Arquitetura e fluxo']) {
629
+ const secBody = sec.get(secName);
630
+ if (!secBody) continue;
631
+ let sm;
632
+ const re = new RegExp(FILE_SYM_RE.source, 'g');
633
+ while ((sm = re.exec(secBody))) {
634
+ const fileRel = sm[1].trim();
635
+ const sym = sm[2].trim();
636
+ if (!fileRel || !sym || /[*<>]|\.\./.test(fileRel)) continue;
637
+ const before = secBody.slice(Math.max(0, sm.index - 40), sm.index);
638
+ if (CREATE_VERB_RE.test(before)) continue;
639
+ const pairKey = `${fileRel}::${sym}`;
640
+ if (checkedSyms.has(pairKey)) continue;
641
+ checkedSyms.add(pairKey);
642
+ const abs = path.join(rootAbs, fileRel);
643
+ if (!fs.existsSync(abs)) continue;
644
+ let content = fileCache.get(abs);
645
+ if (content === undefined) {
646
+ try { content = fs.readFileSync(abs, 'utf8'); } catch { content = ''; }
647
+ fileCache.set(abs, content);
648
+ }
649
+ const symRe = new RegExp(`(?<![A-Za-z0-9_$])${sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_$])`);
650
+ if (content && !symRe.test(content)) {
651
+ warnings.push(`símbolo \`${sym}\` citado como existente não encontrado em \`${fileRel}\` — confira o código real antes de fechar o card`);
652
+ }
653
+ }
654
+ }
655
+ }
656
+
657
+ // Anti-combo cohesion warning for story/task (epics naturally span modules)
658
+ if (kind === 'story' || kind === 'task') {
659
+ const comboReasons = [];
660
+ const titleMatch = /^#\s+(?:[A-Z]+-\d+\s*[—–-]\s*)?(.*)$/m.exec(String(md || '').replace(/<!--[\s\S]*?-->/g, ''));
661
+ const cleanTitle = titleMatch ? titleMatch[1].trim() : '';
662
+ const titleParts = cleanTitle.split(/[,+]|\s+e\s+/i).map((x) => x.trim()).filter(Boolean);
663
+ if (cleanTitle.length > 120 && titleParts.length >= 4) {
664
+ comboReasons.push(`título muito amplo (${cleanTitle.length} chars, ${titleParts.length} frentes)`);
665
+ }
666
+ const refsSec = sec.get('Referências') || '';
667
+ const codeLines = refsSec.split('\n').filter((l) => /^\s*[-*]\s*C[oó]digo\s*:/i.test(l));
668
+ const codePaths = new Set();
669
+ for (const l of codeLines) {
670
+ for (const m of l.matchAll(/`([^`\r\n]+\.(?:[cm]?js|tsx?|jsx?|py|go|rs|json|md))`/g)) codePaths.add(m[1].trim());
671
+ }
672
+ if (codePaths.size >= 5) {
673
+ comboReasons.push(`${codePaths.size} arquivos distintos em Referências/Código`);
674
+ }
675
+ const compoundCas = criteria.filter((c) => /;\s+e\s+/i.test(c.text.replace(/`[^`]*`/g, '')));
676
+ if (compoundCas.length) {
677
+ comboReasons.push(`${compoundCas.map((c) => c.id).join(', ')} combina múltiplas proposições com "; e "`);
678
+ }
679
+ if (comboReasons.length) {
680
+ warnings.push(`coesão/granularidade (card combo): ${comboReasons.join('; ')} — considere dividir em cards menores e independentes`);
681
+ }
682
+ }
683
+
591
684
  return { ok: errors.length === 0, errors, warnings, questions, criteria, needs_info: tbc > 0 };
592
685
  }
593
686
 
@@ -605,7 +698,10 @@ function descriptionBody(md) {
605
698
  async function apply(ctx, collected, md, options = {}) {
606
699
  const { request, site } = ctx;
607
700
  const encKey = encodeURIComponent(collected.key);
608
- const lint = lintSpec(md, collected.kind);
701
+ const lint = lintSpec(md, collected.kind, {
702
+ projectRoot: options.projectRoot || null,
703
+ artifacts: options.artifacts || null,
704
+ });
609
705
  if (!lint.ok && !options.allowLintErrors) throw Object.assign(new Error(`spec reprovado no lint:\n - ${lint.errors.join('\n - ')}`), { lint });
610
706
  const now = await request('GET', `${site}/rest/api/3/issue/${encKey}?fields=description,labels`);
611
707
  const currentText = adfToText(now && now.fields ? now.fields.description : null).trim();
@@ -0,0 +1,304 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 1.22.2 (OXB-222-20): Provider-agnostic CI/VCS adapter (`github`, `gitlab`, `azure-devops`, `local`).
5
+ * Abstracts PR/MR listing, CI run inspection, and release asset retrieval so `ship` and `release`
6
+ * operate cleanly across GitHub (`gh`), GitLab (`glab`), Azure DevOps (`az`), and offline local repos.
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const { spawnSync } = require('child_process');
12
+
13
+ const SUPPORTED_PROVIDERS = Object.freeze(['github', 'gitlab', 'azure-devops', 'local']);
14
+
15
+ function readTextQuiet(file) {
16
+ try { return fs.readFileSync(file, 'utf8'); } catch { return ''; }
17
+ }
18
+
19
+ function readJsonQuiet(file) {
20
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
21
+ }
22
+
23
+ function readConfiguredProvider(projectRoot) {
24
+ const local = readJsonQuiet(path.join(projectRoot, '.oxe', 'config.json'));
25
+ const base = readJsonQuiet(path.join(projectRoot, 'oxe.config.json'));
26
+ const cfg = { ...(base || {}), ...(local || {}) };
27
+ const candidate = (cfg.ci && cfg.ci.provider) || (cfg.delivery && cfg.delivery.ci_provider) || null;
28
+ if (candidate && SUPPORTED_PROVIDERS.includes(String(candidate).toLowerCase())) {
29
+ return String(candidate).toLowerCase();
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function readOriginUrl(projectRoot) {
35
+ const gitEntry = path.join(projectRoot, '.git');
36
+ let gitDir = gitEntry;
37
+ try {
38
+ const st = fs.statSync(gitEntry);
39
+ if (st.isFile()) {
40
+ const m = /gitdir:\s*(.+)/i.exec(readTextQuiet(gitEntry));
41
+ if (m) {
42
+ const resolved = path.resolve(projectRoot, m[1].trim());
43
+ const commondir = readTextQuiet(path.join(resolved, 'commondir')).trim();
44
+ gitDir = commondir ? path.resolve(resolved, commondir) : resolved;
45
+ }
46
+ }
47
+ } catch {
48
+ return null;
49
+ }
50
+ const cfg = readTextQuiet(path.join(gitDir, 'config'));
51
+ const m = /\[remote "origin"\][\s\S]*?url\s*=\s*([^\r\n]+)/i.exec(cfg);
52
+ return m ? m[1].trim() : null;
53
+ }
54
+
55
+ /**
56
+ * Detects the repository CI/VCS provider without network access:
57
+ * `options.provider` > config (`ci.provider`) > `.git/config` remote host > CI pipeline files > `'local'`.
58
+ */
59
+ function detectCiProvider(projectRoot, options = {}) {
60
+ if (options.provider && SUPPORTED_PROVIDERS.includes(String(options.provider).toLowerCase())) {
61
+ return String(options.provider).toLowerCase();
62
+ }
63
+ const rootAbs = path.resolve(projectRoot || process.cwd());
64
+ const fromCfg = readConfiguredProvider(rootAbs);
65
+ if (fromCfg) return fromCfg;
66
+
67
+ const remoteUrl = readOriginUrl(rootAbs);
68
+ if (remoteUrl) {
69
+ if (/github\.com/i.test(remoteUrl)) return 'github';
70
+ if (/gitlab\.com|gitlab\./i.test(remoteUrl)) return 'gitlab';
71
+ if (/dev\.azure\.com|visualstudio\.com/i.test(remoteUrl)) return 'azure-devops';
72
+ }
73
+
74
+ if (fs.existsSync(path.join(rootAbs, '.github', 'workflows'))) return 'github';
75
+ if (fs.existsSync(path.join(rootAbs, '.gitlab-ci.yml'))) return 'gitlab';
76
+ if (
77
+ fs.existsSync(path.join(rootAbs, 'azure-pipelines.yml'))
78
+ || fs.existsSync(path.join(rootAbs, 'azure-pipelines.yaml'))
79
+ || fs.existsSync(path.join(rootAbs, '.azure-pipelines'))
80
+ ) {
81
+ return 'azure-devops';
82
+ }
83
+ return 'local';
84
+ }
85
+
86
+ function runCliJson(spawn, bin, args, cwd) {
87
+ const res = spawn(bin, args, { cwd, encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 });
88
+ if (!res || res.error || res.status !== 0) {
89
+ const msg = String((res && (res.stderr || (res.error && res.error.message) || res.stdout)) || `${bin} falhou`).trim().split(/\r?\n/)[0];
90
+ return { ok: false, error: `${bin} ${args.slice(0, 2).join(' ')}: ${msg}`, data: null };
91
+ }
92
+ try {
93
+ return { ok: true, error: null, data: JSON.parse(String(res.stdout || 'null')) };
94
+ } catch (err) {
95
+ return { ok: false, error: `${bin}: JSON inválido (${err.message})`, data: null };
96
+ }
97
+ }
98
+
99
+ function buildGithubAdapter(rootAbs, spawn) {
100
+ return {
101
+ provider: 'github',
102
+ offline: false,
103
+ listPullRequests(opts = {}) {
104
+ const state = opts.state || 'open';
105
+ const limit = String(opts.limit || 50);
106
+ const r = runCliJson(spawn, 'gh', ['pr', 'list', '--state', state, '--limit', limit, '--json', 'number,title,headRefName,headRefOid,url,labels,isDraft,state'], rootAbs);
107
+ if (!r.ok) return { ok: false, provider: 'github', offline: false, items: [], error: r.error };
108
+ const items = (Array.isArray(r.data) ? r.data : []).map((p) => ({
109
+ number: Number(p.number),
110
+ title: p.title || '',
111
+ branch: p.headRefName || '',
112
+ head_sha: p.headRefOid || null,
113
+ state: String(p.state || 'OPEN').toUpperCase(),
114
+ draft: Boolean(p.isDraft),
115
+ url: p.url || null,
116
+ labels: (p.labels || []).map((l) => (typeof l === 'string' ? l : l.name)).filter(Boolean),
117
+ }));
118
+ return { ok: true, provider: 'github', offline: false, items };
119
+ },
120
+ inspectCiStatus(opts = {}) {
121
+ const args = ['run', 'list', '--limit', String(opts.limit || 10), '--json', 'databaseId,status,conclusion,url,headBranch,displayTitle'];
122
+ if (opts.branch) args.push('--branch', String(opts.branch));
123
+ const r = runCliJson(spawn, 'gh', args, rootAbs);
124
+ if (!r.ok) return { ok: false, provider: 'github', offline: false, runs: [], error: r.error };
125
+ const runs = (Array.isArray(r.data) ? r.data : []).map((run) => ({
126
+ id: run.databaseId || run.id || null,
127
+ status: String(run.status || 'unknown').toLowerCase(),
128
+ conclusion: run.conclusion ? String(run.conclusion).toLowerCase() : null,
129
+ branch: run.headBranch || opts.branch || null,
130
+ url: run.url || null,
131
+ }));
132
+ return { ok: true, provider: 'github', offline: false, runs };
133
+ },
134
+ listReleaseAssets(tag) {
135
+ const r = runCliJson(spawn, 'gh', ['release', 'view', String(tag), '--json', 'tagName,isDraft,assets'], rootAbs);
136
+ if (!r.ok) return { ok: false, provider: 'github', offline: false, tag: String(tag), assets: [], error: r.error };
137
+ const d = r.data || {};
138
+ return {
139
+ ok: true,
140
+ provider: 'github',
141
+ offline: false,
142
+ tag: d.tagName || String(tag),
143
+ draft: Boolean(d.isDraft),
144
+ assets: Array.isArray(d.assets) ? d.assets : [],
145
+ };
146
+ },
147
+ };
148
+ }
149
+
150
+ function buildGitlabAdapter(rootAbs, spawn) {
151
+ return {
152
+ provider: 'gitlab',
153
+ offline: false,
154
+ listPullRequests(opts = {}) {
155
+ const args = ['mr', 'list', '--output', 'json'];
156
+ if (opts.state === 'closed') args.push('--closed');
157
+ else if (opts.state === 'merged') args.push('--merged');
158
+ const r = runCliJson(spawn, 'glab', args, rootAbs);
159
+ if (!r.ok) return { ok: false, provider: 'gitlab', offline: false, items: [], error: r.error };
160
+ const items = (Array.isArray(r.data) ? r.data : []).map((mr) => ({
161
+ number: Number(mr.iid != null ? mr.iid : mr.id),
162
+ title: mr.title || '',
163
+ branch: mr.source_branch || '',
164
+ head_sha: mr.sha || null,
165
+ state: String(mr.state || 'opened').toUpperCase(),
166
+ draft: Boolean(mr.draft || mr.work_in_progress),
167
+ url: mr.web_url || null,
168
+ labels: Array.isArray(mr.labels) ? mr.labels.map(String) : [],
169
+ }));
170
+ return { ok: true, provider: 'gitlab', offline: false, items };
171
+ },
172
+ inspectCiStatus(opts = {}) {
173
+ const args = ['ci', 'list', '--output', 'json'];
174
+ if (opts.branch) args.push('--ref', String(opts.branch));
175
+ const r = runCliJson(spawn, 'glab', args, rootAbs);
176
+ if (!r.ok) return { ok: false, provider: 'gitlab', offline: false, runs: [], error: r.error };
177
+ const runs = (Array.isArray(r.data) ? r.data : []).map((p) => {
178
+ const st = String(p.status || 'unknown').toLowerCase();
179
+ const conclusion = ['success', 'failed', 'canceled', 'skipped'].includes(st) ? st : null;
180
+ return {
181
+ id: p.id || null,
182
+ status: conclusion ? 'completed' : st,
183
+ conclusion,
184
+ branch: p.ref || opts.branch || null,
185
+ url: p.web_url || null,
186
+ };
187
+ });
188
+ return { ok: true, provider: 'gitlab', offline: false, runs };
189
+ },
190
+ listReleaseAssets(tag) {
191
+ const r = runCliJson(spawn, 'glab', ['release', 'view', String(tag), '--output', 'json'], rootAbs);
192
+ if (!r.ok) return { ok: false, provider: 'gitlab', offline: false, tag: String(tag), assets: [], error: r.error };
193
+ const d = r.data || {};
194
+ const links = (d.assets && Array.isArray(d.assets.links)) ? d.assets.links : [];
195
+ const sources = (d.assets && Array.isArray(d.assets.sources)) ? d.assets.sources : [];
196
+ const rawAssets = links.length ? links : (Array.isArray(d.assets) ? d.assets : sources);
197
+ const assets = rawAssets.map((a) => ({
198
+ name: a.name || path.basename(String(a.url || '')),
199
+ url: a.url || null,
200
+ })).filter((a) => a.name);
201
+ return {
202
+ ok: true,
203
+ provider: 'gitlab',
204
+ offline: false,
205
+ tag: d.tag_name || String(tag),
206
+ draft: false,
207
+ assets,
208
+ };
209
+ },
210
+ };
211
+ }
212
+
213
+ function buildAzureDevopsAdapter(rootAbs, spawn) {
214
+ return {
215
+ provider: 'azure-devops',
216
+ offline: false,
217
+ listPullRequests(opts = {}) {
218
+ const args = ['repos', 'pr', 'list', '--output', 'json'];
219
+ if (opts.state) args.push('--status', opts.state === 'open' ? 'active' : String(opts.state));
220
+ const r = runCliJson(spawn, 'az', args, rootAbs);
221
+ if (!r.ok) return { ok: false, provider: 'azure-devops', offline: false, items: [], error: r.error };
222
+ const items = (Array.isArray(r.data) ? r.data : []).map((pr) => ({
223
+ number: Number(pr.pullRequestId != null ? pr.pullRequestId : pr.id),
224
+ title: pr.title || '',
225
+ branch: String(pr.sourceRefName || '').replace(/^refs\/heads\//, ''),
226
+ head_sha: (pr.lastMergeSourceCommit && pr.lastMergeSourceCommit.commitId) || null,
227
+ state: String(pr.status || 'active').toUpperCase(),
228
+ draft: Boolean(pr.isDraft),
229
+ url: pr.url || null,
230
+ labels: Array.isArray(pr.labels) ? pr.labels.map((l) => (typeof l === 'string' ? l : l.name)).filter(Boolean) : [],
231
+ }));
232
+ return { ok: true, provider: 'azure-devops', offline: false, items };
233
+ },
234
+ inspectCiStatus(opts = {}) {
235
+ const args = ['pipelines', 'runs', 'list', '--top', String(opts.limit || 10), '--output', 'json'];
236
+ if (opts.branch) args.push('--branch', String(opts.branch));
237
+ const r = runCliJson(spawn, 'az', args, rootAbs);
238
+ if (!r.ok) return { ok: false, provider: 'azure-devops', offline: false, runs: [], error: r.error };
239
+ const runs = (Array.isArray(r.data) ? r.data : []).map((run) => {
240
+ const res = String(run.result || '').toLowerCase();
241
+ const conclusion = res === 'succeeded' ? 'success' : (res === 'failed' ? 'failure' : (res || null));
242
+ return {
243
+ id: run.id || null,
244
+ status: String(run.status || 'unknown').toLowerCase(),
245
+ conclusion,
246
+ branch: String(run.sourceBranch || opts.branch || '').replace(/^refs\/heads\//, '') || null,
247
+ url: run.url || null,
248
+ };
249
+ });
250
+ return { ok: true, provider: 'azure-devops', offline: false, runs };
251
+ },
252
+ listReleaseAssets(tag) {
253
+ const r = runCliJson(spawn, 'az', ['pipelines', 'runs', 'artifact', 'list', '--run-id', String(tag), '--output', 'json'], rootAbs);
254
+ if (!r.ok) return { ok: false, provider: 'azure-devops', offline: false, tag: String(tag), assets: [], error: r.error };
255
+ const assets = (Array.isArray(r.data) ? r.data : []).map((a) => ({
256
+ name: a.name || String(a.id || ''),
257
+ url: (a.resource && a.resource.downloadUrl) || a.url || null,
258
+ })).filter((a) => a.name);
259
+ return { ok: true, provider: 'azure-devops', offline: false, tag: String(tag), draft: false, assets };
260
+ },
261
+ };
262
+ }
263
+
264
+ function buildLocalAdapter() {
265
+ return {
266
+ provider: 'local',
267
+ offline: true,
268
+ listPullRequests() {
269
+ return { ok: true, provider: 'local', offline: true, items: [], note: 'modo local offline — nenhum provedor remoto de PR/MR configurado' };
270
+ },
271
+ inspectCiStatus() {
272
+ return { ok: true, provider: 'local', offline: true, runs: [], note: 'modo local offline — valide localmente via phase_gates e oxe-cc runtime verify' };
273
+ },
274
+ listReleaseAssets(tag) {
275
+ return { ok: true, provider: 'local', offline: true, tag: String(tag || ''), draft: false, assets: [], note: 'modo local offline — sem release remota' };
276
+ },
277
+ };
278
+ }
279
+
280
+ function resolveCiAdapter(projectRoot, options = {}) {
281
+ const rootAbs = path.resolve(projectRoot || process.cwd());
282
+ const provider = detectCiProvider(rootAbs, options);
283
+ const spawn = options.spawn || spawnSync;
284
+ if (provider === 'github') return buildGithubAdapter(rootAbs, spawn);
285
+ if (provider === 'gitlab') return buildGitlabAdapter(rootAbs, spawn);
286
+ if (provider === 'azure-devops') return buildAzureDevopsAdapter(rootAbs, spawn);
287
+ return buildLocalAdapter();
288
+ }
289
+
290
+ function inspectCiStatus(projectRoot, options = {}) {
291
+ return resolveCiAdapter(projectRoot, options).inspectCiStatus(options);
292
+ }
293
+
294
+ function listReleaseAssets(projectRoot, tag, options = {}) {
295
+ return resolveCiAdapter(projectRoot, options).listReleaseAssets(tag, options);
296
+ }
297
+
298
+ module.exports = {
299
+ SUPPORTED_PROVIDERS,
300
+ detectCiProvider,
301
+ resolveCiAdapter,
302
+ inspectCiStatus,
303
+ listReleaseAssets,
304
+ };
@@ -18,7 +18,7 @@ const DECISION_RE_KT = /\b(if|for|while|when|catch)\b|&&|\|\||\?:/g;
18
18
  const START_RES = [
19
19
  /\bfunction\s*\*?\s*([A-Za-z_$][\w$]*)\s*\([^)]*\)[^{;]*\{/g,
20
20
  /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=>\s*\{/g,
21
- /^\s*(?:public|private|protected|static|async|override|suspend|\s)*\b(?!if\b|for\b|while\b|switch\b|when\b|catch\b|return\b)([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/gm,
21
+ /^[ \t]*(?:(?:public|private|protected|static|async|override|suspend)[ \t]+)*\b(?!if\b|for\b|while\b|switch\b|when\b|catch\b|return\b)([A-Za-z_$][\w$]*)[ \t]*\([^)\n]*\)[ \t]*(?::[ \t]*[^{\n]+)?\{/gm,
22
22
  /\bfun\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)[^{=]*\{/g,
23
23
  ];
24
24