koigrid 0.7.0 → 0.8.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/dist/api.js +21 -3
  3. package/dist/args.js +19 -0
  4. package/dist/commands/analytics.js +1 -1
  5. package/dist/commands/apps.js +181 -21
  6. package/dist/commands/audit.js +1 -1
  7. package/dist/commands/billing.js +31 -0
  8. package/dist/commands/bots.js +1 -1
  9. package/dist/commands/changelog.js +19 -0
  10. package/dist/commands/checks.js +4 -3
  11. package/dist/commands/config.js +9 -6
  12. package/dist/commands/connect.js +2 -2
  13. package/dist/commands/db.js +384 -16
  14. package/dist/commands/dns.js +1 -1
  15. package/dist/commands/errors.js +1 -1
  16. package/dist/commands/flags.js +1 -1
  17. package/dist/commands/heartbeats.js +3 -3
  18. package/dist/commands/images.js +1 -1
  19. package/dist/commands/jobs.js +39 -4
  20. package/dist/commands/links.js +59 -0
  21. package/dist/commands/logs.js +1 -1
  22. package/dist/commands/members.js +26 -1
  23. package/dist/commands/notices.js +24 -0
  24. package/dist/commands/notifications.js +2 -2
  25. package/dist/commands/otel.js +1 -1
  26. package/dist/commands/projects.js +1 -1
  27. package/dist/commands/queues.js +4 -3
  28. package/dist/commands/redis.js +18 -2
  29. package/dist/commands/registry.js +43 -3
  30. package/dist/commands/rewards.js +63 -0
  31. package/dist/commands/sandboxes.js +1 -1
  32. package/dist/commands/speed.js +1 -1
  33. package/dist/commands/spend.js +1 -1
  34. package/dist/commands/status.js +1 -1
  35. package/dist/commands/storage.js +31 -3
  36. package/dist/commands/support.js +47 -0
  37. package/dist/commands/tokens.js +2 -2
  38. package/dist/commands/up.js +6 -2
  39. package/dist/commands/waf.js +1 -1
  40. package/dist/commands/webhooks.js +1 -1
  41. package/dist/commands/wordpress.js +4 -3
  42. package/dist/commands/workflows.js +4 -3
  43. package/dist/index.js +13 -3
  44. package/dist/manifest.js +15 -10
  45. package/dist/output.js +1 -0
  46. package/dist/proyecto.js +6 -0
  47. package/dist/registry-flags.js +17 -0
  48. package/dist/registry.js +6 -2
  49. package/package.json +1 -1
  50. package/dist/commands/ai.js +0 -56
package/CHANGELOG.md CHANGED
@@ -5,7 +5,7 @@ All notable changes to the koigrid CLI are documented here. Format: [Keep a Chan
5
5
  ## [0.7.0] — 2026-07-24
6
6
 
7
7
  ### Added
8
- - **`koigrid apps loadtest <id>`** — reporte de capacidad: martillea la URL de tu app (concurrencia/duración acotadas) → req/s + p50/p95/p99 + señal de saturación + guía de dimensionado. `--duration <s>` `--concurrency <n>` `--path </>`. Ver docs/CAPACITY.md.
8
+ - **`koigrid apps loadtest <id>`** — reporte de capacidad: martillea la URL de tu app (concurrencia/duración acotadas) → req/s + p50/p95/p99 + señal de saturación + guía de dimensionado. `--duration <s>` `--concurrency <n>` `--path </>`. Ver docs/platform/CAPACITY.md.
9
9
 
10
10
  ## [0.6.0] — 2026-07-24
11
11
 
@@ -13,7 +13,7 @@ All notable changes to the koigrid CLI are documented here. Format: [Keep a Chan
13
13
  - **`koigrid up` / `koigrid plan`** — cutover multi-servicio: lee un `koigrid.yaml` (o `.json`) que declara el
14
14
  STACK entero (project + databases + redis + apps cableados por `${{...}}`) y lo levanta en un comando,
15
15
  idempotente (como `docker-compose up` / `terraform apply`). `plan` = dry-run. `up -f <fichero>` para otro
16
- manifiesto. Ver docs/CUTOVER.md. (dep nueva: `yaml` para parsear el manifiesto).
16
+ manifiesto. Ver docs/runbooks/CUTOVER.md. (dep nueva: `yaml` para parsear el manifiesto).
17
17
 
18
18
  ## [0.5.0] — 2026-07-24
19
19
 
package/dist/api.js CHANGED
@@ -1,5 +1,15 @@
1
1
  // Cliente HTTP de la API de koigrid. Añade el Bearer token + maneja errores JSON de forma uniforme.
2
2
  import { loadConfig, DEFAULT_API } from './config.js';
3
+ import { createRequire } from 'node:module';
4
+ // El CLI se IDENTIFICA con su versión: sin esto la API no puede distinguir un CLI viejo (que descartaba flags en
5
+ // silencio) de una petición a mano, ni avisar a quien siga en una versión con fallos conocidos.
6
+ const VERSION = (() => { try {
7
+ return String(createRequire(import.meta.url)('../package.json').version);
8
+ }
9
+ catch {
10
+ return '0';
11
+ } })();
12
+ export const USER_AGENT = `koigrid-cli/${VERSION}`;
3
13
  export class ApiError extends Error {
4
14
  status;
5
15
  detail;
@@ -10,16 +20,24 @@ export class ApiError extends Error {
10
20
  this.name = 'ApiError';
11
21
  }
12
22
  }
23
+ /**
24
+ * `rawBody`: cuerpo en BYTES en vez de JSON (subir un fichero). Va aquí y no en el comando porque lo que hay
25
+ * que no repetir es la resolución del token y de la URL base, no el `fetch`.
26
+ */
13
27
  export async function api(path, opts = {}) {
14
28
  const cfg = loadConfig();
15
29
  const token = opts.token || cfg.token;
16
30
  const base = opts.api || cfg.api || DEFAULT_API;
17
- if (!token)
31
+ // `anon`: endpoints PÚBLICOS a propósito. Exigir credenciales para consultarlos sería una contradicción — el
32
+ // historial de cambios existe para que puedas averiguar si tu problema está arreglado, y quien todavía no ha
33
+ // conseguido autenticarse es justo quien más lo necesita. Si hay token se manda igual (así el consumo se
34
+ // atribuye a quien es); si no lo hay, se pregunta sin él en vez de negarse.
35
+ if (!token && !opts.anon)
18
36
  throw new ApiError(401, 'Not logged in. Run `koigrid login` (or set KOIGRID_TOKEN).');
19
37
  const res = await fetch(`${base}${path}`, {
20
38
  method: opts.method || 'GET',
21
- headers: { Authorization: `Bearer ${token}`, ...(opts.body ? { 'content-type': 'application/json' } : {}) },
22
- body: opts.body ? JSON.stringify(opts.body) : undefined,
39
+ headers: { 'user-agent': USER_AGENT, ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(opts.body ? { 'content-type': 'application/json' } : {}), ...(opts.headers || {}) },
40
+ body: opts.rawBody ? opts.rawBody : opts.body ? JSON.stringify(opts.body) : undefined,
23
41
  signal: AbortSignal.timeout(30_000),
24
42
  }).catch((e) => { throw new ApiError(0, `network error: ${e?.message || e}`); });
25
43
  const text = await res.text();
package/dist/args.js CHANGED
@@ -49,3 +49,22 @@ export function parseArgs(argv) {
49
49
  const sub = positionals.shift();
50
50
  return { cmd, sub, positionals, flags, ...(passthrough ? { passthrough } : {}) };
51
51
  }
52
+ /**
53
+ * Vigila qué flags LEE de verdad el comando, para decir cuáles se ignoraron.
54
+ *
55
+ * ⛔ POR QUÉ (2026-10-08, cuenta real de un cliente). Con el CLI de npm, `koigrid apps deploy … --env KEY=VAL` creó
56
+ * la app SIN variables y no dijo nada: esa versión no conocía `--env` al crear y el parser acepta cualquier flag. La
57
+ * app arrancó sin `DATABASE_URL` y su API devolvía 500. Un flag que no se usa es una instrucción que se pierde, así
58
+ * que se dice. Se mide por LECTURA, no con una lista por comando: una lista se queda atrás al añadir un flag, y lo
59
+ * que importa es si ESTA ejecución lo usó.
60
+ */
61
+ export function vigilarFlags(flags) {
62
+ const leidos = new Set();
63
+ const proxy = new Proxy(flags, {
64
+ get(t, k) { if (typeof k === 'string')
65
+ leidos.add(k); return Reflect.get(t, k); },
66
+ has(t, k) { if (typeof k === 'string')
67
+ leidos.add(k); return Reflect.has(t, k); },
68
+ });
69
+ return { flags: proxy, sinLeer: () => Object.keys(flags).filter((k) => !leidos.has(k)) };
70
+ }
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid analytics — web analytics privacy-first. Ver docs/ANALYTICS.md.
3
+ // koigrid analytics — web analytics privacy-first. Ver docs/products/ANALYTICS.md.
4
4
  export async function analytics(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'sites';
@@ -1,6 +1,9 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
2
3
  import { api } from '../api.js';
3
4
  import { output, green } from '../output.js';
5
+ import { credencialRegistryDeFlags } from '../registry-flags.js';
6
+ import { proyectoDeFlags } from '../proyecto.js';
4
7
  export async function apps(a) {
5
8
  const json = !!a.flags.json, sub = a.sub || 'ls';
6
9
  const id = a.positionals[0];
@@ -18,15 +21,7 @@ export async function apps(a) {
18
21
  const dir = a.flags.dir; // deploy desde un directorio LOCAL (código privado, sin git/Docker)
19
22
  const repoToken = a.flags['repo-token']; // token/deploy-key para repos privados
20
23
  // Registry PRIVADO (imagen inmutable de CI: build en CI → koigrid la corre): credenciales para el pull.
21
- const registry = a.flags.registry;
22
- const registryUsername = a.flags['registry-user'];
23
- const registryPassword = a.flags['registry-password'];
24
- const registryAwsRegion = a.flags['registry-aws-region']; // ECR: token fresco por deploy
25
- const registryAwsAccessKeyId = a.flags['registry-aws-key'];
26
- const registryAwsSecretKey = a.flags['registry-aws-secret'];
27
- const reg = registry && registryUsername && registryPassword ? { registry, registryUsername, registryPassword }
28
- : registry && registryAwsRegion && registryAwsAccessKeyId && registryAwsSecretKey ? { registry, registryAwsRegion, registryAwsAccessKeyId, registryAwsSecretKey }
29
- : {};
24
+ const reg = credencialRegistryDeFlags(a); // compartido con `jobs` (cli/src/registry-flags.ts)
30
25
  const healthPath = a.flags['health-path']; // ruta de salud (/api/health) → koigrid detecta apps rotas
31
26
  const hc = healthPath ? { healthCheckPath: healthPath } : {};
32
27
  // Build settings (git/dir): overridean lo que detecta nixpacks. Un koigrid.json en el repo tiene prioridad.
@@ -41,13 +36,40 @@ export async function apps(a) {
41
36
  bs.rootDirectory = a.flags['root-dir'];
42
37
  if (a.flags['node-version'])
43
38
  bs.nodeVersion = a.flags['node-version'];
39
+ if (a.flags.branch)
40
+ bs.branch = a.flags.branch; // rama a clonar (repo); sin ella, main
41
+ if (a.flags.dockerfile)
42
+ bs.dockerfilePath = a.flags.dockerfile; // otro Dockerfile que el de la raíz de build
43
+ // Tamaño AL CREAR (POST /apps ya lo admitía): sin esto había que crear y luego `apps resize`, o sea dos
44
+ // despliegues, y el primero arrancaba con la memoria por defecto (un Chromium no cabe en ella).
45
+ const tam = {};
46
+ if (a.flags.memory)
47
+ tam.memoryMb = Number(a.flags.memory);
48
+ if (a.flags.cpus)
49
+ tam.cpus = Number(a.flags.cpus);
50
+ // ENTRADA: por defecto la app la sirve el EDGE CENTRAL (su DNS apunta al VIP, no a la máquina). El opt-out
51
+ // es declarado y va al crear, porque cambiarla después es una transición ordenada, no una bandera.
52
+ const ing = a.flags.ingress === 'runner' ? { ingress: 'runner' } : {};
53
+ if (a.flags.ingress !== undefined && a.flags.ingress !== 'runner' && a.flags.ingress !== 'edge')
54
+ throw new Error("--ingress must be 'edge' (default) or 'runner'");
44
55
  if (!name || (!image && !repo && !dir))
45
- throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--repo-token <t>] [--port N] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V]');
56
+ throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
46
57
  const port = a.flags.port ? Number(a.flags.port) : 3000;
58
+ // --env KEY=VAL (repetible): el entorno viaja CON la creación, así que el primer despliegue ya sale con él
59
+ // (ficha d62bcde4). Antes había que crear, fijar variables y redesplegar: el primer despliegue fallaba siempre.
60
+ const envPares = [].concat(a.flags.env ?? []);
61
+ const env = {};
62
+ for (const par of envPares) {
63
+ const i = par.indexOf('=');
64
+ if (i <= 0)
65
+ throw new Error(`--env needs KEY=VALUE (got "${par}")`);
66
+ env[par.slice(0, i)] = par.slice(i + 1);
67
+ }
68
+ const en = envPares.length ? { env, ...(a.flags['env-target'] ? { envTarget: a.flags['env-target'] } : {}) } : {};
47
69
  // deploy --dir: empaqueta el directorio (excluye lo pesado/irrelevante) → subida presignada a koigrid →
48
70
  // el runner lo construye igual que un repo. No requiere git ni Docker local.
49
71
  if (dir) {
50
- const app = await api('/apps', { method: 'POST', body: { name, port, ...hc, ...bs } });
72
+ const app = await api('/apps', { method: 'POST', body: { name, port, ...hc, ...bs, ...tam, ...ing, ...en, ...proyectoDeFlags(a) } });
51
73
  const aid = app.app?.id || app.id;
52
74
  const up = await api(`/apps/${encodeURIComponent(aid)}/source-upload`, { method: 'POST', body: {} });
53
75
  const { uploadUrl, archiveKey } = up.upload;
@@ -61,8 +83,22 @@ export async function apps(a) {
61
83
  // confusión "ids CLI≠API" del journey. appId aparte, etiquetado.
62
84
  return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
63
85
  }
64
- const app = await api('/apps', { method: 'POST', body: repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs } : { name, sourceType: 'image', image, port, ...hc, ...reg } });
86
+ const app = await api('/apps', { method: 'POST', body: { ...proyectoDeFlags(a), ...(repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs, ...tam, ...ing, ...en } : { name, sourceType: 'image', image, port, ...hc, ...tam, ...reg, ...ing, ...en }) } });
65
87
  const aid = app.app?.id || app.id;
88
+ // ⚠️ Una app de IMAGEN se despliega SOLA al crearse. Lanzar aquí otro despliegue daba DOS por cada `apps deploy
89
+ // --image`, que chocaban entre sí (ficha d62bcde4). Con imagen se informa del automático; con repo se lanza.
90
+ if (!repo) {
91
+ // El automático se lanza en segundo plano al crear: se espera hasta ~15 s a que aparezca para devolver su id,
92
+ // que es lo que devolvía este comando (un guion que lea `deploymentId` del --json no debe romperse).
93
+ let auto;
94
+ for (let i = 0; i < 15 && !auto; i++) {
95
+ await new Promise((r) => setTimeout(r, 1000));
96
+ auto = ((await api(`/apps/${encodeURIComponent(aid)}/deployments`)).deployments ?? [])[0];
97
+ }
98
+ return json
99
+ ? console.log(JSON.stringify({ deploymentId: auto?.id ?? null, appId: aid, status: auto?.status || 'queued', automatic: true }, null, 2))
100
+ : console.log(green(`✓ Deploying "${name}"… (deployment ${String(auto?.id || '').slice(0, 8) || 'starting'}, automatic on create)`));
101
+ }
66
102
  const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
67
103
  return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
68
104
  }
@@ -89,8 +125,19 @@ export async function apps(a) {
89
125
  await api(`/apps/${encodeURIComponent(id)}/rollback`, { method: 'POST', body: { deploymentId: d } });
90
126
  return console.log(green('✓ Rolling back…'));
91
127
  }
92
- case 'loadtest': { // reporte de capacidad: rps + p50/p95/p99 + saturación (docs/CAPACITY.md)
93
- need(' [--duration <s≤60>] [--concurrency <n≤100>] [--path /]');
128
+ // Pausar/reanudar: apaga el cómputo sin perder nada (config, env, dominios, historial, volúmenes).
129
+ case 'pause': {
130
+ need('');
131
+ const r = await api(`/apps/${encodeURIComponent(id)}/pause`, { method: 'POST', body: {} });
132
+ return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.alreadyPaused ? `✓ ${id} ya estaba pausada` : `✓ Paused ${id} — se conserva todo; reanuda con: koigrid apps resume ${id}`));
133
+ }
134
+ case 'resume': {
135
+ need('');
136
+ const r = await api(`/apps/${encodeURIComponent(id)}/resume`, { method: 'POST', body: {} });
137
+ return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.wasPaused ? (r.redeployed ? `✓ Resuming ${id}… (relanzando la última imagen)` : `✓ ${id} reanudada (nunca tuvo un deploy vivo: despliega con: koigrid apps deploy)`) : `✓ ${id} no estaba pausada`));
138
+ }
139
+ case 'loadtest': { // reporte de capacidad: rps + p50/p95/p99 + rodilla + señales del servidor (docs/platform/CAPACITY.md)
140
+ need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\']');
94
141
  const body = {};
95
142
  if (a.flags.duration !== undefined)
96
143
  body.durationSec = Number(a.flags.duration);
@@ -98,11 +145,27 @@ export async function apps(a) {
98
145
  body.concurrency = Number(a.flags.concurrency);
99
146
  if (a.flags.path !== undefined)
100
147
  body.path = String(a.flags.path);
148
+ if (a.flags.ramp)
149
+ body.mode = 'ramp';
150
+ if (a.flags.stages !== undefined)
151
+ body.stages = Number(a.flags.stages);
152
+ if (a.flags.warmup !== undefined)
153
+ body.warmupSec = Number(a.flags.warmup);
154
+ if (a.flags.paths !== undefined)
155
+ body.paths = JSON.parse(String(a.flags.paths));
101
156
  const r = await api(`/apps/${encodeURIComponent(id)}/loadtest`, { method: 'POST', body });
102
157
  if (a.flags.json)
103
158
  return console.log(JSON.stringify(r, null, 2));
104
159
  console.log(green(`✓ load-test ${r.app} (${r.target})`));
105
160
  console.log(` ${r.requests} reqs · ~${Math.round(r.rps)} req/s · p50 ${Math.round(r.p50)}ms · p95 ${Math.round(r.p95)}ms · p99 ${Math.round(r.p99)}ms · errores ${(r.errorRate * 100).toFixed(1)}%`);
161
+ if (r.coldStartP95 != null)
162
+ console.log(` arranque en frío (excluido del p95): ${r.coldStartP95}ms`);
163
+ if (r.stages) {
164
+ console.log(' escalones:');
165
+ for (const s of r.stages)
166
+ console.log(` ${String(s.concurrency).padStart(3)} simultáneos → ${Math.round(s.rps)} req/s · p95 ${Math.round(s.p95)}ms · errores ${(s.errorRate * 100).toFixed(1)}%`);
167
+ console.log(` rodilla: ${r.knee?.concurrency ?? '—'}${r.knee?.concurrency ? ' simultáneos' : ''}`);
168
+ }
106
169
  return console.log(` ${r.saturated ? '⚠ ' : '✓ '}${r.note}`);
107
170
  }
108
171
  case 'restore': {
@@ -150,8 +213,34 @@ export async function apps(a) {
150
213
  const r = await api(`/apps/${encodeURIComponent(id)}/autoscale`, { method: 'PUT', body });
151
214
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Autoscale updated'));
152
215
  }
216
+ case 'scale-out': {
217
+ // Sirve la app por el edge central en vez de por el Caddy de su runner. Es lo que hace que se APLIQUEN
218
+ // las reglas (redirect/rewrite/header) de una app en un runner heredado.
219
+ need(' --enabled true|false');
220
+ if (a.flags.enabled === undefined) {
221
+ const r = await api(`/apps/${encodeURIComponent(id)}/scale-out`);
222
+ return console.log(json ? JSON.stringify(r, null, 2) : JSON.stringify(r.scaleOut));
223
+ }
224
+ const body = { enabled: a.flags.enabled === 'true' || a.flags.enabled === true };
225
+ const r = await api(`/apps/${encodeURIComponent(id)}/scale-out`, { method: 'PUT', body });
226
+ if (json)
227
+ return console.log(JSON.stringify(r, null, 2));
228
+ // Apagar NO es inmediato ni es un flag: es una transición en segundo plano (ficha 0d3557e1). Decir
229
+ // «✓ disabled» aquí sería exactamente el tipo de mensaje que este repo persigue —algo declarado hecho sin
230
+ // estarlo—, así que se dice lo que de verdad ha pasado y cómo mirar en qué acaba.
231
+ if (r.transition?.state === 'in_progress') {
232
+ return console.log(`→ Scale-out is being turned off (deployment ${r.transition.deploymentId}).
233
+ ` +
234
+ ` The app keeps being served while it happens; replicas are removed only after its runner is verified.
235
+ ` +
236
+ ` Follow it: koigrid apps scale-out ${id} (enabled:false = done)
237
+ ` +
238
+ ` koigrid events --limit 5 (why, if it kept the replicas)`);
239
+ }
240
+ return console.log(green(`✓ Scale-out ${body.enabled ? 'enabled' : 'disabled'} — ${r.note ?? ''}`));
241
+ }
153
242
  case 'env': {
154
- need(' set KEY=VAL [--target production|preview|all] | rm KEY | ls');
243
+ need(' set KEY=VAL [--target production|preview|all] | replace KEY=VAL ... | rm KEY | ls | verify [KEY] [--value <v>]');
155
244
  const act = a.positionals[1];
156
245
  if (!act || act === 'ls') {
157
246
  const r = await api(`/apps/${encodeURIComponent(id)}/env`);
@@ -176,13 +265,59 @@ export async function apps(a) {
176
265
  await api(`/apps/${encodeURIComponent(id)}/env`, { method: 'POST', body: { env: { [k]: v.join('=') }, target } });
177
266
  return console.log(green(`✓ Set ${k} [${target}] (redeploying)`));
178
267
  }
179
- throw new Error('usage: koigrid apps env <id> set KEY=VAL [--target production|preview|all] | rm KEY | ls');
268
+ // replace: la lista dada pasa a ser el entorno ENTERO de la app (las guardadas que no estén se borran, en la misma
269
+ // transacción) y se despliega. Es la forma de quitar una referencia ${{…}} a un recurso que ya no existe sin
270
+ // ir variable a variable: así se despublicó vencecolombia.co el 2026-10-10.
271
+ if (act === 'replace') {
272
+ const pares = a.positionals.slice(2);
273
+ if (!pares.length)
274
+ throw new Error('need KEY=VALUE ... (the full environment)');
275
+ const env = {};
276
+ for (const par of pares) {
277
+ const i = par.indexOf('=');
278
+ if (i <= 0)
279
+ throw new Error(`need KEY=VALUE (got "${par}")`);
280
+ env[par.slice(0, i)] = par.slice(i + 1);
281
+ }
282
+ const target = a.flags.target || 'all';
283
+ const r = await api(`/apps/${encodeURIComponent(id)}/deployments`, { method: 'POST', body: { env, envTarget: target, envMode: 'replace' } });
284
+ return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(`✓ Environment replaced (${Object.keys(env).length} vars, [${target}]) — deploying ${String(r.deployment?.id || '').slice(0, 8)}`));
285
+ }
286
+ // ⭐ verify: ¿lo que ve el contenedor es lo que crees? Nunca devuelve valores — compara huellas.
287
+ // Con `--value` el sha256 se calcula AQUÍ, en tu máquina: el secreto no sale de ella.
288
+ if (act === 'verify') {
289
+ const k = a.positionals[2];
290
+ const val = a.flags.value;
291
+ const sha = val !== undefined ? createHash('sha256').update(val, 'utf8').digest('hex') : a.flags.sha256;
292
+ if (sha && !k)
293
+ throw new Error('--value/--sha256 necesitan la KEY: koigrid apps env <id> verify KEY --value <valor>');
294
+ const qs = new URLSearchParams();
295
+ if (k)
296
+ qs.set('key', k);
297
+ if (sha)
298
+ qs.set('expected', sha);
299
+ const r = await api(`/apps/${encodeURIComponent(id)}/env/verify${qs.toString() ? `?${qs}` : ''}`);
300
+ if (json)
301
+ return console.log(JSON.stringify(r, null, 2));
302
+ if (!r.reachable)
303
+ console.log('⚠️ no se pudo preguntar al contenedor (¿la app está desplegada y en marcha?)');
304
+ for (const v of r.vars || []) {
305
+ const estado = !v.present ? '✗ no llega al contenedor' : v.matchesConfigured === false ? '⚠ distinta de la guardada (falta desplegar)' : v.matchesConfigured ? '✓ al día' : '· presente';
306
+ console.log(`${v.key}\t[${v.target}]\t${estado}\t${v.fingerprint ?? '-'}`);
307
+ }
308
+ if (r.verdict)
309
+ console.log(`\n${r.verdict.code === 'matches_expected' || r.verdict.code === 'in_sync' ? green('✓') : '→'} ${r.verdict.detail}`);
310
+ return;
311
+ }
312
+ throw new Error('usage: koigrid apps env <id> set KEY=VAL [--target production|preview|all] | replace KEY=VAL ... | rm KEY | ls | verify [KEY] [--value <v> | --sha256 <h>]');
180
313
  }
181
314
  case 'domains': {
182
- need(' add <domain> | rm <domain> | ls | verify');
315
+ need(' add <domain> | move <domain> | rm <domain> | ls | verify');
183
316
  const act = a.positionals[1];
184
- const cols = ['domain', 'status', 'record'];
185
- const rowsOf = (l) => l.map((x) => (typeof x === 'string' ? { domain: x, status: '', record: '' } : { domain: x.domain, status: x.status ?? '', record: x.record ? `${x.record.type} ${x.record.name} → ${x.record.value}` : '' }));
317
+ // `acme`: la delegación opcional del reto del certificado, para migrar sin corte (cert listo ANTES de apuntar el DNS).
318
+ const cols = ['domain', 'status', 'record', 'acme'];
319
+ const acmeDe = (x) => !x.acme ? '' : !x.acme.supported ? 'n/a (runner ingress)' : `${x.acme.record ? `CNAME ${x.acme.record.name} → ${x.acme.record.value}` : ''}${x.acme.delegated ? ` [delegated${x.acme.certReady ? ', cert ready' : ', issuing'}]` : ''}`;
320
+ const rowsOf = (l) => l.map((x) => (typeof x === 'string' ? { domain: x, status: '', record: '', acme: '' } : { domain: x.domain, status: x.status ?? '', record: x.record ? `${x.record.type} ${x.record.name} → ${x.record.value}` : '', acme: acmeDe(x) }));
186
321
  if (!act || act === 'ls') {
187
322
  const r = await api(`/apps/${encodeURIComponent(id)}/domains`);
188
323
  const l = r.domains || r || [];
@@ -198,7 +333,7 @@ export async function apps(a) {
198
333
  if (!d)
199
334
  throw new Error('need <domain>');
200
335
  const r = await api(`/apps/${encodeURIComponent(id)}/domains`, { method: 'POST', body: { domain: d } });
201
- return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Added ${d} — create DNS: ${r.instructions}`));
336
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Added ${d} — create DNS: ${r.instructions}`) + (r.acme?.record ? `\n zero-downtime migration (optional): CNAME ${r.acme.record.name} → ${r.acme.record.value} (cert is issued before your DNS points here)` : ''));
202
337
  }
203
338
  if (act === 'rm') {
204
339
  const d = a.positionals[2];
@@ -207,7 +342,15 @@ export async function apps(a) {
207
342
  await api(`/apps/${encodeURIComponent(id)}/domains?domain=${encodeURIComponent(d)}`, { method: 'DELETE' });
208
343
  return console.log(green(`✓ Removed ${d}`));
209
344
  }
210
- throw new Error('usage: koigrid apps domains <id> add <domain> | rm <domain> | ls | verify');
345
+ // Mover un dominio desde otra app de la organización conservando su certificado y su delegación ACME.
346
+ if (act === 'move') {
347
+ const d = a.positionals[2];
348
+ if (!d)
349
+ throw new Error('need <domain>');
350
+ const r = await api(`/apps/${encodeURIComponent(id)}/domains`, { method: 'POST', body: { domain: d, move: true } });
351
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Moved ${d}${r.movedFrom ? ` from ${r.movedFrom}` : ''} (certificate and ACME delegation kept)`));
352
+ }
353
+ throw new Error('usage: koigrid apps domains <id> add <domain> | move <domain> | rm <domain> | ls | verify');
211
354
  }
212
355
  case 'volumes': {
213
356
  need(' add <name> --size N --mount /path | rm <volId> | ls');
@@ -269,6 +412,23 @@ export async function apps(a) {
269
412
  const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
270
413
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
271
414
  }
415
+ case 'cache': {
416
+ // Caché compartida del edge (guarda sólo lo que la app marca como cacheable: s-maxage / public). Distinta de `cdn`.
417
+ need(' [on|off|purge]');
418
+ const act = a.positionals[1];
419
+ if (!act) {
420
+ const r = await api(`/apps/${encodeURIComponent(id)}/cache`);
421
+ return console.log(json ? JSON.stringify(r, null, 2) : `edge cache: ${r.cache?.enabled ? 'on' : 'off'}`);
422
+ }
423
+ if (act === 'purge') {
424
+ const r = await api(`/apps/${encodeURIComponent(id)}/cache/purge`, { method: 'POST' });
425
+ return console.log(json ? JSON.stringify(r, null, 2) : r.purged ? green('✓ Edge cache purged') : `purge incomplete: ${(r.nodes || []).filter((n) => !n.ok).map((n) => n.node).join(', ')}`);
426
+ }
427
+ if (act !== 'on' && act !== 'off')
428
+ throw new Error('usage: koigrid apps cache <id> [on|off|purge]');
429
+ const r = await api(`/apps/${encodeURIComponent(id)}/cache`, { method: 'PUT', body: { enabled: act === 'on' } });
430
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Edge cache ${act}`));
431
+ }
272
432
  case 'retention': {
273
433
  need(' [<keepLast> | off]');
274
434
  const arg = a.positionals[1];
@@ -1,7 +1,7 @@
1
1
  import { api } from '../api.js';
2
2
  import { output } from '../output.js';
3
3
  // koigrid audit — Audit Log (quién hizo qué, con IP y fecha). Sustituto de AWS CloudTrail. owner/admin only.
4
- // Ver docs/AUDIT-LOG.md.
4
+ // Ver docs/products/AUDIT-LOG.md.
5
5
  // koigrid audit ls [--category members,security] [--type token.created] [--actor-type agent] [--since 30] [--limit 100]
6
6
  // koigrid audit export [mismos filtros] > audit.csv
7
7
  export async function audit(a) {
@@ -0,0 +1,31 @@
1
+ import { api } from '../api.js';
2
+ import { green, dim } from '../output.js';
3
+ // koigrid billing — estado del plan y el TRASPASO al pago. Ver docs/products/BILLING.md.
4
+ //
5
+ // `upgrade` no cobra: pide al proveedor su enlace de pago y lo imprime. Existe porque un agente puede conducir
6
+ // toda una migración por API y se paraba justo aquí — el único paso que no podía dar (ficha c534eb91).
7
+ export async function billing(a) {
8
+ const json = !!a.flags.json;
9
+ const sub = a.sub || 'show';
10
+ if (sub === 'show' || sub === 'status' || sub === 'plans') {
11
+ const r = await api('/billing');
12
+ if (json)
13
+ return console.log(JSON.stringify(r, null, 2));
14
+ console.log(`plan: ${r.plan}${r.checkoutAvailable ? '' : dim(' (pago no configurado)')}`);
15
+ for (const p of r.plans ?? [])
16
+ console.log(` ${p.current ? '→' : ' '} ${String(p.id).padEnd(8)} $${p.priceUsd}/mo`);
17
+ return;
18
+ }
19
+ if (sub === 'upgrade' || sub === 'checkout') {
20
+ const plan = a.positionals[0] ?? a.flags.plan;
21
+ if (!plan)
22
+ throw new Error('usage: koigrid billing upgrade <starter|pro|scale>');
23
+ const r = await api('/billing/checkout-session', { method: 'POST', body: { plan: String(plan) } });
24
+ if (json)
25
+ return console.log(JSON.stringify(r, null, 2));
26
+ console.log(green(`✓ enlace de pago para '${r.plan}':`));
27
+ console.log(` ${r.url}`);
28
+ return console.log(dim(' Ábrelo tú (o pásaselo a quien decide): koigrid no cobra por API.'));
29
+ }
30
+ throw new Error(`unknown: billing ${sub}`);
31
+ }
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { green } from '../output.js';
3
- // koigrid bots — Bot Management (clasifica + decide allow/challenge/block + reto PoW). Ver docs/BOT-MANAGEMENT.md.
3
+ // koigrid bots — Bot Management (clasifica + decide allow/challenge/block + reto PoW). Ver docs/products/BOT-MANAGEMENT.md.
4
4
  export async function bots(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'policy';
@@ -0,0 +1,19 @@
1
+ import { api } from '../api.js';
2
+ import { output } from '../output.js';
3
+ // koigrid changelog — qué ha cambiado. Existe para no tener que reejecutar todas tus pruebas para averiguar si
4
+ // tu problema ya está arreglado. `--since` acota a lo posterior a una fecha.
5
+ export async function changelog(a) {
6
+ const json = !!a.flags.json;
7
+ const since = a.flags.since || a.positionals[0] || '';
8
+ // Sin credenciales: es público a propósito (ver lib/changelog.ts).
9
+ const r = await api(`/changelog${since ? `?since=${encodeURIComponent(since)}` : ''}`, { anon: true });
10
+ const l = r.entries || [];
11
+ if (json)
12
+ return console.log(JSON.stringify(r, null, 2));
13
+ if (!l.length)
14
+ return console.log(`Sin cambios${since ? ` posteriores a ${since}` : ''}. Último cambio: ${r.latest ?? '—'}`);
15
+ return output(l, false, {
16
+ rows: l.map((x) => ({ date: x.date, kind: x.kind, summary: x.summary })),
17
+ columns: ['date', 'kind', 'summary'],
18
+ });
19
+ }
@@ -1,6 +1,7 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid checks — uptime & synthetic monitoring (ver docs/CHECKS.md).
3
+ import { proyectoDeFlags } from '../proyecto.js';
4
+ // koigrid checks — uptime & synthetic monitoring (ver docs/products/CHECKS.md).
4
5
  export async function checks(a) {
5
6
  const json = !!a.flags.json;
6
7
  const sub = a.sub || 'ls';
@@ -16,8 +17,8 @@ export async function checks(a) {
16
17
  const name = a.positionals[0];
17
18
  const target = a.flags.url || a.flags.target || a.positionals[1];
18
19
  if (!name || !target)
19
- throw new Error('usage: koigrid checks create <name> --url <https://…> [--interval 300] [--contains TEXT] [--max-latency 800]');
20
- const body = { name, target, type: a.flags.type || 'url' };
20
+ throw new Error('usage: koigrid checks create <name> --url <https://…> [--interval 300] [--contains TEXT] [--max-latency 800] [--project <id>]');
21
+ const body = { name, target, type: a.flags.type || 'url', ...proyectoDeFlags(a) };
21
22
  if (a.flags.interval)
22
23
  body.intervalSeconds = Number(a.flags.interval);
23
24
  if (a.flags.method)
@@ -1,11 +1,14 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid config — config/secrets compartida del proyecto (cifrada). Ver docs/CONFIG.md.
3
+ // koigrid config — config/secrets compartida del proyecto (cifrada). Ver docs/products/CONFIG.md.
4
4
  export async function config(a) {
5
+ // --project <id>: el proyecto de la config (un token de toda la organización usaría el Default).
6
+ const proyecto = a.flags.project ? String(a.flags.project) : '';
7
+ const qp = proyecto ? `?projectId=${encodeURIComponent(proyecto)}` : '';
5
8
  const json = !!a.flags.json;
6
9
  const sub = a.sub || 'ls';
7
10
  if (sub === 'ls' || sub === 'list') {
8
- const r = await api('/config');
11
+ const r = await api(`/config${qp}`);
9
12
  const l = r.config || [];
10
13
  return output(l, json, {
11
14
  rows: l.map((x) => ({ key: x.key, value: x.masked })),
@@ -17,18 +20,18 @@ export async function config(a) {
17
20
  const value = a.positionals[1];
18
21
  if (!key || value === undefined)
19
22
  throw new Error('usage: koigrid config set <KEY> <value>');
20
- await api('/config', { method: 'PUT', body: { key, value } });
23
+ await api('/config', { method: 'PUT', body: { key, value, ...(proyecto ? { projectId: proyecto } : {}) } });
21
24
  return console.log(green(`✓ Set ${key}`));
22
25
  }
23
26
  if (sub === 'rm' || sub === 'delete') {
24
27
  const key = a.positionals[0];
25
28
  if (!key)
26
29
  throw new Error('usage: koigrid config rm <KEY>');
27
- await api(`/config/${encodeURIComponent(key)}`, { method: 'DELETE' });
30
+ await api(`/config/${encodeURIComponent(key)}?projectId=${encodeURIComponent(proyecto)}`, { method: 'DELETE' });
28
31
  return console.log(green(`✓ Deleted ${key}`));
29
32
  }
30
33
  if (sub === 'pull') {
31
- const r = await api('/config/pull');
34
+ const r = await api(`/config/pull${qp}`);
32
35
  const c = r.config || {};
33
36
  if (json)
34
37
  return console.log(JSON.stringify(c, null, 2));
@@ -42,7 +45,7 @@ export async function config(a) {
42
45
  // Uso: koigrid config run -- <command> [args…] (como `railway run`)
43
46
  if (!a.passthrough || a.passthrough.length === 0)
44
47
  throw new Error('usage: koigrid config run -- <command> [args…]');
45
- const r = await api('/config/pull');
48
+ const r = await api(`/config/pull${qp}`);
46
49
  const env = { ...process.env, ...(r.config || {}) };
47
50
  const { spawnSync } = await import('node:child_process');
48
51
  const res = spawnSync(a.passthrough[0], a.passthrough.slice(1), { stdio: 'inherit', env });
@@ -1,5 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
+ import { proyectoDeFlags } from '../proyecto.js';
3
4
  // koigrid connect — Connect: broker de credenciales de agente (STS/AssumeRole para agentes).
4
5
  // Un GRANT solo puede intercambiarse por tokens EFÍMEROS acotados; en el env va el grant, no un token largo.
5
6
  // koigrid connect grants (alias: connect ls)
@@ -30,8 +31,7 @@ export async function connect(a) {
30
31
  body.maxTtlSeconds = Number(a.flags['max-ttl']);
31
32
  if (a.flags['max-cost'] !== undefined)
32
33
  body.maxCostCents = Number(a.flags['max-cost']);
33
- if (a.flags.project)
34
- body.projectId = String(a.flags.project);
34
+ Object.assign(body, proyectoDeFlags(a));
35
35
  const r = await api('/connect/grants', { method: 'POST', body });
36
36
  if (json)
37
37
  return console.log(JSON.stringify(r, null, 2));