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.
Files changed (110) hide show
  1. package/AI_INSTALL.md +4 -3
  2. package/CHANGELOG.md +70 -1
  3. package/GUIA.html +11 -9
  4. package/README.md +23 -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 +134 -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/team.js +353 -0
  21. package/bin/ui.js +8 -4
  22. package/bin/update.js +169 -0
  23. package/core/AGENTS.md +7 -7
  24. package/docs/EJECUTABLE.md +5 -4
  25. package/docs/MANUAL.md +16 -3
  26. package/docs/ORQUESTADOR.md +59 -1
  27. package/docs/PLUGIN-ORCA.md +131 -24
  28. package/hooks/orca-gate.cjs +402 -0
  29. package/install.sh +26 -13
  30. package/orca-plugin/README.md +7 -1
  31. package/orca-plugin/assets/logos/README.md +10 -0
  32. package/orca-plugin/assets/logos/agent.png +0 -0
  33. package/orca-plugin/assets/logos/aider.png +0 -0
  34. package/orca-plugin/assets/logos/amp.png +0 -0
  35. package/orca-plugin/assets/logos/antigravity.png +0 -0
  36. package/orca-plugin/assets/logos/claude.png +0 -0
  37. package/orca-plugin/assets/logos/cline.png +0 -0
  38. package/orca-plugin/assets/logos/codex.png +0 -0
  39. package/orca-plugin/assets/logos/copilot.png +0 -0
  40. package/orca-plugin/assets/logos/cursor.png +0 -0
  41. package/orca-plugin/assets/logos/devin.png +0 -0
  42. package/orca-plugin/assets/logos/droid.png +0 -0
  43. package/orca-plugin/assets/logos/gemini.png +0 -0
  44. package/orca-plugin/assets/logos/goose.png +0 -0
  45. package/orca-plugin/assets/logos/grok.png +0 -0
  46. package/orca-plugin/assets/logos/kimi.png +0 -0
  47. package/orca-plugin/assets/logos/kiro.png +0 -0
  48. package/orca-plugin/assets/logos/opencode.png +0 -0
  49. package/orca-plugin/assets/logos/qwen-code.png +0 -0
  50. package/orca-plugin/orca-plugin.json +25 -7
  51. package/orca-plugin/src/icons.test.ts +14 -0
  52. package/orca-plugin/src/icons.ts +30 -0
  53. package/orca-plugin/src/kit.test.ts +491 -22
  54. package/orca-plugin/src/kit.ts +687 -37
  55. package/orca-plugin/src/models.test.ts +28 -0
  56. package/orca-plugin/src/models.ts +29 -0
  57. package/orca-plugin/src/node.d.ts +40 -0
  58. package/orca-plugin/src/panel-state.ts +36 -0
  59. package/orca-plugin/src/panel.check.ts +71 -0
  60. package/orca-plugin/src/panel.test.tsx +296 -33
  61. package/orca-plugin/src/panel.tsx +501 -81
  62. package/orca-plugin/src/plan-card.test.ts +99 -0
  63. package/orca-plugin/src/plan-card.ts +107 -0
  64. package/orca-plugin/src/protocol.ts +205 -5
  65. package/orca-plugin/src/tabs/autonomy.tsx +72 -0
  66. package/orca-plugin/src/tabs/history.test.tsx +79 -0
  67. package/orca-plugin/src/tabs/history.tsx +119 -0
  68. package/orca-plugin/src/tabs/notices.test.tsx +184 -0
  69. package/orca-plugin/src/tabs/notices.tsx +274 -0
  70. package/orca-plugin/src/tabs/worktrees.test.tsx +131 -0
  71. package/orca-plugin/src/tabs/worktrees.tsx +138 -0
  72. package/orca-plugin/src/ui/action-card.tsx +112 -0
  73. package/orca-plugin/src/ui/agent-icon.tsx +13 -0
  74. package/orca-plugin/src/worker/actions.test.ts +288 -0
  75. package/orca-plugin/src/worker/actions.ts +292 -0
  76. package/orca-plugin/src/worker/context.test.ts +32 -0
  77. package/orca-plugin/src/worker/context.ts +95 -0
  78. package/orca-plugin/src/worker/history.test.ts +149 -0
  79. package/orca-plugin/src/worker/history.ts +181 -0
  80. package/orca-plugin/src/worker/notices.test.ts +356 -0
  81. package/orca-plugin/src/worker/notices.ts +288 -0
  82. package/orca-plugin/src/worker/system.test.ts +58 -0
  83. package/orca-plugin/src/worker/system.ts +122 -0
  84. package/orca-plugin/src/worker/worktrees.test.ts +177 -0
  85. package/orca-plugin/src/worker/worktrees.ts +188 -0
  86. package/orca-plugin/src/worker.test.ts +285 -24
  87. package/orca-plugin/src/worker.ts +344 -64
  88. package/output-styles/csr-minimal.md +1 -0
  89. package/package.json +3 -3
  90. package/rules/50-done-gate.md +1 -1
  91. package/rules/95-multi-agent.md +13 -3
  92. package/skills/kit-init/SKILL.md +16 -4
  93. package/skills/orca/SKILL.md +28 -5
  94. package/skills/orca/references/adapters/artifact.md +2 -0
  95. package/skills/orca/references/adapters/chat.md +2 -0
  96. package/skills/orca/references/adapters/native-plan.md +6 -0
  97. package/skills/orca/references/adapters/plan-file.md +2 -0
  98. package/skills/orca/references/engine-manual.md +7 -5
  99. package/skills/orca/references/engine-orca.md +1 -0
  100. package/skills/orca/references/engine-subagents.md +4 -4
  101. package/skills/orca/references/integrate.md +14 -2
  102. package/skills/orca/references/ledger.md +1 -1
  103. package/skills/orca/references/olimpo.md +2 -1
  104. package/skills/orca/references/plan-card.md +45 -0
  105. package/skills/orca/references/plan.md +2 -1
  106. package/skills/orca/references/units.md +1 -1
  107. package/skills/orca/references/worker-contract.md +2 -2
  108. package/templates/AGENTS.md +2 -2
  109. package/templates/CLAUDE.md +1 -1
  110. package/templates/claude-settings.json +25 -0
@@ -0,0 +1,328 @@
1
+ // omk run plan: valida units.md y calcula rondas, conflictos y si compensa repartir. No escribe nada.
2
+ // Reglas: skills/orca/references/units.md (§Grafo y rondas, §Salida) y rules/95-multi-agent.md (§Cuenta rápida).
3
+ 'use strict';
4
+
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { RunError, parseArgs, runDir } = require('./util');
8
+ const { parseUnits } = require('./units');
9
+
10
+ const WILDCARD = /[*?[{]/;
11
+ const SIZE_MINUTES = { S: 15, M: 40, L: 90 };
12
+ const DEFAULT_MINUTES = SIZE_MINUTES.M;
13
+ const COST_PER_UNIT = 5;
14
+ const COST_PER_ROUND = 5;
15
+ const COST_PER_SHARED = 10;
16
+ const CROSS_ROLES = new Set(['ariadna', 'perséfone', 'persefone']);
17
+
18
+ const segmentsOf = (pattern) => pattern.replace(/^(\.\/)+/, '').split('/').filter(Boolean);
19
+ // «src/» cubre toda la carpeta (glob.js lo lee como «src/**»): cuenta como comodín.
20
+ const hasWildcard = (pattern) => WILDCARD.test(pattern) || pattern.endsWith('/');
21
+
22
+ /** Segmentos literales antes del primero con comodín (todos, si el patrón no tiene comodín). */
23
+ function literalPrefix(pattern) {
24
+ const out = [];
25
+ for (const segment of segmentsOf(pattern)) {
26
+ if (hasWildcard(segment)) break;
27
+ out.push(segment);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ /** Glob ancho: con comodín y con menos de 2 segmentos literales delante (`**`, `*.js`, `src/**`). */
33
+ function isBroadGlob(pattern) {
34
+ return hasWildcard(pattern) && literalPrefix(pattern).length < 2;
35
+ }
36
+
37
+ const startsWithSegments = (long, short) => short.every((segment, i) => long[i] === segment);
38
+
39
+ /** Solape conservador, sin matcher: dos literales, iguales; con algún glob, un prefijo literal contiene al otro. */
40
+ function overlaps(a, b) {
41
+ if (!hasWildcard(a) && !hasWildcard(b)) return segmentsOf(a).join('/') === segmentsOf(b).join('/');
42
+ const pa = literalPrefix(a);
43
+ const pb = literalPrefix(b);
44
+ return startsWithSegments(pa, pb) || startsWithSegments(pb, pa);
45
+ }
46
+
47
+ /** Rutas o globs del bloque de código bajo «## 2. Shared» de ORCHESTRATION.md. */
48
+ function parseShared(text) {
49
+ const shared = [];
50
+ let inSection = false;
51
+ let inFence = false;
52
+ for (const line of String(text).replace(/^\uFEFF/, '').split(/\r?\n/)) {
53
+ if (!inFence && /^##\s+2\.\s*Shared/i.test(line)) { inSection = true; continue; }
54
+ if (!inSection) continue;
55
+ if (/^\s*```/.test(line)) {
56
+ if (inFence) break;
57
+ inFence = true;
58
+ continue;
59
+ }
60
+ if (!inFence) {
61
+ if (/^##\s/.test(line)) break;
62
+ continue;
63
+ }
64
+ const entry = line.trim();
65
+ if (entry && !entry.startsWith('#')) shared.push(entry);
66
+ }
67
+ return shared;
68
+ }
69
+
70
+ /** Minutos de un `budget` (`45m`, `1h`, `1h30m`) o null si no es válido. */
71
+ function parseBudget(value) {
72
+ const match = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(String(value).trim());
73
+ if (!match || (!match[1] && !match[2])) return null;
74
+ return Number(match[1] || 0) * 60 + Number(match[2] || 0);
75
+ }
76
+
77
+ function findCycles(units, graph) {
78
+ const cycles = [];
79
+ const seen = new Set();
80
+ const state = new Map();
81
+ const stack = [];
82
+ const visit = (id) => {
83
+ state.set(id, 1);
84
+ stack.push(id);
85
+ for (const next of graph.get(id) || []) {
86
+ if (state.get(next) === 1) {
87
+ const cycle = stack.slice(stack.indexOf(next));
88
+ const key = [...cycle].sort().join(',');
89
+ if (!seen.has(key)) { seen.add(key); cycles.push([...cycle, next]); }
90
+ } else if (!state.get(next)) {
91
+ visit(next);
92
+ }
93
+ }
94
+ stack.pop();
95
+ state.set(id, 2);
96
+ };
97
+ for (const unit of units) if (!state.get(unit.id)) visit(unit.id);
98
+ return cycles;
99
+ }
100
+
101
+ /** Validación por unidad: devuelve los errores {unit, line, message}. */
102
+ function validate(units, shared) {
103
+ const errors = [];
104
+ const fail = (unit, message) => errors.push({ unit: unit.id, line: unit.line, message: `${unit.id}: ${message}` });
105
+ const ids = new Set(units.map((u) => u.id));
106
+ const graph = new Map();
107
+ for (const unit of units) {
108
+ const f = unit.fields;
109
+ if (!Array.isArray(f.write)) fail(unit, 'falta el campo write (una unidad de solo lectura lleva «write: []»)');
110
+ if (!f.acceptance || !f.acceptance.length) fail(unit, 'falta acceptance');
111
+ if (Array.isArray(f.write) && f.write.length && (!f.verify || !f.verify.length)) fail(unit, 'write no vacío sin verify');
112
+ for (const dep of f.depends_on || []) {
113
+ if (!ids.has(dep)) fail(unit, `depends_on a una unidad que no existe: ${dep}`);
114
+ }
115
+ graph.set(unit.id, (f.depends_on || []).filter((dep) => ids.has(dep)));
116
+ for (const pattern of f.write || []) {
117
+ if (/^([\\/]|[A-Za-z]:)/.test(pattern)) fail(unit, `ruta absoluta en write: ${pattern}`);
118
+ else if (pattern.split(/[\\/]/).includes('..')) fail(unit, `ruta con «..» en write: ${pattern}`);
119
+ else if (isBroadGlob(pattern)) fail(unit, `glob demasiado ancho en write: ${pattern} (usa uno estrecho, p. ej. src/features/x/**)`);
120
+ }
121
+ if (f.round === 0) {
122
+ const late = (f.depends_on || []).filter((dep) => units.some((u) => u.id === dep && u.fields.round !== 0));
123
+ if (late.length) fail(unit, `es de ronda 0 (coordinador) y depende de ${late.join(', ')}, que no lo es`);
124
+ } else {
125
+ const declared = f.shared || [];
126
+ for (const pattern of shared) {
127
+ const touching = (f.write || []).find((w) => overlaps(w, pattern));
128
+ if (touching && !declared.includes(pattern) && !declared.includes(touching)) {
129
+ fail(unit, `write solapa el fichero shared «${pattern}» y no lo declara en shared`);
130
+ }
131
+ }
132
+ }
133
+ }
134
+ for (const cycle of findCycles(units, graph)) {
135
+ errors.push({ unit: cycle[0], line: units.find((u) => u.id === cycle[0]).line, message: `ciclo en depends_on: ${cycle.join(' → ')}` });
136
+ }
137
+ return errors;
138
+ }
139
+
140
+ /** Rondas: 1 + la mayor de sus depends_on, y el empuje por solape dentro de la misma ronda. */
141
+ function computeRounds(units) {
142
+ const byId = new Map(units.map((u) => [u.id, u]));
143
+ const minRound = new Map();
144
+ const reasons = new Map(units.map((u) => [u.id, []]));
145
+ const filesOf = (unit) => [...(unit.fields.write || []), ...(unit.fields.shared || [])];
146
+
147
+ const compute = () => {
148
+ const rounds = new Map();
149
+ const visiting = new Set();
150
+ const roundOf = (id) => {
151
+ if (rounds.has(id)) return rounds.get(id);
152
+ const unit = byId.get(id);
153
+ if (unit.fields.round === 0) { rounds.set(id, 0); return 0; }
154
+ if (visiting.has(id)) return 0; // ciclo: ya se ha reportado como error
155
+ visiting.add(id);
156
+ const deps = (unit.fields.depends_on || []).filter((dep) => byId.has(dep)).map(roundOf);
157
+ visiting.delete(id);
158
+ const value = Math.max(1 + Math.max(0, ...deps), minRound.get(id) || 1);
159
+ rounds.set(id, value);
160
+ return value;
161
+ };
162
+ for (const unit of units) roundOf(unit.id);
163
+ return rounds;
164
+ };
165
+
166
+ let rounds = compute();
167
+ for (let guard = 0; guard < units.length * units.length + 10; guard += 1) {
168
+ let pushed = false;
169
+ const top = Math.max(0, ...rounds.values());
170
+ for (let r = 1; r <= top && !pushed; r += 1) {
171
+ const seen = [];
172
+ for (const unit of units) {
173
+ if (rounds.get(unit.id) !== r) continue;
174
+ const clash = [];
175
+ for (const mine of filesOf(unit)) {
176
+ if (seen.some((other) => filesOf(other).some((theirs) => overlaps(mine, theirs)))) clash.push(mine);
177
+ }
178
+ if (clash.length) {
179
+ minRound.set(unit.id, r + 1);
180
+ reasons.get(unit.id).push(`solape: ${clash.join(', ')}`);
181
+ pushed = true;
182
+ break;
183
+ }
184
+ seen.push(unit);
185
+ }
186
+ }
187
+ if (!pushed) break;
188
+ rounds = compute();
189
+ }
190
+ return { rounds, reasons };
191
+ }
192
+
193
+ function minutesOf(unit, warnings) {
194
+ const f = unit.fields;
195
+ if (f.budget) {
196
+ const minutes = parseBudget(f.budget);
197
+ if (minutes !== null) return minutes;
198
+ warnings.push({ unit: unit.id, line: unit.line, message: `${unit.id}: budget no válido «${f.budget}» (45m, 1h, 1h30m): se usa el de su talla` });
199
+ }
200
+ return SIZE_MINUTES[String(f.size || '').toUpperCase()] || DEFAULT_MINUTES;
201
+ }
202
+
203
+ /** La cuenta «¿compensa?» de 95-multi-agent.md §Cuenta rápida. */
204
+ function computeWorth(rows) {
205
+ const work = rows.filter((row) => row.round >= 1);
206
+ const rounds = [...new Set(work.map((row) => row.round))];
207
+ let saving = 0;
208
+ let parallel = false;
209
+ let sharedAcross = null;
210
+ for (const round of rounds) {
211
+ const group = work.filter((row) => row.round === round);
212
+ saving += group.reduce((sum, row) => sum + row.minutes, 0) - Math.max(...group.map((row) => row.minutes));
213
+ if (group.length >= 2) {
214
+ parallel = true;
215
+ const big = group.find((row) => String(row.size).toUpperCase() === 'L');
216
+ if (big && !sharedAcross) sharedAcross = big.id;
217
+ }
218
+ }
219
+ const sharedFiles = new Set(work.flatMap((row) => row.shared));
220
+ const cost = COST_PER_UNIT * work.length + COST_PER_ROUND * rounds.length + COST_PER_SHARED * sharedFiles.size;
221
+ let verdict = 'sí';
222
+ let reason;
223
+ if (!parallel) {
224
+ verdict = 'no';
225
+ reason = 'ninguna ronda tiene 2 unidades: no hay nada que paralelizar';
226
+ } else if (sharedAcross) {
227
+ verdict = 'no';
228
+ reason = `divide la unidad L (${sharedAcross}): comparte ronda con otras`;
229
+ } else if (saving < cost) {
230
+ verdict = 'no';
231
+ reason = `el ahorro no cubre el coste: faltan ${cost - saving} min`;
232
+ } else {
233
+ reason = saving === cost ? 'empate: se reparte' : `sobran ${saving - cost} min`;
234
+ }
235
+ return { saving, cost, verdict, reason };
236
+ }
237
+
238
+ /** Todo el cálculo, sin tocar disco: {run, units, rounds, errors, warnings, worth}. */
239
+ function analyze(text, shared = [], run = null) {
240
+ const { units, problems } = parseUnits(text);
241
+ const errors = problems.map((p) => ({ unit: null, line: p.line, message: p.message }));
242
+ const warnings = [];
243
+ if (!units.length) errors.push({ unit: null, line: 0, message: 'units.md no tiene ninguna unidad («### UNIT: U1 — …»)' });
244
+ errors.push(...validate(units, shared));
245
+ const { rounds, reasons } = computeRounds(units);
246
+
247
+ const table = units.map((unit) => {
248
+ const f = unit.fields;
249
+ const write = f.write || [];
250
+ const depends = f.depends_on || [];
251
+ return {
252
+ id: unit.id,
253
+ title: unit.title,
254
+ round: rounds.get(unit.id),
255
+ declaredRound: Number.isInteger(f.round) ? f.round : null,
256
+ role: f.role || null,
257
+ tier: f.tier || null,
258
+ agent: f.agent || null,
259
+ engine: f.engine || null,
260
+ size: f.size || null,
261
+ minutes: minutesOf(unit, warnings),
262
+ write,
263
+ shared: f.shared || [],
264
+ depends_on: depends,
265
+ files: write.length ? String(write.length) : 'lectura',
266
+ depends: depends.length ? depends.join(', ') : '—',
267
+ reasons: reasons.get(unit.id),
268
+ };
269
+ });
270
+
271
+ const warn = (unit, message) => warnings.push({ unit: unit.id, line: units.find((u) => u.id === unit.id).line, message: `${unit.id}: ${message}` });
272
+ for (const row of table) {
273
+ const size = String(row.size || '').toUpperCase();
274
+ const sameRound = table.filter((other) => other.round === row.round).length;
275
+ if (row.declaredRound !== null && row.declaredRound !== row.round) warn(row, `round declarado ${row.declaredRound} ≠ calculado ${row.round} (manda el calculado)`);
276
+ if (size === 'L') warn(row, 'talla L: divídela antes de delegar');
277
+ if (size === 'S' && row.round >= 1 && sameRound > 1) warn(row, 'talla S en una ronda con otras: agrúpala o hazla inline');
278
+ const review = units.find((u) => u.id === row.id).fields.review;
279
+ if ((size === 'L' || CROSS_ROLES.has(String(row.role || '').toLowerCase())) && review !== 'cross') warn(row, 'falta review: cross (talla L o rol Ariadna/Perséfone)');
280
+ }
281
+
282
+ const last = Math.max(0, ...table.map((row) => row.round || 0));
283
+ const roundList = [];
284
+ for (let r = 0; r <= last; r += 1) {
285
+ const ids = table.filter((row) => row.round === r).map((row) => row.id);
286
+ if (ids.length) roundList.push({ round: r, units: ids, parallel: r === 0 ? 'coordinador' : ids.length >= 2 ? 'sí' : '—' });
287
+ }
288
+ return { run, units: table, rounds: roundList, errors, warnings, worth: computeWorth(table) };
289
+ }
290
+
291
+ function renderText(result) {
292
+ const lines = [`run: ${result.run} · unidades: ${result.units.length}`];
293
+ const rows = result.rounds.map((entry) => {
294
+ const notes = entry.units
295
+ .map((id) => ({ id, reasons: result.units.find((u) => u.id === id).reasons }))
296
+ .filter((u) => u.reasons.length)
297
+ .map((u) => `${u.id}: ${u.reasons.join('; ')}`);
298
+ return [String(entry.round), entry.units.join(', '), notes.length ? `${entry.parallel} (${notes.join(' · ')})` : entry.parallel];
299
+ });
300
+ const table = [['round', 'unidades', 'paralelo'], ...rows];
301
+ const widths = [0, 1].map((col) => Math.max(...table.map((row) => row[col].length)));
302
+ for (const row of table) lines.push(`${row[0].padEnd(widths[0])} | ${row[1].padEnd(widths[1])} | ${row[2]}`);
303
+ for (const e of result.errors) lines.push(`RISK: error${e.line ? ` (línea ${e.line})` : ''}: ${e.message}`);
304
+ for (const w of result.warnings) lines.push(`RISK: aviso: ${w.message}`);
305
+ const { worth } = result;
306
+ lines.push(`compensa: ${worth.verdict} — ahorro ${worth.saving} min, coste ${worth.cost} min (${worth.reason})`);
307
+ return lines.join('\n');
308
+ }
309
+
310
+ /** `omk run plan <run> [--json] [--orchestration <ruta>]`. Devuelve el código de salida. */
311
+ function run(sub, args, ctx) {
312
+ const { positional, options } = parseArgs(args, { flags: ['json'], values: ['orchestration'] });
313
+ if (positional.length > 1) throw new RunError(`sobra: ${positional.slice(1).join(' ')}`, 2);
314
+ const id = ctx.resolveRun(ctx.root, positional[0]);
315
+ const unitsFile = path.join(runDir(ctx.root, id), 'units.md');
316
+ if (!fs.existsSync(unitsFile)) throw new RunError(`no existe ${unitsFile}: escribe las unidades antes de planificar`);
317
+
318
+ let shared = [];
319
+ const orchestration = options.orchestration ? path.resolve(ctx.cwd, options.orchestration) : path.join(ctx.root, 'ORCHESTRATION.md');
320
+ if (fs.existsSync(orchestration)) shared = parseShared(fs.readFileSync(orchestration, 'utf8'));
321
+ else if (options.orchestration) throw new RunError(`no existe ${orchestration}`, 2);
322
+
323
+ const result = analyze(fs.readFileSync(unitsFile, 'utf8'), shared, id);
324
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderText(result));
325
+ return result.errors.length ? 1 : 0;
326
+ }
327
+
328
+ module.exports = { run, analyze, overlaps, isBroadGlob, parseShared, parseBudget, renderText };
@@ -0,0 +1,101 @@
1
+ // Lectura de units.md (skills/orca/references/units.md): el contrato entre coordinador y workers.
2
+ // Solo interpreta el formato; las reglas del reparto (globs, rondas, ciclos) las comprueba `omk run plan`.
3
+ 'use strict';
4
+
5
+ const { UNIT_ID } = require('./util');
6
+
7
+ /** Campos con lista entre corchetes (`[a, b]`) o en líneas `- …` debajo. */
8
+ const LIST_FIELDS = new Set(['write', 'read', 'shared', 'depends_on', 'verify', 'out_of_scope', 'acceptance']);
9
+ const KNOWN_FIELDS = new Set([
10
+ 'source', 'goal', 'write', 'read', 'shared', 'depends_on', 'round', 'size', 'role', 'tier', 'agent',
11
+ 'engine', 'acceptance', 'verify', 'out_of_scope', 'notes', 'budget', 'review',
12
+ ]);
13
+
14
+ const HEADER = /^###\s+UNIT:\s*(\S+)\s*(?:[—–-]\s*(.*?))?\s*$/;
15
+ const FIELD = /^- ([a-z_]+):(?:\s+(.*?))?\s*$/;
16
+ const ITEM = /^\s+- (.*?)\s*$/;
17
+ // Comentario al final del valor: dos espacios o más, «#» y un espacio (`tasks.md#US2` no lo es).
18
+ const COMMENT = /\s{2,}#\s.*$/;
19
+
20
+ /** Parte «a, b, {c,d}» por las comas de primer nivel (las de un glob con llaves no cuentan). */
21
+ function splitList(text) {
22
+ const items = [];
23
+ let depth = 0;
24
+ let current = '';
25
+ for (const ch of text) {
26
+ if (ch === '{' || ch === '[' || ch === '(') depth += 1;
27
+ if (ch === '}' || ch === ']' || ch === ')') depth = Math.max(0, depth - 1);
28
+ if (ch === ',' && depth === 0) { items.push(current); current = ''; continue; }
29
+ current += ch;
30
+ }
31
+ items.push(current);
32
+ return items.map((item) => item.trim()).filter(Boolean);
33
+ }
34
+
35
+ function listValue(raw) {
36
+ const text = raw.trim();
37
+ if (text.startsWith('[') && text.endsWith(']')) return splitList(text.slice(1, -1));
38
+ return text ? [text] : [];
39
+ }
40
+
41
+ /**
42
+ * Lee units.md. Devuelve {units, problems}: cada unidad con id, título, línea de su cabecera y sus
43
+ * campos (listas como arrays, `round` como número); `problems` son {line, message} de formato.
44
+ */
45
+ function parseUnits(text) {
46
+ const units = [];
47
+ const problems = [];
48
+ const lines = String(text).replace(/^/, '').split(/\r?\n/);
49
+ let unit = null;
50
+ let listField = null;
51
+ let fence = false;
52
+
53
+ lines.forEach((line, index) => {
54
+ const lineNo = index + 1;
55
+ if (/^\s*```/.test(line)) { fence = !fence; return; }
56
+ if (fence) return;
57
+ const header = HEADER.exec(line);
58
+ if (header) {
59
+ listField = null;
60
+ const [, id, title = ''] = header;
61
+ if (!UNIT_ID.test(id)) problems.push({ line: lineNo, message: `id de unidad no válido: ${id}` });
62
+ if (units.some((u) => u.id === id)) problems.push({ line: lineNo, message: `unidad repetida: ${id}` });
63
+ unit = { id, title, line: lineNo, fields: {} };
64
+ units.push(unit);
65
+ return;
66
+ }
67
+ if (!unit) return;
68
+ if (/^#{1,3}\s/.test(line)) { unit = null; listField = null; return; }
69
+
70
+ const item = listField ? ITEM.exec(line) : null;
71
+ if (item) {
72
+ unit.fields[listField].push(item[1].replace(COMMENT, ''));
73
+ return;
74
+ }
75
+ const field = FIELD.exec(line);
76
+ if (!field) {
77
+ if (line.trim()) listField = null;
78
+ return;
79
+ }
80
+ const [, name, rawValue = ''] = field;
81
+ const value = rawValue.replace(COMMENT, '').trim();
82
+ if (!KNOWN_FIELDS.has(name)) problems.push({ line: lineNo, message: `${unit.id}: campo desconocido «${name}»` });
83
+ if (Object.prototype.hasOwnProperty.call(unit.fields, name)) problems.push({ line: lineNo, message: `${unit.id}: campo repetido «${name}»` });
84
+ if (LIST_FIELDS.has(name)) {
85
+ unit.fields[name] = listValue(value);
86
+ listField = value ? null : name;
87
+ return;
88
+ }
89
+ listField = null;
90
+ if (name === 'round') {
91
+ const round = Number(value);
92
+ if (!Number.isInteger(round) || round < 0) problems.push({ line: lineNo, message: `${unit.id}: round no es un entero ≥0: «${value}»` });
93
+ unit.fields.round = Number.isInteger(round) && round >= 0 ? round : null;
94
+ return;
95
+ }
96
+ unit.fields[name] = value;
97
+ });
98
+ return { units, problems };
99
+ }
100
+
101
+ module.exports = { parseUnits, splitList, LIST_FIELDS, KNOWN_FIELDS };
@@ -0,0 +1,116 @@
1
+ // Piezas comunes de `omk run`: git sin shell, validación de nombres y escritura atómica.
2
+ 'use strict';
3
+
4
+ const { spawnSync } = require('node:child_process');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ /** Error de uso o de estado que el CLI enseña tal cual (sin traza) con su código de salida. */
9
+ class RunError extends Error {
10
+ constructor(message, code = 1) {
11
+ super(message);
12
+ this.name = 'RunError';
13
+ this.code = code;
14
+ }
15
+ }
16
+
17
+ // Ids que acaban en rutas (.work/runs/<run>) y en nombres de rama: solo lo que no puede escapar.
18
+ const RUN_ID = /^[0-9]{8}-[a-z0-9][a-z0-9-]{0,63}$/;
19
+ const UNIT_ID = /^U[0-9]{1,3}[a-z]?$/;
20
+
21
+ function checkRunId(id) {
22
+ if (typeof id !== 'string' || !RUN_ID.test(id)) {
23
+ throw new RunError(`id de run no válido: «${id ?? ''}» (formato AAAAMMDD-nombre, minúsculas, cifras y guiones)`, 2);
24
+ }
25
+ return id;
26
+ }
27
+
28
+ function checkUnitId(id) {
29
+ if (typeof id !== 'string' || !UNIT_ID.test(id)) {
30
+ throw new RunError(`id de unidad no válido: «${id ?? ''}» (formato U<n>, p. ej. U2 o U2r)`, 2);
31
+ }
32
+ return id;
33
+ }
34
+
35
+ /**
36
+ * Ejecuta git con los argumentos en array (nunca por shell). Devuelve {status, stdout, stderr};
37
+ * con `check` lanza RunError si git sale con error.
38
+ */
39
+ function git(args, { cwd, check = true, input } = {}) {
40
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', input, windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
41
+ if (result.error) throw new RunError(`no pude ejecutar git: ${result.error.message}`);
42
+ const out = { status: result.status, stdout: result.stdout || '', stderr: result.stderr || '' };
43
+ if (check && out.status !== 0) {
44
+ throw new RunError(`git ${args.join(' ')} falló (${out.status}): ${out.stderr.trim() || out.stdout.trim()}`);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** Nombre de rama válido para git (git check-ref-format --branch) y que no empieza por «-». */
50
+ function checkBranch(name, cwd) {
51
+ // «@{-1}» y «@» los expande check-ref-format a otra rama: aquí solo valen nombres literales.
52
+ if (typeof name !== 'string' || !name || name === '@' || name.includes('@{') || name.startsWith('-') || /[\s\u0000-\u001f]/.test(name)) {
53
+ throw new RunError(`nombre de rama no válido: «${name ?? ''}»`, 2);
54
+ }
55
+ const res = git(['check-ref-format', '--branch', name], { cwd, check: false });
56
+ if (res.status !== 0) throw new RunError(`nombre de rama no válido: «${name}»`, 2);
57
+ return name;
58
+ }
59
+
60
+ /**
61
+ * Raíz del checkout del coordinador, donde vive .work/runs: la del árbol de trabajo de `cwd`. Con
62
+ * Orca, el coordinador trabaja en su propio workspace (que ya es un worktree), y su run es suyo, no del
63
+ * checkout del que salió. Fuera de un repositorio git, la carpeta dada.
64
+ */
65
+ function checkoutRoot(cwd) {
66
+ const top = git(['rev-parse', '--show-toplevel'], { cwd, check: false });
67
+ return top.status === 0 ? path.resolve(top.stdout.trim()) : path.resolve(cwd);
68
+ }
69
+
70
+ const runsDir = (root) => path.join(root, '.work', 'runs');
71
+ const runDir = (root, id) => path.join(runsDir(root), checkRunId(id));
72
+
73
+ /** Escribe sin dejar un fichero a medias: a un temporal en la misma carpeta y renombrado. */
74
+ function writeAtomic(file, text) {
75
+ fs.mkdirSync(path.dirname(file), { recursive: true });
76
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
77
+ fs.writeFileSync(tmp, text);
78
+ try {
79
+ fs.renameSync(tmp, file);
80
+ } catch (error) {
81
+ fs.rmSync(tmp, { force: true });
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Opciones `--clave valor`, `--clave=valor` y banderas. `flags` son las que no llevan valor.
88
+ * Devuelve {positional, options}; una opción desconocida es un error.
89
+ */
90
+ function parseArgs(args, { flags = [], values = [] } = {}) {
91
+ const positional = [];
92
+ const options = {};
93
+ for (let i = 0; i < args.length; i += 1) {
94
+ const arg = args[i];
95
+ if (arg === '--') { positional.push(...args.slice(i + 1)); break; }
96
+ if (!arg.startsWith('--')) { positional.push(arg); continue; }
97
+ const eq = arg.indexOf('=');
98
+ const name = arg.slice(2, eq === -1 ? undefined : eq);
99
+ if (flags.includes(name)) {
100
+ if (eq !== -1) throw new RunError(`--${name} no lleva valor`, 2);
101
+ options[name] = true;
102
+ } else if (values.includes(name)) {
103
+ const value = eq === -1 ? args[++i] : arg.slice(eq + 1);
104
+ if (value === undefined) throw new RunError(`falta el valor de --${name}`, 2);
105
+ options[name] = value;
106
+ } else {
107
+ throw new RunError(`opción desconocida: --${name}`, 2);
108
+ }
109
+ }
110
+ return { positional, options };
111
+ }
112
+
113
+ /** Hora local HH:MM, como la columna `updated` de run.md. */
114
+ const clock = (date = new Date()) => `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
115
+
116
+ module.exports = { RunError, RUN_ID, UNIT_ID, checkRunId, checkUnitId, checkBranch, git, checkoutRoot, runsDir, runDir, writeAtomic, parseArgs, clock };