@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
@@ -4,42 +4,100 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.prewarmAppWorkspace = exports.runCodegenTool = void 0;
7
+ exports.runCodegenReady = runCodegenReady;
7
8
  exports.createRunCodegenTool = createRunCodegenTool;
8
9
  const node_fs_1 = require("node:fs");
9
10
  const promises_1 = require("node:fs/promises");
10
11
  const node_path_1 = __importDefault(require("node:path"));
11
- const zod_1 = require("zod");
12
+ const harness_1 = require("@agentic-kit/harness");
12
13
  const app_workspace_1 = require("../app-workspace");
13
14
  Object.defineProperty(exports, "prewarmAppWorkspace", { enumerable: true, get: function () { return app_workspace_1.prewarmAppWorkspace; } });
15
+ const failure_1 = require("../failure");
14
16
  const graphql_http_1 = require("../graphql-http");
15
17
  const host_1 = require("../host");
16
- const env_file_1 = require("../provision-database/env-file");
18
+ const ready_1 = require("../ready");
17
19
  const barrels_1 = require("../run-codegen/barrels");
18
20
  const endpoints_1 = require("../run-codegen/endpoints");
19
- const RunCodegenZod = zod_1.z.object({});
20
- function fail(message, extra) {
21
- return {
22
- content: [{ type: 'text', text: message }],
23
- details: { ...extra, success: false, message },
24
- };
21
+ const RunCodegenZod = (0, harness_1.strictObject)('the input', {});
22
+ function fail(failure, extra) {
23
+ return (0, failure_1.failedResult)(failure, { ...extra, success: false, message: (0, failure_1.failureText)(failure) });
25
24
  }
25
+ const failed = (message) => ({ code: 'failed', message });
26
26
  const FETCH_RESET_RE = /Failed to fetch schema|Connection reset|ECONNRESET|socket hang up/i;
27
27
  // A refusal is an answer, not a dropped connection: retrying it only waits.
28
28
  const REFUSED_RE = /\b403\b|Forbidden|ACCESS_SUSPENDED/;
29
- // Read the binding provision_database wrote to the project .env. The
30
- // API_ENDPOINT pin identifies which backend owns the binding — it wins over
31
- // the app's current backend config, matching context.ts data-plane precedence.
32
- async function readProjectEnv(cwd) {
33
- try {
34
- const env = (0, env_file_1.readEnv)(await (0, promises_1.readFile)(node_path_1.default.join(cwd, '.env'), 'utf8'));
29
+ // A composed marker that is not sound: the template fixups would rewrite a composed app, so nothing runs.
30
+ const invalidApp = (reason) => ({
31
+ code: 'failed',
32
+ message: reason,
33
+ hint: 'Recompose packages/app, or remove the marker to use the template flow.',
34
+ });
35
+ // The app's steps before codegen, when the host lets run_codegen prepare the app.
36
+ function appStepsOf(app, scaffolded) {
37
+ if (app.kind === 'composed') {
38
+ 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."];
39
+ }
40
+ return [
41
+ scaffolded
42
+ ? "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."
43
+ : "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.",
44
+ ];
45
+ }
46
+ /**
47
+ * The endpoints codegen reads, from the API endpoint the session trusts: never from an API_ENDPOINT pin in the
48
+ * project's .env, since the schema at the endpoint decides the code that lands in the project.
49
+ */
50
+ const planesOf = (context) => (0, endpoints_1.derivePlaneEndpoints)(context.controlApiEndpoint, context.databaseName);
51
+ // The app data plane endpoint codegen reads: the per-database api host.
52
+ const appEndpointOf = (context) => planesOf(context)?.app;
53
+ /** What the plan says before any app step: the generator is the project's own code, which runs as the person. */
54
+ 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.";
55
+ // A host that prepares no app runs codegen only in an app that is there and installed.
56
+ function noApp(context, message, hint) {
57
+ const appEndpoint = appEndpointOf(context);
58
+ return { code: 'app-missing', message, hint, ...(appEndpoint ? { context: { appEndpoint } } : {}) };
59
+ }
60
+ /**
61
+ * What run_codegen checks before it changes anything: the project's database
62
+ * on the data plane (codegen reads the app's own API, as the Preview does), by
63
+ * name, and the app in packages/app. Its API endpoint is the .env pin when
64
+ * there is one, as the data plane resolves it. A host that prepares no app
65
+ * (`prewarmApp: false`) needs an app there, installed when it is composed.
66
+ */
67
+ async function runCodegenReady(cwd) {
68
+ const ready = await (0, ready_1.projectReady)(cwd, 'data');
69
+ if (ready.kind === 'failed')
70
+ return ready;
71
+ const appDir = node_path_1.default.join(cwd, 'packages', 'app');
72
+ const app = (0, app_workspace_1.detectAppKind)(appDir);
73
+ if (app.kind === 'invalid')
74
+ return { kind: 'failed', failure: invalidApp(app.reason) };
75
+ if (!ready.value.databaseName) {
35
76
  return {
36
- databaseName: env.DATABASE_NAME?.trim() || undefined,
37
- apiEndpoint: env.API_ENDPOINT?.trim() || undefined,
77
+ kind: 'failed',
78
+ failure: {
79
+ code: 'missing-credentials',
80
+ message: 'DATABASE_NAME is missing from .env, and the backend reported no name for the database.',
81
+ hint: "Add DATABASE_NAME with the database's name to .env, then call again.",
82
+ calls: [(0, failure_1.suggest)('run_codegen', {}, 'Generate the SDK once DATABASE_NAME is in .env')],
83
+ },
38
84
  };
39
85
  }
40
- catch {
41
- return {};
86
+ const preparesApp = (0, host_1.getHost)().prewarmApp !== false;
87
+ const scaffolded = (0, node_fs_1.existsSync)(node_path_1.default.join(appDir, 'package.json'));
88
+ if (!preparesApp && !scaffolded) {
89
+ return {
90
+ kind: 'failed',
91
+ 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.'),
92
+ };
42
93
  }
94
+ if (!preparesApp && app.kind === 'composed' && !(0, app_workspace_1.composedInstallComplete)(appDir)) {
95
+ return {
96
+ kind: 'failed',
97
+ 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."),
98
+ };
99
+ }
100
+ return { kind: 'ok', value: { context: ready.value, app, preparesApp, notes: [PROJECT_CODEGEN, ...(preparesApp ? appStepsOf(app, scaffolded) : [])] } };
43
101
  }
44
102
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
45
103
  // Ask the app API itself; a 403 from codegen alone could be anything.
@@ -62,7 +120,7 @@ function codegenCommand(appDir, composed) {
62
120
  // ("Failed to fetch schema: Connection reset"), which is transient — a retry
63
121
  // almost always clears it. Re-run the whole generate (it rebuilds all targets)
64
122
  // up to `attempts` times, only on a fetch/reset failure; any other failure is
65
- // real and returned immediately (CODEGEN-RETRY-001).
123
+ // real and returned immediately.
66
124
  async function runCodegenWithRetry(appDir, env, exec, composed, attempts = 4) {
67
125
  const sdk = node_path_1.default.join(appDir, 'src', 'graphql', 'sdk');
68
126
  const { cmd, args } = codegenCommand(appDir, composed);
@@ -88,21 +146,31 @@ function createRunCodegenTool(exec = app_workspace_1.run) {
88
146
  return {
89
147
  name: 'run_codegen',
90
148
  label: 'Run codegen',
91
- 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.",
92
- 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.',
149
+ 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. " +
150
+ "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; " +
151
+ 'a composed app (packages/app/.constructive/compose.json) installs from its own lockfile only when its packages are missing. ' +
152
+ '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.',
153
+ promptSnippet: "run_codegen: regenerate the typed SDK of the project's app after schema changes. Gated.",
93
154
  parameters: RunCodegenZod,
155
+ effect: 'write',
94
156
  async execute(_params, ctx) {
95
157
  const started = Date.now();
96
158
  const since = (t) => Date.now() - t;
97
159
  const cwd = ctx.cwd;
160
+ const ready = await runCodegenReady(cwd);
161
+ if (ready.kind === 'failed') {
162
+ const appEndpoint = ready.failure.code === 'app-missing' ? ready.failure.context?.appEndpoint : undefined;
163
+ return fail(ready.failure, appEndpoint ? { appEndpoint } : undefined);
164
+ }
165
+ const { databaseName: dbName } = ready.value.context;
166
+ const { preparesApp } = ready.value;
98
167
  const appDir = node_path_1.default.join(cwd, 'packages', 'app');
99
168
  // A prewarm provision_database started may still be installing; let it
100
169
  // finish so this run's install never races it.
101
170
  await (0, app_workspace_1.settlePrewarm)(cwd);
102
171
  const app = (0, app_workspace_1.detectAppKind)(appDir);
103
- if (app.kind === 'invalid') {
104
- return fail(`${app.reason} Recompose packages/app, or remove the marker to use the template flow.`);
105
- }
172
+ if (app.kind === 'invalid')
173
+ return fail(invalidApp(app.reason));
106
174
  const composed = app.kind === 'composed';
107
175
  const appKind = composed ? 'composed' : 'template';
108
176
  const timings = {
@@ -120,57 +188,49 @@ function createRunCodegenTool(exec = app_workspace_1.run) {
120
188
  codegenAttempts,
121
189
  timings: { ...timings, totalMs: since(started) },
122
190
  });
123
- // Materialize packages/app deterministically if it isn't there yet — this
124
- // replaces the flaky `pgpm init` scaffold step (PGPM-001). When
125
- // provision_database prewarmed it, this no-ops.
126
- if (!composed) {
191
+ // Materialize packages/app if it isn't there yet. When provision_database
192
+ // prewarmed it, this no-ops.
193
+ if (preparesApp && !composed) {
127
194
  const t = Date.now();
128
195
  const scaffold = await (0, app_workspace_1.ensureAppScaffold)(cwd, exec);
129
196
  timings.scaffoldMs = since(t);
130
- if (!scaffold.ok) {
131
- return fail(scaffold.out, stepDetails());
132
- }
133
- }
134
- const { databaseName: dbName, apiEndpoint: envApiEndpoint } = await readProjectEnv(cwd);
135
- if (!dbName) {
136
- return fail('DATABASE_NAME missing from .env — provision the database first, then re-run.');
197
+ if (!scaffold.ok)
198
+ return fail(failed(scaffold.out), stepDetails());
137
199
  }
138
- const host = (0, host_1.getHost)();
139
- const apiEndpoint = envApiEndpoint || host.backendConfig()?.apiEndpoint;
140
- if (!apiEndpoint)
141
- return fail((0, host_1.noBackendReason)(host.signInHint));
142
- const planes = (0, endpoints_1.derivePlaneEndpoints)(apiEndpoint, dbName);
200
+ const planes = planesOf(ready.value.context);
143
201
  // The dev server reads .env.local (NEXT_PUBLIC_DB_NAME + per-DB endpoint
144
202
  // overrides so it doesn't fall back to localhost vhosts on a remote
145
203
  // backend); the codegen config reads process.env (passed directly below).
146
- try {
147
- await (0, promises_1.writeFile)(node_path_1.default.join(appDir, '.env.local'), (0, endpoints_1.envLocalContent)(dbName, planes));
148
- }
149
- catch (err) {
150
- return fail(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`);
204
+ if (preparesApp) {
205
+ try {
206
+ await (0, promises_1.writeFile)(node_path_1.default.join(appDir, '.env.local'), (0, endpoints_1.envLocalContent)(dbName, planes));
207
+ }
208
+ catch (err) {
209
+ return fail(failed(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`));
210
+ }
151
211
  }
152
212
  const tInstall = Date.now();
153
- if (composed) {
213
+ if (!preparesApp) {
214
+ installed = false;
215
+ }
216
+ else if (composed) {
154
217
  const install = await (0, app_workspace_1.ensureComposedInstall)(cwd, exec);
155
218
  timings.installMs = since(tInstall);
156
219
  installed = install.installed;
157
- if (!install.ok) {
158
- return fail(install.out, stepDetails());
159
- }
220
+ if (!install.ok)
221
+ return fail(failed(install.out), stepDetails());
160
222
  }
161
223
  else {
162
- // Hoist the graphql override to the root workspace (PNPM-GRAPHQL-OVERRIDE-001)
163
- // and pin codegen to latest (TS-001) before the single clean install. When
164
- // prewarmed by provision_database these are idempotent and the install is a
165
- // fast no-op; otherwise this is the first install (PNPM-BUILDS-001).
224
+ // Hoist the graphql override to the root workspace and pin codegen to
225
+ // latest before the single clean install. When prewarmed these are
226
+ // idempotent and the install is a fast no-op.
166
227
  await (0, app_workspace_1.ensureWorkspaceConfig)(cwd);
167
228
  await (0, app_workspace_1.pinCodegenLatest)(appDir);
168
229
  const install = await exec('pnpm', ['install', '--no-frozen-lockfile'], cwd);
169
230
  timings.installMs = since(tInstall);
170
231
  installed = true;
171
- if (!install.ok && !app_workspace_1.IGNORED_BUILDS_RE.test(install.out)) {
172
- return fail(`pnpm install failed:\n${install.out}`, stepDetails());
173
- }
232
+ if (!install.ok && !app_workspace_1.IGNORED_BUILDS_RE.test(install.out))
233
+ return fail(failed(`pnpm install failed:\n${install.out}`), stepDetails());
174
234
  }
175
235
  const tCodegen = Date.now();
176
236
  const codegen = await runCodegenWithRetry(appDir, {
@@ -183,23 +243,26 @@ function createRunCodegenTool(exec = app_workspace_1.run) {
183
243
  // A refused introspection may be the database itself: deleted or
184
244
  // suspended databases answer ACCESS_SUSPENDED on every app API.
185
245
  if (REFUSED_RE.test(codegen.out) && planes && (await isDatabaseUnavailable(planes.app))) {
186
- 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' });
246
+ return fail({
247
+ code: 'database-unavailable',
248
+ 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.`,
249
+ }, { ...stepDetails(), code: 'database-unavailable' });
187
250
  }
188
- // A reset that survives every internal retry is a backend OUTAGE, not a code
189
- // or install problem — re-running run_codegen cannot fix it. Say so explicitly
190
- // so the agent marks sdk-codegen `blocked` instead of looping the tool to the
191
- // time cap (CODEGEN-OUTAGE-001 / THRASH-001).
251
+ // A reset that survives every internal retry is a backend outage, not a code
252
+ // or install problem, and running the tool again cannot fix it: say so, so
253
+ // an agent stops instead of looping on the tool.
192
254
  if (FETCH_RESET_RE.test(codegen.out)) {
193
- return fail('codegen failed: BACKEND OUTAGE — the Constructive backend reset the connection ' +
194
- 'during schema introspection, and it stayed down across every internal retry. ' +
195
- 'This is an EXTERNAL outage, not a code or install problem; re-running run_codegen ' +
196
- 'will NOT fix it. Check backend reachability once, then report the blocker and wait ' +
197
- 'for the backend to recover. Do NOT loop on run_codegen (THRASH-001).\n\n' +
198
- codegen.out, stepDetails());
255
+ return fail({
256
+ code: 'backend-unreachable',
257
+ message: 'codegen failed: the Constructive backend reset the connection during schema introspection, and it stayed down ' +
258
+ 'across every retry. The backend is down; this is not a code or install problem, and running it again now will ' +
259
+ 'not fix it. Check that the backend answers once, then wait for it to recover.\n\n' +
260
+ codegen.out,
261
+ }, stepDetails());
199
262
  }
200
- return fail(`codegen failed:\n${codegen.out}`, stepDetails());
263
+ return fail(failed(`codegen failed:\n${codegen.out}`), stepDetails());
201
264
  }
202
- // Normalize directory barrels so Turbopack can resolve them (TURBOPACK-BARREL-001).
265
+ // Normalize directory barrels so Turbopack can resolve them.
203
266
  // Only directories that exist are rewritten, so a config without an admin
204
267
  // target leaves nothing pointing at one.
205
268
  const tBarrels = Date.now();
@@ -210,13 +273,18 @@ function createRunCodegenTool(exec = app_workspace_1.run) {
210
273
  // index.ts means codegen had no schema to generate against.
211
274
  const appSdk = node_path_1.default.join(sdkRoot, 'app');
212
275
  const generatedSubmodules = ['hooks', 'orm', 'types'].filter((sub) => (0, node_fs_1.existsSync)(node_path_1.default.join(appSdk, sub)));
213
- const message = generatedSubmodules.length > 0
214
- ? `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`
215
- : `Codegen ran, but no app submodules (hooks/orm/types) were generated — the database may have no entity tables yet. Normalized ${barrelsRewritten} barrel file(s).`;
276
+ if (generatedSubmodules.length === 0) {
277
+ return fail({
278
+ code: 'failed',
279
+ 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).`,
280
+ hint: 'Create tables first, then generate the SDK again.',
281
+ }, { barrelsRewritten, generatedSubmodules, ...stepDetails() });
282
+ }
283
+ const message = `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`;
216
284
  return {
217
285
  content: [{ type: 'text', text: message }],
218
286
  details: {
219
- success: generatedSubmodules.length > 0,
287
+ success: true,
220
288
  message,
221
289
  barrelsRewritten,
222
290
  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 {};