orquestra-mcp 1.74.0 → 1.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orquestra-mcp",
3
- "version": "1.74.0",
3
+ "version": "1.77.0",
4
4
  "description": "Servidor MCP de Orquestra -- 161 tools para leer y escribir tareas, ideas, changelog, infraestructura, contenido, QA y más desde un agente de IA",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,30 @@
1
+ // ORQ-577: apps de Diseño / UI. El `app` viaja SIEMPRE en el query de la API (también en
2
+ // POST/PATCH/DELETE/bulk). Helpers puros, sin red.
3
+ import { DESIGN_PLATFORMS } from './designFlow.mjs'
4
+
5
+ export const APP_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/
6
+ export const APP_DESC = 'Key de la app (list_design_apps); obligatoria con varias apps'
7
+ export const APP_TOKEN_DESC = 'Key de la app (list_design_apps); omitido = token del proyecto, compartido'
8
+
9
+ // Saca de `body` (mutándolo) las claves que van al query y devuelve { clave: valor } con las definidas.
10
+ export function takeQuery(body, keys = []) {
11
+ const query = {}
12
+ for (const k of keys) {
13
+ if (k in body) {
14
+ if (body[k] !== undefined) query[k] = body[k]
15
+ delete body[k]
16
+ }
17
+ }
18
+ return query
19
+ }
20
+
21
+ export const arrayOf = r => (Array.isArray(r) ? r : Array.isArray(r?.items) ? r.items : [])
22
+
23
+ // Resumen compacto de una app: sus plataformas con los mismos conteos y su `next`.
24
+ export function summarizeAppStatus(app, status) {
25
+ const wanted = Array.isArray(app?.platforms) && app.platforms.length ? app.platforms : DESIGN_PLATFORMS
26
+ const platforms = Object.fromEntries(Object.entries(status.platforms).filter(([pl]) => wanted.includes(pl)))
27
+ const out = { key: app.key, name: app.name, platforms }
28
+ if (status.errors) out.errors = status.errors
29
+ return out
30
+ }
@@ -0,0 +1,319 @@
1
+ // ORQ-564: flujo guiado para llenar el módulo Diseño / UI. Datos estáticos, sin red
2
+ // (get_design_flow) + lógica pura de estado (computeDesignStatus, usada por get_design_status).
3
+ // El contenido largo vive aquí, en el VALOR que devuelve la tool, no en su descripción.
4
+
5
+ export const DESIGN_PLATFORMS = ['web', 'ios', 'android']
6
+
7
+ const PRINCIPLES = [
8
+ 'La web es la referencia: se carga primero y las demás plataformas reutilizan sus keys (list_design_nav platform=web).',
9
+ 'No inventes: registra solo lo que está en el código real de la plataforma (router, tab bar, temas, componentes).',
10
+ 'Un agente por plataforma a la vez. Evita cargas simultáneas del mismo nombre/key en el mismo catálogo (tokens, componentes): se pisan.',
11
+ 'Lotes compactos: tokens ≤100, nodos de navegación ≤40, componentes ≤200 por llamada; deja compact=true.',
12
+ 'Los nodos no se borran: se actualizan (upsert). Borrar es la excepción y solo con confirmación del usuario.',
13
+ 'Revisa siempre los `warnings` de la respuesta (tokens o usedIn inexistentes) y corrígelos antes de seguir.',
14
+ 'upsert_design_nav y upsert_design_components MEZCLAN actions/states/platforms por key; update_design_nav_node y update_design_component REEMPLAZAN el array completo.',
15
+ 'No crees tareas (create_parity_tasks, create_task) sin confirmar antes con el usuario.',
16
+ 'Cada paso termina cuando get_design_status lo confirma (el campo `next` avanza), no cuando tú lo sientes terminado.',
17
+ 'Antes de crear cualquier cosa llama a list_* para no duplicar.',
18
+ 'Una app a la vez: con varias apps (list_design_apps) pasa app=<key> en cada llamada y no mezcles apps en una misma pasada.',
19
+ 'Dentro de una app usa los mismos nombres de key en todas sus plataformas; la misma pantalla en OTRA app NO comparte key obligatoriamente.',
20
+ 'Tokens: sin app = token del proyecto (compartido por todas las apps); con app = token de esa app.',
21
+ ]
22
+
23
+ const GLOSSARY = {
24
+ actions: {
25
+ convention: 'entidad.verbo (task.create, project.archive). La misma operación lleva la MISMA key en web, iOS y Android.',
26
+ verbs: ['create', 'edit', 'delete', 'filter', 'search', 'sort', 'export', 'share', 'assign', 'comment', 'convert', 'archive', 'restore', 'open-detail', 'reorder', 'import', 'change-view'],
27
+ },
28
+ states: {
29
+ note: 'Registra solo los que existan en el código de esa pantalla.',
30
+ list: ['loading', 'empty', 'error', 'readonly', 'no-access', 'offline', 'refreshing', 'search-empty'],
31
+ },
32
+ blocks: [
33
+ 'Encabezado', 'Búsqueda', 'Filtros', 'Pestañas', 'Contenido de pestaña', 'Lista', 'Tablero', 'Tarjeta de elemento',
34
+ 'Estado vacío', 'Estado de error', 'Aviso', 'Acciones', 'Formulario', 'KPIs / Métricas', 'Resumen', 'Actividad reciente',
35
+ 'Navegación', 'Primeros pasos', 'Vista por rol', 'Asistente IA', 'Módulos', 'Plataformas / Infraestructura', 'Miembros',
36
+ 'Cuenta y sesión', 'Ajustes',
37
+ ],
38
+ components: [
39
+ 'Button', 'Card', 'Modal', 'Drawer', 'Input', 'Select', 'Checkbox', 'Toggle', 'Badge', 'Chip', 'Tabs', 'SegmentedControl',
40
+ 'ListRow', 'EmptyState', 'Toast', 'Banner', 'Avatar', 'DropdownMenu', 'ProgressBar', 'Tooltip', 'Topbar', 'Sidebar',
41
+ 'SearchBar', 'ConfirmDialog', 'DatePicker',
42
+ ],
43
+ }
44
+
45
+ const STEPS = [
46
+ {
47
+ id: 'apps', title: 'Apps del proyecto',
48
+ goal: 'Saber si el proyecto tiene varias apps de Diseño y trabajar una a la vez.',
49
+ tools: ['list_design_apps', 'migrate_design_apps', 'upsert_design_tokens'],
50
+ how: [
51
+ 'Llama list_design_apps. Con UNA app el parámetro `app` es opcional y todo funciona como siempre; con VARIAS es obligatorio en nav, componentes, paridad, deriva, sync y capturas (la API responde 400 con la lista si falta).',
52
+ 'Con varias apps, cárgalas una por una: cada app con sus plataformas (platforms de list_design_apps) y pasando app=<key> en cada llamada.',
53
+ 'Los tokens compartidos de marca van SIN app (valen para todas); los propios de una app van con app=<key> y pueden sobreescribir uno del proyecto.',
54
+ 'Si ya había datos de antes de tener apps, asígnalos con migrate_design_apps (dryRun:true informa; dryRun:false aplica) SOLO con confirmación del usuario.',
55
+ ],
56
+ doneWhen: 'Sabes qué app(s) existen y con cuál trabajas en esta pasada.',
57
+ pitfalls: ['Omitir `app` con varias apps (400).', 'Cargar tokens de marca con app (dejan de ser compartidos).', 'Correr migrate_design_apps con dryRun:false sin confirmar.'],
58
+ },
59
+ {
60
+ id: 'check', title: 'Revisar qué ya existe',
61
+ goal: 'Saber qué hay cargado en Diseño / UI para no duplicar ni pisar nada.',
62
+ tools: ['get_design_status', 'list_design_tokens', 'list_design_nav', 'list_design_components'],
63
+ how: [
64
+ 'Llama get_design_status: da conteos por plataforma y el primer paso pendiente (`next`).',
65
+ 'Si vas a trabajar una plataforma con datos previos, haz list_design_tokens / list_design_nav / list_design_components con ese platform antes de crear.',
66
+ 'Decide la plataforma de esta pasada (una por agente) y empieza por el `next` que indique el estado.',
67
+ ],
68
+ doneWhen: 'Sabes qué plataforma vas a trabajar y cuál es su primer paso pendiente.',
69
+ pitfalls: ['Crear sin listar primero genera duplicados.', 'Empezar por iOS/Android sin que la web tenga navegación cargada.'],
70
+ },
71
+ {
72
+ id: 'identity', title: 'Identidad: design tokens',
73
+ goal: 'Registrar colores, tipografía, radios, sombras, espaciado, iconos y logo de la plataforma.',
74
+ tools: ['list_design_tokens', 'upsert_design_tokens', 'create_design_token', 'update_design_token'],
75
+ how: [
76
+ 'Lee los archivos que DEFINEN el tema (web: theme/tokens.css/variables.css; iOS: Colors.swift/Theme; Android: Color.kt/Theme.kt), no los que lo usan.',
77
+ 'Usa nombres compartidos entre plataformas: brand, surface, page-bg, border, text-primary, text-secondary, text-tertiary, text-disabled, danger, success, warning, ai, radius-sm, radius-md, radius-lg, radius-pill, font-sans.',
78
+ 'Cada token: kind (color|typography|radius|shadow|spacing|icon-set|logo), value (modo claro) y valueDark si existe, platform, group y sourceRef (archivo y símbolo).',
79
+ 'Carga con upsert_design_tokens en lotes de hasta 100.',
80
+ 'Verifica con get_design_status (tokens > 0 para la plataforma).',
81
+ ],
82
+ doneWhen: 'get_design_status muestra tokens > 0 para la plataforma y los nombres coinciden con los de la web.',
83
+ pitfalls: ['Registrar valores hex que no están en el archivo del tema.', 'Nombres distintos por plataforma para lo mismo (impide comparar paridad).', 'Olvidar valueDark cuando el tema tiene modo oscuro.'],
84
+ },
85
+ {
86
+ id: 'navigation', title: 'Navegación: árbol de pantallas',
87
+ goal: 'Registrar el árbol de menús, secciones, pantallas, pestañas, acciones y overlays con keys estables entre plataformas.',
88
+ tools: ['list_design_nav', 'upsert_design_nav', 'update_design_nav_node', 'reorder_design_nav'],
89
+ how: [
90
+ 'Lee el router (web), el tab bar / NavigationStack (iOS) o el NavHost / bottom bar (Android) y el drawer o sidebar si existe.',
91
+ 'Cada nodo: kind (menu|section|screen|tab|action|overlay), name, key estable, parentKey, route.',
92
+ 'La WEB va primero y es la referencia. iOS y Android primero llaman list_design_nav platform=web y REUTILIZAN sus keys para las mismas pantallas; solo inventan keys para lo propio de su plataforma.',
93
+ 'Carga con upsert_design_nav en lotes de hasta 40 nodos (el padre puede ir en el mismo lote).',
94
+ 'Verifica con get_design_status (navNodes > 0).',
95
+ ],
96
+ doneWhen: 'navNodes > 0 y todas las pantallas del router/tab bar están cargadas con keys alineadas a la web.',
97
+ pitfalls: ['Keys nuevas en iOS/Android para pantallas que ya existen en web.', 'Pantallas sin parentKey (quedan en la raíz).', 'Lotes de más de 40 nodos.'],
98
+ },
99
+ {
100
+ id: 'blocks', title: 'Bloques de cada pantalla',
101
+ goal: 'Describir cada pantalla (kind screen/tab) como bloques de arriba a abajo.',
102
+ tools: ['upsert_design_nav', 'update_design_nav_node'],
103
+ how: [
104
+ 'Abre el código de cada pantalla y lista sus bloques en orden visual, de arriba a abajo.',
105
+ 'Usa los nombres del glosario (glossary.blocks) cuando el bloque sea genérico: Encabezado, Lista, Filtros, Estado vacío, etc. Para algo propio, un nombre corto y descriptivo.',
106
+ 'Cada bloque lleva name y, opcional, description corta.',
107
+ 'Actualiza con upsert_design_nav (misma platform+key): no se duplican nodos.',
108
+ ],
109
+ doneWhen: 'Al menos 50% de las pantallas tienen bloques (idealmente todas) según get_design_status.',
110
+ pitfalls: ['Describir el diseño ideal en vez del código real.', 'Nombres de bloque distintos para lo mismo entre plataformas.'],
111
+ },
112
+ {
113
+ id: 'actions-states', title: 'Acciones y estados por pantalla',
114
+ goal: 'Registrar qué puede hacer el usuario en cada pantalla y qué estados maneja; es lo que compara la paridad.',
115
+ tools: ['upsert_design_nav', 'update_design_nav_node'],
116
+ how: [
117
+ 'Acciones con key entidad.verbo (ej. task.create) y verbos estándar: create, edit, delete, filter, search, sort, export, share, assign, comment, convert, archive, restore, open-detail, reorder, import, change-view.',
118
+ 'Estados: loading, empty, error, readonly, no-access, offline, refreshing, search-empty. Solo los que existan en el código de esa pantalla.',
119
+ 'Misma key para la misma operación en las tres plataformas.',
120
+ 'upsert_design_nav MEZCLA actions/states por key; no repitas los ya cargados innecesariamente.',
121
+ ],
122
+ doneWhen: 'Al menos 50% de las pantallas tienen acciones (y estados donde aplique) según get_design_status.',
123
+ pitfalls: ['Registrar estados que la pantalla no maneja.', 'Verbos distintos para la misma operación (delete vs remove).', 'Usar update_design_nav_node y reemplazar sin querer el array completo.'],
124
+ },
125
+ {
126
+ id: 'components', title: 'Catálogo de componentes',
127
+ goal: 'Catalogar los componentes de UI reales con su referencia en código por plataforma.',
128
+ tools: ['list_design_components', 'upsert_design_components', 'update_design_component'],
129
+ how: [
130
+ 'Usa nombres canónicos: Button, Card, Modal, Drawer, Input, Select, Checkbox, Toggle, Badge, Chip, Tabs, SegmentedControl, ListRow, EmptyState, Toast, Banner, Avatar, DropdownMenu, ProgressBar, Tooltip, Topbar, Sidebar, SearchBar, ConfirmDialog, DatePicker.',
131
+ 'platforms[] con la platform de esta pasada y su sourceRef (archivo y símbolo).',
132
+ 'tokens y usedIn SOLO con nombres de tokens y keys de nav que ya existen (list_design_tokens, list_design_nav).',
133
+ 'Carga con upsert_design_components; revisa `warnings` y corrige.',
134
+ 'UN agente a la vez por catálogo: cargar el mismo name desde otra plataforma mezcla, pero en paralelo se pisan.',
135
+ ],
136
+ doneWhen: 'components > 0 para la plataforma y `warnings` vacío.',
137
+ pitfalls: ['Inventar tokens o usedIn que no existen.', 'Dos agentes cargando componentes al mismo tiempo.', 'Nombres distintos al canónico para el mismo componente.'],
138
+ },
139
+ {
140
+ id: 'parity', title: 'Paridad entre plataformas',
141
+ goal: 'Revisar huecos entre web, iOS y Android y fijar los que no aplican.',
142
+ tools: ['get_design_parity', 'set_design_parity_cell', 'create_parity_tasks'],
143
+ how: [
144
+ 'Llama get_design_parity con soloHuecos:true.',
145
+ 'Contenedores propios de cada plataforma (sidebar, tabbar, drawer, toolbar, grupos) se fijan not_applicable con set_design_parity_cell y un `reason` (obligatorio).',
146
+ 'Los huecos reales (different/missing) NO se corrigen aquí: preséntalos al usuario. Solo con su confirmación conviértelos en tareas con create_parity_tasks (máx. 50 por llamada).',
147
+ ],
148
+ doneWhen: 'Los huecos que quedan son reales y el usuario decidió qué hacer con ellos.',
149
+ pitfalls: ['Crear tareas sin confirmar.', 'Marcar not_applicable sin motivo (la API lo rechaza).', 'Marcar not_applicable un hueco real para que "salga verde".'],
150
+ },
151
+ {
152
+ id: 'drift', title: 'Deriva de tokens',
153
+ goal: 'Detectar valores de diseño escritos a mano fuera de los tokens.',
154
+ tools: ['report_design_drift', 'list_design_drift', 'update_design_drift', 'resolve_missing_design_drift'],
155
+ how: [
156
+ 'Guarda la hora de inicio de la pasada (Date.now()).',
157
+ 'Recorre el código de UNA plataforma buscando hex, radios, spacings y fuentes sueltos; ignora el archivo de definición del tema, tests, previews y valores dinámicos.',
158
+ 'Compara cada valor con los tokens de esa misma plataforma y propón suggestedToken si coincide.',
159
+ 'Reporta en lote con report_design_drift (hasta 200 por llamada).',
160
+ 'Solo tras una pasada COMPLETA, resolve_missing_design_drift en dryRun (platform + reportedBefore = hora de inicio); si es correcto, repite con dryRun:false.',
161
+ ],
162
+ doneWhen: 'La pasada completa de la plataforma está reportada y los hallazgos resueltos ya no aparecen.',
163
+ pitfalls: ['Resolver sin haber terminado la pasada completa.', 'Reportar el archivo del tema como deriva.', 'Mezclar plataformas en una misma pasada.'],
164
+ },
165
+ {
166
+ id: 'sync', title: 'Sincronía con el código (mantenimiento)',
167
+ goal: 'Detectar qué cambió en el código desde la última carga de Diseño / UI y mantener el catálogo al día.',
168
+ tools: ['check_design_sync', 'mark_design_synced', 'upsert_design_nav', 'upsert_design_components'],
169
+ how: [
170
+ 'Línea base: tras una carga completa de la plataforma, corre mark_design_synced con all:true (platform + repoPath absoluto del repo) para guardar la huella de cada archivo citado en sourceRef.',
171
+ 'Después, corre check_design_sync periódicamente o tras merges: compara la huella local con la guardada y marca como outdated lo que cambió.',
172
+ 'Los `changed` se vuelven a leer en el código y se actualizan con upsert_design_nav / upsert_design_components.',
173
+ 'Luego mark_design_synced SOLO de esos (nav: keys, components: nombres) para sellar la nueva huella y limpiar outdated.',
174
+ 'Nada se borra solo: un archivo que ya no existe aparece como no-existe y lo decide el usuario.',
175
+ ],
176
+ doneWhen: 'check_design_sync no reporta `changed` ni `baselineMissing` para la plataforma.',
177
+ pitfalls: ['Usar mark_design_synced sin haber revisado lo que cambió (oculta el cambio).', 'Pasar el repoPath de otra plataforma.', 'Borrar nodos porque su archivo no existe sin confirmar con el usuario.'],
178
+ },
179
+ {
180
+ id: 'screenshots', title: 'Capturas (opcional)',
181
+ goal: 'Adjuntar capturas a las pantallas clave.',
182
+ tools: ['add_design_screenshot', 'remove_design_screenshot'],
183
+ how: [
184
+ 'Para cada pantalla clave: add_design_screenshot con platform, key del nodo y la ruta del archivo (png/jpg/webp ≤5 MB).',
185
+ 'Para marketing, nunca captures el workspace real: usa un usuario demo con datos poblados.',
186
+ ],
187
+ doneWhen: 'Las pantallas clave tienen captura, o el usuario decide omitir este paso.',
188
+ pitfalls: ['Capturas con datos reales de clientes.', 'Archivos fuera de png/jpg/webp o mayores a 5 MB.'],
189
+ },
190
+ ]
191
+
192
+ // order derivado de la posición: insertar un paso no obliga a renumerar a mano.
193
+ STEPS.forEach((st, i) => { st.order = i + 1 })
194
+
195
+ const PLATFORM_LABEL = { web: 'web (React)', ios: 'iOS (Swift)', android: 'Android (Kotlin)' }
196
+
197
+ function adjustStep(step, platform, app) {
198
+ const s = { ...step, how: [...step.how], pitfalls: [...step.pitfalls], tools: [...step.tools] }
199
+ if (step.id === 'navigation' && platform !== 'web') {
200
+ s.how.unshift('PRIMERO lee list_design_nav platform=web (tree o plano) y reutiliza sus keys para las mismas pantallas.')
201
+ }
202
+ if (step.id === 'navigation' && platform === 'web') {
203
+ s.how.unshift('Eres la referencia: define keys estables y claras (iOS y Android las reutilizarán).')
204
+ }
205
+ if (step.id === 'drift' || step.id === 'identity' || step.id === 'components') {
206
+ s.how.push(`Trabaja SOLO platform=${platform} en esta pasada.`)
207
+ }
208
+ if (app) s.how.push(`Trabaja SOLO app=${app}: pásala en cada llamada de este paso.`)
209
+ return s
210
+ }
211
+
212
+ function buildAgentPrompt(platform, steps, app) {
213
+ const ids = steps.map(s => `${s.order}. ${s.id}`).join('; ')
214
+ const webNote = platform === 'web'
215
+ ? 'La web es la referencia: define keys y nombres estables, porque iOS y Android los reutilizarán.'
216
+ : 'Antes de crear nodos lee list_design_nav platform=web y reutiliza sus keys; la web es la referencia.'
217
+ return [
218
+ `Vas a llenar el módulo Diseño / UI de Orquestra para la plataforma ${PLATFORM_LABEL[platform]}${app ? ` de la app "${app}"` : ''}, leyendo su código real. Trabaja SOLO esta plataforma${app ? ' y esta app' : ''} y no inventes nada que no esté en el código.`,
219
+ app
220
+ ? `Pasa app="${app}" en TODAS las llamadas de Diseño (tokens propios de la app con app; los de marca compartidos van sin app). Las keys son las de esta app: la misma pantalla en otra app no comparte key obligatoriamente.`
221
+ : 'Si list_design_apps devuelve varias apps, pide cuál trabajar y pasa app=<key> en todas las llamadas; con una sola app no hace falta.',
222
+ webNote,
223
+ `Pasos en orden (ids de get_design_flow): ${ids}.`,
224
+ 'Empieza llamando get_design_status: su campo `next` te dice el primer paso pendiente de tu plataforma. Para cada paso llama get_design_flow con step=<id> y sigue sus `how`, usando los `tools` indicados.',
225
+ 'Reglas: llama list_* antes de crear para no duplicar; lotes compactos (tokens ≤100, nodos ≤40, componentes ≤200); revisa los `warnings`; no borres nodos, actualízalos; no crees tareas sin confirmar con el usuario; un paso termina cuando get_design_status lo confirma.',
226
+ 'Al terminar cada paso vuelve a llamar get_design_status y avanza al nuevo `next`. Cuando todo esté cargado, resume al usuario los huecos de paridad y la deriva abierta y pregúntale qué hacer.',
227
+ ].join('\n')
228
+ }
229
+
230
+ export const DESIGN_PLATFORM_ARGS = ['web', 'ios', 'android', 'all']
231
+ export const STEP_IDS = STEPS.map(s => s.id)
232
+
233
+ // Devuelve { error } si el step no existe (la tool lo convierte en un 404 amable).
234
+ export function getDesignFlow({ platform = 'all', step, app } = {}) {
235
+ const adjust = platform === 'all' ? s => s : s => adjustStep(s, platform, app)
236
+ const base = { version: 1, platform, ...(app ? { app } : {}), principles: PRINCIPLES, glossary: GLOSSARY }
237
+ if (step) {
238
+ const found = STEPS.find(s => s.id === step)
239
+ if (!found) return { error: `Error (404): no existe el paso "${step}". Pasos disponibles: ${STEP_IDS.join(', ')}.` }
240
+ return { ...base, steps: [adjust(found)] }
241
+ }
242
+ const steps = STEPS.map(adjust)
243
+ const out = { ...base, steps }
244
+ if (platform !== 'all') out.agentPrompt = buildAgentPrompt(platform, steps, app)
245
+ return out
246
+ }
247
+
248
+ // ── get_design_status: lógica pura sobre las respuestas de la API ──────────────
249
+ const arr = r => (Array.isArray(r) ? r : Array.isArray(r?.items) ? r.items : [])
250
+ const nonEmpty = a => Array.isArray(a) && a.length > 0
251
+ const isScreen = n => n?.kind === 'screen' || n?.kind === 'tab'
252
+
253
+ function pickParity(parity, platform) {
254
+ const s = parity?.summary
255
+ const row = s?.[platform] || s?.byPlatform?.[platform]
256
+ if (!row || typeof row !== 'object') return null
257
+ const n = k => Number(row[k] ?? row[k.replace('_', '')] ?? 0) || 0
258
+ return { same: n('same'), different: n('different'), missing: n('missing'), not_applicable: n('not_applicable') }
259
+ }
260
+
261
+ function nextStep(p) {
262
+ if (!p.tokens) return { next: 'identity', reason: 'No hay design tokens cargados para esta plataforma.' }
263
+ if (!p.navNodes) return { next: 'navigation', reason: 'No hay nodos de navegación cargados para esta plataforma.' }
264
+ const screens = p.screens
265
+ if (screens && p.screensWithBlocks < screens / 2) return { next: 'blocks', reason: `Solo ${p.screensWithBlocks} de ${screens} pantallas tienen bloques (meta: al menos 50%).` }
266
+ if (screens && p.screensWithActions < screens / 2) return { next: 'actions-states', reason: `Solo ${p.screensWithActions} de ${screens} pantallas tienen acciones (meta: al menos 50%).` }
267
+ if (!p.components) return { next: 'components', reason: 'No hay componentes catalogados para esta plataforma.' }
268
+ const par = p.parity
269
+ if (par && (par.different + par.missing) > 0) return { next: 'parity', reason: `Hay ${par.different + par.missing} huecos de paridad (different/missing) por revisar.` }
270
+ if (p.driftOpen > 0) return { next: 'drift', reason: `Hay ${p.driftOpen} hallazgos de deriva abiertos.` }
271
+ return { next: 'parity', reason: 'Lo básico está cargado; revisa la paridad y, si quieres, corre la pasada de deriva (drift).' }
272
+ }
273
+
274
+ // results: { tokens, nav: {web,ios,android}, components, drift, parity } — cada uno puede ser { error }
275
+ export function computeDesignStatus(results) {
276
+ const errors = []
277
+ const ok = (key, v) => { if (v?.__error) { errors.push({ source: key, error: v.__error }); return null } return v }
278
+ const tokens = arr(ok('tokens', results.tokens))
279
+ const components = arr(ok('components', results.components))
280
+ const driftRaw = ok('drift', results.drift)
281
+ const drift = arr(driftRaw)
282
+ const parity = ok('parity', results.parity)
283
+ const syncRes = {}
284
+ for (const pl of DESIGN_PLATFORMS) syncRes[pl] = ok(`sync:${pl}`, results.sync?.[pl])
285
+ const platforms = {}
286
+ for (const pl of DESIGN_PLATFORMS) {
287
+ const nav = arr(ok(`nav:${pl}`, results.nav?.[pl]))
288
+ const screens = nav.filter(isScreen)
289
+ const p = {
290
+ tokens: tokens.filter(t => (t.platform || 'all') === pl || t.platform === 'all' || !t.platform).length,
291
+ navNodes: nav.length,
292
+ screens: screens.length,
293
+ screensWithBlocks: screens.filter(n => nonEmpty(n.blocks)).length,
294
+ screensWithActions: screens.filter(n => nonEmpty(n.actions)).length,
295
+ screensWithStates: screens.filter(n => nonEmpty(n.states)).length,
296
+ components: components.filter(c => arr(c.platforms).some(x => x?.platform === pl)).length,
297
+ driftOpen: drift.filter(d => d.platform === pl && (d.status || 'open') === 'open').length,
298
+ parity: pickParity(parity, pl),
299
+ }
300
+ if (!drift.length && driftRaw?.summary?.byPlatform?.[pl] != null) {
301
+ const bp = driftRaw.summary.byPlatform[pl]
302
+ p.driftOpen = typeof bp === 'number' ? bp : Number(bp?.open ?? 0)
303
+ }
304
+ const sy = syncRes[pl]
305
+ if (sy) {
306
+ const sum = k => Number(sy.summary?.nav?.[k] ?? 0) + Number(sy.summary?.components?.[k] ?? 0)
307
+ p.sync = { withHash: sum('withHash'), outdated: sum('outdated'), stale: sum('stale') }
308
+ }
309
+ Object.assign(p, nextStep(p))
310
+ if (p.sync?.outdated > 0) {
311
+ p.next = 'sync'
312
+ p.reason = `Hay ${p.sync.outdated} elementos marcados como desactualizados respecto al código; revísalos con check_design_sync.`
313
+ }
314
+ platforms[pl] = p
315
+ }
316
+ const out = { platforms, parity: { capabilitiesNodes: parity?.capabilitiesNodes ?? null } }
317
+ if (errors.length) out.errors = errors
318
+ return out
319
+ }
@@ -0,0 +1,148 @@
1
+ // ORQ-575: detección de cambios del código desde la última carga de Diseño / UI.
2
+ // Lógica pura y testeable: huellas locales (sha1 de los bytes) de los archivos que citan los
3
+ // sourceRef, comparadas con el sourceHash guardado en Orquestra. Las funciones reciben la API
4
+ // por parámetro (io) para poder probarlas sin red.
5
+ import { createHash } from 'node:crypto'
6
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
7
+ import path from 'node:path'
8
+
9
+ export const MAX_FILE_BYTES = 2 * 1024 * 1024
10
+ export const BATCH_SIZE = 40
11
+ export const LIST_CAP = 100
12
+
13
+ const PATH_RE_ORDERED = /[\w@.\-/]+\.(?:json|jsx|js|tsx|ts|mjs|cjs|css|swift|kts|kt|xml|md)(?![\w])/
14
+
15
+ // Primer fragmento con pinta de ruta de archivo dentro de un sourceRef, o null.
16
+ export function extractSourcePath(sourceRef) {
17
+ if (typeof sourceRef !== 'string') return null
18
+ const m = sourceRef.match(PATH_RE_ORDERED)
19
+ return m ? m[0] : null
20
+ }
21
+
22
+ // → { status: 'ok', hash } | { status: 'no-existe' | 'fuera-del-repo' | 'demasiado-grande' }
23
+ export function hashFile(repoPath, relPath) {
24
+ let repoReal
25
+ try { repoReal = realpathSync(repoPath) } catch { return { status: 'no-existe' } }
26
+ const inside = p => p === repoReal || p.startsWith(repoReal + path.sep)
27
+ const lexical = path.resolve(repoReal, relPath)
28
+ if (!inside(lexical)) return { status: 'fuera-del-repo' }
29
+ let real
30
+ try { real = realpathSync(lexical) } catch { return { status: 'no-existe' } }
31
+ if (!inside(real)) return { status: 'fuera-del-repo' }
32
+ let st
33
+ try { st = statSync(real) } catch { return { status: 'no-existe' } }
34
+ if (!st.isFile()) return { status: 'no-existe' }
35
+ if (st.size > MAX_FILE_BYTES) return { status: 'demasiado-grande' }
36
+ try {
37
+ return { status: 'ok', hash: createHash('sha1').update(readFileSync(real)).digest('hex') }
38
+ } catch { return { status: 'no-existe' } }
39
+ }
40
+
41
+ const chunk = (a, n) => { const out = []; for (let i = 0; i < a.length; i += n) out.push(a.slice(i, i + n)); return out }
42
+ const arr = v => (Array.isArray(v) ? v : [])
43
+
44
+ const STATUS_BUCKET = {
45
+ unchanged: 'unchanged', changed: 'changed', 'baseline-missing': 'baselineMissing',
46
+ 'no-existe': 'missing', 'fuera-del-repo': 'outsideRepo', 'demasiado-grande': 'tooBig', 'sin-ruta': 'noPath',
47
+ }
48
+
49
+ // Clasifica un item de /v1/design-sync contra el repo local. cache: Map ruta → resultado de hashFile.
50
+ export function classifyItem(item, repoPath, cache = new Map()) {
51
+ const rel = extractSourcePath(item?.sourceRef)
52
+ if (!rel) return { state: 'sin-ruta', path: null }
53
+ if (!cache.has(rel)) cache.set(rel, hashFile(repoPath, rel))
54
+ const h = cache.get(rel)
55
+ if (h.status !== 'ok') return { state: h.status, path: rel }
56
+ if (!item.sourceHash) return { state: 'baseline-missing', path: rel, hash: h.hash }
57
+ return { state: h.hash === item.sourceHash ? 'unchanged' : 'changed', path: rel, hash: h.hash }
58
+ }
59
+
60
+ function emptySummary() {
61
+ return { unchanged: 0, changed: 0, baselineMissing: 0, missing: 0, outsideRepo: 0, tooBig: 0, noPath: 0 }
62
+ }
63
+
64
+ // io: { fetchSync(), fetchCategories(), writeNav(nodes), writeComponents(components) }
65
+ export async function runCheck({ platform, repoPath, record = true }, io) {
66
+ const data = await io.fetchSync()
67
+ const nav = arr(data?.nav)
68
+ const components = arr(data?.components)
69
+ const cache = new Map()
70
+ const summary = { nav: emptySummary(), components: emptySummary() }
71
+ const changed = []
72
+ const toMark = { nav: [], components: [] }
73
+ for (const [kind, list] of [['nav', nav], ['component', components]]) {
74
+ for (const it of list) {
75
+ const c = classifyItem(it, repoPath, cache)
76
+ summary[kind === 'nav' ? 'nav' : 'components'][STATUS_BUCKET[c.state]]++
77
+ if (c.state === 'changed') {
78
+ changed.push({ kind, ...(kind === 'nav' ? { key: it.key } : { name: it.name }), path: c.path })
79
+ if (!it.outdated) toMark[kind === 'nav' ? 'nav' : 'components'].push(it)
80
+ }
81
+ }
82
+ }
83
+ const out = { platform, repoPath, summary }
84
+ out.changed = changed.slice(0, LIST_CAP)
85
+ if (changed.length > LIST_CAP) out.changedTruncated = changed.length - LIST_CAP
86
+ const stale = [...nav, ...components].filter(i => i.stale).map(i => i.name || i.key)
87
+ out.stale = stale.slice(0, LIST_CAP)
88
+ if (stale.length > LIST_CAP) out.staleTruncated = stale.length - LIST_CAP
89
+ if (record !== false) {
90
+ let navMarked = 0, compMarked = 0
91
+ for (const part of chunk(toMark.nav, BATCH_SIZE)) {
92
+ await io.writeNav(part.map(n => ({ platform, kind: n.kind, name: n.name, key: n.key, outdated: true })))
93
+ navMarked += part.length
94
+ }
95
+ if (toMark.components.length) {
96
+ const cats = await io.fetchCategories()
97
+ for (const part of chunk(toMark.components, BATCH_SIZE)) {
98
+ await io.writeComponents(part.map(c => ({ name: c.name, category: cats.get(c.name) || 'other', platforms: [{ platform, outdated: true }] })))
99
+ compMarked += part.length
100
+ }
101
+ }
102
+ out.markedOutdated = { nav: navMarked, components: compMarked }
103
+ } else {
104
+ out.markedOutdated = { nav: 0, components: 0, note: 'record:false, no se escribió nada' }
105
+ }
106
+ return out
107
+ }
108
+
109
+ export async function runMark({ platform, repoPath, nav, components, all }, io) {
110
+ const navKeys = arr(nav), compNames = arr(components)
111
+ if (!all && !navKeys.length && !compNames.length) {
112
+ throw new Error('Indica qué marcar: all:true (línea base de todo lo que tenga sourceRef), nav (keys) o components (nombres).')
113
+ }
114
+ const data = await io.fetchSync()
115
+ const navItems = arr(data?.nav), compItems = arr(data?.components)
116
+ const unresolved = []
117
+ const pick = (items, wanted, idOf, kind) => {
118
+ if (all) return items.filter(i => extractSourcePath(i.sourceRef) || (unresolved.push({ kind, [idOf]: i[idOf], reason: 'sin-ruta' }), false))
119
+ const out = []
120
+ for (const w of wanted) {
121
+ const it = items.find(i => i[idOf] === w)
122
+ if (!it) unresolved.push({ kind, [idOf]: w, reason: 'no-encontrado' })
123
+ else out.push(it)
124
+ }
125
+ return out
126
+ }
127
+ const navSel = pick(navItems, navKeys, 'key', 'nav')
128
+ const compSel = pick(compItems, compNames, 'name', 'component')
129
+ const cache = new Map()
130
+ const resolve = (it, kind, idOf) => {
131
+ const c = classifyItem(it, repoPath, cache)
132
+ if (!c.hash) { unresolved.push({ kind, [idOf]: it[idOf], reason: c.state }); return null }
133
+ return c.hash
134
+ }
135
+ const navW = [], compW = []
136
+ for (const it of navSel) { const h = resolve(it, 'nav', 'key'); if (h) navW.push({ platform, kind: it.kind, name: it.name, key: it.key, sourceHash: h }) }
137
+ const compPairs = []
138
+ for (const it of compSel) { const h = resolve(it, 'component', 'name'); if (h) compPairs.push({ name: it.name, h }) }
139
+ for (const part of chunk(navW, BATCH_SIZE)) await io.writeNav(part)
140
+ if (compPairs.length) {
141
+ const cats = await io.fetchCategories()
142
+ for (const p of compPairs) compW.push({ name: p.name, category: cats.get(p.name) || 'other', platforms: [{ platform, sourceHash: p.h }] })
143
+ for (const part of chunk(compW, BATCH_SIZE)) await io.writeComponents(part)
144
+ }
145
+ const out = { platform, repoPath, marked: { nav: navW.length, components: compW.length }, unresolved: unresolved.slice(0, LIST_CAP) }
146
+ if (unresolved.length > LIST_CAP) out.unresolvedTruncated = unresolved.length - LIST_CAP
147
+ return out
148
+ }
package/src/server.mjs CHANGED
@@ -13,6 +13,9 @@ import { SKILLS_CATALOG } from './skillsCatalog.mjs'
13
13
  import { parseSource, previewSkill, installSkill } from './skillInstall.mjs'
14
14
  import { normalizeStatuses, findClosePath } from './closePath.mjs'
15
15
  import { TOOL_GUIDES, GUIDE_TOPICS } from './toolGuides.mjs'
16
+ import { runCheck, runMark } from './designSync.mjs'
17
+ import { APP_SLUG_RE, APP_DESC, APP_TOKEN_DESC, takeQuery, arrayOf, summarizeAppStatus } from './designApps.mjs'
18
+ import { getDesignFlow, computeDesignStatus, DESIGN_PLATFORM_ARGS, DESIGN_PLATFORMS } from './designFlow.mjs'
16
19
 
17
20
  // Versión leída de package.json (3 sep 2026) -- antes estaba hardcodeada
18
21
  // aquí y quedaba atrás en cada bump (decía 1.16.0 con package.json en 1.16.2).
@@ -323,15 +326,16 @@ export function createServer() {
323
326
 
324
327
  // `post(data, body, pid)` (opcional) decora la respuesta tras crear y puede quitar campos del body antes del POST
325
328
  // con `pre(body)`; create_task lo usa para el checklist (ORQ-535).
326
- function registerCreate(name, path, description, extraSchema, { pre, post } = {}) {
329
+ function registerCreate(name, path, description, extraSchema, { pre, post, query: queryKeys = [] } = {}) {
327
330
  server.registerTool(
328
331
  name,
329
332
  { description, inputSchema: { projectId: z.string().optional().describe(PROJECT_ID_DESC), ...extraSchema } },
330
333
  async ({ projectId, ...body }) => {
331
334
  try {
332
335
  const pid = resolveProjectId(projectId)
336
+ const query = takeQuery(body, queryKeys)
333
337
  const extra = pre ? pre(body) : undefined
334
- const data = await apiPost(config, path, { projectId: pid, ...body })
338
+ const data = await apiPost(config, path, { projectId: pid, ...body }, query)
335
339
  return textResult(post ? await post(data, extra, pid) : data)
336
340
  } catch (err) {
337
341
  return errorResult(err)
@@ -340,7 +344,7 @@ export function createServer() {
340
344
  )
341
345
  }
342
346
 
343
- function registerUpdate(name, path, description, extraSchema, { idAlias, compact } = {}) {
347
+ function registerUpdate(name, path, description, extraSchema, { idAlias, compact, query: queryKeys = [] } = {}) {
344
348
  server.registerTool(
345
349
  name,
346
350
  {
@@ -359,8 +363,9 @@ export function createServer() {
359
363
  try {
360
364
  const { projectId, id: idArg, compact: wantsCompact, ...rest } = args
361
365
  if (idAlias) delete rest[idAlias]
366
+ const query = takeQuery(rest, queryKeys)
362
367
  const id = idAlias ? resolveAlias({ id: idArg, [idAlias]: args[idAlias] }, 'id', idAlias) : idArg
363
- const data = await apiPatch(config, path, { projectId: resolveProjectId(projectId), id, ...rest })
368
+ const data = await apiPatch(config, path, { projectId: resolveProjectId(projectId), id, ...rest }, query)
364
369
  return textResult(compact && wantsCompact ? compactTaskResult(data, Object.keys(rest).filter(k => k !== 'opId' && k !== 'comment')) : data)
365
370
  } catch (err) {
366
371
  return errorResult(err)
@@ -2901,6 +2906,8 @@ export function createServer() {
2901
2906
  )
2902
2907
 
2903
2908
  // ═══ IDENTIDAD DE DISEÑO (ORQ-560) ═════════════════════════════════════════
2909
+ const APP_STR = z.string().max(40).regex(APP_SLUG_RE, 'slug: minúsculas, números, - o _')
2910
+ const appArg = desc => APP_STR.optional().describe(desc || APP_DESC)
2904
2911
  const DESIGN_TOKEN_KINDS = ['color', 'typography', 'radius', 'shadow', 'spacing', 'logo', 'icon-set']
2905
2912
  const DESIGN_TOKEN_PLATFORMS = ['all', 'web', 'ios', 'android']
2906
2913
  const DESIGN_TOKEN_VARIANTS = ['light', 'dark', 'icon']
@@ -2930,15 +2937,17 @@ export function createServer() {
2930
2937
  {
2931
2938
  kind: z.enum(DESIGN_TOKEN_KINDS).optional().describe('Filtra por tipo'),
2932
2939
  platform: z.enum(DESIGN_TOKEN_PLATFORMS).optional().describe('Filtra por plataforma (los "all" cuentan como all)'),
2940
+ app: appArg(APP_TOKEN_DESC),
2941
+ scope: z.enum(['own']).optional().describe('own = solo los propios de la app (requiere app); omitido = efectivos (proyecto + app)'),
2933
2942
  },
2934
- (args, projectId) => ({ projectId, kind: args.kind, platform: args.platform })
2943
+ (args, projectId) => ({ projectId, kind: args.kind, platform: args.platform, app: args.app, scope: args.scope })
2935
2944
  )
2936
2945
  registerCreate('create_design_token', '/v1/design-tokens',
2937
2946
  `Crea un token de identidad de diseño. ${DESIGN_TOKEN_PURPOSE} Para cargar muchos de una vez usa upsert_design_tokens, no esta tool en bucle.`,
2938
- designTokenFields(false))
2947
+ { ...designTokenFields(false), app: appArg(APP_TOKEN_DESC) }, { query: ['app'] })
2939
2948
  registerUpdate('update_design_token', '/v1/design-tokens',
2940
2949
  `Edita un token de identidad de diseño existente (parche parcial: manda solo lo que cambia). ${DESIGN_TOKEN_PURPOSE}`,
2941
- designTokenFields(true))
2950
+ { ...designTokenFields(true), app: appArg(APP_TOKEN_DESC) }, { query: ['app'] })
2942
2951
 
2943
2952
  server.registerTool(
2944
2953
  'delete_design_token',
@@ -2947,11 +2956,12 @@ export function createServer() {
2947
2956
  inputSchema: {
2948
2957
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
2949
2958
  tokenId: z.string().describe('ID del token a borrar (ver list_design_tokens)'),
2959
+ app: appArg(APP_TOKEN_DESC),
2950
2960
  },
2951
2961
  },
2952
- async ({ projectId, tokenId }) => {
2962
+ async ({ projectId, tokenId, app }) => {
2953
2963
  try {
2954
- return textResult(await apiDelete(config, '/v1/design-tokens', { projectId: resolveProjectId(projectId), id: tokenId }))
2964
+ return textResult(await apiDelete(config, '/v1/design-tokens', { projectId: resolveProjectId(projectId), id: tokenId }, { app }))
2955
2965
  } catch (err) {
2956
2966
  return errorResult(err)
2957
2967
  }
@@ -2966,11 +2976,12 @@ export function createServer() {
2966
2976
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
2967
2977
  compact: z.boolean().optional().describe('true (default) = el lote devuelve items resumidos {id,name,key?,platform?,action}; false = filas completas'),
2968
2978
  tokens: z.array(z.object(designTokenFields(false))).min(1).max(100).describe('Tokens a crear/actualizar (1-100)'),
2979
+ app: appArg(APP_TOKEN_DESC),
2969
2980
  },
2970
2981
  },
2971
- async ({ projectId, tokens, compact }) => {
2982
+ async ({ projectId, tokens, compact, app }) => {
2972
2983
  try {
2973
- return textResult(await apiPost(config, '/v1/design-tokens/bulk', { projectId: resolveProjectId(projectId), tokens, compact: compact ?? true }))
2984
+ return textResult(await apiPost(config, '/v1/design-tokens/bulk', { projectId: resolveProjectId(projectId), tokens, compact: compact ?? true }, { app }))
2974
2985
  } catch (err) {
2975
2986
  return errorResult(err)
2976
2987
  }
@@ -3042,14 +3053,15 @@ export function createServer() {
3042
3053
  platform: z.enum(NAV_PLATFORMS).describe('Plataforma: web | ios | android'),
3043
3054
  tree: z.boolean().optional().describe('true = árbol anidado ({ items } con children); default lista plana'),
3044
3055
  parentId: z.string().optional().describe('Solo lista plana: hijos directos de este nodo'),
3056
+ app: appArg(),
3045
3057
  },
3046
3058
  },
3047
- async ({ projectId, platform, tree, parentId }) => {
3059
+ async ({ projectId, platform, tree, parentId, app }) => {
3048
3060
  try {
3049
3061
  const pid = resolveProjectId(projectId)
3050
3062
  return textResult(tree
3051
- ? await apiGet(config, '/v1/design-nav/tree', { projectId: pid, platform })
3052
- : await apiGet(config, '/v1/design-nav', { projectId: pid, platform, parentId }))
3063
+ ? await apiGet(config, '/v1/design-nav/tree', { projectId: pid, platform, app })
3064
+ : await apiGet(config, '/v1/design-nav', { projectId: pid, platform, parentId, app }))
3053
3065
  } catch (err) {
3054
3066
  return errorResult(err)
3055
3067
  }
@@ -3057,10 +3069,10 @@ export function createServer() {
3057
3069
  )
3058
3070
  registerCreate('create_design_nav_node', '/v1/design-nav',
3059
3071
  `Crea un nodo de navegación de diseño. ${NAV_PURPOSE} Para cargar muchos de una vez usa upsert_design_nav, no esta tool en bucle. Cada nodo acepta "actions" (convención entidad.verbo, ej. task.create; la misma acción lleva la MISMA key en web, iOS y Android) y "states" (recomendados: loading, empty, error, readonly, no-access, offline, refreshing, search-empty). La matriz de paridad compara primero por capacidades (acciones y estados) y cae a bloques si la referencia no las define.`,
3060
- navNodeFields(false))
3072
+ { ...navNodeFields(false), app: appArg() }, { query: ['app'] })
3061
3073
  registerUpdate('update_design_nav_node', '/v1/design-nav',
3062
3074
  `Edita un nodo de navegación de diseño existente (parche parcial: manda solo lo que cambia; parentId puede mover el nodo o ponerlo en null para dejarlo en la raíz). Ojo: "actions" y "states" REEMPLAZAN el array completo del nodo (manda la lista final; para mezclar por key usa upsert_design_nav). Convención de actions: entidad.verbo (task.create), misma key en web, iOS y Android; states recomendados: loading, empty, error, readonly, no-access, offline, refreshing, search-empty. La matriz de paridad compara primero por capacidades (acciones y estados) y cae a bloques si la referencia no las define. ${NAV_PURPOSE}`,
3063
- navNodeFields(true))
3075
+ { ...navNodeFields(true), app: appArg() }, { query: ['app'] })
3064
3076
 
3065
3077
  server.registerTool(
3066
3078
  'delete_design_nav_node',
@@ -3069,11 +3081,12 @@ export function createServer() {
3069
3081
  inputSchema: {
3070
3082
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
3071
3083
  nodeId: z.string().describe('ID del nodo a borrar (ver list_design_nav)'),
3084
+ app: appArg(),
3072
3085
  },
3073
3086
  },
3074
- async ({ projectId, nodeId }) => {
3087
+ async ({ projectId, nodeId, app }) => {
3075
3088
  try {
3076
- return textResult(await apiDelete(config, '/v1/design-nav', { projectId: resolveProjectId(projectId), id: nodeId }))
3089
+ return textResult(await apiDelete(config, '/v1/design-nav', { projectId: resolveProjectId(projectId), id: nodeId }, { app }))
3077
3090
  } catch (err) {
3078
3091
  return errorResult(err)
3079
3092
  }
@@ -3089,11 +3102,12 @@ export function createServer() {
3089
3102
  platform: z.enum(NAV_PLATFORMS).describe('Plataforma: web | ios | android'),
3090
3103
  parentId: z.string().nullable().describe('ID del padre cuyos hijos se reordenan; null = raíz'),
3091
3104
  ids: z.array(z.string()).min(1).describe('IDs de los hermanos en el orden final'),
3105
+ app: appArg(),
3092
3106
  },
3093
3107
  },
3094
- async ({ projectId, platform, parentId, ids }) => {
3108
+ async ({ projectId, platform, parentId, ids, app }) => {
3095
3109
  try {
3096
- return textResult(await apiPost(config, '/v1/design-nav/reorder', { projectId: resolveProjectId(projectId), platform, parentId, ids }))
3110
+ return textResult(await apiPost(config, '/v1/design-nav/reorder', { projectId: resolveProjectId(projectId), platform, parentId, ids }, { app }))
3097
3111
  } catch (err) {
3098
3112
  return errorResult(err)
3099
3113
  }
@@ -3104,7 +3118,7 @@ export function createServer() {
3104
3118
  server.registerTool(
3105
3119
  'upsert_design_nav',
3106
3120
  {
3107
- description: `Carga en lote (hasta 300 nodos) la navegación de diseño: es el camino para cargar el árbol completo de una plataforma leyendo su código (rutas del router, tab bar, sidebar, pantallas y sus bloques). ${NAV_PURPOSE} En vez de parentId cada nodo lleva parentKey (la key del padre, que puede venir en el mismo lote; sin parentKey = raíz). Un nodo existente se identifica por (platform, key) o, si no hay key, por (platform, parentId, name): se actualiza, si no se crea; nada se borra. "actions" (convención entidad.verbo, ej. task.create; la misma acción = la MISMA key en web, iOS y Android, es lo que permite compararlas) y "states" (recomendados: loading, empty, error, readonly, no-access, offline, refreshing, search-empty) se MEZCLAN por key al actualizar un nodo existente (update_design_nav_node reemplaza el array completo). La paridad compara por capacidades y cae a bloques si la referencia no las define. Ejemplo: [{"platform":"web","kind":"section","name":"Ajustes","key":"settings","route":"/settings"},{"platform":"web","kind":"screen","name":"General","key":"settings.general","parentKey":"settings","route":"/settings/general","blocks":[{"name":"Datos del workspace","description":"Nombre y logo"},{"name":"Zona de peligro"}],"actions":[{"key":"workspace.rename","name":"Renombrar workspace","roles":["owner"]}],"states":[{"key":"loading"},{"key":"readonly"}]}]. Usa la misma key para la misma pantalla en web, iOS y Android. Devuelve { created, updated, items }; por defecto compact=true y items trae solo {id,name,key?,platform?,action}, con compact=false devuelve las filas completas.`,
3121
+ description: `Carga en lote (hasta 300 nodos) la navegación de diseño: es el camino para cargar el árbol completo de una plataforma leyendo su código (rutas del router, tab bar, sidebar, pantallas y sus bloques). ${NAV_PURPOSE} En vez de parentId cada nodo lleva parentKey (la key del padre, que puede venir en el mismo lote; sin parentKey = raíz). Un nodo existente se identifica por (platform, key) o, si no hay key, por (platform, parentId, name): se actualiza, si no se crea; nada se borra. "actions" (convención entidad.verbo, ej. task.create; la misma acción = la MISMA key en web, iOS y Android, es lo que permite compararlas) y "states" (recomendados: loading, empty, error, readonly, no-access, offline, refreshing, search-empty) se MEZCLAN por key al actualizar un nodo existente (update_design_nav_node reemplaza el array completo). La paridad compara por capacidades y cae a bloques si la referencia no las define. Ejemplo: [{"platform":"web","kind":"section","name":"Ajustes","key":"settings","route":"/settings"},{"platform":"web","kind":"screen","name":"General","key":"settings.general","parentKey":"settings","route":"/settings/general","blocks":[{"name":"Datos del workspace","description":"Nombre y logo"},{"name":"Zona de peligro"}],"actions":[{"key":"workspace.rename","name":"Renombrar workspace","roles":["owner"]}],"states":[{"key":"loading"},{"key":"readonly"}]}]. Usa la misma key para la misma pantalla en web, iOS y Android. Devuelve { created, updated, items }; compact=true (default) resume items, false trae filas completas.`,
3108
3122
  inputSchema: {
3109
3123
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
3110
3124
  compact: z.boolean().optional().describe('true (default) = el lote devuelve items resumidos {id,name,key?,platform?,action}; false = filas completas'),
@@ -3112,11 +3126,12 @@ export function createServer() {
3112
3126
  ...navBulkBase,
3113
3127
  parentKey: z.string().optional().describe('Key del nodo padre (en este lote o ya existente); ausente = raíz'),
3114
3128
  })).min(1).max(300).describe('Nodos a crear/actualizar (1-300)'),
3129
+ app: appArg(),
3115
3130
  },
3116
3131
  },
3117
- async ({ projectId, nodes, compact }) => {
3132
+ async ({ projectId, nodes, compact, app }) => {
3118
3133
  try {
3119
- return textResult(await apiPost(config, '/v1/design-nav/bulk', { projectId: resolveProjectId(projectId), nodes, compact: compact ?? true }))
3134
+ return textResult(await apiPost(config, '/v1/design-nav/bulk', { projectId: resolveProjectId(projectId), nodes, compact: compact ?? true }, { app }))
3120
3135
  } catch (err) {
3121
3136
  return errorResult(err)
3122
3137
  }
@@ -3127,8 +3142,8 @@ export function createServer() {
3127
3142
  const SHOT_MIME_BY_EXT = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp' }
3128
3143
  const SHOT_MAX_BYTES = 5 * 1024 * 1024
3129
3144
  const SHOT_NOTE = 'Las capturas son INTERNAS del equipo (se guardan en un bucket privado y se ven con URL firmada de 1 h). No uses capturas del workspace real si van a usarse en marketing o videos: arma un usuario demo.'
3130
- const findNavNode = async (pid, platform, key) => {
3131
- const list = await apiGet(config, '/v1/design-nav', { projectId: pid, platform })
3145
+ const findNavNode = async (pid, platform, key, app) => {
3146
+ const list = await apiGet(config, '/v1/design-nav', { projectId: pid, platform, app })
3132
3147
  const node = (list.items || []).find(n => n.key === key)
3133
3148
  if (!node) throw new Error(`No hay un nodo con key "${key}" en ${platform}; revisa list_design_nav o créalo con upsert_design_nav`)
3134
3149
  return node
@@ -3144,9 +3159,10 @@ export function createServer() {
3144
3159
  filePath: z.string().describe('Ruta local a la imagen (png/jpg/jpeg/webp, máx. 5 MB)'),
3145
3160
  caption: z.string().max(200).optional().describe('Pie de la captura (máx. 200)'),
3146
3161
  state: z.string().optional().describe('Estado que muestra, ej: empty, loading, error'),
3162
+ app: appArg(),
3147
3163
  },
3148
3164
  },
3149
- async ({ projectId, platform, key, filePath, caption, state }) => {
3165
+ async ({ projectId, platform, key, filePath, caption, state, app }) => {
3150
3166
  try {
3151
3167
  const pid = resolveProjectId(projectId)
3152
3168
  const ext = path.extname(filePath).slice(1).toLowerCase()
@@ -3155,12 +3171,12 @@ export function createServer() {
3155
3171
  const stat = statSync(filePath)
3156
3172
  if (!stat.isFile()) throw new Error('filePath no es un archivo')
3157
3173
  if (stat.size > SHOT_MAX_BYTES) throw new Error(`La imagen pesa ${(stat.size / 1048576).toFixed(1)} MB; el máximo es 5 MB`)
3158
- const node = await findNavNode(pid, platform, key)
3174
+ const node = await findNavNode(pid, platform, key, app)
3159
3175
  const name = path.basename(filePath)
3160
- const { uploadUrl, key: shotKey, headers } = await apiPost(config, '/v1/design-assets/presign', { projectId: pid, nodeId: node.id, filename: name, contentType: mime, size: stat.size })
3176
+ const { uploadUrl, key: shotKey, headers } = await apiPost(config, '/v1/design-assets/presign', { projectId: pid, nodeId: node.id, filename: name, contentType: mime, size: stat.size }, { app })
3161
3177
  await putToPresignedUrl(uploadUrl, readFileSync(filePath), mime, headers)
3162
3178
  const shot = { key: shotKey, takenAt: Date.now(), ...(caption ? { caption } : {}), ...(state ? { state } : {}) }
3163
- const res = await apiPost(config, '/v1/design-nav/bulk', { projectId: pid, compact: false, nodes: [{ platform, kind: node.kind, name: node.name, key, screenshots: [shot] }] })
3179
+ const res = await apiPost(config, '/v1/design-nav/bulk', { projectId: pid, compact: false, nodes: [{ platform, kind: node.kind, name: node.name, key, screenshots: [shot] }] }, { app })
3164
3180
  const updated = res.items?.[0]
3165
3181
  return textResult({ key: shotKey, name, nodeId: node.id, screenshots: updated?.screenshots ?? [shot] })
3166
3182
  } catch (err) {
@@ -3177,15 +3193,16 @@ export function createServer() {
3177
3193
  platform: z.enum(NAV_PLATFORMS).describe('Plataforma del nodo: web | ios | android'),
3178
3194
  key: z.string().describe('Key del nodo de navegación'),
3179
3195
  screenshotKey: z.string().describe('Key de S3 de la captura a quitar'),
3196
+ app: appArg(),
3180
3197
  },
3181
3198
  },
3182
- async ({ projectId, platform, key, screenshotKey }) => {
3199
+ async ({ projectId, platform, key, screenshotKey, app }) => {
3183
3200
  try {
3184
3201
  const pid = resolveProjectId(projectId)
3185
- const node = await findNavNode(pid, platform, key)
3202
+ const node = await findNavNode(pid, platform, key, app)
3186
3203
  const current = node.screenshots || []
3187
3204
  if (!current.some(s => s.key === screenshotKey)) throw new Error(`El nodo "${key}" no tiene una captura con key "${screenshotKey}"`)
3188
- const data = await apiPatch(config, '/v1/design-nav', { projectId: pid, id: node.id, screenshots: current.filter(s => s.key !== screenshotKey) })
3205
+ const data = await apiPatch(config, '/v1/design-nav', { projectId: pid, id: node.id, screenshots: current.filter(s => s.key !== screenshotKey) }, { app })
3189
3206
  return textResult({ removed: screenshotKey, nodeId: node.id, screenshots: data.screenshots ?? [] })
3190
3207
  } catch (err) {
3191
3208
  return errorResult(err)
@@ -3227,15 +3244,16 @@ export function createServer() {
3227
3244
  {
3228
3245
  platform: z.enum(COMP_PLATFORMS).optional().describe('Filtra por plataforma: web | ios | android'),
3229
3246
  category: z.string().optional().describe('Filtra por categoría'),
3247
+ app: appArg(),
3230
3248
  },
3231
- (args, projectId) => ({ projectId, platform: args.platform, category: args.category })
3249
+ (args, projectId) => ({ projectId, platform: args.platform, category: args.category, app: args.app })
3232
3250
  )
3233
3251
  registerCreate('create_design_component', '/v1/design-components',
3234
3252
  `Crea un componente de diseño. ${COMP_PURPOSE} Para cargar muchos de una vez usa upsert_design_components, no esta tool en bucle.`,
3235
- designComponentFields(false))
3253
+ { ...designComponentFields(false), app: appArg() }, { query: ['app'] })
3236
3254
  registerUpdate('update_design_component', '/v1/design-components',
3237
3255
  `Edita un componente de diseño existente (parche parcial: manda solo lo que cambia). ${COMP_PURPOSE}`,
3238
- designComponentFields(true))
3256
+ { ...designComponentFields(true), app: appArg() }, { query: ['app'] })
3239
3257
 
3240
3258
  server.registerTool(
3241
3259
  'delete_design_component',
@@ -3244,11 +3262,12 @@ export function createServer() {
3244
3262
  inputSchema: {
3245
3263
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
3246
3264
  componentId: z.string().describe('ID del componente a borrar (ver list_design_components)'),
3265
+ app: appArg(),
3247
3266
  },
3248
3267
  },
3249
- async ({ projectId, componentId }) => {
3268
+ async ({ projectId, componentId, app }) => {
3250
3269
  try {
3251
- return textResult(await apiDelete(config, '/v1/design-components', { projectId: resolveProjectId(projectId), id: componentId }))
3270
+ return textResult(await apiDelete(config, '/v1/design-components', { projectId: resolveProjectId(projectId), id: componentId }, { app }))
3252
3271
  } catch (err) {
3253
3272
  return errorResult(err)
3254
3273
  }
@@ -3263,11 +3282,12 @@ export function createServer() {
3263
3282
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
3264
3283
  compact: z.boolean().optional().describe('true (default) = el lote devuelve items resumidos {id,name,key?,platform?,action}; false = filas completas'),
3265
3284
  components: z.array(z.object(designComponentFields(false))).min(1).max(200).describe('Componentes a crear/actualizar (1-200)'),
3285
+ app: appArg(),
3266
3286
  },
3267
3287
  },
3268
- async ({ projectId, components, compact }) => {
3288
+ async ({ projectId, components, compact, app }) => {
3269
3289
  try {
3270
- return textResult(await apiPost(config, '/v1/design-components/bulk', { projectId: resolveProjectId(projectId), components, compact: compact ?? true }))
3290
+ return textResult(await apiPost(config, '/v1/design-components/bulk', { projectId: resolveProjectId(projectId), components, compact: compact ?? true }, { app }))
3271
3291
  } catch (err) {
3272
3292
  return errorResult(err)
3273
3293
  }
@@ -3275,6 +3295,161 @@ export function createServer() {
3275
3295
  )
3276
3296
 
3277
3297
  // ═══ PARIDAD DE DISEÑO (ORQ-563) ═══════════════════════════════════════════
3298
+
3299
+ // ═══ FLUJO GUIADO DE DISEÑO (ORQ-564) ══════════════════════════════════════
3300
+ server.registerTool(
3301
+ 'get_design_flow',
3302
+ {
3303
+ description: 'Guía paso a paso para llenar Diseño / UI (tokens, navegación, bloques, acciones, componentes, paridad, deriva). Datos estáticos, sin red. Con platform devuelve además un agentPrompt listo para pegar; con step, solo ese paso. Empieza por get_design_status.',
3304
+ inputSchema: {
3305
+ platform: z.enum(DESIGN_PLATFORM_ARGS).optional().describe('web | ios | android | all (default all)'),
3306
+ app: appArg('Key de la app (list_design_apps); con platform, el agentPrompt la incluye'),
3307
+ step: z.string().optional().describe('Id de un paso (apps, check, identity, navigation, blocks, actions-states, components, parity, drift, sync, screenshots)'),
3308
+ },
3309
+ },
3310
+ async ({ platform, step, app }) => {
3311
+ const data = getDesignFlow({ platform, step, app })
3312
+ if (data.error) return { content: [{ type: 'text', text: data.error }], isError: true }
3313
+ return textResult(data)
3314
+ }
3315
+ )
3316
+
3317
+ const safeDesign = p => p.catch(e => ({ __error: e instanceof ApiError ? `HTTP ${e.status}: ${e.message}` : e.message }))
3318
+ // Estado de una app (o del proyecto sin app): las 4 lecturas globales + nav y sync por plataforma.
3319
+ async function fetchDesignStatus(pid, app) {
3320
+ const [tokens, components, drift, parity, ...rest] = await Promise.all([
3321
+ safeDesign(apiGet(config, '/v1/design-tokens', { projectId: pid, app })),
3322
+ safeDesign(apiGet(config, '/v1/design-components', { projectId: pid, app })),
3323
+ safeDesign(apiGet(config, '/v1/design-drift', { projectId: pid, app })),
3324
+ safeDesign(apiGet(config, '/v1/design-parity', { projectId: pid, app })),
3325
+ ...DESIGN_PLATFORMS.map(platform => safeDesign(apiGet(config, '/v1/design-nav', { projectId: pid, platform, app }))),
3326
+ ...DESIGN_PLATFORMS.map(platform => safeDesign(apiGet(config, '/v1/design-sync', { projectId: pid, platform, app }))),
3327
+ ])
3328
+ const n = DESIGN_PLATFORMS.length
3329
+ const nav = Object.fromEntries(DESIGN_PLATFORMS.map((pl, i) => [pl, rest[i]]))
3330
+ const sync = Object.fromEntries(DESIGN_PLATFORMS.map((pl, i) => [pl, rest[n + i]]))
3331
+ return computeDesignStatus({ tokens, components, drift, parity, nav, sync })
3332
+ }
3333
+
3334
+ server.registerTool(
3335
+ 'get_design_status',
3336
+ {
3337
+ description: 'Estado de Diseño / UI por plataforma (web, ios, android): tokens, nodos, pantallas con bloques/acciones/estados, componentes, deriva, sync y paridad, más `next`: el primer paso de get_design_flow pendiente. Solo números. Con varias apps y sin app devuelve un resumen por app.',
3338
+ inputSchema: {
3339
+ projectId: z.string().optional().describe(PROJECT_ID_DESC),
3340
+ app: appArg('Key de la app (list_design_apps). Con varias apps y sin app: resumen compacto por app'),
3341
+ },
3342
+ },
3343
+ async ({ projectId, app }) => {
3344
+ try {
3345
+ const pid = resolveProjectId(projectId)
3346
+ if (app) return textResult(await fetchDesignStatus(pid, app))
3347
+ const apps = await safeDesign(apiGet(config, '/v1/design-apps', { projectId: pid }))
3348
+ if (apps.__error || !apps.multiple || !arrayOf(apps).length) return textResult(await fetchDesignStatus(pid))
3349
+ const perApp = await Promise.all(arrayOf(apps).map(a =>
3350
+ fetchDesignStatus(pid, a.key).then(st => summarizeAppStatus(a, st), e => ({ key: a.key, name: a.name, error: e instanceof ApiError ? `HTTP ${e.status}: ${e.message}` : e.message }))))
3351
+ return textResult({ multiple: true, apps: perApp })
3352
+ } catch (err) {
3353
+ return errorResult(err)
3354
+ }
3355
+ }
3356
+ )
3357
+
3358
+ server.registerTool(
3359
+ 'list_design_apps',
3360
+ {
3361
+ description: 'Lista las apps de Diseño / UI del proyecto ({key,name,platforms,distributionIds,productKey}) y `multiple`. Con varias apps, casi todas las tools de Diseño exigen `app`.',
3362
+ inputSchema: { projectId: z.string().optional().describe(PROJECT_ID_DESC) },
3363
+ },
3364
+ async ({ projectId }) => {
3365
+ try {
3366
+ return textResult(await apiGet(config, '/v1/design-apps', { projectId: resolveProjectId(projectId) }))
3367
+ } catch (err) {
3368
+ return errorResult(err)
3369
+ }
3370
+ }
3371
+ )
3372
+
3373
+ server.registerTool(
3374
+ 'migrate_design_apps',
3375
+ {
3376
+ description: 'Asigna a UNA app todo lo de Diseño que aún no tiene app (nav, componentes, deriva, paridad). Cambia datos existentes: con dryRun:true (default) solo informa qué movería.',
3377
+ inputSchema: {
3378
+ projectId: z.string().optional().describe(PROJECT_ID_DESC),
3379
+ appKey: APP_STR.describe('Key de la app destino (list_design_apps)'),
3380
+ dryRun: z.boolean().optional().describe('true (default) = solo informa; false = aplica la asignación'),
3381
+ },
3382
+ },
3383
+ async ({ projectId, appKey, dryRun }) => {
3384
+ try {
3385
+ return textResult(await apiPost(config, '/v1/design-apps/migrate', { projectId: resolveProjectId(projectId), appKey, dryRun: dryRun ?? true }))
3386
+ } catch (err) {
3387
+ return errorResult(err)
3388
+ }
3389
+ }
3390
+ )
3391
+
3392
+ // ═══ SINCRONÍA CON EL CÓDIGO (ORQ-575) ═════════════════════════════════════
3393
+ const designSyncIo = (pid, platform, staleDays, app) => ({
3394
+ fetchSync: () => apiGet(config, '/v1/design-sync', { projectId: pid, platform, staleDays, app }),
3395
+ fetchCategories: async () => {
3396
+ const r = await apiGet(config, '/v1/design-components', { projectId: pid, app })
3397
+ const list = Array.isArray(r) ? r : Array.isArray(r?.items) ? r.items : []
3398
+ return new Map(list.filter(c => c?.name && c.category).map(c => [c.name, c.category]))
3399
+ },
3400
+ writeNav: nodes => apiPost(config, '/v1/design-nav/bulk', { projectId: pid, nodes, compact: true }, { app }),
3401
+ writeComponents: components => apiPost(config, '/v1/design-components/bulk', { projectId: pid, components, compact: true }, { app }),
3402
+ })
3403
+ const SYNC_PLATFORM = z.enum(['web', 'ios', 'android']).describe('web | ios | android')
3404
+ const SYNC_REPO = z.string().min(1).describe('Ruta absoluta del repo de esa plataforma en esta máquina')
3405
+
3406
+ server.registerTool(
3407
+ 'check_design_sync',
3408
+ {
3409
+ description: 'Compara el código local con lo cargado en Diseño / UI (sourceRef + huella) y reporta qué cambió; con record (default true) marca lo cambiado como outdated. Solo lee archivos dentro de repoPath. Devuelve conteos y listas cortas.',
3410
+ inputSchema: {
3411
+ projectId: z.string().optional().describe(PROJECT_ID_DESC),
3412
+ platform: SYNC_PLATFORM,
3413
+ repoPath: SYNC_REPO,
3414
+ staleDays: z.number().int().min(1).max(365).optional().describe('Días sin sincronizar para considerar stale (1-365)'),
3415
+ record: z.boolean().optional().describe('false = solo reporta, no marca outdated (default true)'),
3416
+ app: appArg(),
3417
+ },
3418
+ },
3419
+ async ({ projectId, platform, repoPath, staleDays, record, app }) => {
3420
+ try {
3421
+ if (!path.isAbsolute(repoPath)) throw new Error('repoPath debe ser una ruta absoluta')
3422
+ return textResult(await runCheck({ platform, repoPath, record }, designSyncIo(resolveProjectId(projectId), platform, staleDays, app)))
3423
+ } catch (err) {
3424
+ return errorResult(err)
3425
+ }
3426
+ }
3427
+ )
3428
+
3429
+ server.registerTool(
3430
+ 'mark_design_synced',
3431
+ {
3432
+ description: 'Guarda la huella actual del código como sincronizada (limpia outdated). Úsala solo después de haber actualizado/revisado en Orquestra lo que cambió, o para fijar la línea base tras una carga completa (all:true).',
3433
+ inputSchema: {
3434
+ projectId: z.string().optional().describe(PROJECT_ID_DESC),
3435
+ platform: SYNC_PLATFORM,
3436
+ repoPath: SYNC_REPO,
3437
+ nav: z.array(z.string()).optional().describe('Keys de nodos de navegación a marcar'),
3438
+ components: z.array(z.string()).optional().describe('Nombres de componentes a marcar'),
3439
+ all: z.boolean().optional().describe('true = línea base de todo lo que tenga sourceRef en la plataforma'),
3440
+ app: appArg(),
3441
+ },
3442
+ },
3443
+ async ({ projectId, platform, repoPath, nav, components, all, app }) => {
3444
+ try {
3445
+ if (!path.isAbsolute(repoPath)) throw new Error('repoPath debe ser una ruta absoluta')
3446
+ return textResult(await runMark({ platform, repoPath, nav, components, all }, designSyncIo(resolveProjectId(projectId), platform, undefined, app)))
3447
+ } catch (err) {
3448
+ return errorResult(err)
3449
+ }
3450
+ }
3451
+ )
3452
+
3278
3453
  const PARITY_PLATFORMS = ['web', 'ios', 'android']
3279
3454
  server.registerTool(
3280
3455
  'get_design_parity',
@@ -3285,11 +3460,12 @@ export function createServer() {
3285
3460
  ref: z.enum(PARITY_PLATFORMS).optional().describe('Plataforma de referencia: web | ios | android (default web)'),
3286
3461
  soloHuecos: z.boolean().optional().describe('true = devuelve solo summary, gaps y threshold (sin las filas), para ahorrar tokens'),
3287
3462
  threshold: z.number().min(0).max(1).optional().describe('Umbral de similitud de bloques (0..1, default 0.6) para considerar "same"'),
3463
+ app: appArg(),
3288
3464
  },
3289
3465
  },
3290
- async ({ projectId, ref, soloHuecos, threshold }) => {
3466
+ async ({ projectId, ref, soloHuecos, threshold, app }) => {
3291
3467
  try {
3292
- const data = await apiGet(config, '/v1/design-parity', { projectId: resolveProjectId(projectId), ref, threshold })
3468
+ const data = await apiGet(config, '/v1/design-parity', { projectId: resolveProjectId(projectId), ref, threshold, app })
3293
3469
  if (soloHuecos && data && typeof data === 'object') return textResult({ summary: data.summary, gaps: data.gaps, threshold: data.threshold })
3294
3470
  return textResult(data)
3295
3471
  } catch (err) {
@@ -3311,14 +3487,15 @@ export function createServer() {
3311
3487
  taskId: z.string().optional().describe('Folio de la tarea que cierra el hueco, ej: ORQ-123'),
3312
3488
  reason: z.string().max(500).optional().describe('Motivo de la decisión (máx. 500). Obligatorio al fijar status not_applicable'),
3313
3489
  adr: z.string().max(60).optional().describe('Id del doc (ADR) que documenta la decisión; se envía como docId. "" lo quita'),
3490
+ app: appArg(),
3314
3491
  },
3315
3492
  },
3316
- async ({ projectId, key, platform, status, note, taskId, reason, adr }) => {
3493
+ async ({ projectId, key, platform, status, note, taskId, reason, adr, app }) => {
3317
3494
  try {
3318
3495
  if (status === 'not_applicable' && !(reason && reason.trim())) {
3319
3496
  return errorResult(new Error('motivo obligatorio al fijar No aplica: pasa reason con el porqué (y opcionalmente adr con el id del doc)'))
3320
3497
  }
3321
- return textResult(await apiPut(config, '/v1/design-parity/cell', { projectId: resolveProjectId(projectId), key, platform, status, note, taskId, reason, docId: adr }))
3498
+ return textResult(await apiPut(config, '/v1/design-parity/cell', { projectId: resolveProjectId(projectId), key, platform, status, note, taskId, reason, docId: adr }, { app }))
3322
3499
  } catch (err) {
3323
3500
  return errorResult(err)
3324
3501
  }
@@ -3341,11 +3518,12 @@ export function createServer() {
3341
3518
  dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Formato YYYY-MM-DD').optional().describe('Fecha límite YYYY-MM-DD; si falta, hoy + 14 días'),
3342
3519
  priority: z.enum(['high', 'medium', 'low']).optional().describe('Prioridad de las tareas'),
3343
3520
  force: z.boolean().optional().describe('true = crea la tarea aunque la celda ya tenga folio'),
3521
+ app: appArg(),
3344
3522
  },
3345
3523
  },
3346
- async ({ projectId, cells, ref, threshold, moduleId, dueDate, priority, force }) => {
3524
+ async ({ projectId, cells, ref, threshold, moduleId, dueDate, priority, force, app }) => {
3347
3525
  try {
3348
- return textResult(await apiPost(config, '/v1/design-parity/tasks', { projectId: resolveProjectId(projectId), cells, ref, threshold, moduleId, dueDate, priority, force }))
3526
+ return textResult(await apiPost(config, '/v1/design-parity/tasks', { projectId: resolveProjectId(projectId), cells, ref, threshold, moduleId, dueDate, priority, force }, { app }))
3349
3527
  } catch (err) {
3350
3528
  return errorResult(err)
3351
3529
  }
@@ -3376,11 +3554,12 @@ export function createServer() {
3376
3554
  projectId: z.string().optional().describe(PROJECT_ID_DESC),
3377
3555
  compact: z.boolean().optional().describe('true (default) = items resumidos {id,platform,file,line?,value,status,action}; false = filas completas'),
3378
3556
  items: z.array(driftItemSchema).min(1).max(200).describe('Hallazgos a reportar (1-200)'),
3557
+ app: appArg(),
3379
3558
  },
3380
3559
  },
3381
- async ({ projectId, items, compact }) => {
3560
+ async ({ projectId, items, compact, app }) => {
3382
3561
  try {
3383
- return textResult(await apiPost(config, '/v1/design-drift/bulk', { projectId: resolveProjectId(projectId), items, compact: compact ?? true }))
3562
+ return textResult(await apiPost(config, '/v1/design-drift/bulk', { projectId: resolveProjectId(projectId), items, compact: compact ?? true }, { app }))
3384
3563
  } catch (err) {
3385
3564
  return errorResult(err)
3386
3565
  }
@@ -3396,11 +3575,12 @@ export function createServer() {
3396
3575
  platform: z.enum(PARITY_PLATFORMS).optional().describe('Filtra por plataforma'),
3397
3576
  kind: z.enum(DRIFT_KINDS).optional().describe('Filtra por tipo'),
3398
3577
  status: z.enum(DRIFT_STATUSES).optional().describe('Filtra por estado: open | ignored | fixed'),
3578
+ app: appArg(),
3399
3579
  },
3400
3580
  },
3401
- async ({ projectId, platform, kind, status }) => {
3581
+ async ({ projectId, platform, kind, status, app }) => {
3402
3582
  try {
3403
- return textResult(await apiGet(config, '/v1/design-drift', { projectId: resolveProjectId(projectId), platform, kind, status }))
3583
+ return textResult(await apiGet(config, '/v1/design-drift', { projectId: resolveProjectId(projectId), platform, kind, status, app }))
3404
3584
  } catch (err) {
3405
3585
  return errorResult(err)
3406
3586
  }
@@ -3417,14 +3597,15 @@ export function createServer() {
3417
3597
  status: z.enum(DRIFT_STATUSES).optional().describe('open | ignored | fixed'),
3418
3598
  note: z.string().max(300).optional().describe('Nota (≤300), ej. el motivo de ignorarlo'),
3419
3599
  suggestedToken: z.string().max(80).optional().describe('name del token que lo reemplazaría (≤80)'),
3600
+ app: appArg(),
3420
3601
  },
3421
3602
  },
3422
- async ({ projectId, driftId, status, note, suggestedToken }) => {
3603
+ async ({ projectId, driftId, status, note, suggestedToken, app }) => {
3423
3604
  if (status === undefined && note === undefined && suggestedToken === undefined) {
3424
3605
  return errorResult(new Error('Nada que actualizar: manda status, note o suggestedToken'))
3425
3606
  }
3426
3607
  try {
3427
- return textResult(await apiPatch(config, '/v1/design-drift', { projectId: resolveProjectId(projectId), id: driftId, status, note, suggestedToken }))
3608
+ return textResult(await apiPatch(config, '/v1/design-drift', { projectId: resolveProjectId(projectId), id: driftId, status, note, suggestedToken }, { app }))
3428
3609
  } catch (err) {
3429
3610
  return errorResult(err)
3430
3611
  }
@@ -3440,11 +3621,12 @@ export function createServer() {
3440
3621
  platform: z.enum(PARITY_PLATFORMS).describe('Plataforma de la pasada: web | ios | android'),
3441
3622
  reportedBefore: z.number().int().positive().describe('ms epoch: se marcan los open con seenAt anterior a este valor'),
3442
3623
  dryRun: z.boolean().optional().describe('true (default) = solo informa; false = marca fixed'),
3624
+ app: appArg(),
3443
3625
  },
3444
3626
  },
3445
- async ({ projectId, platform, reportedBefore, dryRun }) => {
3627
+ async ({ projectId, platform, reportedBefore, dryRun, app }) => {
3446
3628
  try {
3447
- return textResult(await apiPost(config, '/v1/design-drift/resolve-missing', { projectId: resolveProjectId(projectId), platform, reportedBefore, dryRun: dryRun ?? true }))
3629
+ return textResult(await apiPost(config, '/v1/design-drift/resolve-missing', { projectId: resolveProjectId(projectId), platform, reportedBefore, dryRun: dryRun ?? true }, { app }))
3448
3630
  } catch (err) {
3449
3631
  return errorResult(err)
3450
3632
  }