orca-multiagent-kit 1.6.0 → 1.7.1
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/AI_INSTALL.md +4 -3
- package/CHANGELOG.md +47 -1
- package/GUIA.html +11 -9
- package/README.md +22 -23
- package/VERSION +1 -1
- package/bin/backup.js +44 -0
- package/bin/fetch.js +243 -0
- package/bin/hooks.js +187 -0
- package/bin/omk.js +147 -51
- package/bin/run/cleanup.js +402 -0
- package/bin/run/git.js +641 -0
- package/bin/run/glob.js +193 -0
- package/bin/run/ledger.js +243 -0
- package/bin/run/plan.js +328 -0
- package/bin/run/units.js +101 -0
- package/bin/run/util.js +116 -0
- package/bin/run.js +224 -0
- package/bin/setup.js +81 -8
- package/bin/sync.js +222 -0
- package/bin/ui.js +8 -4
- package/bin/update.js +169 -0
- package/core/AGENTS.md +7 -7
- package/docs/EJECUTABLE.md +5 -4
- package/docs/MANUAL.md +16 -3
- package/docs/ORQUESTADOR.md +59 -1
- package/docs/PLUGIN-ORCA.md +34 -16
- package/hooks/orca-gate.cjs +402 -0
- package/install.sh +26 -13
- package/orca-plugin/README.md +3 -1
- package/orca-plugin/orca-plugin.json +2 -2
- package/orca-plugin/src/kit.test.ts +35 -13
- package/orca-plugin/src/kit.ts +64 -19
- package/orca-plugin/src/panel-state.ts +11 -3
- package/orca-plugin/src/panel.check.ts +71 -0
- package/orca-plugin/src/panel.test.tsx +69 -4
- package/orca-plugin/src/panel.tsx +32 -16
- package/orca-plugin/src/protocol.ts +39 -0
- package/orca-plugin/src/tabs/autonomy.tsx +3 -1
- package/orca-plugin/src/tabs/history.test.tsx +1 -0
- package/orca-plugin/src/tabs/history.tsx +1 -0
- package/orca-plugin/src/tabs/notices.test.tsx +1 -0
- package/orca-plugin/src/tabs/worktrees.test.tsx +1 -0
- package/orca-plugin/src/ui/action-card.tsx +112 -0
- package/orca-plugin/src/worker/actions.test.ts +288 -0
- package/orca-plugin/src/worker/actions.ts +292 -0
- package/orca-plugin/src/worker/context.ts +4 -1
- package/orca-plugin/src/worker/history.ts +3 -3
- package/orca-plugin/src/worker/notices.ts +1 -4
- package/orca-plugin/src/worker.test.ts +24 -6
- package/orca-plugin/src/worker.ts +79 -83
- package/output-styles/csr-minimal.md +1 -0
- package/package.json +3 -3
- package/rules/50-done-gate.md +1 -1
- package/rules/95-multi-agent.md +13 -3
- package/skills/kit-init/SKILL.md +16 -4
- package/skills/orca/SKILL.md +27 -5
- package/skills/orca/references/adapters/artifact.md +2 -0
- package/skills/orca/references/adapters/chat.md +2 -0
- package/skills/orca/references/adapters/native-plan.md +6 -0
- package/skills/orca/references/adapters/plan-file.md +2 -0
- package/skills/orca/references/engine-manual.md +7 -5
- package/skills/orca/references/engine-subagents.md +4 -4
- package/skills/orca/references/integrate.md +14 -2
- package/skills/orca/references/ledger.md +1 -1
- package/skills/orca/references/olimpo.md +1 -1
- package/skills/orca/references/plan.md +2 -1
- package/skills/orca/references/units.md +1 -1
- package/skills/orca/references/worker-contract.md +2 -2
- package/templates/AGENTS.md +2 -2
- package/templates/CLAUDE.md +1 -1
- package/templates/claude-settings.json +25 -0
package/bin/run/git.js
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
// omk run start | worktree | check | merge: lo que toca git en un run. Base fresca y rama de
|
|
2
|
+
// integración, un worktree por unidad, alcance contra write y merge --no-ff con ensayo previo.
|
|
3
|
+
// Nunca hace push, reset, --force ni borra nada: ante la duda se niega y explica qué falta.
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { RunError, UNIT_ID, checkUnitId, checkBranch, git, parseArgs, runDir } = require('./util');
|
|
9
|
+
const { parseUnits } = require('./units');
|
|
10
|
+
const ledger = require('./ledger');
|
|
11
|
+
const glob = require('./glob');
|
|
12
|
+
|
|
13
|
+
const { EMPTY } = ledger;
|
|
14
|
+
const REMOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
15
|
+
const SHA = /^[0-9a-f]{7,64}$/;
|
|
16
|
+
const MERGE_TREE_MIN = [2, 38];
|
|
17
|
+
const LOCKFILES = [
|
|
18
|
+
'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock',
|
|
19
|
+
'poetry.lock', 'uv.lock', 'Pipfile.lock', 'go.sum', 'composer.lock', 'Gemfile.lock',
|
|
20
|
+
];
|
|
21
|
+
/**
|
|
22
|
+
* Prohibidos a un worker, sin distinguir mayúsculas: por nombre en cualquier carpeta y por glob
|
|
23
|
+
* (planes y .plans desde la raíz, .work en cualquier nivel). Se comparan en minúsculas.
|
|
24
|
+
*/
|
|
25
|
+
const FORBIDDEN_NAMES = new Set(['tasks.md', 'ORCHESTRATION.md', 'STACK.md', ...LOCKFILES].map((n) => n.toLowerCase()));
|
|
26
|
+
const FORBIDDEN_GLOBS = ['planes/**/*.md', '.plans/**/*.md', '.work/**', '**/.work/**'];
|
|
27
|
+
/** Un segmento de ruta que parece de producción: contiene «prod» o la palabra prd o live. */
|
|
28
|
+
const PRODUCTION = [/prod/i, /(^|[._-])(prd|live)([._-]|$)/i];
|
|
29
|
+
/** Operaciones a medias que dejan el árbol en un estado que start y merge no deben tocar. */
|
|
30
|
+
const IN_PROGRESS = [
|
|
31
|
+
['MERGE_HEAD', 'un merge'], ['CHERRY_PICK_HEAD', 'un cherry-pick'], ['REVERT_HEAD', 'un revert'],
|
|
32
|
+
['rebase-merge', 'un rebase'], ['rebase-apply', 'un rebase o un am'],
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------- git y run.md
|
|
36
|
+
|
|
37
|
+
/** Sha abreviado solo para mensajes; lo que se anota en run.md sale de abbrev() (sin ambigüedad). */
|
|
38
|
+
const short = (sha) => sha.slice(0, 7);
|
|
39
|
+
|
|
40
|
+
function abbrev(cwd, sha) {
|
|
41
|
+
return git(['rev-parse', '--short', sha], { cwd }).stdout.trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function refSha(cwd, ref) {
|
|
45
|
+
const res = git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { cwd, check: false });
|
|
46
|
+
return res.status === 0 ? res.stdout.trim() : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Ruta (absoluta) de un fichero del directorio git de `cwd`; vale también dentro de un worktree. */
|
|
50
|
+
function gitPath(cwd, name) {
|
|
51
|
+
return path.resolve(cwd, git(['rev-parse', '--git-path', name], { cwd }).stdout.trim());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const mergeInProgress = (cwd) => fs.existsSync(gitPath(cwd, 'MERGE_HEAD'));
|
|
55
|
+
|
|
56
|
+
/** Se niega si hay un merge, cherry-pick, revert o rebase a medias en `cwd`. */
|
|
57
|
+
function requireNoOperation(cwd) {
|
|
58
|
+
for (const [name, what] of IN_PROGRESS) {
|
|
59
|
+
if (fs.existsSync(gitPath(cwd, name))) {
|
|
60
|
+
throw new RunError(`hay ${what} a medias en ${cwd} (${name}): termínalo o abórtalo tú antes de seguir`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function currentBranch(cwd) {
|
|
66
|
+
const res = git(['symbolic-ref', '--quiet', '--short', 'HEAD'], { cwd, check: false });
|
|
67
|
+
return res.status === 0 ? res.stdout.trim() : null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Cambios en ficheros versionados (los sin versionar no impiden cambiar de rama ni mergear). */
|
|
71
|
+
function requireCleanTree(cwd, why) {
|
|
72
|
+
const dirty = git(['status', '--porcelain', '--untracked-files=no'], { cwd }).stdout.trim();
|
|
73
|
+
if (dirty) {
|
|
74
|
+
throw new RunError(`hay cambios sin commitear en ficheros versionados de ${cwd} y ${why}:\n${dirty}\ncommitéalos o apártalos tú antes de seguir`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** La rama por defecto según `<remote>/HEAD`; si no se sabe, main y master cuentan como tales. */
|
|
79
|
+
function defaultBranches(cwd, remote = 'origin') {
|
|
80
|
+
const res = git(['symbolic-ref', '--quiet', `refs/remotes/${remote}/HEAD`], { cwd, check: false });
|
|
81
|
+
const prefix = `refs/remotes/${remote}/`;
|
|
82
|
+
const ref = res.stdout.trim();
|
|
83
|
+
if (res.status === 0 && ref.startsWith(prefix)) return [ref.slice(prefix.length)];
|
|
84
|
+
return ['main', 'master'];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function gitVersion(cwd) {
|
|
88
|
+
const match = /(\d+)\.(\d+)/.exec(git(['--version'], { cwd }).stdout);
|
|
89
|
+
return match ? [Number(match[1]), Number(match[2])] : [0, 0];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Ruta canónica (en Windows deshace nombres 8.3 y mayúsculas). Si no existe, la de su antecesor
|
|
94
|
+
* más cercano que exista más el resto; si no se puede leer, solo resuelta.
|
|
95
|
+
*/
|
|
96
|
+
function canonical(p) {
|
|
97
|
+
let current = path.resolve(p);
|
|
98
|
+
const rest = [];
|
|
99
|
+
for (;;) {
|
|
100
|
+
try {
|
|
101
|
+
return path.join(fs.realpathSync.native(current), ...rest);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (!['ENOENT', 'ENOTDIR', 'EPERM', 'EACCES'].includes(error.code)) throw error;
|
|
104
|
+
const parent = path.dirname(current);
|
|
105
|
+
if (parent === current) return path.resolve(p);
|
|
106
|
+
rest.unshift(path.basename(current));
|
|
107
|
+
current = parent;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function samePath(a, b) {
|
|
113
|
+
const x = canonical(a);
|
|
114
|
+
const y = canonical(b);
|
|
115
|
+
return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Si `child` está dentro de `parent` (o es él). */
|
|
119
|
+
function isInside(parent, child) {
|
|
120
|
+
const rel = path.relative(parent, child);
|
|
121
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function loadRun(root, id) {
|
|
125
|
+
const run = ledger.readRun(root, id);
|
|
126
|
+
if (run.problems.length) {
|
|
127
|
+
const lines = run.problems.map((p) => ` ${ledger.runFile(root, id)}:${p.line}: ${p.message}`).join('\n');
|
|
128
|
+
throw new RunError(`run.md tiene problemas de formato: arréglalo antes de seguir\n${lines}`);
|
|
129
|
+
}
|
|
130
|
+
return run;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function loadUnit(root, id, unitId) {
|
|
134
|
+
const file = path.join(runDir(root, id), 'units.md');
|
|
135
|
+
let text;
|
|
136
|
+
try {
|
|
137
|
+
text = fs.readFileSync(file, 'utf8');
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code === 'ENOENT') throw new RunError(`el run ${id} no tiene units.md (${file})`);
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
const parsed = parseUnits(text);
|
|
143
|
+
if (parsed.problems.length) {
|
|
144
|
+
const lines = parsed.problems.map((p) => ` ${file}:${p.line}: ${p.message}`).join('\n');
|
|
145
|
+
throw new RunError(`units.md tiene problemas de formato:\n${lines}`);
|
|
146
|
+
}
|
|
147
|
+
const unit = parsed.units.find((u) => u.id === unitId);
|
|
148
|
+
if (!unit) throw new RunError(`units.md del run ${id} no tiene la unidad ${unitId}`);
|
|
149
|
+
return unit;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function rowOf(run, unitId) {
|
|
153
|
+
const row = run.units.find((u) => u.unit === unitId);
|
|
154
|
+
if (!row) throw new RunError(`run.md del run ${run.id} no tiene la unidad ${unitId}`);
|
|
155
|
+
return row;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const present = (value) => value !== undefined && value !== null && value !== '' && value !== EMPTY;
|
|
159
|
+
|
|
160
|
+
function integrationOf(run, cwd) {
|
|
161
|
+
if (!present(run.meta.integration)) {
|
|
162
|
+
throw new RunError(`el run ${run.id} no tiene rama de integración: ejecuta antes omk run start ${run.id} --parent <rama>`);
|
|
163
|
+
}
|
|
164
|
+
return checkBranch(run.meta.integration, cwd);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** `<run> <unidad>` o, si solo llega la unidad, el único run activo. */
|
|
168
|
+
function runAndUnit(positional, ctx, usage) {
|
|
169
|
+
if (positional.length === 2) return [ctx.resolveRun(ctx.root, positional[0]), checkUnitId(positional[1])];
|
|
170
|
+
if (positional.length === 1 && UNIT_ID.test(positional[0])) return [ctx.resolveRun(ctx.root), positional[0]];
|
|
171
|
+
throw new RunError(`uso: ${usage}`, 2);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const unitBranch = (id, unitId) => `wt/${id}/${unitId.toLowerCase()}`;
|
|
175
|
+
const defaultWorktree = (root, id, unitId) => path.join(path.dirname(root), `${path.basename(root)}.wt`, id, unitId.toLowerCase());
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------- start
|
|
178
|
+
|
|
179
|
+
/** Commits de `right` que no están en `left` y al revés: [detrás, delante] de `right` respecto a `left`. */
|
|
180
|
+
function aheadBehind(cwd, left, right) {
|
|
181
|
+
const counts = git(['rev-list', '--left-right', '--count', `${left}...${right}`], { cwd }).stdout.trim().split(/\s+/).map(Number);
|
|
182
|
+
if (counts.length !== 2 || !counts.every(Number.isInteger)) throw new RunError(`no entiendo la salida de git rev-list: «${counts.join(' ')}»`);
|
|
183
|
+
return counts;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Base de la rama de integración según la tabla de SKILL.md §4: {ref, sha, note}. Con `noFetch`
|
|
188
|
+
* compara con las refs remotas que ya hay (el usuario decidió seguir sin actualizar).
|
|
189
|
+
*/
|
|
190
|
+
function freshBase(root, parent, remote, from, noFetch) {
|
|
191
|
+
const remotes = git(['remote'], { cwd: root }).stdout.split(/\r?\n/).map((r) => r.trim()).filter(Boolean);
|
|
192
|
+
const localSha = refSha(root, `refs/heads/${parent}`);
|
|
193
|
+
if (!remotes.includes(remote)) {
|
|
194
|
+
if (!localSha) throw new RunError(`no existe la rama ${parent} y no hay remoto ${remote}`);
|
|
195
|
+
return { ref: parent, sha: localSha, note: `sin remoto ${remote}: parto de la rama local ${parent}` };
|
|
196
|
+
}
|
|
197
|
+
let fetchNote = '';
|
|
198
|
+
if (noFetch) {
|
|
199
|
+
fetchNote = ` (--no-fetch: refs de ${remote} sin actualizar)`;
|
|
200
|
+
} else {
|
|
201
|
+
// Sin terminal: que un remoto con credenciales falle en vez de quedarse esperando una contraseña.
|
|
202
|
+
if (process.env.GIT_TERMINAL_PROMPT === undefined) process.env.GIT_TERMINAL_PROMPT = '0';
|
|
203
|
+
const fetched = git(['fetch', '--prune', remote], { cwd: root, check: false });
|
|
204
|
+
if (fetched.status !== 0) {
|
|
205
|
+
const reason = (fetched.stderr.trim() || fetched.stdout.trim()).split(/\r?\n/).pop();
|
|
206
|
+
throw new RunError(`RISK: no pude actualizar ${remote} (${reason}). Pregunta al usuario; para seguir con lo que hay: --no-fetch`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const pick = (ref, sha, note) => ({ ref, sha, note: `${note}${fetchNote}` });
|
|
210
|
+
const remoteRef = `${remote}/${parent}`;
|
|
211
|
+
const remoteSha = refSha(root, `refs/remotes/${remoteRef}`);
|
|
212
|
+
if (!remoteSha) {
|
|
213
|
+
if (!localSha) throw new RunError(`no existe ${parent} ni ${remoteRef}`);
|
|
214
|
+
return pick(parent, localSha, `${remoteRef} no existe: parto de la rama local ${parent}`);
|
|
215
|
+
}
|
|
216
|
+
if (!localSha) return pick(remoteRef, remoteSha, `${parent} no existe en local: parto de ${remoteRef}`);
|
|
217
|
+
const [behind, ahead] = aheadBehind(root, `refs/remotes/${remoteRef}`, `refs/heads/${parent}`);
|
|
218
|
+
if (ahead === 0 && behind === 0) return pick(parent, localSha, `${parent} y ${remoteRef} coinciden`);
|
|
219
|
+
// La decisión explícita del usuario manda sobre la tabla.
|
|
220
|
+
if (from === 'local') return pick(parent, localSha, `--from local: parto de ${parent} (${ahead} commit(s) sin subir, ${behind} por detrás de ${remoteRef})`);
|
|
221
|
+
if (from === 'remote') return pick(remoteRef, remoteSha, `--from remote: parto de ${remoteRef}${ahead ? ` sin los ${ahead} commit(s) de la local` : ''}`);
|
|
222
|
+
if (ahead === 0) return pick(remoteRef, remoteSha, `${parent} va ${behind} commit(s) por detrás de ${remoteRef}: parto de ${remoteRef} (la local no se toca)`);
|
|
223
|
+
throw new RunError([
|
|
224
|
+
`la rama local ${parent} tiene ${ahead} commit(s) que no están en ${remoteRef}${behind ? ` y le faltan ${behind}` : ''}. Decide la base:`,
|
|
225
|
+
` --from remote parte de ${remoteRef} (sin esos commits locales)`,
|
|
226
|
+
` --from local parte de ${parent} con sus commits sin subir`,
|
|
227
|
+
].join('\n'), 3);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function cmdStart(args, ctx) {
|
|
231
|
+
const { root } = ctx;
|
|
232
|
+
const { positional, options } = parseArgs(args, { values: ['parent', 'remote', 'from', 'integration'], flags: ['no-fetch'] });
|
|
233
|
+
if (positional.length > 1) throw new RunError(`sobra: ${positional.slice(1).join(' ')}`, 2);
|
|
234
|
+
const id = ctx.resolveRun(root, positional[0]);
|
|
235
|
+
if (options.parent === undefined) throw new RunError('falta --parent <rama> (la rama destino del merge final)', 2);
|
|
236
|
+
const parent = checkBranch(options.parent, root);
|
|
237
|
+
const remote = options.remote === undefined ? 'origin' : options.remote;
|
|
238
|
+
if (!REMOTE_NAME.test(remote)) throw new RunError(`nombre de remoto no válido: «${remote}»`, 2);
|
|
239
|
+
if (options.from !== undefined && !['local', 'remote'].includes(options.from)) throw new RunError('--from admite local o remote', 2);
|
|
240
|
+
|
|
241
|
+
const run = loadRun(root, id);
|
|
242
|
+
const saved = present(run.meta.integration) ? run.meta.integration : null;
|
|
243
|
+
if (saved && options.integration !== undefined && options.integration !== saved) {
|
|
244
|
+
throw new RunError(`run.md ya dice integration: ${saved}; si de verdad cambia, hazlo antes con omk run meta ${id} integration=…`);
|
|
245
|
+
}
|
|
246
|
+
const wanted = options.integration !== undefined ? options.integration : saved;
|
|
247
|
+
if (!wanted) throw new RunError('falta la rama de integración: --integration <rama> (o integration en run.md)', 2);
|
|
248
|
+
const integration = checkBranch(wanted, root);
|
|
249
|
+
if (integration === parent) throw new RunError(`la rama de integración no puede ser la padre (${parent})`);
|
|
250
|
+
if (defaultBranches(root, remote).includes(integration)) throw new RunError(`la rama de integración no puede ser la rama por defecto (${integration})`);
|
|
251
|
+
requireNoOperation(root);
|
|
252
|
+
requireCleanTree(root, 'start va a cambiar de rama');
|
|
253
|
+
|
|
254
|
+
const base = freshBase(root, parent, remote, options.from, Boolean(options['no-fetch']));
|
|
255
|
+
const baseShort = abbrev(root, base.sha);
|
|
256
|
+
console.log(`base: ${base.ref} @ ${baseShort} — ${base.note}`);
|
|
257
|
+
|
|
258
|
+
const existing = refSha(root, `refs/heads/${integration}`);
|
|
259
|
+
const remoteIntegration = refSha(root, `refs/remotes/${remote}/${integration}`);
|
|
260
|
+
let baseRef = run.meta.base_ref;
|
|
261
|
+
if (existing) {
|
|
262
|
+
// --no-overwrite-ignore: un fichero ignorado del checkout (un .env) no se pisa al cambiar de rama.
|
|
263
|
+
if (currentBranch(root) !== integration) git(['switch', '--quiet', '--no-overwrite-ignore', integration], { cwd: root });
|
|
264
|
+
console.log(`la rama de integración ${integration} ya existe (${short(existing)}): no la recreo; estás en ella`);
|
|
265
|
+
if (git(['merge-base', '--is-ancestor', base.sha, existing], { cwd: root, check: false }).status !== 0) {
|
|
266
|
+
console.log(`aviso: la rama padre ha avanzado: ${base.ref} @ ${baseShort} no está en ${integration}; dilo en el plan`);
|
|
267
|
+
}
|
|
268
|
+
if (remoteIntegration) {
|
|
269
|
+
const [behind, ahead] = aheadBehind(root, `refs/remotes/${remote}/${integration}`, `refs/heads/${integration}`);
|
|
270
|
+
if (behind || ahead) console.log(`aviso: ${integration} va ${behind} commit(s) por detrás y ${ahead} por delante de ${remote}/${integration}; no lo toco`);
|
|
271
|
+
}
|
|
272
|
+
if (!present(baseRef)) baseRef = `${base.ref} @ ${baseShort}`;
|
|
273
|
+
} else {
|
|
274
|
+
if (remoteIntegration) {
|
|
275
|
+
throw new RunError(`existe ${remote}/${integration} pero no la rama local: decide si seguir la remota (git switch ${integration}) o usar otro nombre`, 3);
|
|
276
|
+
}
|
|
277
|
+
git(['switch', '--quiet', '--no-overwrite-ignore', '--no-track', '-c', integration, base.sha], { cwd: root });
|
|
278
|
+
console.log(`rama de integración ${integration} creada desde ${base.ref} @ ${baseShort} (sin upstream)`);
|
|
279
|
+
baseRef = `${base.ref} @ ${baseShort}`;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (!saved) ledger.setMeta(run, 'integration', integration);
|
|
283
|
+
ledger.setMeta(run, 'base_ref', baseRef);
|
|
284
|
+
if (run.meta.status === 'planned') ledger.setMeta(run, 'status', 'active');
|
|
285
|
+
ledger.addLog(run, `start: ${existing ? 'reanuda' : 'crea'} ${integration} · base ${base.ref} @ ${baseShort} · ${base.note}`);
|
|
286
|
+
ledger.writeRun(root, run);
|
|
287
|
+
return 0;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ---------------------------------------------------------------- worktree
|
|
291
|
+
|
|
292
|
+
/** Lee .worktreeinclude: rutas literales, una por línea, `#` comentario. */
|
|
293
|
+
function readIncludes(root) {
|
|
294
|
+
const file = path.join(root, '.worktreeinclude');
|
|
295
|
+
let stat;
|
|
296
|
+
try {
|
|
297
|
+
stat = fs.lstatSync(file);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (error.code === 'ENOENT') return [];
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
if (!stat.isFile()) throw new RunError('.worktreeinclude no es un fichero regular: no lo sigo');
|
|
303
|
+
return fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '').split(/\r?\n/)
|
|
304
|
+
.map((line) => line.trim())
|
|
305
|
+
.filter((line) => line && !line.startsWith('#'));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Motivo por el que una línea de .worktreeinclude no se copia, o null si es válida. */
|
|
309
|
+
function includeProblem(root, entry) {
|
|
310
|
+
if (path.isAbsolute(entry) || path.win32.isAbsolute(entry) || /^[A-Za-z]:/.test(entry) || entry.startsWith('\\')) return 'ruta absoluta';
|
|
311
|
+
const segments = entry.replace(/\\/g, '/').split('/').filter((s) => s && s !== '.');
|
|
312
|
+
if (!segments.length) return 'ruta vacía';
|
|
313
|
+
if (segments.includes('..')) return 'sale de la raíz con «..»';
|
|
314
|
+
if (glob.isGlob(entry.replace(/\\/g, '/'))) return 'parece un glob (solo rutas literales)';
|
|
315
|
+
let current = root;
|
|
316
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
317
|
+
current = path.join(current, segments[i]);
|
|
318
|
+
let stat;
|
|
319
|
+
try {
|
|
320
|
+
stat = fs.lstatSync(current);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return 'no existe';
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
if (stat.isSymbolicLink()) return 'es o cruza un enlace simbólico';
|
|
326
|
+
if (i === segments.length - 1 && !stat.isFile()) return 'no es un fichero regular';
|
|
327
|
+
}
|
|
328
|
+
if (!isInside(root, current)) return 'sale de la raíz';
|
|
329
|
+
const rel = segments.join('/');
|
|
330
|
+
if (git(['check-ignore', '-q', '--', rel], { cwd: root, check: false }).status !== 0) return 'no está ignorado por git (lo versionado ya viene en el worktree)';
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** lstat sin seguir enlaces (uno roto también existe), o null si no hay nada en esa ruta. */
|
|
335
|
+
function lstatOrNull(p) {
|
|
336
|
+
try {
|
|
337
|
+
return fs.lstatSync(p);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null;
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Copia los ficheros permitidos de .worktreeinclude. Nunca lee ni enseña su contenido. */
|
|
345
|
+
function copyIncludes(root, worktree) {
|
|
346
|
+
const report = [];
|
|
347
|
+
for (const entry of readIncludes(root)) {
|
|
348
|
+
const segments = entry.replace(/\\/g, '/').split('/').filter((s) => s && s !== '.');
|
|
349
|
+
if (segments.some((segment) => PRODUCTION.some((re) => re.test(segment)))) {
|
|
350
|
+
report.push({ entry, copied: false, reason: 'parece de producción', risk: true });
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const problem = includeProblem(root, entry);
|
|
354
|
+
if (problem) {
|
|
355
|
+
report.push({ entry, copied: false, reason: problem });
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const dest = path.join(worktree, ...segments);
|
|
359
|
+
let parent = worktree;
|
|
360
|
+
let blocked = null;
|
|
361
|
+
for (const segment of segments.slice(0, -1)) {
|
|
362
|
+
parent = path.join(parent, segment);
|
|
363
|
+
try {
|
|
364
|
+
if (fs.lstatSync(parent).isSymbolicLink()) { blocked = 'en el worktree cruza un enlace simbólico'; break; }
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (error.code !== 'ENOENT') throw error;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (!blocked && lstatOrNull(dest)) blocked = 'ya existe en el worktree (no lo piso)';
|
|
370
|
+
if (blocked) {
|
|
371
|
+
report.push({ entry, copied: false, reason: blocked });
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
375
|
+
fs.copyFileSync(path.join(root, ...segments), dest, fs.constants.COPYFILE_EXCL);
|
|
376
|
+
report.push({ entry, copied: true });
|
|
377
|
+
}
|
|
378
|
+
return report;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Entrada de `git worktree list --porcelain` cuya rama es `branch`, o null. */
|
|
382
|
+
function worktreeOfBranch(root, branch) {
|
|
383
|
+
const text = git(['worktree', 'list', '--porcelain'], { cwd: root }).stdout;
|
|
384
|
+
for (const block of text.split(/\r?\n\r?\n/)) {
|
|
385
|
+
const lines = block.split(/\r?\n/);
|
|
386
|
+
const wt = lines.find((l) => l.startsWith('worktree '));
|
|
387
|
+
if (wt && lines.includes(`branch refs/heads/${branch}`)) return wt.slice('worktree '.length);
|
|
388
|
+
}
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function cmdWorktree(args, ctx) {
|
|
393
|
+
const { root, cwd } = ctx;
|
|
394
|
+
const { positional, options } = parseArgs(args, { values: ['path'], flags: ['no-copy'] });
|
|
395
|
+
const [id, unitId] = runAndUnit(positional, ctx, 'omk run worktree <run> <unidad> [--path <ruta>] [--no-copy]');
|
|
396
|
+
const run = loadRun(root, id);
|
|
397
|
+
const row = rowOf(run, unitId);
|
|
398
|
+
loadUnit(root, id, unitId);
|
|
399
|
+
const integration = integrationOf(run, root);
|
|
400
|
+
const baseSha = refSha(root, `refs/heads/${integration}`);
|
|
401
|
+
if (!baseSha) throw new RunError(`no existe la rama de integración ${integration}: ejecuta antes omk run start ${id}`);
|
|
402
|
+
const branch = checkBranch(unitBranch(id, unitId), root);
|
|
403
|
+
const target = options.path !== undefined ? path.resolve(cwd, options.path) : defaultWorktree(root, id, unitId);
|
|
404
|
+
if (/[|\r\n]/.test(target)) throw new RunError('la ruta del worktree no puede llevar «|» ni saltos de línea (rompería run.md)', 2);
|
|
405
|
+
const [realTarget, realRoot] = [canonical(target), canonical(root)];
|
|
406
|
+
if (isInside(realTarget, realRoot)) throw new RunError(`la ruta ${target} contiene el checkout del coordinador`, 2);
|
|
407
|
+
if (isInside(realRoot, realTarget)) throw new RunError(`la ruta ${target} queda dentro del checkout del coordinador: elige una fuera`, 2);
|
|
408
|
+
const otherBranch = present(row.branch) && row.branch !== branch;
|
|
409
|
+
const otherWorktree = present(row.worktree) && !samePath(path.resolve(root, row.worktree), target);
|
|
410
|
+
if (otherBranch || otherWorktree) {
|
|
411
|
+
throw new RunError(`la fila de ${unitId} en run.md ya tiene branch ${row.branch} y worktree ${row.worktree}, distintos de ${branch} y ${target}: no la piso`);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (refSha(root, `refs/heads/${branch}`)) {
|
|
415
|
+
const where = worktreeOfBranch(root, branch);
|
|
416
|
+
if (where && samePath(where, target)) {
|
|
417
|
+
console.log(`${unitId}: el worktree ya existe (${target}, rama ${branch}): no toco nada`);
|
|
418
|
+
return 0;
|
|
419
|
+
}
|
|
420
|
+
throw new RunError(`la rama ${branch} ya existe ${where ? `con worktree en ${where}` : 'sin worktree'}: no la piso`);
|
|
421
|
+
}
|
|
422
|
+
let stat = null;
|
|
423
|
+
try {
|
|
424
|
+
stat = fs.lstatSync(target);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
if (error.code !== 'ENOENT') throw error;
|
|
427
|
+
}
|
|
428
|
+
if (stat && (!stat.isDirectory() || fs.readdirSync(target).length)) {
|
|
429
|
+
throw new RunError(`${target} ya existe y no es una carpeta vacía: elige otra con --path`);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
git(['worktree', 'add', '--quiet', '-b', branch, target, `refs/heads/${integration}`], { cwd: root });
|
|
433
|
+
const base = abbrev(root, baseSha);
|
|
434
|
+
console.log(`${unitId}: worktree ${target} · rama ${branch} desde ${integration} @ ${base}`);
|
|
435
|
+
// Se anota ya: si la copia falla después, el worktree creado consta en run.md (cleanup lo encuentra).
|
|
436
|
+
ledger.setUnit(run, unitId, { branch, worktree: target, base });
|
|
437
|
+
ledger.addLog(run, `${unitId} worktree ${target} · rama ${branch} · base ${base}`);
|
|
438
|
+
ledger.writeRun(root, run);
|
|
439
|
+
if (options['no-copy']) return 0;
|
|
440
|
+
|
|
441
|
+
const report = copyIncludes(root, target);
|
|
442
|
+
for (const r of report) {
|
|
443
|
+
if (r.copied) console.log(` copiado: ${r.entry}`);
|
|
444
|
+
else if (r.risk) console.log(`RISK: omitido ${r.entry}: ${r.reason}; no se copia a ningún worktree`);
|
|
445
|
+
else console.log(` omitido: ${r.entry} — ${r.reason}`);
|
|
446
|
+
}
|
|
447
|
+
const copied = report.filter((r) => r.copied).length;
|
|
448
|
+
const risky = report.filter((r) => r.risk).length;
|
|
449
|
+
if (copied || risky) {
|
|
450
|
+
ledger.addLog(run, `${unitId} .worktreeinclude: ${copied} copiado(s)${risky ? `, ${risky} omitido(s) por parecer de producción` : ''}`);
|
|
451
|
+
ledger.writeRun(root, run);
|
|
452
|
+
}
|
|
453
|
+
return 0;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// ---------------------------------------------------------------- check
|
|
457
|
+
|
|
458
|
+
/** Si un worker no puede tocar este fichero aunque lo cubra un glob de write o shared. */
|
|
459
|
+
function isForbidden(file) {
|
|
460
|
+
const lower = glob.normalizePath(file).toLowerCase();
|
|
461
|
+
const name = lower.split('/').pop();
|
|
462
|
+
return FORBIDDEN_NAMES.has(name) || FORBIDDEN_GLOBS.some((pattern) => glob.matches(lower, pattern));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* El worktree de la unidad: la celda de run.md (relativa a root) o, si está vacía o entre
|
|
467
|
+
* paréntesis («(Orca)»), el que git tenga registrado para su rama. {path, problem}.
|
|
468
|
+
*/
|
|
469
|
+
function unitWorktree(root, row, branch) {
|
|
470
|
+
const cell = present(row.worktree) ? row.worktree.trim() : '';
|
|
471
|
+
if (!cell || /^\(.*\)$/.test(cell)) return { path: worktreeOfBranch(root, branch), problem: null };
|
|
472
|
+
const resolved = path.resolve(root, cell);
|
|
473
|
+
if (!lstatOrNull(resolved)) return { path: null, problem: `el worktree ${cell} de run.md no existe` };
|
|
474
|
+
return { path: resolved, problem: null };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const splitZ = (text) => text.split('\0').filter(Boolean);
|
|
478
|
+
|
|
479
|
+
function gitDir(cwd) {
|
|
480
|
+
const res = git(['rev-parse', '--git-common-dir'], { cwd, check: false });
|
|
481
|
+
return res.status === 0 ? path.resolve(cwd, res.stdout.trim()) : null;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Alcance de una unidad: lo que su rama cambia respecto a la rama de integración (desde su
|
|
486
|
+
* merge-base: si el worker trajo la integración, lo ajeno no cuenta; si revirtió algo integrado, sí)
|
|
487
|
+
* y lo que quede sin commitear en su worktree, contra write ∪ shared. `ok` es false si algo impide integrar.
|
|
488
|
+
*/
|
|
489
|
+
function checkScope(root, run, unitId) {
|
|
490
|
+
const row = rowOf(run, unitId);
|
|
491
|
+
const unit = loadUnit(root, run.id, unitId);
|
|
492
|
+
if (!present(row.base)) throw new RunError(`${unitId} no tiene base en run.md (la anota omk run worktree)`);
|
|
493
|
+
if (!SHA.test(row.base)) throw new RunError(`${unitId}: base no es un sha: «${row.base}»`);
|
|
494
|
+
if (!present(row.branch)) throw new RunError(`${unitId} no tiene rama en run.md (la anota omk run worktree)`);
|
|
495
|
+
const branch = checkBranch(row.branch, root);
|
|
496
|
+
const integration = integrationOf(run, root);
|
|
497
|
+
const base = refSha(root, row.base);
|
|
498
|
+
if (!base) throw new RunError(`${unitId}: la base ${row.base} no es un commit de este repositorio`);
|
|
499
|
+
if (!refSha(root, `refs/heads/${branch}`)) throw new RunError(`${unitId}: no existe la rama ${branch}`);
|
|
500
|
+
if (!refSha(root, `refs/heads/${integration}`)) throw new RunError(`no existe la rama de integración ${integration}`);
|
|
501
|
+
|
|
502
|
+
const problems = [];
|
|
503
|
+
if (git(['merge-base', '--is-ancestor', base, `refs/heads/${branch}`], { cwd: root, check: false }).status !== 0) {
|
|
504
|
+
problems.push(`la base ${row.base} de run.md no es antecesora de ${branch}`);
|
|
505
|
+
}
|
|
506
|
+
const committed = splitZ(git(['diff', '--name-only', '--no-renames', '-z', `refs/heads/${integration}...refs/heads/${branch}`], { cwd: root }).stdout);
|
|
507
|
+
const uncommitted = [];
|
|
508
|
+
const located = unitWorktree(root, row, branch);
|
|
509
|
+
if (located.problem) problems.push(located.problem);
|
|
510
|
+
const worktree = located.path;
|
|
511
|
+
if (worktree) {
|
|
512
|
+
if (gitDir(worktree) === null || !samePath(gitDir(worktree), gitDir(root))) {
|
|
513
|
+
problems.push(`el worktree ${worktree} no es de este repositorio`);
|
|
514
|
+
} else {
|
|
515
|
+
const head = currentBranch(worktree);
|
|
516
|
+
if (head !== branch) problems.push(`el worktree ${worktree} está en ${head || 'HEAD suelto'}, no en ${branch}`);
|
|
517
|
+
const status = git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames'], { cwd: worktree }).stdout;
|
|
518
|
+
for (const entry of splitZ(status)) uncommitted.push(entry.slice(3));
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const write = unit.fields.write || [];
|
|
523
|
+
const allowed = [...write, ...(unit.fields.shared || [])];
|
|
524
|
+
const literal = new Set(write.map((w) => glob.normalizePath(w)));
|
|
525
|
+
const changed = [...new Set([...committed, ...uncommitted])].sort();
|
|
526
|
+
const forbidden = [];
|
|
527
|
+
const outOfScope = [];
|
|
528
|
+
for (const file of changed) {
|
|
529
|
+
if (literal.has(file)) continue;
|
|
530
|
+
if (isForbidden(file)) forbidden.push(file);
|
|
531
|
+
else if (!allowed.some((pattern) => glob.matches(file, pattern))) outOfScope.push(file);
|
|
532
|
+
}
|
|
533
|
+
const ok = !problems.length && !forbidden.length && !outOfScope.length && !uncommitted.length;
|
|
534
|
+
return {
|
|
535
|
+
run: run.id, unit: unitId, base: row.base, branch, worktree, ok,
|
|
536
|
+
changed, committed, uncommitted: [...new Set(uncommitted)].sort(), out_of_scope: outOfScope, forbidden, problems,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function printScope(report, stream = console.log) {
|
|
541
|
+
stream(`check ${report.unit} (${report.branch}, base ${report.base}): ${report.changed.length} fichero(s) cambiado(s)`);
|
|
542
|
+
for (const p of report.problems) stream(` problema: ${p}`);
|
|
543
|
+
for (const f of report.out_of_scope) stream(` fuera de alcance: ${f}`);
|
|
544
|
+
for (const f of report.forbidden) stream(` prohibido a un worker: ${f}`);
|
|
545
|
+
for (const f of report.uncommitted) stream(` sin commitear: ${f}`);
|
|
546
|
+
stream(report.ok ? `check ${report.unit}: OK` : `check ${report.unit}: FALLA (merge solo integra commits dentro de write ∪ shared)`);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function cmdCheck(args, ctx) {
|
|
550
|
+
const { positional, options } = parseArgs(args, { flags: ['json'] });
|
|
551
|
+
const [id, unitId] = runAndUnit(positional, ctx, 'omk run check <run> <unidad> [--json]');
|
|
552
|
+
const report = checkScope(ctx.root, loadRun(ctx.root, id), unitId);
|
|
553
|
+
if (options.json) console.log(JSON.stringify(report, null, 2));
|
|
554
|
+
else printScope(report);
|
|
555
|
+
return report.ok ? 0 : 1;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// ---------------------------------------------------------------- merge
|
|
559
|
+
|
|
560
|
+
function cmdMerge(args, ctx) {
|
|
561
|
+
const { root } = ctx;
|
|
562
|
+
const { positional, options } = parseArgs(args, { flags: ['dry-run'] });
|
|
563
|
+
const [id, unitId] = runAndUnit(positional, ctx, 'omk run merge <run> <unidad> [--dry-run]');
|
|
564
|
+
const run = loadRun(root, id);
|
|
565
|
+
const row = rowOf(run, unitId);
|
|
566
|
+
const unit = loadUnit(root, id, unitId);
|
|
567
|
+
const integration = integrationOf(run, root);
|
|
568
|
+
if (defaultBranches(root).includes(integration)) {
|
|
569
|
+
throw new RunError(`la rama de integración ${integration} es la rama por defecto: el merge a ella lo decide el usuario, no omk run`);
|
|
570
|
+
}
|
|
571
|
+
const current = currentBranch(root);
|
|
572
|
+
if (current !== integration) throw new RunError(`estás en ${current || 'HEAD suelto'}, no en la rama de integración ${integration} (git switch ${integration})`);
|
|
573
|
+
requireNoOperation(root);
|
|
574
|
+
requireCleanTree(root, 'merge necesita el árbol limpio');
|
|
575
|
+
if (row.status !== 'accepted') throw new RunError(`${unitId} está en ${row.status}: solo se integra una unidad accepted`);
|
|
576
|
+
|
|
577
|
+
const scope = checkScope(root, run, unitId);
|
|
578
|
+
if (!scope.ok) {
|
|
579
|
+
printScope(scope, console.error);
|
|
580
|
+
throw new RunError(`${unitId} no pasa check: no la integro`);
|
|
581
|
+
}
|
|
582
|
+
const branchRef = `refs/heads/${scope.branch}`;
|
|
583
|
+
const pending = Number(git(['rev-list', '--count', `refs/heads/${integration}..${branchRef}`], { cwd: root }).stdout.trim());
|
|
584
|
+
if (pending === 0) {
|
|
585
|
+
throw new RunError(`${unitId}: la rama ${scope.branch} no aporta commits a ${integration}; ¿se quedaron sin commitear? No la marco como merged`);
|
|
586
|
+
}
|
|
587
|
+
// git merge acepta --no-overwrite-ignore pero la estrategia ort (la de siempre desde git 2.34)
|
|
588
|
+
// no lo respeta: se comprueba aquí que nada de la rama caiga sobre un fichero sin versionar o ignorado.
|
|
589
|
+
const tracked = new Set(splitZ(git(['ls-files', '-z'], { cwd: root }).stdout));
|
|
590
|
+
const clobbered = scope.committed.filter((file) => !tracked.has(file) && lstatOrNull(path.join(root, ...file.split('/'))));
|
|
591
|
+
if (clobbered.length) {
|
|
592
|
+
throw new RunError(`${unitId}: el merge pisaría ficheros sin versionar o ignorados de ${root}:\n${clobbered.map((f) => ` ${f}`).join('\n')}\napártalos tú antes de integrar; no toco nada`);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const [major, minor] = gitVersion(root);
|
|
596
|
+
if (major < MERGE_TREE_MIN[0] || (major === MERGE_TREE_MIN[0] && minor < MERGE_TREE_MIN[1])) {
|
|
597
|
+
throw new RunError(`git ${major}.${minor} no tiene merge-tree --write-tree: hace falta git ≥ ${MERGE_TREE_MIN.join('.')} para ensayar el merge`);
|
|
598
|
+
}
|
|
599
|
+
const trial = git(['merge-tree', '--write-tree', '--name-only', '--no-messages', `refs/heads/${integration}`, branchRef], { cwd: root, check: false });
|
|
600
|
+
if (trial.status === 1) {
|
|
601
|
+
const files = [...new Set(trial.stdout.split(/\r?\n/).slice(1).map((l) => l.trim()).filter(Boolean))];
|
|
602
|
+
throw new RunError(`${unitId}: el ensayo da conflictos con ${integration} en:\n${files.map((f) => ` ${f}`).join('\n')}\nno toco nada (95-multi-agent.md §Conflictos)`);
|
|
603
|
+
}
|
|
604
|
+
if (trial.status !== 0) {
|
|
605
|
+
throw new RunError(`git merge-tree falló (${trial.status}): ${trial.stderr.trim()} — hace falta git ≥ ${MERGE_TREE_MIN.join('.')}`);
|
|
606
|
+
}
|
|
607
|
+
if (options['dry-run']) {
|
|
608
|
+
console.log(`${unitId}: el ensayo de ${scope.branch} sobre ${integration} sale limpio (${scope.changed.length} fichero(s)); no he integrado nada`);
|
|
609
|
+
return 0;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const message = `merge(${id}): ${unitId}${unit.title ? ` — ${unit.title}` : ''}`;
|
|
613
|
+
const before = refSha(root, 'HEAD');
|
|
614
|
+
// requireNoOperation garantiza que no había MERGE_HEAD: si aparece, lo ha dejado este merge.
|
|
615
|
+
// --no-overwrite-ignore: un fichero ignorado del checkout (un .env) no se pisa con uno de la rama.
|
|
616
|
+
const merged = git(['merge', '--no-ff', '--no-edit', '--no-overwrite-ignore', '-m', message, branchRef], { cwd: root, check: false });
|
|
617
|
+
if (merged.status !== 0) {
|
|
618
|
+
const detail = merged.stderr.trim() || merged.stdout.trim();
|
|
619
|
+
if (!mergeInProgress(root)) throw new RunError(`git merge falló sin empezar a integrar: ${detail}\nla rama de integración está como estaba`);
|
|
620
|
+
const aborted = git(['merge', '--abort'], { cwd: root, check: false });
|
|
621
|
+
throw new RunError(`git merge falló: ${detail}\n${aborted.status === 0 ? 'merge abortado: la rama de integración está como estaba' : `y git merge --abort también falló: ${aborted.stderr.trim()}; revisa ${root} a mano`}`);
|
|
622
|
+
}
|
|
623
|
+
const after = refSha(root, 'HEAD');
|
|
624
|
+
if (!after || after === before) throw new RunError(`git merge salió bien pero HEAD no cambió (${short(before || '')}): no marco ${unitId} como merged; revísalo a mano`);
|
|
625
|
+
const head = abbrev(root, after);
|
|
626
|
+
ledger.setUnit(run, unitId, { status: 'merged', head });
|
|
627
|
+
ledger.addLog(run, `${unitId} integrada en ${integration} · merge ${head}`);
|
|
628
|
+
ledger.writeRun(root, run);
|
|
629
|
+
console.log(`${unitId}: integrada en ${integration} (merge ${head}). No he hecho push`);
|
|
630
|
+
return 0;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const COMMANDS = { start: cmdStart, worktree: cmdWorktree, check: cmdCheck, merge: cmdMerge };
|
|
634
|
+
|
|
635
|
+
/** Contrato de bin/run.js: devuelve el código de salida. */
|
|
636
|
+
function run(sub, args, ctx) {
|
|
637
|
+
if (!COMMANDS[sub]) throw new RunError(`subcomando desconocido para bin/run/git.js: ${sub}`, 2);
|
|
638
|
+
return COMMANDS[sub](args, ctx);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
module.exports = { run, checkScope, isForbidden, defaultBranches, unitBranch, defaultWorktree, FORBIDDEN_GLOBS, FORBIDDEN_NAMES };
|