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.
Files changed (71) hide show
  1. package/AI_INSTALL.md +4 -3
  2. package/CHANGELOG.md +47 -1
  3. package/GUIA.html +11 -9
  4. package/README.md +22 -23
  5. package/VERSION +1 -1
  6. package/bin/backup.js +44 -0
  7. package/bin/fetch.js +243 -0
  8. package/bin/hooks.js +187 -0
  9. package/bin/omk.js +147 -51
  10. package/bin/run/cleanup.js +402 -0
  11. package/bin/run/git.js +641 -0
  12. package/bin/run/glob.js +193 -0
  13. package/bin/run/ledger.js +243 -0
  14. package/bin/run/plan.js +328 -0
  15. package/bin/run/units.js +101 -0
  16. package/bin/run/util.js +116 -0
  17. package/bin/run.js +224 -0
  18. package/bin/setup.js +81 -8
  19. package/bin/sync.js +222 -0
  20. package/bin/ui.js +8 -4
  21. package/bin/update.js +169 -0
  22. package/core/AGENTS.md +7 -7
  23. package/docs/EJECUTABLE.md +5 -4
  24. package/docs/MANUAL.md +16 -3
  25. package/docs/ORQUESTADOR.md +59 -1
  26. package/docs/PLUGIN-ORCA.md +34 -16
  27. package/hooks/orca-gate.cjs +402 -0
  28. package/install.sh +26 -13
  29. package/orca-plugin/README.md +3 -1
  30. package/orca-plugin/orca-plugin.json +2 -2
  31. package/orca-plugin/src/kit.test.ts +35 -13
  32. package/orca-plugin/src/kit.ts +64 -19
  33. package/orca-plugin/src/panel-state.ts +11 -3
  34. package/orca-plugin/src/panel.check.ts +71 -0
  35. package/orca-plugin/src/panel.test.tsx +69 -4
  36. package/orca-plugin/src/panel.tsx +32 -16
  37. package/orca-plugin/src/protocol.ts +39 -0
  38. package/orca-plugin/src/tabs/autonomy.tsx +3 -1
  39. package/orca-plugin/src/tabs/history.test.tsx +1 -0
  40. package/orca-plugin/src/tabs/history.tsx +1 -0
  41. package/orca-plugin/src/tabs/notices.test.tsx +1 -0
  42. package/orca-plugin/src/tabs/worktrees.test.tsx +1 -0
  43. package/orca-plugin/src/ui/action-card.tsx +112 -0
  44. package/orca-plugin/src/worker/actions.test.ts +288 -0
  45. package/orca-plugin/src/worker/actions.ts +292 -0
  46. package/orca-plugin/src/worker/context.ts +4 -1
  47. package/orca-plugin/src/worker/history.ts +3 -3
  48. package/orca-plugin/src/worker/notices.ts +1 -4
  49. package/orca-plugin/src/worker.test.ts +24 -6
  50. package/orca-plugin/src/worker.ts +79 -83
  51. package/output-styles/csr-minimal.md +1 -0
  52. package/package.json +3 -3
  53. package/rules/50-done-gate.md +1 -1
  54. package/rules/95-multi-agent.md +13 -3
  55. package/skills/kit-init/SKILL.md +16 -4
  56. package/skills/orca/SKILL.md +27 -5
  57. package/skills/orca/references/adapters/artifact.md +2 -0
  58. package/skills/orca/references/adapters/chat.md +2 -0
  59. package/skills/orca/references/adapters/native-plan.md +6 -0
  60. package/skills/orca/references/adapters/plan-file.md +2 -0
  61. package/skills/orca/references/engine-manual.md +7 -5
  62. package/skills/orca/references/engine-subagents.md +4 -4
  63. package/skills/orca/references/integrate.md +14 -2
  64. package/skills/orca/references/ledger.md +1 -1
  65. package/skills/orca/references/olimpo.md +1 -1
  66. package/skills/orca/references/plan.md +2 -1
  67. package/skills/orca/references/units.md +1 -1
  68. package/skills/orca/references/worker-contract.md +2 -2
  69. package/templates/AGENTS.md +2 -2
  70. package/templates/CLAUDE.md +1 -1
  71. package/templates/claude-settings.json +25 -0
package/bin/run.js ADDED
@@ -0,0 +1,224 @@
1
+ // omk run: el motor determinista de la skill orca. Lo que no debe depender de que el modelo se
2
+ // acuerde (estado del run, rondas, worktrees, alcance, merge y limpieza) lo hace este código; el
3
+ // modelo decide el reparto y revisa. Estado en .work/runs/<run>/ del checkout del coordinador.
4
+ 'use strict';
5
+
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const { RunError, checkRunId, checkoutRoot, runDir, parseArgs, writeAtomic } = require('./run/util');
9
+ const { parseUnits } = require('./run/units');
10
+ const ledger = require('./run/ledger');
11
+
12
+ const HELP = `Uso: omk run <subcomando> [opciones]
13
+
14
+ new <run> [--input X] [--autonomy semi] [--engine E] [--integration RAMA] [--base "REF @ SHA"]
15
+ Crea .work/runs/<run>/run.md con las unidades de su units.md, en pending
16
+ list [--json] Los runs de este repositorio y su estado
17
+ status [<run>] [--json] Cabecera, unidades y log de un run (sin <run>, el único activo)
18
+ set <run> <unidad> clave=valor… [--force]
19
+ Cambia una unidad: status, ref, branch, worktree, base, head, role,
20
+ agent, round, attempts. status respeta las transiciones de ledger.md
21
+ meta <run> clave=valor… Cambia la cabecera: status, cleanup, integration, base_ref, confirm1…
22
+ log <run> <texto> Añade una línea al log con la hora
23
+ plan <run> [--json] [--orchestration RUTA]
24
+ Valida units.md y calcula rondas, conflictos y si compensa
25
+ start <run> --parent RAMA [--remote origin] [--from local|remote] [--integration RAMA]
26
+ Base fresca y rama de integración (sale con 3 si la decisión es tuya)
27
+ worktree <run> <unidad> [--path RUTA] [--no-copy]
28
+ Worktree y rama wt/<run>/<u> desde la integración, con los .env de desarrollo
29
+ check <run> <unidad> [--json]
30
+ Comprueba que lo cambiado está dentro de su write y commiteado
31
+ merge <run> <unidad> [--dry-run]
32
+ Integra la rama de una unidad accepted (ensayo y merge --no-ff; nunca push)
33
+ cleanup <run> [--apply] [--json] [--integration RAMA]
34
+ Inventario de worktrees y ramas del run; --apply borra lo integrado y limpio
35
+
36
+ Estados de unidad: ${ledger.UNIT_STATUS.join(', ')}.`;
37
+
38
+ // Subcomandos de otros módulos de bin/run/: se cargan al usarlos.
39
+ const EXTERNAL = {
40
+ plan: './run/plan',
41
+ start: './run/git',
42
+ worktree: './run/git',
43
+ check: './run/git',
44
+ merge: './run/git',
45
+ cleanup: './run/cleanup',
46
+ };
47
+
48
+ /** El run indicado o, sin id, el único con status active o closing. */
49
+ function resolveRun(root, id) {
50
+ if (id) return checkRunId(id);
51
+ const open = ledger.listRuns(root).filter((name) => {
52
+ try {
53
+ return ['active', 'closing'].includes(ledger.readRun(root, name).meta.status);
54
+ } catch (error) {
55
+ if (error instanceof RunError) return false;
56
+ throw error;
57
+ }
58
+ });
59
+ if (open.length === 1) return open[0];
60
+ if (open.length === 0) throw new RunError('no hay ningún run activo: indica cuál (omk run list)');
61
+ throw new RunError(`hay varios runs activos (${open.join(', ')}): indica cuál`);
62
+ }
63
+
64
+ function pairs(items) {
65
+ const fields = {};
66
+ for (const item of items) {
67
+ const eq = item.indexOf('=');
68
+ if (eq <= 0) throw new RunError(`se esperaba clave=valor: «${item}»`, 2);
69
+ fields[item.slice(0, eq)] = item.slice(eq + 1);
70
+ }
71
+ if (!Object.keys(fields).length) throw new RunError('falta al menos un clave=valor', 2);
72
+ return fields;
73
+ }
74
+
75
+ function printProblems(problems, where) {
76
+ for (const p of problems) console.error(` ${where}:${p.line}: ${p.message}`);
77
+ }
78
+
79
+ function cmdNew(args, { root }) {
80
+ const { positional, options } = parseArgs(args, { values: ['input', 'autonomy', 'engine', 'integration', 'base'] });
81
+ const id = checkRunId(positional[0]);
82
+ if (positional.length > 1) throw new RunError(`sobra: ${positional.slice(1).join(' ')}`, 2);
83
+ const file = ledger.runFile(root, id);
84
+ if (fs.existsSync(file)) throw new RunError(`el run ${id} ya existe (${file}); para seguirlo: omk run status ${id}`);
85
+ const unitsFile = path.join(runDir(root, id), 'units.md');
86
+ let units = [];
87
+ if (fs.existsSync(unitsFile)) {
88
+ const parsed = parseUnits(fs.readFileSync(unitsFile, 'utf8'));
89
+ if (parsed.problems.length) {
90
+ printProblems(parsed.problems, unitsFile);
91
+ throw new RunError(`units.md tiene ${parsed.problems.length} problema(s) de formato`);
92
+ }
93
+ units = parsed.units.map((u) => ({ id: u.id, round: u.fields.round, role: u.fields.role, agent: u.fields.agent }));
94
+ }
95
+ const meta = {};
96
+ for (const [option, key] of [['input', 'input'], ['autonomy', 'autonomy'], ['engine', 'engine'], ['integration', 'integration'], ['base', 'base_ref']]) {
97
+ if (options[option] !== undefined) meta[key] = options[option];
98
+ }
99
+ const run = ledger.newRun({ id, meta, units });
100
+ ledger.addLog(run, units.length ? `run creado con ${units.length} unidades de units.md` : 'run creado sin units.md');
101
+ ledger.writeRun(root, run);
102
+ console.log(`run ${id} creado: ${path.relative(root, file)} (${units.length} unidades)`);
103
+ return 0;
104
+ }
105
+
106
+ function cmdList(args, { root }) {
107
+ const { positional, options } = parseArgs(args, { flags: ['json'] });
108
+ if (positional.length) throw new RunError(`sobra: ${positional.join(' ')}`, 2);
109
+ const runs = ledger.listRuns(root).map((id) => {
110
+ const run = ledger.readRun(root, id);
111
+ return { id, status: run.meta.status || ledger.EMPTY, cleanup: run.meta.cleanup || ledger.EMPTY, integration: run.meta.integration || ledger.EMPTY, units: run.units.length };
112
+ });
113
+ if (options.json) {
114
+ console.log(JSON.stringify(runs, null, 2));
115
+ return 0;
116
+ }
117
+ if (!runs.length) {
118
+ console.log('no hay runs en .work/runs');
119
+ return 0;
120
+ }
121
+ for (const r of runs) console.log(`${r.id} ${r.status} cleanup ${r.cleanup} ${r.integration} ${r.units} unidades`);
122
+ return 0;
123
+ }
124
+
125
+ function cmdStatus(args, { root }) {
126
+ const { positional, options } = parseArgs(args, { flags: ['json'] });
127
+ if (positional.length > 1) throw new RunError(`sobra: ${positional.slice(1).join(' ')}`, 2);
128
+ const id = resolveRun(root, positional[0]);
129
+ const run = ledger.readRun(root, id);
130
+ if (options.json) {
131
+ const { metaComments, ...data } = run;
132
+ console.log(JSON.stringify(data, null, 2));
133
+ return run.problems.length ? 1 : 0;
134
+ }
135
+ process.stdout.write(ledger.serializeRun(run));
136
+ if (run.problems.length) printProblems(run.problems, ledger.runFile(root, id));
137
+ return run.problems.length ? 1 : 0;
138
+ }
139
+
140
+ function edit(root, id, change) {
141
+ const run = ledger.readRun(root, id);
142
+ if (run.problems.length) {
143
+ printProblems(run.problems, ledger.runFile(root, id));
144
+ throw new RunError('run.md tiene problemas de formato: arréglalo antes de escribir en él');
145
+ }
146
+ const message = change(run);
147
+ ledger.writeRun(root, run);
148
+ if (message) console.log(message);
149
+ return 0;
150
+ }
151
+
152
+ function cmdSet(args, { root }) {
153
+ const { positional, options } = parseArgs(args, { flags: ['force'] });
154
+ const [id, unitId, ...rest] = positional;
155
+ checkRunId(id);
156
+ const fields = pairs(rest);
157
+ return edit(root, id, (run) => {
158
+ const before = run.units.find((u) => u.unit === unitId);
159
+ const from = before ? before.status : null;
160
+ const unit = ledger.setUnit(run, unitId, fields, { force: Boolean(options.force) });
161
+ const summary = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
162
+ ledger.addLog(run, `${unitId} ${fields.status && fields.status !== from ? `${from} → ${unit.status}` : 'actualizada'}${summary ? ` · ${summary}` : ''}${options.force ? ' (forzado)' : ''}`);
163
+ return `${unitId}: ${unit.status}`;
164
+ });
165
+ }
166
+
167
+ function cmdMeta(args, { root }) {
168
+ const { positional } = parseArgs(args);
169
+ const [id, ...rest] = positional;
170
+ checkRunId(id);
171
+ const fields = pairs(rest);
172
+ return edit(root, id, (run) => {
173
+ for (const [key, value] of Object.entries(fields)) ledger.setMeta(run, key, value);
174
+ ledger.addLog(run, `cabecera: ${Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ')}`);
175
+ return `run ${id}: ${Object.keys(fields).join(', ')} actualizado`;
176
+ });
177
+ }
178
+
179
+ function cmdLog(args, { root }) {
180
+ const { positional } = parseArgs(args);
181
+ const [id, ...words] = positional;
182
+ checkRunId(id);
183
+ if (!words.length) throw new RunError('falta el texto: omk run log <run> <texto>', 2);
184
+ return edit(root, id, (run) => {
185
+ ledger.addLog(run, words.join(' '));
186
+ return null;
187
+ });
188
+ }
189
+
190
+ const LOCAL = { new: cmdNew, list: cmdList, status: cmdStatus, set: cmdSet, meta: cmdMeta, log: cmdLog };
191
+
192
+ /** Punto de entrada: devuelve el código de salida (o una promesa de él). */
193
+ function main(args, { cwd = process.cwd() } = {}) {
194
+ const [sub, ...rest] = args;
195
+ if (!sub || sub === 'help' || sub === '-h' || sub === '--help') {
196
+ console.log(HELP);
197
+ return sub ? 0 : 2;
198
+ }
199
+ const ctx = { cwd, root: checkoutRoot(cwd), resolveRun, writeAtomic };
200
+ const handle = (error) => {
201
+ if (!(error instanceof RunError)) throw error;
202
+ console.error(`omk run ${sub}: ${error.message}`);
203
+ return error.code;
204
+ };
205
+ try {
206
+ if (LOCAL[sub]) return LOCAL[sub](rest, ctx);
207
+ if (!EXTERNAL[sub]) throw new RunError(`subcomando desconocido: ${sub}\n${HELP}`, 2);
208
+ let mod;
209
+ try {
210
+ mod = require(EXTERNAL[sub]);
211
+ } catch (error) {
212
+ if (error.code === 'MODULE_NOT_FOUND' && String(error.message).includes(EXTERNAL[sub].slice(2))) {
213
+ throw new RunError(`omk run ${sub} no está disponible en esta versión del kit`, 2);
214
+ }
215
+ throw error;
216
+ }
217
+ const result = mod.run(sub, rest, ctx);
218
+ return result && typeof result.then === 'function' ? result.catch(handle) : result;
219
+ } catch (error) {
220
+ return handle(error);
221
+ }
222
+ }
223
+
224
+ module.exports = { main, resolveRun, HELP };
package/bin/setup.js CHANGED
@@ -7,6 +7,7 @@ const fs = require('node:fs');
7
7
  const os = require('node:os');
8
8
  const path = require('node:path');
9
9
  const readline = require('node:readline');
10
+ const { applyHooks } = require('./hooks');
10
11
  const orcaCli = require('./orca');
11
12
  const { c, sym } = require('./ui');
12
13
 
@@ -20,23 +21,39 @@ const heading = (s) => { out(); out(` ${c.lime('◆')} ${c.bold(s)}`); };
20
21
 
21
22
  /** Separa las opciones propias de omk setup/plugin de las que van a install.sh. */
22
23
  function parseOptions(args) {
23
- const own = { yes: false, dryRun: false, noPlugin: false, noPath: false };
24
+ const own = { yes: false, dryRun: false, noPlugin: false, noPath: false, noHooks: false };
24
25
  const rest = [];
25
26
  for (const a of args) {
26
27
  if (a === '--yes' || a === '-y') own.yes = true;
27
28
  else if (a === '--no-plugin') own.noPlugin = true;
28
29
  else if (a === '--no-path') own.noPath = true;
30
+ else if (a === '--no-hooks') own.noHooks = true;
29
31
  else { if (a === '--dry-run') own.dryRun = true; rest.push(a); }
30
32
  }
31
33
  return { ...own, rest };
32
34
  }
33
35
 
34
- async function ask(question) {
35
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
36
+ // Una aprobación que nadie contesta no deja omk colgado para siempre: el plugin de Orca lo lanza en un
37
+ // terminal que puede no estar a la vista.
38
+ const APPROVAL_TIMEOUT_MS = 10 * 60 * 1000;
39
+
40
+ /** Pregunta de sí o no. Con `timeoutMs`, pasado ese tiempo sin respuesta cuenta como «no» y lo dice. */
41
+ async function ask(question, { timeoutMs = 0, input = process.stdin } = {}) {
42
+ const rl = readline.createInterface({ input, output: process.stdout });
43
+ let timer = null;
36
44
  try {
37
- const answer = await new Promise((resolve) => rl.question(question, resolve));
45
+ const answer = await new Promise((resolve) => {
46
+ rl.question(question, resolve);
47
+ if (timeoutMs > 0) timer = setTimeout(() => resolve(null), timeoutMs);
48
+ });
49
+ if (answer === null) {
50
+ out();
51
+ warn(`Sin respuesta en ${Math.max(1, Math.round(timeoutMs / 60000))} min: no apruebo nada.`);
52
+ return false;
53
+ }
38
54
  return /^(s|si|sí|y|yes)$/i.test(String(answer).trim());
39
55
  } finally {
56
+ clearTimeout(timer);
40
57
  rl.close();
41
58
  }
42
59
  }
@@ -52,7 +69,7 @@ const confirmWith = (yes) => async (grants, data) => {
52
69
  warn('Sin terminal interactivo no puedo preguntarte. Repite con --yes para aprobarlo.');
53
70
  return false;
54
71
  }
55
- return ask(` ${sym.todo} ¿Apruebas este acceso? [s/N] `);
72
+ return ask(` ${sym.todo} ¿Apruebas este acceso? [s/N] `, { timeoutMs: APPROVAL_TIMEOUT_MS });
56
73
  };
57
74
 
58
75
  function listPlugin(orca) {
@@ -191,10 +208,13 @@ function addToWindowsPath(dir) {
191
208
  return r.stdout.trim();
192
209
  }
193
210
 
211
+ /** Dónde queda el ejecutable autónomo instalado (lo usa también la puerta de reparto si no hay node). */
212
+ const installedOmk = () => path.join(binDir(), process.platform === 'win32' ? 'omk.exe' : 'omk');
213
+
194
214
  /** Copia el ejecutable autónomo a binDir() y se asegura de que esa carpeta está en el PATH. */
195
215
  function installSelf({ noPath }) {
196
216
  const dir = binDir();
197
- const target = path.join(dir, process.platform === 'win32' ? 'omk.exe' : 'omk');
217
+ const target = installedOmk();
198
218
  heading('omk en el PATH');
199
219
  if (!orcaCli.samePath(process.execPath, target)) {
200
220
  if (fs.existsSync(target) && !isKitExecutable(target)) {
@@ -229,10 +249,11 @@ function installSelf({ noPath }) {
229
249
  * omk setup: kit global, Orca abierto, plugins encendidos, plugin del kit instalado y su panel
230
250
  * abierto. Devuelve el código de salida.
231
251
  */
232
- async function setup({ kit, args, installer, standalone }) {
252
+ async function setup({ kit, args, installer, standalone, agentsHome }) {
233
253
  const opts = parseOptions(args);
234
254
  const code = await installer(opts.rest);
235
255
  if (code !== 0) return code;
256
+ if (!applyHooks({ kit, agentsHome, dryRun: opts.dryRun, skip: opts.noHooks, omkBinary: standalone ? installedOmk() : null })) return 1;
236
257
  if (standalone && opts.dryRun) {
237
258
  heading('omk en el PATH');
238
259
  detail(`Simulación: copiaría omk a ${binDir()} y comprobaría que está en el PATH.`);
@@ -277,6 +298,58 @@ async function setup({ kit, args, installer, standalone }) {
277
298
  return 0;
278
299
  }
279
300
 
301
+ /**
302
+ * Deja el plugin del kit en la versión de este kit si ya está instalado en Orca (con el mismo flujo
303
+ * de aprobación que setup). Es el paso de plugin de «omk update» y de «omk install». No abre Orca ni
304
+ * instala un plugin que no estaba: eso es de «omk setup». Con `quiet` no dice nada cuando no hay
305
+ * Orca, está cerrado o no hay plugin que actualizar. Devuelve `false` solo si algo falló.
306
+ */
307
+ async function refreshPlugin({ kit, yes, dryRun, quiet = false }) {
308
+ let headed = false;
309
+ const head = () => { if (!headed) heading('Plugin de Orca'); headed = true; };
310
+ const dir = path.join(kit, 'orca-plugin');
311
+ const orca = orcaCli.findOrca();
312
+ if (!orca) {
313
+ if (process.env.OMK_ORCA) { head(); fail(`OMK_ORCA=${process.env.OMK_ORCA} no responde a «orca --version».`); return false; }
314
+ if (!quiet) { head(); detail('No encuentro el CLI de Orca: no hay plugin que actualizar.'); }
315
+ return true;
316
+ }
317
+ const status = orcaCli.runOrca(orca, ['status']);
318
+ const runtime = status.json && status.json.result && status.json.result.runtime;
319
+ if (!runtime || !runtime.reachable) {
320
+ if (!quiet) {
321
+ head();
322
+ warn('Orca está cerrado: su plugin no se ha comprobado.');
323
+ todo('Ábrelo y repite «omk update» (u «omk setup», que lo abre e instala el plugin).');
324
+ }
325
+ return true;
326
+ }
327
+ let installed;
328
+ try {
329
+ installed = listPlugin(orca);
330
+ } catch (e) {
331
+ head();
332
+ fail(e.message);
333
+ return false;
334
+ }
335
+ if (!installed) {
336
+ if (!quiet) {
337
+ head();
338
+ detail('El plugin del kit no está instalado en Orca.');
339
+ todo('Para instalarlo y abrir su panel: omk setup');
340
+ }
341
+ return true;
342
+ }
343
+ head();
344
+ const need = (orcaCli.readManifest(dir).engines || {}).orca;
345
+ if (!orcaCli.satisfies(orca.version, need)) {
346
+ warn(`Orca ${orca.version}: el plugin de este kit necesita ${need}. Actualiza Orca y repite «omk update».`);
347
+ return true;
348
+ }
349
+ const key = await ensurePlugin(orca, kit, { yes, dryRun });
350
+ return dryRun || key !== null;
351
+ }
352
+
280
353
  /** omk plugin <install|status|uninstall>. Devuelve el código de salida. */
281
354
  async function plugin({ kit, args }) {
282
355
  const [sub = 'status', ...rest] = args;
@@ -323,4 +396,4 @@ async function pauseIfAsked(code) {
323
396
  return code;
324
397
  }
325
398
 
326
- module.exports = { setup, plugin, pauseIfAsked, parseOptions, binDir };
399
+ module.exports = { setup, plugin, refreshPlugin, pauseIfAsked, parseOptions, binDir, installedOmk, ask };
package/bin/sync.js ADDED
@@ -0,0 +1,222 @@
1
+ // Pone al día un fichero de proyecto generado desde una plantilla del kit (ORCHESTRATION.md, STACK.md)
2
+ // con las secciones y los campos que la plantilla tiene y el fichero no. Solo añade: nada de lo escrito
3
+ // en el proyecto se cambia, se mueve ni se borra. Lo usa «omk update».
4
+ // Al final del fichero deja un sello con los apartados de la plantilla que ya ha ofrecido: así, lo que
5
+ // el proyecto borre a propósito no vuelve en la siguiente actualización y solo entra lo que la
6
+ // plantilla estrena.
7
+ 'use strict';
8
+
9
+ const crypto = require('node:crypto');
10
+ const fs = require('node:fs');
11
+
12
+ const HEADING = /^##\s+(.+?)\s*$/;
13
+ const FENCE = /^\s*(```|~~~)/;
14
+ // Un campo: una viñeta de primer nivel, con el guion de la plantilla o con «*» o «+».
15
+ const ITEM = /^[-*+] \S/;
16
+ const LABEL_MAX = 80;
17
+ const STAMP = /^<!-- omk:plantilla((?: [0-9a-f]{6})*) .*-->$/;
18
+ const STAMP_NOTE = 'apartados de la plantilla del kit ya ofrecidos: lo que borres no vuelve con «omk update»';
19
+
20
+ /** Texto comparable: sin comentarios, paréntesis, formato, tildes ni signos. */
21
+ const norm = (text) => text
22
+ .replace(/<!--.*?-->/g, ' ')
23
+ .replace(/\([^)]*\)/g, ' ')
24
+ .replace(/[`*_]/g, '')
25
+ .normalize('NFD')
26
+ .replace(/\p{M}/gu, '')
27
+ .toLowerCase()
28
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
29
+ .trim();
30
+
31
+ /** Identificador corto y estable de un apartado de la plantilla, para el sello. */
32
+ const idOf = (section, field = '') => crypto.createHash('sha256').update(`${section}\n${field}`).digest('hex').slice(0, 6);
33
+
34
+ /** «3. Entorno de worktree» -> su número y su nombre comparable; lo que sigue a «:» es un valor. */
35
+ function sectionId(title) {
36
+ const m = /^(\d+)[.)]?\s*(.*)$/.exec(title);
37
+ return { number: m ? m[1] : null, name: norm((m ? m[2] : title).split(':')[0]) };
38
+ }
39
+
40
+ /** La etiqueta de un campo «- Etiqueta (aclaración): valor»; sin «:», la línea entera. */
41
+ function labelOf(line) {
42
+ const text = line.slice(2).replace(/<!--.*?-->/g, ' ').replace(/\([^)]*\)/g, ' ');
43
+ const colon = text.indexOf(':');
44
+ return norm(colon === -1 ? text : text.slice(0, colon)).slice(0, LABEL_MAX);
45
+ }
46
+
47
+ /** Lo que se enseña de un campo añadido: su etiqueta como está en la plantilla, sin la aclaración. */
48
+ function labelText(line) {
49
+ const text = line.slice(2).replace(/<!--.*?-->/g, ' ').replace(/\([^)]*\)/g, ' ');
50
+ const colon = text.indexOf(':');
51
+ return (colon === -1 ? text : text.slice(0, colon)).replace(/\s+/g, ' ').trim().slice(0, LABEL_MAX);
52
+ }
53
+
54
+ /** La misma etiqueta, o una que empieza igual con dos palabras o más (alguien la acortó o la alargó). */
55
+ function sameLabel(a, b) {
56
+ if (a === '' || b === '') return false;
57
+ if (a === b) return true;
58
+ const [short, long] = a.length < b.length ? [a, b] : [b, a];
59
+ return short.split(' ').length >= 2 && long.startsWith(`${short} `);
60
+ }
61
+
62
+ /** Las líneas en secciones «## …»; la primera (sin `heading`) es lo que va antes de todas. */
63
+ function parse(lines) {
64
+ const sections = [];
65
+ let current = { heading: null, number: null, name: '', lines: [] };
66
+ let fenced = false;
67
+ for (const line of lines) {
68
+ if (FENCE.test(line)) fenced = !fenced;
69
+ const m = fenced ? null : HEADING.exec(line);
70
+ if (m) {
71
+ sections.push(current);
72
+ current = { heading: line, ...sectionId(m[1]), lines: [] };
73
+ } else current.lines.push(line);
74
+ }
75
+ sections.push(current);
76
+ return sections;
77
+ }
78
+
79
+ /** Separa las líneas en blanco del final. */
80
+ function splitTail(lines) {
81
+ let end = lines.length;
82
+ while (end > 0 && lines[end - 1].trim() === '') end -= 1;
83
+ return { body: lines.slice(0, end), tail: lines.slice(end) };
84
+ }
85
+
86
+ /** Los campos de una sección: cada viñeta de primer nivel con lo que cuelga de ella. El primero es lo de antes. */
87
+ function blocksOf(lines) {
88
+ const blocks = [{ key: '', lines: [] }];
89
+ let fenced = false;
90
+ for (const line of lines) {
91
+ const fence = FENCE.test(line);
92
+ const key = !fenced && !fence && ITEM.test(line) ? labelOf(line) : '';
93
+ if (fence) fenced = !fenced;
94
+ if (key) blocks.push({ key, lines: [line] });
95
+ else blocks[blocks.length - 1].lines.push(line);
96
+ }
97
+ return blocks;
98
+ }
99
+
100
+ /**
101
+ * Añade a la sección del proyecto los campos de la plantilla que le faltan y que `wants(id)` deja
102
+ * pasar, cada uno tras su vecino. Apunta en `known` todos los campos de la plantilla.
103
+ */
104
+ function mergeFields(template, project, { added, known, wants }) {
105
+ const { body, tail } = splitTail(project.lines);
106
+ const wanted = blocksOf(splitTail(template.lines).body);
107
+ const have = blocksOf(body);
108
+ const indexOf = (key) => have.findIndex((block) => sameLabel(block.key, key));
109
+ wanted.forEach((block, i) => {
110
+ if (i === 0) return;
111
+ const id = idOf(template.name, block.key);
112
+ known.add(id);
113
+ if (indexOf(block.key) !== -1 || !wants(id)) return;
114
+ let at = 1;
115
+ for (let j = i - 1; j >= 1; j -= 1) {
116
+ const anchor = indexOf(wanted[j].key);
117
+ if (anchor !== -1) { at = anchor + 1; break; }
118
+ }
119
+ have.splice(at, 0, { key: block.key, lines: [...block.lines] });
120
+ added.push(`${project.heading.replace(/^##\s+/, '§')} · «${labelText(block.lines[0])}»`);
121
+ });
122
+ project.lines = [...have.flatMap((block) => block.lines), ...tail];
123
+ }
124
+
125
+ /** Qué sección del proyecto corresponde a cada una de la plantilla: por nombre y, si no, por número. */
126
+ function matchSections(template, project) {
127
+ const match = new Map();
128
+ const taken = new Set();
129
+ const pair = (same) => template.forEach((section, ti) => {
130
+ if (ti === 0 || match.has(ti)) return;
131
+ const pi = project.findIndex((candidate, i) => i > 0 && !taken.has(i) && same(section, candidate));
132
+ if (pi !== -1) { match.set(ti, pi); taken.add(pi); }
133
+ });
134
+ pair((a, b) => sameLabel(a.name, b.name));
135
+ pair((a, b) => a.number !== null && a.number === b.number);
136
+ return match;
137
+ }
138
+
139
+ /**
140
+ * El fichero del proyecto con lo que la plantilla tiene de más y su sello al día.
141
+ *
142
+ * - Con sello: entra solo lo que la plantilla estrena desde entonces. Lo que el sello ya conocía y
143
+ * el fichero no tiene se borró a propósito y no vuelve.
144
+ * - Sin sello (primera vez): con `firstRun: 'add'` entra todo lo que falte; con `'stamp'` no entra
145
+ * nada y solo se sella (para un fichero del que se pide borrar lo que no aplique, como STACK.md).
146
+ *
147
+ * Devuelve `text` (con los finales de línea del proyecto), `added` (lo añadido) y `changed`.
148
+ */
149
+ function syncTemplate(templateText, projectText, { firstRun = 'add' } = {}) {
150
+ const lines = projectText.split(/\r?\n/);
151
+ const endsWithNewline = /\n$/.test(projectText);
152
+ if (endsWithNewline) lines.pop();
153
+ // El sello es la última línea con contenido; lo demás es el documento.
154
+ const { body: content } = splitTail(lines);
155
+ const stamped = content.length > 0 ? STAMP.exec(content[content.length - 1]) : null;
156
+ const document = stamped ? splitTail(content.slice(0, -1)).body : content;
157
+ const offered = stamped ? new Set(stamped[1].trim().split(' ').filter(Boolean)) : null;
158
+ const wants = (id) => (offered ? !offered.has(id) : firstRun === 'add');
159
+
160
+ const template = parse(templateText.split(/\r?\n/));
161
+ const project = parse(document);
162
+ const match = matchSections(template, project);
163
+ const added = [];
164
+ const known = new Set();
165
+ // Secciones nuevas: cada una va detrás de la sección del proyecto que la precede en la plantilla.
166
+ const inserts = new Map();
167
+ let anchor = 0;
168
+ template.forEach((section, ti) => {
169
+ if (ti === 0) return;
170
+ const id = idOf(section.name);
171
+ known.add(id);
172
+ const pi = match.get(ti);
173
+ if (pi !== undefined) {
174
+ mergeFields(section, project[pi], { added, known, wants });
175
+ anchor = pi;
176
+ return;
177
+ }
178
+ // Sus campos también quedan ofrecidos: si la sección entra ahora y luego se borra uno, no vuelve.
179
+ for (const block of blocksOf(section.lines).slice(1)) known.add(idOf(section.name, block.key));
180
+ if (!wants(id)) return;
181
+ inserts.set(anchor, [...(inserts.get(anchor) || []), section]);
182
+ added.push(`sección «${section.heading.replace(/^##\s+/, '')}»`);
183
+ });
184
+
185
+ const out = [];
186
+ project.forEach((section, pi) => {
187
+ if (section.heading !== null) out.push(section.heading);
188
+ out.push(...section.lines);
189
+ for (const extra of inserts.get(pi) || []) {
190
+ if (out.length > 0 && out[out.length - 1].trim() !== '') out.push('');
191
+ out.push(extra.heading, ...splitTail(extra.lines).body, '');
192
+ }
193
+ });
194
+ const stamp = `<!-- omk:plantilla ${[...known].sort().join(' ')} · ${STAMP_NOTE} -->`;
195
+ const eol = projectText.includes('\r\n') ? '\r\n' : '\n';
196
+ const text = [...splitTail(out).body, '', stamp].join(eol) + (endsWithNewline ? eol : '');
197
+ return { text, added, changed: text !== projectText };
198
+ }
199
+
200
+ /**
201
+ * Pone al día `file` con `templateFile`. Devuelve `{ added, changed }`. Antes de escribir llama a
202
+ * `backup(file)`; la escritura es atómica. Con `dryRun` no escribe nada.
203
+ */
204
+ function syncFile(templateFile, file, { dryRun = false, backup = null, firstRun = 'add' } = {}) {
205
+ if (!fs.lstatSync(file).isFile()) throw new Error(`${file} no es un fichero normal (¿un enlace?): no lo toco`);
206
+ const current = fs.readFileSync(file, 'utf8');
207
+ const { text, added, changed } = syncTemplate(fs.readFileSync(templateFile, 'utf8'), current, { firstRun });
208
+ if (!changed || dryRun) return { added, changed };
209
+ if (backup) backup(file);
210
+ const tmp = `${file}.omk-${process.pid}.tmp`;
211
+ // «wx»: si ya hay algo con ese nombre (también un enlace), falla en vez de escribir a través de él.
212
+ fs.writeFileSync(tmp, text, { flag: 'wx' });
213
+ try {
214
+ fs.renameSync(tmp, file);
215
+ } catch (e) {
216
+ fs.rmSync(tmp, { force: true });
217
+ throw e;
218
+ }
219
+ return { added, changed };
220
+ }
221
+
222
+ module.exports = { syncTemplate, syncFile };
package/bin/ui.js CHANGED
@@ -3,6 +3,10 @@
3
3
  'use strict';
4
4
 
5
5
  const readline = require('node:readline');
6
+ const { isTransientCopy } = require('./fetch');
7
+
8
+ // Cómo se llama a omk desde donde corre: con npx no hay un «omk» en el PATH.
9
+ const CLI = isTransientCopy(__dirname) ? 'npx orca-multiagent-kit' : 'omk';
6
10
 
7
11
  const tty = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
8
12
  const truecolor = /truecolor|24bit/i.test(process.env.COLORTERM || '');
@@ -70,12 +74,12 @@ function footer(kind, stamp, dry, todos, infos, started) {
70
74
  if (kind === 'restore') { out(` ${sym.ok} ${c.bold('Restaurado')} ${c.grey('en ' + secs + ' s')}`); out(); return; }
71
75
  out(` ${sym.ok} ${c.bold(todos.length ? 'Hecho, con ' + todos.length + ' pendiente' + (todos.length > 1 ? 's' : '') : 'Hecho')} ${c.grey('en ' + secs + ' s')}`);
72
76
  if (kind === 'global') {
73
- rows.push(['comprobar', 'omk verify']);
74
- rows.push(['proyectos', 'omk init ' + c.grey('(dentro de cada proyecto)')]);
77
+ rows.push(['comprobar', `${CLI} verify`]);
78
+ rows.push(['proyectos', `${CLI} init ` + c.grey('(dentro de cada proyecto)')]);
75
79
  } else {
76
80
  rows.push(['siguiente', 'en el agente: «inicializa el proyecto»']);
77
81
  }
78
- if (stamp) rows.push(['deshacer', 'omk restore ' + stamp]);
82
+ if (stamp) rows.push(['deshacer', `${CLI} restore ${stamp}`]);
79
83
  for (const [k, v] of rows) out(` ${c.grey(k.padEnd(10))} ${c.lime(v)}`);
80
84
  out();
81
85
  }
@@ -150,7 +154,7 @@ function render(child) {
150
154
  case 'result':
151
155
  out();
152
156
  if (checks.fail === 0) out(` ${sym.ok} ${c.bold('Todo correcto')} ${c.grey(checks.ok + ' comprobaciones')}`);
153
- else out(` ${sym.fail} ${c.bold(c.red(checks.fail + (checks.fail > 1 ? ' fallos' : ' fallo')))} ${c.grey('repáralos con')} ${c.lime('omk install')}`);
157
+ else out(` ${sym.fail} ${c.bold(c.red(checks.fail + (checks.fail > 1 ? ' fallos' : ' fallo')))} ${c.grey('repáralos con')} ${c.lime(`${CLI} install`)}`);
154
158
  out();
155
159
  break;
156
160
  case 'footer': await endPhase(); footer(f[0], f[1], f[2], todos, infos, started); break;