@liriraid/agentflow-ai 1.0.19 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/orchestrator.js CHANGED
@@ -122,6 +122,7 @@ const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
122
122
 
123
123
  const QUEUE_FILE = path.join(WORKSPACE, "QUEUE.md");
124
124
  const INBOX_FILE = path.join(WORKSPACE, "INBOX.md");
125
+ const NOTIFY_FILE = path.join(WORKSPACE, "NOTIFY.md");
125
126
  const AWAY_MODE_FILE = path.join(WORKSPACE, ".away-mode");
126
127
  const LOG_DIR = path.join(WORKSPACE, "logs");
127
128
 
@@ -266,6 +267,11 @@ const TEXT = {
266
267
  inboxReasonLabel: "- **Motivo:**",
267
268
  inboxNewAgentLabel: "- **Nuevo agente:**",
268
269
  inboxFailAction: "- **Acción:** La TUI reasignó automáticamente. Verifica en QUEUE.md o espera la siguiente notificación de completada.",
270
+ // NOTIFY.md — notificación concisa a la sesión interactiva de Claude
271
+ notifyComplete: (ts, id, agent, dur) => `🔔 [${ts}] ${id} completada por ${agent} (${dur}).\nRevisa INBOX.md y crea la siguiente tarea de implementación en QUEUE.md si aún no existe.`,
272
+ notifyFailed: (ts, id, from, to, reason) => `⚠️ [${ts}] ${id} falló en ${from} → reasignada a ${to}.\nMotivo: ${reason}\nRevisa INBOX.md para el contexto.`,
273
+ notifyPermanentFail: (ts, id, agent) => `🚨 [${ts}] ${id} falló permanentemente en ${agent} (sin más reintentos).\nDecide si eliminar, reasignar o escalar la tarea en QUEUE.md.`,
274
+ notifyRateLimit: (ts, id, agent, resetStr, retries, max) => `⏳ [${ts}] ${id} — ${agent} alcanzó el límite de tokens (reintento ${retries}/${max}, ${resetStr}).\nSi quieres reasignar ahora: asigna a Claude-Worker (Frontend). Si esperas, reintentará automáticamente.`,
269
275
  },
270
276
  en: {
271
277
  configExists:
@@ -370,6 +376,11 @@ const TEXT = {
370
376
  inboxReasonLabel: "- **Reason:**",
371
377
  inboxNewAgentLabel: "- **New agent:**",
372
378
  inboxFailAction: "- **Action:** TUI reassigned automatically. Check QUEUE.md or wait for the next completion notification.",
379
+ // NOTIFY.md — concise notification to the interactive Claude session
380
+ notifyComplete: (ts, id, agent, dur) => `🔔 [${ts}] ${id} completed by ${agent} (${dur}).\nCheck INBOX.md and create the next implementation task in QUEUE.md if it does not exist yet.`,
381
+ notifyFailed: (ts, id, from, to, reason) => `⚠️ [${ts}] ${id} failed on ${from} → reassigned to ${to}.\nReason: ${reason}\nCheck INBOX.md for context.`,
382
+ notifyPermanentFail: (ts, id, agent) => `🚨 [${ts}] ${id} permanently failed on ${agent} (no more retries).\nDecide whether to remove, reassign, or escalate the task in QUEUE.md.`,
383
+ notifyRateLimit: (ts, id, agent, resetStr, retries, max) => `⏳ [${ts}] ${id} — ${agent} hit token/rate limit (retry ${retries}/${max}, ${resetStr}).\nTo reassign now: assign to Claude-Worker (Frontend). Otherwise it will retry automatically.`,
373
384
  },
374
385
  };
375
386
  const L = TEXT[WORKSPACE_LANGUAGE];
@@ -1064,6 +1075,15 @@ function writeInboxFailureNotification(task, failedAgent, newAgent, reason) {
1064
1075
  } catch {}
1065
1076
  }
1066
1077
 
1078
+ // Escribe una notificación concisa en NOTIFY.md para la sesión interactiva de Claude.
1079
+ // Los hooks de .claude/settings.json leen y limpian este archivo automáticamente.
1080
+ function writeNotifyFile(message) {
1081
+ try {
1082
+ const sep = fs.existsSync(NOTIFY_FILE) ? '\n---\n' : '';
1083
+ fs.appendFileSync(NOTIFY_FILE, sep + message + '\n', 'utf-8');
1084
+ } catch {}
1085
+ }
1086
+
1067
1087
  // GAP 2 — Move a task line from ## Pending to ## In Progress when it starts
1068
1088
  function moveTaskToInProgress(task) {
1069
1089
  if (!fs.existsSync(QUEUE_FILE)) return;
@@ -1523,6 +1543,7 @@ function completeTask(task, agentName) {
1523
1543
  ag.lastLine = L.lastCompleted(task.id);
1524
1544
  updateQueueFile(task);
1525
1545
  writeInboxNotification(task, agentName, elapsed);
1546
+ writeNotifyFile(L.notifyComplete(timestamp(), task.id, agentName, formatDuration(elapsed)));
1526
1547
  scheduleNext();
1527
1548
  renderDashboard();
1528
1549
  }
@@ -1591,6 +1612,7 @@ function failTask(task, agentName, code) {
1591
1612
  `{yellow-fg}${escBl(L.agentRateLimit(resetStr))}{/yellow-fg}`,
1592
1613
  true,
1593
1614
  );
1615
+ writeNotifyFile(L.notifyRateLimit(timestamp(), task.id, agentName, resetStr, retries, maxRetries));
1594
1616
  } else {
1595
1617
  log("FAIL", L.logFail(agentName, task.id, code, retries, maxRetries));
1596
1618
  appendToAgent(
@@ -1622,6 +1644,7 @@ function failTask(task, agentName, code) {
1622
1644
  : L.reasonPersistent;
1623
1645
  if (tryFallbackToAlternative(task, agentName, reason)) {
1624
1646
  writeInboxFailureNotification(task, agentName, task.agent, reason);
1647
+ writeNotifyFile(L.notifyFailed(timestamp(), task.id, agentName, task.agent, reason));
1625
1648
  setTimeout(() => {
1626
1649
  scheduleNext();
1627
1650
  safeRenderDashboard();
@@ -1634,6 +1657,7 @@ function failTask(task, agentName, code) {
1634
1657
  task.status = "failed";
1635
1658
  ag.lastLine = L.lastFailed(task.id);
1636
1659
  log("ERROR", L.logPermanentFail(task.id, retries));
1660
+ writeNotifyFile(L.notifyPermanentFail(timestamp(), task.id, agentName));
1637
1661
  } else {
1638
1662
  task.status = "pending";
1639
1663
  let retryDelay = rl.isRateLimit
@@ -1817,7 +1841,6 @@ function getClaudeFallbackAgent(task) {
1817
1841
  }
1818
1842
 
1819
1843
  function getAlternativeSupportAgent(failedAgentName) {
1820
- if (failedAgentName === "Codex") return "OpenCode";
1821
1844
  if (failedAgentName === "OpenCode") return "Codex";
1822
1845
  return null;
1823
1846
  }
@@ -1825,7 +1848,7 @@ function getAlternativeSupportAgent(failedAgentName) {
1825
1848
  function tryFallbackToAlternative(task, failedAgentName, reason) {
1826
1849
  if (!["Codex", "OpenCode"].includes(failedAgentName)) return false;
1827
1850
 
1828
- // Step 1: try sibling support agent (CodexOpenCode, OpenCode Codex)
1851
+ // Step 1: try sibling support agent (OpenCodeCodex only; Codex falls through directly)
1829
1852
  const siblingAgent = getAlternativeSupportAgent(failedAgentName);
1830
1853
  const siblingAvailable =
1831
1854
  siblingAgent &&
@@ -1931,16 +1954,18 @@ setInterval(() => {
1931
1954
  if (command) applyControlCommand(command);
1932
1955
  }, 1000);
1933
1956
 
1934
- // Real-time queue detection via fs.watch fires immediately when QUEUE.md changes
1935
- // (e.g. Claude writes a new task). No more 30s delay.
1957
+ // Real-time queue detection watches WORKSPACE directory (not the file directly)
1958
+ // because on Windows fs.watch on a file is unreliable; watching the parent dir
1959
+ // and filtering by filename is the stable pattern (same as AWAY MODE watcher).
1936
1960
  let _queueWatchDebounce = null;
1937
1961
  function startQueueWatcher() {
1938
- if (!fs.existsSync(QUEUE_FILE)) return;
1939
1962
  try {
1940
- const watcher = fs.watch(QUEUE_FILE, {persistent: false}, (eventType) => {
1941
- if (eventType !== 'change') return;
1963
+ const watchName = path.basename(QUEUE_FILE);
1964
+ const watcher = fs.watch(WORKSPACE, {persistent: false}, (eventType, filename) => {
1965
+ if (filename !== watchName) return;
1942
1966
  if (_queueWatchDebounce) clearTimeout(_queueWatchDebounce);
1943
1967
  _queueWatchDebounce = setTimeout(() => {
1968
+ if (!fs.existsSync(QUEUE_FILE)) return;
1944
1969
  const prevCount = state.queue.length;
1945
1970
  reloadQueue();
1946
1971
  if (!state.paused) scheduleNext();
@@ -2042,8 +2067,9 @@ function startInboxWatcher() {
2042
2067
  try { fs.writeFileSync(INBOX_FILE, '', 'utf-8'); } catch {}
2043
2068
  }
2044
2069
  try {
2045
- const watcher = fs.watch(INBOX_FILE, {persistent: false}, (eventType) => {
2046
- if (eventType !== 'change') return;
2070
+ const watchName = path.basename(INBOX_FILE);
2071
+ const watcher = fs.watch(WORKSPACE, {persistent: false}, (eventType, filename) => {
2072
+ if (filename !== watchName) return;
2047
2073
  if (_inboxDebounce) clearTimeout(_inboxDebounce);
2048
2074
  _inboxDebounce = setTimeout(dispatchInboxClaude, 100);
2049
2075
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liriraid/agentflow-ai",
3
- "version": "1.0.19",
3
+ "version": "1.0.20",
4
4
  "description": "Multi-agent workspace orchestrator with TUI. Coordinates AI coding agents over your real frontend and backend projects.",
5
5
  "author": "LiriRaid",
6
6
  "homepage": "https://github.com/LiriRaid/agentflow-ai#readme",
package/src/ink/index.mjs CHANGED
@@ -393,11 +393,16 @@ function shutdown() {
393
393
  }
394
394
 
395
395
  // Reactivo: dispara un refresh inmediato cuando el engine escribe el STATE_FILE.
396
- // Esto elimina el lag de polling para cambios de cola y estado de agentes.
396
+ // Vigila el directorio logs/ (no el archivo directamente) porque en Windows
397
+ // fs.watch sobre un archivo es poco confiable — el patrón estable es vigilar
398
+ // el directorio padre y filtrar por nombre de archivo.
397
399
  function ensureStateWatcher() {
398
- if (stateWatcher || !fs.existsSync(STATE_FILE)) return;
400
+ const logsDir = path.dirname(STATE_FILE);
401
+ const stateFileName = path.basename(STATE_FILE);
402
+ if (stateWatcher || !fs.existsSync(logsDir)) return;
399
403
  try {
400
- stateWatcher = fs.watch(STATE_FILE, {persistent: false}, () => {
404
+ stateWatcher = fs.watch(logsDir, {persistent: false}, (eventType, filename) => {
405
+ if (filename !== stateFileName) return;
401
406
  if (stateWatchDebounce) clearTimeout(stateWatchDebounce);
402
407
  stateWatchDebounce = setTimeout(() => {
403
408
  if (quitRequested) return;
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // Reads NOTIFY.md from the workspace and writes its content to stdout so the
4
+ // Claude Code hook injects it into the interactive session.
5
+ // The file is deleted after reading to avoid repeating the notification.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+
9
+ const notifyFile = path.join(process.cwd(), 'NOTIFY.md');
10
+ if (!fs.existsSync(notifyFile)) process.exit(0);
11
+
12
+ const content = fs.readFileSync(notifyFile, 'utf8').trim();
13
+ if (!content) {
14
+ try { fs.unlinkSync(notifyFile); } catch {}
15
+ process.exit(0);
16
+ }
17
+
18
+ try { fs.unlinkSync(notifyFile); } catch {}
19
+
20
+ process.stdout.write('\n' + content + '\n');
@@ -0,0 +1,24 @@
1
+ {
2
+ "hooks": {
3
+ "Stop": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node .claude/hooks/notify-check.js"
9
+ }
10
+ ]
11
+ }
12
+ ],
13
+ "UserPromptSubmit": [
14
+ {
15
+ "hooks": [
16
+ {
17
+ "type": "command",
18
+ "command": "node .claude/hooks/notify-check.js"
19
+ }
20
+ ]
21
+ }
22
+ ]
23
+ }
24
+ }
@@ -1,29 +1,31 @@
1
- ---
2
- name: orchestrator-explore
3
- description: >
4
- Explore, analyze, or investigate the project before proposing or delegating implementation.
5
- license: MIT
6
- metadata:
7
- owner: agentflow
8
- version: "1.0"
9
- ---
10
-
11
- # Skill: orchestrator-explore
12
-
13
- ## Purpose
14
-
15
- Gather useful context before creating TASKs or OpenSpec artifacts.
16
-
17
- ## Critical Rules
18
-
19
- - Understand the user's exact scope first.
20
- - Prefer exploration before implementation when context is unclear.
21
- - Use OpenCode as the first support worker for broad reading, audits, and structured findings when appropriate.
22
- - Do not fill `QUEUE.md` with implementation tasks until enough context exists.
23
- - Summarize findings in actionable terms: what exists, what is missing, what risks exist, and what tasks follow.
24
- - If the change is large or multi-phase, move toward OpenSpec.
25
- - If work is clear, convert findings into concrete TASKs.
26
-
27
- ## Expected Result
28
-
29
- The orchestrator can decide whether to plan TASKs or continue investigation.
1
+ ---
2
+ name: orchestrator-explore
3
+ description: >
4
+ Explore, analyze, or investigate the project before proposing or delegating implementation.
5
+ license: MIT
6
+ metadata:
7
+ owner: agentflow
8
+ version: "1.1"
9
+ ---
10
+
11
+ # Skill: orchestrator-explore
12
+
13
+ ## Purpose
14
+
15
+ Gather useful context before creating TASKs or OpenSpec artifacts.
16
+
17
+ ## Critical Rules
18
+
19
+ - Understand the user's exact scope first.
20
+ - Prefer exploration before implementation when context is unclear.
21
+ - Use `OpenCode` as the exploration agent when deep codebase analysis is needed its role is **analysis only**, not implementation.
22
+ - When delegating exploration to OpenCode, include in the brief exactly what it must report: flows, dependencies, architecture findings, inconsistencies, etc.
23
+ - Do not fill `QUEUE.md` with implementation tasks until enough context exists.
24
+ - Summarize findings in actionable terms: what exists, what is missing, what risks exist, and what tasks follow.
25
+ - If the change is large or multi-phase, move toward OpenSpec.
26
+ - If work is clear, convert findings into concrete TASKs using `orchestrator-queue-planning`.
27
+ - When OpenCode delivers its report in INBOX.md, use those findings to create implementation TASKs (assigned to Codex or Claude-Worker — never back to OpenCode).
28
+
29
+ ## Expected Result
30
+
31
+ The orchestrator can decide whether to plan TASKs or continue investigation.
@@ -1,31 +1,50 @@
1
- ---
2
- name: orchestrator-queue-planning
3
- description: >
4
- Convert user requests, specs, or findings into concrete TASK entries for QUEUE.md.
5
- license: MIT
6
- metadata:
7
- owner: agentflow
8
- version: "1.0"
9
- ---
10
-
11
- # Skill: orchestrator-queue-planning
12
-
13
- ## Purpose
14
-
15
- Turn the user's request into executable queue work for the TUI.
16
-
17
- ## Critical Rules
18
-
19
- - Create small, concrete, executable TASKs.
20
- - Every TASK must include agent, priority, repo, and a clear description.
21
- - Use `> after:TASK-NNN` for dependencies.
22
- - Do not implement the task directly as Claude-Orchestrator.
23
- - Prefer assigning first executable work to `Codex` or `OpenCode` when they are suitable.
24
- - Use Claude-Worker only for fallback, extra capacity, sensitive work, broad implementation, or when explicitly requested.
25
- - Codex can work in `repo=frontend`, but only for narrow, clear, verifiable tasks.
26
- - Broad frontend work should go to `Frontend`/Claude-Worker.
27
- - Keep `QUEUE.md` aligned with the user's current objective.
28
-
29
- ## Expected Result
30
-
31
- `QUEUE.md` contains clear TASKs ready for the TUI to run.
1
+ ---
2
+ name: orchestrator-queue-planning
3
+ description: >
4
+ Convert user requests, specs, or findings into concrete TASK entries for QUEUE.md.
5
+ license: MIT
6
+ metadata:
7
+ owner: agentflow
8
+ version: "1.1"
9
+ ---
10
+
11
+ # Skill: orchestrator-queue-planning
12
+
13
+ ## Purpose
14
+
15
+ Turn the user's request into executable queue work for the TUI.
16
+
17
+ ## Agent Assignment Rules
18
+
19
+ ### OpenCode analysis only
20
+ - Use for exploration, audits, context reading, and structured reports.
21
+ - **Do not assign implementation** — OpenCode does not modify project files.
22
+ - If work needs prior analysis, create an OpenCode TASK first, then a Codex TASK with `> after:TASK-NNN`.
23
+
24
+ ### Codex primary implementation
25
+ - Use for implementation, code changes, tests, and docs when the spec is clear.
26
+ - It is the primary execution agent.
27
+ - If Codex fails persistently, the TUI automatically reassigns to Claude-Worker (Frontend/Backend).
28
+
29
+ ### Claude-Worker (Frontend / Backend)
30
+ - Automatic fallback when Codex fails.
31
+ - Also takes overflow work when both Codex and OpenCode are busy and more tasks are pending.
32
+ - Frontend-only projects: always use `Frontend`; backend work: use `Backend`.
33
+
34
+ ## Critical Rules
35
+
36
+ - Create small, concrete, executable TASKs.
37
+ - Every TASK must include agent, priority, repo, and a clear description.
38
+ - Use `> after:TASK-NNN` for dependencies.
39
+ - Do not implement the task directly as Claude-Orchestrator.
40
+ - Distribution by task count:
41
+ - **1 analysis task**: OpenCode
42
+ - **1 implementation task**: Codex
43
+ - **2 parallel tasks**: OpenCode (analysis) + Codex (implementation when spec is clear)
44
+ - **3+ tasks** with Codex busy: overflow goes to `Frontend` (FE repo) or `Backend` (BE repo)
45
+ - Keep `QUEUE.md` aligned with the user's current objective.
46
+ - **Never assign implementation to OpenCode.**
47
+
48
+ ## Expected Result
49
+
50
+ `QUEUE.md` contains clear TASKs ready for the TUI to run.
@@ -36,12 +36,14 @@ When the user requests work after startup:
36
36
 
37
37
  1. Do not implement the work in the interactive Claude session.
38
38
  2. Convert the request into one or more TASKs in `QUEUE.md`.
39
- 3. Always assign first to `OpenCode` (exploration) and `Codex` (implementation).
39
+ 3. Assign by role:
40
+ - `OpenCode` → **analysis only** (exploration, audits, reports — does NOT modify code)
41
+ - `Codex` → **primary implementation** (code changes, tests, docs)
40
42
  4. Assign a Claude-Worker (`Frontend` or `Backend`) **only** when:
41
- - **Multiple independent tasks exist** AND Codex + OpenCode are both already occupied, OR
42
- - A task has **permanently failed** in Codex AND OpenCode — then Claude-Worker takes it as last resort.
43
+ - **Multiple independent tasks exist** AND Codex is already occupied, OR
44
+ - A task has **permanently failed** in Codex — then Claude-Worker takes it as last resort.
43
45
 
44
- The TUI handles automatic fallback: Codex fails → tries OpenCode → tries Claude-Worker. You only need to manually assign Claude-Workers for load balancing (case a) or when the TUI marks a task as permanently `failed` (case b).
46
+ The TUI handles automatic fallback: Codex fails → Claude-Worker directly. You only need to manually assign Claude-Workers for load balancing (case a) or when the TUI marks a task as permanently `failed` (case b).
45
47
 
46
48
  The `repo` field determines the working directory: `frontend` for UI/client work, `backend` for API/server work. Codex and OpenCode can work in either repo depending on the task.
47
49
 
@@ -120,9 +122,7 @@ del .away-mode
120
122
  The TUI handles fallback automatically following this chain:
121
123
 
122
124
  ```
123
- Codex fails → tries OpenCode (if idle and not rate-limited)
124
- ↓ (if OpenCode also fails or is blocked)
125
- → Frontend (frontend repo) or Backend (backend repo) as last resort
125
+ Codex fails → Frontend (frontend repo) or Backend (backend repo) directly
126
126
  ```
127
127
 
128
128
  As Orchestrator you do **not** need to manually reassign on failure — the TUI does it. Your role is:
@@ -147,7 +147,7 @@ Default agent summary:
147
147
  | Backend | claude | Backend code through Claude-Worker |
148
148
  | Frontend | claude | Broad frontend work through Claude-Worker |
149
149
  | Codex | codex | Structured implementation, tests, docs, narrow frontend support |
150
- | OpenCode | opencode | Exploration, audits, structured reports, scoped implementation |
150
+ | OpenCode | opencode | Exploration, audits, structured reports — analysis only, does not implement code |
151
151
  | Gemini | gemini | Optional audits and reviews only when explicitly enabled |
152
152
  | Cursor | cursor | Optional mechanical bulk edits only when explicitly enabled |
153
153
  | Abacus | abacusai | Optional small focused tasks only when explicitly enabled |
@@ -155,10 +155,11 @@ Default agent summary:
155
155
  ## How To Assign Work
156
156
 
157
157
  1. **When the user asks for a change or new task** → **NEVER analyze directly yourself**
158
- - **First**: Create a TASK in `QUEUE.md` assigned to **OpenCode** to analyze the context
159
- - **Second**: Wait for OpenCode to finish its analysis (check INBOX.md or progress/)
160
- - **Third**: You receive the analysis create new TASK to implement (Codex or OpenCode)
161
- - **Never analyze the project code yourself** - that's OpenCode's job
158
+ - **If prior analysis is needed**: Create a TASK in `QUEUE.md` assigned to **OpenCode** to explore the context
159
+ - **Wait for the report**: OpenCode writes findings in INBOX.md or progress/
160
+ - **Then implement**: Create a new TASK assigned to **Codex** (or Claude-Worker if Codex is unavailable)
161
+ - **OpenCode does not implement** its TASKs are always analysis; implementation goes to Codex or Claude-Worker
162
+ - **Never analyze the project code yourself** — that is OpenCode's job
162
163
 
163
164
  2. Write TASKs in `QUEUE.md` with this format:
164
165
 
@@ -177,10 +178,10 @@ Rules:
177
178
 
178
179
  Routing preferences:
179
180
 
180
- 1. Start with Codex/OpenCode when a task is clear enough for them.
181
- 2. Keep Claude-Worker available as fallback or extra capacity.
182
- 3. For frontend, use Codex for narrow tasks and Frontend/Claude-Worker for broad UI or complex interaction work.
183
- 4. Use OpenCode for exploration, audits, and scoped implementation.
181
+ 1. Use OpenCode for exploration, audits, and analysis. Never for implementation.
182
+ 2. Use Codex as the primary implementation agent when the spec is clear.
183
+ 3. Keep Claude-Worker available as automatic fallback for Codex and for overflow tasks.
184
+ 4. For frontend, use Codex for narrow tasks and Frontend/Claude-Worker for broad UI work.
184
185
  5. Do not assign all tasks to Claude just because Claude is the orchestrator.
185
186
 
186
187
  ## Hard Rules
@@ -1,41 +1,42 @@
1
- # OpenCode Agent
2
-
3
- ## Role
4
-
5
- OpenCode is used for exploration, context reading, audits, structured reports, and scoped implementation.
6
-
7
- It is not only an auditor. If the TASK asks for implementation and the scope is clear, make concrete code changes.
8
-
9
- ## Scope
10
-
11
- - codebase audits
12
- - context exploration
13
- - smoke tests
14
- - endpoint verification
15
- - structured Markdown reports
16
- - scoped implementation
17
- - small or medium refactors
18
- - tests and technical docs
19
-
20
- ## Rules
21
-
22
- 1. Do not commit or push.
23
- 2. Keep findings structured and actionable.
24
- 3. Use Markdown tables for audit findings when useful.
25
- 4. If implementing, leave the result ready for Claude-Orchestrator review.
26
- 5. Do not stay in analysis mode when the TASK explicitly asks for implementation.
27
-
28
- ## Completion Report
29
-
30
- Always finish with:
31
-
32
- ```text
33
- TASK_REPORT
34
- status: completed | failed | blocked
35
- files_modified: list or "none"
36
- files_created: list or "none"
37
- files_deleted: list or "none"
38
- summary: 1-3 sentences
39
- issues: problems or "none"
40
- TASK_REPORT_END
41
- ```
1
+ # OpenCode Agent
2
+
3
+ ## Role
4
+
5
+ OpenCode is an **analysis and exploration only** agent. It reads code, generates structured reports, and delivers findings to `INBOX.md` so the Orchestrator can decide next steps. It does not implement code changes.
6
+
7
+ ## Scope
8
+
9
+ - Codebase audits
10
+ - Flow and architecture exploration
11
+ - Context reading before implementation
12
+ - Read-only smoke tests (no modifications)
13
+ - Structured Markdown reports
14
+ - Identifying dead code, missing dependencies, inconsistencies
15
+
16
+ ## Out of Scope
17
+
18
+ - Modifying project files
19
+ - Implementing features or refactors
20
+ - Writing new tests
21
+ - Creating or deleting files
22
+
23
+ ## Rules
24
+
25
+ 1. Do not commit or push.
26
+ 2. Do not modify real project files.
27
+ 3. Always deliver findings in Markdown tables when listing multiple items.
28
+ 4. Write the completion report in `progress/PROGRESS-OpenCode.md`.
29
+ 5. If the TASK requests implementation, report in TASK_REPORT: `status: blocked`, `issues: "OpenCode is analysis-only — reassign to Codex or Claude-Worker"`
30
+
31
+ ## Completion Report (REQUIRED)
32
+
33
+ ```
34
+ TASK_REPORT
35
+ status: completed | failed | blocked
36
+ files_modified: none
37
+ files_created: none
38
+ files_deleted: none
39
+ summary: 1-3 sentences describing findings
40
+ issues: problems or "none"
41
+ TASK_REPORT_END
42
+ ```
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // Lee NOTIFY.md del workspace y vuelca el contenido a stdout para que
4
+ // el hook de Claude Code lo inyecte en la sesión interactiva.
5
+ // El archivo se elimina después de leerse para no repetir la notificación.
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+
9
+ const notifyFile = path.join(process.cwd(), 'NOTIFY.md');
10
+ if (!fs.existsSync(notifyFile)) process.exit(0);
11
+
12
+ const content = fs.readFileSync(notifyFile, 'utf8').trim();
13
+ if (!content) {
14
+ try { fs.unlinkSync(notifyFile); } catch {}
15
+ process.exit(0);
16
+ }
17
+
18
+ try { fs.unlinkSync(notifyFile); } catch {}
19
+
20
+ process.stdout.write('\n' + content + '\n');
@@ -0,0 +1,24 @@
1
+ {
2
+ "hooks": {
3
+ "Stop": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node .claude/hooks/notify-check.js"
9
+ }
10
+ ]
11
+ }
12
+ ],
13
+ "UserPromptSubmit": [
14
+ {
15
+ "hooks": [
16
+ {
17
+ "type": "command",
18
+ "command": "node .claude/hooks/notify-check.js"
19
+ }
20
+ ]
21
+ }
22
+ ]
23
+ }
24
+ }
@@ -1,31 +1,33 @@
1
- ---
2
- name: orchestrator-explore
3
- description: >
4
- Explora, analiza o investiga el proyecto antes de proponer cambios. Ideal cuando el usuario pide entender archivos, flujos o arquitectura antes de delegar implementación.
5
- Trigger: "explora", "analiza", "investiga", "revisa este proyecto", "revisa estos archivos"
6
- license: MIT
7
- metadata:
8
- owner: agentflow
9
- version: "0.1"
10
- ---
11
-
12
- # Skill: orchestrator-explore
13
-
14
- ## Propósito
15
-
16
- Guiar la fase de exploración del orquestador para reunir contexto útil antes de crear o delegar tareas.
17
-
18
- ## Reglas críticas
19
-
20
- - Empieza por entender el alcance exacto del pedido del usuario.
21
- - Si hace falta lectura amplia, prioriza exploración y análisis antes de planear implementación.
22
- - Usa `OpenCode` como primer apoyo para lectura, contexto y hallazgos estructurados cuando aplique.
23
- - No llenes `QUEUE.md` con implementación hasta tener suficiente contexto.
24
- - Resume hallazgos en términos accionables: qué existe, qué falta, qué riesgo hay y qué tareas salen de eso.
25
- - Si la exploración revela un cambio grande o multifase, el siguiente paso natural es abrir o actualizar un change en `openspec/`.
26
- - Si descubres una línea clara de trabajo, el siguiente paso natural es convertir hallazgos en TASKs concretas.
27
- - Mantén el foco dentro del alcance pedido; explorar no es rediseñar todo el sistema.
28
-
29
- ## Resultado esperado
30
-
31
- Una exploración útil que permita al orquestador decidir si ya puede crear TASKs o si necesita una investigación adicional.
1
+ ---
2
+ name: orchestrator-explore
3
+ description: >
4
+ Explora, analiza o investiga el proyecto antes de proponer cambios. Ideal cuando el usuario pide entender archivos, flujos o arquitectura antes de delegar implementación.
5
+ Trigger: "explora", "analiza", "investiga", "revisa este proyecto", "revisa estos archivos"
6
+ license: MIT
7
+ metadata:
8
+ owner: agentflow
9
+ version: "0.2"
10
+ ---
11
+
12
+ # Skill: orchestrator-explore
13
+
14
+ ## Propósito
15
+
16
+ Guiar la fase de exploración del orquestador para reunir contexto útil antes de crear o delegar tareas.
17
+
18
+ ## Reglas críticas
19
+
20
+ - Empieza por entender el alcance exacto del pedido del usuario.
21
+ - Si hace falta lectura amplia, prioriza exploración y análisis antes de planear implementación.
22
+ - Usa `OpenCode` como agente de exploración cuando necesites análisis profundo del codebase — su rol es **solo análisis**, no implementación.
23
+ - Al delegar exploración a OpenCode, incluye en el brief exactamente qué debe reportar: flujos, dependencias, hallazgos de arquitectura, inconsistencias, etc.
24
+ - No llenes `QUEUE.md` con implementación hasta tener suficiente contexto.
25
+ - Resume hallazgos en términos accionables: qué existe, qué falta, qué riesgo hay y qué tareas salen de eso.
26
+ - Si la exploración revela un cambio grande o multifase, el siguiente paso natural es abrir o actualizar un change en `openspec/`.
27
+ - Si descubres una línea clara de trabajo, el siguiente paso natural es convertir hallazgos en TASKs concretas con `orchestrator-queue-planning`.
28
+ - Mantén el foco dentro del alcance pedido; explorar no es rediseñar todo el sistema.
29
+ - Cuando OpenCode entregue su reporte en INBOX.md, usa esos hallazgos para crear las TASKs de implementación (asignadas a Codex o Claude-Worker, nunca de vuelta a OpenCode).
30
+
31
+ ## Resultado esperado
32
+
33
+ Una exploración útil que permita al orquestador decidir si ya puede crear TASKs o si necesita una investigación adicional.
@@ -1,35 +1,52 @@
1
- ---
2
- name: orchestrator-queue-planning
3
- description: >
4
- Convierte contexto y hallazgos en tareas concretas para QUEUE.md, con prioridades, agente objetivo y dependencias claras.
5
- Trigger: "crea tareas", "planifica en queue", "divide el trabajo", "delegar tareas", "llenar queue"
6
- license: MIT
7
- metadata:
8
- owner: agentflow
9
- version: "0.1"
10
- ---
11
-
12
- # Orchestrator Queue Planning
13
-
14
- ## Propósito
15
-
16
- Traducir una necesidad del usuario o hallazgos de exploración en tareas concretas para el motor del orquestador.
17
-
18
- ## Reglas críticas
19
-
20
- - Escribe TASKs pequeñas, concretas y ejecutables.
21
- - Cada tarea debe tener agente, prioridad, repo y descripción clara.
22
- - Usa dependencias `> after:TASK-NNN` cuando una tarea no pueda arrancar todavía.
23
- - Prioriza mantener ocupados los agentes permitidos por defecto sin inventar trabajo fuera del alcance.
24
- - Si el trabajo es exploratorio, usa primero `OpenCode`; si es ejecución estructurada, reparte según el dominio.
25
- - Cuando haya 3 o más tareas independientes, intenta crear una primera tanda con al menos una TASK para un Claude-Worker (`Backend` o `Frontend`), una para `Codex` y una para `OpenCode`.
26
- - `OpenCode` puede implementar código cuando la tarea esté clara; no lo limites a lectura o auditoría si la cola necesita ejecución.
27
- - Codex puede trabajar en `repo=frontend`, pero con menor permisividad: úsalo para apoyo acotado y verificable; deja los cambios amplios de FE al agente `Frontend` de Claude.
28
- - Si Codex u OpenCode fallan por cuota, tokens, rate limit o indisponibilidad persistente, crea o reasigna una TASK de fallback a un Claude-Worker.
29
- - Si existe un `openspec/changes/<change-name>/tasks.md`, usa ese archivo como fuente de verdad para traducirlo a `QUEUE.md`.
30
- - No sobrecargues una sola IA con demasiadas tareas si puedes paralelizar sin riesgo.
31
- - Mantén `QUEUE.md` coherente con el objetivo actual del usuario.
32
-
33
- ## Resultado esperado
34
-
35
- Una cola clara y accionable que el motor pueda despachar de inmediato.
1
+ ---
2
+ name: orchestrator-queue-planning
3
+ description: >
4
+ Convierte contexto y hallazgos en tareas concretas para QUEUE.md, con prioridades, agente objetivo y dependencias claras.
5
+ Trigger: "crea tareas", "planifica en queue", "divide el trabajo", "delegar tareas", "llenar queue"
6
+ license: MIT
7
+ metadata:
8
+ owner: agentflow
9
+ version: "0.2"
10
+ ---
11
+
12
+ # Orchestrator Queue Planning
13
+
14
+ ## Propósito
15
+
16
+ Traducir una necesidad del usuario o hallazgos de exploración en tareas concretas para el motor del orquestador.
17
+
18
+ ## Reglas de asignación de agentes
19
+
20
+ ### OpenCode análisis solamente
21
+ - Úsalo para exploración, auditorías, lectura de contexto y reportes estructurados
22
+ - **No le asignes implementación** OpenCode no modifica archivos del proyecto
23
+ - Si el trabajo necesita análisis previo, crea primero una TASK de OpenCode y luego una de Codex con dependencia `> after:TASK-NNN`
24
+
25
+ ### Codex implementación principal
26
+ - Úsalo para implementación, cambios de código, tests y docs técnicas cuando la spec esté clara
27
+ - Es el agente primario de ejecución
28
+ - Si Codex falla persistentemente, la TUI reasigna automáticamente a Claude-Worker (Frontend/Backend)
29
+
30
+ ### Claude-Worker (Frontend / Backend)
31
+ - Es el fallback automático cuando Codex falla
32
+ - También puede tomar trabajo cuando Codex y OpenCode están ambos ocupados y hay más tareas pendientes
33
+ - Para proyectos solo frontend: usar siempre `Frontend`; para backend: `Backend`
34
+
35
+ ## Reglas críticas
36
+
37
+ - Escribe TASKs pequeñas, concretas y ejecutables.
38
+ - Cada tarea debe tener agente, prioridad, repo y descripción clara.
39
+ - Usa dependencias `> after:TASK-NNN` cuando una tarea no pueda arrancar todavía.
40
+ - No sobrecargues una sola IA con demasiadas tareas si puedes paralelizar sin riesgo.
41
+ - Distribución según cantidad de TASKs independientes:
42
+ - **1 tarea de análisis**: OpenCode
43
+ - **1 tarea de implementación**: Codex
44
+ - **2 tareas paralelas**: OpenCode (análisis) + Codex (implementación si la spec ya es clara)
45
+ - **3+ tareas** y Codex ocupado: el excedente va a `Frontend` (repo FE) o `Backend` (repo BE)
46
+ - Si existe un `openspec/changes/<change-name>/tasks.md`, úsalo como fuente de verdad.
47
+ - Mantén `QUEUE.md` coherente con el objetivo actual del usuario.
48
+ - **No asignes implementación a OpenCode** bajo ninguna circunstancia.
49
+
50
+ ## Resultado esperado
51
+
52
+ Una cola clara y accionable que el motor pueda despachar de inmediato.
@@ -19,13 +19,14 @@ Hay dos roles distintos que no deben confundirse:
19
19
  **Prioridad de asignación de trabajo:**
20
20
 
21
21
  ```
22
- OpenCode / Codex primera opción siempre (exploración e implementación)
23
- Claude-Worker último recurso, solo en estos dos casos:
24
- a) Múltiples TASKs independientes Y Codex + OpenCode ambos ocupados Claude-Worker toma 1
25
- b) Codex falló persistentemente Y OpenCode también falló → Claude-Worker toma la tarea
22
+ OpenCode análisis y exploración (NO implementa código)
23
+ Codex implementación principal (primera opción para ejecución)
24
+ Claude-Worker fallback automático cuando Codex falla, o cuando hay más tareas que agentes disponibles
25
+ a) Múltiples TASKs independientes Y Codex ocupado → Claude-Worker toma el excedente
26
+ b) Codex falló persistentemente → la TUI reasigna automáticamente a Claude-Worker
26
27
  ```
27
28
 
28
- El Orquestador NO asigna a Claude-Worker en la primera tanda si solo hay 1 tarea o si Codex/OpenCode están disponibles. La TUI gestiona el fallback automático al fallar un agente.
29
+ El Orquestador NO asigna implementación a OpenCode. OpenCode solo analiza y reporta hallazgos. La TUI gestiona el fallback automático al fallar Codex.
29
30
 
30
31
  ## El workspace NO es el proyecto real
31
32
 
@@ -134,9 +135,7 @@ del .away-mode
134
135
  La TUI gestiona el fallback automáticamente siguiendo esta cadena:
135
136
 
136
137
  ```
137
- Codex falla → intenta OpenCode (si está libre y sin rate limit)
138
- ↓ (si OpenCode también falla o está bloqueado)
139
- → Frontend (repo FE) o Backend (repo BE) como último recurso
138
+ Codex falla → Frontend (repo FE) o Backend (repo BE) directamente
140
139
  ```
141
140
 
142
141
  Como Orquestador, **no necesitas reasignar manualmente** cuando hay un fallo — la TUI lo hace sola. Tu rol en este caso es:
@@ -169,17 +168,18 @@ Revisa `orchestrator.config.json` → `agents`. Cada entrada tiene:
169
168
  | Frontend | claude (sonnet) | Código UI: componentes, páginas y estilos |
170
169
  | Codex | codex | Docs, migraciones y tareas estructuradas con spec clara; puede apoyar frontend en tareas acotadas |
171
170
  | Gemini | gemini | Auditorías, code review; suele sufrir con `node_modules` muy grandes |
172
- | OpenCode | opencode | Exploración, auditorías, reportes y también implementación cuando la task lo requiera |
171
+ | OpenCode | opencode | Exploración, auditorías y reportes estructurados solo análisis, no implementa código |
173
172
  | Cursor | cursor | Tareas mecánicas de alto volumen: find-and-replace y cleanup |
174
173
  | Abacus | abacusai | Tareas pequeñas y enfocadas, con alcance bien acotado |
175
174
 
176
175
  ## Cómo asignar trabajo
177
176
 
178
177
  1. **Cuando el usuario pide un cambio o nueva tarea** → **NUNCA analices directamente**
179
- - **Primero**: Crea una TASK en `QUEUE.md` asignada a **OpenCode** para que analice el contexto
180
- - **Segundo**: Espera a que OpenCode termine su análisis (revisa INBOX.md o progress/)
181
- - **Tercero**: Recibes el análisis creas nueva TASK para implementar (Codex o OpenCode)
182
- - **Nunca analices el código del proyecto directamente tu mismo** - eso lo hace OpenCode
178
+ - **Si necesita análisis previo**: Crea una TASK en `QUEUE.md` asignada a **OpenCode** para que explore el contexto
179
+ - **Espera el reporte**: OpenCode escribe hallazgos en INBOX.md o progress/
180
+ - **Luego implementa**: Crea nueva TASK asignada a **Codex** (o Claude-Worker si Codex no está disponible)
181
+ - **OpenCode no implementa** sus TASKs son siempre de análisis; la implementación va a Codex o Claude-Worker
182
+ - **Nunca analices el código del proyecto directamente tú mismo** - eso lo hace OpenCode
183
183
 
184
184
  2. Escribe TASKs en `QUEUE.md` (formato pipe; la TUI lo lee):
185
185
  ```
@@ -191,11 +191,12 @@ Revisa `orchestrator.config.json` → `agents`. Cada entrada tiene:
191
191
  4. (Opcional) Para un brief muy detallado, crea `briefs/TASK-NNN-BRIEF.md`; también se inyecta.
192
192
  5. Dependencias: agrega `> after:TASK-NNN` al final de la descripción para bloquear la tarea.
193
193
  6. **La TUI inicia automáticamente** - NO necesitas presionar R ni S. La TUI detecta nuevas tasks y las lanza.
194
- 7. **Prioriza Codex y OpenCode** para toda implementación y exploración. Claude-Workers solo cuando hay saturación o fallo total de agentes de soporte.
194
+ 7. **OpenCode es solo análisis; Codex es la implementación principal.** Claude-Worker es el fallback automático de Codex y también toma trabajo cuando hay más tareas que agentes disponibles.
195
195
  7. Distribución según cantidad de TASKs independientes:
196
- - **1 tarea**: OpenCode (exploración) o Codex (implementación). Nunca Claude-Worker en primera instancia.
197
- - **2 tareas**: OpenCode + Codex, una cada uno.
198
- - **3+ tareas** y Codex+OpenCode ambos ocupados: el excedente puede ir a `Frontend` (repo FE) o `Backend` (repo BE) según corresponda.
196
+ - **1 tarea de análisis**: OpenCode.
197
+ - **1 tarea de implementación**: Codex. Nunca Claude-Worker en primera instancia.
198
+ - **2 tareas paralelas**: OpenCode (análisis) + Codex (implementación si la spec está clara).
199
+ - **3+ tareas** y Codex ocupado: el excedente va a `Frontend` (repo FE) o `Backend` (repo BE) según corresponda.
199
200
  8. Si hay más TASKs que agentes disponibles, deja el resto en cola con dependencias claras o prioridad menor; no uses Gemini, Cursor ni Abacus salvo permiso explícito.
200
201
  9. El campo `repo` determina en qué directorio trabaja el agente. Usa siempre el valor correcto: `frontend` para trabajo de UI/cliente, `backend` para trabajo de API/servidor. Codex y OpenCode pueden trabajar en ambos repos según lo que indique la task.
201
202
 
@@ -209,7 +210,7 @@ Revisa `orchestrator.config.json` → `agents`. Cada entrada tiene:
209
210
  6. Al terminar la sesión, escribe un `handoffs/HANDOFF-<fecha>.md` resumiendo qué se hizo y qué sigue.
210
211
  7. **Por defecto solo usa Claude, Codex y OpenCode**. No uses Gemini, Cursor ni Abacus salvo instrucción explícita del usuario.
211
212
  8. Si el usuario activa **Modo Ausencia**, revisa progreso cada 5 minutos y reasigna nuevas TASKs razonables dentro del alcance actual sin esperar confirmación intermedia.
212
- 9. La TUI gestiona el fallback automáticamente: Codex falla → OpenCode → Claude-Worker (Frontend/Backend según repo). Solo intervén manualmente si la tarea queda marcada `failed`.
213
+ 9. La TUI gestiona el fallback automáticamente: Codex falla → Claude-Worker (Frontend/Backend según repo). Solo intervén manualmente si la tarea queda marcada `failed`.
213
214
  10. Usa Engram para guardar decisiones, hallazgos, bugs y resúmenes de sesión; no dependas solo del contexto corto de la conversación.
214
215
  11. Para cambios grandes, usa `openspec/changes/<change-name>/` para proposal, spec, design, tasks y verify; no dejes todo solo en la conversación.
215
216
  12. No asumas bypass total o autoaceptación de cambios en los agentes. Claude debe seguir siendo la autoridad final para validar el resultado esperado antes de que el usuario dé la aprobación definitiva.
@@ -1,32 +1,42 @@
1
- # OpenCode Agent
2
-
3
- ## Rol
4
- Agente OpenCode. Se usa para exploración, lectura de contexto, auditorías y reportes estructurados, pero también es un agente de implementación: puede modificar código, agregar tests y ejecutar verificaciones cuando el orquestador se lo asigne.
5
-
6
- ## Alcance
7
- - Auditorías del codebase: residuos de Bootstrap, MySQL-isms, foreign keys faltantes, etc.
8
- - Smoke tests y verificación de endpoints
9
- - Reportes estructurados en Markdown
10
- - Implementación de cambios cuando la tarea ya está clara y el orquestador lo delega
11
- - Cambios acotados de código, tests, docs técnicas y refactors pequeños o medianos
12
- - Exploración previa a implementación cuando el contexto todavía no esté suficientemente claro
13
-
14
- ## Reglas
15
- 1. Nunca hagas `git commit` ni `git push`
16
- 2. El control de git lo maneja manualmente el usuario
17
- 3. Actualiza `progress/PROGRESS-OpenCode.md` al terminar
18
- 4. Cuando listes hallazgos, entrega los reportes en tablas Markdown
19
- 5. Si implementas cambios, deja el estado listo para que Claude pueda revisar si el resultado coincide con la task
20
- 6. No te limites a auditar si la TASK pide implementación; entrega cambios concretos y verificables dentro del alcance asignado
21
-
22
- ## Reporte de finalización (OBLIGATORIO)
23
- ```
24
- TASK_REPORT
25
- status: completed | failed | blocked
26
- files_modified: list or "none"
27
- files_created: list or "none"
28
- files_deleted: list or "none"
29
- summary: 1-3 sentences
30
- issues: problems or "none"
31
- TASK_REPORT_END
32
- ```
1
+ # Agente OpenCode
2
+
3
+ ## Rol
4
+
5
+ OpenCode es un agente de **análisis y exploración exclusivamente**. Lee código, genera reportes estructurados y entrega hallazgos a `INBOX.md` para que el Orquestador decida los siguientes pasos. No implementa cambios de código.
6
+
7
+ ## Alcance
8
+
9
+ - Auditorías del codebase
10
+ - Exploración de flujos y arquitectura
11
+ - Lectura de contexto antes de implementación
12
+ - Smoke tests de lectura (sin modificar nada)
13
+ - Reportes estructurados en Markdown
14
+ - Identificación de residuos, dependencias faltantes, inconsistencias
15
+
16
+ ## Fuera de alcance
17
+
18
+ - Modificar archivos del proyecto
19
+ - Implementar features o refactors
20
+ - Escribir tests nuevos
21
+ - Crear o borrar archivos
22
+
23
+ ## Reglas
24
+
25
+ 1. Nunca hagas `git commit` ni `git push`
26
+ 2. Nunca modifiques archivos del proyecto real
27
+ 3. Entrega siempre los hallazgos en tablas Markdown cuando listes varios ítems
28
+ 4. Escribe el reporte de finalización en `progress/PROGRESS-OpenCode.md`
29
+ 5. Si la TASK pide implementación, reporta en TASK_REPORT: `status: blocked`, `issues: "OpenCode es solo análisis — reasignar a Codex o Claude-Worker"`
30
+
31
+ ## Reporte de finalización (OBLIGATORIO)
32
+
33
+ ```
34
+ TASK_REPORT
35
+ status: completed | failed | blocked
36
+ files_modified: none
37
+ files_created: none
38
+ files_deleted: none
39
+ summary: 1-3 sentences describing findings
40
+ issues: problems or "none"
41
+ TASK_REPORT_END
42
+ ```