@agentic-kit/db-tools 0.12.47 → 0.13.1

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 (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
@@ -1,37 +1,94 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { rm, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { z } from 'zod';
5
- import { detectAppKind, ensureAppScaffold, ensureComposedInstall, ensureWorkspaceConfig, IGNORED_BUILDS_RE, pinCodegenLatest, prewarmAppWorkspace, run, settlePrewarm, } from '../app-workspace';
4
+ import { strictObject } from '@agentic-kit/harness';
5
+ import { composedInstallComplete, detectAppKind, ensureAppScaffold, ensureComposedInstall, ensureWorkspaceConfig, IGNORED_BUILDS_RE, pinCodegenLatest, prewarmAppWorkspace, run, settlePrewarm, } from '../app-workspace';
6
+ import { failedResult, failureText, suggest } from '../failure';
6
7
  import { classifyBackendErrors, postGraphQL } from '../graphql-http';
7
- import { getHost, noBackendReason } from '../host';
8
- import { readEnv } from '../provision-database/env-file';
8
+ import { getHost } from '../host';
9
+ import { projectReady } from '../ready';
9
10
  import { normalizeSdkBarrels } from '../run-codegen/barrels';
10
11
  import { codegenEndpointEnv, derivePlaneEndpoints, envLocalContent } from '../run-codegen/endpoints';
11
- const RunCodegenZod = z.object({});
12
- function fail(message, extra) {
13
- return {
14
- content: [{ type: 'text', text: message }],
15
- details: { ...extra, success: false, message },
16
- };
12
+ const RunCodegenZod = strictObject('the input', {});
13
+ function fail(failure, extra) {
14
+ return failedResult(failure, { ...extra, success: false, message: failureText(failure) });
17
15
  }
16
+ const failed = (message) => ({ code: 'failed', message });
18
17
  const FETCH_RESET_RE = /Failed to fetch schema|Connection reset|ECONNRESET|socket hang up/i;
19
18
  // A refusal is an answer, not a dropped connection: retrying it only waits.
20
19
  const REFUSED_RE = /\b403\b|Forbidden|ACCESS_SUSPENDED/;
21
- // Read the binding provision_database wrote to the project .env. The
22
- // API_ENDPOINT pin identifies which backend owns the binding — it wins over
23
- // the app's current backend config, matching context.ts data-plane precedence.
24
- async function readProjectEnv(cwd) {
25
- try {
26
- const env = readEnv(await readFile(path.join(cwd, '.env'), 'utf8'));
20
+ // A composed marker that is not sound: the template fixups would rewrite a composed app, so nothing runs.
21
+ const invalidApp = (reason) => ({
22
+ code: 'failed',
23
+ message: reason,
24
+ hint: 'Recompose packages/app, or remove the marker to use the template flow.',
25
+ });
26
+ // The app's steps before codegen, when the host lets run_codegen prepare the app.
27
+ function appStepsOf(app, scaffolded) {
28
+ if (app.kind === 'composed') {
29
+ return ["This writes the app's endpoints to packages/app/.env.local and installs the app's packages from its lockfile when they are missing, then generates the SDK."];
30
+ }
31
+ return [
32
+ scaffolded
33
+ ? "This writes the app's endpoints to packages/app/.env.local, sets the workspace's package settings, moves the code generator to its latest version and installs the packages, then generates the SDK."
34
+ : "This creates packages/app from the app template, writes the app's endpoints to packages/app/.env.local, sets the workspace's package settings and installs the packages, then generates the SDK.",
35
+ ];
36
+ }
37
+ /**
38
+ * The endpoints codegen reads, from the API endpoint the session trusts: never from an API_ENDPOINT pin in the
39
+ * project's .env, since the schema at the endpoint decides the code that lands in the project.
40
+ */
41
+ const planesOf = (context) => derivePlaneEndpoints(context.controlApiEndpoint, context.databaseName);
42
+ // The app data plane endpoint codegen reads: the per-database api host.
43
+ const appEndpointOf = (context) => planesOf(context)?.app;
44
+ /** What the plan says before any app step: the generator is the project's own code, which runs as the person. */
45
+ const PROJECT_CODEGEN = "This runs the project's own code generator in packages/app: graphql-codegen with the project's graphql-codegen.config.ts, or the app's own codegen script. That is code from the project, and it runs on this machine as you.";
46
+ // A host that prepares no app runs codegen only in an app that is there and installed.
47
+ function noApp(context, message, hint) {
48
+ const appEndpoint = appEndpointOf(context);
49
+ return { code: 'app-missing', message, hint, ...(appEndpoint ? { context: { appEndpoint } } : {}) };
50
+ }
51
+ /**
52
+ * What run_codegen checks before it changes anything: the project's database
53
+ * on the data plane (codegen reads the app's own API, as the Preview does), by
54
+ * name, and the app in packages/app. Its API endpoint is the .env pin when
55
+ * there is one, as the data plane resolves it. A host that prepares no app
56
+ * (`prewarmApp: false`) needs an app there, installed when it is composed.
57
+ */
58
+ export async function runCodegenReady(cwd) {
59
+ const ready = await projectReady(cwd, 'data');
60
+ if (ready.kind === 'failed')
61
+ return ready;
62
+ const appDir = path.join(cwd, 'packages', 'app');
63
+ const app = detectAppKind(appDir);
64
+ if (app.kind === 'invalid')
65
+ return { kind: 'failed', failure: invalidApp(app.reason) };
66
+ if (!ready.value.databaseName) {
27
67
  return {
28
- databaseName: env.DATABASE_NAME?.trim() || undefined,
29
- apiEndpoint: env.API_ENDPOINT?.trim() || undefined,
68
+ kind: 'failed',
69
+ failure: {
70
+ code: 'missing-credentials',
71
+ message: 'DATABASE_NAME is missing from .env, and the backend reported no name for the database.',
72
+ hint: "Add DATABASE_NAME with the database's name to .env, then call again.",
73
+ calls: [suggest('run_codegen', {}, 'Generate the SDK once DATABASE_NAME is in .env')],
74
+ },
30
75
  };
31
76
  }
32
- catch {
33
- return {};
77
+ const preparesApp = getHost().prewarmApp !== false;
78
+ const scaffolded = existsSync(path.join(appDir, 'package.json'));
79
+ if (!preparesApp && !scaffolded) {
80
+ return {
81
+ kind: 'failed',
82
+ failure: noApp(ready.value, 'There is no app in packages/app to generate the SDK into, and this host does not create one, so nothing was written.', 'Generate the SDK from the endpoint in the result, or add an app in packages/app, then call again.'),
83
+ };
34
84
  }
85
+ if (!preparesApp && app.kind === 'composed' && !composedInstallComplete(appDir)) {
86
+ return {
87
+ kind: 'failed',
88
+ failure: noApp(ready.value, 'The app in packages/app has no installed packages, and this host does not install them, so nothing was written.', "Install the app's packages from its lockfile, then call again."),
89
+ };
90
+ }
91
+ return { kind: 'ok', value: { context: ready.value, app, preparesApp, notes: [PROJECT_CODEGEN, ...(preparesApp ? appStepsOf(app, scaffolded) : [])] } };
35
92
  }
36
93
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
94
  // Ask the app API itself; a 403 from codegen alone could be anything.
@@ -54,7 +111,7 @@ function codegenCommand(appDir, composed) {
54
111
  // ("Failed to fetch schema: Connection reset"), which is transient — a retry
55
112
  // almost always clears it. Re-run the whole generate (it rebuilds all targets)
56
113
  // up to `attempts` times, only on a fetch/reset failure; any other failure is
57
- // real and returned immediately (CODEGEN-RETRY-001).
114
+ // real and returned immediately.
58
115
  async function runCodegenWithRetry(appDir, env, exec, composed, attempts = 4) {
59
116
  const sdk = path.join(appDir, 'src', 'graphql', 'sdk');
60
117
  const { cmd, args } = codegenCommand(appDir, composed);
@@ -80,21 +137,31 @@ export function createRunCodegenTool(exec = run) {
80
137
  return {
81
138
  name: 'run_codegen',
82
139
  label: 'Run codegen',
83
- description: "Generate the typed GraphQL SDK for the project's Next.js app (packages/app). Runs the exact deterministic sequence — scaffold packages/app from the constructive-app template if it doesn't exist yet, hoist the graphql override to the root workspace so a single grafast resolves, pin codegen to latest, do one clean install, run codegen (retrying transient backend connection resets), and normalize SDK barrels for Turbopack. A composed app (packages/app/.constructive/compose.json) skips the scaffold and those fixups: it installs from its own lockfile only when node_modules is missing and runs its local codegen. Run AFTER provisioning the database and creating schema; it scaffolds packages/app itself, so no separate `pgpm init` step is needed. The scaffold + install are usually prewarmed during provision_database, so this is fast.",
84
- promptSnippet: 'run_codegen: scaffold packages/app (if missing) + regenerate the typed SDK (workspace-config + clean install + codegen-with-retry + barrel-normalize; a composed app keeps its lockfile and local codegen). Run after schema changes. Gated.',
140
+ description: "Generate the typed GraphQL SDK of the project's app (packages/app) from the database: run the project's own code generator (its graphql-codegen.config.ts, or the app's codegen script), retrying transient backend connection resets, and normalize the SDK barrels. " +
141
+ "Where the host prepares the app, it first creates packages/app from the app template when it is missing, writes the app's endpoints to packages/app/.env.local and installs the packages; " +
142
+ 'a composed app (packages/app/.constructive/compose.json) installs from its own lockfile only when its packages are missing. ' +
143
+ 'Where the host prepares no app, it runs the codegen of the app that is there and installs nothing, and answers app-missing, with the endpoint to generate from, when there is no app. Run after the schema changes.',
144
+ promptSnippet: "run_codegen: regenerate the typed SDK of the project's app after schema changes. Gated.",
85
145
  parameters: RunCodegenZod,
146
+ effect: 'write',
86
147
  async execute(_params, ctx) {
87
148
  const started = Date.now();
88
149
  const since = (t) => Date.now() - t;
89
150
  const cwd = ctx.cwd;
151
+ const ready = await runCodegenReady(cwd);
152
+ if (ready.kind === 'failed') {
153
+ const appEndpoint = ready.failure.code === 'app-missing' ? ready.failure.context?.appEndpoint : undefined;
154
+ return fail(ready.failure, appEndpoint ? { appEndpoint } : undefined);
155
+ }
156
+ const { databaseName: dbName } = ready.value.context;
157
+ const { preparesApp } = ready.value;
90
158
  const appDir = path.join(cwd, 'packages', 'app');
91
159
  // A prewarm provision_database started may still be installing; let it
92
160
  // finish so this run's install never races it.
93
161
  await settlePrewarm(cwd);
94
162
  const app = detectAppKind(appDir);
95
- if (app.kind === 'invalid') {
96
- return fail(`${app.reason} Recompose packages/app, or remove the marker to use the template flow.`);
97
- }
163
+ if (app.kind === 'invalid')
164
+ return fail(invalidApp(app.reason));
98
165
  const composed = app.kind === 'composed';
99
166
  const appKind = composed ? 'composed' : 'template';
100
167
  const timings = {
@@ -112,57 +179,49 @@ export function createRunCodegenTool(exec = run) {
112
179
  codegenAttempts,
113
180
  timings: { ...timings, totalMs: since(started) },
114
181
  });
115
- // Materialize packages/app deterministically if it isn't there yet — this
116
- // replaces the flaky `pgpm init` scaffold step (PGPM-001). When
117
- // provision_database prewarmed it, this no-ops.
118
- if (!composed) {
182
+ // Materialize packages/app if it isn't there yet. When provision_database
183
+ // prewarmed it, this no-ops.
184
+ if (preparesApp && !composed) {
119
185
  const t = Date.now();
120
186
  const scaffold = await ensureAppScaffold(cwd, exec);
121
187
  timings.scaffoldMs = since(t);
122
- if (!scaffold.ok) {
123
- return fail(scaffold.out, stepDetails());
124
- }
125
- }
126
- const { databaseName: dbName, apiEndpoint: envApiEndpoint } = await readProjectEnv(cwd);
127
- if (!dbName) {
128
- return fail('DATABASE_NAME missing from .env — provision the database first, then re-run.');
188
+ if (!scaffold.ok)
189
+ return fail(failed(scaffold.out), stepDetails());
129
190
  }
130
- const host = getHost();
131
- const apiEndpoint = envApiEndpoint || host.backendConfig()?.apiEndpoint;
132
- if (!apiEndpoint)
133
- return fail(noBackendReason(host.signInHint));
134
- const planes = derivePlaneEndpoints(apiEndpoint, dbName);
191
+ const planes = planesOf(ready.value.context);
135
192
  // The dev server reads .env.local (NEXT_PUBLIC_DB_NAME + per-DB endpoint
136
193
  // overrides so it doesn't fall back to localhost vhosts on a remote
137
194
  // backend); the codegen config reads process.env (passed directly below).
138
- try {
139
- await writeFile(path.join(appDir, '.env.local'), envLocalContent(dbName, planes));
140
- }
141
- catch (err) {
142
- return fail(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`);
195
+ if (preparesApp) {
196
+ try {
197
+ await writeFile(path.join(appDir, '.env.local'), envLocalContent(dbName, planes));
198
+ }
199
+ catch (err) {
200
+ return fail(failed(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`));
201
+ }
143
202
  }
144
203
  const tInstall = Date.now();
145
- if (composed) {
204
+ if (!preparesApp) {
205
+ installed = false;
206
+ }
207
+ else if (composed) {
146
208
  const install = await ensureComposedInstall(cwd, exec);
147
209
  timings.installMs = since(tInstall);
148
210
  installed = install.installed;
149
- if (!install.ok) {
150
- return fail(install.out, stepDetails());
151
- }
211
+ if (!install.ok)
212
+ return fail(failed(install.out), stepDetails());
152
213
  }
153
214
  else {
154
- // Hoist the graphql override to the root workspace (PNPM-GRAPHQL-OVERRIDE-001)
155
- // and pin codegen to latest (TS-001) before the single clean install. When
156
- // prewarmed by provision_database these are idempotent and the install is a
157
- // fast no-op; otherwise this is the first install (PNPM-BUILDS-001).
215
+ // Hoist the graphql override to the root workspace and pin codegen to
216
+ // latest before the single clean install. When prewarmed these are
217
+ // idempotent and the install is a fast no-op.
158
218
  await ensureWorkspaceConfig(cwd);
159
219
  await pinCodegenLatest(appDir);
160
220
  const install = await exec('pnpm', ['install', '--no-frozen-lockfile'], cwd);
161
221
  timings.installMs = since(tInstall);
162
222
  installed = true;
163
- if (!install.ok && !IGNORED_BUILDS_RE.test(install.out)) {
164
- return fail(`pnpm install failed:\n${install.out}`, stepDetails());
165
- }
223
+ if (!install.ok && !IGNORED_BUILDS_RE.test(install.out))
224
+ return fail(failed(`pnpm install failed:\n${install.out}`), stepDetails());
166
225
  }
167
226
  const tCodegen = Date.now();
168
227
  const codegen = await runCodegenWithRetry(appDir, {
@@ -175,23 +234,26 @@ export function createRunCodegenTool(exec = run) {
175
234
  // A refused introspection may be the database itself: deleted or
176
235
  // suspended databases answer ACCESS_SUSPENDED on every app API.
177
236
  if (REFUSED_RE.test(codegen.out) && planes && (await isDatabaseUnavailable(planes.app))) {
178
- return fail(`codegen failed: the app database "${dbName}" is unavailable (the backend answered ACCESS_SUSPENDED: it was deleted or is suspended). Re-running run_codegen won't help until it is restored.`, { ...stepDetails(), code: 'database-unavailable' });
237
+ return fail({
238
+ code: 'database-unavailable',
239
+ message: `codegen failed: the app database "${dbName}" is unavailable: it was deleted or is suspended. Running it again won't help until it is restored.`,
240
+ }, { ...stepDetails(), code: 'database-unavailable' });
179
241
  }
180
- // A reset that survives every internal retry is a backend OUTAGE, not a code
181
- // or install problem — re-running run_codegen cannot fix it. Say so explicitly
182
- // so the agent marks sdk-codegen `blocked` instead of looping the tool to the
183
- // time cap (CODEGEN-OUTAGE-001 / THRASH-001).
242
+ // A reset that survives every internal retry is a backend outage, not a code
243
+ // or install problem, and running the tool again cannot fix it: say so, so
244
+ // an agent stops instead of looping on the tool.
184
245
  if (FETCH_RESET_RE.test(codegen.out)) {
185
- return fail('codegen failed: BACKEND OUTAGE — the Constructive backend reset the connection ' +
186
- 'during schema introspection, and it stayed down across every internal retry. ' +
187
- 'This is an EXTERNAL outage, not a code or install problem; re-running run_codegen ' +
188
- 'will NOT fix it. Check backend reachability once, then report the blocker and wait ' +
189
- 'for the backend to recover. Do NOT loop on run_codegen (THRASH-001).\n\n' +
190
- codegen.out, stepDetails());
246
+ return fail({
247
+ code: 'backend-unreachable',
248
+ message: 'codegen failed: the Constructive backend reset the connection during schema introspection, and it stayed down ' +
249
+ 'across every retry. The backend is down; this is not a code or install problem, and running it again now will ' +
250
+ 'not fix it. Check that the backend answers once, then wait for it to recover.\n\n' +
251
+ codegen.out,
252
+ }, stepDetails());
191
253
  }
192
- return fail(`codegen failed:\n${codegen.out}`, stepDetails());
254
+ return fail(failed(`codegen failed:\n${codegen.out}`), stepDetails());
193
255
  }
194
- // Normalize directory barrels so Turbopack can resolve them (TURBOPACK-BARREL-001).
256
+ // Normalize directory barrels so Turbopack can resolve them.
195
257
  // Only directories that exist are rewritten, so a config without an admin
196
258
  // target leaves nothing pointing at one.
197
259
  const tBarrels = Date.now();
@@ -202,13 +264,18 @@ export function createRunCodegenTool(exec = run) {
202
264
  // index.ts means codegen had no schema to generate against.
203
265
  const appSdk = path.join(sdkRoot, 'app');
204
266
  const generatedSubmodules = ['hooks', 'orm', 'types'].filter((sub) => existsSync(path.join(appSdk, sub)));
205
- const message = generatedSubmodules.length > 0
206
- ? `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`
207
- : `Codegen ran, but no app submodules (hooks/orm/types) were generated — the database may have no entity tables yet. Normalized ${barrelsRewritten} barrel file(s).`;
267
+ if (generatedSubmodules.length === 0) {
268
+ return fail({
269
+ code: 'failed',
270
+ message: `Codegen ran, but no app submodules (hooks/orm/types) were generated — the database may have no entity tables yet. Normalized ${barrelsRewritten} barrel file(s).`,
271
+ hint: 'Create tables first, then generate the SDK again.',
272
+ }, { barrelsRewritten, generatedSubmodules, ...stepDetails() });
273
+ }
274
+ const message = `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`;
208
275
  return {
209
276
  content: [{ type: 'text', text: message }],
210
277
  details: {
211
- success: generatedSubmodules.length > 0,
278
+ success: true,
212
279
  message,
213
280
  barrelsRewritten,
214
281
  generatedSubmodules,
@@ -1,6 +1,8 @@
1
1
  import { type ConfirmPreviewTable, type HarnessTool } from '@agentic-kit/harness';
2
+ import type { BlueprintDefinition } from 'node-type-registry';
2
3
  import { z } from 'zod';
3
4
  import type { ProjectContext } from '../context';
5
+ import { type Result } from '../failure';
4
6
  export type TemplateDetails = {
5
7
  success: boolean;
6
8
  message: string;
@@ -23,6 +25,8 @@ type TemplateTable = {
23
25
  relationCount: number;
24
26
  };
25
27
  type TemplateInfo = {
28
+ id: string;
29
+ version: string | null;
26
30
  displayName: string;
27
31
  description: string | null;
28
32
  categories: string[];
@@ -36,19 +40,38 @@ export type CreateTemplatePreview = {
36
40
  tables: ConfirmPreviewTable[];
37
41
  };
38
42
  export declare function createTemplatePreviewTables(context: ProjectContext, blueprintName: string | undefined): Promise<CreateTemplatePreview>;
39
- declare const ListTemplatesZod: z.ZodObject<{}, z.core.$strip>;
43
+ /** What update_template and delete_template check before they change anything: the project, and the template. */
44
+ export declare function templateReady(params: {
45
+ templateName: string;
46
+ }, cwd: string): Promise<Result<{
47
+ context: ProjectContext;
48
+ templateId: string;
49
+ }>>;
50
+ declare const ListTemplatesZod: z.ZodObject<{}, z.core.$strict>;
40
51
  export declare const listTemplatesTool: HarnessTool<typeof ListTemplatesZod, ListTemplatesDetails>;
41
52
  declare const CreateTemplateZod: z.ZodObject<{
42
53
  displayName: z.ZodString;
43
54
  blueprintName: z.ZodOptional<z.ZodString>;
44
55
  description: z.ZodOptional<z.ZodString>;
45
56
  categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
46
- }, z.core.$strip>;
57
+ }, z.core.$strict>;
47
58
  export declare const createTemplateTool: HarnessTool<typeof CreateTemplateZod, CreateTemplateDetails>;
48
59
  declare const ApplyTemplateZod: z.ZodObject<{
49
60
  templateName: z.ZodString;
50
61
  nameOverride: z.ZodOptional<z.ZodString>;
51
- }, z.core.$strip>;
62
+ }, z.core.$strict>;
63
+ type ApplyTemplateParams = z.infer<typeof ApplyTemplateZod>;
64
+ /**
65
+ * What apply_template checks before it changes anything: an owned project,
66
+ * the template, and none of its tables in the project yet.
67
+ */
68
+ export declare function applyTemplateReady(params: ApplyTemplateParams, cwd: string): Promise<Result<{
69
+ context: ProjectContext & {
70
+ ownerId: string;
71
+ };
72
+ templateId: string;
73
+ definition: BlueprintDefinition;
74
+ }>>;
52
75
  export declare const applyTemplateTool: HarnessTool<typeof ApplyTemplateZod, TemplateDetails>;
53
76
  declare const UpdateTemplateZod: z.ZodObject<{
54
77
  templateName: z.ZodString;
@@ -58,14 +81,14 @@ declare const UpdateTemplateZod: z.ZodObject<{
58
81
  categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
59
82
  tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
60
83
  visibility: z.ZodOptional<z.ZodEnum<{
61
- private: "private";
62
84
  public: "public";
85
+ private: "private";
63
86
  }>>;
64
- }, z.core.$strip>;
65
- }, z.core.$strip>;
87
+ }, z.core.$strict>;
88
+ }, z.core.$strict>;
66
89
  export declare const updateTemplateTool: HarnessTool<typeof UpdateTemplateZod, TemplateDetails>;
67
90
  declare const DeleteTemplateZod: z.ZodObject<{
68
91
  templateName: z.ZodString;
69
- }, z.core.$strip>;
92
+ }, z.core.$strict>;
70
93
  export declare const deleteTemplateTool: HarnessTool<typeof DeleteTemplateZod, TemplateDetails>;
71
94
  export {};