orca-multiagent-kit 1.5.0 → 1.7.0
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 +70 -1
- package/GUIA.html +11 -9
- package/README.md +23 -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 +134 -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/team.js +353 -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 +131 -24
- package/hooks/orca-gate.cjs +402 -0
- package/install.sh +26 -13
- package/orca-plugin/README.md +7 -1
- package/orca-plugin/assets/logos/README.md +10 -0
- package/orca-plugin/assets/logos/agent.png +0 -0
- package/orca-plugin/assets/logos/aider.png +0 -0
- package/orca-plugin/assets/logos/amp.png +0 -0
- package/orca-plugin/assets/logos/antigravity.png +0 -0
- package/orca-plugin/assets/logos/claude.png +0 -0
- package/orca-plugin/assets/logos/cline.png +0 -0
- package/orca-plugin/assets/logos/codex.png +0 -0
- package/orca-plugin/assets/logos/copilot.png +0 -0
- package/orca-plugin/assets/logos/cursor.png +0 -0
- package/orca-plugin/assets/logos/devin.png +0 -0
- package/orca-plugin/assets/logos/droid.png +0 -0
- package/orca-plugin/assets/logos/gemini.png +0 -0
- package/orca-plugin/assets/logos/goose.png +0 -0
- package/orca-plugin/assets/logos/grok.png +0 -0
- package/orca-plugin/assets/logos/kimi.png +0 -0
- package/orca-plugin/assets/logos/kiro.png +0 -0
- package/orca-plugin/assets/logos/opencode.png +0 -0
- package/orca-plugin/assets/logos/qwen-code.png +0 -0
- package/orca-plugin/orca-plugin.json +25 -7
- package/orca-plugin/src/icons.test.ts +14 -0
- package/orca-plugin/src/icons.ts +30 -0
- package/orca-plugin/src/kit.test.ts +491 -22
- package/orca-plugin/src/kit.ts +687 -37
- package/orca-plugin/src/models.test.ts +28 -0
- package/orca-plugin/src/models.ts +29 -0
- package/orca-plugin/src/node.d.ts +40 -0
- package/orca-plugin/src/panel-state.ts +36 -0
- package/orca-plugin/src/panel.check.ts +71 -0
- package/orca-plugin/src/panel.test.tsx +296 -33
- package/orca-plugin/src/panel.tsx +501 -81
- package/orca-plugin/src/plan-card.test.ts +99 -0
- package/orca-plugin/src/plan-card.ts +107 -0
- package/orca-plugin/src/protocol.ts +205 -5
- package/orca-plugin/src/tabs/autonomy.tsx +72 -0
- package/orca-plugin/src/tabs/history.test.tsx +79 -0
- package/orca-plugin/src/tabs/history.tsx +119 -0
- package/orca-plugin/src/tabs/notices.test.tsx +184 -0
- package/orca-plugin/src/tabs/notices.tsx +274 -0
- package/orca-plugin/src/tabs/worktrees.test.tsx +131 -0
- package/orca-plugin/src/tabs/worktrees.tsx +138 -0
- package/orca-plugin/src/ui/action-card.tsx +112 -0
- package/orca-plugin/src/ui/agent-icon.tsx +13 -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.test.ts +32 -0
- package/orca-plugin/src/worker/context.ts +95 -0
- package/orca-plugin/src/worker/history.test.ts +149 -0
- package/orca-plugin/src/worker/history.ts +181 -0
- package/orca-plugin/src/worker/notices.test.ts +356 -0
- package/orca-plugin/src/worker/notices.ts +288 -0
- package/orca-plugin/src/worker/system.test.ts +58 -0
- package/orca-plugin/src/worker/system.ts +122 -0
- package/orca-plugin/src/worker/worktrees.test.ts +177 -0
- package/orca-plugin/src/worker/worktrees.ts +188 -0
- package/orca-plugin/src/worker.test.ts +285 -24
- package/orca-plugin/src/worker.ts +344 -64
- 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 +28 -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-orca.md +1 -0
- 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 +2 -1
- package/skills/orca/references/plan-card.md +45 -0
- 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
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// omk run cleanup: inventario, sacado de git, de los worktrees y ramas que deja un run y, con --apply,
|
|
2
|
+
// borrado de solo lo integrado y limpio (skills/orca/references/integrate.md §6). Borra trabajo, así
|
|
3
|
+
// que ante la duda se queda: nada de --force ni -D, y nada que git no liste como worktree o rama.
|
|
4
|
+
//
|
|
5
|
+
// Lo que hace git sin --force (comprobado con git 2.52): `git worktree remove` se lleva los ficheros
|
|
6
|
+
// ignorados (el .env copiado, las dependencias) y se niega si hay ficheros no versionados, cambios
|
|
7
|
+
// sin commit o el worktree está bloqueado; `git branch -d` se niega si la rama sigue en un worktree o
|
|
8
|
+
// no está integrada en su upstream o en el HEAD del checkout donde corre.
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const fs = require('node:fs');
|
|
12
|
+
const path = require('node:path');
|
|
13
|
+
const { RunError, checkBranch, git, parseArgs } = require('./util');
|
|
14
|
+
const ledger = require('./ledger');
|
|
15
|
+
|
|
16
|
+
const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
17
|
+
const HEADS = 'refs/heads/';
|
|
18
|
+
const WIN = process.platform === 'win32';
|
|
19
|
+
|
|
20
|
+
/** Clave para comparar rutas: absoluta, real si existe y, en Windows, sin mayúsculas. */
|
|
21
|
+
function pathKey(p) {
|
|
22
|
+
let full = path.resolve(p);
|
|
23
|
+
try {
|
|
24
|
+
full = fs.realpathSync.native(full);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
// Sin ruta real (no existe o no se puede leer) se compara la ruta tal cual: no se borra por ello.
|
|
27
|
+
if (!['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM'].includes(error.code)) throw error;
|
|
28
|
+
}
|
|
29
|
+
return WIN ? full.toLowerCase() : full;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Si `child` es `parent` o está dentro de él. */
|
|
33
|
+
function isInside(child, parent) {
|
|
34
|
+
const c = pathKey(child);
|
|
35
|
+
const p = pathKey(parent);
|
|
36
|
+
return c === p || c.startsWith(p.endsWith(path.sep) ? p : p + path.sep);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Salida de `git worktree list --porcelain` en objetos: campos separados por NUL (con -z) o por líneas
|
|
41
|
+
* (git < 2.36, donde en Windows cada línea puede acabar en \r).
|
|
42
|
+
*/
|
|
43
|
+
function parsePorcelain(text, sep) {
|
|
44
|
+
const list = [];
|
|
45
|
+
let cur = null;
|
|
46
|
+
for (const raw of text.split(sep)) {
|
|
47
|
+
const field = sep === '\0' ? raw : raw.replace(/\r$/, '');
|
|
48
|
+
if (field === '') {
|
|
49
|
+
if (cur) list.push(cur);
|
|
50
|
+
cur = null;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const space = field.indexOf(' ');
|
|
54
|
+
const key = space === -1 ? field : field.slice(0, space);
|
|
55
|
+
const value = space === -1 ? '' : field.slice(space + 1);
|
|
56
|
+
if (key === 'worktree') {
|
|
57
|
+
if (cur) list.push(cur);
|
|
58
|
+
cur = { path: value, head: null, branch: null, bare: false, detached: false, locked: false, prunable: false };
|
|
59
|
+
} else if (cur) {
|
|
60
|
+
if (key === 'HEAD') cur.head = value;
|
|
61
|
+
else if (key === 'branch') cur.branch = value.startsWith(HEADS) ? value.slice(HEADS.length) : null;
|
|
62
|
+
else if (['bare', 'detached', 'locked', 'prunable'].includes(key)) cur[key] = true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (cur) list.push(cur);
|
|
66
|
+
return list;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** `git worktree list --porcelain` (con -z si el git lo admite) en objetos. */
|
|
70
|
+
function listWorktrees(root) {
|
|
71
|
+
const res = git(['worktree', 'list', '--porcelain', '-z'], { cwd: root, check: false });
|
|
72
|
+
if (res.status === 0) return parsePorcelain(res.stdout, '\0');
|
|
73
|
+
return parsePorcelain(git(['worktree', 'list', '--porcelain'], { cwd: root }).stdout, '\n');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 0 → sí, 1 → no, otra cosa → no se sabe (null). */
|
|
77
|
+
function isAncestor(root, commit, target) {
|
|
78
|
+
const res = git(['merge-base', '--is-ancestor', commit, target], { cwd: root, check: false });
|
|
79
|
+
if (res.status === 0) return true;
|
|
80
|
+
if (res.status === 1) return false;
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function countAhead(root, commit, target) {
|
|
85
|
+
const res = git(['rev-list', '--count', `${target}..${commit}`], { cwd: root, check: false });
|
|
86
|
+
return res.status === 0 ? Number.parseInt(res.stdout.trim(), 10) : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Cambios sin commit (con no versionados) e ignorados de un worktree, sin tomar el bloqueo del índice. */
|
|
90
|
+
function worktreeChanges(root, dir) {
|
|
91
|
+
const res = git(['--no-optional-locks', '-C', dir, 'status', '--porcelain', '-z', '--untracked-files=all', '--ignored=matching'], { cwd: root, check: false });
|
|
92
|
+
if (res.status !== 0) return null;
|
|
93
|
+
const entries = res.stdout.split('\0');
|
|
94
|
+
let changes = 0;
|
|
95
|
+
let ignored = 0;
|
|
96
|
+
for (let i = 0; i < entries.length; i += 1) {
|
|
97
|
+
const entry = entries[i];
|
|
98
|
+
if (entry.length < 3) continue;
|
|
99
|
+
if (entry.startsWith('!! ')) { ignored += 1; continue; }
|
|
100
|
+
changes += 1;
|
|
101
|
+
if (entry[0] === 'R' || entry[0] === 'C') i += 1; // con -z, el origen de un renombrado va en la entrada siguiente
|
|
102
|
+
}
|
|
103
|
+
return { changes, ignored };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function validBranch(name, root) {
|
|
107
|
+
try {
|
|
108
|
+
checkBranch(name, root);
|
|
109
|
+
return true;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error instanceof RunError) return false;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Rama padre del run según base_ref («<ref> @ <sha>»), sin el «<remoto>/» si ese remoto existe. */
|
|
117
|
+
function parentBranch(root, run) {
|
|
118
|
+
const raw = run && run.meta.base_ref;
|
|
119
|
+
if (!raw || raw === ledger.EMPTY) return null;
|
|
120
|
+
const match = /^(.*?)\s+@\s+\S+$/.exec(raw.trim());
|
|
121
|
+
const ref = (match ? match[1] : raw).trim();
|
|
122
|
+
if (!ref || ref === ledger.EMPTY) return null;
|
|
123
|
+
const slash = ref.indexOf('/');
|
|
124
|
+
if (slash > 0) {
|
|
125
|
+
const remotes = git(['remote'], { cwd: root }).stdout.split(/\r?\n/).filter(Boolean);
|
|
126
|
+
if (remotes.includes(ref.slice(0, slash))) return ref.slice(slash + 1);
|
|
127
|
+
}
|
|
128
|
+
return ref;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Ramas que nunca se tocan: devuelve una función que da el motivo (o null). Entran la por defecto
|
|
133
|
+
* (origin/HEAD, main y master), la actual del coordinador, la de integración, la padre del run y toda
|
|
134
|
+
* rama local con upstream configurado (está publicada: su limpieza es cosa del usuario).
|
|
135
|
+
*/
|
|
136
|
+
function protectedBranches(root, integration, run, upstreams) {
|
|
137
|
+
const guard = new Map([['main', 'rama por defecto'], ['master', 'rama por defecto']]);
|
|
138
|
+
const origin = git(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { cwd: root, check: false });
|
|
139
|
+
const remoteHead = origin.status === 0 ? origin.stdout.trim() : '';
|
|
140
|
+
if (remoteHead.startsWith('refs/remotes/origin/') && remoteHead.length > 'refs/remotes/origin/'.length) {
|
|
141
|
+
guard.set(remoteHead.slice('refs/remotes/origin/'.length), 'rama por defecto');
|
|
142
|
+
}
|
|
143
|
+
const parent = parentBranch(root, run);
|
|
144
|
+
if (parent) guard.set(parent, 'rama padre del run');
|
|
145
|
+
const current = git(['symbolic-ref', '--quiet', '--short', 'HEAD'], { cwd: root, check: false });
|
|
146
|
+
if (current.status === 0 && current.stdout.trim()) guard.set(current.stdout.trim(), 'rama actual del coordinador');
|
|
147
|
+
guard.set(integration, 'rama de integración');
|
|
148
|
+
return (name) => guard.get(name) || (upstreams.get(name) ? `tiene upstream (${upstreams.get(name)})` : null);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Una celda de run.md con valor (ni «—» ni «(principal)», «(Orca)»…). */
|
|
152
|
+
const isCell = (cell) => Boolean(cell) && cell !== ledger.EMPTY && !/^\(.*\)$/.test(cell);
|
|
153
|
+
|
|
154
|
+
/** Estados de unidad con los que lo suyo ya se puede borrar. */
|
|
155
|
+
const SETTLED = ['merged', 'discarded', 'reverted'];
|
|
156
|
+
|
|
157
|
+
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Inventario del run: lista de {type, name, branch?, state, action: delete|keep|gone, reason, protected}.
|
|
161
|
+
* Solo entra lo que git lista; las rutas de run.md que git no lista salen como `ruta` y no se tocan.
|
|
162
|
+
* Lo que pertenece a una fila de run.md solo se borra si la unidad está cerrada (SETTLED).
|
|
163
|
+
*/
|
|
164
|
+
function inventory({ root, id, integration, run }) {
|
|
165
|
+
const prefix = `${HEADS}wt/${id}/`;
|
|
166
|
+
const worktrees = listWorktrees(root);
|
|
167
|
+
const main = worktrees[0];
|
|
168
|
+
const listedKeys = new Set(worktrees.map((wt) => pathKey(wt.path)));
|
|
169
|
+
const refLines = git(['for-each-ref', '--format=%(refname)%09%(upstream)', HEADS], { cwd: root }).stdout.split(/\r?\n/).filter(Boolean);
|
|
170
|
+
const local = new Set();
|
|
171
|
+
const upstreams = new Map();
|
|
172
|
+
for (const line of refLines) {
|
|
173
|
+
const [ref, upstream = ''] = line.split('\t');
|
|
174
|
+
local.add(ref);
|
|
175
|
+
if (upstream) upstreams.set(ref.slice(HEADS.length), upstream);
|
|
176
|
+
}
|
|
177
|
+
const guardOf = protectedBranches(root, integration, run, upstreams);
|
|
178
|
+
const integrationRef = `${HEADS}${integration}`;
|
|
179
|
+
const rows = (run ? run.units : []).map((u) => {
|
|
180
|
+
const pathCell = isCell(u.worktree) ? u.worktree : null;
|
|
181
|
+
const full = pathCell ? path.resolve(root, pathCell) : null;
|
|
182
|
+
return { unit: u.unit, status: u.status, branch: isCell(u.branch) ? u.branch : null, pathCell, full, key: full ? pathKey(full) : null };
|
|
183
|
+
});
|
|
184
|
+
const busyRow = (owners) => owners.find((r) => !SETTLED.includes(r.status));
|
|
185
|
+
const items = [];
|
|
186
|
+
|
|
187
|
+
// 1. Worktrees del run: rama wt/<run>/… o ruta de una celda de run.md cuya fila tenga esa misma rama.
|
|
188
|
+
const removing = new Set();
|
|
189
|
+
for (const wt of worktrees) {
|
|
190
|
+
if (wt.bare) continue;
|
|
191
|
+
const key = pathKey(wt.path);
|
|
192
|
+
const byPrefix = Boolean(wt.branch) && `${HEADS}${wt.branch}`.startsWith(prefix);
|
|
193
|
+
const pathRows = rows.filter((r) => r.key === key);
|
|
194
|
+
if (!byPrefix && !pathRows.length) continue;
|
|
195
|
+
const item = { type: 'worktree', name: wt.path, branch: wt.branch, state: '', action: 'keep', reason: '', protected: false };
|
|
196
|
+
items.push(item);
|
|
197
|
+
const keep = (state, reason, isProtected = false) => Object.assign(item, { state, reason, protected: isProtected });
|
|
198
|
+
if (!byPrefix && !pathRows.some((r) => r.branch && r.branch === wt.branch)) {
|
|
199
|
+
keep(`en ${wt.branch || 'HEAD separado'}`, 'la ruta de run.md no es de esta unidad', true);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const owners = rows.filter((r) => r.key === key || (wt.branch && r.branch === wt.branch));
|
|
203
|
+
const guard = wt.branch ? guardOf(wt.branch) : null;
|
|
204
|
+
if (wt === main || isInside(main.path, wt.path)) { keep('checkout principal', 'es el checkout principal del repositorio', true); continue; }
|
|
205
|
+
if (isInside(root, wt.path)) { keep('checkout del coordinador', 'aquí vive el run', true); continue; }
|
|
206
|
+
if (guard) { keep(`en ${wt.branch}`, `su rama: ${guard}`, true); continue; }
|
|
207
|
+
const busy = busyRow(owners);
|
|
208
|
+
if (busy) { keep(`${busy.unit} en ${busy.status}`, `unidad en ${busy.status}`); continue; }
|
|
209
|
+
if (wt.prunable) { keep('ruta desaparecida', 'git lo lista pero la carpeta no existe: git worktree prune'); continue; }
|
|
210
|
+
if (wt.locked) { keep('bloqueado', 'está bloqueado (git worktree unlock si ya no hace falta)'); continue; }
|
|
211
|
+
const changes = worktreeChanges(root, wt.path);
|
|
212
|
+
if (!changes) { keep('sin estado', 'git status falló en el worktree'); continue; }
|
|
213
|
+
const ignoredNote = changes.ignored ? ` · ${plural(changes.ignored, 'ignorado', 'ignorados')} (${changes.ignored === 1 ? 'se va' : 'se van'} con el worktree)` : '';
|
|
214
|
+
if (changes.changes) { keep(`${plural(changes.changes, 'cambio', 'cambios')} sin commit${ignoredNote}`, 'se perderían los cambios sin commit'); continue; }
|
|
215
|
+
if (!wt.head || !SHA.test(wt.head)) { keep('sin commit', 'no tiene un HEAD que comprobar'); continue; }
|
|
216
|
+
const integrated = isAncestor(root, wt.head, integrationRef);
|
|
217
|
+
if (integrated === null) { keep('sin comprobar', `no pude comparar con ${integration}`); continue; }
|
|
218
|
+
if (!integrated) {
|
|
219
|
+
const ahead = countAhead(root, wt.head, integrationRef);
|
|
220
|
+
keep(`${ahead === null ? 'commits' : plural(ahead, 'commit', 'commits')} sin integrar${ignoredNote}`, `no está integrado en ${integration}`);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
Object.assign(item, { state: `limpio, integrado${ignoredNote}`, action: 'delete', reason: '' });
|
|
224
|
+
removing.add(wt);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Una fila ya limpiada: ni su rama ni su worktree siguen en git, y su carpeta ya no existe.
|
|
228
|
+
const rowGone = (r) => !(r.branch && local.has(`${HEADS}${r.branch}`))
|
|
229
|
+
&& !(r.key && (listedKeys.has(r.key) || fs.existsSync(r.full)));
|
|
230
|
+
const gone = (type, name) => ({ type, name, state: 'ni rama ni worktree en git', action: 'gone', reason: '', protected: true });
|
|
231
|
+
|
|
232
|
+
// 2. Ramas del run: wt/<run>/… y las celdas branch de run.md, solo si git las lista.
|
|
233
|
+
const names = [];
|
|
234
|
+
for (const ref of local) if (ref.startsWith(prefix)) names.push(ref.slice(HEADS.length));
|
|
235
|
+
for (const r of rows) {
|
|
236
|
+
if (!r.branch || r.branch === integration || names.includes(r.branch)) continue;
|
|
237
|
+
if (local.has(`${HEADS}${r.branch}`)) names.push(r.branch);
|
|
238
|
+
else if (rowGone(r)) items.push(gone('rama', r.branch));
|
|
239
|
+
else items.push({ type: 'rama', name: r.branch, state: 'git no la lista', action: 'keep', reason: 'run.md la nombra pero no existe como rama local', protected: true });
|
|
240
|
+
}
|
|
241
|
+
const checkedOut = new Map(worktrees.filter((wt) => wt.branch).map((wt) => [wt.branch, wt]));
|
|
242
|
+
for (const name of names) {
|
|
243
|
+
const item = { type: 'rama', name, state: '', action: 'keep', reason: '', protected: false };
|
|
244
|
+
items.push(item);
|
|
245
|
+
const keep = (state, reason, isProtected = false) => Object.assign(item, { state, reason, protected: isProtected });
|
|
246
|
+
const guard = guardOf(name);
|
|
247
|
+
if (guard) { keep(guard, 'no se toca nunca', true); continue; }
|
|
248
|
+
if (!validBranch(name, root)) { keep('nombre no válido', 'git check-ref-format la rechaza', true); continue; }
|
|
249
|
+
const busy = busyRow(rows.filter((r) => r.branch === name));
|
|
250
|
+
if (busy) { keep(`${busy.unit} en ${busy.status}`, `unidad en ${busy.status}`); continue; }
|
|
251
|
+
const holder = checkedOut.get(name);
|
|
252
|
+
if (holder && !removing.has(holder)) { keep('en uso', `la tiene el worktree ${holder.path}, que se queda`); continue; }
|
|
253
|
+
const ref = `${HEADS}${name}`;
|
|
254
|
+
const integrated = isAncestor(root, ref, integrationRef);
|
|
255
|
+
if (integrated === null) { keep('sin comprobar', `no pude comparar con ${integration}`); continue; }
|
|
256
|
+
if (!integrated) {
|
|
257
|
+
const ahead = countAhead(root, ref, integrationRef);
|
|
258
|
+
keep(`${ahead === null ? 'commits' : plural(ahead, 'commit', 'commits')} sin integrar`, `no está integrada en ${integration}`);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
Object.assign(item, { state: 'integrada', action: 'delete', worktree: holder ? holder.path : null });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// 3. Rutas de run.md que git no lista como worktree: se informan y no se tocan nunca; las de filas
|
|
265
|
+
// ya limpiadas salen como «ya borrado».
|
|
266
|
+
const seen = new Set();
|
|
267
|
+
for (const r of rows) {
|
|
268
|
+
if (!r.key || listedKeys.has(r.key) || seen.has(r.key)) continue;
|
|
269
|
+
seen.add(r.key);
|
|
270
|
+
if (rowGone(r)) items.push(gone('ruta', r.pathCell));
|
|
271
|
+
else items.push({ type: 'ruta', name: r.pathCell, state: 'git no la lista como worktree', action: 'keep', reason: 'no es un worktree de git: no se toca', protected: true });
|
|
272
|
+
}
|
|
273
|
+
return { items, worktrees };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Borra lo marcado: primero los worktrees y después sus ramas. Devuelve cuántos fallos hubo. */
|
|
277
|
+
function apply({ root, integration, items, worktrees }) {
|
|
278
|
+
let failed = 0;
|
|
279
|
+
const removed = new Set();
|
|
280
|
+
const fail = (item, res) => {
|
|
281
|
+
failed += 1;
|
|
282
|
+
item.result = 'falló';
|
|
283
|
+
item.error = (res.stderr.trim() || res.stdout.trim()).split(/\r?\n/)[0];
|
|
284
|
+
};
|
|
285
|
+
for (const item of items.filter((i) => i.type === 'worktree' && i.action === 'delete')) {
|
|
286
|
+
const res = git(['worktree', 'remove', item.name], { cwd: root, check: false });
|
|
287
|
+
if (res.status === 0) { item.result = 'borrado'; removed.add(pathKey(item.name)); } else fail(item, res);
|
|
288
|
+
}
|
|
289
|
+
// `git branch -d` compara con el HEAD de donde corre: se lanza desde el worktree de la integración si lo hay.
|
|
290
|
+
const host = worktrees.find((wt) => wt.branch === integration && !wt.prunable && fs.existsSync(wt.path));
|
|
291
|
+
const cwd = host ? host.path : root;
|
|
292
|
+
for (const item of items.filter((i) => i.type === 'rama' && i.action === 'delete')) {
|
|
293
|
+
if (item.worktree && !removed.has(pathKey(item.worktree))) {
|
|
294
|
+
failed += 1;
|
|
295
|
+
Object.assign(item, { result: 'falló', error: 'su worktree no se borró' });
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const res = git(['branch', '-d', item.name], { cwd, check: false });
|
|
299
|
+
if (res.status === 0) item.result = 'borrada'; else fail(item, res);
|
|
300
|
+
}
|
|
301
|
+
return failed;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const ACTION_TEXT = { delete: 'borrar', keep: 'se queda', gone: 'ya borrado' };
|
|
305
|
+
|
|
306
|
+
function actionText(item) {
|
|
307
|
+
if (item.result) return item.error ? `${item.result} — ${item.error}` : item.result;
|
|
308
|
+
return item.action === 'keep' ? `${ACTION_TEXT.keep} — ${item.reason}` : ACTION_TEXT[item.action];
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function summarize(items) {
|
|
312
|
+
const count = (type, action) => items.filter((i) => i.type === type && i.action === action).length;
|
|
313
|
+
return {
|
|
314
|
+
delete: { worktrees: count('worktree', 'delete'), branches: count('rama', 'delete') },
|
|
315
|
+
keep: items.filter((i) => i.action === 'keep').length,
|
|
316
|
+
gone: items.filter((i) => i.action === 'gone').length,
|
|
317
|
+
unlisted: count('ruta', 'keep'),
|
|
318
|
+
prunable: items.some((i) => i.type === 'worktree' && i.state === 'ruta desaparecida'),
|
|
319
|
+
deleted: items.filter((i) => i.result === 'borrado' || i.result === 'borrada').length,
|
|
320
|
+
failed: items.filter((i) => i.result === 'falló').length,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function printTable(items) {
|
|
325
|
+
const rows = [['tipo', 'nombre', 'estado', 'acción'], ...items.map((i) => [i.type, i.name, i.state, actionText(i)])];
|
|
326
|
+
const widths = [0, 1, 2].map((c) => Math.max(...rows.map((r) => r[c].length)));
|
|
327
|
+
for (const row of rows) console.log(row.map((cell, c) => (c < 3 ? cell.padEnd(widths[c]) : cell)).join(' | ').trimEnd());
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Lo que queda del run tras --apply (sin contar lo protegido ni las rutas que git no lista). */
|
|
331
|
+
function leftovers(items) {
|
|
332
|
+
return items.filter((i) => i.type !== 'ruta' && !i.protected).length;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function run(sub, args, ctx) {
|
|
336
|
+
const { positional, options } = parseArgs(args, { flags: ['apply', 'json'], values: ['integration'] });
|
|
337
|
+
if (positional.length > 1) throw new RunError(`sobra: ${positional.slice(1).join(' ')}`, 2);
|
|
338
|
+
const { root } = ctx;
|
|
339
|
+
const id = ctx.resolveRun(root, positional[0]);
|
|
340
|
+
const file = ledger.runFile(root, id);
|
|
341
|
+
let ledgerRun = null;
|
|
342
|
+
if (fs.existsSync(file)) {
|
|
343
|
+
ledgerRun = ledger.readRun(root, id);
|
|
344
|
+
if (ledgerRun.problems.length) {
|
|
345
|
+
for (const p of ledgerRun.problems) console.error(` ${file}:${p.line}: ${p.message}`);
|
|
346
|
+
if (options.apply) throw new RunError('run.md tiene problemas de formato: arréglalo antes de borrar nada');
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const fromLedger = ledgerRun && ledgerRun.meta.integration && ledgerRun.meta.integration !== ledger.EMPTY ? ledgerRun.meta.integration : null;
|
|
350
|
+
const integration = options.integration || fromLedger;
|
|
351
|
+
if (!integration) {
|
|
352
|
+
throw new RunError(ledgerRun ? 'run.md no tiene rama de integración: indícala con --integration <rama>' : `no existe ${file}: para un run sin run.md indica --integration <rama>`, 2);
|
|
353
|
+
}
|
|
354
|
+
checkBranch(integration, root);
|
|
355
|
+
if (git(['rev-parse', '--verify', '--quiet', `${HEADS}${integration}`], { cwd: root, check: false }).status !== 0) {
|
|
356
|
+
throw new RunError(`la rama de integración «${integration}» no existe en este repositorio`);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const { items, worktrees } = inventory({ root, id, integration, run: ledgerRun });
|
|
360
|
+
let failed = 0;
|
|
361
|
+
let cleanup = null;
|
|
362
|
+
let ledgerError = null;
|
|
363
|
+
if (options.apply) {
|
|
364
|
+
failed = apply({ root, integration, items, worktrees });
|
|
365
|
+
if (ledgerRun) {
|
|
366
|
+
cleanup = leftovers(inventory({ root, id, integration, run: ledgerRun }).items) ? 'pending' : 'done';
|
|
367
|
+
const s = summarize(items);
|
|
368
|
+
try {
|
|
369
|
+
const fresh = ledger.readRun(root, id);
|
|
370
|
+
if (fresh.problems.length) throw new RunError('run.md cambió y ahora tiene problemas de formato: no lo toco');
|
|
371
|
+
ledger.setMeta(fresh, 'cleanup', cleanup);
|
|
372
|
+
ledger.addLog(fresh, `cleanup --apply: ${s.deleted} borrados · ${s.keep} se quedan${s.failed ? ` · ${s.failed} fallos` : ''} · cleanup ${cleanup}`);
|
|
373
|
+
ledger.writeRun(root, fresh);
|
|
374
|
+
} catch (error) {
|
|
375
|
+
if (!(error instanceof RunError)) throw error;
|
|
376
|
+
ledgerError = error.message;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const summary = summarize(items);
|
|
382
|
+
const code = failed || ledgerError ? 1 : 0;
|
|
383
|
+
if (options.json) {
|
|
384
|
+
console.log(JSON.stringify({ run: id, integration, apply: Boolean(options.apply), items, summary, cleanup, ledgerError }, null, 2));
|
|
385
|
+
return code;
|
|
386
|
+
}
|
|
387
|
+
console.log(`cleanup ${id} · integración ${integration} · ${options.apply ? 'borrando' : 'ensayo: sin --apply no se borra nada'}`);
|
|
388
|
+
if (items.length) printTable(items);
|
|
389
|
+
else console.log('no queda ningún worktree ni rama de este run');
|
|
390
|
+
const parts = options.apply
|
|
391
|
+
? [`${summary.deleted} borrados`, `${summary.keep} se quedan`, ...(summary.failed ? [`${summary.failed} fallos`] : [])]
|
|
392
|
+
: [`para borrar: ${plural(summary.delete.worktrees, 'worktree', 'worktrees')} y ${plural(summary.delete.branches, 'rama', 'ramas')}`, `${summary.keep} se quedan`];
|
|
393
|
+
if (summary.gone) parts.push(`${summary.gone} ya borrados`);
|
|
394
|
+
console.log(`resumen: ${parts.join(' · ')}`);
|
|
395
|
+
if (summary.unlisted) console.log(`aviso: ${plural(summary.unlisted, 'ruta', 'rutas')} de run.md que git no lista como worktree: no se tocan`);
|
|
396
|
+
if (summary.prunable) console.log('aviso: hay worktrees cuya carpeta ya no existe: git worktree prune los quita del registro');
|
|
397
|
+
if (cleanup) console.log(`run.md: cleanup ${cleanup}`);
|
|
398
|
+
if (ledgerError) console.error(`omk run cleanup: ${ledgerError}`);
|
|
399
|
+
return code;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
module.exports = { run, inventory, listWorktrees, parsePorcelain, pathKey };
|