orca-multiagent-kit 1.6.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 (71) hide show
  1. package/AI_INSTALL.md +4 -3
  2. package/CHANGELOG.md +41 -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 +127 -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
@@ -0,0 +1,402 @@
1
+ #!/usr/bin/env node
2
+ // Puerta de reparto obligatoria en Claude Code (hooks UserPromptSubmit y PreToolUse de ~/.claude/settings.json).
3
+ //
4
+ // La regla del núcleo (~/.agents/AGENTS.md §6) pide que, al cargar la skill orca, su veredicto quede escrito
5
+ // en el chat en una línea «ORCA: …» antes de editar y que, si reparte, no se toque el proyecto hasta que la
6
+ // persona responda al plan de rondas. Con texto el modelo no lo cumple siempre; este hook lo impone:
7
+ // - UserPromptSubmit: apunta cuándo escribe la persona (las notificaciones de tareas no cuentan).
8
+ // - PostToolUse sobre Skill: apunta cuándo se carga la skill orca.
9
+ // - PreToolUse: apunta el veredicto cuando el agente lo registra con `echo "ORCA: …"` y, tras cargar la
10
+ // skill, deniega editar el proyecto, escribir desde la shell o lanzar workers hasta que haya veredicto
11
+ // y, si reparte, hasta que la persona haya respondido.
12
+ // Por qué `echo`: Claude Code escribe el transcript con retraso (a veces al acabar el turno), así que la
13
+ // línea «ORCA:» del chat no se ve a tiempo desde el hook; la orden sí, porque llega en su propia entrada.
14
+ // El transcript se sigue leyendo para lo que ya está escrito (cargas leyendo SKILL.md, veredictos de
15
+ // turnos anteriores).
16
+ // Solo actúa después de que se cargue la skill orca: sin ella, no hace nada. Si algo falla (transcript
17
+ // ilegible, formato desconocido), deja pasar y lo avisa: nunca bloquea por un fallo suyo.
18
+ // Desactivarlo: OMK_NO_GATE=1, u «omk gate off».
19
+ // Es .cjs a propósito: un package.json con "type": "module" en una carpeta superior no lo convierte en ESM.
20
+ 'use strict';
21
+
22
+ const fs = require('node:fs');
23
+ const os = require('node:os');
24
+ const path = require('node:path');
25
+
26
+ const MARK = '[Orca Multiagent Kit]';
27
+ const TAIL_BYTES = 8 * 1024 * 1024;
28
+ const PROMPTS_KEPT = 40;
29
+ const EVENTS_KEPT = 40;
30
+ const STATE_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
31
+ const SESSION_ID = /^[\w-]{1,128}$/;
32
+
33
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
34
+ const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
35
+ const AGENT_TOOLS = new Set(['Agent', 'Task']);
36
+
37
+ // Órdenes que escriben, en la primera palabra de cada tramo de una línea de shell.
38
+ const WRITE_COMMANDS = new Set(['tee', 'touch', 'mkdir', 'rmdir', 'rm', 'cp', 'mv', 'ln', 'chmod', 'chown', 'install', 'truncate', 'dd', 'patch', 'unzip', 'tar']);
39
+ const GIT_WRITES = new Set(['add', 'commit', 'merge', 'rebase', 'reset', 'checkout', 'switch', 'apply', 'am', 'cherry-pick', 'restore', 'rm', 'mv', 'clean', 'push', 'pull', 'revert', 'init', 'clone']);
40
+ const PKG_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun', 'pip', 'pip3', 'cargo', 'go', 'composer', 'bundle', 'dotnet', 'gem']);
41
+ const PKG_WRITES = new Set(['install', 'i', 'ci', 'add', 'remove', 'rm', 'uninstall', 'update', 'up', 'upgrade', 'get', 'init', 'new']);
42
+ const PS_WRITES = /\b(Set-Content|Add-Content|Out-File|New-Item|Remove-Item|Copy-Item|Move-Item|Rename-Item|Clear-Content|Expand-Archive|Set-ItemProperty)\b/i;
43
+ const SCRIPT_WRITES = /\b(writeFileSync|writeFile|appendFileSync|appendFile|rmSync|mkdirSync|renameSync|copyFileSync|unlinkSync|WriteAllText|WriteAllBytes)\b|\bopen\([^)]*['"][wa]b?\+?['"]/;
44
+ // Redirección a un fichero: «>» o «>>» seguido de un nombre. No cuentan 2>&1, >/dev/null ni >$null.
45
+ const REDIRECT = /(^|[\s;|&(])\d?>>?\s*(?!&|\/dev\/null\b|\$null\b|nul\b)["']?[\w.~/\\$:-]/i;
46
+ const WORK_DIR = /(^|[\s"'=:/\\])\.work[/\\]/;
47
+
48
+ // ---------------------------------------------------------------- utilidades
49
+
50
+ const agentsHome = (env = process.env) => env.AGENT_KIT_HOME || path.join(os.homedir(), '.agents');
51
+ const stateDir = (env = process.env) => path.join(agentsHome(env), 'state', 'gate');
52
+ const isDisabled = (env = process.env) => env.OMK_NO_GATE === '1' || fs.existsSync(path.join(stateDir(env), 'off'));
53
+
54
+ function readJson(file, fallback) {
55
+ try {
56
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
57
+ } catch (e) {
58
+ if (e.code === 'ENOENT') return fallback;
59
+ throw e;
60
+ }
61
+ }
62
+
63
+ function writeJsonAtomic(file, value) {
64
+ fs.mkdirSync(path.dirname(file), { recursive: true });
65
+ const tmp = `${file}.${process.pid}.tmp`;
66
+ fs.writeFileSync(tmp, JSON.stringify(value));
67
+ fs.renameSync(tmp, file);
68
+ }
69
+
70
+ const stateFile = (sessionId, env) => path.join(stateDir(env), `${sessionId}.json`);
71
+
72
+ /** Borra el estado de sesiones de hace más de dos semanas. Un fallo aquí no importa a nadie: se ignora con motivo. */
73
+ function pruneOldState(env) {
74
+ const dir = stateDir(env);
75
+ let names;
76
+ try {
77
+ names = fs.readdirSync(dir);
78
+ } catch {
79
+ return; // sin carpeta de estado todavía: nada que limpiar
80
+ }
81
+ const limit = Date.now() - STATE_MAX_AGE_MS;
82
+ for (const name of names) {
83
+ if (!name.endsWith('.json')) continue;
84
+ const file = path.join(dir, name);
85
+ try {
86
+ if (fs.statSync(file).mtimeMs < limit) fs.rmSync(file, { force: true });
87
+ } catch {
88
+ // otra sesión lo está escribiendo o ya lo borró: se intentará la próxima vez
89
+ }
90
+ }
91
+ }
92
+
93
+ /** Si el texto de un prompt lo escribió la persona (no una notificación de tarea en segundo plano). */
94
+ function isHumanPrompt(prompt) {
95
+ const text = String(prompt || '').trim();
96
+ if (text === '') return false;
97
+ if (/^<task-notification>/.test(text) || /\[SYSTEM NOTIFICATION/.test(text.slice(0, 200))) return false;
98
+ return true;
99
+ }
100
+
101
+ /** El transcript de la sesión principal: el de un subagente vive en <sesión>/subagents/agent-*.jsonl. */
102
+ function mainTranscript(file) {
103
+ const m = /^(.*)[\\/]subagents[\\/]agent-[^\\/]+\.jsonl$/.exec(file || '');
104
+ return m ? `${m[1]}.jsonl` : file;
105
+ }
106
+
107
+ /** Las últimas `bytes` del transcript, empezando en una línea entera. */
108
+ function readTail(file, bytes = TAIL_BYTES) {
109
+ const fd = fs.openSync(file, 'r');
110
+ try {
111
+ const size = fs.fstatSync(fd).size;
112
+ const start = Math.max(0, size - bytes);
113
+ const buffer = Buffer.alloc(size - start);
114
+ fs.readSync(fd, buffer, 0, buffer.length, start);
115
+ const text = buffer.toString('utf8');
116
+ return start === 0 ? text : text.slice(text.indexOf('\n') + 1);
117
+ } finally {
118
+ fs.closeSync(fd);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Lo que interesa del transcript: los bloques del asistente en orden (texto y llamadas a herramientas),
124
+ * cada uno con su hora. `recognized` es falso si no hay ninguna entrada de asistente con la forma esperada.
125
+ */
126
+ function parseTranscript(text) {
127
+ const blocks = [];
128
+ let recognized = false;
129
+ for (const line of text.split('\n')) {
130
+ if (!line.includes('"assistant"')) continue;
131
+ let entry;
132
+ try {
133
+ entry = JSON.parse(line);
134
+ } catch {
135
+ continue; // una línea a medio escribir al final del fichero
136
+ }
137
+ const message = entry && entry.message;
138
+ if (!message || message.role !== 'assistant' || !Array.isArray(message.content)) continue;
139
+ if (entry.isSidechain) continue;
140
+ recognized = true;
141
+ const at = Date.parse(entry.timestamp);
142
+ if (!Number.isFinite(at)) continue;
143
+ for (const block of message.content) {
144
+ if (block.type === 'text' && typeof block.text === 'string') blocks.push({ at, kind: 'text', text: block.text });
145
+ else if (block.type === 'tool_use') blocks.push({ at, kind: 'tool', name: block.name, input: block.input || {} });
146
+ }
147
+ }
148
+ return { blocks, recognized };
149
+ }
150
+
151
+ const isOrcaLoad = (block) => block.kind === 'tool' && (
152
+ (block.name === 'Skill' && /(^|:)orca$/i.test(String(block.input.skill || '').trim()))
153
+ || (block.name === 'Read' && /skills[\\/]orca[\\/]SKILL\.md$/i.test(String(block.input.file_path || ''))));
154
+
155
+ /** Las líneas «ORCA: …» de un texto, sin el formato Markdown de alrededor. */
156
+ function verdictLines(text) {
157
+ const found = [];
158
+ for (const raw of text.split(/\r?\n/)) {
159
+ const line = raw.replace(/[*_`]/g, '').replace(/^\s*(?:[>#-]\s*)*/, '').trim();
160
+ const m = /^ORCA:\s*(.*)$/.exec(line);
161
+ if (m) found.push(m[1].trim());
162
+ }
163
+ return found;
164
+ }
165
+
166
+ const isReparto = (verdict) => /^\d+\s+unidad/i.test(verdict);
167
+ const isAutoAutonomy = (verdict) => /autonom[ií]a\s+auto\b/i.test(verdict);
168
+
169
+ /** Si una orden de git escribe en el repositorio. `branch`, `tag`, `stash` y `worktree` también sirven para listar. */
170
+ function gitWrites(args) {
171
+ const [sub = '', ...rest] = args.filter((a) => !/^-C$/.test(a));
172
+ const operands = rest.filter((a) => !a.startsWith('-'));
173
+ if (GIT_WRITES.has(sub)) return true;
174
+ if (sub === 'branch' || sub === 'tag') return operands.length > 0 || rest.some((a) => /^-[dDmMcCf]$|^--(delete|move|copy|force)$/.test(a));
175
+ if (sub === 'stash') return !['list', 'show'].includes(operands[0] || '');
176
+ if (sub === 'worktree') return ['add', 'remove', 'move', 'prune', 'repair'].includes(operands[0] || '');
177
+ return false;
178
+ }
179
+
180
+ /** Si una línea de shell escribe en el proyecto (aproximado y a propósito estrecho: solo actúa con la puerta cerrada). */
181
+ function isShellWrite(command) {
182
+ const cmd = String(command || '');
183
+ if (WORK_DIR.test(cmd)) return false;
184
+ if (PS_WRITES.test(cmd) || SCRIPT_WRITES.test(cmd) || REDIRECT.test(cmd)) return true;
185
+ if (/\bsed\s+(-\w*\s+)*-i/.test(cmd) || /\bperl\s+(-\w*\s+)*-\w*i/.test(cmd)) return true;
186
+ for (const segment of cmd.split(/&&|\|\||[;|\n]/)) {
187
+ const words = segment.trim().split(/\s+/).filter((w) => w !== '' && !/^\w+=/.test(w)).map((w) => w.replace(/^["']|["']$/g, ''));
188
+ while (['sudo', 'command', 'env', 'exec'].includes(words[0])) words.shift();
189
+ const [first = '', ...args] = words;
190
+ const name = path.basename(first).toLowerCase().replace(/\.(exe|cmd)$/, '');
191
+ const [second = '', third = ''] = args.map((a) => a.toLowerCase());
192
+ if (WRITE_COMMANDS.has(name)) return true;
193
+ if (name === 'git' && gitWrites(args)) return true;
194
+ if (PKG_MANAGERS.has(name) && PKG_WRITES.has(second)) return true;
195
+ if (name === 'orca' && ((second === 'worktree' && /^(create|rm|remove)$/.test(third)) || (second === 'orchestration' && /^(worker-start|dispatch)$/.test(third)))) return true;
196
+ }
197
+ return false;
198
+ }
199
+
200
+ /** Si una ruta queda dentro del proyecto (`cwd`) y fuera de `.work/`. */
201
+ function isProjectPath(file, cwd) {
202
+ if (!file || !cwd) return false;
203
+ const norm = (p) => path.resolve(p).replace(/[\\/]+$/, '');
204
+ const abs = norm(path.resolve(cwd, file));
205
+ const root = norm(cwd);
206
+ const same = process.platform === 'win32' ? (a, b) => a.toLowerCase() === b.toLowerCase() : (a, b) => a === b;
207
+ const inside = same(abs, root) || (process.platform === 'win32' ? abs.toLowerCase() : abs).startsWith((process.platform === 'win32' ? root.toLowerCase() : root) + path.sep);
208
+ if (!inside) return false;
209
+ const rel = path.relative(root, abs).split(path.sep);
210
+ return rel[0] !== '.work';
211
+ }
212
+
213
+ // ---------------------------------------------------------------- decisión
214
+
215
+ const REGISTER = 'regístrala ejecutando `echo "ORCA: …"` con la misma línea (la puerta la lee de esa orden)';
216
+ const DENY_NO_VERDICT = `${MARK} Puerta de reparto: has cargado la skill orca y no hay veredicto registrado. Antes de editar el proyecto, escribe en el chat una línea visible que empiece por «ORCA:» —«ORCA: secuencial — <motivo>», o «ORCA: <N> unidades · …» seguida del plan de rondas—, ${REGISTER}, y vuelve a intentarlo. No reintentes la edición sin ese echo: se volverá a denegar.`;
217
+ const denyAwait = (verdict) => `${MARK} Puerta de reparto: tu veredicto es repartir («ORCA: ${verdict.slice(0, 120)}»). No se edita el proyecto, no se escribe desde la shell y no se lanzan workers hasta que el usuario responda al plan de rondas (confirmación 1). Termina el turno con el plan y la pregunta «¿Lanzo? (sí / cambia X)». Si en vez de repartir lo haces secuencial, escribe «ORCA: secuencial — <motivo>» y ${REGISTER}.`;
218
+
219
+ /**
220
+ * Qué hacer con una llamada a herramienta. Devuelve `null` (dejar pasar) o `{ deny: motivo }`.
221
+ * - `input`: la entrada de PreToolUse (tool_name, tool_input, cwd).
222
+ * - `blocks`: los bloques del asistente del transcript principal, en orden (puede venir vacío).
223
+ * - `prompts`: las horas (ms) en que escribió la persona.
224
+ * - `loads`, `verdicts`: lo que han apuntado los propios hooks (horas en ms; veredictos con su texto).
225
+ */
226
+ /** Qué vigila la puerta de esta llamada: 'edit', 'shell' o 'agent'; `null` si no le afecta (leer, escribir fuera del proyecto…). */
227
+ function gatedKind(input) {
228
+ const tool = input.tool_name;
229
+ const args = input.tool_input || {};
230
+ if (EDIT_TOOLS.has(tool)) return isProjectPath(args.file_path || args.notebook_path, input.cwd) ? 'edit' : null;
231
+ if (SHELL_TOOLS.has(tool)) return isShellWrite(args.command) ? 'shell' : null;
232
+ if (AGENT_TOOLS.has(tool)) return 'agent';
233
+ return null;
234
+ }
235
+
236
+ function decide({ input, blocks = [], prompts = [], loads = [], verdicts = [], since = 0 }) {
237
+ const kind = gatedKind(input);
238
+ if (kind === null) return null;
239
+
240
+ // Cargas y veredictos de las dos fuentes, por orden de hora.
241
+ const events = [
242
+ ...loads.map((at) => ({ at, load: true })),
243
+ ...verdicts.map((v) => ({ at: v.at, text: v.text })),
244
+ ];
245
+ for (const block of blocks) {
246
+ if (isOrcaLoad(block)) events.push({ at: block.at, load: true });
247
+ else if (block.kind === 'text') for (const text of verdictLines(block.text)) events.push({ at: block.at, text });
248
+ }
249
+ events.sort((a, b) => a.at - b.at);
250
+ let loadIndex = -1;
251
+ for (let i = events.length - 1; i >= 0; i -= 1) if (events[i].load) { loadIndex = i; break; }
252
+ if (loadIndex === -1) return null;
253
+ const loadAt = events[loadIndex].at;
254
+ const after = events.slice(loadIndex + 1).filter((e) => !e.load);
255
+
256
+ if (after.length === 0) {
257
+ // Una carga de la skill de un encargo anterior (la persona ha escrito después) ya no obliga.
258
+ if (prompts.some((at) => at > loadAt)) return null;
259
+ // Una carga anterior a que la puerta empezara a apuntar en esta sesión (se instaló con la sesión ya
260
+ // abierta) no se puede juzgar: no se sabe si la persona escribió después.
261
+ if (loadAt < since) return null;
262
+ // Antes del veredicto, un subagente puede explorar; lo que no se hace es tocar el proyecto.
263
+ return kind === 'agent' ? null : { deny: DENY_NO_VERDICT };
264
+ }
265
+ const latest = after[after.length - 1];
266
+ if (!isReparto(latest.text) || isAutoAutonomy(latest.text)) return null;
267
+ const answered = (verdict) => prompts.some((at) => at > verdict.at);
268
+ if (answered(latest)) return null;
269
+ // Repetir el mismo plan ya confirmado (al dar el estado de una ronda, por ejemplo) no pide otra
270
+ // confirmación; un plan distinto (tras «cambia X») sí.
271
+ const key = (text) => text.toLowerCase().replace(/\s+/g, ' ');
272
+ if (after.some((v) => v !== latest && isReparto(v.text) && key(v.text) === key(latest.text) && answered(v))) return null;
273
+ return { deny: denyAwait(latest.text) };
274
+ }
275
+
276
+ // ---------------------------------------------------------------- entrada y salida del hook
277
+
278
+ const BLANK = { first: null, prompts: [], loads: [], verdicts: [] };
279
+ // `since`: desde cuándo apunta la puerta en esta sesión; lo anterior no se juzga. Solo lo lleva un
280
+ // estado nuevo: uno que ya existía sin él lo apuntó otra versión y se juzga entero.
281
+ const emptyState = () => ({ since: Date.now(), ...BLANK });
282
+ const withDefaults = (state) => ({ ...BLANK, ...state });
283
+
284
+ /** Lee, cambia y guarda el estado de la sesión. Devuelve el estado guardado, o `null` si el id no vale. */
285
+ function updateState(input, env, change) {
286
+ const sessionId = String(input.session_id || '');
287
+ if (!SESSION_ID.test(sessionId)) return null;
288
+ const file = stateFile(sessionId, env);
289
+ const stored = readJson(file, null);
290
+ const state = stored === null ? emptyState() : withDefaults(stored);
291
+ change(state);
292
+ writeJsonAtomic(file, state);
293
+ return state;
294
+ }
295
+
296
+ function onPrompt(input, env) {
297
+ updateState(input, env, (state) => {
298
+ const prompt = String(input.prompt || '');
299
+ if (state.first === null) state.first = prompt.trim().slice(0, 40);
300
+ if (isHumanPrompt(prompt)) state.prompts = [...state.prompts, Date.now()].slice(-PROMPTS_KEPT);
301
+ });
302
+ if (Math.random() < 0.05) pruneOldState(env);
303
+ }
304
+
305
+ /** PostToolUse sobre Skill: si se ha cargado la skill orca, se apunta la hora. */
306
+ function onPostToolUse(input, env) {
307
+ if (input.tool_name !== 'Skill') return;
308
+ if (!/(^|:)orca$/i.test(String((input.tool_input || {}).skill || '').trim())) return;
309
+ updateState(input, env, (state) => { state.loads = [...state.loads, Date.now()].slice(-EVENTS_KEPT); });
310
+ }
311
+
312
+ function onPreToolUse(input, env) {
313
+ const sessionId = String(input.session_id || '');
314
+ let state = SESSION_ID.test(sessionId) ? readJson(stateFile(sessionId, env), null) : null;
315
+ // Sin estado, la sesión empezó antes de instalar la puerta (o su UserPromptSubmit no corre): no se
316
+ // sabe cuándo ha escrito la persona y no se juzga.
317
+ if (state === null) return { result: null };
318
+ state = withDefaults(state);
319
+ // Un worker despachado por la skill orca trabaja su unidad: no reparte ni pasa por la puerta.
320
+ if (/^UNIT:/.test(String(state.first || ''))) return { result: null };
321
+ // El agente registra su veredicto con un echo que lo lleva: se apunta y la orden pasa. Solo cuenta un
322
+ // echo (o printf, Write-Output): un grep que busca «ORCA:» no es un veredicto.
323
+ const command = String((input.tool_input || {}).command || '');
324
+ if (SHELL_TOOLS.has(input.tool_name) && /^\s*(echo|printf|Write-Output|Write-Host)\b/i.test(command)) {
325
+ const lines = verdictLines(command.replace(/["']/g, '\n')).filter((text) => text !== '');
326
+ if (lines.length > 0) {
327
+ const at = Date.now();
328
+ state = updateState(input, env, (s) => { s.verdicts = [...s.verdicts, ...lines.map((text) => ({ at, text: text.slice(0, 300) }))].slice(-EVENTS_KEPT); });
329
+ return { result: null };
330
+ }
331
+ }
332
+ // Lo que no vigila (la mayoría de las llamadas) sale sin leer el transcript.
333
+ if (gatedKind(input) === null) return { result: null };
334
+ let blocks = [];
335
+ let warning = null;
336
+ const transcript = mainTranscript(String(input.transcript_path || ''));
337
+ try {
338
+ const parsed = parseTranscript(readTail(transcript));
339
+ if (parsed.recognized) blocks = parsed.blocks;
340
+ else warning = 'el transcript no tiene el formato que conozco';
341
+ } catch (e) {
342
+ warning = `no pude leer el transcript (${e.code || e.message})`;
343
+ }
344
+ // Sin transcript, lo apuntado por los hooks basta para decidir; si no hay nada apuntado, no se sabe
345
+ // si se cargó la skill leyendo su SKILL.md, y se deja pasar avisando.
346
+ if (warning && state.loads.length === 0) return { result: null, warning };
347
+ return { result: decide({ input, blocks, prompts: state.prompts, loads: state.loads, verdicts: state.verdicts, since: Number(state.since) || 0 }) };
348
+ }
349
+
350
+ function logError(env, message) {
351
+ try {
352
+ fs.mkdirSync(stateDir(env), { recursive: true });
353
+ fs.appendFileSync(path.join(stateDir(env), 'errors.log'), `${new Date().toISOString()} ${message}\n`);
354
+ } catch {
355
+ // sin disco donde apuntarlo: el aviso al usuario por systemMessage sigue saliendo
356
+ }
357
+ }
358
+
359
+ /** Ejecuta el hook con la entrada `raw` (JSON de stdin). Devuelve lo que hay que escribir por stdout. */
360
+ function run(raw, env = process.env) {
361
+ let input;
362
+ try {
363
+ input = JSON.parse(raw);
364
+ } catch {
365
+ return '';
366
+ }
367
+ if (isDisabled(env)) return '';
368
+ try {
369
+ if (input.hook_event_name === 'UserPromptSubmit') {
370
+ onPrompt(input, env);
371
+ return '';
372
+ }
373
+ if (input.hook_event_name === 'PostToolUse') {
374
+ onPostToolUse(input, env);
375
+ return '';
376
+ }
377
+ if (input.hook_event_name !== 'PreToolUse') return '';
378
+ const { result, warning } = onPreToolUse(input, env);
379
+ if (warning) {
380
+ logError(env, warning);
381
+ return JSON.stringify({ systemMessage: `${MARK} Puerta de reparto sin comprobar: ${warning}. La herramienta sigue.` });
382
+ }
383
+ if (!result) return '';
384
+ return JSON.stringify({
385
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: result.deny },
386
+ });
387
+ } catch (e) {
388
+ logError(env, e && e.stack ? e.stack : String(e));
389
+ return JSON.stringify({ systemMessage: `${MARK} Puerta de reparto sin comprobar por un fallo interno (${e.message}). La herramienta sigue; detalle en ${path.join(stateDir(env), 'errors.log')}.` });
390
+ }
391
+ }
392
+
393
+ if (require.main === module) {
394
+ const chunks = [];
395
+ process.stdin.on('data', (chunk) => chunks.push(chunk));
396
+ process.stdin.on('end', () => {
397
+ const output = run(Buffer.concat(chunks).toString('utf8'));
398
+ if (output) process.stdout.write(output);
399
+ });
400
+ }
401
+
402
+ module.exports = { MARK, run, decide, parseTranscript, verdictLines, isShellWrite, isProjectPath, isHumanPrompt, mainTranscript, stateDir };
package/install.sh CHANGED
@@ -45,6 +45,16 @@ DEVIN_DIR="$HOME/.config/devin"
45
45
  STAMP="$(date +%Y%m%d-%H%M%S)"
46
46
  BK="$AG/backups/$STAMP"
47
47
  VERSION="$(cat "$SRC/VERSION")"
48
+ # Cómo se le dice cada cosa a quien lo lee: con omk (npm, npx o el ejecutable, que ponen OMK_CLI) o con
49
+ # este mismo script (zip, clon o curl, donde no hay omk).
50
+ SELF="$SRC/install.sh"
51
+ # shellcheck disable=SC2088 # es texto para enseñar, no una ruta que se vaya a expandir
52
+ case "$SELF" in "$HOME"/*) SELF="~/${SELF#"$HOME"/}" ;; esac
53
+ if [ -n "${OMK_CLI:-}" ]; then
54
+ K_INSTALL="omk install"; K_VERIFY="omk verify"; K_INIT="omk init <ruta>"; K_RESTORE="omk restore"; K_BACKUPS="omk backups"
55
+ else
56
+ K_INSTALL="$SELF"; K_VERIFY="$SELF --verify"; K_INIT="$SELF --project-only <ruta>"; K_RESTORE="$SELF --restore"; K_BACKUPS="ls $AG/backups"
57
+ fi
48
58
  KIT_SKILLS="kit-init orca speckit-orca-implement csr-stack csr-gate csr-audit"
49
59
  # Skills de versiones anteriores que esta versión retira (consolidadas en "orca")
50
60
  OLD_SKILLS="maw-route maw-brief maw-plan maw-dispatch maw-worker maw-integrate maw-race maw-setup"
@@ -99,10 +109,10 @@ footer() { # $1 global|project|both
99
109
  if [ "$DRY" -eq 1 ]; then printf '\n%sSimulación: no se ha escrito nada.%s\n\n' "$C_Y" "$C_0"; return 0; fi
100
110
  printf '\n%s✓ Hecho%s\n' "$C_L$C_B" "$C_0"
101
111
  case "$1" in
102
- global) printf ' %scomprobar%s ./install.sh --verify\n %sproyecto%s ./install.sh --project-only <ruta>\n' "$C_D" "$C_0" "$C_D" "$C_0" ;;
112
+ global) printf ' %scomprobar%s %s\n %sproyecto%s %s\n' "$C_D" "$C_0" "$K_VERIFY" "$C_D" "$C_0" "$K_INIT" ;;
103
113
  *) printf ' %ssiguiente%s en el agente: «inicializa el proyecto»\n' "$C_D" "$C_0" ;;
104
114
  esac
105
- [ -n "$st" ] && printf ' %sdeshacer%s ./install.sh --restore %s\n' "$C_D" "$C_0" "$st"
115
+ [ -n "$st" ] && printf ' %sdeshacer%s %s %s\n' "$C_D" "$C_0" "$K_RESTORE" "$st"
106
116
  printf '\n'; }
107
117
  NSK=0; for _s in $KIT_SKILLS; do NSK=$((NSK+1)); done
108
118
  # Cursor guarda las reglas de usuario en su base de datos de estado: basta con buscar la ruta del núcleo.
@@ -142,7 +152,7 @@ snapshot() {
142
152
  run mkdir -p "$BK/$(dirname "$rel")"
143
153
  run cp -a "$p" "$BK/$rel"
144
154
  }
145
- LINK_HELP="En Windows, activa el Modo de desarrollador (Configuracion > Sistema > Para programadores) o abre Git Bash como administrador, y repite. Lo ya movido esta en el backup: ./install.sh --restore $STAMP"
155
+ LINK_HELP="En Windows, activa el Modo de desarrollador (Configuracion > Sistema > Para programadores) o abre Git Bash como administrador, y repite. Lo ya movido esta en el backup: $K_RESTORE $STAMP"
146
156
  # Deja $2 como enlace simbolico a $1. Si habia otra cosa, va al backup.
147
157
  link() {
148
158
  local target="$1" l="$2"
@@ -230,7 +240,7 @@ fi
230
240
 
231
241
  # ------------------------------------------------------------------ restore
232
242
  if [ -n "$RESTORE" ]; then
233
- R="$AG/backups/$RESTORE"; [ -d "$R" ] || { echo "No existe la copia $R (consulta: omk backups)" >&2; exit 1; }
243
+ R="$AG/backups/$RESTORE"; [ -d "$R" ] || { echo "No existe la copia $R (consulta: $K_BACKUPS)" >&2; exit 1; }
234
244
  title "Restaurar" "copia $RESTORE"
235
245
  phase "Devolviendo ficheros a su sitio"
236
246
  N=0
@@ -303,7 +313,7 @@ if [ "$VERIFY" -eq 1 ]; then
303
313
  vinfo() { if [ -n "$EV" ]; then ev "check::info::$1"; else printf ' %s· %s%s\n' "$C_D" "$1" "$C_0"; fi; }
304
314
  chk_link() {
305
315
  if [ -L "$3" ] && [ "$(readlink "$3")" = "$2" ]; then vok "$1"
306
- elif [ -e "$3" ] && [ ! -L "$3" ]; then vfail "$1: $(short "$3") es una copia, no un enlace (acabará divergiendo; ejecuta omk install)"
316
+ elif [ -e "$3" ] && [ ! -L "$3" ]; then vfail "$1: $(short "$3") es una copia, no un enlace (acabará divergiendo; ejecuta $K_INSTALL)"
307
317
  else vfail "$1: $(short "$3") no enlaza a $(short "$2")"; fi; }
308
318
  # Skills de un agente: separa las copias (divergen en silencio) de las que faltan o apuntan a otro sitio.
309
319
  chk_skills() { # $1 agente · $2 carpeta de skills
@@ -312,18 +322,19 @@ if [ "$VERIFY" -eq 1 ]; then
312
322
  if [ -L "$2/$s" ] && [ "$(readlink "$2/$s")" = "$AG/skills/$s" ]; then continue; fi
313
323
  if [ -e "$2/$s" ] && [ ! -L "$2/$s" ]; then cs="$cs $s"; else ms="$ms $s"; fi
314
324
  done
315
- [ -n "$cs" ] && vfail "$1: skills copiadas en vez de enlazadas (acabarán divergiendo; ejecuta omk install):$cs"
325
+ [ -n "$cs" ] && vfail "$1: skills copiadas en vez de enlazadas (acabarán divergiendo; ejecuta $K_INSTALL):$cs"
316
326
  [ -n "$ms" ] && vfail "$1: skills sin enlazar:$ms"
317
327
  [ -z "$cs$ms" ] && vok "$1: skills enlazadas"; return 0; }
318
328
  title "Verificación" "$(agent_names)"
319
329
  [ "$CLAUDE_SKIP" -eq 1 ] && vfail "Claude Code: el perfil de Orca $(short "$ORCA_PROFILE") no importa ~/.claude/CLAUDE.md, así que Claude en Orca no ve el kit"
320
- [ -f "$AG/AGENTS.md" ] && vok "núcleo en ~/.agents/AGENTS.md (v$(cat "$AG/AGENT_KIT_VERSION" 2>/dev/null || echo '?'))" || vfail "falta ~/.agents/AGENTS.md: ejecuta omk install"
330
+ [ -f "$AG/AGENTS.md" ] && vok "núcleo en ~/.agents/AGENTS.md (v$(cat "$AG/AGENT_KIT_VERSION" 2>/dev/null || echo '?'))" || vfail "falta ~/.agents/AGENTS.md: ejecuta $K_INSTALL"
321
331
  n=$(ls -1 "$AG/rules/lang"/*.md 2>/dev/null | wc -l | tr -d ' '); [ "$n" -ge 17 ] && vok "$n guías de lenguaje" || vfail "guías de lenguaje: $n de 17"
322
332
  ms=""; for s in $KIT_SKILLS; do [ -f "$AG/skills/$s/SKILL.md" ] || ms="$ms $s"; done
323
333
  [ -z "$ms" ] && vok "$NSK skills del kit" || vfail "faltan skills:$ms"
324
- [ -f "$AG/skills/orca/references/olimpo.md" ] && vok "roles de Olimpo" || vfail "falta skills/orca/references/olimpo.md: ejecuta omk install"
325
- [ -f "$AG/models.md" ] && vok "modelos por nivel en ~/.agents/models.md" || vfail "falta ~/.agents/models.md (qué modelo usa cada nivel): ejecuta omk install"
334
+ [ -f "$AG/skills/orca/references/olimpo.md" ] && vok "roles de Olimpo" || vfail "falta skills/orca/references/olimpo.md: ejecuta $K_INSTALL"
335
+ [ -f "$AG/models.md" ] && vok "modelos por nivel en ~/.agents/models.md" || vfail "falta ~/.agents/models.md (qué modelo usa cada nivel): ejecuta $K_INSTALL"
326
336
  [ -f "$AG/speckit-ext/orca/extension.yml" ] && vok "extensión de spec-kit" || vfail "falta la extensión de spec-kit (~/.agents/speckit-ext/orca)"
337
+ [ -f "$AG/hooks/orca-gate.cjs" ] && vok "puerta de reparto (hooks/orca-gate.cjs)" || vfail "falta ~/.agents/hooks/orca-gate.cjs: ejecuta $K_INSTALL"
327
338
  for s in $OLD_SKILLS; do [ -e "$AG/skills/$s" ] && vfail "skill retirada sigue instalada: $s"; done
328
339
  if has_agent claude; then
329
340
  grep -q '@~/.agents/AGENTS.md' "$CLAUDE_DIR/CLAUDE.md" 2>/dev/null && vok "Claude Code: CLAUDE.md importa el núcleo" || vfail "Claude Code: CLAUDE.md no importa el núcleo"
@@ -345,7 +356,7 @@ if [ "$VERIFY" -eq 1 ]; then
345
356
  fi
346
357
  if [ -n "$EV" ]; then ev "result::$bad::$nok"; exit $((bad > 0)); fi
347
358
  if [ "$bad" -eq 0 ]; then printf '\n%s✓ Todo correcto%s %s%s comprobaciones%s\n\n' "$C_L$C_B" "$C_0" "$C_D" "$nok" "$C_0"; exit 0; fi
348
- printf '\n%s✗ %s fallos%s %sejecuta «omk install» para repararlos%s\n\n' "$C_R$C_B" "$bad" "$C_0" "$C_D" "$C_0"; exit 1
359
+ printf '\n%s✗ %s fallos%s %sejecuta «%s» para repararlos%s\n\n' "$C_R$C_B" "$bad" "$C_0" "$C_D" "$K_INSTALL" "$C_0"; exit 1
349
360
  fi
350
361
 
351
362
  # ------------------------------------------------------------------ global
@@ -370,6 +381,9 @@ if [ "$PROJECT_ONLY" -eq 0 ]; then
370
381
  done
371
382
  run cp -R "$SRC/templates/." "$AG/templates/"
372
383
  run cp -R "$SRC/output-styles/." "$AG/output-styles/"
384
+ # La puerta de reparto de Claude Code (omk la registra en ~/.claude/settings.json).
385
+ run mkdir -p "$AG/hooks"
386
+ run cp -R "$SRC/hooks/." "$AG/hooks/"
373
387
  run cp "$SRC/VERSION" "$AG/AGENT_KIT_VERSION"
374
388
  run mkdir -p "$AG/speckit-ext"
375
389
  [ -e "$AG/speckit-ext/orca" ] && run rm -rf "$AG/speckit-ext/orca"
@@ -465,8 +479,7 @@ if [ -n "$PROJECT" ]; then
465
479
  phase "Proyecto $PNAME"
466
480
  INSTALLED="$(cat "$AG/AGENT_KIT_VERSION" 2>/dev/null || true)"
467
481
  if [ "$PROJECT_ONLY" -eq 1 ] && [ "$INSTALLED" != "$VERSION" ]; then
468
- if [ -n "${OMK_CLI:-}" ]; then FIX="omk install"; else FIX="./install.sh"; fi
469
- todo "Instalación global: en ~/.agents hay ${INSTALLED:-una versión sin instalar} y este kit es v${VERSION}. Ejecuta «${FIX}» para tener las skills orca y kit-init."
482
+ todo "Instalación global: en ~/.agents hay ${INSTALLED:-una versión sin instalar} y este kit es v${VERSION}. Ejecuta «${K_INSTALL}» para tener las skills orca y kit-init."
470
483
  fi
471
484
  OV=""
472
485
  for f in "$PROJECT/CLAUDE.md" "$PROJECT/AGENTS.md"; do [ -f "$f" ] && OV="$OV$(extract_overrides "$f")
@@ -487,7 +500,7 @@ if [ -n "$PROJECT" ]; then
487
500
  rm -f "$TMP" "$REST"
488
501
  [ -e "$PROJECT/.worktreeinclude" ] && HADWI=1 || HADWI=0
489
502
  for f in STACK.md ORCHESTRATION.md orca.yaml .worktreeinclude; do
490
- if [ -e "$PROJECT/$f" ]; then item keep "$f ya existía: no se toca"; else run cp "$SRC/templates/$f" "$PROJECT/$f"; item add "$f creado"; fi
503
+ if [ -e "$PROJECT/$f" ]; then item keep "$f ya existía: se conserva"; else run cp "$SRC/templates/$f" "$PROJECT/$f"; item add "$f creado"; fi
491
504
  done
492
505
  guard_worktreeinclude "$PROJECT" "$HADWI"
493
506
  if [ ! -e "$PROJECT/.claude/settings.json" ] && has_agent claude; then run mkdir -p "$PROJECT/.claude"; run cp "$SRC/templates/claude-settings.json" "$PROJECT/.claude/settings.json"; item add ".claude/settings.json creado"; fi
@@ -11,6 +11,8 @@ orca plugin inspect . --json # qué aporta y qué acceso pide
11
11
  - `src/kit.ts`: lógica pura (detección de despachos, mensajes de "comando no encontrado", resumen de agentes).
12
12
  - `src/protocol.ts`: el contrato entre panel y worker (peticiones y eventos), declarado una vez.
13
13
  - `src/worker.ts`: el worker que Orca carga; solo habla con Orca por su API. Oye cada hook y evento una vez y lo reparte a `src/worker/{notices,worktrees,history}.ts` (`src/worker/context.ts`).
14
- - `src/panel.tsx`: el panel; las pestañas Avisos, Worktrees, Historial y la autonomía viven en `src/tabs/`.
14
+ - `src/worker/actions.ts`: sigue en su terminal el comando `omk` o el agente que se acaba de lanzar, hasta que termina.
15
+ - `src/panel.tsx`: el panel; las pestañas Avisos, Worktrees, Historial y la autonomía viven en `src/tabs/`, y la tarjeta de la acción en curso en `src/ui/action-card.tsx`.
16
+ - `src/panel.check.ts`: escenarios del panel para `orca plugin check` y `orca plugin shot . --scenario <nombre>`.
15
17
  - `src/plan-card.ts`: valida el `plan.json` de la skill `orca` ([formato](../skills/orca/references/plan-card.md)).
16
18
  - `assets/logos/`: los logos de agente que usa Orca, a 16 px (ver su README).
@@ -2,8 +2,8 @@
2
2
  "manifestVersion": 2,
3
3
  "id": "multiagent-kit",
4
4
  "name": "Orca Multiagent Kit",
5
- "version": "0.6.0",
6
- "description": "Comandos del kit en la paleta; un panel con los avisos que esperan tu respuesta (plan de rondas incluido), los agentes por nombre y con su icono, los worktrees de la orquestación y su modelo, el historial de runs, el equipo de roles y la autonomía, orquestar una tarea, las acciones y los ajustes; el contrato del worker en cada despacho del kit; avisos de agentes bloqueados y de runs terminados, y los agentes activos en la barra de estado.",
5
+ "version": "0.7.0",
6
+ "description": "Comandos del kit en la paleta; un panel con los avisos que esperan tu respuesta (plan de rondas incluido), los agentes por nombre y con su icono, los worktrees de la orquestación y su modelo, el historial de runs, el equipo de roles y la autonomía, orquestar una tarea, las acciones (verificar, inicializar, actualizar) con su estado y su salida en el propio panel, y los ajustes; el contrato del worker en cada despacho del kit; avisos de agentes bloqueados y de runs terminados, y los agentes activos en la barra de estado.",
7
7
  "author": {
8
8
  "name": "Fernando Baquero y Necro-Coder",
9
9
  "url": "https://github.com/FernandoBaqueroo/orca-multiagent-kit"
@@ -33,7 +33,11 @@ import {
33
33
  parseContractHintMode,
34
34
  parseDispatch,
35
35
  parseTeam,
36
- pollUntil,
36
+ OUTPUT_LINE_MAX,
37
+ exitCodeOf,
38
+ isYesNoPrompt,
39
+ lacksExitMarker,
40
+ outputLines,
37
41
  resolveFocusedWorkspaceId,
38
42
  summarizeAgents,
39
43
  teamCommand,
@@ -613,20 +617,38 @@ describe('autonomía', () => {
613
617
  })
614
618
  })
615
619
 
616
- describe('pollUntil', () => {
617
- const instant = { attempts: 3, delayMs: 10, sleep: async () => undefined }
620
+ describe('salida de un comando omk en su terminal', () => {
621
+ test('la línea de cierre da el código de salida; sin ella, nada', () => {
622
+ assert.equal(exitCodeOf(['PS C:\\repo> omk verify --exit-marker', ' ✓ Todo correcto', '', '[omk:fin] verify salida=0']), 0)
623
+ assert.equal(exitCodeOf(['[omk:fin] update salida=1', 'PS C:\\repo>']), 1)
624
+ assert.equal(exitCodeOf(['\u001b[32m[omk:fin] team salida=2\u001b[0m']), 2)
625
+ // La orden tecleada lleva la opción, no la línea de cierre.
626
+ assert.equal(exitCodeOf(['$ omk update --exit-marker', ' ✓ Fuente única en ~/.agents']), null)
627
+ assert.equal(exitCodeOf(['[omk:fin] update salida=', '[omk:fin] salida=0', '[omk:fin] update salida=1234']), null)
628
+ assert.equal(exitCodeOf([]), null)
629
+ })
630
+
631
+ test('reconoce un omk anterior a la línea de cierre', () => {
632
+ assert.equal(lacksExitMarker([' Opcion desconocida: --exit-marker']), true)
633
+ assert.equal(lacksExitMarker(['omk team: opción desconocida para omk team: --exit-marker']), true)
634
+ assert.equal(lacksExitMarker(['omk: comando desconocido: --exit-marker']), true)
635
+ assert.equal(lacksExitMarker(['$ omk verify --exit-marker', ' ✓ núcleo en ~/.agents/AGENTS.md']), false)
636
+ })
618
637
 
619
- test('para en cuanto la salida coincide', async () => {
620
- let reads = 0
621
- const found = await pollUntil(async () => [String(++reads)], (lines) => lines[0] === '2', instant)
622
- assert.equal(found, true)
623
- assert.equal(reads, 2)
638
+ test('una pregunta de sí o no solo cuenta si es lo último', () => {
639
+ assert.equal(isYesNoPrompt([' Orca pide tu aprobación', ' › ¿Apruebas este acceso? [s/N] ', '']), true)
640
+ assert.equal(isYesNoPrompt([' › ¿Apruebas este acceso? [s/N] s', ' ✓ Plugin instalado']), false)
641
+ assert.equal(isYesNoPrompt([]), false)
624
642
  })
625
643
 
626
- test('se rinde tras el número de intentos', async () => {
627
- let reads = 0
628
- const found = await pollUntil(async () => [String(++reads)], () => false, instant)
629
- assert.equal(found, false)
630
- assert.equal(reads, 3)
644
+ test('limpia la salida: sin escapes ni control, con sangría, sin la línea de cierre y acotada', () => {
645
+ assert.deepEqual(
646
+ outputLines(['\u001b[1m ✓ Hecho\u001b[0m\u0007', ' + models.md\u202e creado', '[omk:fin] update salida=0', '', ' ']),
647
+ [' ✓ Hecho', ' + models.md creado']
648
+ )
649
+ assert.equal(outputLines([`${'x'.repeat(OUTPUT_LINE_MAX)}yz`])[0]?.length, OUTPUT_LINE_MAX)
650
+ assert.deepEqual(outputLines(['a', 'b', 'c'], 2), ['b', 'c'])
651
+ // Un spinner leído como salida acumulada: cuenta el último fotograma, no todos pegados.
652
+ assert.deepEqual(outputLines(['\r ⠋ Claude Code…\r ⠙ Claude Code…\r ✓ Claude Code\r']), [' ✓ Claude Code'])
631
653
  })
632
654
  })