@hablala/cli 0.12.11 → 0.13.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
@@ -66,10 +66,11 @@ var red = paint("31");
66
66
  var dim = paint("2");
67
67
  var bold = paint("1");
68
68
  function changeLabel(change) {
69
- if (change.type === "attribute")
70
- return `attribute ${change.objectSlug ?? "?"}.${change.slug ?? "?"}`;
69
+ const identifier = change.apiName ?? change.slug;
70
+ if (change.type === "field")
71
+ return `field ${change.objectApiName ?? "?"}.${identifier ?? "?"}`;
71
72
  if (change.type === "agent") return `agent @${change.handle ?? "?"}`;
72
- return `${change.type} ${change.slug ?? change.name ?? "?"}`;
73
+ return `${change.type} ${identifier ?? change.name ?? "?"}`;
73
74
  }
74
75
  function accessSentence(change) {
75
76
  const access = change.access ?? {};
@@ -109,13 +110,13 @@ function changeLines(change) {
109
110
  }
110
111
  function renderErrors(errors) {
111
112
  return errors.map((error) => {
112
- const where = [error.type, error.objectSlug, error.identifier].filter(Boolean).join(" ");
113
+ const where = [error.type, error.objectApiName, error.identifier].filter(Boolean).join(" ");
113
114
  return ` ${red("\u2716")} ${where}: ${error.message}`;
114
115
  }).join("\n");
115
116
  }
116
117
  function accessLine(change) {
117
118
  const symbol = change.action === "create" ? green("+") : change.action === "update" ? yellow("~") : red("-");
118
- return ` ${symbol} ${change.slug ?? "?"} \u2014 ${accessSentence(change)}`;
119
+ return ` ${symbol} ${change.apiName ?? "?"} \u2014 ${accessSentence(change)}`;
119
120
  }
120
121
  function renderPlan(plan2) {
121
122
  const lines = [];
@@ -153,27 +154,6 @@ function renderPlan(plan2) {
153
154
  lines.push(`${bold("Plan:")} ${counts}`);
154
155
  return lines.join("\n");
155
156
  }
156
- function renderEvals(result) {
157
- const lines = [];
158
- for (const agent2 of result.agents ?? []) {
159
- lines.push(bold(`@${agent2.handle}`));
160
- if (agent2.error) {
161
- lines.push(` ${red("\u2716")} ${agent2.error}`);
162
- continue;
163
- }
164
- for (const c of agent2.cases ?? []) {
165
- const mark = c.passed ? green("\u2714") : red("\u2716");
166
- lines.push(` ${mark} ${c.name}`);
167
- if (!c.passed) for (const f of c.failures ?? []) lines.push(` ${dim(f)}`);
168
- }
169
- }
170
- const passed = result.passed ?? 0;
171
- const failed = result.failed ?? 0;
172
- const mode = result.live ? " (LLM real)" : "";
173
- lines.push("");
174
- lines.push(`${bold("Evals:")} ${green(`${passed} pasaron`)}, ${failed ? red(`${failed} fallaron`) : `${failed} fallaron`}${mode}`);
175
- return lines.join("\n");
176
- }
177
157
 
178
158
  // src/codegen.ts
179
159
  async function codegen(args) {
@@ -217,8 +197,8 @@ async function codegen(args) {
217
197
  }
218
198
 
219
199
  // src/commands.ts
220
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
221
- import { join as join3, resolve as resolve2 } from "path";
200
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
201
+ import { join as join4, resolve as resolve2 } from "path";
222
202
  import { createInterface } from "readline";
223
203
 
224
204
  // src/api.ts
@@ -294,23 +274,6 @@ async function putManifest(api, manifest, options) {
294
274
  }
295
275
  throw new Error(formatApiError(response.status, body));
296
276
  }
297
- async function runEvals(api, manifest, options) {
298
- const { data, error, response } = await api.POST("/v1/account-config/eval", {
299
- params: { query: { live: options.live } },
300
- body: { config: { account: { kind: ACCOUNT_KIND, ...manifest } } }
301
- });
302
- if (response.ok && data) return { result: data.data };
303
- const body = error;
304
- if (response.status === 422) {
305
- const errors = body?.errors;
306
- if (errors) {
307
- return {
308
- failure: { detail: errors.detail ?? "el manifiesto no pas\xF3 validaci\xF3n", planErrors: errors.manifest ?? [] }
309
- };
310
- }
311
- }
312
- throw new Error(formatApiError(response.status, body));
313
- }
314
277
  function formatApiError(status, body) {
315
278
  const errors = body?.errors;
316
279
  if (errors && typeof errors === "object") {
@@ -329,24 +292,26 @@ function formatApiError(status, body) {
329
292
  function agentGuide(identity) {
330
293
  return `# Account as Code \u2014 ${identity.organization.name}
331
294
 
332
- Este directorio declara la configuraci\xF3n de la organizaci\xF3n como **archivos versionables**.
333
- T\xFA (el agente) editas los archivos; el CLI valida, muestra el diff y aplica:
295
+ Este proyecto declara la configuraci\xF3n de la organizaci\xF3n como **c\xF3digo TypeScript versionable**
296
+ (\`hablala.config.ts\`): un \`Account\` del SDK \`@hablala/schema/synth\` con sus objects, relationships,
297
+ policies, etc. T\xFA (el agente) editas el c\xF3digo; el CLI lo compila (\`synth()\`), valida, muestra el diff
298
+ y aplica:
334
299
 
335
300
  hablala plan # diff declarado vs. real \u2014 NUNCA toca nada
336
301
  hablala apply # reconcilia (crear / actualizar / archivar; jam\xE1s borrar)
337
- hablala pull # re-sincroniza los archivos con el estado real
338
- hablala pull --check # \xBFlos archivos siguen el estado real? (sale 1 si no; para CI)
302
+ hablala pull # re-genera hablala.config.ts con el estado real
303
+ hablala pull --check # \xBFel config sigue el estado real? (sale 1 si no; para CI)
339
304
 
340
305
  ## Runbook (SEGUIR SIEMPRE, en orden)
341
306
 
342
- La \xFAnica fuente de verdad es la organizaci\xF3n (la BD), no estos archivos: son una **proyecci\xF3n
343
- versionada** de ella, como un clon de git respecto al remoto. La UI, MCP y este manifiesto
344
- escriben todos al mismo lugar; estos archivos pueden quedar **atr\xE1s** si alguien cambi\xF3 la org
345
- por otra v\xEDa. Por eso, en CADA sesi\xF3n de trabajo:
307
+ La \xFAnica fuente de verdad es la organizaci\xF3n (la BD), no este archivo: es una **proyecci\xF3n
308
+ versionada** de ella, como un clon de git respecto al remoto. La UI, MCP y este config escriben
309
+ todos al mismo lugar; el archivo puede quedar **atr\xE1s** si alguien cambi\xF3 la org por otra v\xEDa. Por
310
+ eso, en CADA sesi\xF3n de trabajo:
346
311
 
347
- 1. hablala pull --check # \xBFmis archivos siguen la verdad? (drift inverso)
312
+ 1. hablala pull --check # \xBFmi config sigue la verdad? (drift inverso)
348
313
  2. hablala pull # SI hubo drift: re-sincroniza ANTES de tocar nada
349
- 3. \u2026edita los .yaml\u2026
314
+ 3. \u2026edita hablala.config.ts\u2026
350
315
  4. hablala plan # revisa el diff \u2014 vigila los archive/delete
351
316
  5. \u2026corrige conflictos y repite plan hasta que salga limpio\u2026
352
317
  6. hablala apply # aplica (pide confirmaci\xF3n; --yes en CI)
@@ -360,7 +325,7 @@ c\xF3digo 1 si hay drift, y es m\xE1s barato enterarte ah\xED que en un apply re
360
325
 
361
326
  **Red de seguridad autom\xE1tica (optimistic locking).** Adem\xE1s de la disciplina, el \`pull\` guarda
362
327
  en \`.hablala-version\` el \`lineage\` (el id de tu organizaci\xF3n) + la versi\xF3n del estado. Es estado
363
- **local por cuenta**, como el \`.tfstate\` de Terraform: **va en \`.gitignore\`, NO se versiona**
328
+ **local por cuenta**, como un archivo de estado local de infraestructura-como-c\xF3digo: **va en \`.gitignore\`, NO se versiona**
364
329
  (lleva el id de UNA org concreta; commitearlo romper\xEDa un clon apuntado a otra cuenta). Borrarlo es
365
330
  seguro \u2014 el siguiente \`pull\` lo regenera. El \`apply\` reenv\xEDa la versi\xF3n como precondici\xF3n: si la
366
331
  org cambi\xF3 desde tu \xFAltimo \`pull\` (UI, MCP, otro apply), el server RECHAZA el apply con un conflicto
@@ -372,74 +337,74 @@ AHORRA ese GET y ancla tu baseline a un \`pull\` concreto; su ausencia ya no es
372
337
 
373
338
  ## Estructura
374
339
 
375
- objects/<slug>.yaml # un objeto del modelo de datos por archivo
376
- policies/<slug>.yaml # una regla ABAC de acceso a datos por archivo
377
- webhooks/<slug>.yaml # un endpoint de webhook saliente por archivo
340
+ Todo vive en \`hablala.config.ts\`: importas el SDK, creas un \`Account\` y lo declaras con *constructs*
341
+ tipados. Un \`object(...)\` encadena sus \`field(...)\` y sus \`relationship(...)\` salientes
342
+ (el \`source\` lo inyecta el builder). \`export default\` el account; el CLI llama \`synth()\`.
343
+
344
+ import {
345
+ Account, text, number, select, multiselect, reference, file, formula, rollup,
346
+ } from "@hablala/schema/synth";
347
+
348
+ const account = new Account({ kind: "organization" });
349
+
350
+ account.object("producto", {
351
+ title: "Productos",
352
+ titleSingular: "Producto",
353
+ description: "Producto del cat\xE1logo, unidad serializada.",
354
+ synonyms: ["product", "item"],
355
+ })
356
+ .field("categoria", select({
357
+ description: "Categor\xEDa del producto.", // title impl\xEDcito: "Categoria" (del apiName)
358
+ isRequired: true,
359
+ options: ["A", "B", "C"],
360
+ }))
361
+ .field("sku", text({
362
+ title: "SKU", // title expl\xEDcito cuando el apiName no basta
363
+ description: "C\xF3digo \xFAnico.",
364
+ isUnique: true,
365
+ }))
366
+ .relationship("producto_reservations", {
367
+ target: "reservation",
368
+ cardinality: "one_to_many",
369
+ });
370
+
371
+ export default account;
378
372
 
379
373
  Reglas del manifiesto:
380
374
 
381
- - **Cada directorio es autoritativo**: lo que existe en la organizaci\xF3n y no est\xE1 declarado
382
- en archivos SE ARCHIVA al aplicar (\`plan\` siempre lo muestra antes). Borrar un archivo
383
- archiva esa entidad; nunca se destruye nada. **Excepci\xF3n: las policies se BORRAN** (no
384
- se archivan) \u2014 para una regla de acceso, quitarla del manifiesto debe significar que
385
- deja de aplicar. \`plan\` lo muestra como \`delete\`.
386
- - El \`slug\` del contenido es la identidad; el nombre de archivo es convenci\xF3n.
387
- - Las \`relationships\` van DENTRO del archivo de su objeto origen (\`source\` impl\xEDcito):
388
-
389
- # objects/producto.yaml
390
- slug: producto
391
- title: Productos
392
- titleSingular: Producto
393
- description: Producto del cat\xE1logo, unidad serializada.
394
- synonyms: [product, item]
395
- attributes:
396
- - slug: categoria
397
- description: Categor\xEDa del producto. # title impl\xEDcito: "Categoria" (del slug)
398
- dataType: select
399
- isRequired: true
400
- config: { options: [A, B, C] }
401
- - slug: sku
402
- title: SKU # title expl\xEDcito cuando el slug no basta
403
- description: C\xF3digo \xFAnico.
404
- dataType: text
405
- isUnique: true
406
- relationships:
407
- - slug: producto_reservations
408
- title: Reservas del producto
409
- description: Las reservas de este producto.
410
- target: reservation
411
- cardinality: one_to_many
412
-
413
- - \`description\` es obligatoria en todo (objetos, atributos, relationships): es el contexto
414
- con el que los agentes LLM de la plataforma descubren y operan cada cosa v\xEDa MCP.
415
- \`synonyms\` ayuda al mismo fin.
416
- - \`title\` es OPCIONAL: si lo omites se deriva del \`slug\` (\`precio_base\` \u2192 "Precio Base").
417
- En un object, \`titleSingular\` ausente cae al \`title\`. Decl\xE1ralos solo cuando el derivado
418
- no baste (siglas, may\xFAsculas especiales). \`description\` NUNCA se deriva: escr\xEDbela siempre.
419
- - **Secretos: NUNCA en el manifiesto.** El manifiesto vive en git (historial permanente,
420
- clones que viajan). No pongas tokens, API keys ni passwords en ning\xFAn \`.yaml\` \u2014 ni
421
- "temporalmente". Un secreto commiteado queda en el historial para siempre. Cuando una
422
- integraci\xF3n necesite una credencial externa (p. ej. el signing secret de un webhook), el
423
- server la genera o la guardas fuera del manifiesto; nunca inline en un \`.yaml\`.
424
- (Las credenciales del CLI ya viven fuera: \`~/.config/hablala\` o la variable
375
+ - **Cada secci\xF3n declarada es autoritativa**: lo que existe en la organizaci\xF3n y no est\xE1 declarado
376
+ SE ARCHIVA al aplicar (\`plan\` siempre lo muestra antes). Quitar un \`object(...)\` del config lo
377
+ archiva; nunca se destruye nada. **Excepci\xF3n: las policies se BORRAN** (no se archivan) \u2014 para una
378
+ regla de acceso, quitarla debe significar que deja de aplicar. \`plan\` lo muestra como \`delete\`.
379
+ - El \`apiName\` (primer argumento de \`object(...)\`) es la identidad.
380
+ - Las \`relationships\` se declaran con \`.relationship(...)\` sobre su object ORIGEN (el \`source\`
381
+ se inyecta solo); tambi\xE9n puedes declararlas a nivel de cuenta con \`account.relationship({...})\`.
382
+ - \`description\` es obligatoria en todo (objetos, campos, relationships): es el contexto con el que
383
+ los agentes LLM de la plataforma descubren y operan cada cosa v\xEDa MCP. \`synonyms\` ayuda al mismo fin.
384
+ - \`title\` es OPCIONAL: si lo omites se deriva del \`apiName\` (\`precio_base\` \u2192 "Precio Base"). En un
385
+ object, \`titleSingular\` ausente cae al \`title\`. Decl\xE1ralos solo cuando el derivado no baste
386
+ (siglas, may\xFAsculas especiales). \`description\` NUNCA se deriva: escr\xEDbela siempre.
387
+ - **Secretos: NUNCA en el config.** Vive en git (historial permanente, clones que viajan). No pongas
388
+ tokens, API keys ni passwords en \`hablala.config.ts\` \u2014 ni "temporalmente". Cuando una integraci\xF3n
389
+ necesite una credencial externa (p. ej. el signing secret de un webhook), el server la genera o la
390
+ guardas fuera del config. (Las credenciales del CLI viven en \`~/.config/hablala\` o en
425
391
  \`HABLALA_ACCESS_TOKEN\`.)
426
- - \`dataType\`: text | number | boolean | date | timestamp | select | multiselect |
427
- reference | file | formula | rollup. \`cardinality\`: one_to_one | one_to_many | many_to_many.
428
- Los dos \xFAltimos son DERIVADOS (se calculan al leer, no se almacenan): \`formula\` computa de
429
- otros campos del MISMO record (\`config: { expression: "subtotal + tax" }\`); \`rollup\` agrega
430
- campos de records RELACIONADOS (\`config: { relationship, aggregate: sum|count|avg|min|max, target }\`).
431
- No admiten \`isRequired\`/\`isIndexed\`/\`embedInVector\`.
432
- - **\`config\` por tipo** (el \`plan\` valida su forma; un error se atrapa antes de aplicar):
433
- - \`select\`/\`multiselect\`: \`config: { options: [...] }\` \u2014 OBLIGATORIO y no vac\xEDo.
434
- - \`number\`: \`config: { min, max }\` \u2014 num\xE9ricos y \`min <= max\` (ambos opcionales).
435
- - \`file\`: \`config: { maxCount, acceptedContentTypes }\` \u2014 \`maxCount\` entero positivo;
436
- \`acceptedContentTypes\` lista de mime (admite comodines: \`image/*\`).
437
- - \`reference\`: \`config: { targetObject: <slug> }\` \u2014 OPCIONAL; restringe la referencia a
438
- records de ese object (el \`plan\` valida que el object exista; al escribir, el motor
439
- rechaza un record de otro tipo). Sin \`targetObject\`, la referencia acepta cualquier record.
440
- - **Flags por tipo** (tambi\xE9n validados en el \`plan\`): \`isUnique\` no va en
441
- \`multiselect\`/\`boolean\`/\`file\`; un \`file\` no se indexa (\`isIndexed\`) ni se embebe
442
- (\`embedInVector\`). \`defaultValue\` es el sobre del valor (un objeto), no un escalar crudo.
392
+ - **Helpers de campo por \`data_type\`** \u2014 uno por tipo, cada uno tipa su config; el \`plan\` valida
393
+ adem\xE1s la forma (un error se atrapa antes de aplicar):
394
+ - \`text()\`, \`number({ min, max, decimals })\`, \`boolean()\`, \`date()\`, \`timestamp()\`.
395
+ - \`select({ options })\` / \`multiselect({ options })\` \u2014 \`options\` OBLIGATORIO y no vac\xEDo.
396
+ - \`reference({ targetObject })\` o \`reference({ relationship })\` \u2014 *linked record* vs *belongs_to*,
397
+ mutuamente excluyentes. El \`plan\` valida que el object/relationship exista.
398
+ - \`file({ maxCount, maxSizeBytes, acceptedContentTypes, visibility })\` \u2014 mime admite comodines
399
+ (\`image/*\`); \`visibility\` \u2208 public | private.
400
+ - \`formula({ expression, resultType })\` y \`rollup({ relationship, aggregate, target })\` son
401
+ DERIVADOS (se calculan al leer, no se almacenan): \`aggregate\` \u2208 sum | count | avg | min | max
402
+ (\`target\` obligatorio salvo \`count\`). No admiten flags de entrada/almacenamiento \u2014 el tipo del
403
+ helper lo impide.
404
+ - **Flags por tipo** (el helper + el \`plan\` los validan): \`isUnique\` no va en
405
+ \`multiselect\`/\`boolean\`/\`file\` ni derivados; un \`file\` no se indexa (\`isIndexed\`) ni se embebe
406
+ (\`embedInVector\`).
407
+ - \`cardinality\` (en \`.relationship\`): one_to_one | one_to_many | many_to_many.
443
408
 
444
409
  ## El \xE1rbol de decisi\xF3n: \xBFobjeto del motor o m\xF3dulo core?
445
410
 
@@ -472,20 +437,21 @@ es de sistema (proyecci\xF3n read-only): no lo declares.
472
437
  ## Policies (control de acceso ABAC)
473
438
 
474
439
  Una policy define QU\xC9 datos ve cada qui\xE9n. El motor es **default-deny**: sin una policy
475
- \`allow\`, un principal no ve nada de un objeto. Se identifican por \`slug\`.
476
-
477
- # policies/public_producto_publicado.yaml
478
- slug: public_producto_publicado
479
- effect: allow # allow | deny (deny gana)
480
- action: [read, update] # read | create | update | delete | signal \u2014 string o lista
481
- principal: public # qui\xE9n (ver abajo)
482
- object: producto # slug del object; OMITE la clave para "toda la organizaci\xF3n"
483
- condition: { attr: estado, op: eq, value: publicado } # predicado por fila (opcional)
484
- field_mask: [nombre, categoria, estado] # campos visibles (opcional)
485
-
486
- - \`action\` acepta **un string o una lista**: \`action: [read, update]\` concede ambas bajo
487
- el mismo slug (una policy declarada = N grants, uno por acci\xF3n). Quitar una acci\xF3n de la
488
- lista borra solo ese grant; \`pull\` re-colapsa las acciones de un slug en la lista.
440
+ \`allow\`, un principal no ve nada de un objeto. Se identifican por \`apiName\`.
441
+
442
+ account.policy({
443
+ apiName: "public_producto_publicado",
444
+ effect: "allow", // allow | deny (deny gana)
445
+ action: ["read", "update"], // read | create | update | delete | signal \u2014 string o lista
446
+ principal: "public", // qui\xE9n (ver abajo)
447
+ object: "producto", // apiName del object; OMITE la clave para "toda la organizaci\xF3n"
448
+ condition: { attr: "estado", op: "eq", value: "publicado" }, // predicado por fila (opcional)
449
+ fieldMask: ["nombre", "categoria", "estado"], // campos visibles (opcional)
450
+ });
451
+
452
+ - \`action\` acepta **un string o una lista**: \`["read", "update"]\` concede ambas bajo el mismo
453
+ apiName (una policy declarada = N grants, uno por acci\xF3n). Quitar una acci\xF3n de la lista borra solo ese
454
+ grant; \`pull\` re-colapsa las acciones de un apiName en la lista.
489
455
  - \`principal\` es una **referencia legible** (nunca un id): \`public\` (el canal
490
456
  p\xFAblico del frontend con API key), \`end_user\` (el usuario final con sesi\xF3n \`sess_\`),
491
457
  \`access_token\` (m\xE1quinas: CLI/CI/agentes con \`mat_\`) o \`role:<name>\` (un rol). Los
@@ -494,878 +460,182 @@ Una policy define QU\xC9 datos ve cada qui\xE9n. El motor es **default-deny**: s
494
460
  (\`mat_\`) se autoriza por su LISTA RBAC, no por el ABAC \u2014 sembrar y luego leer records con un
495
461
  \`mat_\` funciona SIN declarar policies. Las policies \`access_token\` son **opt-in para
496
462
  RESTRINGIRLO** (deny, \`condition\`, \`field_mask\`), no el requisito para habilitarlo.
497
- - \`object\` es el slug del object gobernado; el server resuelve la ref a su id al aplicar.
498
- - **Al quitar el archivo la policy se BORRA** (no se archiva): deja de conceder/negar.
463
+ - \`object\` es el apiName del object gobernado; el server resuelve la ref a su id al aplicar.
464
+ - **Al quitar la policy del config se BORRA** (no se archiva): deja de conceder/negar.
499
465
  \`plan\` lo muestra como \`delete\` \u2014 rev\xEDsalo, es un cambio de seguridad.
500
- - Los secretos NUNCA van en una policy (ni en ning\xFAn \`.yaml\`): ver la regla de secretos.
466
+ - Los secretos NUNCA van en una policy (ni en ning\xFAn lado del config): ver la regla de secretos.
501
467
 
502
- ### La \`condition\` (filtrado por fila) y el \`field_mask\` (por campo)
468
+ ### La \`condition\` (filtrado por fila) y el \`fieldMask\` (por campo)
503
469
 
504
470
  La \`condition\` es un predicado ABAC opcional: la policy solo aplica a las filas que lo
505
471
  satisfacen:
506
472
 
507
- condition: { attr: <slug>, op: <op>, value: <literal> } # una hoja
508
- condition: { and: [ <hoja>, <hoja>, \u2026 ] } # todas
509
- condition: { or: [ <hoja>, <hoja>, \u2026 ] } # alguna
473
+ condition: { attr: "<apiName>", op: "<op>", value: <literal> } // una hoja
474
+ condition: { and: [ <hoja>, <hoja>, \u2026 ] } // todas
475
+ condition: { or: [ <hoja>, <hoja>, \u2026 ] } // alguna
510
476
 
511
- - \`attr\` es un slug de atributo **del object gobernado**. \`op\` \u2208 \`eq\`, \`neq\`, \`gt\`,
477
+ - \`attr\` es un apiName de campo **del object gobernado**. \`op\` \u2208 \`eq\`, \`neq\`, \`gt\`,
512
478
  \`gte\`, \`lt\`, \`lte\`, \`in\`, \`contains\`, \`is_null\`, \`is_not_null\`. El operador debe
513
- ser compatible con el tipo del atributo (p. ej. \`gt\` no aplica a un \`select\`).
479
+ ser compatible con el tipo del campo (p. ej. \`gt\` no aplica a un \`select\`).
514
480
  - **ABAC din\xE1mico**: en vez de un \`value\` literal, una hoja puede comparar contra un
515
- atributo del solicitante con \`value_from: "principal.<attr>"\` \u2014 p. ej. "cada quien ve
481
+ campo del solicitante con \`value_from: "principal.<attr>"\` \u2014 p. ej. "cada quien ve
516
482
  solo las filas de su misma regi\xF3n":
517
483
 
518
- condition: { attr: region, op: eq, value_from: "principal.region" }
484
+ condition: { attr: "region", op: "eq", value_from: "principal.region" }
519
485
 
520
- - \`field_mask\` es la lista de slugs de atributo **visibles**; omitirla = todos los
486
+ - \`fieldMask\` es la lista de apiNames de campo **visibles**; omitirla = todos los
521
487
  permitidos. Con varias policies \`allow\`, la visibilidad es la intersecci\xF3n de sus masks.
522
488
  - Todo esto se **valida en el \`plan\`**: un \`attr\`/campo inexistente, un \`op\` desconocido
523
489
  o incompatible con el tipo es un conflicto que bloquea el apply (no un fallo silencioso
524
490
  en runtime). Corr\xEDgelo en tu loop antes de aplicar.
525
491
  `;
526
492
  }
527
- function hablalaYaml(identity, endpoint) {
528
- return `# Metadatos de la organizaci\xF3n (informativo \u2014 la identidad real sale del access token).
529
- # Generado por \`hablala init\`. Portable entre entornos: no versiona ids del server, solo
530
- # nombres/slugs legibles. Adem\xE1s, \`plan\`/\`apply\` leen \`modes\` (abajo) de este archivo.
531
- endpoint: ${endpoint}
532
- organization:
533
- name: ${JSON.stringify(identity.organization.name)}
534
- slug: ${identity.organization.slug}
535
-
536
- # Modo de reconciliaci\xF3n por secci\xF3n. Default (sin declarar): "authoritative" \u2014 lo no declarado
537
- # se archiva/borra (estado deseado completo). Ponlo en "additive" para A\xD1ADIR sin expulsar lo no
538
- # declarado (\xFAtil cuando declaras solo una parte del modelo; least astonishment). An\xE1logo al
539
- # server-side apply de Kubernetes: intenci\xF3n parcial, sin pruning.
540
- # modes:
541
- # objects: additive
542
- # relationships: additive
543
- `;
544
- }
545
- function gitignore() {
546
- return `# Credenciales y secretos \u2014 NUNCA en git (viven en ~/.config/hablala o en variables de entorno).
547
- credentials.json
548
- .env
549
- .env.*
550
- !.env.example
551
- *.local.yaml
552
- *.local.yml
553
-
554
- # Lockfile: estado local por cuenta (lineage/org id + versi\xF3n aplicada). Como el .tfstate de
555
- # Terraform, NO se versiona \u2014 lleva el id de UNA org; el siguiente pull lo regenera.
556
- .hablala-version
557
- `;
558
- }
559
493
 
560
- // src/manifest.ts
561
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
494
+ // src/config-module.ts
495
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync3 } from "fs";
562
496
  import { join as join2 } from "path";
563
- import { parse, parseDocument, stringify } from "yaml";
564
- var DATA_TYPES = [
565
- "text",
566
- "number",
567
- "boolean",
568
- "date",
569
- "timestamp",
570
- "select",
571
- "multiselect",
572
- "reference",
573
- "file",
574
- "formula",
575
- "rollup"
576
- ];
577
- var CARDINALITIES = ["one_to_one", "one_to_many", "many_to_many"];
578
- var AUTHORITY_SOURCES = ["delegated", "assigned"];
579
- var POLICY_EFFECTS = ["allow", "deny"];
580
- var POLICY_ACTIONS = ["read", "create", "update", "delete", "signal"];
581
- var WEBHOOK_EVENTS = [
582
- "record.created",
583
- "record.updated",
584
- "record.deleted",
585
- "record.restored",
586
- "edge.created",
587
- "edge.deleted"
588
- ];
589
- var WEBHOOK_STATUSES = ["enabled", "disabled"];
590
- var OBJECT_KEYS = withSnake([
591
- "slug",
592
- "title",
593
- "titleSingular",
594
- "description",
595
- "synonyms",
596
- "config",
597
- // Primary field: el slug del attribute que titula un record. Opcional.
598
- "titleAttributeSlug",
599
- // Señal read-only que emite `pull` (tenant/seeded/system): la aceptamos para que re-aplicar un
600
- // manifiesto recién exportado no falle como "clave desconocida". El server la ignora en el diff.
601
- "manageability",
602
- // Señal read-only que emite `pull` (core/commerce/crm…): a qué vertical instalable pertenece el
603
- // object. Se acepta por el mismo motivo que `manageability`; un package se instala declarándolo en
604
- // `packages:` (no marcando esta clave). El server la ignora en el diff.
605
- "package",
606
- "attributes",
607
- "relationships",
608
- // REFERENCE DATA del object (sección `reference:`): los records de configuración/clasificación que
609
- // `apply` reconcilia (managed/desired-state, por clave de negocio; ver Config.Resources.ReferenceData
610
- // en el server). El manifiesto es la fuente de verdad. El server NO los re-deriva en `pull` (no
611
- // distingue config de data de negocio), así que el pull PRESERVA la `reference` local (es del autor,
612
- // como un .tf que no se regenera desde el estado). Ejemplos: un `setting`, un catálogo de colores.
613
- "reference"
614
- ]);
615
- var ATTRIBUTE_KEYS = withSnake([
616
- "slug",
617
- "title",
618
- "description",
619
- "synonyms",
620
- "dataType",
621
- "isRequired",
622
- "isUnique",
623
- "isIndexed",
624
- "defaultValue",
625
- "config",
626
- "embedInVector"
627
- ]);
628
- var RELATIONSHIP_KEYS = withSnake([
629
- "slug",
630
- "title",
631
- "description",
632
- "source",
633
- "target",
634
- "cardinality"
635
- ]);
636
- var WORKFLOW_KEYS = withSnake([
637
- "slug",
638
- "title",
639
- "description",
640
- "synonyms",
641
- "trigger",
642
- "initialState",
643
- "states"
644
- ]);
645
- var AGENT_KEYS = withSnake([
646
- "handle",
647
- "name",
648
- "description",
649
- "systemPrompt",
650
- "provider",
651
- "model",
652
- "authoritySource",
653
- "allowedActivities",
654
- "agentPermissions",
655
- "handoffs",
656
- "approvalRequired",
657
- "evals",
658
- "ownerUserId"
659
- ]);
660
- var POLICY_KEYS = withSnake([
661
- "slug",
662
- "effect",
663
- "action",
664
- "principal",
665
- "object",
666
- "condition",
667
- "fieldMask"
668
- ]);
669
- var ROLE_KEYS = withSnake(["name", "permissions"]);
670
- var ACTION_KEYS = withSnake(["slug", "title", "description", "synonyms", "steps"]);
671
- var WEBHOOK_KEYS = withSnake(["slug", "url", "enabledEvents", "status"]);
672
- function withSnake(keys) {
673
- const snake = keys.map((key) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
674
- return /* @__PURE__ */ new Set([...keys, ...snake]);
675
- }
676
- var STRUCTURE_KEY_CAMEL = (() => {
677
- const map = /* @__PURE__ */ new Map();
678
- const camelKeys = [
679
- "titleSingular",
680
- "titleAttributeSlug",
681
- "dataType",
682
- "isRequired",
683
- "isUnique",
684
- "isIndexed",
685
- "defaultValue",
686
- "embedInVector",
687
- "enabledEvents",
688
- "endUserObjectSlug",
689
- "settingsObjectSlug",
690
- "fieldMask"
691
- // OJO: `value_from` NO va aquí. Es una clave de DOMINIO dentro de `condition` (junto a
692
- // `attr`/`op`/`value`): el server la exporta snake_case sin renombrar. Meterla aquí haría
693
- // que `canonicalize` reescribiera el `value_from` local a `valueFrom` y `--check` reportara
694
- // drift falso contra el export (que sigue en snake). Verificado contra el account-config del
695
- // server. La regla: solo claves de ESTRUCTURA (top-level de entidad) se normalizan.
696
- ];
697
- for (const camel of camelKeys) {
698
- map.set(camel.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`), camel);
699
- }
700
- return map;
701
- })();
702
- function canonicalKey(key) {
703
- return STRUCTURE_KEY_CAMEL.get(key) ?? key;
704
- }
705
- var DRIFT_IGNORED_KEYS = /* @__PURE__ */ new Set(["manageability", "package"]);
706
- function canonicalize(value) {
707
- if (Array.isArray(value)) return value.map(canonicalize);
708
- if (value && typeof value === "object") {
709
- const cleaned = clean(value);
710
- const out3 = {};
711
- for (const key of Object.keys(cleaned).sort()) {
712
- if (DRIFT_IGNORED_KEYS.has(canonicalKey(key))) continue;
713
- out3[canonicalKey(key)] = canonicalize(cleaned[key]);
714
- }
715
- return out3;
716
- }
717
- return value;
718
- }
719
- function localMatchesServer(local, server) {
720
- return subsetMatch(canonicalize(local), canonicalize(server));
721
- }
722
- function subsetMatch(local, server) {
723
- if (Array.isArray(local) || Array.isArray(server)) {
724
- if (!Array.isArray(local) || !Array.isArray(server)) return false;
725
- if (local.length !== server.length) return false;
726
- const idKey = entityIdKey(local[0]) ?? entityIdKey(server[0]);
727
- if (idKey) {
728
- const serverById = new Map(
729
- server.map((item) => [item?.[idKey], item])
730
- );
731
- return local.every((item) => {
732
- const id = item?.[idKey];
733
- return serverById.has(id) && subsetMatch(item, serverById.get(id));
734
- });
735
- }
736
- if (local.every(isPrimitive) && server.every(isPrimitive)) {
737
- const bag = (xs) => xs.map((x) => JSON.stringify(x)).sort().join("\0");
738
- return bag(local) === bag(server);
739
- }
740
- return local.every((item, i) => subsetMatch(item, server[i]));
741
- }
742
- if (local && server && typeof local === "object" && typeof server === "object") {
743
- return Object.entries(local).every(
744
- ([key, value]) => key === "reference" || subsetMatch(value, server[key])
745
- );
746
- }
747
- return JSON.stringify(local) === JSON.stringify(server);
748
- }
749
- function isPrimitive(value) {
750
- return value === null || typeof value !== "object" && typeof value !== "function";
751
- }
752
- function entityIdKey(item) {
753
- if (!item || typeof item !== "object" || Array.isArray(item)) return null;
754
- const obj = item;
755
- for (const key of ["slug", "handle", "name"]) {
756
- if (typeof obj[key] === "string") return key;
497
+ import { pathToFileURL } from "url";
498
+ import { build } from "esbuild";
499
+ var CONFIG_FILENAMES = ["hablala.config.ts", "hablala.config.mts", "hablala.config.js", "hablala.config.mjs"];
500
+ async function loadConfig(dir) {
501
+ const entry = resolveEntry(dir);
502
+ if (!entry) {
503
+ return {
504
+ manifest: {},
505
+ problems: [
506
+ `No se encontr\xF3 ${CONFIG_FILENAMES[0]} en ${dir}. Corre \`hablala init\` para generarlo.`
507
+ ]
508
+ };
757
509
  }
758
- return null;
759
- }
760
- function safeParse(text) {
510
+ let account;
761
511
  try {
762
- return parse(text);
763
- } catch {
764
- return void 0;
765
- }
766
- }
767
- var SECTION_MODES = ["authoritative", "additive"];
768
- function readModes(dir, problems) {
769
- const modes = {};
770
- const file = join2(dir, "hablala.yaml");
771
- if (!existsSync2(file)) return modes;
772
- const doc = parse(readFileSync2(file, "utf8"));
773
- const declared = doc?.modes;
774
- if (!declared || typeof declared !== "object") return modes;
775
- for (const [section, mode] of Object.entries(declared)) {
776
- if (typeof mode === "string" && SECTION_MODES.includes(mode)) {
777
- modes[section] = mode;
778
- } else {
779
- problems.push(
780
- `hablala.yaml: modes.${section} inv\xE1lido "${String(mode)}" (usa ${SECTION_MODES.join(" | ")})`
781
- );
782
- }
783
- }
784
- return modes;
785
- }
786
- var SETTINGS_KEYS = /* @__PURE__ */ new Set([
787
- "endUserObjectSlug",
788
- "end_user_object_slug",
789
- "settingsObjectSlug",
790
- "settings_object_slug"
791
- ]);
792
- function readSettings(dir, problems) {
793
- const file = join2(dir, "hablala.yaml");
794
- if (!existsSync2(file)) return void 0;
795
- const doc = parse(readFileSync2(file, "utf8"));
796
- const declared = doc?.settings;
797
- if (declared === void 0 || declared === null) return void 0;
798
- if (typeof declared !== "object" || Array.isArray(declared)) {
799
- problems.push("hablala.yaml: settings debe ser un objeto (singleton, no una lista)");
800
- return void 0;
512
+ account = await importAccount(entry, dir);
513
+ } catch (error) {
514
+ return { manifest: {}, problems: [messageOf(error)] };
801
515
  }
802
- const settings = declared;
803
- const unknown = Object.keys(settings).filter((key) => !SETTINGS_KEYS.has(key));
804
- if (unknown.length > 0) {
805
- problems.push(`hablala.yaml: settings tiene claves desconocidas: ${unknown.join(", ")} (\xBFtypo?)`);
516
+ try {
517
+ const manifest = account.synth();
518
+ return { manifest, modes: readModes(account), problems: [] };
519
+ } catch (error) {
520
+ return { manifest: {}, problems: [messageOf(error)] };
806
521
  }
807
- return settings;
808
522
  }
809
- function readPackages(dir, problems) {
810
- const file = join2(dir, "hablala.yaml");
811
- if (!existsSync2(file)) return void 0;
812
- const doc = parse(readFileSync2(file, "utf8"));
813
- const declared = doc?.packages;
814
- if (declared === void 0 || declared === null) return void 0;
815
- if (!Array.isArray(declared)) {
816
- problems.push("hablala.yaml: packages debe ser una lista de nombres (p. ej. [commerce, crm])");
817
- return void 0;
818
- }
819
- const packages = [];
820
- for (const entry of declared) {
821
- if (typeof entry === "string" && entry.trim() !== "") {
822
- packages.push(entry);
823
- } else {
824
- problems.push(`hablala.yaml: packages tiene una entrada inv\xE1lida "${String(entry)}" (usa nombres de package)`);
825
- }
523
+ function resolveEntry(dir) {
524
+ for (const name of CONFIG_FILENAMES) {
525
+ const path = join2(dir, name);
526
+ if (existsSync2(path)) return path;
826
527
  }
827
- return packages;
528
+ return void 0;
828
529
  }
829
- function readManifest(dir) {
830
- const problems = [];
831
- const modes = readModes(dir, problems);
832
- const manifest = {};
833
- const settings = readSettings(dir, problems);
834
- if (settings) manifest.settings = settings;
835
- const packages = readPackages(dir, problems);
836
- if (packages) manifest.packages = packages;
837
- const objectsDir = join2(dir, "objects");
838
- if (existsSync2(objectsDir)) {
839
- const objects = [];
840
- const relationships = [];
841
- for (const { file, content } of readYamlDir(objectsDir, problems)) {
842
- const { relationships: embedded, ...object } = content;
843
- validateEntity(object, "slug", OBJECT_KEYS, `objects/${file}`, problems);
844
- for (const attribute of asList(object.attributes)) {
845
- validateEntity(attribute, "slug", ATTRIBUTE_KEYS, `objects/${file} (attribute)`, problems);
846
- validateEnum(
847
- attribute,
848
- ["dataType", "data_type"],
849
- DATA_TYPES,
850
- `objects/${file}`,
851
- problems
852
- );
853
- validateAttributeRules(attribute, `objects/${file} (attribute)`, problems);
854
- }
855
- const relationshipSlugs = /* @__PURE__ */ new Set();
856
- for (const relationship of asList(embedded)) {
857
- const declared = relationship;
858
- const withSource = {
859
- ...declared,
860
- source: declared.source ?? object.slug
861
- };
862
- validateEntity(
863
- withSource,
864
- "slug",
865
- RELATIONSHIP_KEYS,
866
- `objects/${file} (relationship)`,
867
- problems
868
- );
869
- validateEnum(withSource, ["cardinality"], CARDINALITIES, `objects/${file}`, problems);
870
- if (!withSource.target)
871
- problems.push(
872
- `objects/${file}: la relationship "${withSource.slug}" no declara "target"`
873
- );
874
- if (typeof withSource.slug === "string") relationshipSlugs.add(withSource.slug);
875
- relationships.push(withSource);
876
- }
877
- const attributeSlugs = new Set(
878
- asList(object.attributes).map((a) => a.slug).filter((s) => typeof s === "string")
879
- );
880
- validateLayout(object.config, attributeSlugs, relationshipSlugs, `objects/${file}`, problems);
881
- objects.push(object);
882
- }
883
- manifest.objects = objects;
884
- manifest.relationships = relationships;
885
- }
886
- const workflowsDir = join2(dir, "workflows");
887
- if (existsSync2(workflowsDir)) {
888
- manifest.workflows = readYamlDir(workflowsDir, problems).map(({ file, content }) => {
889
- validateEntity(content, "slug", WORKFLOW_KEYS, `workflows/${file}`, problems);
890
- return content;
530
+ async function importAccount(entry, dir) {
531
+ const workDir = join2(dir, ".hablala");
532
+ mkdirSync2(workDir, { recursive: true });
533
+ const outfile = join2(workDir, `config.${process.pid}.${buildCounter++}.mjs`);
534
+ try {
535
+ await build({
536
+ entryPoints: [entry],
537
+ outfile,
538
+ bundle: true,
539
+ platform: "node",
540
+ format: "esm",
541
+ packages: "external",
542
+ logLevel: "silent"
891
543
  });
892
- }
893
- const agentsDir = join2(dir, "agents");
894
- if (existsSync2(agentsDir)) {
895
- manifest.agents = readYamlDir(agentsDir, problems).map(({ file, content }) => {
896
- validateEntity(content, "handle", AGENT_KEYS, `agents/${file}`, problems);
897
- validateEnum(
898
- content,
899
- ["authoritySource", "authority_source"],
900
- AUTHORITY_SOURCES,
901
- `agents/${file}`,
902
- problems
544
+ const mod = await import(pathToFileURL(outfile).href);
545
+ const candidate = mod.default ?? mod.account;
546
+ if (!candidate || typeof candidate.synth !== "function") {
547
+ throw new Error(
548
+ `${entry} debe exportar un \`Account\` (export default new Account(...)). No se encontr\xF3 uno.`
903
549
  );
904
- validateStringList(content, ["allowedActivities", "allowed_activities"], `agents/${file}`, problems);
905
- validateStringList(content, ["agentPermissions", "agent_permissions"], `agents/${file}`, problems);
906
- validateStringList(content, ["handoffs"], `agents/${file}`, problems);
907
- validateStringList(content, ["approvalRequired", "approval_required"], `agents/${file}`, problems);
908
- validateEvals(content.evals, `agents/${file}`, problems);
909
- return content;
910
- });
911
- }
912
- const policiesDir = join2(dir, "policies");
913
- if (existsSync2(policiesDir)) {
914
- manifest.policies = readYamlDir(policiesDir, problems).map(({ file, content }) => {
915
- validateEntity(content, "slug", POLICY_KEYS, `policies/${file}`, problems);
916
- validateEnum(content, ["effect"], POLICY_EFFECTS, `policies/${file}`, problems);
917
- validateEnumOrList(content, "action", POLICY_ACTIONS, `policies/${file}`, problems);
918
- return content;
919
- });
920
- }
921
- const rolesDir = join2(dir, "roles");
922
- if (existsSync2(rolesDir)) {
923
- manifest.roles = readYamlDir(rolesDir, problems).map(({ file, content }) => {
924
- validateEntity(content, "name", ROLE_KEYS, `roles/${file}`, problems);
925
- return content;
926
- });
927
- }
928
- const actionsDir = join2(dir, "actions");
929
- if (existsSync2(actionsDir)) {
930
- manifest.actions = readYamlDir(actionsDir, problems).map(({ file, content }) => {
931
- validateEntity(content, "slug", ACTION_KEYS, `actions/${file}`, problems);
932
- if (!Array.isArray(content.steps) || content.steps.length === 0)
933
- problems.push(`actions/${file}: "steps" debe ser una lista no vac\xEDa`);
934
- return content;
935
- });
936
- }
937
- const webhooksDir = join2(dir, "webhooks");
938
- if (existsSync2(webhooksDir)) {
939
- manifest.webhooks = readYamlDir(webhooksDir, problems).map(({ file, content }) => {
940
- validateEntity(content, "slug", WEBHOOK_KEYS, `webhooks/${file}`, problems);
941
- validateEnum(content, ["status"], WEBHOOK_STATUSES, `webhooks/${file}`, problems);
942
- validateEnumOrList(content, "enabled_events", WEBHOOK_EVENTS, `webhooks/${file}`, problems);
943
- validateEnumOrList(content, "enabledEvents", WEBHOOK_EVENTS, `webhooks/${file}`, problems);
944
- return content;
945
- });
946
- }
947
- return { manifest, modes, problems };
948
- }
949
- function writeManifest(dir, manifest, options = {}) {
950
- const written = [];
951
- const stale = [];
952
- const pruned = [];
953
- const drift = [];
954
- const objects = manifest.objects ?? [];
955
- const relationships = manifest.relationships ?? [];
956
- const bySource = /* @__PURE__ */ new Map();
957
- for (const relationship of relationships) {
958
- const list = bySource.get(relationship.source) ?? [];
959
- const rest = { ...relationship };
960
- delete rest.source;
961
- list.push(rest);
962
- bySource.set(relationship.source, list);
963
- }
964
- const shared = {
965
- written,
966
- stale,
967
- pruned,
968
- drift,
969
- prune: options.prune ?? false,
970
- check: options.check ?? false
971
- };
972
- const localReference = readLocalReference(join2(dir, "objects"));
973
- syncDir(
974
- join2(dir, "objects"),
975
- objects.map((object) => {
976
- const embedded = bySource.get(object.slug);
977
- const reference = localReference.get(object.slug);
978
- const withEmbedded = embedded ? { ...object, relationships: embedded } : { ...object };
979
- return {
980
- id: object.slug,
981
- content: clean(reference ? { ...withEmbedded, reference } : withEmbedded)
982
- };
983
- }),
984
- "slug",
985
- { ...shared, base: "objects", banner: objectBanner }
986
- );
987
- syncDir(
988
- join2(dir, "workflows"),
989
- (manifest.workflows ?? []).map((workflow) => ({
990
- id: workflow.slug,
991
- content: clean({ ...workflow })
992
- })),
993
- "slug",
994
- { ...shared, base: "workflows" }
995
- );
996
- syncDir(
997
- join2(dir, "agents"),
998
- (manifest.agents ?? []).map((agent2) => ({ id: agent2.handle, content: clean({ ...agent2 }) })),
999
- "handle",
1000
- { ...shared, base: "agents" }
1001
- );
1002
- syncDir(
1003
- join2(dir, "policies"),
1004
- (manifest.policies ?? []).map((policy) => ({ id: policy.slug, content: clean({ ...policy }) })),
1005
- "slug",
1006
- { ...shared, base: "policies" }
1007
- );
1008
- syncDir(
1009
- join2(dir, "roles"),
1010
- (manifest.roles ?? []).map((role) => ({ id: role.name, content: clean({ ...role }) })),
1011
- "name",
1012
- { ...shared, base: "roles" }
1013
- );
1014
- syncDir(
1015
- join2(dir, "actions"),
1016
- // keepEmptyObjects: un `invoice: {}` en un step es el discriminador del tipo, no ruido.
1017
- (manifest.actions ?? []).map((action) => ({
1018
- id: action.slug,
1019
- content: clean({ ...action }, { keepEmptyObjects: true })
1020
- })),
1021
- "slug",
1022
- { ...shared, base: "actions" }
1023
- );
1024
- syncDir(
1025
- join2(dir, "webhooks"),
1026
- (manifest.webhooks ?? []).map((webhook) => ({
1027
- id: webhook.slug,
1028
- content: clean({ ...webhook })
1029
- })),
1030
- "slug",
1031
- { ...shared, base: "webhooks" }
1032
- );
1033
- syncSettings(dir, manifest.settings, shared);
1034
- return { written, stale, pruned, drift };
1035
- }
1036
- function syncSettings(dir, settings, out3) {
1037
- const file = join2(dir, "hablala.yaml");
1038
- if (!existsSync2(file) && (!settings || Object.keys(settings).length === 0)) return;
1039
- const doc = existsSync2(file) ? parseDocument(readFileSync2(file, "utf8")) : parseDocument("");
1040
- const current = doc.get("settings");
1041
- const currentJson = current ? JSON.stringify(doc.toJS().settings) : null;
1042
- const desiredJson = settings && Object.keys(settings).length > 0 ? JSON.stringify(settings) : null;
1043
- if (currentJson === desiredJson) return;
1044
- if (out3.check) {
1045
- out3.drift.push("hablala.yaml");
1046
- return;
1047
- }
1048
- if (desiredJson === null) doc.delete("settings");
1049
- else doc.set("settings", settings);
1050
- writeFileSync3(file, doc.toString(), "utf8");
1051
- out3.written.push("hablala.yaml");
1052
- }
1053
- function objectBanner(content) {
1054
- const level = content.manageability;
1055
- if (level === "seeded") {
1056
- 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";
1057
- }
1058
- if (level === "system") {
1059
- 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";
1060
- }
1061
- return "";
1062
- }
1063
- function syncDir(dirPath, entities, idKey, out3) {
1064
- if (!out3.check) mkdirSync2(dirPath, { recursive: true });
1065
- else if (!existsSync2(dirPath)) {
1066
- for (const { id } of entities) out3.drift.push(`${out3.base}/${id}.yaml`);
1067
- return;
1068
- }
1069
- const fileById = /* @__PURE__ */ new Map();
1070
- for (const file of yamlFiles(dirPath)) {
1071
- try {
1072
- const content = parse(readFileSync2(join2(dirPath, file), "utf8"));
1073
- const id = content?.[idKey];
1074
- if (typeof id === "string") fileById.set(id, file);
1075
- } catch {
1076
- }
1077
- }
1078
- const writtenFiles = /* @__PURE__ */ new Set();
1079
- for (const { id, content } of entities) {
1080
- const file = fileById.get(id) ?? `${id}.yaml`;
1081
- const serialized = (out3.banner?.(content) ?? "") + stringify(content);
1082
- if (out3.check) {
1083
- const path = join2(dirPath, file);
1084
- const local = existsSync2(path) ? safeParse(readFileSync2(path, "utf8")) : void 0;
1085
- if (local === void 0 || !localMatchesServer(local, content)) {
1086
- out3.drift.push(`${out3.base}/${file}`);
1087
- }
1088
- } else {
1089
- writeFileSync3(join2(dirPath, file), serialized, "utf8");
1090
- out3.written.push(`${out3.base}/${file}`);
1091
- }
1092
- writtenFiles.add(file);
1093
- }
1094
- for (const file of yamlFiles(dirPath)) {
1095
- if (writtenFiles.has(file)) continue;
1096
- if (out3.check) {
1097
- out3.drift.push(`${out3.base}/${file}`);
1098
- } else if (out3.prune) {
1099
- rmSync(join2(dirPath, file));
1100
- out3.pruned.push(`${out3.base}/${file}`);
1101
- } else {
1102
- out3.stale.push(`${out3.base}/${file}`);
1103
550
  }
551
+ return candidate;
552
+ } finally {
553
+ rmSync(outfile, { force: true });
554
+ rmSync(`${outfile}.map`, { force: true });
1104
555
  }
1105
556
  }
1106
- function readLocalReference(dirPath) {
1107
- const reference = /* @__PURE__ */ new Map();
1108
- if (!existsSync2(dirPath)) return reference;
1109
- for (const file of yamlFiles(dirPath)) {
1110
- try {
1111
- const content = parse(readFileSync2(join2(dirPath, file), "utf8"));
1112
- const slug = content?.slug;
1113
- if (typeof slug === "string" && content?.reference !== void 0) {
1114
- reference.set(slug, content.reference);
1115
- }
1116
- } catch {
1117
- }
1118
- }
1119
- return reference;
1120
- }
1121
- function readYamlDir(dirPath, problems) {
1122
- const entries = [];
1123
- for (const file of yamlFiles(dirPath)) {
1124
- let content;
1125
- try {
1126
- content = parse(readFileSync2(join2(dirPath, file), "utf8"));
1127
- } catch (error) {
1128
- problems.push(
1129
- `${file}: YAML inv\xE1lido \u2014 ${error instanceof Error ? error.message : String(error)}`
1130
- );
1131
- continue;
1132
- }
1133
- if (content === null || content === void 0) continue;
1134
- if (typeof content !== "object" || Array.isArray(content)) {
1135
- problems.push(`${file}: debe ser un mapa YAML (una entidad por archivo)`);
1136
- continue;
1137
- }
1138
- entries.push({ file, content });
1139
- }
1140
- return entries.sort((a, b) => a.file.localeCompare(b.file));
1141
- }
1142
- function yamlFiles(dirPath) {
1143
- return readdirSync(dirPath).filter((file) => file.endsWith(".yaml") || file.endsWith(".yml")).sort();
1144
- }
1145
- function validateEntity(entity, idKey, knownKeys, where, problems) {
1146
- const id = entity[idKey];
1147
- if (typeof id !== "string" || id === "") {
1148
- problems.push(`${where}: falta "${idKey}" (el identificador estable de la entidad)`);
1149
- }
1150
- const unknown = Object.keys(entity).filter((key) => !knownKeys.has(key));
1151
- if (unknown.length > 0) {
1152
- problems.push(`${where}: claves desconocidas: ${unknown.join(", ")} (\xBFtypo?)`);
1153
- }
557
+ var buildCounter = 0;
558
+ function readModes(account) {
559
+ return Object.keys(account.modes).length > 0 ? account.modes : void 0;
1154
560
  }
1155
- function validateEnum(entity, keys, allowed, where, problems) {
1156
- if (allowed.length === 0) return;
1157
- for (const key of keys) {
1158
- const value = entity[key];
1159
- if (typeof value === "string" && !allowed.includes(value)) {
1160
- problems.push(`${where}: "${key}: ${value}" no es v\xE1lido (valores: ${allowed.join(", ")})`);
1161
- }
1162
- }
561
+ function messageOf(error) {
562
+ return error instanceof Error ? error.message : String(error);
1163
563
  }
1164
- function validateEnumOrList(entity, key, allowed, where, problems) {
1165
- const value = entity[key];
1166
- if (value === void 0) return;
1167
- const values = Array.isArray(value) ? value : [value];
1168
- if (values.length === 0) {
1169
- problems.push(`${where}: "${key}" no puede ser una lista vac\xEDa`);
1170
- return;
1171
- }
1172
- for (const item of values) {
1173
- if (typeof item !== "string" || !allowed.includes(item)) {
1174
- problems.push(
1175
- `${where}: "${key}: ${String(item)}" no es v\xE1lido (valores: ${allowed.join(", ")})`
1176
- );
1177
- }
1178
- }
564
+ function writeConfigFile(dir, content, filename = CONFIG_FILENAMES[0]) {
565
+ writeFileSync3(join2(dir, filename), content, "utf8");
1179
566
  }
1180
- function validateStringList(entity, keys, where, problems) {
1181
- for (const key of keys) {
1182
- const value = entity[key];
1183
- if (value === void 0) continue;
1184
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
1185
- problems.push(`${where}: "${key}" debe ser una lista de slugs (strings)`);
1186
- }
1187
- }
567
+
568
+ // src/scaffold.ts
569
+ import { manifestToConfigSource } from "@hablala/schema/synth";
570
+ function configFile(manifest) {
571
+ return manifestToConfigSource(manifest);
1188
572
  }
1189
- var EVAL_ASSERTIONS = /* @__PURE__ */ new Set([
1190
- "tool",
1191
- "noTool",
1192
- "no_tool",
1193
- "handoff",
1194
- "requiresApproval",
1195
- "requires_approval",
1196
- "contains"
1197
- ]);
1198
- function validateEvals(evals, where, problems) {
1199
- if (evals === void 0) return;
1200
- if (!Array.isArray(evals)) {
1201
- problems.push(`${where}: "evals" debe ser una lista de casos de prueba`);
1202
- return;
1203
- }
1204
- for (const raw of evals) {
1205
- if (!raw || typeof raw !== "object") {
1206
- problems.push(`${where}: cada eval debe ser un mapa {name, input, expect}`);
1207
- continue;
1208
- }
1209
- const eval_ = raw;
1210
- if (typeof eval_.name !== "string" || eval_.name === "")
1211
- problems.push(`${where}: un eval declara un "name" no vac\xEDo`);
1212
- if (typeof eval_.input !== "string" || eval_.input === "")
1213
- problems.push(`${where}: el eval "${String(eval_.name)}" declara un "input" no vac\xEDo`);
1214
- const expect = eval_.expect;
1215
- if (expect !== void 0) {
1216
- if (!expect || typeof expect !== "object") {
1217
- problems.push(`${where}: el "expect" del eval "${String(eval_.name)}" debe ser un mapa`);
1218
- } else {
1219
- for (const key of Object.keys(expect)) {
1220
- if (!EVAL_ASSERTIONS.has(key))
1221
- problems.push(`${where}: el eval "${String(eval_.name)}" usa aserci\xF3n desconocida "${key}"`);
1222
- }
573
+ function projectPackageJson(identity) {
574
+ const name = identity.organization.slug || "hablala-account";
575
+ return `${JSON.stringify(
576
+ {
577
+ name: `${name}-config`,
578
+ private: true,
579
+ type: "module",
580
+ description: `Configuraci\xF3n (config as code) de ${identity.organization.name} en Hablal\xE1.`,
581
+ devDependencies: {
582
+ "@hablala/schema": "^0.1.0",
583
+ typescript: "^5.7.2"
1223
584
  }
1224
- }
1225
- }
1226
- }
1227
- var UNIQUE_INCOMPATIBLE = /* @__PURE__ */ new Set(["multiselect", "boolean", "file", "formula", "rollup"]);
1228
- var OPTIONS_TYPES = /* @__PURE__ */ new Set(["select", "multiselect"]);
1229
- var DERIVED_TYPES = /* @__PURE__ */ new Set(["formula", "rollup"]);
1230
- var ROLLUP_AGGREGATES = /* @__PURE__ */ new Set(["sum", "count", "avg", "min", "max"]);
1231
- function flag(attribute, camel, snake) {
1232
- return attribute[camel] === true || attribute[snake] === true;
1233
- }
1234
- function validateAttributeRules(attribute, where, problems) {
1235
- const dataType = attribute.dataType ?? attribute.data_type;
1236
- if (typeof dataType !== "string" || !DATA_TYPES.includes(dataType)) return;
1237
- if (flag(attribute, "isUnique", "is_unique") && UNIQUE_INCOMPATIBLE.has(dataType)) {
1238
- problems.push(`${where}: "isUnique" no es soportado para el tipo ${dataType}`);
1239
- }
1240
- if (dataType === "file") {
1241
- if (flag(attribute, "isIndexed", "is_indexed"))
1242
- problems.push(`${where}: "isIndexed" no es soportado para el tipo file`);
1243
- if (flag(attribute, "embedInVector", "embed_in_vector"))
1244
- problems.push(`${where}: "embedInVector" no es soportado para el tipo file`);
1245
- }
1246
- if (DERIVED_TYPES.has(dataType)) {
1247
- if (flag(attribute, "isIndexed", "is_indexed"))
1248
- problems.push(`${where}: "isIndexed" no es soportado para el tipo ${dataType} (derivado)`);
1249
- if (flag(attribute, "embedInVector", "embed_in_vector"))
1250
- problems.push(`${where}: "embedInVector" no es soportado para el tipo ${dataType} (derivado)`);
1251
- if (flag(attribute, "isRequired", "is_required"))
1252
- problems.push(`${where}: "isRequired" no es soportado para el tipo ${dataType} (derivado)`);
1253
- }
1254
- const config = attribute.config;
1255
- const cfg = config && typeof config === "object" ? config : {};
1256
- if (OPTIONS_TYPES.has(dataType)) {
1257
- const options = cfg.options;
1258
- if (!Array.isArray(options) || options.length === 0) {
1259
- problems.push(`${where}: el tipo ${dataType} requiere "config.options" (lista no vac\xEDa)`);
1260
- } else if (!options.every((o) => typeof o === "string" || o && typeof o === "object")) {
1261
- problems.push(`${where}: "config.options" debe ser una lista de strings (o de {value, label})`);
1262
- }
1263
- }
1264
- if (dataType === "number") {
1265
- const { min, max } = cfg;
1266
- if (min !== void 0 && typeof min !== "number")
1267
- problems.push(`${where}: "config.min" debe ser un n\xFAmero`);
1268
- if (max !== void 0 && typeof max !== "number")
1269
- problems.push(`${where}: "config.max" debe ser un n\xFAmero`);
1270
- if (typeof min === "number" && typeof max === "number" && min > max)
1271
- problems.push(`${where}: "config.min" no puede ser mayor que "config.max"`);
1272
- }
1273
- if (dataType === "file") {
1274
- const maxCount = cfg.max_count ?? cfg.maxCount;
1275
- if (maxCount !== void 0 && !(typeof maxCount === "number" && Number.isInteger(maxCount) && maxCount > 0))
1276
- problems.push(`${where}: "config.maxCount" debe ser un entero positivo`);
1277
- const accepted = cfg.accepted_content_types ?? cfg.acceptedContentTypes;
1278
- if (accepted !== void 0 && (!Array.isArray(accepted) || !accepted.every((t) => typeof t === "string")))
1279
- problems.push(`${where}: "config.acceptedContentTypes" debe ser una lista de strings (mime, admite comodines image/*)`);
1280
- }
1281
- if (dataType === "reference") {
1282
- const target = cfg.target_object ?? cfg.targetObject;
1283
- if (target !== void 0 && !(typeof target === "string" && target.length > 0))
1284
- problems.push(`${where}: "config.targetObject" debe ser un slug de object (string no vac\xEDo)`);
1285
- }
1286
- if (dataType === "formula") {
1287
- const expression = cfg.expression;
1288
- if (typeof expression !== "string" || expression.length === 0)
1289
- problems.push(`${where}: el tipo formula requiere "config.expression" (string no vac\xEDo)`);
1290
- }
1291
- if (dataType === "rollup") {
1292
- const relationship = cfg.relationship;
1293
- const aggregate = cfg.aggregate;
1294
- const target = cfg.target;
1295
- if (typeof relationship !== "string" || relationship.length === 0)
1296
- problems.push(`${where}: el tipo rollup requiere "config.relationship" (slug del relationship)`);
1297
- if (typeof aggregate !== "string" || !ROLLUP_AGGREGATES.has(aggregate))
1298
- problems.push(
1299
- `${where}: el tipo rollup requiere "config.aggregate" \u2208 ${[...ROLLUP_AGGREGATES].join("/")}`
1300
- );
1301
- if (aggregate !== "count" && (typeof target !== "string" || target.length === 0))
1302
- problems.push(`${where}: el rollup "${String(aggregate)}" requiere "config.target" (slug del atributo a agregar)`);
1303
- }
585
+ },
586
+ null,
587
+ 2
588
+ )}
589
+ `;
1304
590
  }
1305
- function validateLayout(config, attributeSlugs, relationshipSlugs, where, problems) {
1306
- if (!config || typeof config !== "object") return;
1307
- const layout = config.layout;
1308
- if (layout === void 0) return;
1309
- if (typeof layout !== "object" || layout === null) {
1310
- problems.push(`${where}: "config.layout" debe ser un objeto`);
1311
- return;
1312
- }
1313
- const l = layout;
1314
- if (l.highlights !== void 0) {
1315
- if (!Array.isArray(l.highlights)) {
1316
- problems.push(`${where}: "layout.highlights" debe ser una lista de slugs de attribute`);
1317
- } else {
1318
- for (const slug of l.highlights) {
1319
- if (typeof slug !== "string" || !attributeSlugs.has(slug))
1320
- problems.push(`${where}: "layout.highlights" referencia un attribute inexistente: "${String(slug)}"`);
1321
- }
1322
- }
1323
- }
1324
- if (l.sections !== void 0) {
1325
- if (!Array.isArray(l.sections)) {
1326
- problems.push(`${where}: "layout.sections" debe ser una lista de {title, fields}`);
1327
- } else {
1328
- for (const section of l.sections) {
1329
- const s = section;
1330
- if (typeof s?.title !== "string" || s.title.length === 0)
1331
- problems.push(`${where}: cada "layout.sections" requiere un "title" (string no vac\xEDo)`);
1332
- if (!Array.isArray(s?.fields)) {
1333
- problems.push(`${where}: "layout.sections[].fields" debe ser una lista de slugs de attribute`);
1334
- } else {
1335
- for (const slug of s.fields) {
1336
- if (typeof slug !== "string" || !attributeSlugs.has(slug))
1337
- problems.push(`${where}: "layout.sections" referencia un attribute inexistente: "${String(slug)}"`);
1338
- }
1339
- }
1340
- }
1341
- }
1342
- }
1343
- if (l.related !== void 0) {
1344
- if (!Array.isArray(l.related)) {
1345
- problems.push(`${where}: "layout.related" debe ser una lista de {relationship}`);
1346
- } else {
1347
- for (const item of l.related) {
1348
- const slug = item?.relationship;
1349
- if (typeof slug !== "string" || !relationshipSlugs.has(slug))
1350
- problems.push(`${where}: "layout.related" referencia un relationship inexistente: "${String(slug)}"`);
1351
- }
1352
- }
1353
- }
1354
- const groupBy = l.groupBy ?? l.group_by;
1355
- if (groupBy !== void 0 && (typeof groupBy !== "string" || !attributeSlugs.has(groupBy)))
1356
- problems.push(`${where}: "layout.groupBy" referencia un attribute inexistente: "${String(groupBy)}"`);
591
+ function projectTsconfig() {
592
+ return `${JSON.stringify(
593
+ {
594
+ compilerOptions: {
595
+ target: "ES2022",
596
+ module: "NodeNext",
597
+ moduleResolution: "NodeNext",
598
+ strict: true,
599
+ noEmit: true,
600
+ skipLibCheck: true
601
+ },
602
+ include: ["hablala.config.ts"]
603
+ },
604
+ null,
605
+ 2
606
+ )}
607
+ `;
1357
608
  }
1358
- function asList(value) {
1359
- return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : [];
609
+ function gitignore() {
610
+ return `# Credenciales y secretos \u2014 NUNCA en git (viven en ~/.config/hablala o en variables de entorno).
611
+ credentials.json
612
+ .env
613
+ .env.*
614
+ !.env.example
615
+
616
+ # Dependencias del proyecto de config.
617
+ node_modules/
618
+
619
+ # Artefactos transpilados del CLI al cargar hablala.config.ts (ef\xEDmeros).
620
+ .hablala/
621
+
622
+ # Lockfile: estado local por cuenta (lineage/org id + versi\xF3n aplicada). Como un archivo de estado
623
+ # local de infraestructura-como-c\xF3digo, NO se versiona \u2014 lleva el id de UNA org; el siguiente pull lo regenera.
624
+ .hablala-version
625
+ `;
1360
626
  }
627
+
628
+ // src/lock.ts
629
+ import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync4 } from "fs";
630
+ import { join as join3 } from "path";
1361
631
  var VERSION_FILE = ".hablala-version";
1362
632
  function writeLock(dir, lock) {
1363
- writeFileSync3(join2(dir, VERSION_FILE), `${JSON.stringify(lock, null, 2)}
633
+ writeFileSync4(join3(dir, VERSION_FILE), `${JSON.stringify(lock, null, 2)}
1364
634
  `, "utf8");
1365
635
  }
1366
636
  function readLock(dir) {
1367
- const path = join2(dir, VERSION_FILE);
1368
- if (!existsSync2(path)) return void 0;
637
+ const path = join3(dir, VERSION_FILE);
638
+ if (!existsSync3(path)) return void 0;
1369
639
  const raw = readFileSync2(path, "utf8").trim();
1370
640
  if (raw === "") return void 0;
1371
641
  if (raw.startsWith("{")) {
@@ -1380,26 +650,9 @@ function readLock(dir) {
1380
650
  }
1381
651
  return { version: raw };
1382
652
  }
1383
- function clean(value, opts = {}) {
1384
- const result = {};
1385
- for (const [key, entry] of Object.entries(value)) {
1386
- if (entry === null || entry === void 0) continue;
1387
- if (Array.isArray(entry)) {
1388
- if (entry.length === 0) continue;
1389
- result[key] = entry.map(
1390
- (item) => item && typeof item === "object" && !Array.isArray(item) ? clean(item, opts) : item
1391
- );
1392
- continue;
1393
- }
1394
- if (typeof entry === "object") {
1395
- if (!opts.keepEmptyObjects && Object.keys(entry).length === 0) continue;
1396
- result[key] = entry;
1397
- continue;
1398
- }
1399
- result[key] = entry;
1400
- }
1401
- return result;
1402
- }
653
+
654
+ // src/commands.ts
655
+ import { manifestsMatch } from "@hablala/schema/synth";
1403
656
 
1404
657
  // src/oauth.ts
1405
658
  import { spawn } from "child_process";
@@ -1624,7 +877,7 @@ function hablalaSkill() {
1624
877
  name: hablala
1625
878
  description: >-
1626
879
  Operar la plataforma Hablal\xE1: configurar una organizaci\xF3n con Account as Code
1627
- (hablala plan/apply sobre YAML), consumir su Public API con @hablala/client, generar
880
+ (hablala plan/apply sobre hablala.config.ts), consumir su Public API con @hablala/client, generar
1628
881
  una app con npm create @hablala/app, y manejar las credenciales pk_/sk_/mat_/sess_.
1629
882
  \xDAsala cuando el usuario pida modelar objects/policies, sembrar records, integrar el
1630
883
  SDK, o depurar un 401/403/lista vac\xEDa del canal p\xFAblico.
@@ -1633,14 +886,14 @@ description: >-
1633
886
  # Hablal\xE1 \u2014 c\xF3mo operar la plataforma
1634
887
 
1635
888
  Hablal\xE1 es una plataforma headless horizontal: la organizaci\xF3n declara su modelo de datos
1636
- (objects/attributes/relationships) y sus reglas de acceso (policies ABAC, **default-deny**),
889
+ (objects/fields/relationships) y sus reglas de acceso (policies ABAC, **default-deny**),
1637
890
  y cualquier app lo consume por la Public API.
1638
891
 
1639
892
  ## Qu\xE9 herramienta usar
1640
893
 
1641
894
  | Tarea | Herramienta |
1642
895
  |---|---|
1643
- | Configurar el modelo/policies/workflows/agents/webhooks | CLI \`hablala\` (Account as Code: \`plan\`/\`apply\` sobre YAML) |
896
+ | Configurar el modelo/policies/workflows/agents/webhooks | CLI \`hablala\` (Account as Code: \`plan\`/\`apply\` sobre \`hablala.config.ts\`) |
1644
897
  | Construir el modelo conversando, sin proyecto | MCP server \`@hablala/mcp\` (22 tools \`hablala_*\`) |
1645
898
  | Leer/escribir datos desde una app | SDK \`@hablala/client\` (canal p\xFAblico) |
1646
899
  | Generar una app cliente nueva | \`npm create @hablala/app@latest\` |
@@ -1654,7 +907,7 @@ y cualquier app lo consume por la Public API.
1654
907
  - \`sess_\` end-user session \u2014 el usuario final de la app; lo gestiona el SDK.
1655
908
 
1656
909
  Siempre por variables de entorno (\`HABLALA_ACCESS_TOKEN\` para el \`mat_\`), nunca en
1657
- flags, c\xF3digo ni YAML versionado.
910
+ flags, c\xF3digo ni en el config versionado.
1658
911
 
1659
912
  ## Arrancar de cero SIN cuenta (claimable organization)
1660
913
 
@@ -1674,14 +927,15 @@ en 72 h si nadie la reclama; el \`claimUrl\` dura 24 h y se renueva con
1674
927
 
1675
928
  ## Runbook Account as Code (en orden, siempre)
1676
929
 
1677
- 1. hablala pull --check # \xBFmis archivos siguen la verdad? (sale 1 si hay drift)
930
+ 1. hablala pull --check # \xBFmi config sigue la verdad? (sale 1 si hay drift)
1678
931
  2. hablala pull # si hubo drift, re-sincroniza ANTES de editar
1679
- 3. \u2026edita objects/*.yaml, policies/*.yaml\u2026
932
+ 3. \u2026edita hablala.config.ts (el SDK @hablala/schema/synth)\u2026
1680
933
  4. hablala plan # revisa el diff \u2014 vigila los archive/delete inesperados
1681
934
  5. hablala apply # aplica (pide confirmaci\xF3n; --yes en CI)
1682
935
 
1683
936
  \`apply\` es autoritativo por secci\xF3n: lo no declarado se archiva (objects) o se borra
1684
- (policies) \u2014 salvo \`modes: additive\` en \`hablala.yaml\`. \`plan\` nunca toca nada.
937
+ (policies) \u2014 salvo que la secci\xF3n se declare \`additive\` (\`account.mode("objects", "additive")\`).
938
+ \`plan\` nunca toca nada.
1685
939
 
1686
940
  ## Reglas que evitan los errores t\xEDpicos
1687
941
 
@@ -1692,17 +946,17 @@ en 72 h si nadie la reclama; el \`claimUrl\` dura 24 h y se renueva con
1692
946
  re-emite el token con ese preset; no inventes permisos.
1693
947
  - **422 \`type_mismatch\`**: el operador no es compatible con el \`data_type\`
1694
948
  (\`gt/gte/lt/lte\` solo number/date/timestamp; \`contains\` solo text/multiselect).
1695
- - **Referencias por clave de negocio**: un atributo \`reference\` acepta
1696
- \`{"$ref": {"sku": "\u2026"}}\` (cualquier atributo \`is_unique\` del destino) adem\xE1s del
949
+ - **Referencias por clave de negocio**: un campo \`reference\` acepta
950
+ \`{"$ref": {"sku": "\u2026"}}\` (cualquier campo \`is_unique\` del destino) adem\xE1s del
1697
951
  \`rec_\u2026\` \u2014 \xFAsalo al sembrar datos que vienen de un sistema externo.
1698
- - Filtrar/ordenar exige \`is_indexed: true\` en el atributo; la b\xFAsqueda sem\xE1ntica exige
952
+ - Filtrar/ordenar exige \`is_indexed: true\` en el campo; la b\xFAsqueda sem\xE1ntica exige
1699
953
  \`embed_in_vector: true\`.
1700
- - \`description\` y \`synonyms\` de objects/attributes no son relleno: la plataforma y los
954
+ - \`description\` y \`synonyms\` de objects/fields no son relleno: la plataforma y los
1701
955
  agentes razonan el dominio con ellos.
1702
956
  - **Webhooks salientes** (que un sistema externo reaccione sin polling): declara
1703
- \`webhooks/<slug>.yaml\` con \`url\` + \`enabled_events\` (\`record.created\`, \u2026). El signing
1704
- secret \`whsec_\` NO va en YAML: recup\xE9ralo con \`GET /v1/webhooks/:id/secret\` y verifica
1705
- cada entrega con la spec Standard Webhooks (headers \`webhook-id\`/\`-timestamp\`/\`-signature\`).
957
+ \`account.webhook({ slug, url, enabledEvents: ["record.created", \u2026] })\`. El signing secret
958
+ \`whsec_\` NO va en el config: recup\xE9ralo con \`GET /v1/webhooks/:id/secret\` y verifica cada
959
+ entrega con la spec Standard Webhooks (headers \`webhook-id\`/\`-timestamp\`/\`-signature\`).
1706
960
 
1707
961
  ## Referencia
1708
962
 
@@ -1725,7 +979,7 @@ var WRITE_PERMISSIONS = [
1725
979
  ];
1726
980
  var info = (message) => console.error(message);
1727
981
  var out = (message) => console.log(message);
1728
- function flag2(args, name) {
982
+ function flag(args, name) {
1729
983
  const value = args[name];
1730
984
  return typeof value === "string" ? value : void 0;
1731
985
  }
@@ -1736,8 +990,8 @@ function targetDir(args) {
1736
990
  return resolve2(process.cwd(), args._[1] ?? ".");
1737
991
  }
1738
992
  async function login(args) {
1739
- const endpoint = (flag2(args, "endpoint") ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
1740
- let token = flag2(args, "token") ?? process.env.HABLALA_ACCESS_TOKEN;
993
+ const endpoint = (flag(args, "endpoint") ?? process.env.HABLALA_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
994
+ let token = flag(args, "token") ?? process.env.HABLALA_ACCESS_TOKEN;
1741
995
  if (token) {
1742
996
  token = token.trim();
1743
997
  if (!token.startsWith("mat_")) {
@@ -1776,86 +1030,73 @@ async function login(args) {
1776
1030
  async function pull(args) {
1777
1031
  const dir = targetDir(args);
1778
1032
  const config = resolveConfig({
1779
- tokenFlag: flag2(args, "token"),
1780
- endpointFlag: flag2(args, "endpoint")
1033
+ tokenFlag: flag(args, "token"),
1034
+ endpointFlag: flag(args, "endpoint")
1781
1035
  });
1782
1036
  const api = createApiClient(config);
1783
1037
  const check = has(args, "check");
1784
1038
  info(dim(`\u2192 GET ${config.endpoint}/v1/account-config`));
1785
1039
  const { sections: manifest, version: version2 } = await fetchManifest(api);
1786
- const result = writeManifest(dir, manifest, { prune: has(args, "prune"), check });
1787
- if (!check && version2) {
1788
- const identity = await whoami(api);
1789
- writeLock(dir, { lineage: identity.organization.id, version: version2 });
1790
- }
1791
1040
  if (check) {
1041
+ const local = await loadConfig(dir);
1042
+ const localSections = { ...local.manifest };
1043
+ delete localSections.kind;
1044
+ delete localSections.version;
1045
+ const drift = local.problems.length > 0 || !manifestsMatch(localSections, manifest);
1792
1046
  if (has(args, "json")) {
1793
- out(JSON.stringify({ drift: result.drift }, null, 2));
1794
- return result.drift.length > 0 ? 1 : 0;
1047
+ out(JSON.stringify({ drift }, null, 2));
1048
+ return drift ? 1 : 0;
1795
1049
  }
1796
- if (result.drift.length === 0) {
1797
- out(`${green("\u2714")} Los archivos est\xE1n en sincron\xEDa con la organizaci\xF3n.`);
1050
+ if (!drift) {
1051
+ out(`${green("\u2714")} \`hablala.config.ts\` est\xE1 en sincron\xEDa con la organizaci\xF3n.`);
1798
1052
  return 0;
1799
1053
  }
1800
- out(`${yellow("!")} ${result.drift.length} archivo(s) difieren del estado real de la organizaci\xF3n:`);
1801
- for (const file of result.drift) out(` ${file}`);
1802
- 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."));
1054
+ out(`${yellow("!")} \`hablala.config.ts\` difiere del estado real de la organizaci\xF3n.`);
1055
+ out(dim(" Alguien cambi\xF3 la organizaci\xF3n por otra v\xEDa (panel/MCP), o editaste el config. Corre `hablala pull` para re-sincronizar antes de aplicar."));
1803
1056
  return 1;
1804
1057
  }
1058
+ writeConfigFile(dir, configFile(manifest));
1059
+ if (version2) {
1060
+ const identity = await whoami(api);
1061
+ writeLock(dir, { lineage: identity.organization.id, version: version2 });
1062
+ }
1805
1063
  if (has(args, "json")) {
1806
- out(
1807
- JSON.stringify(
1808
- { written: result.written, pruned: result.pruned, stale: result.stale },
1809
- null,
1810
- 2
1811
- )
1812
- );
1064
+ out(JSON.stringify({ written: ["hablala.config.ts"] }, null, 2));
1813
1065
  return 0;
1814
1066
  }
1815
- out(`${green("\u2714")} ${result.written.length} archivo(s) sincronizados en ${dir}.`);
1816
- for (const file of result.pruned) out(dim(` borrado (sobrante): ${file}`));
1817
- if (result.stale.length > 0) {
1818
- out(`${yellow("!")} Archivos que no corresponden a nada en la organizaci\xF3n (\xBFWIP o sobrantes?):`);
1819
- for (const file of result.stale) out(` ${file}`);
1820
- out(dim(" `apply` los crear\xEDa; `pull --prune` los borra."));
1821
- }
1067
+ out(`${green("\u2714")} \`hablala.config.ts\` sincronizado desde la organizaci\xF3n en ${dir}.`);
1822
1068
  return 0;
1823
1069
  }
1824
1070
  async function init(args) {
1825
1071
  const dir = targetDir(args);
1826
1072
  const config = resolveConfig({
1827
- tokenFlag: flag2(args, "token"),
1828
- endpointFlag: flag2(args, "endpoint")
1073
+ tokenFlag: flag(args, "token"),
1074
+ endpointFlag: flag(args, "endpoint")
1829
1075
  });
1830
1076
  const api = createApiClient(config);
1831
1077
  const identity = await whoami(api);
1832
1078
  mkdirSync3(dir, { recursive: true });
1833
- scaffoldFile(
1834
- join3(dir, "hablala.yaml"),
1835
- hablalaYaml(identity, config.endpoint),
1836
- has(args, "force")
1837
- );
1838
- scaffoldFile(join3(dir, ".gitignore"), gitignore(), has(args, "force"));
1839
- const guide = agentGuide(identity);
1840
- scaffoldFile(join3(dir, "CLAUDE.md"), guide, has(args, "force"));
1841
- scaffoldFile(join3(dir, "AGENTS.md"), guide, has(args, "force"));
1842
1079
  const { sections: manifest, version: version2 } = await fetchManifest(api);
1843
- const result = writeManifest(dir, manifest, { prune: false });
1080
+ scaffoldFile(join4(dir, "hablala.config.ts"), configFile(manifest), has(args, "force"));
1081
+ scaffoldFile(join4(dir, "package.json"), projectPackageJson(identity), has(args, "force"));
1082
+ scaffoldFile(join4(dir, "tsconfig.json"), projectTsconfig(), has(args, "force"));
1083
+ scaffoldFile(join4(dir, ".gitignore"), gitignore(), has(args, "force"));
1084
+ const guide = agentGuide(identity);
1085
+ scaffoldFile(join4(dir, "CLAUDE.md"), guide, has(args, "force"));
1086
+ scaffoldFile(join4(dir, "AGENTS.md"), guide, has(args, "force"));
1844
1087
  if (version2) writeLock(dir, { lineage: identity.organization.id, version: version2 });
1845
1088
  out(`${green("\u2714")} Organizaci\xF3n ${bold(identity.organization.name)} inicializada en ${dir}:`);
1846
- out(
1847
- ` hablala.yaml, .gitignore, CLAUDE.md + AGENTS.md y ${result.written.length} archivo(s) de configuraci\xF3n.`
1848
- );
1089
+ out(" hablala.config.ts, package.json, tsconfig.json, .gitignore, CLAUDE.md + AGENTS.md.");
1849
1090
  out("");
1850
- out(` Siguiente paso: edita los archivos y corre ${bold("hablala plan")}.`);
1091
+ out(` Siguiente paso: \`npm install\`, edita ${bold("hablala.config.ts")} y corre ${bold("hablala plan")}.`);
1851
1092
  return 0;
1852
1093
  }
1853
1094
  function scaffoldFile(path, content, force) {
1854
- if (existsSync3(path) && !force) {
1095
+ if (existsSync4(path) && !force) {
1855
1096
  info(dim(` ${path} ya existe; no se sobreescribe (usa --force).`));
1856
1097
  return;
1857
1098
  }
1858
- writeFileSync4(path, content, "utf8");
1099
+ writeFileSync5(path, content, "utf8");
1859
1100
  }
1860
1101
  async function agent(args) {
1861
1102
  const sub = args._[1];
@@ -1866,21 +1107,21 @@ async function agent(args) {
1866
1107
  return 1;
1867
1108
  }
1868
1109
  const dir = resolve2(process.cwd(), args._[2] ?? ".");
1869
- const skillDir = join3(dir, ".claude", "skills", "hablala");
1110
+ const skillDir = join4(dir, ".claude", "skills", "hablala");
1870
1111
  mkdirSync3(skillDir, { recursive: true });
1871
- scaffoldFile(join3(skillDir, "SKILL.md"), hablalaSkill(), has(args, "force"));
1872
- out(`${green("\u2714")} Skill instalada: ${join3(skillDir, "SKILL.md")}`);
1112
+ scaffoldFile(join4(skillDir, "SKILL.md"), hablalaSkill(), has(args, "force"));
1113
+ out(`${green("\u2714")} Skill instalada: ${join4(skillDir, "SKILL.md")}`);
1873
1114
  out("");
1874
1115
  out(" Los agentes de c\xF3digo que lean skills del repo (Claude Code y compatibles) ya");
1875
1116
  out(" saben operar Hablal\xE1: Account as Code, el SDK y las credenciales.");
1876
1117
  return 0;
1877
1118
  }
1878
1119
  async function plan(args) {
1879
- const loaded = loadLocal(args);
1120
+ const loaded = await loadLocal(args);
1880
1121
  if (typeof loaded === "number") return loaded;
1881
1122
  const config = resolveConfig({
1882
- tokenFlag: flag2(args, "token"),
1883
- endpointFlag: flag2(args, "endpoint")
1123
+ tokenFlag: flag(args, "token"),
1124
+ endpointFlag: flag(args, "endpoint")
1884
1125
  });
1885
1126
  const api = createApiClient(config);
1886
1127
  info(dim(`\u2192 PUT ${config.endpoint}/v1/account-config?dry_run=true`));
@@ -1901,11 +1142,11 @@ async function plan(args) {
1901
1142
  return planResult.errors.length > 0 ? 1 : 0;
1902
1143
  }
1903
1144
  async function apply(args) {
1904
- const loaded = loadLocal(args);
1145
+ const loaded = await loadLocal(args);
1905
1146
  if (typeof loaded === "number") return loaded;
1906
1147
  const config = resolveConfig({
1907
- tokenFlag: flag2(args, "token"),
1908
- endpointFlag: flag2(args, "endpoint")
1148
+ tokenFlag: flag(args, "token"),
1149
+ endpointFlag: flag(args, "endpoint")
1909
1150
  });
1910
1151
  const api = createApiClient(config);
1911
1152
  const dir = targetDir(args);
@@ -1994,42 +1235,19 @@ async function apply(args) {
1994
1235
  );
1995
1236
  return 0;
1996
1237
  }
1997
- async function evalAgents(args) {
1998
- const loaded = loadLocal(args);
1999
- if (typeof loaded === "number") return loaded;
2000
- const config = resolveConfig({
2001
- tokenFlag: flag2(args, "token"),
2002
- endpointFlag: flag2(args, "endpoint")
2003
- });
2004
- const api = createApiClient(config);
2005
- const live = has(args, "live");
2006
- info(dim(`\u2192 POST ${config.endpoint}/v1/account-config/eval${live ? "?live=true" : ""}`));
2007
- const { result, failure } = await runEvals(api, loaded.manifest, { live });
2008
- if (failure) {
2009
- printFailure(failure);
2010
- return 1;
2011
- }
2012
- const evalResult = result;
2013
- if (has(args, "json")) {
2014
- out(JSON.stringify(evalResult, null, 2));
2015
- } else {
2016
- out(renderEvals(evalResult));
2017
- }
2018
- return (evalResult.failed ?? 0) > 0 ? 1 : 0;
2019
- }
2020
- function loadLocal(args) {
1238
+ async function loadLocal(args) {
2021
1239
  const dir = targetDir(args);
2022
- const { manifest, modes, problems } = readManifest(dir);
1240
+ const { manifest, modes, problems } = await loadConfig(dir);
2023
1241
  if (problems.length > 0) {
2024
- out(bold("El manifiesto no pasa la validaci\xF3n local:"));
1242
+ out(bold("La configuraci\xF3n no pasa la validaci\xF3n local:"));
2025
1243
  for (const problem of problems) out(` ${red("\u2716")} ${problem}`);
2026
1244
  return 1;
2027
1245
  }
2028
- if (!manifest.objects && !manifest.workflows && !manifest.agents && !manifest.policies && !manifest.roles && !manifest.actions && !manifest.webhooks) {
1246
+ if (!manifest.objects && !manifest.workflows && !manifest.agents && !manifest.policies && !manifest.roles && !manifest.transactions && !manifest.webhooks) {
2029
1247
  out(
2030
- `${yellow("!")} ${dir} no tiene objects/, policies/, roles/, actions/ ni webhooks/ \u2014 nada que declarar.`
1248
+ `${yellow("!")} ${dir} no declara objects/workflows/agents/policies/roles/transactions/webhooks \u2014 nada que declarar.`
2031
1249
  );
2032
- out(dim(" Corre `hablala init` para bajar el estado actual a archivos."));
1250
+ out(dim(" Corre `hablala init` para bajar el estado actual a `hablala.config.ts`."));
2033
1251
  return 1;
2034
1252
  }
2035
1253
  return { manifest, modes };
@@ -2060,7 +1278,7 @@ function promptLine(query) {
2060
1278
  // src/members.ts
2061
1279
  var info2 = (message) => console.error(message);
2062
1280
  var out2 = (message) => console.log(message);
2063
- function flag3(args, name) {
1281
+ function flag2(args, name) {
2064
1282
  const value = args[name];
2065
1283
  return typeof value === "string" ? value : void 0;
2066
1284
  }
@@ -2090,23 +1308,23 @@ async function resolveRoleId(api, roleName) {
2090
1308
  if (!match) {
2091
1309
  const names = roles.map((r) => r.name).join(", ") || "(ninguno)";
2092
1310
  throw new Error(
2093
- `El rol "${roleName}" no existe en la organizaci\xF3n. Roles disponibles: ${names}. Decl\xE1ralo con Account as Code (roles/<name>.yaml \u2192 \`hablala apply\`) antes de invitar.`
1311
+ `El rol "${roleName}" no existe en la organizaci\xF3n. Roles disponibles: ${names}. Decl\xE1ralo con Account as Code (account.role({...}) en hablala.config.ts \u2192 \`hablala apply\`) antes de invitar.`
2094
1312
  );
2095
1313
  }
2096
1314
  return match.id;
2097
1315
  }
2098
1316
  async function invite(args) {
2099
- const email = flag3(args, "email");
1317
+ const email = flag2(args, "email");
2100
1318
  if (!email) {
2101
1319
  info2(`${red("\u2716")} Falta --email.
2102
1320
 
2103
1321
  ${INVITE_USAGE}`);
2104
1322
  return 1;
2105
1323
  }
2106
- const roleName = flag3(args, "role");
1324
+ const roleName = flag2(args, "role");
2107
1325
  const config = resolveConfig({
2108
- tokenFlag: flag3(args, "token"),
2109
- endpointFlag: flag3(args, "endpoint")
1326
+ tokenFlag: flag2(args, "token"),
1327
+ endpointFlag: flag2(args, "endpoint")
2110
1328
  });
2111
1329
  const api = createApiClient(config);
2112
1330
  const roleId = await resolveRoleId(api, roleName);
@@ -2138,17 +1356,17 @@ var CREATE_USAGE = `hablala members create --email <email> [--role <name>]
2138
1356
  Devuelve un link de set-password: la persona fija su propia contrase\xF1a (no se comparte ninguna
2139
1357
  generada). Para bootstrap \u2014 dar de alta al primer operador. El resto de opciones, como invite.`;
2140
1358
  async function create(args) {
2141
- const email = flag3(args, "email");
1359
+ const email = flag2(args, "email");
2142
1360
  if (!email) {
2143
1361
  info2(`${red("\u2716")} Falta --email.
2144
1362
 
2145
1363
  ${CREATE_USAGE}`);
2146
1364
  return 1;
2147
1365
  }
2148
- const roleName = flag3(args, "role");
1366
+ const roleName = flag2(args, "role");
2149
1367
  const config = resolveConfig({
2150
- tokenFlag: flag3(args, "token"),
2151
- endpointFlag: flag3(args, "endpoint")
1368
+ tokenFlag: flag2(args, "token"),
1369
+ endpointFlag: flag2(args, "endpoint")
2152
1370
  });
2153
1371
  const api = createApiClient(config);
2154
1372
  const { data, response } = await api.POST("/v1/members", {
@@ -2223,9 +1441,10 @@ Opciones globales:
2223
1441
  -h, --help Esta ayuda
2224
1442
  -v, --version La versi\xF3n
2225
1443
 
2226
- El manifiesto: objects/<slug>.yaml (objetos + relationships), policies/<slug>.yaml,
2227
- webhooks/<slug>.yaml. Cada directorio presente es autoritativo: lo no declarado se
2228
- archiva (nunca se borra). \`plan\` siempre muestra el diff completo antes de aplicar.
1444
+ La configuraci\xF3n: un \`hablala.config.ts\` (config as code) que declara objects, relationships,
1445
+ workflows, agents, policies, roles, transactions y webhooks con el SDK \`@hablala/schema\`. Cada
1446
+ secci\xF3n declarada es autoritativa: lo no declarado se archiva (nunca se borra). \`plan\` siempre
1447
+ muestra el diff completo antes de aplicar.
2229
1448
 
2230
1449
  Docs y soporte: https://github.com/hablala/hablala
2231
1450
  `;
@@ -2271,7 +1490,6 @@ async function main() {
2271
1490
  pull,
2272
1491
  plan,
2273
1492
  apply,
2274
- eval: evalAgents,
2275
1493
  codegen,
2276
1494
  agent,
2277
1495
  members,