gencow 0.1.298 → 0.2.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 (169) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/index.js +261 -1447
  3. package/core/package.json +1 -1
  4. package/dashboard/assets/{index-BnBn8uo4.js → index-DYqUzCmS.js} +3 -3
  5. package/dashboard/assets/index-OH2xW1ZG.css +2 -0
  6. package/dashboard/index.html +2 -2
  7. package/docs/packaging.md +14 -4
  8. package/lib/cli-artifact-guard.mjs +53 -3
  9. package/lib/cli-command-runner.d.mts +11 -0
  10. package/lib/cli-dev-runtime.mjs +1 -0
  11. package/lib/cli-project-runtime.mjs +26 -14
  12. package/lib/codegen-command.mjs +16 -0
  13. package/lib/coding-guardrails.mjs +2 -0
  14. package/lib/component-readme.mjs +4 -4
  15. package/lib/dashboard-artifact.mjs +65 -0
  16. package/lib/dashboard-assets.mjs +20 -0
  17. package/lib/db-command.mjs +121 -80
  18. package/lib/db-migration-command-steps.mjs +19 -16
  19. package/lib/db-push-command.mjs +1 -1
  20. package/lib/deploy-codegen-preflight.mjs +1 -0
  21. package/lib/deploy-cron-manifest-diagnostic.mjs +93 -0
  22. package/lib/deploy-failure-diagnostic.mjs +4 -43
  23. package/lib/deploy-route-target-rejection-diagnostic.mjs +43 -0
  24. package/lib/dev-cloud-command.mjs +1 -1
  25. package/lib/dev-local-command.mjs +19 -56
  26. package/lib/document-local-converter.mjs +11 -0
  27. package/lib/jobs-command.mjs +33 -1
  28. package/lib/local-dashboard-plan.mjs +60 -0
  29. package/lib/local-database-commands.mjs +127 -0
  30. package/lib/local-development-migrations.mjs +157 -0
  31. package/lib/local-drizzle-database.config.mjs +10 -0
  32. package/lib/local-runtime-features.mjs +12 -0
  33. package/lib/rag-selection.mjs +7 -0
  34. package/lib/readme-codegen.mjs +2 -2
  35. package/lib/runtime-local-worker.mjs +116 -0
  36. package/lib/runtime-mode.mjs +3 -0
  37. package/lib/standalone-codegen-adapter.mjs +91 -0
  38. package/lib/ts-codegen-import-extension.mjs +228 -19
  39. package/package.json +16 -9
  40. package/runtime/config.mjs +218 -2
  41. package/runtime/dependency-lock.mjs +5 -1
  42. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  43. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  44. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  45. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  46. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  47. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  48. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  49. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  50. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  51. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  52. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  53. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  54. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  55. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  56. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  57. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  58. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  59. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  60. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  61. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  62. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  63. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  64. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  65. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  66. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  67. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  68. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  69. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  70. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  71. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  72. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  73. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  74. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  75. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  76. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  77. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  78. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  79. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  80. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  81. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  82. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  83. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  84. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  85. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  86. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  87. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  88. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  89. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  90. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  91. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  92. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  93. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  94. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  95. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  96. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  97. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  98. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  99. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  100. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  101. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  102. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  103. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  104. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  105. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  106. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  107. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  108. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  109. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  110. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  111. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  112. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  113. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  114. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  115. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  116. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  117. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  118. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  119. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  120. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  121. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  122. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  123. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  124. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  125. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  126. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  127. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  128. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  129. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  130. package/runtime/engine/composition.mjs +325 -0
  131. package/runtime/engine/document-local.mjs +504 -0
  132. package/runtime/engine/graph.json +4134 -0
  133. package/runtime/engine/index.mjs +265 -0
  134. package/runtime/engine/local-postgres-support.mjs +69 -0
  135. package/runtime/engine/local.mjs +3275 -0
  136. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  137. package/runtime/engine/rag.mjs +11 -0
  138. package/runtime/engine/search.mjs +18 -0
  139. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  140. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  141. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  142. package/runtime/framework-migrations/manifest.json +56 -0
  143. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  144. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  145. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  146. package/runtime/runtime-metadata.json +27 -0
  147. package/runtime/tooling.mjs +10549 -10543
  148. package/scripts/bundle-runtime-config.mjs +23 -0
  149. package/scripts/bundle-runtime.mjs +100 -0
  150. package/scripts/bundle-runtime.test.mjs +33 -0
  151. package/scripts/bundle-shared.mjs +3 -0
  152. package/scripts/copy-dashboard.mjs +16 -0
  153. package/scripts/pre-publish-check.mjs +23 -11
  154. package/templateFeature/ai/ai-embedding-result.ts +82 -0
  155. package/templateFeature/ai/ai-facade.ts +24 -7
  156. package/templateFeature/ai/ai-provider.ts +17 -1
  157. package/templateFeature/ai/ai.ts +1 -0
  158. package/templateFeature/ai/manifest.json +4 -3
  159. package/templateFeature/reranker/manifest.json +1 -1
  160. package/templateFeature/reranker/reranker.ts +4 -3
  161. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  162. package/templateFeature/tools/manifest.json +2 -1
  163. package/templateFeature/tools/tools.ts +3 -3
  164. package/dashboard/assets/index-C6-BpKKR.css +0 -2
  165. package/runtime/server.mjs +0 -14320
  166. package/scripts/bundle-server.mjs +0 -223
  167. package/server/config.js +0 -1
  168. package/server/index.js +0 -1
  169. package/server/package.json +0 -6
@@ -1,4 +1,8 @@
1
+ import { resolveLocalRuntimeFeatures } from "./local-runtime-features.mjs";
2
+ import { createLocalDbMigrateCommand } from "./local-database-commands.mjs";
3
+ import { formatRuntimeDiagnostic } from "../runtime/engine/index.mjs";
1
4
  import { execSync } from "child_process";
5
+ import { request as httpRequest } from "node:http";
2
6
  import {
3
7
  cpSync,
4
8
  existsSync,
@@ -28,6 +32,57 @@ import { platformFetch, requireCreds } from "./platform-client.mjs";
28
32
  import { cloudTargetRejectionMessage, prodRetryCommandLine } from "./deploy-app-target.mjs";
29
33
  import { readProjectMetadata, resolveProjectSelection } from "./project-context.mjs";
30
34
 
35
+ // Node's fetch adds browser Fetch Metadata even for a CLI request. Use the
36
+ // native HTTP transport for this loopback-only mutation; the Runtime must keep
37
+ // rejecting browser-originated seed requests.
38
+ function localSeedPost(url) {
39
+ const target = new URL(url);
40
+ if (
41
+ target.protocol !== "http:" || target.hostname !== "127.0.0.1" || target.pathname !== "/_admin/seed" ||
42
+ target.username || target.password || target.search || target.hash
43
+ )
44
+ return Promise.reject(new Error("Invalid local seed endpoint"));
45
+ return new Promise((resolveResponse, reject) => {
46
+ const request = httpRequest(
47
+ { hostname: "127.0.0.1", port: target.port, path: target.pathname,
48
+ method: "POST", headers: { "content-type": "application/json", "content-length": "0" } },
49
+ (response) => {
50
+ const chunks = [];
51
+ response.on("data", (chunk) => chunks.push(chunk));
52
+ response.on("error", reject);
53
+ response.on("aborted", () => reject(new Error("Local seed response interrupted")));
54
+ response.on("end", () => {
55
+ const status = response.statusCode ?? 0;
56
+ const text = Buffer.concat(chunks).toString("utf8");
57
+ resolveResponse({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(text) });
58
+ });
59
+ },
60
+ );
61
+ request.on("error", reject);
62
+ request.end();
63
+ });
64
+ }
65
+
66
+ function localMaintenanceDiagnostic(code, nextAction, dataImpact = "none") {
67
+ return formatRuntimeDiagnostic({ code, stage: "request", capability: "database", servingStarted: "unchanged",
68
+ dataImpact, retryable: false, retryPrecondition: "Settle any current local database owner and inspect prior effects before retrying.",
69
+ nextAction, correlationId: crypto.randomUUID() });
70
+ }
71
+
72
+ function localSeedFailure(data, fallbackCode, dataImpact = "unknown") {
73
+ const safeText = (value, fallback) => typeof value === "string" && value.length <= 400 &&
74
+ !/[\u0000-\u001f\u007f]|(?:https?|postgres(?:ql)?):\/\/|(?:^|\s)\/(?!\/)|\b(?:select|insert|update|delete|truncate|params:)\b/iu.test(value)
75
+ ? value : fallback;
76
+ const code = typeof data?.code === "string" && /^[A-Z][A-Z0-9_]{2,100}$/u.test(data.code) ? data.code : fallbackCode;
77
+ const correlationId = typeof data?.correlationId === "string" && /^[A-Za-z0-9_-]{8,128}$/u.test(data.correlationId)
78
+ ? data.correlationId : crypto.randomUUID();
79
+ return formatRuntimeDiagnostic({ code, stage: "request", capability: "application", servingStarted: "unchanged",
80
+ dataImpact: ["none", "committed", "unknown"].includes(data?.dataImpact) ? data.dataImpact : dataImpact,
81
+ retryable: data?.retryable === true,
82
+ retryPrecondition: safeText(data?.retryPrecondition, "Inspect the local Runtime and any prior seed effects before retrying."),
83
+ nextAction: safeText(data?.nextAction, "Inspect the app state and seed configuration before rerunning gencow db:seed --local."), correlationId });
84
+ }
85
+
31
86
  export function resolveDbCloudTarget(args, gencowJson = null) {
32
87
  let explicitAppId = null;
33
88
  let hasExplicitApp = false;
@@ -166,9 +221,10 @@ function renderDbGenerateHelp(logImpl = log) {
166
221
  logImpl(` ${HINTS_DATA_LOSS_NOTICE}\n`);
167
222
  }
168
223
 
169
- function renderLocalSeedMissingFile({ infoImpl = info, logImpl = log, warnImpl = warn } = {}) {
170
- warnImpl("gencow/seed.ts not found");
171
- infoImpl(`\n ${DIM}Create gencow/seed.ts:${RESET}\n`);
224
+ function renderLocalSeedMissingFile({ infoImpl = info, logImpl = log, warnImpl = warn, rootDir = "gencow" } = {}) {
225
+ const safeRoot = typeof rootDir === "string" && /^(?!\/)(?!.*\.\.)[A-Za-z0-9_./-]{1,160}$/u.test(rootDir) ? rootDir : "configured backend root";
226
+ warnImpl(`${safeRoot}/seed.ts not found`);
227
+ infoImpl(`\n ${DIM}Create ${safeRoot}/seed.ts:${RESET}\n`);
172
228
  logImpl(` ${DIM}import { tasks } from "./schema";${RESET}`);
173
229
  logImpl(` ${DIM}export default async function seed(ctx) {${RESET}`);
174
230
  logImpl(` ${DIM} await ctx.db.insert(tasks).values([${RESET}`);
@@ -191,6 +247,7 @@ export function createDbCommands({
191
247
  sourceRevision,
192
248
  buildEnv,
193
249
  cleanupOldBackups,
250
+ applyLocalMigrationsImpl,
194
251
  createInterfaceImpl,
195
252
  cwdImpl = () => process.cwd(),
196
253
  drizzleKitCmdImpl,
@@ -198,6 +255,7 @@ export function createDbCommands({
198
255
  exitImpl = (code) => process.exit(code),
199
256
  existsSyncImpl = existsSync,
200
257
  fetchImpl = fetch,
258
+ localSeedPostImpl = fetchImpl === globalThis.fetch ? localSeedPost : fetchImpl,
201
259
  isLocalDbTarget,
202
260
  isMonorepo,
203
261
  loadConfig,
@@ -229,6 +287,8 @@ export function createDbCommands({
229
287
  } = {}) {
230
288
  const dbMigrationDependencies = {
231
289
  buildEnv,
290
+ applyLocalMigrationsImpl,
291
+ spawnSyncImpl,
232
292
  cpSyncImpl,
233
293
  createInterfaceImpl,
234
294
  cwdImpl,
@@ -275,7 +335,7 @@ export function createDbCommands({
275
335
  return {
276
336
  async dbReset(...args) {
277
337
  const config = await loadConfig();
278
- const cwd = cwdImpl();
338
+ const cwd = resolveProjectSelection({ allowMissingConfig: true, cwd: cwdImpl(), existsSyncImpl, resolvePathImpl, processEnv }).projectDir;
279
339
  const isLocal = isLocalDbTarget(args);
280
340
 
281
341
  if (!isLocal) {
@@ -293,71 +353,43 @@ export function createDbCommands({
293
353
 
294
354
  let serverAlive = false;
295
355
  try {
296
- const res = await fetchImpl(`http://localhost:${port}/_admin/status`, {
356
+ const response = await fetchImpl(`http://127.0.0.1:${port}/health`, {
297
357
  signal: AbortSignal.timeout(2000),
298
358
  });
299
- serverAlive = res.ok;
359
+ serverAlive = response.ok;
300
360
  } catch {
301
361
  /* ignore */
302
362
  }
303
363
 
304
364
  if (serverAlive) {
305
- infoImpl(`Server detected on :${port} — using API reset (TRUNCATE + seed)`);
365
+ errorImpl(localMaintenanceDiagnostic("RUNTIME_LOCAL_RESET_REQUIRES_STOP", "Stop gencow dev --local, then run gencow db:reset --local."));
306
366
  logImpl("");
307
-
308
- try {
309
- const res = await fetchImpl(`http://localhost:${port}/_admin/reset`, {
310
- method: "POST",
311
- headers: { "Content-Type": "application/json" },
312
- body: JSON.stringify({ confirm: "delete all data" }),
313
- });
314
- const data = await res.json().catch(() => null);
315
- if (data === null) {
316
- errorImpl("Server connection failed: the server response could not be read.");
317
- logImpl("");
318
- return 1;
319
- }
320
-
321
- if (!res.ok) {
322
- renderMaintenanceFailure(data, res.status, {
323
- errorImpl,
324
- infoImpl,
325
- label: "Reset failed",
326
- retryCommand: "gencow db:reset",
327
- impactNote: "verify which tables still contain data before rerunning",
328
- });
329
- logImpl("");
330
- return 1;
331
- }
332
-
333
- successImpl(`TRUNCATE done: ${data.truncated?.length || 0} tables`);
334
- if (data.truncated?.length > 0) {
335
- infoImpl(` ${DIM}${data.truncated.join(", ")}${RESET}`);
336
- }
337
- if (data.seeded) {
338
- successImpl(`Seed completed ✓`);
339
- } else {
340
- infoImpl(`${DIM}No seed.ts found — skipping${RESET}`);
341
- }
342
- } catch (e) {
343
- errorImpl(`Server connection failed: ${e.message}`);
344
- logImpl("");
367
+ return 1;
368
+ } else {
369
+ const env = buildEnv(config, { cwd, processEnv });
370
+ if (
371
+ (await resolveLocalRuntimeFeatures(config, env)).database?.adapter !== "pglite" ||
372
+ /^postgres(?:ql)?:/iu.test(config.db.url)
373
+ ) {
374
+ errorImpl(localMaintenanceDiagnostic("RUNTIME_LOCAL_RESET_UNSUPPORTED", "Use the documented PostgreSQL administration procedure; this local reset supports only PGlite."));
345
375
  return 1;
346
376
  }
347
- } else {
348
377
  const dbPath = resolvePathImpl(cwd, config.db.url);
349
378
  if (existsSyncImpl(dbPath)) {
350
- const backupDir = resolvePathImpl(cwd, ".gencow", "backups");
351
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
352
- const backupPath = resolvePathImpl(backupDir, ts);
353
- mkdirSyncImpl(backupPath, { recursive: true });
354
- cpSyncImpl(dbPath, backupPath, { recursive: true });
355
- successImpl(`Backup created: .gencow/backups/${ts}`);
356
-
357
- cleanupOldBackups(backupDir, 3);
358
-
359
- rmSyncImpl(dbPath, { recursive: true, force: true });
360
- successImpl("DB deleted — restart with gencow dev --local to create a new one");
379
+ try {
380
+ const backupDir = resolvePathImpl(cwd, ".gencow", "backups");
381
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
382
+ const backupPath = resolvePathImpl(backupDir, ts);
383
+ mkdirSyncImpl(backupPath, { recursive: true });
384
+ cpSyncImpl(dbPath, backupPath, { recursive: true });
385
+ successImpl(`Backup created: .gencow/backups/${ts}`);
386
+ cleanupOldBackups(backupDir, 3);
387
+ rmSyncImpl(dbPath, { recursive: true, force: true });
388
+ successImpl("DB deleted — restart with gencow dev --local to create a new one");
389
+ } catch {
390
+ errorImpl(localMaintenanceDiagnostic("RUNTIME_LOCAL_RESET_FAILED", "Inspect the local database and backup before retrying.", "unknown"));
391
+ return 1;
392
+ }
361
393
  } else {
362
394
  infoImpl("DB does not exist yet. Run gencow dev --local to get started.");
363
395
  }
@@ -379,35 +411,39 @@ export function createDbCommands({
379
411
  logImpl(`\n${BOLD}${CYAN}Gencow DB Seed${RESET} ${DIM}(local)${RESET}\n`);
380
412
 
381
413
  try {
382
- const statusRes = await fetchImpl(`http://localhost:${port}/_admin/status`, {
414
+ const statusRes = await fetchImpl(`http://127.0.0.1:${port}/health`, {
383
415
  signal: AbortSignal.timeout(2000),
384
416
  });
385
- if (!statusRes.ok) throw new Error("Server not ready");
417
+ if (!statusRes.ok) {
418
+ errorImpl(localSeedFailure(await statusRes.json().catch(() => null), "RUNTIME_LOCAL_SERVER_STATUS_UNAVAILABLE", "none"));
419
+ return 1;
420
+ }
386
421
  } catch {
387
- errorImpl(`Server not running on :${port}`);
388
- infoImpl(`${DIM}Start the local server first: ${GREEN}gencow dev --local${RESET}`);
422
+ errorImpl(localSeedFailure({ nextAction: "Run gencow dev --local from this app workspace, then retry gencow db:seed --local.",
423
+ retryPrecondition: "Start the local Runtime and wait for it to become ready.", dataImpact: "none" }, "RUNTIME_LOCAL_SERVER_UNREACHABLE", "none"));
389
424
  logImpl("");
390
425
  return 1;
391
426
  }
392
427
 
393
428
  try {
394
- const res = await fetchImpl(`http://localhost:${port}/_admin/seed`, {
429
+ const res = await localSeedPostImpl(`http://127.0.0.1:${port}/_admin/seed`, {
395
430
  method: "POST",
396
431
  headers: { "Content-Type": "application/json" },
397
432
  });
398
433
  const data = await res.json();
399
434
 
400
- if (res.status === 404) {
401
- renderLocalSeedMissingFile({ infoImpl, logImpl, warnImpl });
435
+ if (res.status === 404 && data?.code === "RUNTIME_LOCAL_SEED_NOT_FOUND") {
436
+ errorImpl(localSeedFailure(data, "RUNTIME_LOCAL_SEED_NOT_FOUND", "none"));
437
+ renderLocalSeedMissingFile({ infoImpl, logImpl, warnImpl, rootDir: config.rootDir });
402
438
  return 1;
403
439
  } else if (!res.ok) {
404
- errorImpl(`Seed failed: ${data.error || "Unknown error"}`);
440
+ errorImpl(localSeedFailure(data, "RUNTIME_LOCAL_SEED_FAILED"));
405
441
  return 1;
406
442
  } else {
407
443
  successImpl("Seed completed ✓");
408
444
  }
409
- } catch (e) {
410
- errorImpl(`Server connection failed: ${e.message}`);
445
+ } catch {
446
+ errorImpl(localSeedFailure(null, "RUNTIME_LOCAL_SEED_TRANSPORT_UNAVAILABLE"));
411
447
  return 1;
412
448
  }
413
449
  logImpl("");
@@ -496,7 +532,15 @@ export function createDbCommands({
496
532
 
497
533
  async dbRestore() {
498
534
  const config = await loadConfig();
499
- const cwd = cwdImpl();
535
+ const cwd = resolveProjectSelection({ allowMissingConfig: true, cwd: cwdImpl(), existsSyncImpl, resolvePathImpl, processEnv }).projectDir;
536
+ const env = buildEnv(config, { cwd, processEnv });
537
+ if (
538
+ (await resolveLocalRuntimeFeatures(config, env)).database?.adapter !== "pglite" ||
539
+ /^postgres(?:ql)?:/iu.test(config.db.url)
540
+ ) {
541
+ errorImpl(localMaintenanceDiagnostic("RUNTIME_LOCAL_RESTORE_UNSUPPORTED", "Use the documented PostgreSQL administration procedure; this local restore supports only PGlite."));
542
+ return 1;
543
+ }
500
544
  const backupDir = resolvePathImpl(cwd, ".gencow", "backups");
501
545
  const dbPath = resolvePathImpl(cwd, config.db.url);
502
546
 
@@ -529,12 +573,15 @@ export function createDbCommands({
529
573
  const latest = backups[0];
530
574
  const latestPath = resolvePathImpl(backupDir, latest);
531
575
 
532
- if (existsSyncImpl(dbPath)) {
533
- rmSyncImpl(dbPath, { recursive: true, force: true });
576
+ try {
577
+ if (existsSyncImpl(dbPath)) rmSyncImpl(dbPath, { recursive: true, force: true });
578
+ cpSyncImpl(latestPath, dbPath, { recursive: true });
579
+ successImpl(`Restored from: .gencow/backups/${latest}`);
580
+ infoImpl("Restart with gencow dev --local.");
581
+ } catch {
582
+ errorImpl(localMaintenanceDiagnostic("RUNTIME_LOCAL_RESTORE_FAILED", "Inspect the local database and backup before retrying.", "unknown"));
583
+ return 1;
534
584
  }
535
- cpSyncImpl(latestPath, dbPath, { recursive: true });
536
- successImpl(`Restored from: .gencow/backups/${latest}`);
537
- infoImpl("Restart with gencow dev --local.");
538
585
  logImpl("");
539
586
  },
540
587
 
@@ -595,13 +642,7 @@ export function createDbCommands({
595
642
  successImpl("Migration files generated in the configured migration directory.");
596
643
  },
597
644
 
598
- async dbMigrate() {
599
- const config = await loadConfig();
600
- logImpl(`\n${BOLD}${CYAN}Gencow DB Migrate${RESET}\n`);
601
- infoImpl("Applying pending migrations...");
602
- runInServer("pnpm db:migrate", buildEnv(config));
603
- successImpl("Migrations applied!");
604
- },
645
+ dbMigrate: createLocalDbMigrateCommand(dbMigrationDependencies),
605
646
 
606
647
  async dbStudio() {
607
648
  infoImpl(`Drizzle Studio is ${BOLD}coming soon${RESET}.`);
@@ -18,6 +18,12 @@ import {
18
18
  import { BOLD, CYAN, DIM, RED, RESET } from "./output.mjs";
19
19
  import { askConfirmation } from "./confirm-gate.mjs";
20
20
  import { emitMigrationAdvisories, extractMigrationAdvisories } from "./migration-advisory.mjs";
21
+ import { runtimeDiagnostic } from "../runtime/engine/index.mjs";
22
+ import { localMigrationDiagnostic } from "./local-development-migrations.mjs";
23
+ import { runLocalDatabaseCommand } from "./local-database-commands.mjs";
24
+ import { configuredLocalDatabaseAdapter } from "./local-runtime-features.mjs";
25
+ import { isActionableMigrationDiagnostic } from "./migration-diagnostic.mjs";
26
+ import { resolveProjectSelection } from "./project-context.mjs";
21
27
 
22
28
  function explicitAppRequested(args) {
23
29
  return args.includes("--app") || args.includes("-a");
@@ -80,7 +86,7 @@ export async function promptDbPushConfirm(appId, createInterfaceImpl, plain = fa
80
86
  return answer.trim().toLowerCase() === "yes";
81
87
  }
82
88
 
83
- export function handleLocalMigrationCommand({
89
+ export async function handleLocalMigrationCommand({
84
90
  deps,
85
91
  args,
86
92
  command,
@@ -95,39 +101,36 @@ export function handleLocalMigrationCommand({
95
101
  emitFailure(buildClientUserFixableDiagnostic("MIGRATION_CHECK_CLOUD_ONLY", correlationId()));
96
102
  return true;
97
103
  }
104
+ const projectDir = resolveProjectSelection({ allowMissingConfig: true, cwd: deps.cwdImpl(),
105
+ existsSyncImpl: deps.existsSyncImpl, resolvePathImpl: deps.resolvePathImpl, processEnv: deps.processEnv }).projectDir;
106
+ const localDeps = { ...deps, cwdImpl: () => projectDir };
98
107
  const { envPath } = resolveBackendEnvFile(config, {
99
- cwd: deps.cwdImpl(),
108
+ cwd: projectDir,
100
109
  existsSyncImpl: deps.existsSyncImpl,
101
110
  resolvePathImpl: deps.resolvePathImpl,
102
111
  warnImpl: deps.warnImpl,
103
112
  });
104
- const hasDb = deps.hasLocalDatabaseUrl({
113
+ const hasDbUrl = deps.hasLocalDatabaseUrl({
105
114
  envPath,
106
115
  existsSyncImpl: deps.existsSyncImpl,
107
116
  infoImpl: deps.infoImpl,
108
117
  processEnv: deps.processEnv,
109
118
  readFileSyncImpl: deps.readFileSyncImpl,
110
119
  });
120
+ const adapter = configuredLocalDatabaseAdapter(config);
121
+ const hasDb = adapter === "postgres" || (adapter !== "pglite" && hasDbUrl);
111
122
  if (!jsonMode) {
112
123
  const targetDb = hasDb ? "local PG" : "local fallback: PGlite";
113
124
  deps.logImpl(`\n${BOLD}${CYAN}Gencow DB Push${RESET} ${DIM}(${targetDb})${RESET}\n`);
114
- deps.infoImpl("Pushing schema.ts → database (no migration files)...");
125
+ deps.infoImpl(hasDb ? "Pushing schema.ts → database (no migration files)..." : "Generating and applying local PGlite migrations...");
115
126
  }
116
127
  try {
117
- const env = deps.buildEnv(config);
118
- const childOptions = jsonMode ? { infoImpl: () => {}, stdio: "pipe" } : undefined;
119
- if (hasDb) {
120
- deps.runInServer("pnpm db:push --force", env, childOptions);
121
- } else {
122
- // Drizzle Kit cannot attach PGlite's packaged pgvector/pg_trgm modules.
123
- // Generate the same desired-state migration, then apply it through the
124
- // runtime connection that owns those extensions.
125
- deps.runInServer("pnpm db:generate", env, childOptions);
126
- deps.runInServer("bun src/local-pglite-migrate.ts", env, childOptions);
127
- }
128
+ await runLocalDatabaseCommand({ command, config, deps: localDeps, jsonMode });
128
129
  } catch (error) {
129
130
  if (!jsonMode) throw error;
130
- emitFailure(buildLocalExecutionFailureDiagnostic(correlationId()));
131
+ const diagnostic = localMigrationDiagnostic(error) ?? runtimeDiagnostic(error);
132
+ emitFailure(diagnostic ? { diagnosticVersion: 1, ok: false, command, target: "local", ...diagnostic }
133
+ : isActionableMigrationDiagnostic(error?.diagnostic) ? error.diagnostic : buildLocalExecutionFailureDiagnostic(correlationId()));
131
134
  return true;
132
135
  }
133
136
  if (jsonMode) {
@@ -203,7 +203,7 @@ function createDbMigrationCommand(deps, command) {
203
203
  }
204
204
 
205
205
  if (
206
- handleLocalMigrationCommand({
206
+ await handleLocalMigrationCommand({
207
207
  deps,
208
208
  args,
209
209
  command,
@@ -165,6 +165,7 @@ export async function prepareDeployCodegenArtifacts({
165
165
  cwd,
166
166
  diagnosticsColors,
167
167
  logImpl,
168
+ includeStandalone: false,
168
169
  outDir: deployCodegenDir,
169
170
  publishDir: deployCodegenClientDir,
170
171
  serverPublishDir: deployCodegenServerDir,
@@ -0,0 +1,93 @@
1
+ import { formatDeployCorrelationId } from "./deploy-correlation-diagnostic.mjs";
2
+
3
+ const CRON_MANIFEST_CODE = "CRON_MANIFEST_INVALID";
4
+ // Must match the platform's stable rule codes (CRON_MANIFEST_RULE_CODES). An unknown code falls back to the generic text.
5
+ const RULE_CODES = new Set([
6
+ "manifest_structure_invalid",
7
+ "manifest_version_unsupported",
8
+ "source_hash_mismatch",
9
+ "bundle_path_unsafe",
10
+ "cron_name_empty",
11
+ "cron_name_duplicate",
12
+ "cron_pattern_empty",
13
+ "cron_action_empty",
14
+ "cron_expression_invalid",
15
+ "cron_seconds_field_not_allowed",
16
+ "cron_interval_too_short",
17
+ "legacy_cron_not_parseable",
18
+ ]);
19
+ const MUTATION_IMPACTS = new Set(["NONE", "ROLLED_BACK", "APPLIED", "UNKNOWN"]);
20
+ const SERVING_IMPACTS = new Set(["PRESERVED", "CHANGED", "NOT_APPLICABLE", "UNKNOWN"]);
21
+ const OPERATION_STATES = new Set(["PENDING", "FAILED", "BLOCKED", "COMPLETED"]);
22
+ const SECRET_PATTERN = /(?:postgres(?:ql)?:\/\/|password|secret|token|authorization|api[_-]?key|bearer\s)/iu;
23
+ const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/u;
24
+
25
+ function safeLine(value, maxLength = 240) {
26
+ if (typeof value !== "string") return null;
27
+ const normalized = value.trim();
28
+ if (
29
+ !normalized ||
30
+ normalized.length > maxLength ||
31
+ CONTROL_PATTERN.test(normalized) ||
32
+ SECRET_PATTERN.test(normalized)
33
+ ) {
34
+ return null;
35
+ }
36
+ return normalized;
37
+ }
38
+
39
+ // Reads the typed rule from the platform's self-service diagnostic. Any field that does not match the contract makes the
40
+ // whole rule unusable, so the caller falls back to the generic rendering instead of printing a partial diagnosis.
41
+ function readCronRuleDiagnostic(responseBody, contract) {
42
+ const selfService = responseBody?.diagnostic?.selfService;
43
+ if (!selfService || typeof selfService !== "object") return null;
44
+ const { stateImpact, retry, action, reason } = selfService;
45
+ const fix =
46
+ Array.isArray(action?.prerequisites) && action.prerequisites.length === 1
47
+ ? safeLine(action.prerequisites[0])
48
+ : null;
49
+ const summary = safeLine(reason?.summary);
50
+ const condition = safeLine(retry?.condition, 500);
51
+ if (
52
+ selfService.diagnosticVersion !== 1 ||
53
+ selfService.code !== CRON_MANIFEST_CODE ||
54
+ selfService.stage !== contract.stage ||
55
+ selfService.correlationId !== contract.correlationId ||
56
+ action?.kind !== contract.userAction ||
57
+ !RULE_CODES.has(reason?.code) ||
58
+ !summary ||
59
+ !fix?.startsWith("Fix: ") ||
60
+ !MUTATION_IMPACTS.has(stateImpact?.mutation) ||
61
+ !SERVING_IMPACTS.has(stateImpact?.incumbentServing) ||
62
+ !OPERATION_STATES.has(stateImpact?.operationState) ||
63
+ retry?.policy !== "AFTER_FIX" ||
64
+ !condition
65
+ ) {
66
+ return null;
67
+ }
68
+ return { stateImpact, condition, summary, fix };
69
+ }
70
+
71
+ /**
72
+ * Renders a cron manifest rejection from its typed rule: the cron name, the rule, the exact fix, and the state impact.
73
+ * Returns null when the response carries no valid typed rule, so the generic rendering stays in charge.
74
+ */
75
+ export function renderCronManifestFailureLines(responseBody, contract) {
76
+ if (contract?.code !== CRON_MANIFEST_CODE) return null;
77
+ const rule = readCronRuleDiagnostic(responseBody, contract);
78
+ if (!rule) return null;
79
+ const lines = [
80
+ `Deploy failed: ${safeLine(responseBody.error) ?? "Deploy cron configuration is invalid."}`,
81
+ `Code: ${contract.code}`,
82
+ `Stage: ${contract.stage}`,
83
+ `Database mutation: ${rule.stateImpact.mutation}`,
84
+ `Incumbent serving: ${rule.stateImpact.incumbentServing}`,
85
+ `Operation state: ${rule.stateImpact.operationState}`,
86
+ `Retry policy: AFTER_FIX — ${rule.condition}`,
87
+ `${rule.summary} ${rule.fix}`,
88
+ ];
89
+ const correlationLine = formatDeployCorrelationId(contract.correlationId);
90
+ if (correlationLine) lines.push(correlationLine);
91
+ lines.push("Next action: EDIT_AND_CHECK");
92
+ return lines;
93
+ }
@@ -1,4 +1,5 @@
1
1
  import { appendDeclarationFailureState } from "./deploy-declaration-diagnostic.mjs";
2
+ import { renderCronManifestFailureLines } from "./deploy-cron-manifest-diagnostic.mjs";
2
3
  import { MIGRATION_NEXT_ACTION_KINDS, MIGRATION_RETRY_POLICIES } from "@gencow/migration-contract";
3
4
 
4
5
  import { APP_DELETE_OPERATION_PATTERN } from "./app-response-error.mjs";
@@ -6,6 +7,7 @@ import { formatDeployFailureNextAction } from "./deploy-failure-next-action.mjs"
6
7
  import { formatDeployCorrelationId } from "./deploy-correlation-diagnostic.mjs";
7
8
  import { formatDeploymentOperationPhase } from "./deployment-operation-poll.mjs";
8
9
  import { isPlatformUnavailableStatus, renderPlatformUnavailableLines } from "./deploy-platform-unavailable-diagnostic.mjs";
10
+ import { readRouteTargetRejections } from "./deploy-route-target-rejection-diagnostic.mjs";
9
11
  import { credentialEnvNameOf, formatCliAuthFailureLines, readTypedCliAuthDiagnostic } from "./prod-create-auth-diagnostic.mjs";
10
12
 
11
13
  export { credentialEnvNameOf };
@@ -180,49 +182,6 @@ function readRoutePrepareRootCauseClass(value, code, stage) {
180
182
  : null;
181
183
  }
182
184
 
183
- // Revalidate every route-target rejection field at the CLI boundary. A
184
- // malformed or mismatched response is omitted rather than shown as diagnosis.
185
- const ROUTE_TARGET_PHASES = new Set(["prepare", "commit", "tombstone"]);
186
- const ROUTE_TARGET_KIND_LABELS = {
187
- edge: "edge",
188
- gateway: "gateway",
189
- static_origin: "static-origin",
190
- analytics_collector: "analytics-collector",
191
- domain_authorizer: "domain-authorizer",
192
- };
193
- const ROUTE_TARGET_REASON_CODE = /^[A-Z][A-Z0-9_]{2,95}$/u;
194
- const MAX_ROUTE_TARGET_REJECTIONS = 8;
195
- const ROUTE_TARGET_REJECTION_CODES = new Set([
196
- "ROUTE_CONVERGENCE_BLOCKED",
197
- "ROUTE_CONVERGENCE_TIMEOUT",
198
- "DEPLOYMENT_EXECUTOR_ROUTE_PREPARE_BLOCKED",
199
- "DEPLOYMENT_EXECUTOR_DEFER_BUDGET_EXHAUSTED",
200
- ]);
201
-
202
- function readRouteTargetRejections(value, code, stage) {
203
- if (!ROUTE_TARGET_REJECTION_CODES.has(code) || stage !== "route" || !Array.isArray(value)) return [];
204
- const entries = [];
205
- for (const entry of value) {
206
- if (
207
- !entry ||
208
- typeof entry !== "object" ||
209
- Object.keys(entry).length !== 4 ||
210
- !ROUTE_TARGET_PHASES.has(entry.phase) ||
211
- !Object.hasOwn(ROUTE_TARGET_KIND_LABELS, entry.targetKind) ||
212
- typeof entry.reasonCode !== "string" ||
213
- !ROUTE_TARGET_REASON_CODE.test(entry.reasonCode) ||
214
- !Number.isInteger(entry.attempts) ||
215
- entry.attempts < 0 ||
216
- entry.attempts > 100
217
- ) {
218
- return [];
219
- }
220
- entries.push(
221
- `Route target rejection: ${ROUTE_TARGET_KIND_LABELS[entry.targetKind]} ${entry.phase} ${entry.reasonCode} (attempts ${entry.attempts})`,
222
- );
223
- }
224
- return entries.slice(0, MAX_ROUTE_TARGET_REJECTIONS);
225
- }
226
185
 
227
186
  function appendRootCauseLines(lines, contract, statusCommand) {
228
187
  lines.push(...contract.routeTargetRejectionLines);
@@ -581,6 +540,8 @@ export function renderDeployFailureDiagnosticLines(responseBody, statusText, opt
581
540
  return formatCliAuthFailureLines(typedAuth, { credentialEnvName: options.credentialEnvName ?? null });
582
541
  }
583
542
  const contract = readDeployFailureContract(responseBody, options.expectedAppName);
543
+ const cronManifestLines = renderCronManifestFailureLines(responseBody, contract);
544
+ if (cronManifestLines) return cronManifestLines;
584
545
  const fallbackMessage = safeText(statusText, 120) ?? "Request failed";
585
546
  if (!contract) {
586
547
  const structuredFields =
@@ -0,0 +1,43 @@
1
+ // Route-target rejection lines: every field is revalidated at the CLI boundary. A malformed or
2
+ // mismatched response yields no lines rather than a partial diagnosis.
3
+ const ROUTE_TARGET_PHASES = new Set(["prepare", "commit", "tombstone"]);
4
+ const ROUTE_TARGET_KIND_LABELS = {
5
+ edge: "edge",
6
+ gateway: "gateway",
7
+ static_origin: "static-origin",
8
+ analytics_collector: "analytics-collector",
9
+ domain_authorizer: "domain-authorizer",
10
+ };
11
+ const ROUTE_TARGET_REASON_CODE = /^[A-Z][A-Z0-9_]{2,95}$/u;
12
+ const MAX_ROUTE_TARGET_REJECTIONS = 8;
13
+ const ROUTE_TARGET_REJECTION_CODES = new Set([
14
+ "ROUTE_CONVERGENCE_BLOCKED",
15
+ "ROUTE_CONVERGENCE_TIMEOUT",
16
+ "DEPLOYMENT_EXECUTOR_ROUTE_PREPARE_BLOCKED",
17
+ "DEPLOYMENT_EXECUTOR_DEFER_BUDGET_EXHAUSTED",
18
+ ]);
19
+
20
+ export function readRouteTargetRejections(value, code, stage) {
21
+ if (!ROUTE_TARGET_REJECTION_CODES.has(code) || stage !== "route" || !Array.isArray(value)) return [];
22
+ const entries = [];
23
+ for (const entry of value) {
24
+ if (
25
+ !entry ||
26
+ typeof entry !== "object" ||
27
+ Object.keys(entry).length !== 4 ||
28
+ !ROUTE_TARGET_PHASES.has(entry.phase) ||
29
+ !Object.hasOwn(ROUTE_TARGET_KIND_LABELS, entry.targetKind) ||
30
+ typeof entry.reasonCode !== "string" ||
31
+ !ROUTE_TARGET_REASON_CODE.test(entry.reasonCode) ||
32
+ !Number.isInteger(entry.attempts) ||
33
+ entry.attempts < 0 ||
34
+ entry.attempts > 100
35
+ ) {
36
+ return [];
37
+ }
38
+ entries.push(
39
+ `Route target rejection: ${ROUTE_TARGET_KIND_LABELS[entry.targetKind]} ${entry.phase} ${entry.reasonCode} (attempts ${entry.attempts})`,
40
+ );
41
+ }
42
+ return entries.slice(0, MAX_ROUTE_TARGET_REJECTIONS);
43
+ }
@@ -262,7 +262,7 @@ export function createDevCloudCommand(deps) {
262
262
  }
263
263
 
264
264
  try {
265
- await deps.generateApiTsImpl(config, { cwd: projectDir });
265
+ await deps.generateApiTsImpl(config, { cwd: projectDir, includeStandalone: false });
266
266
  } catch {
267
267
  /* ignore */
268
268
  }