@hablala/cli 0.4.0 → 0.5.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/dist/index.js CHANGED
@@ -71,6 +71,19 @@ function changeLabel(change) {
71
71
  if (change.type === "agent") return `agent @${change.handle ?? "?"}`;
72
72
  return `${change.type} ${change.slug ?? "?"}`;
73
73
  }
74
+ function accessSentence(change) {
75
+ const access = change.access ?? {};
76
+ const principal = access.principal ?? "?";
77
+ const scope = access.object ? `\`${access.object}\`` : "toda la organizaci\xF3n";
78
+ const action = access.action ?? "?";
79
+ const effect = access.effect === "deny" ? "niega" : "concede";
80
+ if (change.action === "delete") {
81
+ const what = access.effect === "deny" ? "el bloqueo de" : "el acceso a";
82
+ return `revoca ${what} \`${action}\` de ${principal} sobre ${scope}`;
83
+ }
84
+ const verb = change.action === "create" ? effect : `re-${effect}`;
85
+ return `${verb} \`${action}\` a ${principal} sobre ${scope}`;
86
+ }
74
87
  function short(value) {
75
88
  const text = JSON.stringify(value);
76
89
  if (text === void 0) return "null";
@@ -93,28 +106,65 @@ function renderErrors(errors) {
93
106
  return ` ${red("\u2716")} ${where}: ${error.message}`;
94
107
  }).join("\n");
95
108
  }
109
+ function accessLine(change) {
110
+ const symbol = change.action === "create" ? green("+") : change.action === "update" ? yellow("~") : red("-");
111
+ return ` ${symbol} ${change.slug ?? "?"} \u2014 ${accessSentence(change)}`;
112
+ }
96
113
  function renderPlan(plan2) {
97
114
  const lines = [];
98
115
  const active = plan2.changes.filter((change) => change.action !== "noop");
116
+ const policyChanges = active.filter((change) => change.type === "policy");
117
+ const otherChanges = active.filter((change) => change.type !== "policy");
99
118
  for (const action of ["create", "update", "archive"]) {
100
- for (const change of active.filter((c) => c.action === action)) {
119
+ for (const change of otherChanges.filter((c) => c.action === action)) {
101
120
  lines.push(...changeLines(change));
102
121
  }
103
122
  }
123
+ if (policyChanges.length > 0) {
124
+ if (lines.length > 0) lines.push("");
125
+ lines.push(yellow(bold("\u26A0 Cambios de acceso (revisar \u2014 afectan qui\xE9n ve qu\xE9):")));
126
+ for (const action of ["create", "update", "delete"]) {
127
+ for (const change of policyChanges.filter((c) => c.action === action)) {
128
+ lines.push(accessLine(change));
129
+ }
130
+ }
131
+ }
104
132
  if (plan2.errors.length > 0) {
105
133
  if (lines.length > 0) lines.push("");
106
134
  lines.push(bold("Conflictos (bloquean el apply):"));
107
135
  lines.push(renderErrors(plan2.errors));
108
136
  }
109
137
  const { summary } = plan2;
110
- const counts = `${summary.create ?? 0} a crear, ${summary.update ?? 0} a actualizar, ${summary.archive ?? 0} a archivar (${summary.noop ?? 0} sin cambios)`;
138
+ const deletePart = summary.delete ? `, ${summary.delete} a borrar` : "";
139
+ const counts = `${summary.create ?? 0} a crear, ${summary.update ?? 0} a actualizar, ${summary.archive ?? 0} a archivar${deletePart} (${summary.noop ?? 0} sin cambios)`;
111
140
  if (active.length === 0 && plan2.errors.length === 0) {
112
- return `${bold("Sin cambios.")} El workspace ya coincide con el manifiesto (${summary.noop ?? 0} recursos).`;
141
+ return `${bold("Sin cambios.")} La organizaci\xF3n ya coincide con el manifiesto (${summary.noop ?? 0} recursos).`;
113
142
  }
114
143
  lines.push("");
115
144
  lines.push(`${bold("Plan:")} ${counts}`);
116
145
  return lines.join("\n");
117
146
  }
147
+ function renderEvals(result) {
148
+ const lines = [];
149
+ for (const agent of result.agents ?? []) {
150
+ lines.push(bold(`@${agent.handle}`));
151
+ if (agent.error) {
152
+ lines.push(` ${red("\u2716")} ${agent.error}`);
153
+ continue;
154
+ }
155
+ for (const c of agent.cases ?? []) {
156
+ const mark = c.passed ? green("\u2714") : red("\u2716");
157
+ lines.push(` ${mark} ${c.name}`);
158
+ if (!c.passed) for (const f of c.failures ?? []) lines.push(` ${dim(f)}`);
159
+ }
160
+ }
161
+ const passed = result.passed ?? 0;
162
+ const failed = result.failed ?? 0;
163
+ const mode = result.live ? " (LLM real)" : "";
164
+ lines.push("");
165
+ lines.push(`${bold("Evals:")} ${green(`${passed} pasaron`)}, ${failed ? red(`${failed} fallaron`) : `${failed} fallaron`}${mode}`);
166
+ return lines.join("\n");
167
+ }
118
168
 
119
169
  // src/codegen.ts
120
170
  async function codegen(args) {
@@ -165,6 +215,7 @@ import { createInterface } from "readline";
165
215
 
166
216
  // src/api.ts
167
217
  import createClient from "openapi-fetch";
218
+ var ACCOUNT_KIND = "organization";
168
219
  function createApiClient(config) {
169
220
  return createClient({
170
221
  baseUrl: config.endpoint,
@@ -181,19 +232,45 @@ async function whoami(api) {
181
232
  return data.data;
182
233
  }
183
234
  async function fetchManifest(api) {
184
- const { data, error, response } = await api.GET("/v1/workspace-config");
235
+ const { data, error, response } = await api.GET("/v1/account-config");
185
236
  if (!response.ok || !data) {
186
237
  throw new Error(formatApiError(response.status, error));
187
238
  }
188
- return data.data;
239
+ const { kind, version: version2, ...sections } = data.data.account;
240
+ void kind;
241
+ return { sections, version: version2 };
242
+ }
243
+ function withModes(manifest, modes) {
244
+ if (!modes || Object.keys(modes).length === 0) return manifest;
245
+ const out2 = { ...manifest };
246
+ for (const [section, mode] of Object.entries(modes)) {
247
+ const items = manifest[section];
248
+ if (Array.isArray(items)) out2[section] = { mode, items };
249
+ }
250
+ return out2;
189
251
  }
190
252
  async function putManifest(api, manifest, options) {
191
- const { data, error, response } = await api.PUT("/v1/workspace-config", {
253
+ const { data, error, response } = await api.PUT("/v1/account-config", {
192
254
  params: { query: { dry_run: options.dryRun } },
193
- body: { config: manifest }
255
+ // El `If-Match` es la precondición de versión (optimistic locking): solo en el apply real, y
256
+ // solo si tenemos una versión del `pull`. Sin él, el server aplica sin chequear (retrocompat).
257
+ headers: !options.dryRun && options.expectedVersion ? { "If-Match": options.expectedVersion } : void 0,
258
+ body: {
259
+ config: { account: { kind: ACCOUNT_KIND, ...withModes(manifest, options.modes) } }
260
+ }
194
261
  });
195
262
  if (response.ok && data) return { plan: data.data };
196
263
  const body = error;
264
+ if (response.status === 412) {
265
+ const errors = body?.errors;
266
+ return {
267
+ failure: {
268
+ detail: errors?.detail ?? "la cuenta cambi\xF3 desde tu \xFAltimo `pull`; corre `hablala pull` para re-sincronizar",
269
+ planErrors: [],
270
+ versionConflict: true
271
+ }
272
+ };
273
+ }
197
274
  if (response.status === 422) {
198
275
  const errors = body?.errors;
199
276
  if (errors) {
@@ -209,6 +286,23 @@ async function putManifest(api, manifest, options) {
209
286
  }
210
287
  throw new Error(formatApiError(response.status, body));
211
288
  }
289
+ async function runEvals(api, manifest, options) {
290
+ const { data, error, response } = await api.POST("/v1/account-config/eval", {
291
+ params: { query: { live: options.live } },
292
+ body: { config: { account: { kind: ACCOUNT_KIND, ...manifest } } }
293
+ });
294
+ if (response.ok && data) return { result: data.data };
295
+ const body = error;
296
+ if (response.status === 422) {
297
+ const errors = body?.errors;
298
+ if (errors) {
299
+ return {
300
+ failure: { detail: errors.detail ?? "el manifiesto no pas\xF3 validaci\xF3n", planErrors: errors.manifest ?? [] }
301
+ };
302
+ }
303
+ }
304
+ throw new Error(formatApiError(response.status, body));
305
+ }
212
306
  function formatApiError(status, body) {
213
307
  const errors = body?.errors;
214
308
  if (errors && typeof errors === "object") {
@@ -225,61 +319,114 @@ function formatApiError(status, body) {
225
319
 
226
320
  // src/claude-md.ts
227
321
  function agentGuide(identity) {
228
- return `# Workspace as Code \u2014 ${identity.workspace.name} (${identity.organization.name})
322
+ return `# Account as Code \u2014 ${identity.organization.name}
229
323
 
230
- Este directorio declara la configuraci\xF3n del workspace como **archivos versionables**.
324
+ Este directorio declara la configuraci\xF3n de la organizaci\xF3n como **archivos versionables**.
231
325
  T\xFA (el agente) editas los archivos; el CLI valida, muestra el diff y aplica:
232
326
 
233
- hablala plan # diff declarado vs. real \u2014 NUNCA toca nada
234
- hablala apply # reconcilia (crear / actualizar / archivar; jam\xE1s borrar)
235
- hablala pull # re-sincroniza los archivos con el estado real
327
+ hablala plan # diff declarado vs. real \u2014 NUNCA toca nada
328
+ hablala apply # reconcilia (crear / actualizar / archivar; jam\xE1s borrar)
329
+ hablala eval # corre los evals de los agentes (--live: LLM real; sale 1 si alg\xFAn caso falla)
330
+ hablala pull # re-sincroniza los archivos con el estado real
331
+ hablala pull --check # \xBFlos archivos siguen el estado real? (sale 1 si no; para CI)
332
+
333
+ ## Runbook (SEGUIR SIEMPRE, en orden)
334
+
335
+ La \xFAnica fuente de verdad es la organizaci\xF3n (la BD), no estos archivos: son una **proyecci\xF3n
336
+ versionada** de ella, como un clon de git respecto al remoto. La UI, MCP y este manifiesto
337
+ escriben todos al mismo lugar; estos archivos pueden quedar **atr\xE1s** si alguien cambi\xF3 la org
338
+ por otra v\xEDa. Por eso, en CADA sesi\xF3n de trabajo:
339
+
340
+ 1. hablala pull --check # \xBFmis archivos siguen la verdad? (drift inverso)
341
+ 2. hablala pull # SI hubo drift: re-sincroniza ANTES de tocar nada
342
+ 3. \u2026edita los .yaml\u2026
343
+ 4. hablala plan # revisa el diff \u2014 vigila los archive/delete
344
+ 5. \u2026corrige conflictos y repite plan hasta que salga limpio\u2026
345
+ 6. hablala apply # aplica (pide confirmaci\xF3n; --yes en CI)
346
+
347
+ **El paso 1 no es opcional.** \`apply\` es autoritativo: lo que existe en la org y NO est\xE1 en tus
348
+ archivos se ARCHIVA. Si editas y aplicas un manifiesto viejo (sin el paso 1-2), archivas
349
+ silenciosamente lo que el cliente agreg\xF3 por la UI o un agente por MCP. \`pull --check\` sale con
350
+ c\xF3digo 1 si hay drift \u2014 \xFAsalo como guardia en pre-commit/CI.
236
351
 
237
- Loop recomendado: edita \u2192 \`plan\` \u2192 corrige conflictos \u2192 \`plan\` limpio \u2192 \`apply\`.
352
+ **Red de seguridad autom\xE1tica (optimistic locking).** Adem\xE1s de la disciplina, el \`pull\` guarda
353
+ la versi\xF3n del estado en \`.hablala-version\` (un lockfile \u2014 versi\xF3nalo en git). El \`apply\` la
354
+ reenv\xEDa como precondici\xF3n: si la org cambi\xF3 desde tu \xFAltimo \`pull\` (UI, MCP, otro apply), el
355
+ server RECHAZA el apply con un conflicto de versi\xF3n en vez de pisar lo que no viste \u2014 como un
356
+ \`git push\` rechazado cuando tu rama est\xE1 atr\xE1s. Si eso pasa: \`hablala pull\`, revisa el diff,
357
+ reaplica. (Sin \`.hablala-version\` \u2014nunca hiciste \`pull\`\u2014 el apply avisa y procede sin chequeo.)
238
358
 
239
359
  ## Estructura
240
360
 
241
361
  objects/<slug>.yaml # un objeto del modelo de datos por archivo
242
362
  workflows/<slug>.yaml # una definici\xF3n de workflow por archivo
243
363
  agents/<handle>.yaml # un agente de IA por archivo
364
+ policies/<slug>.yaml # una regla ABAC de acceso a datos por archivo
244
365
 
245
366
  Reglas del manifiesto:
246
367
 
247
- - **Cada directorio es autoritativo**: lo que existe en el workspace y no est\xE1 declarado
368
+ - **Cada directorio es autoritativo**: lo que existe en la organizaci\xF3n y no est\xE1 declarado
248
369
  en archivos SE ARCHIVA al aplicar (\`plan\` siempre lo muestra antes). Borrar un archivo
249
- archiva esa entidad; nunca se destruye nada.
370
+ archiva esa entidad; nunca se destruye nada. **Excepci\xF3n: las policies se BORRAN** (no
371
+ se archivan) \u2014 para una regla de acceso, quitarla del manifiesto debe significar que
372
+ deja de aplicar. \`plan\` lo muestra como \`delete\`.
250
373
  - El \`slug\`/\`handle\` del contenido es la identidad; el nombre de archivo es convenci\xF3n.
251
374
  - Las \`relationships\` van DENTRO del archivo de su objeto origen (\`source\` impl\xEDcito):
252
375
 
253
- # objects/vestido.yaml
254
- slug: vestido
255
- title: Vestidos
256
- titleSingular: Vestido
257
- description: Vestido de renta, unidad serializada.
258
- synonyms: [dress, prenda]
376
+ # objects/producto.yaml
377
+ slug: producto
378
+ title: Productos
379
+ titleSingular: Producto
380
+ description: Producto del cat\xE1logo, unidad serializada.
381
+ synonyms: [product, item]
259
382
  attributes:
260
- - slug: talla
261
- title: Talla
262
- description: Talla del vestido.
383
+ - slug: categoria
384
+ description: Categor\xEDa del producto. # title impl\xEDcito: "Categoria" (del slug)
263
385
  dataType: select
264
386
  isRequired: true
265
- config: { options: [XS, S, M, L, XL] }
387
+ config: { options: [A, B, C] }
266
388
  - slug: sku
267
- title: SKU
389
+ title: SKU # title expl\xEDcito cuando el slug no basta
268
390
  description: C\xF3digo \xFAnico.
269
391
  dataType: text
270
392
  isUnique: true
271
393
  relationships:
272
- - slug: vestido_rentas
273
- title: Rentas del vestido
274
- description: Las rentas de este vestido.
275
- target: rental
394
+ - slug: producto_bookings
395
+ title: Reservas del producto
396
+ description: Las reservas de este producto.
397
+ target: booking
276
398
  cardinality: one_to_many
277
399
 
278
400
  - \`description\` es obligatoria en todo (objetos, atributos, workflows): es el contexto
279
401
  con el que los agentes LLM de la plataforma descubren y operan cada cosa v\xEDa MCP.
280
402
  \`synonyms\` ayuda al mismo fin.
403
+ - \`title\` es OPCIONAL: si lo omites se deriva del \`slug\` (\`precio_base\` \u2192 "Precio Base").
404
+ En un object, \`titleSingular\` ausente cae al \`title\`. Decl\xE1ralos solo cuando el derivado
405
+ no baste (siglas, may\xFAsculas especiales). \`description\` NUNCA se deriva: escr\xEDbela siempre.
406
+ - **Secretos: NUNCA en el manifiesto.** El manifiesto vive en git (historial permanente,
407
+ clones que viajan). No pongas tokens, API keys ni passwords en ning\xFAn \`.yaml\` \u2014 ni
408
+ "temporalmente". Un secreto commiteado queda en el historial para siempre. Cuando un
409
+ workflow o agente necesite una credencial externa (p. ej. una API de terceros), se
410
+ **referenciar\xE1** desde un vault con \`\${secret:nombre}\` y el valor vivir\xE1 fuera de git;
411
+ jam\xE1s inline. (Las credenciales del CLI ya viven fuera: \`~/.config/hablala\` o la variable
412
+ \`HABLALA_ACCESS_TOKEN\`.)
281
413
  - \`dataType\`: text | number | boolean | date | timestamp | select | multiselect |
282
- reference | file. \`cardinality\`: one_to_one | one_to_many | many_to_many.
414
+ reference | file | formula | rollup. \`cardinality\`: one_to_one | one_to_many | many_to_many.
415
+ Los dos \xFAltimos son DERIVADOS (se calculan al leer, no se almacenan): \`formula\` computa de
416
+ otros campos del MISMO record (\`config: { expression: "subtotal + tax" }\`); \`rollup\` agrega
417
+ campos de records RELACIONADOS (\`config: { relationship, aggregate: sum|count|avg|min|max, target }\`).
418
+ No admiten \`isRequired\`/\`isIndexed\`/\`embedInVector\`.
419
+ - **\`config\` por tipo** (el \`plan\` valida su forma; un error se atrapa antes de aplicar):
420
+ - \`select\`/\`multiselect\`: \`config: { options: [...] }\` \u2014 OBLIGATORIO y no vac\xEDo.
421
+ - \`number\`: \`config: { min, max }\` \u2014 num\xE9ricos y \`min <= max\` (ambos opcionales).
422
+ - \`file\`: \`config: { maxCount, acceptedContentTypes }\` \u2014 \`maxCount\` entero positivo;
423
+ \`acceptedContentTypes\` lista de mime (admite comodines: \`image/*\`).
424
+ - \`reference\`: \`config: { targetObject: <slug> }\` \u2014 OPCIONAL; restringe la referencia a
425
+ records de ese object (el \`plan\` valida que el object exista; al escribir, el motor
426
+ rechaza un record de otro tipo). Sin \`targetObject\`, la referencia acepta cualquier record.
427
+ - **Flags por tipo** (tambi\xE9n validados en el \`plan\`): \`isUnique\` no va en
428
+ \`multiselect\`/\`boolean\`/\`file\`; un \`file\` no se indexa (\`isIndexed\`) ni se embebe
429
+ (\`embedInVector\`). \`defaultValue\` es el sobre del valor (un objeto), no un escalar crudo.
283
430
 
284
431
  ## El \xE1rbol de decisi\xF3n: \xBFobjeto del motor o m\xF3dulo core?
285
432
 
@@ -293,7 +440,7 @@ NO los redefinas como objetos \u2014 \xFAsalos:
293
440
  | Facturas, pagos, numeraci\xF3n legal | \`invoicing\` | \`factura\`, \`pago\` |
294
441
  | Stock (ledger de doble entrada) | \`inventory\` | \`stock\`, \`existencias\` |
295
442
 
296
- Todo lo dem\xE1s \u2014 los **sustantivos del negocio** (p\xF3lizas, pacientes, vestidos, \xF3rdenes) \u2014
443
+ Todo lo dem\xE1s \u2014 los **sustantivos del negocio** que defina tu vertical \u2014
297
444
  son objetos del modelo de datos en \`objects/\`. **En caso de duda: objeto del motor.**
298
445
 
299
446
  Objetos est\xE1ndar ya sembrados (exti\xE9ndelos o arch\xEDvalos, no los dupliques):
@@ -307,14 +454,14 @@ es de sistema (proyecci\xF3n read-only): no lo declares.
307
454
  - \`company\` = empresa del CRM. La organizaci\xF3n (tenant) NUNCA se llama company.
308
455
  - \`product\`/\`price\` separados: el precio nunca vive en el producto.
309
456
  - \`account\` est\xE1 prohibido (polisemia). Usa el t\xE9rmino espec\xEDfico.
310
- - Slugs en snake_case, singulares (\`vestido\`, no \`vestidos\`); el plural va en \`title\`.
457
+ - Slugs en snake_case, singulares (\`producto\`, no \`productos\`); el plural va en \`title\`.
311
458
 
312
459
  ## Workflows y agentes
313
460
 
314
461
  # workflows/al_devolver.yaml
315
462
  slug: al_devolver
316
463
  title: Al devolver
317
- description: Reacciona a la devoluci\xF3n de una renta.
464
+ description: Reacciona a la devoluci\xF3n de un booking.
318
465
  trigger: { event_type: booking.returned }
319
466
  initialState: registrar
320
467
  states:
@@ -328,30 +475,137 @@ es de sistema (proyecci\xF3n read-only): no lo declares.
328
475
  name: Recepcionista
329
476
  description: Atiende consultas y agenda citas.
330
477
  systemPrompt: Eres una recepcionista amable\u2026
331
- allowedActivities: [search_records, send_message]
478
+ provider: anthropic # opcional; registrado (anthropic). Omite = default
479
+ model: claude-opus-4-8 # opcional; texto libre, lo valida el provider
480
+ authoritySource: delegated # delegated | assigned (opcional; default delegated)
481
+ allowedActivities: [search_records] # allowlist de TOOLS (ver abajo)
482
+ agentPermissions: [records:read] # allowlist RBAC que estrecha el scope delegado (opcional)
483
+ handoffs: [ventas] # handles a los que puede TRANSFERIR la conversaci\xF3n (opcional)
484
+ approvalRequired: [create_record] # tools que exigen aprobaci\xF3n humana (opcional; \u2286 allowedActivities)
332
485
 
333
486
  Los agentes se identifican por \`handle\`; quitar su archivo los revoca (archive).
487
+
488
+ - \`allowedActivities\` son las **tools** que el agente puede llamar. Deben ser tools reales
489
+ (hoy: \`search_records\`); un slug fuera del cat\xE1logo lo rechaza el \`plan\`. NO pongas aqu\xED
490
+ efectos del motor como \`send_message\` (el agente responde solo, no es una tool).
491
+ - \`agentPermissions\` son permisos RBAC \`recurso:accion\` (p. ej. \`records:read\`,
492
+ \`records:create\`) que **acotan** lo que el agente puede hacer por debajo de su due\xF1o
493
+ (least-privilege). Vac\xEDo = hereda todo lo del due\xF1o. Un permiso inexistente lo rechaza el \`plan\`.
494
+ - El agente act\xFAa **a nombre de un humano** (\`ownerUserId\`, id p\xFAblico \`user_\u2026\`). Con un
495
+ usuario, el creador es el due\xF1o por defecto; con un token de m\xE1quina, \`ownerUserId\` es
496
+ **obligatorio** al crear.
497
+ - \`handoffs\` son los **handles** de otros agentes a los que este puede **transferir** la
498
+ conversaci\xF3n (handoff / sub-agente): el motor le da una tool \`transfer_to_agent\` acotada a
499
+ esa lista, y el agente destino contin\xFAa. Cada handle debe ser un agente real (no \xE9l mismo);
500
+ lo valida el \`plan\`.
501
+ - \`approvalRequired\` son tools (\u2286 \`allowedActivities\`) que exigen **aprobaci\xF3n humana** antes
502
+ de correr (para acciones irreversibles): el motor crea una tarea y espera el visto bueno en vez
503
+ de ejecutarlas directo.
504
+ - \`evals\` son **casos de prueba** del comportamiento del agente (testing declarativo): cada uno
505
+ da un \`input\`, aserciones \`expect\` \u2014 \`tool\`, \`noTool\`, \`handoff\`, \`requiresApproval\`,
506
+ \`contains\` \u2014 y un \`script\` opcional. Corre con \`hablala eval\`.
507
+
508
+ Dos modos (como promptfoo): por defecto, **determinista** \u2014 el \`script\` declara qu\xE9 hace el
509
+ agente-guionizado (\`{tool, input}\` o \`{text}\`) y las aserciones verifican que el motor lo
510
+ cablea bien, sin tokens, apto para CI. Con \`--live\`, contra el LLM real (prueba qu\xE9 elige de
511
+ verdad; el \`script\` se ignora). Sin \`script\` ni \`--live\`, las aserciones de comportamiento
512
+ no son evaluables (no se puede predecir qu\xE9 har\xEDa el agente). Ejemplo:
513
+
514
+ # dentro del archivo del agente
515
+ evals:
516
+ - name: busca al preguntar por un producto
517
+ input: \xBFtienen sillas de oficina?
518
+ script: { tool: search_records } # el guion determinista
519
+ expect: { tool: search_records }
520
+ - name: escala una queja al humano
521
+ input: quiero cancelar y hablar con alguien
522
+ script: { tool: transfer_to_agent, input: { target: soporte } }
523
+ expect: { handoff: soporte }
524
+
525
+ ## Policies (control de acceso ABAC)
526
+
527
+ Una policy define QU\xC9 datos ve cada qui\xE9n. El motor es **default-deny**: sin una policy
528
+ \`allow\`, un principal no ve nada de un objeto. Se identifican por \`slug\`.
529
+
530
+ # policies/storefront_producto_publicado.yaml
531
+ slug: storefront_producto_publicado
532
+ effect: allow # allow | deny (deny gana)
533
+ action: [read, update] # read | create | update | delete | signal \u2014 string o lista
534
+ principal: storefront # qui\xE9n (ver abajo)
535
+ object: producto # slug del object; OMITE la clave para "toda la organizaci\xF3n"
536
+ condition: { attr: estado, op: eq, value: publicado } # predicado por fila (opcional)
537
+ field_mask: [nombre, categoria, estado] # campos visibles (opcional)
538
+
539
+ - \`action\` acepta **un string o una lista**: \`action: [read, update]\` concede ambas bajo
540
+ el mismo slug (una policy declarada = N grants, uno por acci\xF3n). Quitar una acci\xF3n de la
541
+ lista borra solo ese grant; \`pull\` re-colapsa las acciones de un slug en la lista.
542
+ - \`principal\` es una **referencia legible** (nunca un id): \`storefront\` (el recorte
543
+ p\xFAblico del frontend), \`access_token\` (agentes que escriben por HTTP), \`role:<name>\`
544
+ (un rol) o \`agent:<handle>\` (un agente). Los principales por USUARIO no se declaran
545
+ aqu\xED \u2014 son datos, no config; gesti\xF3nalos por API/MCP.
546
+ - \`object\` es el slug del object gobernado; el server resuelve la ref a su id al aplicar.
547
+ - **Al quitar el archivo la policy se BORRA** (no se archiva): deja de conceder/negar.
548
+ \`plan\` lo muestra como \`delete\` \u2014 rev\xEDsalo, es un cambio de seguridad.
549
+ - Los secretos NUNCA van en una policy (ni en ning\xFAn \`.yaml\`): ver la regla de secretos.
550
+
551
+ ### La \`condition\` (filtrado por fila) y el \`field_mask\` (por campo)
552
+
553
+ La \`condition\` es un predicado ABAC opcional: la policy solo aplica a las filas que lo
554
+ satisfacen. Misma gram\xE1tica que el guard de un \`choice\` de workflow:
555
+
556
+ condition: { attr: <slug>, op: <op>, value: <literal> } # una hoja
557
+ condition: { and: [ <hoja>, <hoja>, \u2026 ] } # todas
558
+ condition: { or: [ <hoja>, <hoja>, \u2026 ] } # alguna
559
+
560
+ - \`attr\` es un slug de atributo **del object gobernado**. \`op\` \u2208 \`eq\`, \`neq\`, \`gt\`,
561
+ \`gte\`, \`lt\`, \`lte\`, \`in\`, \`contains\`, \`is_null\`, \`is_not_null\`. El operador debe
562
+ ser compatible con el tipo del atributo (p. ej. \`gt\` no aplica a un \`select\`).
563
+ - **ABAC din\xE1mico**: en vez de un \`value\` literal, una hoja puede comparar contra un
564
+ atributo del solicitante con \`value_from: "principal.<attr>"\` \u2014 p. ej. "cada quien ve
565
+ solo las filas de su misma regi\xF3n":
566
+
567
+ condition: { attr: region, op: eq, value_from: "principal.region" }
568
+
569
+ - \`field_mask\` es la lista de slugs de atributo **visibles**; omitirla = todos los
570
+ permitidos. Con varias policies \`allow\`, la visibilidad es la intersecci\xF3n de sus masks.
571
+ - Todo esto se **valida en el \`plan\`**: un \`attr\`/campo inexistente, un \`op\` desconocido
572
+ o incompatible con el tipo es un conflicto que bloquea el apply (no un fallo silencioso
573
+ en runtime). Corr\xEDgelo en tu loop antes de aplicar.
334
574
  `;
335
575
  }
336
576
  function hablalaYaml(identity, endpoint) {
337
- return `# Metadatos del workspace (informativo \u2014 la identidad real sale del access token).
338
- # Generado por \`hablala init\`; \`pull\`/\`plan\`/\`apply\` no lo leen.
577
+ return `# Metadatos de la organizaci\xF3n (informativo \u2014 la identidad real sale del access token).
578
+ # Generado por \`hablala init\`. Portable entre entornos: no versiona ids del server, solo
579
+ # nombres/slugs legibles. Adem\xE1s, \`plan\`/\`apply\` leen \`modes\` (abajo) de este archivo.
339
580
  endpoint: ${endpoint}
340
581
  organization:
341
- id: ${identity.organization.id}
342
582
  name: ${JSON.stringify(identity.organization.name)}
343
583
  slug: ${identity.organization.slug}
344
- workspace:
345
- id: ${identity.workspace.id}
346
- name: ${JSON.stringify(identity.workspace.name)}
347
- slug: ${identity.workspace.slug}
584
+
585
+ # Modo de reconciliaci\xF3n por secci\xF3n. Default (sin declarar): "authoritative" \u2014 lo no declarado
586
+ # se archiva/borra (estado deseado completo). Ponlo en "additive" para A\xD1ADIR sin expulsar lo no
587
+ # declarado (\xFAtil cuando declaras solo una parte del modelo; least astonishment). An\xE1logo al
588
+ # server-side apply de Kubernetes: intenci\xF3n parcial, sin pruning.
589
+ # modes:
590
+ # objects: additive
591
+ # relationships: additive
592
+ `;
593
+ }
594
+ function gitignore() {
595
+ return `# Credenciales y secretos \u2014 NUNCA en git (viven en ~/.config/hablala o en variables de entorno).
596
+ credentials.json
597
+ .env
598
+ .env.*
599
+ !.env.example
600
+ *.local.yaml
601
+ *.local.yml
348
602
  `;
349
603
  }
350
604
 
351
605
  // src/manifest.ts
352
606
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
353
607
  import { join as join2 } from "path";
354
- import { parse, stringify } from "yaml";
608
+ import { parse, parseDocument, stringify } from "yaml";
355
609
  var DATA_TYPES = [
356
610
  "text",
357
611
  "number",
@@ -361,10 +615,14 @@ var DATA_TYPES = [
361
615
  "select",
362
616
  "multiselect",
363
617
  "reference",
364
- "file"
618
+ "file",
619
+ "formula",
620
+ "rollup"
365
621
  ];
366
622
  var CARDINALITIES = ["one_to_one", "one_to_many", "many_to_many"];
367
623
  var AUTHORITY_SOURCES = ["delegated", "assigned"];
624
+ var POLICY_EFFECTS = ["allow", "deny"];
625
+ var POLICY_ACTIONS = ["read", "create", "update", "delete", "signal"];
368
626
  var OBJECT_KEYS = withSnake([
369
627
  "slug",
370
628
  "title",
@@ -372,6 +630,11 @@ var OBJECT_KEYS = withSnake([
372
630
  "description",
373
631
  "synonyms",
374
632
  "config",
633
+ // Primary field (patrón Airtable): el slug del attribute que titula un record. Opcional.
634
+ "titleAttributeSlug",
635
+ // Señal read-only que emite `pull` (tenant/seeded/system): la aceptamos para que re-aplicar un
636
+ // manifiesto recién exportado no falle como "clave desconocida". El server la ignora en el diff.
637
+ "manageability",
375
638
  "attributes",
376
639
  "relationships"
377
640
  ]);
@@ -415,15 +678,68 @@ var AGENT_KEYS = withSnake([
415
678
  "authoritySource",
416
679
  "allowedActivities",
417
680
  "agentPermissions",
681
+ "handoffs",
682
+ "approvalRequired",
683
+ "evals",
418
684
  "ownerUserId"
419
685
  ]);
686
+ var POLICY_KEYS = withSnake([
687
+ "slug",
688
+ "effect",
689
+ "action",
690
+ "principal",
691
+ "object",
692
+ "condition",
693
+ "fieldMask"
694
+ ]);
695
+ var ROLE_KEYS = withSnake(["name", "permissions"]);
420
696
  function withSnake(keys) {
421
697
  const snake = keys.map((key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
422
698
  return /* @__PURE__ */ new Set([...keys, ...snake]);
423
699
  }
700
+ var SECTION_MODES = ["authoritative", "additive"];
701
+ function readModes(dir, problems) {
702
+ const modes = {};
703
+ const file = join2(dir, "hablala.yaml");
704
+ if (!existsSync2(file)) return modes;
705
+ const doc = parse(readFileSync2(file, "utf8"));
706
+ const declared = doc?.modes;
707
+ if (!declared || typeof declared !== "object") return modes;
708
+ for (const [section, mode] of Object.entries(declared)) {
709
+ if (typeof mode === "string" && SECTION_MODES.includes(mode)) {
710
+ modes[section] = mode;
711
+ } else {
712
+ problems.push(
713
+ `hablala.yaml: modes.${section} inv\xE1lido "${String(mode)}" (usa ${SECTION_MODES.join(" | ")})`
714
+ );
715
+ }
716
+ }
717
+ return modes;
718
+ }
719
+ var SETTINGS_KEYS = /* @__PURE__ */ new Set(["endUserObjectSlug", "end_user_object_slug"]);
720
+ function readSettings(dir, problems) {
721
+ const file = join2(dir, "hablala.yaml");
722
+ if (!existsSync2(file)) return void 0;
723
+ const doc = parse(readFileSync2(file, "utf8"));
724
+ const declared = doc?.settings;
725
+ if (declared === void 0 || declared === null) return void 0;
726
+ if (typeof declared !== "object" || Array.isArray(declared)) {
727
+ problems.push("hablala.yaml: settings debe ser un objeto (singleton, no una lista)");
728
+ return void 0;
729
+ }
730
+ const settings = declared;
731
+ const unknown = Object.keys(settings).filter((key) => !SETTINGS_KEYS.has(key));
732
+ if (unknown.length > 0) {
733
+ problems.push(`hablala.yaml: settings tiene claves desconocidas: ${unknown.join(", ")} (\xBFtypo?)`);
734
+ }
735
+ return settings;
736
+ }
424
737
  function readManifest(dir) {
425
738
  const problems = [];
739
+ const modes = readModes(dir, problems);
426
740
  const manifest = {};
741
+ const settings = readSettings(dir, problems);
742
+ if (settings) manifest.settings = settings;
427
743
  const objectsDir = join2(dir, "objects");
428
744
  if (existsSync2(objectsDir)) {
429
745
  const objects = [];
@@ -440,6 +756,7 @@ function readManifest(dir) {
440
756
  `objects/${file}`,
441
757
  problems
442
758
  );
759
+ validateAttributeRules(attribute, `objects/${file} (attribute)`, problems);
443
760
  }
444
761
  for (const relationship of asList(embedded)) {
445
762
  const declared = relationship;
@@ -484,15 +801,37 @@ function readManifest(dir) {
484
801
  `agents/${file}`,
485
802
  problems
486
803
  );
804
+ validateStringList(content, ["allowedActivities", "allowed_activities"], `agents/${file}`, problems);
805
+ validateStringList(content, ["agentPermissions", "agent_permissions"], `agents/${file}`, problems);
806
+ validateStringList(content, ["handoffs"], `agents/${file}`, problems);
807
+ validateStringList(content, ["approvalRequired", "approval_required"], `agents/${file}`, problems);
808
+ validateEvals(content.evals, `agents/${file}`, problems);
809
+ return content;
810
+ });
811
+ }
812
+ const policiesDir = join2(dir, "policies");
813
+ if (existsSync2(policiesDir)) {
814
+ manifest.policies = readYamlDir(policiesDir, problems).map(({ file, content }) => {
815
+ validateEntity(content, "slug", POLICY_KEYS, `policies/${file}`, problems);
816
+ validateEnum(content, ["effect"], POLICY_EFFECTS, `policies/${file}`, problems);
817
+ validateEnumOrList(content, "action", POLICY_ACTIONS, `policies/${file}`, problems);
487
818
  return content;
488
819
  });
489
820
  }
490
- return { manifest, problems };
821
+ const rolesDir = join2(dir, "roles");
822
+ if (existsSync2(rolesDir)) {
823
+ manifest.roles = readYamlDir(rolesDir, problems).map(({ file, content }) => {
824
+ validateEntity(content, "name", ROLE_KEYS, `roles/${file}`, problems);
825
+ return content;
826
+ });
827
+ }
828
+ return { manifest, modes, problems };
491
829
  }
492
830
  function writeManifest(dir, manifest, options = {}) {
493
831
  const written = [];
494
832
  const stale = [];
495
833
  const pruned = [];
834
+ const drift = [];
496
835
  const objects = manifest.objects ?? [];
497
836
  const relationships = manifest.relationships ?? [];
498
837
  const bySource = /* @__PURE__ */ new Map();
@@ -503,6 +842,14 @@ function writeManifest(dir, manifest, options = {}) {
503
842
  list.push(rest);
504
843
  bySource.set(relationship.source, list);
505
844
  }
845
+ const shared = {
846
+ written,
847
+ stale,
848
+ pruned,
849
+ drift,
850
+ prune: options.prune ?? false,
851
+ check: options.check ?? false
852
+ };
506
853
  syncDir(
507
854
  join2(dir, "objects"),
508
855
  objects.map((object) => {
@@ -513,7 +860,7 @@ function writeManifest(dir, manifest, options = {}) {
513
860
  };
514
861
  }),
515
862
  "slug",
516
- { written, stale, pruned, prune: options.prune ?? false, base: "objects" }
863
+ { ...shared, base: "objects", banner: objectBanner }
517
864
  );
518
865
  syncDir(
519
866
  join2(dir, "workflows"),
@@ -522,18 +869,62 @@ function writeManifest(dir, manifest, options = {}) {
522
869
  content: clean({ ...workflow })
523
870
  })),
524
871
  "slug",
525
- { written, stale, pruned, prune: options.prune ?? false, base: "workflows" }
872
+ { ...shared, base: "workflows" }
526
873
  );
527
874
  syncDir(
528
875
  join2(dir, "agents"),
529
876
  (manifest.agents ?? []).map((agent) => ({ id: agent.handle, content: clean({ ...agent }) })),
530
877
  "handle",
531
- { written, stale, pruned, prune: options.prune ?? false, base: "agents" }
878
+ { ...shared, base: "agents" }
879
+ );
880
+ syncDir(
881
+ join2(dir, "policies"),
882
+ (manifest.policies ?? []).map((policy) => ({ id: policy.slug, content: clean({ ...policy }) })),
883
+ "slug",
884
+ { ...shared, base: "policies" }
885
+ );
886
+ syncDir(
887
+ join2(dir, "roles"),
888
+ (manifest.roles ?? []).map((role) => ({ id: role.name, content: clean({ ...role }) })),
889
+ "name",
890
+ { ...shared, base: "roles" }
532
891
  );
533
- return { written, stale, pruned };
892
+ syncSettings(dir, manifest.settings, shared);
893
+ return { written, stale, pruned, drift };
894
+ }
895
+ function syncSettings(dir, settings, out2) {
896
+ const file = join2(dir, "hablala.yaml");
897
+ if (!existsSync2(file) && (!settings || Object.keys(settings).length === 0)) return;
898
+ const doc = existsSync2(file) ? parseDocument(readFileSync2(file, "utf8")) : parseDocument("");
899
+ const current = doc.get("settings");
900
+ const currentJson = current ? JSON.stringify(doc.toJS().settings) : null;
901
+ const desiredJson = settings && Object.keys(settings).length > 0 ? JSON.stringify(settings) : null;
902
+ if (currentJson === desiredJson) return;
903
+ if (out2.check) {
904
+ out2.drift.push("hablala.yaml");
905
+ return;
906
+ }
907
+ if (desiredJson === null) doc.delete("settings");
908
+ else doc.set("settings", settings);
909
+ writeFileSync3(file, doc.toString(), "utf8");
910
+ out2.written.push("hablala.yaml");
911
+ }
912
+ function objectBanner(content) {
913
+ const level = content.manageability;
914
+ if (level === "seeded") {
915
+ return "# manageability: seeded \u2014 sembrado por la plataforma. NO edites su ra\xEDz (title/description/\n# config): re-aplicar el YAML tal cual es un noop. S\xCD puedes extenderlo agregando attributes.\n";
916
+ }
917
+ if (level === "system") {
918
+ return "# manageability: system \u2014 proyecci\xF3n de la plataforma, intocable. NO lo declares, edites ni\n# archives; hacerlo es un error de plan. Est\xE1 aqu\xED solo como referencia de lo que existe.\n";
919
+ }
920
+ return "";
534
921
  }
535
922
  function syncDir(dirPath, entities, idKey, out2) {
536
- mkdirSync2(dirPath, { recursive: true });
923
+ if (!out2.check) mkdirSync2(dirPath, { recursive: true });
924
+ else if (!existsSync2(dirPath)) {
925
+ for (const { id } of entities) out2.drift.push(`${out2.base}/${id}.yaml`);
926
+ return;
927
+ }
537
928
  const fileById = /* @__PURE__ */ new Map();
538
929
  for (const file of yamlFiles(dirPath)) {
539
930
  try {
@@ -546,13 +937,22 @@ function syncDir(dirPath, entities, idKey, out2) {
546
937
  const writtenFiles = /* @__PURE__ */ new Set();
547
938
  for (const { id, content } of entities) {
548
939
  const file = fileById.get(id) ?? `${id}.yaml`;
549
- writeFileSync3(join2(dirPath, file), stringify(content), "utf8");
940
+ const serialized = (out2.banner?.(content) ?? "") + stringify(content);
941
+ if (out2.check) {
942
+ const path = join2(dirPath, file);
943
+ const current = existsSync2(path) ? readFileSync2(path, "utf8") : null;
944
+ if (current !== serialized) out2.drift.push(`${out2.base}/${file}`);
945
+ } else {
946
+ writeFileSync3(join2(dirPath, file), serialized, "utf8");
947
+ out2.written.push(`${out2.base}/${file}`);
948
+ }
550
949
  writtenFiles.add(file);
551
- out2.written.push(`${out2.base}/${file}`);
552
950
  }
553
951
  for (const file of yamlFiles(dirPath)) {
554
952
  if (writtenFiles.has(file)) continue;
555
- if (out2.prune) {
953
+ if (out2.check) {
954
+ out2.drift.push(`${out2.base}/${file}`);
955
+ } else if (out2.prune) {
556
956
  rmSync(join2(dirPath, file));
557
957
  out2.pruned.push(`${out2.base}/${file}`);
558
958
  } else {
@@ -603,9 +1003,161 @@ function validateEnum(entity, keys, allowed, where, problems) {
603
1003
  }
604
1004
  }
605
1005
  }
1006
+ function validateEnumOrList(entity, key, allowed, where, problems) {
1007
+ const value = entity[key];
1008
+ if (value === void 0) return;
1009
+ const values = Array.isArray(value) ? value : [value];
1010
+ if (values.length === 0) {
1011
+ problems.push(`${where}: "${key}" no puede ser una lista vac\xEDa`);
1012
+ return;
1013
+ }
1014
+ for (const item of values) {
1015
+ if (typeof item !== "string" || !allowed.includes(item)) {
1016
+ problems.push(
1017
+ `${where}: "${key}: ${String(item)}" no es v\xE1lido (valores: ${allowed.join(", ")})`
1018
+ );
1019
+ }
1020
+ }
1021
+ }
1022
+ function validateStringList(entity, keys, where, problems) {
1023
+ for (const key of keys) {
1024
+ const value = entity[key];
1025
+ if (value === void 0) continue;
1026
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
1027
+ problems.push(`${where}: "${key}" debe ser una lista de slugs (strings)`);
1028
+ }
1029
+ }
1030
+ }
1031
+ var EVAL_ASSERTIONS = /* @__PURE__ */ new Set([
1032
+ "tool",
1033
+ "noTool",
1034
+ "no_tool",
1035
+ "handoff",
1036
+ "requiresApproval",
1037
+ "requires_approval",
1038
+ "contains"
1039
+ ]);
1040
+ function validateEvals(evals, where, problems) {
1041
+ if (evals === void 0) return;
1042
+ if (!Array.isArray(evals)) {
1043
+ problems.push(`${where}: "evals" debe ser una lista de casos de prueba`);
1044
+ return;
1045
+ }
1046
+ for (const raw of evals) {
1047
+ if (!raw || typeof raw !== "object") {
1048
+ problems.push(`${where}: cada eval debe ser un mapa {name, input, expect}`);
1049
+ continue;
1050
+ }
1051
+ const eval_ = raw;
1052
+ if (typeof eval_.name !== "string" || eval_.name === "")
1053
+ problems.push(`${where}: un eval declara un "name" no vac\xEDo`);
1054
+ if (typeof eval_.input !== "string" || eval_.input === "")
1055
+ problems.push(`${where}: el eval "${String(eval_.name)}" declara un "input" no vac\xEDo`);
1056
+ const expect = eval_.expect;
1057
+ if (expect !== void 0) {
1058
+ if (!expect || typeof expect !== "object") {
1059
+ problems.push(`${where}: el "expect" del eval "${String(eval_.name)}" debe ser un mapa`);
1060
+ } else {
1061
+ for (const key of Object.keys(expect)) {
1062
+ if (!EVAL_ASSERTIONS.has(key))
1063
+ problems.push(`${where}: el eval "${String(eval_.name)}" usa aserci\xF3n desconocida "${key}"`);
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+ }
1069
+ var UNIQUE_INCOMPATIBLE = /* @__PURE__ */ new Set(["multiselect", "boolean", "file", "formula", "rollup"]);
1070
+ var OPTIONS_TYPES = /* @__PURE__ */ new Set(["select", "multiselect"]);
1071
+ var DERIVED_TYPES = /* @__PURE__ */ new Set(["formula", "rollup"]);
1072
+ var ROLLUP_AGGREGATES = /* @__PURE__ */ new Set(["sum", "count", "avg", "min", "max"]);
1073
+ function flag(attribute, camel, snake) {
1074
+ return attribute[camel] === true || attribute[snake] === true;
1075
+ }
1076
+ function validateAttributeRules(attribute, where, problems) {
1077
+ const dataType = attribute.dataType ?? attribute.data_type;
1078
+ if (typeof dataType !== "string" || !DATA_TYPES.includes(dataType)) return;
1079
+ if (flag(attribute, "isUnique", "is_unique") && UNIQUE_INCOMPATIBLE.has(dataType)) {
1080
+ problems.push(`${where}: "isUnique" no es soportado para el tipo ${dataType}`);
1081
+ }
1082
+ if (dataType === "file") {
1083
+ if (flag(attribute, "isIndexed", "is_indexed"))
1084
+ problems.push(`${where}: "isIndexed" no es soportado para el tipo file`);
1085
+ if (flag(attribute, "embedInVector", "embed_in_vector"))
1086
+ problems.push(`${where}: "embedInVector" no es soportado para el tipo file`);
1087
+ }
1088
+ if (DERIVED_TYPES.has(dataType)) {
1089
+ if (flag(attribute, "isIndexed", "is_indexed"))
1090
+ problems.push(`${where}: "isIndexed" no es soportado para el tipo ${dataType} (derivado)`);
1091
+ if (flag(attribute, "embedInVector", "embed_in_vector"))
1092
+ problems.push(`${where}: "embedInVector" no es soportado para el tipo ${dataType} (derivado)`);
1093
+ if (flag(attribute, "isRequired", "is_required"))
1094
+ problems.push(`${where}: "isRequired" no es soportado para el tipo ${dataType} (derivado)`);
1095
+ }
1096
+ const config = attribute.config;
1097
+ const cfg = config && typeof config === "object" ? config : {};
1098
+ if (OPTIONS_TYPES.has(dataType)) {
1099
+ const options = cfg.options;
1100
+ if (!Array.isArray(options) || options.length === 0) {
1101
+ problems.push(`${where}: el tipo ${dataType} requiere "config.options" (lista no vac\xEDa)`);
1102
+ } else if (!options.every((o) => typeof o === "string" || o && typeof o === "object")) {
1103
+ problems.push(`${where}: "config.options" debe ser una lista de strings (o de {value, label})`);
1104
+ }
1105
+ }
1106
+ if (dataType === "number") {
1107
+ const { min, max } = cfg;
1108
+ if (min !== void 0 && typeof min !== "number")
1109
+ problems.push(`${where}: "config.min" debe ser un n\xFAmero`);
1110
+ if (max !== void 0 && typeof max !== "number")
1111
+ problems.push(`${where}: "config.max" debe ser un n\xFAmero`);
1112
+ if (typeof min === "number" && typeof max === "number" && min > max)
1113
+ problems.push(`${where}: "config.min" no puede ser mayor que "config.max"`);
1114
+ }
1115
+ if (dataType === "file") {
1116
+ const maxCount = cfg.max_count ?? cfg.maxCount;
1117
+ if (maxCount !== void 0 && !(typeof maxCount === "number" && Number.isInteger(maxCount) && maxCount > 0))
1118
+ problems.push(`${where}: "config.maxCount" debe ser un entero positivo`);
1119
+ const accepted = cfg.accepted_content_types ?? cfg.acceptedContentTypes;
1120
+ if (accepted !== void 0 && (!Array.isArray(accepted) || !accepted.every((t) => typeof t === "string")))
1121
+ problems.push(`${where}: "config.acceptedContentTypes" debe ser una lista de strings (mime, admite comodines image/*)`);
1122
+ }
1123
+ if (dataType === "reference") {
1124
+ const target = cfg.target_object ?? cfg.targetObject;
1125
+ if (target !== void 0 && !(typeof target === "string" && target.length > 0))
1126
+ problems.push(`${where}: "config.targetObject" debe ser un slug de object (string no vac\xEDo)`);
1127
+ }
1128
+ if (dataType === "formula") {
1129
+ const expression = cfg.expression;
1130
+ if (typeof expression !== "string" || expression.length === 0)
1131
+ problems.push(`${where}: el tipo formula requiere "config.expression" (string no vac\xEDo)`);
1132
+ }
1133
+ if (dataType === "rollup") {
1134
+ const relationship = cfg.relationship;
1135
+ const aggregate = cfg.aggregate;
1136
+ const target = cfg.target;
1137
+ if (typeof relationship !== "string" || relationship.length === 0)
1138
+ problems.push(`${where}: el tipo rollup requiere "config.relationship" (slug del relationship)`);
1139
+ if (typeof aggregate !== "string" || !ROLLUP_AGGREGATES.has(aggregate))
1140
+ problems.push(
1141
+ `${where}: el tipo rollup requiere "config.aggregate" \u2208 ${[...ROLLUP_AGGREGATES].join("/")}`
1142
+ );
1143
+ if (aggregate !== "count" && (typeof target !== "string" || target.length === 0))
1144
+ problems.push(`${where}: el rollup "${String(aggregate)}" requiere "config.target" (slug del atributo a agregar)`);
1145
+ }
1146
+ }
606
1147
  function asList(value) {
607
1148
  return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
608
1149
  }
1150
+ var VERSION_FILE = ".hablala-version";
1151
+ function writeVersion(dir, version2) {
1152
+ writeFileSync3(join2(dir, VERSION_FILE), `${version2}
1153
+ `, "utf8");
1154
+ }
1155
+ function readVersion(dir) {
1156
+ const path = join2(dir, VERSION_FILE);
1157
+ if (!existsSync2(path)) return void 0;
1158
+ const value = readFileSync2(path, "utf8").trim();
1159
+ return value === "" ? void 0 : value;
1160
+ }
609
1161
  function clean(value) {
610
1162
  const result = {};
611
1163
  for (const [key, entry] of Object.entries(value)) {
@@ -633,6 +1185,7 @@ import { createHash, randomBytes } from "crypto";
633
1185
  import { createServer } from "http";
634
1186
  import { hostname } from "os";
635
1187
  var CLIENT_ID = "hablala-cli";
1188
+ var DEFAULT_PRESET = "account_as_code";
636
1189
  var DEFAULT_APP_URL = "https://app.hablala.com";
637
1190
  var LOOPBACK_TIMEOUT_MS = 5 * 60 * 1e3;
638
1191
  var defaultSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
@@ -772,6 +1325,7 @@ async function loginWithBrowser(endpoint, deps = {}) {
772
1325
  authorizeUrl.searchParams.set("code_challenge", challenge);
773
1326
  authorizeUrl.searchParams.set("code_challenge_method", "S256");
774
1327
  authorizeUrl.searchParams.set("device_name", hostname());
1328
+ authorizeUrl.searchParams.set("preset", DEFAULT_PRESET);
775
1329
  log("Abriendo el navegador para autorizar\u2026");
776
1330
  if (!open(authorizeUrl.toString())) {
777
1331
  log("No se pudo abrir el navegador. Abre esta URL a mano:");
@@ -795,7 +1349,11 @@ async function loginWithDeviceFlow(endpoint, deps = {}) {
795
1349
  const startResponse = await fetchImpl(metadata.device_authorization_endpoint, {
796
1350
  method: "POST",
797
1351
  headers: { "content-type": "application/x-www-form-urlencoded" },
798
- body: new URLSearchParams({ client_id: CLIENT_ID, device_name: hostname() }).toString()
1352
+ body: new URLSearchParams({
1353
+ client_id: CLIENT_ID,
1354
+ device_name: hostname(),
1355
+ preset: DEFAULT_PRESET
1356
+ }).toString()
799
1357
  });
800
1358
  if (!startResponse.ok) {
801
1359
  throw new Error(`no se pudo iniciar el device flow (${startResponse.status}).`);
@@ -852,7 +1410,7 @@ var WRITE_PERMISSIONS = [
852
1410
  ];
853
1411
  var info = (message) => console.error(message);
854
1412
  var out = (message) => console.log(message);
855
- function flag(args, name) {
1413
+ function flag2(args, name) {
856
1414
  const value = args[name];
857
1415
  return typeof value === "string" ? value : void 0;
858
1416
  }
@@ -863,8 +1421,8 @@ function targetDir(args) {
863
1421
  return resolve2(process.cwd(), args._[1] ?? ".");
864
1422
  }
865
1423
  async function login(args) {
866
- const endpoint = (flag(args, "endpoint") ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
867
- let token = flag(args, "token") ?? process.env.HABLALA_ACCESS_TOKEN;
1424
+ const endpoint = (flag2(args, "endpoint") ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
1425
+ let token = flag2(args, "token") ?? process.env.HABLALA_ACCESS_TOKEN;
868
1426
  if (token) {
869
1427
  token = token.trim();
870
1428
  if (!token.startsWith("hpat_")) {
@@ -879,9 +1437,16 @@ async function login(args) {
879
1437
  const identity = await whoami(api);
880
1438
  const path = writeCredentials({ endpoint, accessToken: token });
881
1439
  out(
882
- `${green("\u2714")} Autenticado como ${bold(identity.organization.name)} / workspace ${bold(identity.workspace.name)}.`
1440
+ `${green("\u2714")} Autenticado en la organizaci\xF3n ${bold(identity.organization.name)}.`
883
1441
  );
884
1442
  out(dim(` Credenciales en ${path} (0600).`));
1443
+ if (identity.principal === "public") {
1444
+ out(
1445
+ `${yellow("!")} Esta es una API key publishable (solo lectura): \`pull\` y \`plan\` funcionan, pero \`apply\` no.`
1446
+ );
1447
+ out(dim(" Para aplicar cambios, emite un token de acceso (hpat_\u2026) con permisos de escritura."));
1448
+ return 0;
1449
+ }
885
1450
  const missing = WRITE_PERMISSIONS.filter(
886
1451
  (permission) => !identity.permissions.includes(permission)
887
1452
  );
@@ -896,13 +1461,29 @@ async function login(args) {
896
1461
  async function pull(args) {
897
1462
  const dir = targetDir(args);
898
1463
  const config = resolveConfig({
899
- tokenFlag: flag(args, "token"),
900
- endpointFlag: flag(args, "endpoint")
1464
+ tokenFlag: flag2(args, "token"),
1465
+ endpointFlag: flag2(args, "endpoint")
901
1466
  });
902
1467
  const api = createApiClient(config);
903
- info(dim(`\u2192 GET ${config.endpoint}/v1/workspace-config`));
904
- const manifest = await fetchManifest(api);
905
- const result = writeManifest(dir, manifest, { prune: has(args, "prune") });
1468
+ const check = has(args, "check");
1469
+ info(dim(`\u2192 GET ${config.endpoint}/v1/account-config`));
1470
+ const { sections: manifest, version: version2 } = await fetchManifest(api);
1471
+ const result = writeManifest(dir, manifest, { prune: has(args, "prune"), check });
1472
+ if (!check && version2) writeVersion(dir, version2);
1473
+ if (check) {
1474
+ if (has(args, "json")) {
1475
+ out(JSON.stringify({ drift: result.drift }, null, 2));
1476
+ return result.drift.length > 0 ? 1 : 0;
1477
+ }
1478
+ if (result.drift.length === 0) {
1479
+ out(`${green("\u2714")} Los archivos est\xE1n en sincron\xEDa con la organizaci\xF3n.`);
1480
+ return 0;
1481
+ }
1482
+ out(`${yellow("!")} ${result.drift.length} archivo(s) difieren del estado real de la organizaci\xF3n:`);
1483
+ for (const file of result.drift) out(` ${file}`);
1484
+ out(dim(" Alguien cambi\xF3 la organizaci\xF3n por otra v\xEDa (panel/MCP). Corre `hablala pull` para re-sincronizar antes de editar o aplicar."));
1485
+ return 1;
1486
+ }
906
1487
  if (has(args, "json")) {
907
1488
  out(
908
1489
  JSON.stringify(
@@ -916,7 +1497,7 @@ async function pull(args) {
916
1497
  out(`${green("\u2714")} ${result.written.length} archivo(s) sincronizados en ${dir}.`);
917
1498
  for (const file of result.pruned) out(dim(` borrado (sobrante): ${file}`));
918
1499
  if (result.stale.length > 0) {
919
- out(`${yellow("!")} Archivos que no corresponden a nada en el workspace (\xBFWIP o sobrantes?):`);
1500
+ out(`${yellow("!")} Archivos que no corresponden a nada en la organizaci\xF3n (\xBFWIP o sobrantes?):`);
920
1501
  for (const file of result.stale) out(` ${file}`);
921
1502
  out(dim(" `apply` los crear\xEDa; `pull --prune` los borra."));
922
1503
  }
@@ -925,8 +1506,8 @@ async function pull(args) {
925
1506
  async function init(args) {
926
1507
  const dir = targetDir(args);
927
1508
  const config = resolveConfig({
928
- tokenFlag: flag(args, "token"),
929
- endpointFlag: flag(args, "endpoint")
1509
+ tokenFlag: flag2(args, "token"),
1510
+ endpointFlag: flag2(args, "endpoint")
930
1511
  });
931
1512
  const api = createApiClient(config);
932
1513
  const identity = await whoami(api);
@@ -936,14 +1517,16 @@ async function init(args) {
936
1517
  hablalaYaml(identity, config.endpoint),
937
1518
  has(args, "force")
938
1519
  );
1520
+ scaffoldFile(join3(dir, ".gitignore"), gitignore(), has(args, "force"));
939
1521
  const guide = agentGuide(identity);
940
1522
  scaffoldFile(join3(dir, "CLAUDE.md"), guide, has(args, "force"));
941
1523
  scaffoldFile(join3(dir, "AGENTS.md"), guide, has(args, "force"));
942
- const manifest = await fetchManifest(api);
1524
+ const { sections: manifest, version: version2 } = await fetchManifest(api);
943
1525
  const result = writeManifest(dir, manifest, { prune: false });
944
- out(`${green("\u2714")} Workspace ${bold(identity.workspace.name)} inicializado en ${dir}:`);
1526
+ if (version2) writeVersion(dir, version2);
1527
+ out(`${green("\u2714")} Organizaci\xF3n ${bold(identity.organization.name)} inicializada en ${dir}:`);
945
1528
  out(
946
- ` hablala.yaml, CLAUDE.md + AGENTS.md y ${result.written.length} archivo(s) de configuraci\xF3n.`
1529
+ ` hablala.yaml, .gitignore, CLAUDE.md + AGENTS.md y ${result.written.length} archivo(s) de configuraci\xF3n.`
947
1530
  );
948
1531
  out("");
949
1532
  out(` Siguiente paso: edita los archivos y corre ${bold("hablala plan")}.`);
@@ -960,12 +1543,15 @@ async function plan(args) {
960
1543
  const loaded = loadLocal(args);
961
1544
  if (typeof loaded === "number") return loaded;
962
1545
  const config = resolveConfig({
963
- tokenFlag: flag(args, "token"),
964
- endpointFlag: flag(args, "endpoint")
1546
+ tokenFlag: flag2(args, "token"),
1547
+ endpointFlag: flag2(args, "endpoint")
965
1548
  });
966
1549
  const api = createApiClient(config);
967
- info(dim(`\u2192 PUT ${config.endpoint}/v1/workspace-config?dry_run=true`));
968
- const { plan: result, failure } = await putManifest(api, loaded, { dryRun: true });
1550
+ info(dim(`\u2192 PUT ${config.endpoint}/v1/account-config?dry_run=true`));
1551
+ const { plan: result, failure } = await putManifest(api, loaded.manifest, {
1552
+ dryRun: true,
1553
+ modes: loaded.modes
1554
+ });
969
1555
  if (failure) {
970
1556
  printFailure(failure);
971
1557
  return 1;
@@ -982,11 +1568,18 @@ async function apply(args) {
982
1568
  const loaded = loadLocal(args);
983
1569
  if (typeof loaded === "number") return loaded;
984
1570
  const config = resolveConfig({
985
- tokenFlag: flag(args, "token"),
986
- endpointFlag: flag(args, "endpoint")
1571
+ tokenFlag: flag2(args, "token"),
1572
+ endpointFlag: flag2(args, "endpoint")
987
1573
  });
988
1574
  const api = createApiClient(config);
989
- const preview = await putManifest(api, loaded, { dryRun: true });
1575
+ const dir = targetDir(args);
1576
+ const expectedVersion = readVersion(dir);
1577
+ if (!expectedVersion) {
1578
+ info(
1579
+ yellow("!") + " Sin `.hablala-version` (no se ha hecho `pull`): se aplicar\xE1 sin verificar drift. Corre `hablala pull` primero para no pisar cambios hechos por UI/MCP."
1580
+ );
1581
+ }
1582
+ const preview = await putManifest(api, loaded.manifest, { dryRun: true, modes: loaded.modes });
990
1583
  if (preview.failure) {
991
1584
  printFailure(preview.failure);
992
1585
  return 1;
@@ -1008,32 +1601,68 @@ async function apply(args) {
1008
1601
  return 1;
1009
1602
  }
1010
1603
  }
1011
- const { plan: applied, failure } = await putManifest(api, loaded, { dryRun: false });
1604
+ const { plan: applied, failure } = await putManifest(api, loaded.manifest, {
1605
+ dryRun: false,
1606
+ expectedVersion,
1607
+ modes: loaded.modes
1608
+ });
1012
1609
  if (failure) {
1013
1610
  printFailure(failure);
1611
+ if (failure.versionConflict) {
1612
+ info(dim(" \u2192 corre `hablala pull` para traer los cambios, revisa el diff y vuelve a aplicar."));
1613
+ }
1014
1614
  return 1;
1015
1615
  }
1016
- const summary = applied.summary;
1616
+ const applyResult = applied;
1617
+ const nextVersion = applyResult.version;
1618
+ if (nextVersion) writeVersion(dir, nextVersion);
1619
+ const summary = applyResult.summary;
1620
+ const deletePart = summary.delete ? `, ${summary.delete} borrado(s)` : "";
1017
1621
  out("");
1018
1622
  out(
1019
- `${green("\u2714")} Aplicado: ${summary.create ?? 0} creado(s), ${summary.update ?? 0} actualizado(s), ${summary.archive ?? 0} archivado(s).`
1623
+ `${green("\u2714")} Aplicado: ${summary.create ?? 0} creado(s), ${summary.update ?? 0} actualizado(s), ${summary.archive ?? 0} archivado(s)${deletePart}.`
1020
1624
  );
1021
1625
  return 0;
1022
1626
  }
1627
+ async function evalAgents(args) {
1628
+ const loaded = loadLocal(args);
1629
+ if (typeof loaded === "number") return loaded;
1630
+ const config = resolveConfig({
1631
+ tokenFlag: flag2(args, "token"),
1632
+ endpointFlag: flag2(args, "endpoint")
1633
+ });
1634
+ const api = createApiClient(config);
1635
+ const live = has(args, "live");
1636
+ info(dim(`\u2192 POST ${config.endpoint}/v1/account-config/eval${live ? "?live=true" : ""}`));
1637
+ const { result, failure } = await runEvals(api, loaded.manifest, { live });
1638
+ if (failure) {
1639
+ printFailure(failure);
1640
+ return 1;
1641
+ }
1642
+ const evalResult = result;
1643
+ if (has(args, "json")) {
1644
+ out(JSON.stringify(evalResult, null, 2));
1645
+ } else {
1646
+ out(renderEvals(evalResult));
1647
+ }
1648
+ return (evalResult.failed ?? 0) > 0 ? 1 : 0;
1649
+ }
1023
1650
  function loadLocal(args) {
1024
1651
  const dir = targetDir(args);
1025
- const { manifest, problems } = readManifest(dir);
1652
+ const { manifest, modes, problems } = readManifest(dir);
1026
1653
  if (problems.length > 0) {
1027
1654
  out(bold("El manifiesto no pasa la validaci\xF3n local:"));
1028
1655
  for (const problem of problems) out(` ${red("\u2716")} ${problem}`);
1029
1656
  return 1;
1030
1657
  }
1031
- if (!manifest.objects && !manifest.workflows && !manifest.agents) {
1032
- out(`${yellow("!")} ${dir} no tiene objects/, workflows/ ni agents/ \u2014 nada que declarar.`);
1658
+ if (!manifest.objects && !manifest.workflows && !manifest.agents && !manifest.policies) {
1659
+ out(
1660
+ `${yellow("!")} ${dir} no tiene objects/, workflows/, agents/ ni policies/ \u2014 nada que declarar.`
1661
+ );
1033
1662
  out(dim(" Corre `hablala init` para bajar el estado actual a archivos."));
1034
1663
  return 1;
1035
1664
  }
1036
- return manifest;
1665
+ return { manifest, modes };
1037
1666
  }
1038
1667
  function printFailure(failure) {
1039
1668
  out(`${red("\u2716")} ${failure.detail}`);
@@ -1060,16 +1689,20 @@ function promptLine(query) {
1060
1689
 
1061
1690
  // src/index.ts
1062
1691
  var { version } = createRequire(import.meta.url)("../package.json");
1063
- var USAGE = `hablala v${version} \u2014 Workspace as Code de Hablal\xE1
1692
+ var USAGE = `hablala v${version} \u2014 Account as Code de Hablal\xE1
1064
1693
 
1065
1694
  Uso:
1066
1695
  hablala login [--device] [--endpoint URL] Inicia sesi\xF3n por el navegador y guarda
1067
1696
  la credencial (--device: sin navegador
1068
1697
  local \u2014 SSH/contenedores; se autodetecta)
1069
1698
  hablala init [dir] [--force] Scaffold + pull del estado actual
1070
- hablala pull [dir] [--prune] [--json] Exporta el estado real a archivos
1699
+ hablala pull [dir] [--prune] [--check] [--json] Exporta el estado real a archivos
1700
+ (--check: no escribe; sale 1 si los
1701
+ archivos difieren del server \u2014 CI)
1071
1702
  hablala plan [dir] [--json] Diff declarado vs. real (dry-run)
1072
- hablala apply [dir] [--yes] Reconcilia contra el workspace
1703
+ hablala apply [dir] [--yes] Reconcilia contra la organizaci\xF3n
1704
+ hablala eval [dir] [--live] [--json] Corre los evals de los agentes
1705
+ (--live: LLM real; sale 1 si alg\xFAn caso falla)
1073
1706
  hablala codegen [--out hablala.types.ts] Tipos TS por tenant para @hablala/client
1074
1707
 
1075
1708
  Opciones globales:
@@ -1088,7 +1721,7 @@ archiva (nunca se borra). \`plan\` siempre muestra el diff completo antes de apl
1088
1721
 
1089
1722
  Docs y soporte: https://github.com/hablala/hablala
1090
1723
  `;
1091
- var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["help", "force", "prune", "yes", "device", "json"]);
1724
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["help", "force", "prune", "yes", "device", "json", "check"]);
1092
1725
  function parseArgs(argv) {
1093
1726
  const args = { _: [] };
1094
1727
  for (let i = 0; i < argv.length; i++) {
@@ -1121,6 +1754,7 @@ async function main() {
1121
1754
  pull,
1122
1755
  plan,
1123
1756
  apply,
1757
+ eval: evalAgents,
1124
1758
  codegen,
1125
1759
  // Alias histórico del bin de @hablala/client (`hablala gen`).
1126
1760
  gen: codegen