@hablala/cli 0.4.0 → 0.6.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
@@ -45,12 +45,12 @@ function resolveConfig(options = {}) {
45
45
  const accessToken = options.tokenFlag?.trim() || env.HABLALA_ACCESS_TOKEN?.trim() || stored?.accessToken;
46
46
  if (!accessToken) {
47
47
  throw new Error(
48
- "No hay credenciales. Corre `hablala login` (o define HABLALA_ACCESS_TOKEN con un access token hpat_\u2026)."
48
+ "No hay credenciales. Corre `hablala login` (o define HABLALA_ACCESS_TOKEN con un access token mat_\u2026)."
49
49
  );
50
50
  }
51
- if (!accessToken.startsWith("hpat_")) {
51
+ if (!accessToken.startsWith("mat_")) {
52
52
  throw new Error(
53
- 'El token no parece un access token v\xE1lido: debe empezar por "hpat_". Em\xEDtelo en Ajustes \u2192 Access tokens con permisos de escritura de diccionario, workflows y agentes.'
53
+ 'El token no parece un access token v\xE1lido: debe empezar por "mat_". Em\xEDtelo en Ajustes \u2192 Access tokens con permisos de escritura de diccionario, workflows y agentes.'
54
54
  );
55
55
  }
56
56
  const endpoint = options.endpointFlag?.trim() || env.HABLALA_ENDPOINT?.trim() || stored?.endpoint || DEFAULT_ENDPOINT;
@@ -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,48 +106,84 @@ 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) {
121
171
  const endpoint = ((typeof args.endpoint === "string" ? args.endpoint : void 0) ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
122
- const token = (typeof args.token === "string" ? args.token : void 0) ?? process.env.HABLALA_STOREFRONT_TOKEN ?? process.env.HABLALA_PRIVATE_TOKEN ?? process.env.HABLALA_PUBLIC_TOKEN;
172
+ const token = (typeof args.token === "string" ? args.token : void 0) ?? process.env.HABLALA_TOKEN ?? process.env.HABLALA_STOREFRONT_TOKEN ?? process.env.HABLALA_PRIVATE_TOKEN ?? process.env.HABLALA_PUBLIC_TOKEN;
123
173
  const out2 = typeof args.out === "string" ? args.out : "hablala.types.ts";
124
174
  if (!token) {
125
175
  console.error(
126
- `${red("\u2716")} Falta el token: un storefront token sfpk_/sfpr_ (--token o HABLALA_STOREFRONT_TOKEN).`
176
+ `${red("\u2716")} Falta el token: una API key pk_/sk_ (--token o HABLALA_TOKEN).`
127
177
  );
128
178
  console.error(
129
- dim(" Ojo: codegen NO usa el access token hpat_ \u2014 introspecciona el storefront.")
179
+ dim(" Ojo: codegen NO usa el machine access token mat_ \u2014 introspecciona el canal p\xFAblico.")
130
180
  );
131
181
  return 1;
132
182
  }
133
- const url = `${endpoint}/v1/storefront/schema`;
183
+ const url = `${endpoint}/v1/public/schema`;
134
184
  console.error(dim(`\u2192 Introspeccionando ${url}`));
135
185
  const response = await fetch(url, {
136
186
  headers: {
137
- "X-Hablala-Storefront-Token": token,
138
187
  Authorization: `Bearer ${token}`
139
188
  }
140
189
  });
@@ -165,6 +214,7 @@ import { createInterface } from "readline";
165
214
 
166
215
  // src/api.ts
167
216
  import createClient from "openapi-fetch";
217
+ var ACCOUNT_KIND = "organization";
168
218
  function createApiClient(config) {
169
219
  return createClient({
170
220
  baseUrl: config.endpoint,
@@ -175,25 +225,51 @@ async function whoami(api) {
175
225
  const { data, response } = await api.GET("/v1/whoami");
176
226
  if (!response.ok || !data) {
177
227
  throw new Error(
178
- `No se pudo identificar el access token (GET /v1/whoami \u2192 ${response.status}). Verifica que sea un hpat_\u2026 v\xE1lido y no est\xE9 revocado ni expirado.`
228
+ `No se pudo identificar el access token (GET /v1/whoami \u2192 ${response.status}). Verifica que sea un mat_\u2026 v\xE1lido y no est\xE9 revocado ni expirado.`
179
229
  );
180
230
  }
181
231
  return data.data;
182
232
  }
183
233
  async function fetchManifest(api) {
184
- const { data, error, response } = await api.GET("/v1/workspace-config");
234
+ const { data, error, response } = await api.GET("/v1/account-config");
185
235
  if (!response.ok || !data) {
186
236
  throw new Error(formatApiError(response.status, error));
187
237
  }
188
- return data.data;
238
+ const { kind, version: version2, ...sections } = data.data.account;
239
+ void kind;
240
+ return { sections, version: version2 };
241
+ }
242
+ function withModes(manifest, modes) {
243
+ if (!modes || Object.keys(modes).length === 0) return manifest;
244
+ const out2 = { ...manifest };
245
+ for (const [section, mode] of Object.entries(modes)) {
246
+ const items = manifest[section];
247
+ if (Array.isArray(items)) out2[section] = { mode, items };
248
+ }
249
+ return out2;
189
250
  }
190
251
  async function putManifest(api, manifest, options) {
191
- const { data, error, response } = await api.PUT("/v1/workspace-config", {
252
+ const { data, error, response } = await api.PUT("/v1/account-config", {
192
253
  params: { query: { dry_run: options.dryRun } },
193
- body: { config: manifest }
254
+ // El `If-Match` es la precondición de versión (optimistic locking): solo en el apply real, y
255
+ // solo si tenemos una versión del `pull`. Sin él, el server aplica sin chequear (retrocompat).
256
+ headers: !options.dryRun && options.expectedVersion ? { "If-Match": options.expectedVersion } : void 0,
257
+ body: {
258
+ config: { account: { kind: ACCOUNT_KIND, ...withModes(manifest, options.modes) } }
259
+ }
194
260
  });
195
261
  if (response.ok && data) return { plan: data.data };
196
262
  const body = error;
263
+ if (response.status === 412) {
264
+ const errors = body?.errors;
265
+ return {
266
+ failure: {
267
+ detail: errors?.detail ?? "la cuenta cambi\xF3 desde tu \xFAltimo `pull`; corre `hablala pull` para re-sincronizar",
268
+ planErrors: [],
269
+ versionConflict: true
270
+ }
271
+ };
272
+ }
197
273
  if (response.status === 422) {
198
274
  const errors = body?.errors;
199
275
  if (errors) {
@@ -209,6 +285,23 @@ async function putManifest(api, manifest, options) {
209
285
  }
210
286
  throw new Error(formatApiError(response.status, body));
211
287
  }
288
+ async function runEvals(api, manifest, options) {
289
+ const { data, error, response } = await api.POST("/v1/account-config/eval", {
290
+ params: { query: { live: options.live } },
291
+ body: { config: { account: { kind: ACCOUNT_KIND, ...manifest } } }
292
+ });
293
+ if (response.ok && data) return { result: data.data };
294
+ const body = error;
295
+ if (response.status === 422) {
296
+ const errors = body?.errors;
297
+ if (errors) {
298
+ return {
299
+ failure: { detail: errors.detail ?? "el manifiesto no pas\xF3 validaci\xF3n", planErrors: errors.manifest ?? [] }
300
+ };
301
+ }
302
+ }
303
+ throw new Error(formatApiError(response.status, body));
304
+ }
212
305
  function formatApiError(status, body) {
213
306
  const errors = body?.errors;
214
307
  if (errors && typeof errors === "object") {
@@ -225,61 +318,114 @@ function formatApiError(status, body) {
225
318
 
226
319
  // src/claude-md.ts
227
320
  function agentGuide(identity) {
228
- return `# Workspace as Code \u2014 ${identity.workspace.name} (${identity.organization.name})
321
+ return `# Account as Code \u2014 ${identity.organization.name}
229
322
 
230
- Este directorio declara la configuraci\xF3n del workspace como **archivos versionables**.
323
+ Este directorio declara la configuraci\xF3n de la organizaci\xF3n como **archivos versionables**.
231
324
  T\xFA (el agente) editas los archivos; el CLI valida, muestra el diff y aplica:
232
325
 
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
326
+ hablala plan # diff declarado vs. real \u2014 NUNCA toca nada
327
+ hablala apply # reconcilia (crear / actualizar / archivar; jam\xE1s borrar)
328
+ hablala eval # corre los evals de los agentes (--live: LLM real; sale 1 si alg\xFAn caso falla)
329
+ hablala pull # re-sincroniza los archivos con el estado real
330
+ hablala pull --check # \xBFlos archivos siguen el estado real? (sale 1 si no; para CI)
331
+
332
+ ## Runbook (SEGUIR SIEMPRE, en orden)
236
333
 
237
- Loop recomendado: edita \u2192 \`plan\` \u2192 corrige conflictos \u2192 \`plan\` limpio \u2192 \`apply\`.
334
+ La \xFAnica fuente de verdad es la organizaci\xF3n (la BD), no estos archivos: son una **proyecci\xF3n
335
+ versionada** de ella, como un clon de git respecto al remoto. La UI, MCP y este manifiesto
336
+ escriben todos al mismo lugar; estos archivos pueden quedar **atr\xE1s** si alguien cambi\xF3 la org
337
+ por otra v\xEDa. Por eso, en CADA sesi\xF3n de trabajo:
338
+
339
+ 1. hablala pull --check # \xBFmis archivos siguen la verdad? (drift inverso)
340
+ 2. hablala pull # SI hubo drift: re-sincroniza ANTES de tocar nada
341
+ 3. \u2026edita los .yaml\u2026
342
+ 4. hablala plan # revisa el diff \u2014 vigila los archive/delete
343
+ 5. \u2026corrige conflictos y repite plan hasta que salga limpio\u2026
344
+ 6. hablala apply # aplica (pide confirmaci\xF3n; --yes en CI)
345
+
346
+ **El paso 1 no es opcional.** \`apply\` es autoritativo: lo que existe en la org y NO est\xE1 en tus
347
+ archivos se ARCHIVA. Si editas y aplicas un manifiesto viejo (sin el paso 1-2), archivas
348
+ silenciosamente lo que el cliente agreg\xF3 por la UI o un agente por MCP. \`pull --check\` sale con
349
+ c\xF3digo 1 si hay drift \u2014 \xFAsalo como guardia en pre-commit/CI.
350
+
351
+ **Red de seguridad autom\xE1tica (optimistic locking).** Adem\xE1s de la disciplina, el \`pull\` guarda
352
+ la versi\xF3n del estado en \`.hablala-version\` (un lockfile \u2014 versi\xF3nalo en git). El \`apply\` la
353
+ reenv\xEDa como precondici\xF3n: si la org cambi\xF3 desde tu \xFAltimo \`pull\` (UI, MCP, otro apply), el
354
+ server RECHAZA el apply con un conflicto de versi\xF3n en vez de pisar lo que no viste \u2014 como un
355
+ \`git push\` rechazado cuando tu rama est\xE1 atr\xE1s. Si eso pasa: \`hablala pull\`, revisa el diff,
356
+ reaplica. (Sin \`.hablala-version\` \u2014nunca hiciste \`pull\`\u2014 el apply avisa y procede sin chequeo.)
238
357
 
239
358
  ## Estructura
240
359
 
241
360
  objects/<slug>.yaml # un objeto del modelo de datos por archivo
242
361
  workflows/<slug>.yaml # una definici\xF3n de workflow por archivo
243
362
  agents/<handle>.yaml # un agente de IA por archivo
363
+ policies/<slug>.yaml # una regla ABAC de acceso a datos por archivo
244
364
 
245
365
  Reglas del manifiesto:
246
366
 
247
- - **Cada directorio es autoritativo**: lo que existe en el workspace y no est\xE1 declarado
367
+ - **Cada directorio es autoritativo**: lo que existe en la organizaci\xF3n y no est\xE1 declarado
248
368
  en archivos SE ARCHIVA al aplicar (\`plan\` siempre lo muestra antes). Borrar un archivo
249
- archiva esa entidad; nunca se destruye nada.
369
+ archiva esa entidad; nunca se destruye nada. **Excepci\xF3n: las policies se BORRAN** (no
370
+ se archivan) \u2014 para una regla de acceso, quitarla del manifiesto debe significar que
371
+ deja de aplicar. \`plan\` lo muestra como \`delete\`.
250
372
  - El \`slug\`/\`handle\` del contenido es la identidad; el nombre de archivo es convenci\xF3n.
251
373
  - Las \`relationships\` van DENTRO del archivo de su objeto origen (\`source\` impl\xEDcito):
252
374
 
253
- # objects/vestido.yaml
254
- slug: vestido
255
- title: Vestidos
256
- titleSingular: Vestido
257
- description: Vestido de renta, unidad serializada.
258
- synonyms: [dress, prenda]
375
+ # objects/producto.yaml
376
+ slug: producto
377
+ title: Productos
378
+ titleSingular: Producto
379
+ description: Producto del cat\xE1logo, unidad serializada.
380
+ synonyms: [product, item]
259
381
  attributes:
260
- - slug: talla
261
- title: Talla
262
- description: Talla del vestido.
382
+ - slug: categoria
383
+ description: Categor\xEDa del producto. # title impl\xEDcito: "Categoria" (del slug)
263
384
  dataType: select
264
385
  isRequired: true
265
- config: { options: [XS, S, M, L, XL] }
386
+ config: { options: [A, B, C] }
266
387
  - slug: sku
267
- title: SKU
388
+ title: SKU # title expl\xEDcito cuando el slug no basta
268
389
  description: C\xF3digo \xFAnico.
269
390
  dataType: text
270
391
  isUnique: true
271
392
  relationships:
272
- - slug: vestido_rentas
273
- title: Rentas del vestido
274
- description: Las rentas de este vestido.
275
- target: rental
393
+ - slug: producto_bookings
394
+ title: Reservas del producto
395
+ description: Las reservas de este producto.
396
+ target: booking
276
397
  cardinality: one_to_many
277
398
 
278
399
  - \`description\` es obligatoria en todo (objetos, atributos, workflows): es el contexto
279
400
  con el que los agentes LLM de la plataforma descubren y operan cada cosa v\xEDa MCP.
280
401
  \`synonyms\` ayuda al mismo fin.
402
+ - \`title\` es OPCIONAL: si lo omites se deriva del \`slug\` (\`precio_base\` \u2192 "Precio Base").
403
+ En un object, \`titleSingular\` ausente cae al \`title\`. Decl\xE1ralos solo cuando el derivado
404
+ no baste (siglas, may\xFAsculas especiales). \`description\` NUNCA se deriva: escr\xEDbela siempre.
405
+ - **Secretos: NUNCA en el manifiesto.** El manifiesto vive en git (historial permanente,
406
+ clones que viajan). No pongas tokens, API keys ni passwords en ning\xFAn \`.yaml\` \u2014 ni
407
+ "temporalmente". Un secreto commiteado queda en el historial para siempre. Cuando un
408
+ workflow o agente necesite una credencial externa (p. ej. una API de terceros), se
409
+ **referenciar\xE1** desde un vault con \`\${secret:nombre}\` y el valor vivir\xE1 fuera de git;
410
+ jam\xE1s inline. (Las credenciales del CLI ya viven fuera: \`~/.config/hablala\` o la variable
411
+ \`HABLALA_ACCESS_TOKEN\`.)
281
412
  - \`dataType\`: text | number | boolean | date | timestamp | select | multiselect |
282
- reference | file. \`cardinality\`: one_to_one | one_to_many | many_to_many.
413
+ reference | file | formula | rollup. \`cardinality\`: one_to_one | one_to_many | many_to_many.
414
+ Los dos \xFAltimos son DERIVADOS (se calculan al leer, no se almacenan): \`formula\` computa de
415
+ otros campos del MISMO record (\`config: { expression: "subtotal + tax" }\`); \`rollup\` agrega
416
+ campos de records RELACIONADOS (\`config: { relationship, aggregate: sum|count|avg|min|max, target }\`).
417
+ No admiten \`isRequired\`/\`isIndexed\`/\`embedInVector\`.
418
+ - **\`config\` por tipo** (el \`plan\` valida su forma; un error se atrapa antes de aplicar):
419
+ - \`select\`/\`multiselect\`: \`config: { options: [...] }\` \u2014 OBLIGATORIO y no vac\xEDo.
420
+ - \`number\`: \`config: { min, max }\` \u2014 num\xE9ricos y \`min <= max\` (ambos opcionales).
421
+ - \`file\`: \`config: { maxCount, acceptedContentTypes }\` \u2014 \`maxCount\` entero positivo;
422
+ \`acceptedContentTypes\` lista de mime (admite comodines: \`image/*\`).
423
+ - \`reference\`: \`config: { targetObject: <slug> }\` \u2014 OPCIONAL; restringe la referencia a
424
+ records de ese object (el \`plan\` valida que el object exista; al escribir, el motor
425
+ rechaza un record de otro tipo). Sin \`targetObject\`, la referencia acepta cualquier record.
426
+ - **Flags por tipo** (tambi\xE9n validados en el \`plan\`): \`isUnique\` no va en
427
+ \`multiselect\`/\`boolean\`/\`file\`; un \`file\` no se indexa (\`isIndexed\`) ni se embebe
428
+ (\`embedInVector\`). \`defaultValue\` es el sobre del valor (un objeto), no un escalar crudo.
283
429
 
284
430
  ## El \xE1rbol de decisi\xF3n: \xBFobjeto del motor o m\xF3dulo core?
285
431
 
@@ -293,7 +439,7 @@ NO los redefinas como objetos \u2014 \xFAsalos:
293
439
  | Facturas, pagos, numeraci\xF3n legal | \`invoicing\` | \`factura\`, \`pago\` |
294
440
  | Stock (ledger de doble entrada) | \`inventory\` | \`stock\`, \`existencias\` |
295
441
 
296
- Todo lo dem\xE1s \u2014 los **sustantivos del negocio** (p\xF3lizas, pacientes, vestidos, \xF3rdenes) \u2014
442
+ Todo lo dem\xE1s \u2014 los **sustantivos del negocio** que defina tu vertical \u2014
297
443
  son objetos del modelo de datos en \`objects/\`. **En caso de duda: objeto del motor.**
298
444
 
299
445
  Objetos est\xE1ndar ya sembrados (exti\xE9ndelos o arch\xEDvalos, no los dupliques):
@@ -307,14 +453,14 @@ es de sistema (proyecci\xF3n read-only): no lo declares.
307
453
  - \`company\` = empresa del CRM. La organizaci\xF3n (tenant) NUNCA se llama company.
308
454
  - \`product\`/\`price\` separados: el precio nunca vive en el producto.
309
455
  - \`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\`.
456
+ - Slugs en snake_case, singulares (\`producto\`, no \`productos\`); el plural va en \`title\`.
311
457
 
312
458
  ## Workflows y agentes
313
459
 
314
460
  # workflows/al_devolver.yaml
315
461
  slug: al_devolver
316
462
  title: Al devolver
317
- description: Reacciona a la devoluci\xF3n de una renta.
463
+ description: Reacciona a la devoluci\xF3n de un booking.
318
464
  trigger: { event_type: booking.returned }
319
465
  initialState: registrar
320
466
  states:
@@ -328,30 +474,137 @@ es de sistema (proyecci\xF3n read-only): no lo declares.
328
474
  name: Recepcionista
329
475
  description: Atiende consultas y agenda citas.
330
476
  systemPrompt: Eres una recepcionista amable\u2026
331
- allowedActivities: [search_records, send_message]
477
+ provider: anthropic # opcional; registrado (anthropic). Omite = default
478
+ model: claude-opus-4-8 # opcional; texto libre, lo valida el provider
479
+ authoritySource: delegated # delegated | assigned (opcional; default delegated)
480
+ allowedActivities: [search_records] # allowlist de TOOLS (ver abajo)
481
+ agentPermissions: [records:read] # allowlist RBAC que estrecha el scope delegado (opcional)
482
+ handoffs: [ventas] # handles a los que puede TRANSFERIR la conversaci\xF3n (opcional)
483
+ approvalRequired: [create_record] # tools que exigen aprobaci\xF3n humana (opcional; \u2286 allowedActivities)
332
484
 
333
485
  Los agentes se identifican por \`handle\`; quitar su archivo los revoca (archive).
486
+
487
+ - \`allowedActivities\` son las **tools** que el agente puede llamar. Deben ser tools reales
488
+ (hoy: \`search_records\`); un slug fuera del cat\xE1logo lo rechaza el \`plan\`. NO pongas aqu\xED
489
+ efectos del motor como \`send_message\` (el agente responde solo, no es una tool).
490
+ - \`agentPermissions\` son permisos RBAC \`recurso:accion\` (p. ej. \`records:read\`,
491
+ \`records:create\`) que **acotan** lo que el agente puede hacer por debajo de su due\xF1o
492
+ (least-privilege). Vac\xEDo = hereda todo lo del due\xF1o. Un permiso inexistente lo rechaza el \`plan\`.
493
+ - El agente act\xFAa **a nombre de un humano** (\`ownerUserId\`, id p\xFAblico \`user_\u2026\`). Con un
494
+ usuario, el creador es el due\xF1o por defecto; con un token de m\xE1quina, \`ownerUserId\` es
495
+ **obligatorio** al crear.
496
+ - \`handoffs\` son los **handles** de otros agentes a los que este puede **transferir** la
497
+ conversaci\xF3n (handoff / sub-agente): el motor le da una tool \`transfer_to_agent\` acotada a
498
+ esa lista, y el agente destino contin\xFAa. Cada handle debe ser un agente real (no \xE9l mismo);
499
+ lo valida el \`plan\`.
500
+ - \`approvalRequired\` son tools (\u2286 \`allowedActivities\`) que exigen **aprobaci\xF3n humana** antes
501
+ de correr (para acciones irreversibles): el motor crea una tarea y espera el visto bueno en vez
502
+ de ejecutarlas directo.
503
+ - \`evals\` son **casos de prueba** del comportamiento del agente (testing declarativo): cada uno
504
+ da un \`input\`, aserciones \`expect\` \u2014 \`tool\`, \`noTool\`, \`handoff\`, \`requiresApproval\`,
505
+ \`contains\` \u2014 y un \`script\` opcional. Corre con \`hablala eval\`.
506
+
507
+ Dos modos (como promptfoo): por defecto, **determinista** \u2014 el \`script\` declara qu\xE9 hace el
508
+ agente-guionizado (\`{tool, input}\` o \`{text}\`) y las aserciones verifican que el motor lo
509
+ cablea bien, sin tokens, apto para CI. Con \`--live\`, contra el LLM real (prueba qu\xE9 elige de
510
+ verdad; el \`script\` se ignora). Sin \`script\` ni \`--live\`, las aserciones de comportamiento
511
+ no son evaluables (no se puede predecir qu\xE9 har\xEDa el agente). Ejemplo:
512
+
513
+ # dentro del archivo del agente
514
+ evals:
515
+ - name: busca al preguntar por un producto
516
+ input: \xBFtienen sillas de oficina?
517
+ script: { tool: search_records } # el guion determinista
518
+ expect: { tool: search_records }
519
+ - name: escala una queja al humano
520
+ input: quiero cancelar y hablar con alguien
521
+ script: { tool: transfer_to_agent, input: { target: soporte } }
522
+ expect: { handoff: soporte }
523
+
524
+ ## Policies (control de acceso ABAC)
525
+
526
+ Una policy define QU\xC9 datos ve cada qui\xE9n. El motor es **default-deny**: sin una policy
527
+ \`allow\`, un principal no ve nada de un objeto. Se identifican por \`slug\`.
528
+
529
+ # policies/public_producto_publicado.yaml
530
+ slug: public_producto_publicado
531
+ effect: allow # allow | deny (deny gana)
532
+ action: [read, update] # read | create | update | delete | signal \u2014 string o lista
533
+ principal: public # qui\xE9n (ver abajo)
534
+ object: producto # slug del object; OMITE la clave para "toda la organizaci\xF3n"
535
+ condition: { attr: estado, op: eq, value: publicado } # predicado por fila (opcional)
536
+ field_mask: [nombre, categoria, estado] # campos visibles (opcional)
537
+
538
+ - \`action\` acepta **un string o una lista**: \`action: [read, update]\` concede ambas bajo
539
+ el mismo slug (una policy declarada = N grants, uno por acci\xF3n). Quitar una acci\xF3n de la
540
+ lista borra solo ese grant; \`pull\` re-colapsa las acciones de un slug en la lista.
541
+ - \`principal\` es una **referencia legible** (nunca un id): \`public\` (el canal
542
+ p\xFAblico del frontend), \`access_token\` (agentes que escriben por HTTP), \`role:<name>\`
543
+ (un rol) o \`agent:<handle>\` (un agente). Los principales por USUARIO no se declaran
544
+ aqu\xED \u2014 son datos, no config; gesti\xF3nalos por API/MCP.
545
+ - \`object\` es el slug del object gobernado; el server resuelve la ref a su id al aplicar.
546
+ - **Al quitar el archivo la policy se BORRA** (no se archiva): deja de conceder/negar.
547
+ \`plan\` lo muestra como \`delete\` \u2014 rev\xEDsalo, es un cambio de seguridad.
548
+ - Los secretos NUNCA van en una policy (ni en ning\xFAn \`.yaml\`): ver la regla de secretos.
549
+
550
+ ### La \`condition\` (filtrado por fila) y el \`field_mask\` (por campo)
551
+
552
+ La \`condition\` es un predicado ABAC opcional: la policy solo aplica a las filas que lo
553
+ satisfacen. Misma gram\xE1tica que el guard de un \`choice\` de workflow:
554
+
555
+ condition: { attr: <slug>, op: <op>, value: <literal> } # una hoja
556
+ condition: { and: [ <hoja>, <hoja>, \u2026 ] } # todas
557
+ condition: { or: [ <hoja>, <hoja>, \u2026 ] } # alguna
558
+
559
+ - \`attr\` es un slug de atributo **del object gobernado**. \`op\` \u2208 \`eq\`, \`neq\`, \`gt\`,
560
+ \`gte\`, \`lt\`, \`lte\`, \`in\`, \`contains\`, \`is_null\`, \`is_not_null\`. El operador debe
561
+ ser compatible con el tipo del atributo (p. ej. \`gt\` no aplica a un \`select\`).
562
+ - **ABAC din\xE1mico**: en vez de un \`value\` literal, una hoja puede comparar contra un
563
+ atributo del solicitante con \`value_from: "principal.<attr>"\` \u2014 p. ej. "cada quien ve
564
+ solo las filas de su misma regi\xF3n":
565
+
566
+ condition: { attr: region, op: eq, value_from: "principal.region" }
567
+
568
+ - \`field_mask\` es la lista de slugs de atributo **visibles**; omitirla = todos los
569
+ permitidos. Con varias policies \`allow\`, la visibilidad es la intersecci\xF3n de sus masks.
570
+ - Todo esto se **valida en el \`plan\`**: un \`attr\`/campo inexistente, un \`op\` desconocido
571
+ o incompatible con el tipo es un conflicto que bloquea el apply (no un fallo silencioso
572
+ en runtime). Corr\xEDgelo en tu loop antes de aplicar.
334
573
  `;
335
574
  }
336
575
  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.
576
+ return `# Metadatos de la organizaci\xF3n (informativo \u2014 la identidad real sale del access token).
577
+ # Generado por \`hablala init\`. Portable entre entornos: no versiona ids del server, solo
578
+ # nombres/slugs legibles. Adem\xE1s, \`plan\`/\`apply\` leen \`modes\` (abajo) de este archivo.
339
579
  endpoint: ${endpoint}
340
580
  organization:
341
- id: ${identity.organization.id}
342
581
  name: ${JSON.stringify(identity.organization.name)}
343
582
  slug: ${identity.organization.slug}
344
- workspace:
345
- id: ${identity.workspace.id}
346
- name: ${JSON.stringify(identity.workspace.name)}
347
- slug: ${identity.workspace.slug}
583
+
584
+ # Modo de reconciliaci\xF3n por secci\xF3n. Default (sin declarar): "authoritative" \u2014 lo no declarado
585
+ # se archiva/borra (estado deseado completo). Ponlo en "additive" para A\xD1ADIR sin expulsar lo no
586
+ # declarado (\xFAtil cuando declaras solo una parte del modelo; least astonishment). An\xE1logo al
587
+ # server-side apply de Kubernetes: intenci\xF3n parcial, sin pruning.
588
+ # modes:
589
+ # objects: additive
590
+ # relationships: additive
591
+ `;
592
+ }
593
+ function gitignore() {
594
+ return `# Credenciales y secretos \u2014 NUNCA en git (viven en ~/.config/hablala o en variables de entorno).
595
+ credentials.json
596
+ .env
597
+ .env.*
598
+ !.env.example
599
+ *.local.yaml
600
+ *.local.yml
348
601
  `;
349
602
  }
350
603
 
351
604
  // src/manifest.ts
352
605
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
353
606
  import { join as join2 } from "path";
354
- import { parse, stringify } from "yaml";
607
+ import { parse, parseDocument, stringify } from "yaml";
355
608
  var DATA_TYPES = [
356
609
  "text",
357
610
  "number",
@@ -361,10 +614,14 @@ var DATA_TYPES = [
361
614
  "select",
362
615
  "multiselect",
363
616
  "reference",
364
- "file"
617
+ "file",
618
+ "formula",
619
+ "rollup"
365
620
  ];
366
621
  var CARDINALITIES = ["one_to_one", "one_to_many", "many_to_many"];
367
622
  var AUTHORITY_SOURCES = ["delegated", "assigned"];
623
+ var POLICY_EFFECTS = ["allow", "deny"];
624
+ var POLICY_ACTIONS = ["read", "create", "update", "delete", "signal"];
368
625
  var OBJECT_KEYS = withSnake([
369
626
  "slug",
370
627
  "title",
@@ -372,6 +629,15 @@ var OBJECT_KEYS = withSnake([
372
629
  "description",
373
630
  "synonyms",
374
631
  "config",
632
+ // Primary field: el slug del attribute que titula un record. Opcional.
633
+ "titleAttributeSlug",
634
+ // Señal read-only que emite `pull` (tenant/seeded/system): la aceptamos para que re-aplicar un
635
+ // manifiesto recién exportado no falle como "clave desconocida". El server la ignora en el diff.
636
+ "manageability",
637
+ // Señal read-only que emite `pull` (core/commerce/crm…): a qué vertical instalable pertenece el
638
+ // object. Se acepta por el mismo motivo que `manageability`; un package se instala declarándolo en
639
+ // `packages:` (no marcando esta clave). El server la ignora en el diff.
640
+ "package",
375
641
  "attributes",
376
642
  "relationships"
377
643
  ]);
@@ -415,15 +681,90 @@ var AGENT_KEYS = withSnake([
415
681
  "authoritySource",
416
682
  "allowedActivities",
417
683
  "agentPermissions",
684
+ "handoffs",
685
+ "approvalRequired",
686
+ "evals",
418
687
  "ownerUserId"
419
688
  ]);
689
+ var POLICY_KEYS = withSnake([
690
+ "slug",
691
+ "effect",
692
+ "action",
693
+ "principal",
694
+ "object",
695
+ "condition",
696
+ "fieldMask"
697
+ ]);
698
+ var ROLE_KEYS = withSnake(["name", "permissions"]);
420
699
  function withSnake(keys) {
421
700
  const snake = keys.map((key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
422
701
  return /* @__PURE__ */ new Set([...keys, ...snake]);
423
702
  }
703
+ var SECTION_MODES = ["authoritative", "additive"];
704
+ function readModes(dir, problems) {
705
+ const modes = {};
706
+ const file = join2(dir, "hablala.yaml");
707
+ if (!existsSync2(file)) return modes;
708
+ const doc = parse(readFileSync2(file, "utf8"));
709
+ const declared = doc?.modes;
710
+ if (!declared || typeof declared !== "object") return modes;
711
+ for (const [section, mode] of Object.entries(declared)) {
712
+ if (typeof mode === "string" && SECTION_MODES.includes(mode)) {
713
+ modes[section] = mode;
714
+ } else {
715
+ problems.push(
716
+ `hablala.yaml: modes.${section} inv\xE1lido "${String(mode)}" (usa ${SECTION_MODES.join(" | ")})`
717
+ );
718
+ }
719
+ }
720
+ return modes;
721
+ }
722
+ var SETTINGS_KEYS = /* @__PURE__ */ new Set(["endUserObjectSlug", "end_user_object_slug"]);
723
+ function readSettings(dir, problems) {
724
+ const file = join2(dir, "hablala.yaml");
725
+ if (!existsSync2(file)) return void 0;
726
+ const doc = parse(readFileSync2(file, "utf8"));
727
+ const declared = doc?.settings;
728
+ if (declared === void 0 || declared === null) return void 0;
729
+ if (typeof declared !== "object" || Array.isArray(declared)) {
730
+ problems.push("hablala.yaml: settings debe ser un objeto (singleton, no una lista)");
731
+ return void 0;
732
+ }
733
+ const settings = declared;
734
+ const unknown = Object.keys(settings).filter((key) => !SETTINGS_KEYS.has(key));
735
+ if (unknown.length > 0) {
736
+ problems.push(`hablala.yaml: settings tiene claves desconocidas: ${unknown.join(", ")} (\xBFtypo?)`);
737
+ }
738
+ return settings;
739
+ }
740
+ function readPackages(dir, problems) {
741
+ const file = join2(dir, "hablala.yaml");
742
+ if (!existsSync2(file)) return void 0;
743
+ const doc = parse(readFileSync2(file, "utf8"));
744
+ const declared = doc?.packages;
745
+ if (declared === void 0 || declared === null) return void 0;
746
+ if (!Array.isArray(declared)) {
747
+ problems.push("hablala.yaml: packages debe ser una lista de nombres (p. ej. [commerce, crm])");
748
+ return void 0;
749
+ }
750
+ const packages = [];
751
+ for (const entry of declared) {
752
+ if (typeof entry === "string" && entry.trim() !== "") {
753
+ packages.push(entry);
754
+ } else {
755
+ problems.push(`hablala.yaml: packages tiene una entrada inv\xE1lida "${String(entry)}" (usa nombres de package)`);
756
+ }
757
+ }
758
+ return packages;
759
+ }
424
760
  function readManifest(dir) {
425
761
  const problems = [];
762
+ const modes = readModes(dir, problems);
426
763
  const manifest = {};
764
+ const settings = readSettings(dir, problems);
765
+ if (settings) manifest.settings = settings;
766
+ const packages = readPackages(dir, problems);
767
+ if (packages) manifest.packages = packages;
427
768
  const objectsDir = join2(dir, "objects");
428
769
  if (existsSync2(objectsDir)) {
429
770
  const objects = [];
@@ -440,7 +781,9 @@ function readManifest(dir) {
440
781
  `objects/${file}`,
441
782
  problems
442
783
  );
784
+ validateAttributeRules(attribute, `objects/${file} (attribute)`, problems);
443
785
  }
786
+ const relationshipSlugs = /* @__PURE__ */ new Set();
444
787
  for (const relationship of asList(embedded)) {
445
788
  const declared = relationship;
446
789
  const withSource = {
@@ -459,8 +802,13 @@ function readManifest(dir) {
459
802
  problems.push(
460
803
  `objects/${file}: la relationship "${withSource.slug}" no declara "target"`
461
804
  );
805
+ if (typeof withSource.slug === "string") relationshipSlugs.add(withSource.slug);
462
806
  relationships.push(withSource);
463
807
  }
808
+ const attributeSlugs = new Set(
809
+ asList(object.attributes).map((a) => a.slug).filter((s) => typeof s === "string")
810
+ );
811
+ validateLayout(object.config, attributeSlugs, relationshipSlugs, `objects/${file}`, problems);
464
812
  objects.push(object);
465
813
  }
466
814
  manifest.objects = objects;
@@ -484,15 +832,37 @@ function readManifest(dir) {
484
832
  `agents/${file}`,
485
833
  problems
486
834
  );
835
+ validateStringList(content, ["allowedActivities", "allowed_activities"], `agents/${file}`, problems);
836
+ validateStringList(content, ["agentPermissions", "agent_permissions"], `agents/${file}`, problems);
837
+ validateStringList(content, ["handoffs"], `agents/${file}`, problems);
838
+ validateStringList(content, ["approvalRequired", "approval_required"], `agents/${file}`, problems);
839
+ validateEvals(content.evals, `agents/${file}`, problems);
840
+ return content;
841
+ });
842
+ }
843
+ const policiesDir = join2(dir, "policies");
844
+ if (existsSync2(policiesDir)) {
845
+ manifest.policies = readYamlDir(policiesDir, problems).map(({ file, content }) => {
846
+ validateEntity(content, "slug", POLICY_KEYS, `policies/${file}`, problems);
847
+ validateEnum(content, ["effect"], POLICY_EFFECTS, `policies/${file}`, problems);
848
+ validateEnumOrList(content, "action", POLICY_ACTIONS, `policies/${file}`, problems);
849
+ return content;
850
+ });
851
+ }
852
+ const rolesDir = join2(dir, "roles");
853
+ if (existsSync2(rolesDir)) {
854
+ manifest.roles = readYamlDir(rolesDir, problems).map(({ file, content }) => {
855
+ validateEntity(content, "name", ROLE_KEYS, `roles/${file}`, problems);
487
856
  return content;
488
857
  });
489
858
  }
490
- return { manifest, problems };
859
+ return { manifest, modes, problems };
491
860
  }
492
861
  function writeManifest(dir, manifest, options = {}) {
493
862
  const written = [];
494
863
  const stale = [];
495
864
  const pruned = [];
865
+ const drift = [];
496
866
  const objects = manifest.objects ?? [];
497
867
  const relationships = manifest.relationships ?? [];
498
868
  const bySource = /* @__PURE__ */ new Map();
@@ -503,6 +873,14 @@ function writeManifest(dir, manifest, options = {}) {
503
873
  list.push(rest);
504
874
  bySource.set(relationship.source, list);
505
875
  }
876
+ const shared = {
877
+ written,
878
+ stale,
879
+ pruned,
880
+ drift,
881
+ prune: options.prune ?? false,
882
+ check: options.check ?? false
883
+ };
506
884
  syncDir(
507
885
  join2(dir, "objects"),
508
886
  objects.map((object) => {
@@ -513,7 +891,7 @@ function writeManifest(dir, manifest, options = {}) {
513
891
  };
514
892
  }),
515
893
  "slug",
516
- { written, stale, pruned, prune: options.prune ?? false, base: "objects" }
894
+ { ...shared, base: "objects", banner: objectBanner }
517
895
  );
518
896
  syncDir(
519
897
  join2(dir, "workflows"),
@@ -522,18 +900,62 @@ function writeManifest(dir, manifest, options = {}) {
522
900
  content: clean({ ...workflow })
523
901
  })),
524
902
  "slug",
525
- { written, stale, pruned, prune: options.prune ?? false, base: "workflows" }
903
+ { ...shared, base: "workflows" }
526
904
  );
527
905
  syncDir(
528
906
  join2(dir, "agents"),
529
907
  (manifest.agents ?? []).map((agent) => ({ id: agent.handle, content: clean({ ...agent }) })),
530
908
  "handle",
531
- { written, stale, pruned, prune: options.prune ?? false, base: "agents" }
909
+ { ...shared, base: "agents" }
910
+ );
911
+ syncDir(
912
+ join2(dir, "policies"),
913
+ (manifest.policies ?? []).map((policy) => ({ id: policy.slug, content: clean({ ...policy }) })),
914
+ "slug",
915
+ { ...shared, base: "policies" }
916
+ );
917
+ syncDir(
918
+ join2(dir, "roles"),
919
+ (manifest.roles ?? []).map((role) => ({ id: role.name, content: clean({ ...role }) })),
920
+ "name",
921
+ { ...shared, base: "roles" }
532
922
  );
533
- return { written, stale, pruned };
923
+ syncSettings(dir, manifest.settings, shared);
924
+ return { written, stale, pruned, drift };
925
+ }
926
+ function syncSettings(dir, settings, out2) {
927
+ const file = join2(dir, "hablala.yaml");
928
+ if (!existsSync2(file) && (!settings || Object.keys(settings).length === 0)) return;
929
+ const doc = existsSync2(file) ? parseDocument(readFileSync2(file, "utf8")) : parseDocument("");
930
+ const current = doc.get("settings");
931
+ const currentJson = current ? JSON.stringify(doc.toJS().settings) : null;
932
+ const desiredJson = settings && Object.keys(settings).length > 0 ? JSON.stringify(settings) : null;
933
+ if (currentJson === desiredJson) return;
934
+ if (out2.check) {
935
+ out2.drift.push("hablala.yaml");
936
+ return;
937
+ }
938
+ if (desiredJson === null) doc.delete("settings");
939
+ else doc.set("settings", settings);
940
+ writeFileSync3(file, doc.toString(), "utf8");
941
+ out2.written.push("hablala.yaml");
942
+ }
943
+ function objectBanner(content) {
944
+ const level = content.manageability;
945
+ if (level === "seeded") {
946
+ 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";
947
+ }
948
+ if (level === "system") {
949
+ 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";
950
+ }
951
+ return "";
534
952
  }
535
953
  function syncDir(dirPath, entities, idKey, out2) {
536
- mkdirSync2(dirPath, { recursive: true });
954
+ if (!out2.check) mkdirSync2(dirPath, { recursive: true });
955
+ else if (!existsSync2(dirPath)) {
956
+ for (const { id } of entities) out2.drift.push(`${out2.base}/${id}.yaml`);
957
+ return;
958
+ }
537
959
  const fileById = /* @__PURE__ */ new Map();
538
960
  for (const file of yamlFiles(dirPath)) {
539
961
  try {
@@ -546,13 +968,22 @@ function syncDir(dirPath, entities, idKey, out2) {
546
968
  const writtenFiles = /* @__PURE__ */ new Set();
547
969
  for (const { id, content } of entities) {
548
970
  const file = fileById.get(id) ?? `${id}.yaml`;
549
- writeFileSync3(join2(dirPath, file), stringify(content), "utf8");
971
+ const serialized = (out2.banner?.(content) ?? "") + stringify(content);
972
+ if (out2.check) {
973
+ const path = join2(dirPath, file);
974
+ const current = existsSync2(path) ? readFileSync2(path, "utf8") : null;
975
+ if (current !== serialized) out2.drift.push(`${out2.base}/${file}`);
976
+ } else {
977
+ writeFileSync3(join2(dirPath, file), serialized, "utf8");
978
+ out2.written.push(`${out2.base}/${file}`);
979
+ }
550
980
  writtenFiles.add(file);
551
- out2.written.push(`${out2.base}/${file}`);
552
981
  }
553
982
  for (const file of yamlFiles(dirPath)) {
554
983
  if (writtenFiles.has(file)) continue;
555
- if (out2.prune) {
984
+ if (out2.check) {
985
+ out2.drift.push(`${out2.base}/${file}`);
986
+ } else if (out2.prune) {
556
987
  rmSync(join2(dirPath, file));
557
988
  out2.pruned.push(`${out2.base}/${file}`);
558
989
  } else {
@@ -603,9 +1034,225 @@ function validateEnum(entity, keys, allowed, where, problems) {
603
1034
  }
604
1035
  }
605
1036
  }
1037
+ function validateEnumOrList(entity, key, allowed, where, problems) {
1038
+ const value = entity[key];
1039
+ if (value === void 0) return;
1040
+ const values = Array.isArray(value) ? value : [value];
1041
+ if (values.length === 0) {
1042
+ problems.push(`${where}: "${key}" no puede ser una lista vac\xEDa`);
1043
+ return;
1044
+ }
1045
+ for (const item of values) {
1046
+ if (typeof item !== "string" || !allowed.includes(item)) {
1047
+ problems.push(
1048
+ `${where}: "${key}: ${String(item)}" no es v\xE1lido (valores: ${allowed.join(", ")})`
1049
+ );
1050
+ }
1051
+ }
1052
+ }
1053
+ function validateStringList(entity, keys, where, problems) {
1054
+ for (const key of keys) {
1055
+ const value = entity[key];
1056
+ if (value === void 0) continue;
1057
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
1058
+ problems.push(`${where}: "${key}" debe ser una lista de slugs (strings)`);
1059
+ }
1060
+ }
1061
+ }
1062
+ var EVAL_ASSERTIONS = /* @__PURE__ */ new Set([
1063
+ "tool",
1064
+ "noTool",
1065
+ "no_tool",
1066
+ "handoff",
1067
+ "requiresApproval",
1068
+ "requires_approval",
1069
+ "contains"
1070
+ ]);
1071
+ function validateEvals(evals, where, problems) {
1072
+ if (evals === void 0) return;
1073
+ if (!Array.isArray(evals)) {
1074
+ problems.push(`${where}: "evals" debe ser una lista de casos de prueba`);
1075
+ return;
1076
+ }
1077
+ for (const raw of evals) {
1078
+ if (!raw || typeof raw !== "object") {
1079
+ problems.push(`${where}: cada eval debe ser un mapa {name, input, expect}`);
1080
+ continue;
1081
+ }
1082
+ const eval_ = raw;
1083
+ if (typeof eval_.name !== "string" || eval_.name === "")
1084
+ problems.push(`${where}: un eval declara un "name" no vac\xEDo`);
1085
+ if (typeof eval_.input !== "string" || eval_.input === "")
1086
+ problems.push(`${where}: el eval "${String(eval_.name)}" declara un "input" no vac\xEDo`);
1087
+ const expect = eval_.expect;
1088
+ if (expect !== void 0) {
1089
+ if (!expect || typeof expect !== "object") {
1090
+ problems.push(`${where}: el "expect" del eval "${String(eval_.name)}" debe ser un mapa`);
1091
+ } else {
1092
+ for (const key of Object.keys(expect)) {
1093
+ if (!EVAL_ASSERTIONS.has(key))
1094
+ problems.push(`${where}: el eval "${String(eval_.name)}" usa aserci\xF3n desconocida "${key}"`);
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ }
1100
+ var UNIQUE_INCOMPATIBLE = /* @__PURE__ */ new Set(["multiselect", "boolean", "file", "formula", "rollup"]);
1101
+ var OPTIONS_TYPES = /* @__PURE__ */ new Set(["select", "multiselect"]);
1102
+ var DERIVED_TYPES = /* @__PURE__ */ new Set(["formula", "rollup"]);
1103
+ var ROLLUP_AGGREGATES = /* @__PURE__ */ new Set(["sum", "count", "avg", "min", "max"]);
1104
+ function flag(attribute, camel, snake) {
1105
+ return attribute[camel] === true || attribute[snake] === true;
1106
+ }
1107
+ function validateAttributeRules(attribute, where, problems) {
1108
+ const dataType = attribute.dataType ?? attribute.data_type;
1109
+ if (typeof dataType !== "string" || !DATA_TYPES.includes(dataType)) return;
1110
+ if (flag(attribute, "isUnique", "is_unique") && UNIQUE_INCOMPATIBLE.has(dataType)) {
1111
+ problems.push(`${where}: "isUnique" no es soportado para el tipo ${dataType}`);
1112
+ }
1113
+ if (dataType === "file") {
1114
+ if (flag(attribute, "isIndexed", "is_indexed"))
1115
+ problems.push(`${where}: "isIndexed" no es soportado para el tipo file`);
1116
+ if (flag(attribute, "embedInVector", "embed_in_vector"))
1117
+ problems.push(`${where}: "embedInVector" no es soportado para el tipo file`);
1118
+ }
1119
+ if (DERIVED_TYPES.has(dataType)) {
1120
+ if (flag(attribute, "isIndexed", "is_indexed"))
1121
+ problems.push(`${where}: "isIndexed" no es soportado para el tipo ${dataType} (derivado)`);
1122
+ if (flag(attribute, "embedInVector", "embed_in_vector"))
1123
+ problems.push(`${where}: "embedInVector" no es soportado para el tipo ${dataType} (derivado)`);
1124
+ if (flag(attribute, "isRequired", "is_required"))
1125
+ problems.push(`${where}: "isRequired" no es soportado para el tipo ${dataType} (derivado)`);
1126
+ }
1127
+ const config = attribute.config;
1128
+ const cfg = config && typeof config === "object" ? config : {};
1129
+ if (OPTIONS_TYPES.has(dataType)) {
1130
+ const options = cfg.options;
1131
+ if (!Array.isArray(options) || options.length === 0) {
1132
+ problems.push(`${where}: el tipo ${dataType} requiere "config.options" (lista no vac\xEDa)`);
1133
+ } else if (!options.every((o) => typeof o === "string" || o && typeof o === "object")) {
1134
+ problems.push(`${where}: "config.options" debe ser una lista de strings (o de {value, label})`);
1135
+ }
1136
+ }
1137
+ if (dataType === "number") {
1138
+ const { min, max } = cfg;
1139
+ if (min !== void 0 && typeof min !== "number")
1140
+ problems.push(`${where}: "config.min" debe ser un n\xFAmero`);
1141
+ if (max !== void 0 && typeof max !== "number")
1142
+ problems.push(`${where}: "config.max" debe ser un n\xFAmero`);
1143
+ if (typeof min === "number" && typeof max === "number" && min > max)
1144
+ problems.push(`${where}: "config.min" no puede ser mayor que "config.max"`);
1145
+ }
1146
+ if (dataType === "file") {
1147
+ const maxCount = cfg.max_count ?? cfg.maxCount;
1148
+ if (maxCount !== void 0 && !(typeof maxCount === "number" && Number.isInteger(maxCount) && maxCount > 0))
1149
+ problems.push(`${where}: "config.maxCount" debe ser un entero positivo`);
1150
+ const accepted = cfg.accepted_content_types ?? cfg.acceptedContentTypes;
1151
+ if (accepted !== void 0 && (!Array.isArray(accepted) || !accepted.every((t) => typeof t === "string")))
1152
+ problems.push(`${where}: "config.acceptedContentTypes" debe ser una lista de strings (mime, admite comodines image/*)`);
1153
+ }
1154
+ if (dataType === "reference") {
1155
+ const target = cfg.target_object ?? cfg.targetObject;
1156
+ if (target !== void 0 && !(typeof target === "string" && target.length > 0))
1157
+ problems.push(`${where}: "config.targetObject" debe ser un slug de object (string no vac\xEDo)`);
1158
+ }
1159
+ if (dataType === "formula") {
1160
+ const expression = cfg.expression;
1161
+ if (typeof expression !== "string" || expression.length === 0)
1162
+ problems.push(`${where}: el tipo formula requiere "config.expression" (string no vac\xEDo)`);
1163
+ }
1164
+ if (dataType === "rollup") {
1165
+ const relationship = cfg.relationship;
1166
+ const aggregate = cfg.aggregate;
1167
+ const target = cfg.target;
1168
+ if (typeof relationship !== "string" || relationship.length === 0)
1169
+ problems.push(`${where}: el tipo rollup requiere "config.relationship" (slug del relationship)`);
1170
+ if (typeof aggregate !== "string" || !ROLLUP_AGGREGATES.has(aggregate))
1171
+ problems.push(
1172
+ `${where}: el tipo rollup requiere "config.aggregate" \u2208 ${[...ROLLUP_AGGREGATES].join("/")}`
1173
+ );
1174
+ if (aggregate !== "count" && (typeof target !== "string" || target.length === 0))
1175
+ problems.push(`${where}: el rollup "${String(aggregate)}" requiere "config.target" (slug del atributo a agregar)`);
1176
+ }
1177
+ }
1178
+ function validateLayout(config, attributeSlugs, relationshipSlugs, where, problems) {
1179
+ if (!config || typeof config !== "object") return;
1180
+ const layout = config.layout;
1181
+ if (layout === void 0) return;
1182
+ if (typeof layout !== "object" || layout === null) {
1183
+ problems.push(`${where}: "config.layout" debe ser un objeto`);
1184
+ return;
1185
+ }
1186
+ const l = layout;
1187
+ if (l.highlights !== void 0) {
1188
+ if (!Array.isArray(l.highlights)) {
1189
+ problems.push(`${where}: "layout.highlights" debe ser una lista de slugs de attribute`);
1190
+ } else {
1191
+ for (const slug of l.highlights) {
1192
+ if (typeof slug !== "string" || !attributeSlugs.has(slug))
1193
+ problems.push(`${where}: "layout.highlights" referencia un attribute inexistente: "${String(slug)}"`);
1194
+ }
1195
+ }
1196
+ }
1197
+ if (l.sections !== void 0) {
1198
+ if (!Array.isArray(l.sections)) {
1199
+ problems.push(`${where}: "layout.sections" debe ser una lista de {title, fields}`);
1200
+ } else {
1201
+ for (const section of l.sections) {
1202
+ const s = section;
1203
+ if (typeof s?.title !== "string" || s.title.length === 0)
1204
+ problems.push(`${where}: cada "layout.sections" requiere un "title" (string no vac\xEDo)`);
1205
+ if (!Array.isArray(s?.fields)) {
1206
+ problems.push(`${where}: "layout.sections[].fields" debe ser una lista de slugs de attribute`);
1207
+ } else {
1208
+ for (const slug of s.fields) {
1209
+ if (typeof slug !== "string" || !attributeSlugs.has(slug))
1210
+ problems.push(`${where}: "layout.sections" referencia un attribute inexistente: "${String(slug)}"`);
1211
+ }
1212
+ }
1213
+ }
1214
+ }
1215
+ }
1216
+ if (l.related !== void 0) {
1217
+ if (!Array.isArray(l.related)) {
1218
+ problems.push(`${where}: "layout.related" debe ser una lista de {relationship}`);
1219
+ } else {
1220
+ for (const item of l.related) {
1221
+ const slug = item?.relationship;
1222
+ if (typeof slug !== "string" || !relationshipSlugs.has(slug))
1223
+ problems.push(`${where}: "layout.related" referencia un relationship inexistente: "${String(slug)}"`);
1224
+ }
1225
+ }
1226
+ }
1227
+ const groupBy = l.groupBy ?? l.group_by;
1228
+ if (groupBy !== void 0 && (typeof groupBy !== "string" || !attributeSlugs.has(groupBy)))
1229
+ problems.push(`${where}: "layout.groupBy" referencia un attribute inexistente: "${String(groupBy)}"`);
1230
+ }
606
1231
  function asList(value) {
607
1232
  return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
608
1233
  }
1234
+ var VERSION_FILE = ".hablala-version";
1235
+ function writeLock(dir, lock) {
1236
+ writeFileSync3(join2(dir, VERSION_FILE), `${JSON.stringify(lock, null, 2)}
1237
+ `, "utf8");
1238
+ }
1239
+ function readLock(dir) {
1240
+ const path = join2(dir, VERSION_FILE);
1241
+ if (!existsSync2(path)) return void 0;
1242
+ const raw = readFileSync2(path, "utf8").trim();
1243
+ if (raw === "") return void 0;
1244
+ if (raw.startsWith("{")) {
1245
+ try {
1246
+ const parsed = JSON.parse(raw);
1247
+ const lineage = typeof parsed.lineage === "string" ? parsed.lineage : void 0;
1248
+ const version2 = typeof parsed.version === "string" ? parsed.version : void 0;
1249
+ if (!lineage && !version2) return void 0;
1250
+ return { lineage, version: version2 };
1251
+ } catch {
1252
+ }
1253
+ }
1254
+ return { version: raw };
1255
+ }
609
1256
  function clean(value) {
610
1257
  const result = {};
611
1258
  for (const [key, entry] of Object.entries(value)) {
@@ -633,6 +1280,7 @@ import { createHash, randomBytes } from "crypto";
633
1280
  import { createServer } from "http";
634
1281
  import { hostname } from "os";
635
1282
  var CLIENT_ID = "hablala-cli";
1283
+ var DEFAULT_PRESET = "account_as_code";
636
1284
  var DEFAULT_APP_URL = "https://app.hablala.com";
637
1285
  var LOOPBACK_TIMEOUT_MS = 5 * 60 * 1e3;
638
1286
  var defaultSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
@@ -772,6 +1420,7 @@ async function loginWithBrowser(endpoint, deps = {}) {
772
1420
  authorizeUrl.searchParams.set("code_challenge", challenge);
773
1421
  authorizeUrl.searchParams.set("code_challenge_method", "S256");
774
1422
  authorizeUrl.searchParams.set("device_name", hostname());
1423
+ authorizeUrl.searchParams.set("preset", DEFAULT_PRESET);
775
1424
  log("Abriendo el navegador para autorizar\u2026");
776
1425
  if (!open(authorizeUrl.toString())) {
777
1426
  log("No se pudo abrir el navegador. Abre esta URL a mano:");
@@ -795,7 +1444,11 @@ async function loginWithDeviceFlow(endpoint, deps = {}) {
795
1444
  const startResponse = await fetchImpl(metadata.device_authorization_endpoint, {
796
1445
  method: "POST",
797
1446
  headers: { "content-type": "application/x-www-form-urlencoded" },
798
- body: new URLSearchParams({ client_id: CLIENT_ID, device_name: hostname() }).toString()
1447
+ body: new URLSearchParams({
1448
+ client_id: CLIENT_ID,
1449
+ device_name: hostname(),
1450
+ preset: DEFAULT_PRESET
1451
+ }).toString()
799
1452
  });
800
1453
  if (!startResponse.ok) {
801
1454
  throw new Error(`no se pudo iniciar el device flow (${startResponse.status}).`);
@@ -852,7 +1505,7 @@ var WRITE_PERMISSIONS = [
852
1505
  ];
853
1506
  var info = (message) => console.error(message);
854
1507
  var out = (message) => console.log(message);
855
- function flag(args, name) {
1508
+ function flag2(args, name) {
856
1509
  const value = args[name];
857
1510
  return typeof value === "string" ? value : void 0;
858
1511
  }
@@ -863,12 +1516,12 @@ function targetDir(args) {
863
1516
  return resolve2(process.cwd(), args._[1] ?? ".");
864
1517
  }
865
1518
  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;
1519
+ const endpoint = (flag2(args, "endpoint") ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
1520
+ let token = flag2(args, "token") ?? process.env.HABLALA_ACCESS_TOKEN;
868
1521
  if (token) {
869
1522
  token = token.trim();
870
- if (!token.startsWith("hpat_")) {
871
- info(red("\u2716") + ' El token debe empezar por "hpat_".');
1523
+ if (!token.startsWith("mat_")) {
1524
+ info(red("\u2716") + ' El token debe empezar por "mat_".');
872
1525
  return 1;
873
1526
  }
874
1527
  } else {
@@ -879,9 +1532,16 @@ async function login(args) {
879
1532
  const identity = await whoami(api);
880
1533
  const path = writeCredentials({ endpoint, accessToken: token });
881
1534
  out(
882
- `${green("\u2714")} Autenticado como ${bold(identity.organization.name)} / workspace ${bold(identity.workspace.name)}.`
1535
+ `${green("\u2714")} Autenticado en la organizaci\xF3n ${bold(identity.organization.name)}.`
883
1536
  );
884
1537
  out(dim(` Credenciales en ${path} (0600).`));
1538
+ if (identity.principal === "public") {
1539
+ out(
1540
+ `${yellow("!")} Esta es una API key publishable (solo lectura): \`pull\` y \`plan\` funcionan, pero \`apply\` no.`
1541
+ );
1542
+ out(dim(" Para aplicar cambios, emite un token de acceso (mat_\u2026) con permisos de escritura."));
1543
+ return 0;
1544
+ }
885
1545
  const missing = WRITE_PERMISSIONS.filter(
886
1546
  (permission) => !identity.permissions.includes(permission)
887
1547
  );
@@ -896,13 +1556,32 @@ async function login(args) {
896
1556
  async function pull(args) {
897
1557
  const dir = targetDir(args);
898
1558
  const config = resolveConfig({
899
- tokenFlag: flag(args, "token"),
900
- endpointFlag: flag(args, "endpoint")
1559
+ tokenFlag: flag2(args, "token"),
1560
+ endpointFlag: flag2(args, "endpoint")
901
1561
  });
902
1562
  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") });
1563
+ const check = has(args, "check");
1564
+ info(dim(`\u2192 GET ${config.endpoint}/v1/account-config`));
1565
+ const { sections: manifest, version: version2 } = await fetchManifest(api);
1566
+ const result = writeManifest(dir, manifest, { prune: has(args, "prune"), check });
1567
+ if (!check && version2) {
1568
+ const identity = await whoami(api);
1569
+ writeLock(dir, { lineage: identity.organization.id, version: version2 });
1570
+ }
1571
+ if (check) {
1572
+ if (has(args, "json")) {
1573
+ out(JSON.stringify({ drift: result.drift }, null, 2));
1574
+ return result.drift.length > 0 ? 1 : 0;
1575
+ }
1576
+ if (result.drift.length === 0) {
1577
+ out(`${green("\u2714")} Los archivos est\xE1n en sincron\xEDa con la organizaci\xF3n.`);
1578
+ return 0;
1579
+ }
1580
+ out(`${yellow("!")} ${result.drift.length} archivo(s) difieren del estado real de la organizaci\xF3n:`);
1581
+ for (const file of result.drift) out(` ${file}`);
1582
+ 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."));
1583
+ return 1;
1584
+ }
906
1585
  if (has(args, "json")) {
907
1586
  out(
908
1587
  JSON.stringify(
@@ -916,7 +1595,7 @@ async function pull(args) {
916
1595
  out(`${green("\u2714")} ${result.written.length} archivo(s) sincronizados en ${dir}.`);
917
1596
  for (const file of result.pruned) out(dim(` borrado (sobrante): ${file}`));
918
1597
  if (result.stale.length > 0) {
919
- out(`${yellow("!")} Archivos que no corresponden a nada en el workspace (\xBFWIP o sobrantes?):`);
1598
+ out(`${yellow("!")} Archivos que no corresponden a nada en la organizaci\xF3n (\xBFWIP o sobrantes?):`);
920
1599
  for (const file of result.stale) out(` ${file}`);
921
1600
  out(dim(" `apply` los crear\xEDa; `pull --prune` los borra."));
922
1601
  }
@@ -925,8 +1604,8 @@ async function pull(args) {
925
1604
  async function init(args) {
926
1605
  const dir = targetDir(args);
927
1606
  const config = resolveConfig({
928
- tokenFlag: flag(args, "token"),
929
- endpointFlag: flag(args, "endpoint")
1607
+ tokenFlag: flag2(args, "token"),
1608
+ endpointFlag: flag2(args, "endpoint")
930
1609
  });
931
1610
  const api = createApiClient(config);
932
1611
  const identity = await whoami(api);
@@ -936,14 +1615,16 @@ async function init(args) {
936
1615
  hablalaYaml(identity, config.endpoint),
937
1616
  has(args, "force")
938
1617
  );
1618
+ scaffoldFile(join3(dir, ".gitignore"), gitignore(), has(args, "force"));
939
1619
  const guide = agentGuide(identity);
940
1620
  scaffoldFile(join3(dir, "CLAUDE.md"), guide, has(args, "force"));
941
1621
  scaffoldFile(join3(dir, "AGENTS.md"), guide, has(args, "force"));
942
- const manifest = await fetchManifest(api);
1622
+ const { sections: manifest, version: version2 } = await fetchManifest(api);
943
1623
  const result = writeManifest(dir, manifest, { prune: false });
944
- out(`${green("\u2714")} Workspace ${bold(identity.workspace.name)} inicializado en ${dir}:`);
1624
+ if (version2) writeLock(dir, { lineage: identity.organization.id, version: version2 });
1625
+ out(`${green("\u2714")} Organizaci\xF3n ${bold(identity.organization.name)} inicializada en ${dir}:`);
945
1626
  out(
946
- ` hablala.yaml, CLAUDE.md + AGENTS.md y ${result.written.length} archivo(s) de configuraci\xF3n.`
1627
+ ` hablala.yaml, .gitignore, CLAUDE.md + AGENTS.md y ${result.written.length} archivo(s) de configuraci\xF3n.`
947
1628
  );
948
1629
  out("");
949
1630
  out(` Siguiente paso: edita los archivos y corre ${bold("hablala plan")}.`);
@@ -960,12 +1641,15 @@ async function plan(args) {
960
1641
  const loaded = loadLocal(args);
961
1642
  if (typeof loaded === "number") return loaded;
962
1643
  const config = resolveConfig({
963
- tokenFlag: flag(args, "token"),
964
- endpointFlag: flag(args, "endpoint")
1644
+ tokenFlag: flag2(args, "token"),
1645
+ endpointFlag: flag2(args, "endpoint")
965
1646
  });
966
1647
  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 });
1648
+ info(dim(`\u2192 PUT ${config.endpoint}/v1/account-config?dry_run=true`));
1649
+ const { plan: result, failure } = await putManifest(api, loaded.manifest, {
1650
+ dryRun: true,
1651
+ modes: loaded.modes
1652
+ });
969
1653
  if (failure) {
970
1654
  printFailure(failure);
971
1655
  return 1;
@@ -982,11 +1666,38 @@ async function apply(args) {
982
1666
  const loaded = loadLocal(args);
983
1667
  if (typeof loaded === "number") return loaded;
984
1668
  const config = resolveConfig({
985
- tokenFlag: flag(args, "token"),
986
- endpointFlag: flag(args, "endpoint")
1669
+ tokenFlag: flag2(args, "token"),
1670
+ endpointFlag: flag2(args, "endpoint")
987
1671
  });
988
1672
  const api = createApiClient(config);
989
- const preview = await putManifest(api, loaded, { dryRun: true });
1673
+ const dir = targetDir(args);
1674
+ const identity = await whoami(api);
1675
+ const lineage = identity.organization.id;
1676
+ const lock = readLock(dir);
1677
+ let expectedVersion = lock?.version;
1678
+ if (lock?.lineage && lock.lineage !== lineage) {
1679
+ if (has(args, "force-lineage")) {
1680
+ info(
1681
+ yellow("!") + ` El lockfile es de la cuenta ${dim(lock.lineage)} pero apuntas a ${dim(lineage)}. \`--force-lineage\`: ignoro el ETag viejo y aplico como backend nuevo.`
1682
+ );
1683
+ expectedVersion = void 0;
1684
+ } else {
1685
+ info(
1686
+ `${red("\u2716")} Este \`.hablala-version\` pertenece a otra cuenta (lineage ${bold(lock.lineage)}), pero el token apunta a ${bold(lineage)}.`
1687
+ );
1688
+ info(
1689
+ dim(
1690
+ " Suele pasar tras resetear la DB (org nueva). Si es intencional, borra `.hablala-version` (se regenera al aplicar) o corre `hablala apply --force-lineage`. Si NO lo es, revisa que el token apunte a la cuenta correcta antes de aplicar."
1691
+ )
1692
+ );
1693
+ return 1;
1694
+ }
1695
+ } else if (!lock) {
1696
+ info(
1697
+ 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."
1698
+ );
1699
+ }
1700
+ const preview = await putManifest(api, loaded.manifest, { dryRun: true, modes: loaded.modes });
990
1701
  if (preview.failure) {
991
1702
  printFailure(preview.failure);
992
1703
  return 1;
@@ -1008,32 +1719,68 @@ async function apply(args) {
1008
1719
  return 1;
1009
1720
  }
1010
1721
  }
1011
- const { plan: applied, failure } = await putManifest(api, loaded, { dryRun: false });
1722
+ const { plan: applied, failure } = await putManifest(api, loaded.manifest, {
1723
+ dryRun: false,
1724
+ expectedVersion,
1725
+ modes: loaded.modes
1726
+ });
1012
1727
  if (failure) {
1013
1728
  printFailure(failure);
1729
+ if (failure.versionConflict) {
1730
+ info(dim(" \u2192 corre `hablala pull` para traer los cambios, revisa el diff y vuelve a aplicar."));
1731
+ }
1014
1732
  return 1;
1015
1733
  }
1016
- const summary = applied.summary;
1734
+ const applyResult = applied;
1735
+ const nextVersion = applyResult.version;
1736
+ writeLock(dir, { lineage, version: nextVersion });
1737
+ const summary = applyResult.summary;
1738
+ const deletePart = summary.delete ? `, ${summary.delete} borrado(s)` : "";
1017
1739
  out("");
1018
1740
  out(
1019
- `${green("\u2714")} Aplicado: ${summary.create ?? 0} creado(s), ${summary.update ?? 0} actualizado(s), ${summary.archive ?? 0} archivado(s).`
1741
+ `${green("\u2714")} Aplicado: ${summary.create ?? 0} creado(s), ${summary.update ?? 0} actualizado(s), ${summary.archive ?? 0} archivado(s)${deletePart}.`
1020
1742
  );
1021
1743
  return 0;
1022
1744
  }
1745
+ async function evalAgents(args) {
1746
+ const loaded = loadLocal(args);
1747
+ if (typeof loaded === "number") return loaded;
1748
+ const config = resolveConfig({
1749
+ tokenFlag: flag2(args, "token"),
1750
+ endpointFlag: flag2(args, "endpoint")
1751
+ });
1752
+ const api = createApiClient(config);
1753
+ const live = has(args, "live");
1754
+ info(dim(`\u2192 POST ${config.endpoint}/v1/account-config/eval${live ? "?live=true" : ""}`));
1755
+ const { result, failure } = await runEvals(api, loaded.manifest, { live });
1756
+ if (failure) {
1757
+ printFailure(failure);
1758
+ return 1;
1759
+ }
1760
+ const evalResult = result;
1761
+ if (has(args, "json")) {
1762
+ out(JSON.stringify(evalResult, null, 2));
1763
+ } else {
1764
+ out(renderEvals(evalResult));
1765
+ }
1766
+ return (evalResult.failed ?? 0) > 0 ? 1 : 0;
1767
+ }
1023
1768
  function loadLocal(args) {
1024
1769
  const dir = targetDir(args);
1025
- const { manifest, problems } = readManifest(dir);
1770
+ const { manifest, modes, problems } = readManifest(dir);
1026
1771
  if (problems.length > 0) {
1027
1772
  out(bold("El manifiesto no pasa la validaci\xF3n local:"));
1028
1773
  for (const problem of problems) out(` ${red("\u2716")} ${problem}`);
1029
1774
  return 1;
1030
1775
  }
1031
- if (!manifest.objects && !manifest.workflows && !manifest.agents) {
1032
- out(`${yellow("!")} ${dir} no tiene objects/, workflows/ ni agents/ \u2014 nada que declarar.`);
1776
+ if (!manifest.objects && !manifest.workflows && !manifest.agents && !manifest.policies) {
1777
+ out(
1778
+ `${yellow("!")} ${dir} no tiene objects/, workflows/, agents/ ni policies/ \u2014 nada que declarar.`
1779
+ );
1033
1780
  out(dim(" Corre `hablala init` para bajar el estado actual a archivos."));
1034
1781
  return 1;
1035
1782
  }
1036
- return manifest;
1783
+ return { manifest, modes };
1037
1784
  }
1038
1785
  function printFailure(failure) {
1039
1786
  out(`${red("\u2716")} ${failure.detail}`);
@@ -1060,23 +1807,29 @@ function promptLine(query) {
1060
1807
 
1061
1808
  // src/index.ts
1062
1809
  var { version } = createRequire(import.meta.url)("../package.json");
1063
- var USAGE = `hablala v${version} \u2014 Workspace as Code de Hablal\xE1
1810
+ var USAGE = `hablala v${version} \u2014 Account as Code de Hablal\xE1
1064
1811
 
1065
1812
  Uso:
1066
1813
  hablala login [--device] [--endpoint URL] Inicia sesi\xF3n por el navegador y guarda
1067
1814
  la credencial (--device: sin navegador
1068
1815
  local \u2014 SSH/contenedores; se autodetecta)
1069
1816
  hablala init [dir] [--force] Scaffold + pull del estado actual
1070
- hablala pull [dir] [--prune] [--json] Exporta el estado real a archivos
1817
+ hablala pull [dir] [--prune] [--check] [--json] Exporta el estado real a archivos
1818
+ (--check: no escribe; sale 1 si los
1819
+ archivos difieren del server \u2014 CI)
1071
1820
  hablala plan [dir] [--json] Diff declarado vs. real (dry-run)
1072
- hablala apply [dir] [--yes] Reconcilia contra el workspace
1821
+ hablala apply [dir] [--yes] [--force-lineage] Reconcilia contra la organizaci\xF3n
1822
+ (--force-lineage: aplica aunque el lockfile
1823
+ sea de otra cuenta, p. ej. tras resetear la DB)
1824
+ hablala eval [dir] [--live] [--json] Corre los evals de los agentes
1825
+ (--live: LLM real; sale 1 si alg\xFAn caso falla)
1073
1826
  hablala codegen [--out hablala.types.ts] Tipos TS por tenant para @hablala/client
1074
1827
 
1075
1828
  Opciones globales:
1076
- --token <hpat_\u2026> Access token pegado a mano \u2014 el camino de CI. Prefiere la variable
1829
+ --token <mat_\u2026> Access token pegado a mano \u2014 el camino de CI. Prefiere la variable
1077
1830
  de entorno HABLALA_ACCESS_TOKEN: pasarlo por flag filtra el secreto
1078
1831
  en el historial del shell y en \`ps\`.
1079
- (codegen usa un storefront token sfpk_/sfpr_ \u2014 HABLALA_STOREFRONT_TOKEN)
1832
+ (codegen usa una API key pk_/sk_ \u2014 HABLALA_TOKEN)
1080
1833
  --endpoint <url> Host de la API (o HABLALA_ENDPOINT). Default: https://api.hablala.com
1081
1834
  --json Salida JSON parseable por stdout (para pipes/CI); en plan y pull
1082
1835
  -h, --help Esta ayuda
@@ -1088,7 +1841,16 @@ archiva (nunca se borra). \`plan\` siempre muestra el diff completo antes de apl
1088
1841
 
1089
1842
  Docs y soporte: https://github.com/hablala/hablala
1090
1843
  `;
1091
- var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["help", "force", "prune", "yes", "device", "json"]);
1844
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
1845
+ "help",
1846
+ "force",
1847
+ "prune",
1848
+ "yes",
1849
+ "device",
1850
+ "json",
1851
+ "check",
1852
+ "force-lineage"
1853
+ ]);
1092
1854
  function parseArgs(argv) {
1093
1855
  const args = { _: [] };
1094
1856
  for (let i = 0; i < argv.length; i++) {
@@ -1121,6 +1883,7 @@ async function main() {
1121
1883
  pull,
1122
1884
  plan,
1123
1885
  apply,
1886
+ eval: evalAgents,
1124
1887
  codegen,
1125
1888
  // Alias histórico del bin de @hablala/client (`hablala gen`).
1126
1889
  gen: codegen