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.
- package/.cursor/commands/oxe-discuss.md +45 -45
- package/.cursor/commands/oxe-execute.md +52 -52
- package/.cursor/commands/oxe-help.md +44 -44
- package/.cursor/commands/oxe-next.md +44 -44
- package/.cursor/commands/oxe-plan.md +49 -49
- package/.cursor/commands/oxe-quick.md +49 -49
- package/.cursor/commands/oxe-review-pr.md +47 -47
- package/.cursor/commands/oxe-scan.md +47 -47
- package/.cursor/commands/oxe-ship.md +47 -47
- package/.cursor/commands/oxe-spec.md +49 -49
- package/.cursor/commands/oxe-verify.md +50 -50
- package/.cursor/commands/oxe.md +51 -51
- package/.github/prompts/oxe-alm.prompt.md +47 -47
- package/.github/prompts/oxe-ask.prompt.md +47 -47
- package/.github/prompts/oxe-capabilities.prompt.md +47 -47
- package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
- package/.github/prompts/oxe-compact.prompt.md +46 -46
- package/.github/prompts/oxe-dashboard.prompt.md +47 -47
- package/.github/prompts/oxe-debug.prompt.md +47 -47
- package/.github/prompts/oxe-discuss.prompt.md +47 -47
- package/.github/prompts/oxe-execute.prompt.md +52 -52
- package/.github/prompts/oxe-forensics.prompt.md +47 -47
- package/.github/prompts/oxe-help.prompt.md +46 -46
- package/.github/prompts/oxe-loop.prompt.md +47 -47
- package/.github/prompts/oxe-milestone.prompt.md +47 -47
- package/.github/prompts/oxe-next.prompt.md +46 -46
- package/.github/prompts/oxe-obs.prompt.md +47 -47
- package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
- package/.github/prompts/oxe-plan.prompt.md +49 -49
- package/.github/prompts/oxe-project.prompt.md +47 -47
- package/.github/prompts/oxe-quick.prompt.md +49 -49
- package/.github/prompts/oxe-research.prompt.md +47 -47
- package/.github/prompts/oxe-retro.prompt.md +47 -47
- package/.github/prompts/oxe-review-pr.prompt.md +47 -47
- package/.github/prompts/oxe-route.prompt.md +47 -47
- package/.github/prompts/oxe-scan.prompt.md +47 -47
- package/.github/prompts/oxe-security.prompt.md +47 -47
- package/.github/prompts/oxe-session.prompt.md +47 -47
- package/.github/prompts/oxe-ship.prompt.md +47 -47
- package/.github/prompts/oxe-skill.prompt.md +47 -47
- package/.github/prompts/oxe-spec.prompt.md +49 -49
- package/.github/prompts/oxe-ui-review.prompt.md +47 -47
- package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
- package/.github/prompts/oxe-update.prompt.md +46 -46
- package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
- package/.github/prompts/oxe-verify.prompt.md +50 -50
- package/.github/prompts/oxe-workstream.prompt.md +47 -47
- package/.github/prompts/oxe.prompt.md +51 -51
- package/.github/workflows/release.yml +31 -0
- package/CHANGELOG.md +88 -0
- package/README.md +1 -1
- package/bin/lib/commands/ops-commands.cjs +751 -0
- package/bin/lib/commands/spec-program-commands.cjs +337 -0
- package/bin/lib/operational/alm-refine-runtime.cjs +791 -0
- package/bin/lib/operational/child-env.cjs +52 -0
- package/bin/lib/operational/promote-runtime.cjs +1187 -0
- package/bin/lib/oxe-agent-coord.cjs +246 -0
- package/bin/lib/oxe-alm-refine.cjs +97 -1
- package/bin/lib/oxe-ci-adapter.cjs +304 -0
- package/bin/lib/oxe-complexity.cjs +1 -1
- package/bin/lib/oxe-decisions.cjs +9 -3
- package/bin/lib/oxe-dir-info.cjs +20 -1
- package/bin/lib/oxe-env-sanitize.cjs +6 -1
- package/bin/lib/oxe-git-root.cjs +97 -0
- package/bin/lib/oxe-grill.cjs +90 -1
- package/bin/lib/oxe-onboard.cjs +640 -0
- package/bin/lib/oxe-operational.cjs +14481 -15949
- package/bin/lib/oxe-origin.cjs +4 -1
- package/bin/lib/oxe-phase-gates.cjs +139 -2
- package/bin/lib/oxe-plan-build.cjs +62 -2
- package/bin/lib/oxe-plan-mutate.cjs +108 -2
- package/bin/lib/oxe-preflight.cjs +9 -3
- package/bin/lib/oxe-presets.cjs +216 -0
- package/bin/lib/oxe-project-env.cjs +79 -0
- package/bin/lib/oxe-project-health.cjs +2 -0
- package/bin/lib/oxe-reevaluate.cjs +198 -0
- package/bin/lib/oxe-release-ops.cjs +51 -15
- package/bin/lib/oxe-scorecard.cjs +394 -1
- package/bin/lib/oxe-ship-pr.cjs +72 -4
- package/bin/lib/oxe-spec-check.cjs +32 -0
- package/bin/lib/oxe-suite-impact.cjs +1160 -1145
- package/bin/lib/oxe-sync.cjs +99 -2
- package/bin/lib/oxe-verify-cache.cjs +132 -0
- package/bin/lib/oxe-vitest-batch.cjs +10 -3
- package/bin/lib/oxe-worktree-gc.cjs +655 -170
- package/bin/oxe-cc.js +10042 -10669
- package/commands/oxe/alm.md +54 -54
- package/commands/oxe/ask.md +55 -55
- package/commands/oxe/capabilities.md +50 -50
- package/commands/oxe/checkpoint.md +53 -53
- package/commands/oxe/compact.md +47 -47
- package/commands/oxe/dashboard.md +51 -51
- package/commands/oxe/debug.md +58 -58
- package/commands/oxe/discuss.md +58 -58
- package/commands/oxe/execute.md +63 -63
- package/commands/oxe/forensics.md +53 -53
- package/commands/oxe/help.md +48 -48
- package/commands/oxe/loop.md +54 -54
- package/commands/oxe/milestone.md +53 -53
- package/commands/oxe/next.md +49 -49
- package/commands/oxe/obs.md +53 -53
- package/commands/oxe/oxe.md +55 -55
- package/commands/oxe/plan-agent.md +57 -57
- package/commands/oxe/plan.md +59 -59
- package/commands/oxe/project.md +53 -53
- package/commands/oxe/quick.md +53 -53
- package/commands/oxe/research.md +53 -53
- package/commands/oxe/retro.md +53 -53
- package/commands/oxe/review-pr.md +53 -53
- package/commands/oxe/route.md +48 -48
- package/commands/oxe/scan.md +58 -58
- package/commands/oxe/security.md +53 -53
- package/commands/oxe/session.md +53 -53
- package/commands/oxe/ship.md +53 -53
- package/commands/oxe/skill.md +53 -53
- package/commands/oxe/spec.md +59 -59
- package/commands/oxe/ui-review.md +53 -53
- package/commands/oxe/ui-spec.md +53 -53
- package/commands/oxe/update.md +53 -53
- package/commands/oxe/validate-gaps.md +53 -53
- package/commands/oxe/verify-audit.md +50 -50
- package/commands/oxe/verify.md +60 -60
- package/commands/oxe/workflow-authoring.md +50 -50
- package/commands/oxe/workstream.md +53 -53
- package/docs/RELEASE-READINESS.md +7 -1
- package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -29
- package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -29
- package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -29
- package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -29
- package/docs/adr/D-5-core-agnostico-vs-presets-declarativos-de-dominio.md +29 -0
- package/docs/adr/D-6-decomposicao-strangler-fig-de-oxe-cc-e-oxe-operational.md +29 -0
- package/docs/adr/D-7-paridade-pre-push-com-phase-gates-path-aware-json-compacto-e.md +28 -0
- package/docs/adr/D-F1F4-1-paridade-pre-push-compactacao-json-sync-version-pins-e-quali.md +44 -0
- package/docs/adr/README.md +18 -14
- package/lib/runtime/verification/verification-compiler.d.ts +12 -1
- package/lib/runtime/verification/verification-compiler.js +235 -65
- package/oxe/templates/CONFIG.md +14 -1
- package/oxe/workflows/help.md +3 -0
- package/oxe/workflows/lean/execute.md +2 -1
- package/oxe/workflows/ship.md +4 -2
- package/package.json +4 -4
- package/packages/runtime/package.json +1 -1
- package/packages/runtime/src/verification/verification-compiler.ts +193 -25
- package/packages/runtime/tsconfig.json +1 -0
- package/vscode-extension/package.json +1 -1
|
@@ -0,0 +1,1187 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 1.22.2 (OXB-222-16, ADR D-6 Fatia 2): Extracted promote runtime (`collectPromoteRiskSuites`,
|
|
5
|
+
* `finalizePromotedWorktree`, `finalizePromotePrBodyAndEvents`, `cleanupPromoteWorktree`,
|
|
6
|
+
* `runtimePromote`) with explicit dependency injection and zero circular require.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const { spawnSync } = require('child_process');
|
|
13
|
+
|
|
14
|
+
function createPromoteRuntime(deps = {}) {
|
|
15
|
+
const {
|
|
16
|
+
activeProgramPhase,
|
|
17
|
+
allocatePromoteWorktreePath,
|
|
18
|
+
almAutoSync,
|
|
19
|
+
appendEvent,
|
|
20
|
+
commitTaskVerifyTimeout,
|
|
21
|
+
dirtyProjectPaths,
|
|
22
|
+
gitLines,
|
|
23
|
+
gitRun,
|
|
24
|
+
loadRuntimeModule,
|
|
25
|
+
ownPushedPromoteBranch,
|
|
26
|
+
ownUnpushedPromoteBranch,
|
|
27
|
+
promoteAssumedTasks,
|
|
28
|
+
promoteStack,
|
|
29
|
+
promoteTestRoot,
|
|
30
|
+
readPlanJsonDoc,
|
|
31
|
+
readProjectConfig,
|
|
32
|
+
readTextIfExists,
|
|
33
|
+
resolveImportAt,
|
|
34
|
+
resolvePromoteBase,
|
|
35
|
+
resolveRuntimeArtifactPaths,
|
|
36
|
+
runChildCommandFull,
|
|
37
|
+
runProgressCommand,
|
|
38
|
+
sweepStalePromoteWorkspaces,
|
|
39
|
+
taskCommitShas,
|
|
40
|
+
taskPhaseContext,
|
|
41
|
+
timedOutMessage,
|
|
42
|
+
writeTextAtomic,
|
|
43
|
+
} = deps;
|
|
44
|
+
|
|
45
|
+
function collectPromoteRiskSuites(repoDir, { projectRoot, activeSession, planTasks, touchedFiles, excludeSuites = [], config = null }) {
|
|
46
|
+
const promoteHelpers = require('../oxe-promote-helpers.cjs');
|
|
47
|
+
const pcfg = config || readProjectConfig(projectRoot) || {};
|
|
48
|
+
const excludedList = (excludeSuites || []).map((s) => String(s || '').replace(/\\/g, '/'));
|
|
49
|
+
const riskSuites = promoteHelpers.discoverMainCiRiskSuites(repoDir, touchedFiles || [], {
|
|
50
|
+
excludeSuites: excludedList,
|
|
51
|
+
});
|
|
52
|
+
let planDoc = null;
|
|
53
|
+
try { planDoc = readPlanJsonDoc(projectRoot, activeSession).doc; } catch { planDoc = null; }
|
|
54
|
+
// OXB-C6 #1: Include non-frozen active unit/integration/e2e specs discovered by extended G45 on `repoDir`
|
|
55
|
+
try {
|
|
56
|
+
const lintCfg = (pcfg && pcfg.lint) || {};
|
|
57
|
+
if (lintCfg.cross_card_conflicts !== 'off') {
|
|
58
|
+
const pathsG45 = resolveRuntimeArtifactPaths(projectRoot, activeSession);
|
|
59
|
+
const g45Hits = require('../oxe-cross-card-conflicts.cjs').crossCardFrozenConflicts(
|
|
60
|
+
repoDir,
|
|
61
|
+
{
|
|
62
|
+
tasks: (planTasks || []).map((t) => ({ ...t, done: false })),
|
|
63
|
+
acceptance_tests: (planDoc && planDoc.acceptance_tests) || [],
|
|
64
|
+
},
|
|
65
|
+
{ specText: readTextIfExists(pathsG45.spec) || '' },
|
|
66
|
+
);
|
|
67
|
+
const excludedSet = new Set(excludedList);
|
|
68
|
+
const existingSuites = new Set(riskSuites.map((s) => s.suite));
|
|
69
|
+
for (const f of g45Hits) {
|
|
70
|
+
if (!f || !f.test || excludedSet.has(f.test) || existingSuites.has(f.test)) continue;
|
|
71
|
+
existingSuites.add(f.test);
|
|
72
|
+
const isE2e = /(^|\/)(e2e|playwright)\//i.test(f.test) || /\.e2e\./i.test(f.test)
|
|
73
|
+
|| (/\.spec\.[cm]?[jt]sx?$/i.test(f.test) && /@playwright\/test|playwright/i.test(readTextIfExists(path.join(repoDir, f.test)) || ''));
|
|
74
|
+
riskSuites.push({ suite: f.test, kind: isE2e ? 'e2e' : 'unit_g45', covers: [f.component || f.token || f.test] });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} catch { /* auxiliar */ }
|
|
78
|
+
return { riskSuites, planDoc };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function finalizePromotedWorktree({
|
|
82
|
+
projectRoot,
|
|
83
|
+
activeSession,
|
|
84
|
+
work,
|
|
85
|
+
result,
|
|
86
|
+
taskId,
|
|
87
|
+
planTasks,
|
|
88
|
+
phaseCtx,
|
|
89
|
+
base,
|
|
90
|
+
baseSha,
|
|
91
|
+
buildSha,
|
|
92
|
+
branch,
|
|
93
|
+
programTip,
|
|
94
|
+
withFixtures,
|
|
95
|
+
preserveMergedFixtures,
|
|
96
|
+
ordered,
|
|
97
|
+
verifyTests,
|
|
98
|
+
resolvedCapFiles,
|
|
99
|
+
pushArgs,
|
|
100
|
+
options,
|
|
101
|
+
}) {
|
|
102
|
+
const promoteHelpers = require('../oxe-promote-helpers.cjs');
|
|
103
|
+
const preserveMergedSet = new Set(Array.isArray(preserveMergedFixtures) ? preserveMergedFixtures : []);
|
|
104
|
+
const originTrailers = [
|
|
105
|
+
...planTasks.map((t) => `OXE-Task: ${phaseCtx.phase ? `${phaseCtx.phase}/` : ''}${t.id}`),
|
|
106
|
+
...[...new Set(planTasks.map((t) => t.run_id).filter(Boolean))].map((r) => `OXE-Run: ${r}`),
|
|
107
|
+
].join('\n');
|
|
108
|
+
const commitWorkFiles = (files, subject, body, errLabel) => {
|
|
109
|
+
if (!files || !files.length) return true;
|
|
110
|
+
gitRun(work, ['add', '--', ...files]);
|
|
111
|
+
if (gitRun(work, ['diff', '--cached', '--quiet']).ok) return true;
|
|
112
|
+
const cm = gitRun(work, ['commit', '-q', '-m', subject, '-m', body, '-m', originTrailers]);
|
|
113
|
+
if (!cm.ok) {
|
|
114
|
+
result.error = `${errLabel}: ${(cm.stderr || cm.stdout || '').trim().split(/\r?\n/).pop()}`;
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
return true;
|
|
118
|
+
};
|
|
119
|
+
const eqLf = (a, b) => a != null && b != null && a.replace(/\r\n/g, '\n') === b.replace(/\r\n/g, '\n');
|
|
120
|
+
// OXB-156 (b): the task's frozen tests as files from the program tip; identical-on-base ones are skipped.
|
|
121
|
+
// OXB-C8: fixtures modified on both `base` and the task's commits preserve cherry-pick's merge instead of overwriting with tip.
|
|
122
|
+
if (!result.conflict && withFixtures.length) {
|
|
123
|
+
const added = [];
|
|
124
|
+
for (const file of withFixtures) {
|
|
125
|
+
if (preserveMergedSet.has(file) && fs.existsSync(path.join(work, file))) continue;
|
|
126
|
+
const tip = gitRun(projectRoot, ['show', `${programTip}:${file}`]);
|
|
127
|
+
if (!tip.ok) continue;
|
|
128
|
+
const onBase = gitRun(projectRoot, ['show', `${baseSha}:${file}`]);
|
|
129
|
+
const current = fs.existsSync(path.join(work, file)) ? fs.readFileSync(path.join(work, file), 'utf8') : null;
|
|
130
|
+
if ((onBase.ok && eqLf(onBase.stdout, tip.stdout)) || eqLf(current, tip.stdout)) continue;
|
|
131
|
+
const r = spawnSync('git', ['show', `${programTip}:${file}`], { cwd: projectRoot, windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
|
|
132
|
+
fs.mkdirSync(path.dirname(path.join(work, file)), { recursive: true });
|
|
133
|
+
fs.writeFileSync(path.join(work, file), r.stdout);
|
|
134
|
+
added.push(file);
|
|
135
|
+
}
|
|
136
|
+
if (added.length) {
|
|
137
|
+
commitWorkFiles(
|
|
138
|
+
added,
|
|
139
|
+
`test(acceptance): frozen tests of ${taskId}`,
|
|
140
|
+
`From the program branch at ${String(programTip).slice(0, 10)}: ${added.join(', ')}`,
|
|
141
|
+
'commit dos testes congelados falhou',
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
result.frozen_tests = added;
|
|
145
|
+
}
|
|
146
|
+
if (!result.conflict && !result.error) {
|
|
147
|
+
const pcfg = readProjectConfig(projectRoot) || {};
|
|
148
|
+
const lockAdj = promoteHelpers.reconcilePromotedEnforcedLocks(
|
|
149
|
+
projectRoot,
|
|
150
|
+
work,
|
|
151
|
+
buildSha,
|
|
152
|
+
Array.isArray(ordered) ? ordered : null,
|
|
153
|
+
{ resolve: options && options.resolve },
|
|
154
|
+
);
|
|
155
|
+
if (lockAdj.adjusted.length) {
|
|
156
|
+
const lockMsg = lockAdj.adjusted.map((a) => `${a.file}: removido(s) [${a.removed_ids.join(', ') || 'stale'}] de fora de ${base}`).join('\n');
|
|
157
|
+
commitWorkFiles(
|
|
158
|
+
lockAdj.files,
|
|
159
|
+
`chore(lock): reconcile enforced lock of ${taskId} on ${base}`,
|
|
160
|
+
lockMsg,
|
|
161
|
+
'commit de ajuste de enforced.lock falhou',
|
|
162
|
+
);
|
|
163
|
+
result.enforced_locks_adjusted = lockAdj.adjusted;
|
|
164
|
+
const pruned = [...new Set(lockAdj.adjusted.flatMap((a) => a.removed_ids || []))];
|
|
165
|
+
if (pruned.length) {
|
|
166
|
+
result.warnings.push(`enforced.lock reconciliado contra ${base} + ${taskId}: removido(s) ${pruned.join(', ')} (já ausente(s)/retirado(s) em ${base})`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const ratchetAdj = promoteHelpers.reconcilePromotedRatchets(work, buildSha, pcfg, { resolvedCapFiles: [...resolvedCapFiles] });
|
|
170
|
+
if (ratchetAdj.adjusted.length) {
|
|
171
|
+
commitWorkFiles(
|
|
172
|
+
ratchetAdj.files,
|
|
173
|
+
`chore(ratchet): reconcile ratchet caps of ${taskId} on ${base}`,
|
|
174
|
+
ratchetAdj.adjusted.map((a) => `${a.file}:${a.line} ${a.program_cap} -> ${a.promoted_cap} (real count: ${a.real_count})`).join('\n'),
|
|
175
|
+
'commit de ajuste de ratchet falhou',
|
|
176
|
+
);
|
|
177
|
+
result.ratchets_adjusted = ratchetAdj.adjusted;
|
|
178
|
+
result.warnings.push(`ratchet(s) recalculado(s) contra ${base} + ${taskId}: ${ratchetAdj.adjusted.map((a) => `${a.file}:${a.line} ${a.program_cap} → ${a.promoted_cap}`).join(', ')}`);
|
|
179
|
+
}
|
|
180
|
+
const enforcedCheck = promoteHelpers.checkPromotedEnforcedTargets(work, buildSha, { base, config: pcfg });
|
|
181
|
+
if (enforcedCheck.gaps.length) {
|
|
182
|
+
result.enforced_scene_gaps = enforcedCheck.gaps;
|
|
183
|
+
result.warnings.push(...enforcedCheck.warnings);
|
|
184
|
+
}
|
|
185
|
+
// OXB-222-03: reconcile sequential migrations & sync.version_pins against base inside the promoted worktree.
|
|
186
|
+
const syncEnabled = !(pcfg.sync && pcfg.sync.on_promote === false) && !(options && options.sync === false);
|
|
187
|
+
if (syncEnabled && !result.error) {
|
|
188
|
+
try {
|
|
189
|
+
const syncLib = require('../oxe-sync.cjs');
|
|
190
|
+
const syncPlan = syncLib.syncSequentialResources(work, { base: buildSha, config: pcfg, apply: false });
|
|
191
|
+
if ((syncPlan.migration_bumps && syncPlan.migration_bumps.length) || (syncPlan.version_pin_updates && syncPlan.version_pin_updates.length)) {
|
|
192
|
+
const syncApplied = syncLib.syncSequentialResources(work, { base: buildSha, config: pcfg, apply: true });
|
|
193
|
+
const existingToStage = [...new Set([
|
|
194
|
+
...(syncApplied.applied_migrations || []).map((m) => m.to),
|
|
195
|
+
...(syncApplied.applied_version_pins || []).map((p) => p.file),
|
|
196
|
+
])].filter((f) => f && fs.existsSync(path.join(work, f)));
|
|
197
|
+
const deletedToStage = [...new Set((syncApplied.applied_migrations || []).map((m) => m.from))]
|
|
198
|
+
.filter((f) => f && !fs.existsSync(path.join(work, f)));
|
|
199
|
+
if (deletedToStage.length) gitRun(work, ['rm', '-q', '--ignore-unmatch', '--', ...deletedToStage]);
|
|
200
|
+
if (existingToStage.length) gitRun(work, ['add', '--', ...existingToStage]);
|
|
201
|
+
if ((existingToStage.length || deletedToStage.length) && !gitRun(work, ['diff', '--cached', '--quiet']).ok) {
|
|
202
|
+
const summaryLines = [
|
|
203
|
+
...(syncApplied.applied_migrations || []).map((m) => `${m.from} -> ${m.to}`),
|
|
204
|
+
...(syncApplied.applied_version_pins || []).map((p) => `${p.file}${p.label ? ` (${p.label})` : ''}: ${p.from} -> ${p.to}`),
|
|
205
|
+
];
|
|
206
|
+
const cm = gitRun(work, [
|
|
207
|
+
'commit', '-q',
|
|
208
|
+
'-m', `chore(sync): bump sequential resources of ${taskId} on ${base}`,
|
|
209
|
+
'-m', summaryLines.join('\n'),
|
|
210
|
+
'-m', originTrailers,
|
|
211
|
+
]);
|
|
212
|
+
if (!cm.ok) {
|
|
213
|
+
result.error = `commit de sync sequencial falhou: ${(cm.stderr || cm.stdout || '').trim().split(/\r?\n/).pop()}`;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
result.sync = syncApplied;
|
|
217
|
+
result.warnings.push(`sync sequencial aplicado contra ${base}: ${(syncApplied.applied_migrations || []).length} migration(s), ${(syncApplied.applied_version_pins || []).length} version_pin(s)`);
|
|
218
|
+
}
|
|
219
|
+
} catch (err) {
|
|
220
|
+
result.warnings.push(`sync sequencial no promote falhou: ${err && err.message ? err.message : String(err)}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (!result.conflict && !result.error) {
|
|
225
|
+
const icLib = require('../oxe-integration-checks.cjs');
|
|
226
|
+
const parked = icLib.findTrackedParkedAcceptance(work, { baseRef: baseSha });
|
|
227
|
+
if (parked.length) {
|
|
228
|
+
result.parked_acceptance = parked;
|
|
229
|
+
result.error = `gate de PR bloqueado em ${branch}: ${icLib.formatParkedAcceptanceError(parked)}`;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (!result.conflict && !result.error && options.integrationChecks !== false) {
|
|
233
|
+
const ic = require('../oxe-integration-checks.cjs').runIntegrationChecks(work, { configRoot: projectRoot, baseRef: baseSha });
|
|
234
|
+
if (ic.ran.length) result.integration_checks = ic.ran;
|
|
235
|
+
if (!ic.ok) result.error = `check de integração vermelho em ${branch}: \`${ic.failed.command}\` (exit ${ic.failed.exit})${ic.failed.tail ? `\n${String(ic.failed.tail).split(/\r?\n/).slice(-5).map((l) => ` ${l}`).join('\n')}\n` : ''} — nada foi enviado; a branch local ${branch} fica (não enviada). Corrija no programa (ex.: um quick que reduz o arquivo acima do teto, ou npm run notices:generate) e rode o promote de novo: a branch é refeita com o conserto`;
|
|
236
|
+
}
|
|
237
|
+
if (!result.conflict && !result.error) {
|
|
238
|
+
const pcfg = readProjectConfig(projectRoot) || {};
|
|
239
|
+
const promotedDiffFiles = gitLines(work, ['diff', '--name-only', buildSha, 'HEAD']) || [];
|
|
240
|
+
const { riskSuites, planDoc } = collectPromoteRiskSuites(work, {
|
|
241
|
+
projectRoot,
|
|
242
|
+
activeSession,
|
|
243
|
+
planTasks,
|
|
244
|
+
touchedFiles: promotedDiffFiles,
|
|
245
|
+
excludeSuites: [...verifyTests, ...(result.frozen_tests || [])],
|
|
246
|
+
config: pcfg,
|
|
247
|
+
});
|
|
248
|
+
if (riskSuites.length) result.ci_risk_suites = riskSuites;
|
|
249
|
+
if (options.previewCi) {
|
|
250
|
+
const previewCmds = promoteHelpers.buildPreviewCiCommands(work, riskSuites, pcfg, { projectRoot, planTasks, planDoc });
|
|
251
|
+
const previewRuns = [];
|
|
252
|
+
let previewOk = true;
|
|
253
|
+
const baseVerifyTimeout = Number(pcfg.verify_timeout_ms) > 0 ? Number(pcfg.verify_timeout_ms) : 10 * 60_000;
|
|
254
|
+
for (const cmd of previewCmds) {
|
|
255
|
+
const ms = commitTaskVerifyTimeout(projectRoot, options, cmd, baseVerifyTimeout);
|
|
256
|
+
const r = runChildCommandFull(work, cmd, ms);
|
|
257
|
+
const failInfo = !r.ok ? promoteHelpers.extractPreviewCiFailure(r.output || r.tail) : null;
|
|
258
|
+
previewRuns.push({
|
|
259
|
+
command: cmd,
|
|
260
|
+
ok: r.ok,
|
|
261
|
+
status: r.status,
|
|
262
|
+
timed_out: r.timedOut,
|
|
263
|
+
tail: failInfo ? failInfo.summary : r.tail,
|
|
264
|
+
...(failInfo && failInfo.failing_specs.length ? { failing_specs: failInfo.failing_specs } : {}),
|
|
265
|
+
});
|
|
266
|
+
if (!r.ok) {
|
|
267
|
+
previewOk = false;
|
|
268
|
+
const specLine = failInfo && failInfo.failing_specs.length
|
|
269
|
+
? `\n spec(s) falhando: ${failInfo.failing_specs.join(', ')}`
|
|
270
|
+
: '';
|
|
271
|
+
const detailText = failInfo ? failInfo.summary : String(r.tail || '');
|
|
272
|
+
const detailLines = detailText
|
|
273
|
+
? `\n${detailText.split(/\r?\n/).filter(Boolean).slice(-8).map((l) => ` ${l}`).join('\n')}`
|
|
274
|
+
: '';
|
|
275
|
+
result.error = r.timedOut
|
|
276
|
+
? timedOutMessage(`preview-ci em ${branch}`, cmd, ms, { ...r, tail: detailText || r.tail })
|
|
277
|
+
: `preview-ci vermelho em ${branch}: \`${cmd}\` (exit ${r.status})${specLine}${detailLines}`;
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
result.preview_ci = { ok: previewOk, suites: riskSuites.map((s) => s.suite), runs: previewRuns };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (!result.conflict && options.openPr && !result.error) {
|
|
285
|
+
const push = gitRun(work, pushArgs());
|
|
286
|
+
if (!push.ok) result.error = `push falhou: ${push.stderr.trim().split(/\r?\n/).slice(-2).join(' · ')}`;
|
|
287
|
+
else result.pushed = true;
|
|
288
|
+
}
|
|
289
|
+
if (!result.conflict && !result.error) {
|
|
290
|
+
let pkg = null;
|
|
291
|
+
try { pkg = JSON.parse(fs.readFileSync(path.join(work, 'package.json'), 'utf8')); } catch { pkg = null; }
|
|
292
|
+
if (pkg && pkg.scripts && pkg.scripts['pr:ready'] && options.prReady !== false) {
|
|
293
|
+
const ready = runProgressCommand(work, 'npm run pr:ready', 1_800_000, { quiet: options.quietProgress === true || process.env.OXE_PROGRESS === '0' });
|
|
294
|
+
const tail = String(ready.tail || '');
|
|
295
|
+
const STATUS_LINE = /not on GitHub yet|push it first|(post|create|set)\w*\s+(the\s+)?(commit\s+)?status/i;
|
|
296
|
+
const otherLines = tail.split(/\r?\n/).filter((l) => !STATUS_LINE.test(l) && !/^\s*npm (ERR!|error|warn)\b/i.test(l)).join('\n');
|
|
297
|
+
const statusOnly = !ready.ok && STATUS_LINE.test(tail) && !/\bFAIL\b|\bfailed\b|✗|×|error TS\d+|\d+ (failing|failed)/i.test(otherLines);
|
|
298
|
+
result.pr_ready = { ok: ready.ok || statusOnly, tail: ready.tail, ...(statusOnly ? { status_post_failed: true } : {}) };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function finalizePromotePrBodyAndEvents({
|
|
304
|
+
projectRoot,
|
|
305
|
+
activeSession,
|
|
306
|
+
result,
|
|
307
|
+
task,
|
|
308
|
+
taskId,
|
|
309
|
+
criteria,
|
|
310
|
+
ordered,
|
|
311
|
+
branch,
|
|
312
|
+
original,
|
|
313
|
+
base,
|
|
314
|
+
remote,
|
|
315
|
+
stack,
|
|
316
|
+
pushArgs,
|
|
317
|
+
options,
|
|
318
|
+
}) {
|
|
319
|
+
const paths = resolveRuntimeArtifactPaths(projectRoot, activeSession);
|
|
320
|
+
const crs = require('../oxe-change.cjs').listChanges(paths.programDir || path.join(projectRoot, '.oxe', 'program'))
|
|
321
|
+
.filter((cr) => (cr.criteria || []).some((a) => criteria.has(a)));
|
|
322
|
+
const body = [
|
|
323
|
+
`## ${taskId} — ${task.title || ''}`.trim(),
|
|
324
|
+
'',
|
|
325
|
+
options.testsOnly
|
|
326
|
+
? `Promovida de \`${original}\` por \`oxe-cc runtime promote --tests-only\` (apenas ${((result.frozen_tests || []).length)} arquivo(s) de testes congelados e fixtures; commits de código já na base).`
|
|
327
|
+
: `Promovida de \`${original}\` por \`oxe-cc runtime promote\` (cherry-pick -x de ${ordered.length} commit(s)).`,
|
|
328
|
+
'',
|
|
329
|
+
...(stack ? [
|
|
330
|
+
`> **Empilhada sobre ${stack.task}** (${stack.pr ? `PR ${stack.pr}, ` : ''}branch \`${stack.branch}\`), ainda não mergeada em \`${base}\`: este PR traz os commits dela até ela entrar. Mergeie ${stack.task} primeiro; depois disso o diff deste PR encolhe para os commits de ${taskId}.`,
|
|
331
|
+
'',
|
|
332
|
+
] : []),
|
|
333
|
+
'### Arquivos',
|
|
334
|
+
...(task.files || []).map((f) => `- \`${f}\``),
|
|
335
|
+
'',
|
|
336
|
+
`### Critérios: ${[...criteria].join(', ') || '—'}`,
|
|
337
|
+
...(crs.length ? ['', '### Change requests', ...crs.map((cr) => `- ${cr.id} (${cr.class}, ${cr.status}): ${cr.summary}`)] : []),
|
|
338
|
+
'',
|
|
339
|
+
'### Commits da tarefa',
|
|
340
|
+
...(ordered.length ? ordered.map((sha) => `- ${sha.slice(0, 10)} ${(gitLines(projectRoot, ['log', '-1', '--format=%s', sha]) || [''])[0]}`) : ['- —']),
|
|
341
|
+
'',
|
|
342
|
+
'### Testes congelados (arquivos do tip do programa)',
|
|
343
|
+
...((result.frozen_tests || []).length ? result.frozen_tests.map((f) => `- \`${f}\``) : ['- — (já na base, ou nenhum)']),
|
|
344
|
+
...((result.quick_commits || []).length ? ['', '### Quicks incluídos', ...result.quick_commits.map((q) => `- ${q.sha.slice(0, 10)} (${q.quick}${q.card ? `, ${q.card}` : ''})`)] : []),
|
|
345
|
+
...((result.ratchets_adjusted || []).length ? ['', '### Ratchets ajustados para a base', ...result.ratchets_adjusted.map((a) => `- \`${a.file}:${a.line}\`: ${a.program_cap} → ${a.promoted_cap} (contagem real na branch: ${a.real_count})`)] : []),
|
|
346
|
+
...(result.suggested_promote_order && result.suggested_promote_order.length ? ['', `### Ordem sugerida de promoção: ${result.suggested_promote_order.join(' → ')}`] : []),
|
|
347
|
+
...(((result.ci_risk_suites && result.ci_risk_suites.length) || (result.enforced_scene_gaps && result.enforced_scene_gaps.length)) ? [
|
|
348
|
+
'',
|
|
349
|
+
'### Riscos de CI na main (fora do verify da tarefa)',
|
|
350
|
+
...((result.ci_risk_suites || []).map((s) => `- \`${s.suite}\` (${s.kind} — cobre ${s.covers.map((c) => `\`${c}\``).join(', ')})`)),
|
|
351
|
+
...((result.enforced_scene_gaps || []).map((g) => `- \`${g.file}\` → \`${g.id}\`: seletor \`${g.selector}\` ausente na cena de conformidade (sugestão: manter \`${g.proposed_status}\` — ${g.proposed_reason})`)),
|
|
352
|
+
] : []),
|
|
353
|
+
...(result.preview_ci ? ['', `### preview-ci: ${result.preview_ci.ok ? 'verde' : 'VERMELHO'} (${result.preview_ci.suites.length} suíte(s))`] : []),
|
|
354
|
+
...(result.pr_ready ? ['', `### pr:ready: ${result.pr_ready.ok ? 'verde' : 'VERMELHO'}`] : []),
|
|
355
|
+
'',
|
|
356
|
+
].join('\n');
|
|
357
|
+
const bodyFile = path.join(projectRoot, '.oxe', 'promote', `${taskId}.md`);
|
|
358
|
+
writeTextAtomic(bodyFile, body);
|
|
359
|
+
result.body_file = path.relative(projectRoot, bodyFile).replace(/\\/g, '/');
|
|
360
|
+
let almKey = null;
|
|
361
|
+
const lookupIds = [taskId, ...(Array.isArray(options.taskIds) ? options.taskIds : [])].filter(Boolean);
|
|
362
|
+
try {
|
|
363
|
+
const almLib = require('../oxe-alm.cjs');
|
|
364
|
+
const cfgAlm = almLib.almConfig(readProjectConfig(projectRoot) || {});
|
|
365
|
+
const ph = activeProgramPhase(projectRoot, activeSession);
|
|
366
|
+
const pd = resolveRuntimeArtifactPaths(projectRoot, activeSession).programDir || path.join(projectRoot, '.oxe', 'program');
|
|
367
|
+
if (cfgAlm) {
|
|
368
|
+
for (const lid of lookupIds) {
|
|
369
|
+
almKey = almLib.keyFor(pd, cfgAlm, ph ? ph.id : null, lid);
|
|
370
|
+
if (almKey) break;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
} catch { almKey = null; }
|
|
374
|
+
if (almKey) result.alm_key = almKey;
|
|
375
|
+
if (almKey) {
|
|
376
|
+
try {
|
|
377
|
+
const almLib = require('../oxe-alm.cjs');
|
|
378
|
+
const cfgAlm = almLib.almConfig(readProjectConfig(projectRoot) || {});
|
|
379
|
+
const ph = activeProgramPhase(projectRoot, activeSession);
|
|
380
|
+
const pd = resolveRuntimeArtifactPaths(projectRoot, activeSession).programDir || path.join(projectRoot, '.oxe', 'program');
|
|
381
|
+
const docM = readPlanJsonDoc(projectRoot, activeSession).doc;
|
|
382
|
+
const promotedSet = new Set(lookupIds);
|
|
383
|
+
const docForMarker = docM && promotedSet.size > 1 && Array.isArray(docM.tasks)
|
|
384
|
+
? { ...docM, tasks: docM.tasks.map((t) => (t && promotedSet.has(t.id) ? { ...t, done: true } : t)) }
|
|
385
|
+
: docM;
|
|
386
|
+
const mk = require('../oxe-alm-prs.cjs').prMarkerFor(almKey, taskId, docForMarker, (id) => almLib.keyFor(pd, cfgAlm, ph ? ph.id : null, id));
|
|
387
|
+
if (mk) {
|
|
388
|
+
result.alm_marker = mk.marker;
|
|
389
|
+
writeTextAtomic(bodyFile, `${body}\n${mk.marker}${mk.open_tasks.length ? ` (ainda abertas no card: ${mk.open_tasks.join(', ')})` : ''}\n`);
|
|
390
|
+
}
|
|
391
|
+
} catch { /* auxiliar: o PR segue sem o marcador */ }
|
|
392
|
+
}
|
|
393
|
+
const title = `${taskId}: ${task.title || 'promote'}${almKey ? ` (${almKey})` : ''}`;
|
|
394
|
+
const prBase = base.replace(new RegExp(`^${remote}/`), '');
|
|
395
|
+
result.commands = [
|
|
396
|
+
`git push -u ${remote} ${branch}`,
|
|
397
|
+
`gh pr create --base ${prBase} --head ${branch} --title ${JSON.stringify(title)} --body-file ${result.body_file}`,
|
|
398
|
+
];
|
|
399
|
+
if (options.openPr && !result.error) {
|
|
400
|
+
if (result.pr_ready && !result.pr_ready.ok) {
|
|
401
|
+
result.error = `pr:ready vermelho em ${branch} — PR não aberto (a branch já está em ${remote}; corrija e rode os comandos abaixo — o PR vai contra ${prBase}${stack ? `, não contra a branch de ${stack.task}` : ''})`;
|
|
402
|
+
} else {
|
|
403
|
+
const push = result.pushed ? { ok: true } : gitRun(projectRoot, pushArgs());
|
|
404
|
+
if (!push.ok) result.error = `push falhou: ${push.stderr.trim().split(/\r?\n/).slice(-2).join(' · ')}`;
|
|
405
|
+
else {
|
|
406
|
+
const gh = (options.ghSpawn || spawnSync)('gh', ['pr', 'create', '--base', prBase, '--head', branch, '--title', title, '--body-file', bodyFile], { cwd: projectRoot, encoding: 'utf8', windowsHide: true });
|
|
407
|
+
if (gh.status === 0) result.pr = String(gh.stdout || '').trim().split(/\r?\n/).pop();
|
|
408
|
+
else result.error = `gh pr create falhou: ${String(gh.stderr || gh.stdout || '').trim().split(/\r?\n/).slice(-2).join(' · ')}`;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
appendEvent(projectRoot, activeSession, { type: 'TaskPromoted', work_item_id: taskId, payload: { base, branch, commits: ordered, pr_ready: result.pr_ready ? result.pr_ready.ok : null, pr: result.pr, ...(stack ? { stacked_on: result.stacked_on } : {}) } });
|
|
413
|
+
almAutoSync(projectRoot, activeSession);
|
|
414
|
+
return result;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function cleanupPromoteWorktree(projectRoot, wt, linked) {
|
|
418
|
+
const rel = path.relative(projectRoot, wt).replace(/\\/g, '/');
|
|
419
|
+
try {
|
|
420
|
+
const rt = loadRuntimeModule();
|
|
421
|
+
if (rt && typeof rt.unlinkExternalLinks === 'function') rt.unlinkExternalLinks(wt);
|
|
422
|
+
else if (linked && fs.existsSync(path.join(wt, 'node_modules'))) fs.unlinkSync(path.join(wt, 'node_modules'));
|
|
423
|
+
} catch { /* */ }
|
|
424
|
+
let rm = gitRun(projectRoot, ['worktree', 'remove', wt]);
|
|
425
|
+
if (!rm.ok) {
|
|
426
|
+
let linkLeft = false;
|
|
427
|
+
try { linkLeft = fs.lstatSync(path.join(wt, 'node_modules')).isSymbolicLink(); } catch { linkLeft = false; }
|
|
428
|
+
if (!linkLeft) rm = gitRun(projectRoot, ['worktree', 'remove', '--force', wt]);
|
|
429
|
+
}
|
|
430
|
+
if (rm.ok) { try { fs.rmSync(`${wt}.pid`, { force: true }); } catch { /* */ } }
|
|
431
|
+
gitRun(projectRoot, ['worktree', 'prune']);
|
|
432
|
+
return rm.ok ? null : `worktree ${rel} não removida (${rm.stderr.trim().split(/\r?\n/).pop()}) — remova à mão depois de conferir que não há links dentro`;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* `oxe-cc runtime promote <Tn> --base main [--branch name] [--open-pr] [--remote origin]`: a branch from the base with
|
|
437
|
+
* the task's checkpoint commits (OXE-Task trailer / done_commit) and the commits of its frozen acceptance tests,
|
|
438
|
+
* cherry-picked with -x in history order. Stops (and cleans up, unless `--keep-on-conflict`) on a conflict; resolves
|
|
439
|
+
* `lint.ratchets` cap-only conflicts and append-only `enforced.lock.json` JSON unions automatically (or per `--resolve`).
|
|
440
|
+
*/
|
|
441
|
+
function runtimePromote(projectRoot, activeSession, options = {}) {
|
|
442
|
+
const promoteHelpers = require('../oxe-promote-helpers.cjs');
|
|
443
|
+
promoteHelpers.parseResolveRules(options.resolve); // fail fast on malformed --resolve rules
|
|
444
|
+
if (!gitLines(projectRoot, ['rev-parse', '--git-dir'])) throw new Error('runtime promote exige um repositório git');
|
|
445
|
+
|
|
446
|
+
const pendingFile = path.join(projectRoot, '.oxe', 'promote', 'pending-conflict.json');
|
|
447
|
+
const original = (gitLines(projectRoot, ['rev-parse', '--abbrev-ref', 'HEAD']) || [])[0];
|
|
448
|
+
const originalSha = (gitLines(projectRoot, ['rev-parse', 'HEAD']) || [])[0];
|
|
449
|
+
const remote = String(options.remote || 'origin');
|
|
450
|
+
|
|
451
|
+
if (options.continue === true) {
|
|
452
|
+
if (!fs.existsSync(pendingFile)) {
|
|
453
|
+
throw new Error('nenhum promote pausado em conflito (.oxe/promote/pending-conflict.json não encontrado)');
|
|
454
|
+
}
|
|
455
|
+
const saved = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
|
|
456
|
+
if ((options.task || options.tasks) && saved.task) {
|
|
457
|
+
const reqIds = [...new Set((options.tasks ? (Array.isArray(options.tasks) ? options.tasks : String(options.tasks).split(',')) : [options.task]).map((t) => String(t || '').trim().toUpperCase()).filter(Boolean))].join('-');
|
|
458
|
+
if (reqIds && reqIds !== saved.task) {
|
|
459
|
+
throw new Error(`promote pausado é para ${saved.task} (worktree ${path.relative(projectRoot, saved.worktree).replace(/\\/g, '/')}), não para ${reqIds}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const work = saved.worktree;
|
|
463
|
+
if (!fs.existsSync(work)) {
|
|
464
|
+
throw new Error(`worktree do promote pausado não existe mais (${saved.worktree}) — rode o promote do início sem --continue`);
|
|
465
|
+
}
|
|
466
|
+
const taskId = saved.task;
|
|
467
|
+
const taskIds = saved.taskIds || [];
|
|
468
|
+
const branch = saved.branch;
|
|
469
|
+
const base = saved.base;
|
|
470
|
+
const baseSha = saved.baseSha;
|
|
471
|
+
const buildSha = saved.buildSha || baseSha;
|
|
472
|
+
const programTip = saved.programTip || originalSha;
|
|
473
|
+
const ordered = saved.ordered || [];
|
|
474
|
+
const remaining = Array.isArray(saved.remaining_commits) ? saved.remaining_commits : [];
|
|
475
|
+
const withFixtures = saved.withFixtures || [];
|
|
476
|
+
const verifyTests = saved.verifyTests || [];
|
|
477
|
+
const sharedSkipped = saved.sharedSkipped || [];
|
|
478
|
+
const criteria = new Set(saved.criteria || []);
|
|
479
|
+
const phaseCtx = saved.phaseCtx || taskPhaseContext(projectRoot, activeSession);
|
|
480
|
+
const { doc } = readPlanJsonDoc(projectRoot, activeSession);
|
|
481
|
+
const planTasks = taskIds.map((id) => (doc && Array.isArray(doc.tasks) ? doc.tasks.find((x) => x && x.id === id) : null) || { id, acceptance: saved.criteria || [], files: [] });
|
|
482
|
+
const task = saved.taskMeta || planTasks[0];
|
|
483
|
+
const resolvedCapFiles = new Set(saved.resolved_cap_files || []);
|
|
484
|
+
const resolvedConflicts = Array.isArray(saved.resolved_conflicts) ? [...saved.resolved_conflicts] : [];
|
|
485
|
+
const result = {
|
|
486
|
+
...(saved.resultSnapshot || {}),
|
|
487
|
+
task: taskId,
|
|
488
|
+
branch,
|
|
489
|
+
base,
|
|
490
|
+
base_sha: baseSha,
|
|
491
|
+
worktree: path.relative(projectRoot, work).replace(/\\/g, '/'),
|
|
492
|
+
conflict: null,
|
|
493
|
+
error: undefined,
|
|
494
|
+
warnings: [...((saved.resultSnapshot && saved.resultSnapshot.warnings) || [])],
|
|
495
|
+
resumed_from_conflict: true,
|
|
496
|
+
};
|
|
497
|
+
if (resolvedConflicts.length) result.resolved_conflicts = resolvedConflicts;
|
|
498
|
+
const pcfg = readProjectConfig(projectRoot) || {};
|
|
499
|
+
const linked = (() => { try { return fs.lstatSync(path.join(work, 'node_modules')).isSymbolicLink(); } catch { return false; } })();
|
|
500
|
+
let keepWorktree = false;
|
|
501
|
+
const cleanup = () => {
|
|
502
|
+
if (saved.inPlace) {
|
|
503
|
+
gitRun(projectRoot, ['checkout', '-q', original && original !== 'HEAD' ? original : originalSha]);
|
|
504
|
+
} else {
|
|
505
|
+
const w = cleanupPromoteWorktree(projectRoot, work, linked);
|
|
506
|
+
if (w) result.cleanup_warning = w;
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
const pushArgs = () => ['push', ...(saved.forceLease ? [`--force-with-lease=${branch}:${saved.forceLease}`] : []), '-u', saved.remote || remote, branch];
|
|
510
|
+
const onSignal = (sig) => { try { if (!keepWorktree) cleanup(); } catch { /* */ } process.exit(sig === 'SIGINT' ? 130 : 143); };
|
|
511
|
+
const signals = ['SIGINT', 'SIGTERM'];
|
|
512
|
+
for (const sig of signals) process.once(sig, onSignal);
|
|
513
|
+
try {
|
|
514
|
+
const stillUnmerged = gitLines(work, ['diff', '--name-only', '--diff-filter=U']) || [];
|
|
515
|
+
if (stillUnmerged.length && options.resolve && (Array.isArray(options.resolve) ? options.resolve.length : options.resolve)) {
|
|
516
|
+
const res = promoteHelpers.tryResolvePromoteCherryPickConflict(projectRoot, work, saved.conflict_commit, pcfg, stillUnmerged, { resolve: options.resolve, skipRatchet: true, commit: false });
|
|
517
|
+
if (res.resolved && res.resolved_files) {
|
|
518
|
+
for (const rf of res.resolved_files) {
|
|
519
|
+
resolvedConflicts.push({ commit: saved.conflict_commit, ...rf });
|
|
520
|
+
result.warnings.push(`conflito resolvido em ${rf.file} (${rf.strategy})`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
const unmergedAfter = gitLines(work, ['diff', '--name-only', '--diff-filter=U']) || [];
|
|
525
|
+
if (unmergedAfter.length) {
|
|
526
|
+
keepWorktree = true;
|
|
527
|
+
result.conflict = { commit: saved.conflict_commit, files: unmergedAfter };
|
|
528
|
+
result.kept_worktree = result.worktree;
|
|
529
|
+
result.error = `conflito ainda aberto em ${unmergedAfter.join(', ')} (worktree ${result.worktree}) — resolva, rode \`git add\` e depois \`oxe-cc runtime promote ${taskId} --continue\` (ou passe --resolve <arquivo>=ours|theirs|union-json-array)`;
|
|
530
|
+
} else if (gitLines(work, ['rev-parse', '--verify', '-q', 'CHERRY_PICK_HEAD'])) {
|
|
531
|
+
const cached = gitRun(work, ['diff', '--cached', '--quiet']);
|
|
532
|
+
const contRes = cached.ok
|
|
533
|
+
? gitRun(work, ['cherry-pick', '--skip'])
|
|
534
|
+
: spawnSync('git', ['-c', 'core.editor=true', 'cherry-pick', '--continue'], { cwd: work, encoding: 'utf8', windowsHide: true, env: { ...process.env, GIT_EDITOR: 'true' } });
|
|
535
|
+
if ((contRes.status != null ? contRes.status : (contRes.ok ? 0 : 1)) !== 0) {
|
|
536
|
+
keepWorktree = true;
|
|
537
|
+
result.conflict = { commit: saved.conflict_commit, files: gitLines(work, ['diff', '--name-only', '--diff-filter=U']) || [] };
|
|
538
|
+
result.kept_worktree = result.worktree;
|
|
539
|
+
result.error = `cherry-pick --continue falhou em ${result.worktree}: ${String(contRes.stderr || contRes.stdout || '').trim().split(/\r?\n/).slice(-3).join(' · ')}`;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (!result.conflict && !result.error) {
|
|
543
|
+
for (let idx = 0; idx < remaining.length; idx += 1) {
|
|
544
|
+
const sha = remaining[idx];
|
|
545
|
+
const pick = gitRun(work, ['cherry-pick', '-x', sha]);
|
|
546
|
+
if (!pick.ok) {
|
|
547
|
+
const files = gitLines(work, ['diff', '--name-only', '--diff-filter=U']) || [];
|
|
548
|
+
const auto = promoteHelpers.tryResolvePromoteCherryPickConflict(projectRoot, work, sha, pcfg, files, { resolve: options.resolve });
|
|
549
|
+
if (auto.resolved) {
|
|
550
|
+
for (const rf of auto.resolved_cap_files || []) resolvedCapFiles.add(rf);
|
|
551
|
+
for (const rf of auto.resolved_files || []) {
|
|
552
|
+
resolvedConflicts.push({ commit: sha, ...rf });
|
|
553
|
+
result.warnings.push(`conflito auto-resolvido em ${rf.file} (${rf.strategy})`);
|
|
554
|
+
}
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
keepWorktree = true;
|
|
558
|
+
const updatedPending = { ...saved, conflict_commit: sha, remaining_commits: remaining.slice(idx + 1), resolved_cap_files: [...resolvedCapFiles], resolved_conflicts: resolvedConflicts };
|
|
559
|
+
writeTextAtomic(pendingFile, `${JSON.stringify(updatedPending, null, 2)}\n`);
|
|
560
|
+
result.conflict = { commit: sha, files };
|
|
561
|
+
result.kept_worktree = result.worktree;
|
|
562
|
+
result.error = `conflito no cherry-pick de ${sha.slice(0, 8)} (${files.join(', ') || 'sem arquivos'}) — worktree mantida em ${result.worktree}; resolva, rode \`git add\` e \`oxe-cc runtime promote ${taskId} --continue\` (ou use --resolve <arquivo>=ours|theirs|union-json-array)`;
|
|
563
|
+
break;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (!result.conflict && !result.error) {
|
|
568
|
+
if (resolvedConflicts.length) result.resolved_conflicts = resolvedConflicts;
|
|
569
|
+
finalizePromotedWorktree({
|
|
570
|
+
projectRoot,
|
|
571
|
+
activeSession,
|
|
572
|
+
work,
|
|
573
|
+
result,
|
|
574
|
+
task,
|
|
575
|
+
taskId,
|
|
576
|
+
taskIds,
|
|
577
|
+
planTasks,
|
|
578
|
+
phaseCtx,
|
|
579
|
+
base,
|
|
580
|
+
baseSha,
|
|
581
|
+
buildSha,
|
|
582
|
+
branch,
|
|
583
|
+
remote: saved.remote || remote,
|
|
584
|
+
programTip,
|
|
585
|
+
withFixtures,
|
|
586
|
+
preserveMergedFixtures: saved.preserveMergedFixtures || [],
|
|
587
|
+
ordered,
|
|
588
|
+
verifyTests,
|
|
589
|
+
criteria,
|
|
590
|
+
resolvedCapFiles,
|
|
591
|
+
pushArgs,
|
|
592
|
+
options,
|
|
593
|
+
});
|
|
594
|
+
try { fs.rmSync(pendingFile, { force: true }); } catch { /* */ }
|
|
595
|
+
}
|
|
596
|
+
} finally {
|
|
597
|
+
for (const sig of signals) process.removeListener(sig, onSignal);
|
|
598
|
+
if (!keepWorktree) cleanup();
|
|
599
|
+
}
|
|
600
|
+
if (result.conflict) {
|
|
601
|
+
appendEvent(projectRoot, activeSession, { type: 'TaskPromoteFailed', work_item_id: taskId, payload: { base, reason: result.error || 'conflict', commit: result.conflict.commit, files: result.conflict.files, kept_worktree: result.kept_worktree || null } });
|
|
602
|
+
return result;
|
|
603
|
+
}
|
|
604
|
+
return finalizePromotePrBodyAndEvents({ projectRoot, activeSession, result, task, taskId, criteria, ordered, branch, original: saved.original || original, base, remote: saved.remote || remote, stack: saved.stack || null, pushArgs, options: { ...options, taskIds } });
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// OXB-169: `--tasks T4,T5,T6,T7` builds ONE branch from the tasks' commits in commit order (the execute may commit
|
|
608
|
+
// them out of plan order — a checkpoint retry committed T4/T5 after T6/T7, and T4's diff assumed theirs).
|
|
609
|
+
const taskIds = [...new Set((options.tasks ? (Array.isArray(options.tasks) ? options.tasks : String(options.tasks).split(',')) : [options.task])
|
|
610
|
+
.map((t) => String(t || '').trim().toUpperCase()).filter(Boolean))];
|
|
611
|
+
if (!taskIds.length || !taskIds.every((t) => /^T\d+$/.test(t))) throw new Error('informe a tarefa: oxe-cc runtime promote T<n> --base main (ou --tasks T4,T5,…)');
|
|
612
|
+
const taskId = taskIds.join('-');
|
|
613
|
+
const testsOnly = options.testsOnly === true;
|
|
614
|
+
// OXB-157: `--base main` used the LOCAL main (11 days old) — the PR conflicted on files identical on origin/main.
|
|
615
|
+
const resolvedBase = resolvePromoteBase(projectRoot, options.base, remote, options);
|
|
616
|
+
const base = resolvedBase.ref;
|
|
617
|
+
// OXB-151: by default promote works in its OWN temporary worktree — the program tree (checkout, index, node_modules)
|
|
618
|
+
// is never touched, so it is safe while `runtime execute` runs there. --in-place keeps the old behavior.
|
|
619
|
+
const inPlace = options.inPlace === true;
|
|
620
|
+
if (inPlace && !options.dryRun) {
|
|
621
|
+
const dirty = dirtyProjectPaths(projectRoot);
|
|
622
|
+
if (dirty.length) throw new Error(`working tree com mudanças fora de .oxe/ (${dirty.slice(0, 5).join(', ')}) — faça commit ou stash antes do promote`);
|
|
623
|
+
}
|
|
624
|
+
let baseSha = (gitLines(projectRoot, ['rev-parse', '--verify', `${base}^{commit}`]) || [])[0];
|
|
625
|
+
if (!baseSha) throw new Error(`base desconhecida: ${base}`);
|
|
626
|
+
const { doc } = readPlanJsonDoc(projectRoot, activeSession);
|
|
627
|
+
const planTasks = taskIds.map((id) => {
|
|
628
|
+
const t = doc && Array.isArray(doc.tasks) ? doc.tasks.find((x) => x && x.id === id) : null;
|
|
629
|
+
if (!t) throw new Error(`${id} não está no PLAN.json`);
|
|
630
|
+
if (t.done !== true) throw new Error(`${id} não está done — só uma tarefa concluída e verde é promovida`);
|
|
631
|
+
return t;
|
|
632
|
+
});
|
|
633
|
+
const idSet = new Set(taskIds);
|
|
634
|
+
// One task: itself. Several: their union — files, criteria, and the dependencies OUTSIDE the set (for stacking).
|
|
635
|
+
const task = planTasks.length === 1 ? planTasks[0] : {
|
|
636
|
+
id: taskId,
|
|
637
|
+
title: planTasks.map((t) => `${t.id} ${t.title || ''}`.trim()).join(' · '),
|
|
638
|
+
files: [...new Set(planTasks.flatMap((t) => t.files || []))],
|
|
639
|
+
acceptance: [...new Set(planTasks.flatMap((t) => t.acceptance || []))],
|
|
640
|
+
depends_on: [...new Set(planTasks.flatMap((t) => t.depends_on || []))].filter((d) => !idSet.has(d)),
|
|
641
|
+
done: true,
|
|
642
|
+
};
|
|
643
|
+
// Commits of the task not yet in the base: its checkpoints and the frozen tests of its criteria.
|
|
644
|
+
const range = `${baseSha}..HEAD`;
|
|
645
|
+
// OXB-166: by phase + task; with a done_commit, the phase-less legacy trailers are not searched at all.
|
|
646
|
+
const phaseCtx = taskPhaseContext(projectRoot, activeSession);
|
|
647
|
+
const shas = new Set();
|
|
648
|
+
if (!testsOnly) {
|
|
649
|
+
const inRangeAll = gitLines(projectRoot, ['rev-list', range]) || [];
|
|
650
|
+
for (const t of planTasks) {
|
|
651
|
+
const own = t.done_commit && phaseCtx.phase
|
|
652
|
+
? (gitLines(projectRoot, ['log', '--format=%H', '-E', `--grep=^OXE-Task: ${phaseCtx.phase}/${t.id}$`, range]) || [])
|
|
653
|
+
: taskCommitShas(projectRoot, t.id, range, phaseCtx);
|
|
654
|
+
for (const sha of own) shas.add(sha);
|
|
655
|
+
if (t.done_commit) {
|
|
656
|
+
const full = (gitLines(projectRoot, ['rev-parse', '--verify', `${t.done_commit}^{commit}`]) || [])[0];
|
|
657
|
+
if (full && inRangeAll.includes(full)) shas.add(full);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
const quickSelection = (testsOnly || options.quicks === false)
|
|
662
|
+
? { quicks: [], skipped: [], warnings: [] }
|
|
663
|
+
: promoteHelpers.selectPromoteQuickCommits(projectRoot, {
|
|
664
|
+
range,
|
|
665
|
+
orderedTaskShas: [...shas],
|
|
666
|
+
planTasks,
|
|
667
|
+
allTasks: doc && Array.isArray(doc.tasks) ? doc.tasks : [],
|
|
668
|
+
phase: phaseCtx.phase,
|
|
669
|
+
programDir: resolveRuntimeArtifactPaths(projectRoot, activeSession).programDir,
|
|
670
|
+
config: readProjectConfig(projectRoot) || {},
|
|
671
|
+
});
|
|
672
|
+
if (!testsOnly) for (const q of quickSelection.quicks) shas.add(q.sha);
|
|
673
|
+
// OXB-C27-3 (polish2 989902e60): the planner's single frozen-tests commit (only acceptance test files, of several
|
|
674
|
+
// tasks) is never cherry-picked — every task PR carried the others' red tests. The task's own frozen tests are
|
|
675
|
+
// carried as files below (OXB-156); the commit leaves the pick list, named in the warnings.
|
|
676
|
+
{
|
|
677
|
+
const frozenOwner = new Map();
|
|
678
|
+
for (const a of (doc && Array.isArray(doc.acceptance_tests) ? doc.acceptance_tests : [])) {
|
|
679
|
+
for (const f of (a && a.files) || []) {
|
|
680
|
+
const rel = String(typeof f === 'string' ? f : (f && f.path) || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
681
|
+
if (!rel) continue;
|
|
682
|
+
if (!frozenOwner.has(rel)) frozenOwner.set(rel, new Set());
|
|
683
|
+
frozenOwner.get(rel).add(String(a.task || a.criterion || '?').toUpperCase());
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (frozenOwner.size) {
|
|
687
|
+
for (const sha of [...shas]) {
|
|
688
|
+
const files = (gitLines(projectRoot, ['show', '--name-only', '--format=', '--no-renames', sha]) || []).map((f) => f.replace(/\\/g, '/')).filter((f) => f && !f.startsWith('.oxe/'));
|
|
689
|
+
if (!files.length || !files.every((f) => frozenOwner.has(f))) continue;
|
|
690
|
+
const owners = new Set(files.flatMap((f) => [...frozenOwner.get(f)]));
|
|
691
|
+
const ownCriteria = new Set(planTasks.flatMap((t) => (t.acceptance || []).map((c) => String(c).toUpperCase())));
|
|
692
|
+
const foreign = [...owners].filter((o) => !idSet.has(o) && !ownCriteria.has(o));
|
|
693
|
+
if (!foreign.length) continue;
|
|
694
|
+
shas.delete(sha);
|
|
695
|
+
resolvedBase.warnings.push(`${sha.slice(0, 8)} é o commit de testes congelados do planejador (também de ${foreign.slice(0, 6).join(', ')}): não vai no PR; os congelados de ${taskIds.join(',')} vão como arquivos [OXB-C27-3]`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const criteria = new Set(Array.isArray(task.acceptance) ? task.acceptance : []);
|
|
700
|
+
// OXB-156: the PR carries (a) the task's OWN commits (OXE-Task trailer / done_commit) and (b) the frozen tests it
|
|
701
|
+
// proves, taken as FILES from the program tip (+ the local fixtures they import) — never the program branch's import
|
|
702
|
+
// commits, which also carry other tasks' and parked tests (F2-T1: a conflict on tests/acceptance/parked-f3/…).
|
|
703
|
+
const programTip = (gitLines(projectRoot, ['rev-parse', 'HEAD']) || [])[0];
|
|
704
|
+
const TEST_FILE_RE = /(^|\/)(tests?|__tests__|spec)\/|\.(test|spec)\.[cm]?[jt]sx?$/i;
|
|
705
|
+
const normRel = (f) => String(typeof f === 'string' ? f : (f && f.path) || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
706
|
+
const differsFromBase = (file) => {
|
|
707
|
+
const tip = gitRun(projectRoot, ['show', `${programTip}:${file}`]);
|
|
708
|
+
if (!tip.ok) return false;
|
|
709
|
+
const onBase = gitRun(projectRoot, ['show', `${baseSha}:${file}`]);
|
|
710
|
+
return !(onBase.ok && onBase.stdout === tip.stdout);
|
|
711
|
+
};
|
|
712
|
+
// OxeSpace 15/11 (OxeCode F6 T30): the task was built against u83 as RE-FROZEN by a CR's quick (cdfd414f9) — a test
|
|
713
|
+
// in its FILES, not an acceptance entry of it — and the PR carried main's old u83, which its code turns red. The
|
|
714
|
+
// test files of the task's own scope that differ from the base go in too, as files from the program tip.
|
|
715
|
+
const scopeCandidates = [...new Set(planTasks.flatMap((t) => (t.files || []).map(normRel)))].filter((f) => f && !f.includes('*') && !f.endsWith('/') && TEST_FILE_RE.test(f) && differsFromBase(f));
|
|
716
|
+
// cross-review 15/11: a SHARED suite (in the files of several waves) that ANOTHER task already changed on the program
|
|
717
|
+
// branch is never copied from the tip — it would bring that task's unpromoted assertions into this PR. Only a file
|
|
718
|
+
// whose changes in the range come from this task or from no task (a CR quick re-freeze) is carried.
|
|
719
|
+
const otherTaskTouched = (file) => {
|
|
720
|
+
const bodies = (gitRun(projectRoot, ['log', '--format=%B%x00', `${baseSha}..HEAD`, '--', file]).stdout || '').split('\0');
|
|
721
|
+
// phase-aware (OXB-166): F5/T3 is not the T3 of F6 being promoted
|
|
722
|
+
return bodies.some((b) => {
|
|
723
|
+
if ([...b.matchAll(/^OXE-Task:\s*(?:(F\d+)\/)?(T\d+)\s*$/gm)].some((m) => (phaseCtx.phase && m[1] && m[1] !== phaseCtx.phase) || !idSet.has(m[2]))) return true;
|
|
724
|
+
// OXB-C23-2 (152chat T5, tests/design-lint.test.ts 415→406): a QUICK that did another task (no OXE-Task trailer,
|
|
725
|
+
// it names T10) changed the file too — the tip carries that task's assertions. A quick naming this task (a CR
|
|
726
|
+
// re-freeze of its test) is still ours.
|
|
727
|
+
if (!/^OXE-Quick:/m.test(b)) return false;
|
|
728
|
+
const named = [...b.matchAll(/(?:(F\d+)\/)?\b(T\d+)\b/g)].filter((m) => !(phaseCtx.phase && m[1] && m[1] !== phaseCtx.phase)).map((m) => m[2]);
|
|
729
|
+
return named.length > 0 && !named.some((t) => idSet.has(t));
|
|
730
|
+
});
|
|
731
|
+
};
|
|
732
|
+
const scopeTests = scopeCandidates.filter((f) => !otherTaskTouched(f));
|
|
733
|
+
const sharedSkipped = scopeCandidates.filter((f) => !scopeTests.includes(f));
|
|
734
|
+
// OXB-C31-2 (152perf T2, #1050): the planner's commit (OXE-Plan) froze T2's test AND amended tests/agent-state.test.ts,
|
|
735
|
+
// a NON-frozen test that T2's behavior change makes wrong. The planner commit is never cherry-picked, so the PR would
|
|
736
|
+
// be born red. When a planner commit touches this task's own frozen tests, the non-frozen tests it amended go too (as
|
|
737
|
+
// files from the tip) — unless another task's frozen tests share that commit or another task changed the file: then
|
|
738
|
+
// the promote says the amendment stays out.
|
|
739
|
+
const ownFrozenFiles = new Set((Array.isArray(doc.acceptance_tests) ? doc.acceptance_tests : [])
|
|
740
|
+
.filter((a) => a && ((a.task && idSet.has(a.task)) || (!a.task && criteria.has(a.criterion))))
|
|
741
|
+
.flatMap((a) => (a.files || []).map(normRel)));
|
|
742
|
+
const anyFrozen = new Map();
|
|
743
|
+
for (const a of (Array.isArray(doc.acceptance_tests) ? doc.acceptance_tests : [])) {
|
|
744
|
+
for (const f of (a && a.files) || []) {
|
|
745
|
+
const rel = normRel(f);
|
|
746
|
+
if (!rel) continue;
|
|
747
|
+
if (!anyFrozen.has(rel)) anyFrozen.set(rel, new Set());
|
|
748
|
+
anyFrozen.get(rel).add(String(a.task || a.criterion || '?').toUpperCase());
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const plannerAmends = [];
|
|
752
|
+
const plannerWarnings = [];
|
|
753
|
+
if (!testsOnly && ownFrozenFiles.size) {
|
|
754
|
+
for (const sha of gitLines(projectRoot, ['rev-list', '--reverse', range]) || []) {
|
|
755
|
+
const body = (gitRun(projectRoot, ['log', '-1', '--format=%B', sha]).stdout) || '';
|
|
756
|
+
if (!/^OXE-Plan:/m.test(body)) continue;
|
|
757
|
+
const files = (gitLines(projectRoot, ['show', '--name-only', '--format=', '--no-renames', sha]) || []).map((f) => f.replace(/\\/g, '/')).filter((f) => f && !f.startsWith('.oxe/'));
|
|
758
|
+
if (!files.some((f) => ownFrozenFiles.has(f))) continue;
|
|
759
|
+
const otherFrozenOwners = [...new Set(files.filter((f) => anyFrozen.has(f) && !ownFrozenFiles.has(f)).flatMap((f) => [...anyFrozen.get(f)]))].filter((o) => !idSet.has(o) && !criteria.has(o));
|
|
760
|
+
for (const f of files.filter((x) => !anyFrozen.has(x) && TEST_FILE_RE.test(x))) {
|
|
761
|
+
if (plannerAmends.includes(f) || scopeTests.includes(f) || !differsFromBase(f)) continue;
|
|
762
|
+
if (otherFrozenOwners.length) plannerWarnings.push(`emenda do planejador em ${f} (${sha.slice(0, 8)}) fica de fora: o mesmo commit congela testes de ${otherFrozenOwners.slice(0, 4).join(', ')} — se ${taskId} precisa dela, ponha ${f} nos files da tarefa [OXB-C31-2]`);
|
|
763
|
+
else if (otherTaskTouched(f)) plannerWarnings.push(`emenda do planejador em ${f} (${sha.slice(0, 8)}) fica de fora: outra tarefa também mudou o arquivo no programa — promova junto se precisar das duas [OXB-C31-2]`);
|
|
764
|
+
else plannerAmends.push(f);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const testFiles = [...new Set([...ownFrozenFiles, ...scopeTests, ...plannerAmends])];
|
|
769
|
+
// a test the verify runs that differs from the base but is NOT the task's (not in its files nor its entries): the PR
|
|
770
|
+
// runs the base version — named, with the commits that changed it, never carried silently
|
|
771
|
+
const verifyTests = [...new Set(planTasks.flatMap((t) => [...((t.verify && t.verify.commands) || []), t.verify && t.verify.command, t.verifyCommand].filter(Boolean).join(' ').replace(/\\/g, '/').match(/[^\s"'`]+/g) || []))]
|
|
772
|
+
.map(normRel).filter((s) => s.includes('/') && TEST_FILE_RE.test(s) && /\.[cm]?[jt]sx?$/i.test(s));
|
|
773
|
+
// a shared suite that is ALSO the task's own frozen entry is carried (as before): never reported as not carried
|
|
774
|
+
const notCarried = [...new Set([...verifyTests.filter((f) => !testFiles.includes(f) && differsFromBase(f)), ...sharedSkipped.filter((f) => !testFiles.includes(f))])];
|
|
775
|
+
if (!shas.size && !testFiles.length) throw new Error(`${taskId}: nenhum commit da tarefa fora de ${base} (sem trailer OXE-Task/done_commit em ${base}..HEAD) — já está na base?`);
|
|
776
|
+
const ordered = testsOnly ? [] : (gitLines(projectRoot, ['rev-list', '--reverse', '--topo-order', range]) || []).filter((sha) => shas.has(sha));
|
|
777
|
+
// local fixtures the frozen tests import (relative specifiers), one level deep — OXB-160 + OXB-C8 (T59 / #917):
|
|
778
|
+
// carry a local fixture from the program tree ONLY when it is new on `base` (not deleted on `base`) or when THIS
|
|
779
|
+
// task itself modified it; otherwise keep `base`'s file and warn when `base` has a newer/divergent version.
|
|
780
|
+
const directTestSet = new Set(testFiles);
|
|
781
|
+
const mergeBaseWithBase = (gitLines(projectRoot, ['merge-base', baseSha, programTip]) || [])[0] || null;
|
|
782
|
+
const skippedFixtures = [];
|
|
783
|
+
const preserveMergedFixtures = [];
|
|
784
|
+
const fixtureWarnings = [];
|
|
785
|
+
const withFixtures = (() => {
|
|
786
|
+
const out = new Set(testFiles);
|
|
787
|
+
const seenFixtures = new Set();
|
|
788
|
+
for (const file of testFiles) {
|
|
789
|
+
const root = promoteTestRoot(file);
|
|
790
|
+
const text = (gitRun(projectRoot, ['show', `${programTip}:${file}`]).stdout) || '';
|
|
791
|
+
for (const m of text.matchAll(/(?:from\s+|require\(\s*|import\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g)) {
|
|
792
|
+
const cand = resolveImportAt(projectRoot, programTip, path.posix.normalize(path.posix.join(path.posix.dirname(file), m[1])));
|
|
793
|
+
if (!cand || !(cand + '/').startsWith(root + '/') || /\/src\//.test(`/${cand}`)) continue;
|
|
794
|
+
if (directTestSet.has(cand) || seenFixtures.has(cand)) continue;
|
|
795
|
+
seenFixtures.add(cand);
|
|
796
|
+
|
|
797
|
+
const existsOnBase = gitRun(projectRoot, ['show', `${baseSha}:${cand}`]).ok;
|
|
798
|
+
const divergesFromBase = differsFromBase(cand);
|
|
799
|
+
if (!divergesFromBase) {
|
|
800
|
+
out.add(cand);
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
const baseChangedAfterFork = mergeBaseWithBase
|
|
804
|
+
? (gitLines(projectRoot, ['diff', '--name-only', mergeBaseWithBase, baseSha, '--', cand]) || []).length > 0
|
|
805
|
+
: false;
|
|
806
|
+
const existsAtMergeBase = mergeBaseWithBase ? gitRun(projectRoot, ['show', `${mergeBaseWithBase}:${cand}`]).ok : false;
|
|
807
|
+
const deletedOnBase = !existsOnBase && existsAtMergeBase && baseChangedAfterFork;
|
|
808
|
+
const taskCommitsTouching = (gitLines(projectRoot, ['log', '--no-merges', '--format=%H', range, '--', cand]) || []).filter((h) => shas.has(h));
|
|
809
|
+
const inTaskFiles = planTasks.some((t) => (t.files || []).some((f) => normRel(f) === cand));
|
|
810
|
+
const taskChangedFixture = taskCommitsTouching.length > 0 || (inTaskFiles && !otherTaskTouched(cand));
|
|
811
|
+
|
|
812
|
+
if ((existsOnBase || deletedOnBase) && !taskChangedFixture) {
|
|
813
|
+
const reason = deletedOnBase ? 'removed_on_base' : (baseChangedAfterFork ? 'older_than_base' : 'not_changed_by_task');
|
|
814
|
+
skippedFixtures.push({ file: cand, reason });
|
|
815
|
+
fixtureWarnings.push(
|
|
816
|
+
`fixture ${cand} importada pelo teste congelado difere de ${base}, mas não foi alterada por ${taskId}${deletedOnBase ? ` (removida em ${base})` : baseChangedAfterFork ? ` (cópia do programa é mais antiga que ${base})` : ''} — mantida a versão de ${base}`
|
|
817
|
+
);
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if (baseChangedAfterFork) {
|
|
822
|
+
if (!testsOnly && taskCommitsTouching.length > 0) {
|
|
823
|
+
preserveMergedFixtures.push(cand);
|
|
824
|
+
fixtureWarnings.push(
|
|
825
|
+
`fixture ${cand} alterada por ${taskId} também mudou em ${base} após o fork — mantida a mescla do cherry-pick em vez da cópia antiga do programa`
|
|
826
|
+
);
|
|
827
|
+
} else {
|
|
828
|
+
fixtureWarnings.push(
|
|
829
|
+
`fixture ${cand} carregada do programa difere de ${base}, que a modificou após o fork (cópia pode estar mais antiga que ${base})`
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
out.add(cand);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return [...out];
|
|
837
|
+
})();
|
|
838
|
+
if (testsOnly) {
|
|
839
|
+
const differingTests = withFixtures.filter((f) => differsFromBase(f));
|
|
840
|
+
if (!withFixtures.length || !differingTests.length) {
|
|
841
|
+
throw new Error(`${taskId}: nenhum teste congelado ou fixture diferente de ${base} para promover com --tests-only`);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// OXB-169: other tasks' unpromoted commits BEFORE this task's, on the same files — this diff assumes them; the
|
|
845
|
+
// cherry-pick will likely conflict. Name them and the combined promote.
|
|
846
|
+
const assumed = testsOnly ? [] : promoteAssumedTasks(projectRoot, range, ordered, idSet, phaseCtx);
|
|
847
|
+
// ALM: with an item for the task, the branch starts with its key ("oxe-12-t3"; Azure DevOps "ab-123-t3").
|
|
848
|
+
let branchKey = null;
|
|
849
|
+
try {
|
|
850
|
+
const almLib = require('../oxe-alm.cjs');
|
|
851
|
+
const almCfg = almLib.almConfig(readProjectConfig(projectRoot) || {});
|
|
852
|
+
const ph = activeProgramPhase(projectRoot, activeSession);
|
|
853
|
+
const pd = resolveRuntimeArtifactPaths(projectRoot, activeSession).programDir || path.join(projectRoot, '.oxe', 'program');
|
|
854
|
+
let k = null;
|
|
855
|
+
if (almCfg) {
|
|
856
|
+
for (const lid of [taskId, ...taskIds]) {
|
|
857
|
+
k = almLib.keyFor(pd, almCfg, ph ? ph.id : null, lid);
|
|
858
|
+
if (k) break;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
branchKey = k ? k.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null;
|
|
862
|
+
} catch { branchKey = null; }
|
|
863
|
+
const branch = String(options.branch || (branchKey ? `${branchKey}-${taskId.toLowerCase()}` : `oxe/promote-${taskId.toLowerCase()}`)).trim();
|
|
864
|
+
const stackInfo = promoteStack(projectRoot, activeSession, task, { base, baseSha, remote, options });
|
|
865
|
+
baseSha = stackInfo.baseSha;
|
|
866
|
+
const stack = stackInfo.stack;
|
|
867
|
+
const buildSha = stack ? stack.sha : baseSha;
|
|
868
|
+
const unpromoDeps = testsOnly
|
|
869
|
+
? { dependencies: [], suggested_order: [], warnings: [] }
|
|
870
|
+
: promoteHelpers.analyzeUnpromotedDependencies(projectRoot, {
|
|
871
|
+
range,
|
|
872
|
+
baseSha: buildSha,
|
|
873
|
+
orderedTaskShas: ordered,
|
|
874
|
+
planTasks,
|
|
875
|
+
phase: phaseCtx.phase,
|
|
876
|
+
stackedTaskIds: stack ? [stack.task] : [],
|
|
877
|
+
});
|
|
878
|
+
if (options.strict && unpromoDeps.dependencies.length) {
|
|
879
|
+
throw new Error(`promote --strict recusado para ${taskId}: ${unpromoDeps.warnings[0]}`);
|
|
880
|
+
}
|
|
881
|
+
resolvedBase.warnings = [...(resolvedBase.warnings || []), ...stackInfo.warnings, ...quickSelection.warnings, ...fixtureWarnings, ...plannerWarnings, ...plannerAmends.map((f) => `${f}: emenda do planejador (commit OXE-Plan que congelou os testes de ${taskId}) vai no PR como arquivo [OXB-C31-2]`)];
|
|
882
|
+
if (assumed.length && !stack) {
|
|
883
|
+
resolvedBase.warnings.push(`${taskId} vem depois de ${assumed.map((a) => `${a.task} (${a.sha.slice(0, 8)})`).join(', ')} no histórico e mexe nos mesmos arquivos (${[...new Set(assumed.flatMap((a) => a.files))].slice(0, 4).join(', ')}) — o cherry-pick pode conflitar; promova junto: oxe-cc runtime promote --tasks ${[...new Set([...assumed.map((a) => a.task), ...taskIds])].join(',')}`);
|
|
884
|
+
}
|
|
885
|
+
for (const w of unpromoDeps.warnings) {
|
|
886
|
+
if (!resolvedBase.warnings.includes(w)) resolvedBase.warnings.push(w);
|
|
887
|
+
}
|
|
888
|
+
const notCarriedWarnings = [];
|
|
889
|
+
for (const f of notCarried) {
|
|
890
|
+
const by = (gitLines(projectRoot, ['log', '--format=%h %s', range, '--', f]) || []).slice(0, 3);
|
|
891
|
+
notCarriedWarnings.push(sharedSkipped.includes(f)
|
|
892
|
+
? `${f} está nos files de ${taskId}, mas outra tarefa também o mudou no programa: o PR leva só o que o cherry-pick da tarefa trouxe (não a versão da ponta, com as asserções dela)${by.length ? ` — commits: ${by.join('; ')}` : ''}. Se precisar das duas, promova junto`
|
|
893
|
+
: `${f} está no verify de ${taskId} e difere de ${base}, mas não é da tarefa (fora dos files e dos testes congelados dela): o PR roda a versão de ${base}${by.length ? ` — mudado por ${by.join('; ')}` : ''}. Se a tarefa foi construída contra a nova, ponha o arquivo nos files dela (ou promova junto com a dona)`);
|
|
894
|
+
}
|
|
895
|
+
resolvedBase.warnings.push(...notCarriedWarnings);
|
|
896
|
+
if (options.dryRun) {
|
|
897
|
+
const quickShaSet = new Set(quickSelection.quicks.map((q) => q.sha));
|
|
898
|
+
const pcfgDry = readProjectConfig(projectRoot) || {};
|
|
899
|
+
const dryTouchedFiles = [...new Set([
|
|
900
|
+
...planTasks.flatMap((t) => (t.files || []).map(normRel)),
|
|
901
|
+
...ordered.flatMap((sha) => gitLines(projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', sha]) || []),
|
|
902
|
+
])].filter((f) => f && !f.includes('*'));
|
|
903
|
+
const { riskSuites: dryRiskSuites, planDoc: dryPlanDoc } = collectPromoteRiskSuites(projectRoot, {
|
|
904
|
+
projectRoot,
|
|
905
|
+
activeSession,
|
|
906
|
+
planTasks,
|
|
907
|
+
touchedFiles: dryTouchedFiles,
|
|
908
|
+
excludeSuites: [...verifyTests, ...withFixtures],
|
|
909
|
+
config: pcfgDry,
|
|
910
|
+
});
|
|
911
|
+
const dryPreviewCmds = options.previewCi && dryRiskSuites.length
|
|
912
|
+
? promoteHelpers.buildPreviewCiCommands(projectRoot, dryRiskSuites, pcfgDry, { projectRoot, planTasks, planDoc: dryPlanDoc })
|
|
913
|
+
: [];
|
|
914
|
+
return {
|
|
915
|
+
dry_run: true,
|
|
916
|
+
...(testsOnly ? { tests_only: true } : {}),
|
|
917
|
+
task: taskId,
|
|
918
|
+
base,
|
|
919
|
+
base_sha: baseSha,
|
|
920
|
+
...(stack ? { stacked_on: { task: stack.task, branch: stack.branch, pr: stack.pr || null, sha: stack.sha } } : {}),
|
|
921
|
+
base_requested: resolvedBase.requested,
|
|
922
|
+
warnings: resolvedBase.warnings,
|
|
923
|
+
branch,
|
|
924
|
+
commits: ordered,
|
|
925
|
+
commit_details: ordered.map((sha) => ({
|
|
926
|
+
sha,
|
|
927
|
+
subject: (gitLines(projectRoot, ['log', '-1', '--format=%s', sha]) || [''])[0],
|
|
928
|
+
is_quick: quickShaSet.has(sha),
|
|
929
|
+
})),
|
|
930
|
+
...(quickSelection.quicks.length ? { quick_commits: quickSelection.quicks } : {}),
|
|
931
|
+
...(quickSelection.skipped.length ? { skipped_quicks: quickSelection.skipped } : {}),
|
|
932
|
+
...(unpromoDeps.dependencies.length ? { unpromoted_dependencies: unpromoDeps.dependencies, suggested_promote_order: unpromoDeps.suggested_order } : {}),
|
|
933
|
+
...(notCarried.length ? { not_carried_tests: notCarried } : {}),
|
|
934
|
+
...(skippedFixtures.length ? { skipped_fixtures: skippedFixtures } : {}),
|
|
935
|
+
...(dryRiskSuites.length ? { ci_risk_suites: dryRiskSuites } : {}),
|
|
936
|
+
...(dryPreviewCmds.length ? { preview_ci_commands: dryPreviewCmds } : {}),
|
|
937
|
+
frozen_tests: withFixtures,
|
|
938
|
+
conflict: null,
|
|
939
|
+
pr_ready: null,
|
|
940
|
+
body_file: null,
|
|
941
|
+
pr: null,
|
|
942
|
+
commands: [],
|
|
943
|
+
worktree: null,
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
// Never a force-push: a branch already on the remote with commits we do not have is refused before anything changes.
|
|
947
|
+
// OXB-160: a local branch an earlier (failed) promote left behind — created by the promote, never pushed — is
|
|
948
|
+
// reused: dropped and rebuilt. Any other existing branch is refused, as before.
|
|
949
|
+
let replacedBranch = null;
|
|
950
|
+
// OXB-162: the promote's own branch already on the remote with NO PR (a run that died, or pr:ready red) is rebuilt
|
|
951
|
+
// and force-pushed with a lease on the sha it has now. A branch with a PR, or with commits that are not the
|
|
952
|
+
// promote's, is refused as before.
|
|
953
|
+
const remoteHead0 = gitRun(projectRoot, ['ls-remote', '--heads', remote, branch]);
|
|
954
|
+
const remoteSha = remoteHead0.ok ? remoteHead0.stdout.trim().split(/\s+/)[0] : '';
|
|
955
|
+
let forceLease = null;
|
|
956
|
+
if (remoteSha) {
|
|
957
|
+
const own = ownPushedPromoteBranch(projectRoot, activeSession, branch, remote, remoteSha, baseSha, options);
|
|
958
|
+
if (!own.ok) throw new Error(`a branch ${branch} já existe em ${remote} (${remoteSha.slice(0, 8)}) — ${own.why}; o promote não sobrescreve; use --branch <outra>`);
|
|
959
|
+
forceLease = remoteSha;
|
|
960
|
+
}
|
|
961
|
+
// OxeSpace 14/11: the leftover worktree of an earlier failed promote holds the branch ("está em uso numa worktree");
|
|
962
|
+
// sweep the stale promote worktrees (pid gone) BEFORE checking whether the branch is ours to rebuild.
|
|
963
|
+
const sweptEarly = sweepStalePromoteWorkspaces(projectRoot);
|
|
964
|
+
if (gitLines(projectRoot, ['rev-parse', '--verify', '-q', `refs/heads/${branch}`])) {
|
|
965
|
+
const own = ownUnpushedPromoteBranch(projectRoot, branch, remote, baseSha, { allowRemote: Boolean(forceLease) });
|
|
966
|
+
if (!own.ok) throw new Error(`a branch ${branch} já existe${own.why ? ` (${own.why})` : ''} — use --branch <outra> ou apague-a`);
|
|
967
|
+
const del = gitRun(projectRoot, ['branch', '-D', branch]);
|
|
968
|
+
if (!del.ok) throw new Error(`a branch ${branch} (de um promote anterior) não pôde ser recriada: ${del.stderr.trim()}`);
|
|
969
|
+
replacedBranch = own.sha;
|
|
970
|
+
}
|
|
971
|
+
const pushArgs = () => ['push', ...(forceLease ? [`--force-with-lease=${branch}:${forceLease}`] : []), '-u', remote, branch];
|
|
972
|
+
const result = {
|
|
973
|
+
task: taskId,
|
|
974
|
+
...(testsOnly ? { tests_only: true } : {}),
|
|
975
|
+
base,
|
|
976
|
+
base_sha: baseSha,
|
|
977
|
+
...(stack ? { stacked_on: { task: stack.task, branch: stack.branch, pr: stack.pr || null, sha: stack.sha } } : {}),
|
|
978
|
+
base_requested: resolvedBase.requested,
|
|
979
|
+
warnings: resolvedBase.warnings,
|
|
980
|
+
branch,
|
|
981
|
+
commits: ordered,
|
|
982
|
+
...(quickSelection.quicks.length ? { quick_commits: quickSelection.quicks } : {}),
|
|
983
|
+
...(quickSelection.skipped.length ? { skipped_quicks: quickSelection.skipped } : {}),
|
|
984
|
+
...(skippedFixtures.length ? { skipped_fixtures: skippedFixtures } : {}),
|
|
985
|
+
...(unpromoDeps.dependencies.length ? { unpromoted_dependencies: unpromoDeps.dependencies, suggested_promote_order: unpromoDeps.suggested_order } : {}),
|
|
986
|
+
conflict: null,
|
|
987
|
+
pr_ready: null,
|
|
988
|
+
body_file: null,
|
|
989
|
+
pr: null,
|
|
990
|
+
commands: [],
|
|
991
|
+
worktree: null,
|
|
992
|
+
...(replacedBranch ? { replaced_branch: replacedBranch } : {}),
|
|
993
|
+
...(forceLease ? { replaced_remote: forceLease } : {}),
|
|
994
|
+
};
|
|
995
|
+
if (notCarried.length) result.not_carried_tests = notCarried;
|
|
996
|
+
// Where the branch is built: a temporary worktree (default) or, with --in-place, the program checkout.
|
|
997
|
+
let work = projectRoot;
|
|
998
|
+
let wtPidFile = null;
|
|
999
|
+
let cleanup = () => {};
|
|
1000
|
+
if (inPlace) {
|
|
1001
|
+
const back = () => gitRun(projectRoot, ['checkout', '-q', original && original !== 'HEAD' ? original : originalSha]);
|
|
1002
|
+
const co = gitRun(projectRoot, ['checkout', '-q', '-b', branch, buildSha]);
|
|
1003
|
+
if (!co.ok) throw new Error(`não foi possível criar ${branch}: ${co.stderr.trim()}`);
|
|
1004
|
+
gitRun(projectRoot, ['config', `branch.${branch}.oxePromote`, 'true']);
|
|
1005
|
+
cleanup = back;
|
|
1006
|
+
} else {
|
|
1007
|
+
const alloc = allocatePromoteWorktreePath(projectRoot, taskIds, taskId, buildSha);
|
|
1008
|
+
const wt = alloc.wt;
|
|
1009
|
+
wtPidFile = alloc.pidFile;
|
|
1010
|
+
fs.mkdirSync(path.dirname(wt), { recursive: true });
|
|
1011
|
+
fs.mkdirSync(path.dirname(wtPidFile), { recursive: true });
|
|
1012
|
+
// OXB-162: worktrees of killed promotes (their junction unlinked first), and this one's pid for the next sweep.
|
|
1013
|
+
result.swept = [...sweptEarly, ...sweepStalePromoteWorkspaces(projectRoot)];
|
|
1014
|
+
fs.writeFileSync(wtPidFile, JSON.stringify({ pid: process.pid, task: taskId, ...(alloc.external ? { dir: wt } : {}), at: new Date().toISOString() }));
|
|
1015
|
+
const addArgs = process.platform === 'win32'
|
|
1016
|
+
? ['-c', 'core.longpaths=true', 'worktree', 'add', '-q', '-b', branch, wt, buildSha]
|
|
1017
|
+
: ['worktree', 'add', '-q', '-b', branch, wt, buildSha];
|
|
1018
|
+
const add = gitRun(projectRoot, addArgs);
|
|
1019
|
+
if (!add.ok) throw new Error(`não foi possível criar a worktree de ${branch}: ${add.stderr.trim()}`);
|
|
1020
|
+
gitRun(projectRoot, ['config', `branch.${branch}.oxePromote`, 'true']);
|
|
1021
|
+
work = (() => { try { return fs.realpathSync.native ? fs.realpathSync.native(wt) : fs.realpathSync(wt); } catch { return wt; } })();
|
|
1022
|
+
// OXB-163: machine-local files (worktree.copy_local) pr:ready needs (gradle's local.properties, .env.local).
|
|
1023
|
+
try { result.local_copied = require('../oxe-local-config.cjs').copyLocalFiles(projectRoot, work).copied; } catch { /* auxiliar */ }
|
|
1024
|
+
const relWt = path.relative(projectRoot, work).replace(/\\/g, '/');
|
|
1025
|
+
result.worktree = relWt.startsWith('..') ? work.replace(/\\/g, '/') : relWt;
|
|
1026
|
+
// pr:ready needs the dependencies: a junction to the program's node_modules (or deps_link_from), never an install.
|
|
1027
|
+
let linked = false;
|
|
1028
|
+
try {
|
|
1029
|
+
const pc = require('../oxe-parallel.cjs').parallelConfig(projectRoot);
|
|
1030
|
+
const from = pc.deps && pc.deps.from ? pc.deps.from : projectRoot;
|
|
1031
|
+
const src = path.join(from, 'node_modules');
|
|
1032
|
+
if (fs.existsSync(src) && !fs.existsSync(path.join(work, 'node_modules'))) {
|
|
1033
|
+
fs.symlinkSync(fs.realpathSync(src), path.join(work, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
|
|
1034
|
+
linked = true;
|
|
1035
|
+
}
|
|
1036
|
+
} catch { /* pr:ready reports the missing deps */ }
|
|
1037
|
+
cleanup = () => {
|
|
1038
|
+
// Links first (a junction must never be followed by a recursive delete), then the worktree — never --force.
|
|
1039
|
+
try {
|
|
1040
|
+
const rt = loadRuntimeModule();
|
|
1041
|
+
if (rt && typeof rt.unlinkExternalLinks === 'function') rt.unlinkExternalLinks(work);
|
|
1042
|
+
else if (linked) fs.unlinkSync(path.join(work, 'node_modules'));
|
|
1043
|
+
} catch { /* */ }
|
|
1044
|
+
let rm = gitRun(projectRoot, ['worktree', 'remove', work]);
|
|
1045
|
+
// OxeSpace 14/11: a failed step (the frozen-tests commit refused) leaves uncommitted files in this promote's OWN
|
|
1046
|
+
// worktree; plain remove refuses and the worktree keeps holding the branch, so the next promote cannot rebuild
|
|
1047
|
+
// it. It is ours (created above): with no link left inside, a forced removal is safe.
|
|
1048
|
+
if (!rm.ok) {
|
|
1049
|
+
let linkLeft = false;
|
|
1050
|
+
try { linkLeft = fs.lstatSync(path.join(work, 'node_modules')).isSymbolicLink(); } catch { linkLeft = false; }
|
|
1051
|
+
if (!linkLeft) rm = gitRun(projectRoot, ['worktree', 'remove', '--force', work]);
|
|
1052
|
+
}
|
|
1053
|
+
if (rm.ok) {
|
|
1054
|
+
try { fs.rmSync(wtPidFile, { force: true }); } catch { /* */ }
|
|
1055
|
+
if (alloc.external) { try { fs.rmSync(`${work}.pid`, { force: true }); } catch { /* */ } }
|
|
1056
|
+
}
|
|
1057
|
+
if (!rm.ok) result.cleanup_warning = `worktree ${result.worktree} não removida (${rm.stderr.trim().split(/\r?\n/).pop()}) — remova à mão depois de conferir que não há links dentro`;
|
|
1058
|
+
gitRun(projectRoot, ['worktree', 'prune']);
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
// OXB-162: Ctrl+C / SIGTERM while the promote runs still unlinks and removes its worktree (a hard kill is swept by
|
|
1062
|
+
// the next promote).
|
|
1063
|
+
let keepWorktree = false;
|
|
1064
|
+
const onSignal = (sig) => { try { if (!keepWorktree) cleanup(); } catch { /* */ } process.exit(sig === 'SIGINT' ? 130 : 143); };
|
|
1065
|
+
const signals = ['SIGINT', 'SIGTERM'];
|
|
1066
|
+
for (const sig of signals) process.once(sig, onSignal);
|
|
1067
|
+
try {
|
|
1068
|
+
const resolvedCapFiles = new Set();
|
|
1069
|
+
const resolvedConflicts = [];
|
|
1070
|
+
const pcfgPick = readProjectConfig(projectRoot) || {};
|
|
1071
|
+
for (let idx = 0; idx < ordered.length; idx += 1) {
|
|
1072
|
+
const sha = ordered[idx];
|
|
1073
|
+
const pick = gitRun(work, ['cherry-pick', '-x', sha]);
|
|
1074
|
+
if (!pick.ok) {
|
|
1075
|
+
const files = gitLines(work, ['diff', '--name-only', '--diff-filter=U']) || [];
|
|
1076
|
+
const auto = promoteHelpers.tryResolvePromoteCherryPickConflict(projectRoot, work, sha, pcfgPick, files, { resolve: options.resolve });
|
|
1077
|
+
if (auto.resolved) {
|
|
1078
|
+
for (const rf of auto.resolved_cap_files || []) resolvedCapFiles.add(rf);
|
|
1079
|
+
for (const rf of auto.resolved_files || []) {
|
|
1080
|
+
resolvedConflicts.push({ commit: sha, ...rf });
|
|
1081
|
+
result.warnings.push(`conflito auto-resolvido em ${rf.file} (${rf.strategy})`);
|
|
1082
|
+
}
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
if (options.keepOnConflict && !inPlace) {
|
|
1086
|
+
keepWorktree = true;
|
|
1087
|
+
try {
|
|
1088
|
+
const pidTarget = wtPidFile || `${work}.pid`;
|
|
1089
|
+
const pausedMeta = JSON.stringify({ pid: process.pid, task: taskId, paused: true, ...(pidTarget !== `${work}.pid` ? { dir: work } : {}), at: new Date().toISOString() });
|
|
1090
|
+
fs.writeFileSync(pidTarget, pausedMeta);
|
|
1091
|
+
if (pidTarget !== `${work}.pid`) fs.writeFileSync(`${work}.pid`, pausedMeta);
|
|
1092
|
+
} catch { /* */ }
|
|
1093
|
+
const pendingState = {
|
|
1094
|
+
task: taskId,
|
|
1095
|
+
taskIds,
|
|
1096
|
+
branch,
|
|
1097
|
+
base,
|
|
1098
|
+
baseSha,
|
|
1099
|
+
buildSha,
|
|
1100
|
+
original,
|
|
1101
|
+
originalSha,
|
|
1102
|
+
remote,
|
|
1103
|
+
inPlace,
|
|
1104
|
+
forceLease,
|
|
1105
|
+
worktree: work,
|
|
1106
|
+
programTip,
|
|
1107
|
+
ordered,
|
|
1108
|
+
conflict_commit: sha,
|
|
1109
|
+
remaining_commits: ordered.slice(idx + 1),
|
|
1110
|
+
resolved_cap_files: [...resolvedCapFiles],
|
|
1111
|
+
resolved_conflicts: resolvedConflicts,
|
|
1112
|
+
withFixtures,
|
|
1113
|
+
preserveMergedFixtures,
|
|
1114
|
+
verifyTests,
|
|
1115
|
+
sharedSkipped,
|
|
1116
|
+
criteria: [...criteria],
|
|
1117
|
+
phaseCtx,
|
|
1118
|
+
taskMeta: { id: task.id, title: task.title || '', files: task.files || [], acceptance: task.acceptance || [] },
|
|
1119
|
+
quickSelection,
|
|
1120
|
+
stack,
|
|
1121
|
+
resultSnapshot: { ...result },
|
|
1122
|
+
};
|
|
1123
|
+
writeTextAtomic(pendingFile, `${JSON.stringify(pendingState, null, 2)}\n`);
|
|
1124
|
+
result.conflict = { commit: sha, files };
|
|
1125
|
+
result.kept_worktree = result.worktree;
|
|
1126
|
+
result.error = `conflito no cherry-pick de ${sha.slice(0, 8)} (${files.join(', ') || 'sem arquivos'}) — worktree mantida em ${result.worktree} (branch ${branch}); resolva os arquivos, rode \`git -C ${work} add ${files.join(' ') || '.'}\` e finalize com \`oxe-cc runtime promote ${taskId} --continue\`${assumed.length ? ` (ou promova junto: --tasks ${[...new Set([...assumed.map((a) => a.task), ...taskIds])].join(',')})` : ''}`;
|
|
1127
|
+
break;
|
|
1128
|
+
}
|
|
1129
|
+
gitRun(work, ['cherry-pick', '--abort']);
|
|
1130
|
+
result.conflict = { commit: sha, files };
|
|
1131
|
+
result.error = `conflito no cherry-pick de ${sha.slice(0, 8)} (${files.join(', ') || 'sem arquivos'}) — branch ${branch} descartada; ${assumed.length ? `a tarefa depende de commits de ${assumed.map((a) => a.task).join(', ')} feitos antes dela: promova junto (--tasks ${[...new Set([...assumed.map((a) => a.task), ...taskIds])].join(',')}) — ` : ''}use --resolve <arquivo>=ours|theirs|union-json-array ou rode com --keep-on-conflict para resolver na worktree e finalizar com \`oxe-cc runtime promote ${taskId} --continue\``;
|
|
1132
|
+
break;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (resolvedConflicts.length) result.resolved_conflicts = resolvedConflicts;
|
|
1136
|
+
if (!result.conflict && !result.error) {
|
|
1137
|
+
finalizePromotedWorktree({
|
|
1138
|
+
projectRoot,
|
|
1139
|
+
activeSession,
|
|
1140
|
+
work,
|
|
1141
|
+
result,
|
|
1142
|
+
taskId,
|
|
1143
|
+
planTasks,
|
|
1144
|
+
phaseCtx,
|
|
1145
|
+
base,
|
|
1146
|
+
baseSha,
|
|
1147
|
+
buildSha,
|
|
1148
|
+
branch,
|
|
1149
|
+
programTip,
|
|
1150
|
+
withFixtures,
|
|
1151
|
+
preserveMergedFixtures,
|
|
1152
|
+
ordered,
|
|
1153
|
+
verifyTests,
|
|
1154
|
+
resolvedCapFiles,
|
|
1155
|
+
pushArgs,
|
|
1156
|
+
options,
|
|
1157
|
+
});
|
|
1158
|
+
if (fs.existsSync(pendingFile)) { try { fs.rmSync(pendingFile, { force: true }); } catch { /* */ } }
|
|
1159
|
+
}
|
|
1160
|
+
} finally {
|
|
1161
|
+
for (const sig of signals) process.removeListener(sig, onSignal);
|
|
1162
|
+
if (!keepWorktree) cleanup();
|
|
1163
|
+
}
|
|
1164
|
+
if (result.conflict) {
|
|
1165
|
+
if (!keepWorktree) gitRun(projectRoot, ['branch', '-D', branch]);
|
|
1166
|
+
appendEvent(projectRoot, activeSession, { type: 'TaskPromoteFailed', work_item_id: taskId, payload: { base, reason: result.error || 'conflict', commit: result.conflict.commit, files: result.conflict.files, ...(keepWorktree ? { kept_worktree: result.kept_worktree } : {}) } });
|
|
1167
|
+
return result;
|
|
1168
|
+
}
|
|
1169
|
+
return finalizePromotePrBodyAndEvents({ projectRoot, activeSession, result, task, taskId, criteria, ordered, branch, original, base, remote, stack, pushArgs, options: { ...options, taskIds } });
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* OXB-076: what removing criteria from the CURRENT plan means — their acceptance tests go, they leave the tasks'
|
|
1174
|
+
* `acceptance`, and a pending task left with no criterion goes too. Refused when another pending task depends on a
|
|
1175
|
+
* task that would go, or when such a task has a checkpoint (its work exists). Returns the new doc (not written).
|
|
1176
|
+
*/
|
|
1177
|
+
|
|
1178
|
+
return {
|
|
1179
|
+
collectPromoteRiskSuites,
|
|
1180
|
+
finalizePromotedWorktree,
|
|
1181
|
+
finalizePromotePrBodyAndEvents,
|
|
1182
|
+
cleanupPromoteWorktree,
|
|
1183
|
+
runtimePromote,
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
module.exports = { createPromoteRuntime };
|