@agentic-kit/db-tools 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 (131) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +138 -0
  3. package/app-workspace.d.ts +16 -0
  4. package/app-workspace.js +145 -0
  5. package/context.d.ts +62 -0
  6. package/context.js +282 -0
  7. package/db-probe.d.ts +30 -0
  8. package/db-probe.js +50 -0
  9. package/esm/app-workspace.d.ts +16 -0
  10. package/esm/app-workspace.js +134 -0
  11. package/esm/context.d.ts +62 -0
  12. package/esm/context.js +270 -0
  13. package/esm/db-probe.d.ts +30 -0
  14. package/esm/db-probe.js +47 -0
  15. package/esm/host.d.ts +115 -0
  16. package/esm/host.js +23 -0
  17. package/esm/index.d.ts +20 -0
  18. package/esm/index.js +52 -0
  19. package/esm/policy/add-policies-to-table.d.ts +26 -0
  20. package/esm/policy/add-policies-to-table.js +66 -0
  21. package/esm/policy/provision-helpers.d.ts +38 -0
  22. package/esm/policy/provision-helpers.js +50 -0
  23. package/esm/provision-database/credential.d.ts +14 -0
  24. package/esm/provision-database/credential.js +19 -0
  25. package/esm/provision-database/env-file.d.ts +37 -0
  26. package/esm/provision-database/env-file.js +85 -0
  27. package/esm/provision-database/manifest.d.ts +10 -0
  28. package/esm/provision-database/manifest.js +48 -0
  29. package/esm/provision-database/pg-fixups.d.ts +16 -0
  30. package/esm/provision-database/pg-fixups.js +132 -0
  31. package/esm/provision-database/preset-match.d.ts +13 -0
  32. package/esm/provision-database/preset-match.js +66 -0
  33. package/esm/provision-database/presets.d.ts +4 -0
  34. package/esm/provision-database/presets.js +13 -0
  35. package/esm/provision-database/request-database.d.ts +61 -0
  36. package/esm/provision-database/request-database.js +130 -0
  37. package/esm/provision-database/resolve.d.ts +27 -0
  38. package/esm/provision-database/resolve.js +49 -0
  39. package/esm/records/meta.d.ts +41 -0
  40. package/esm/records/meta.js +167 -0
  41. package/esm/run-codegen/barrels.d.ts +3 -0
  42. package/esm/run-codegen/barrels.js +48 -0
  43. package/esm/run-codegen/endpoints.d.ts +8 -0
  44. package/esm/run-codegen/endpoints.js +46 -0
  45. package/esm/schema-resolve.d.ts +23 -0
  46. package/esm/schema-resolve.js +69 -0
  47. package/esm/tool-schema.d.ts +3 -0
  48. package/esm/tool-schema.js +10 -0
  49. package/esm/tools/add-policies.d.ts +24 -0
  50. package/esm/tools/add-policies.js +94 -0
  51. package/esm/tools/add-records.d.ts +18 -0
  52. package/esm/tools/add-records.js +122 -0
  53. package/esm/tools/add-relation-schema.d.ts +29 -0
  54. package/esm/tools/add-relation-schema.js +56 -0
  55. package/esm/tools/add-relation.d.ts +10 -0
  56. package/esm/tools/add-relation.js +91 -0
  57. package/esm/tools/create-api-key.d.ts +25 -0
  58. package/esm/tools/create-api-key.js +214 -0
  59. package/esm/tools/describe-schema.d.ts +19 -0
  60. package/esm/tools/describe-schema.js +130 -0
  61. package/esm/tools/manage-entity-types.d.ts +40 -0
  62. package/esm/tools/manage-entity-types.js +201 -0
  63. package/esm/tools/mutations.d.ts +35 -0
  64. package/esm/tools/mutations.js +230 -0
  65. package/esm/tools/provision-blueprint.d.ts +21 -0
  66. package/esm/tools/provision-blueprint.js +109 -0
  67. package/esm/tools/provision-database.d.ts +18 -0
  68. package/esm/tools/provision-database.js +260 -0
  69. package/esm/tools/run-codegen.d.ts +12 -0
  70. package/esm/tools/run-codegen.js +137 -0
  71. package/esm/tools/templates.d.ts +71 -0
  72. package/esm/tools/templates.js +331 -0
  73. package/host.d.ts +115 -0
  74. package/host.js +28 -0
  75. package/index.d.ts +20 -0
  76. package/index.js +76 -0
  77. package/package.json +49 -0
  78. package/policy/add-policies-to-table.d.ts +26 -0
  79. package/policy/add-policies-to-table.js +71 -0
  80. package/policy/provision-helpers.d.ts +38 -0
  81. package/policy/provision-helpers.js +58 -0
  82. package/provision-database/credential.d.ts +14 -0
  83. package/provision-database/credential.js +22 -0
  84. package/provision-database/env-file.d.ts +37 -0
  85. package/provision-database/env-file.js +91 -0
  86. package/provision-database/manifest.d.ts +10 -0
  87. package/provision-database/manifest.js +56 -0
  88. package/provision-database/pg-fixups.d.ts +16 -0
  89. package/provision-database/pg-fixups.js +170 -0
  90. package/provision-database/preset-match.d.ts +13 -0
  91. package/provision-database/preset-match.js +70 -0
  92. package/provision-database/presets.d.ts +4 -0
  93. package/provision-database/presets.js +17 -0
  94. package/provision-database/request-database.d.ts +61 -0
  95. package/provision-database/request-database.js +134 -0
  96. package/provision-database/resolve.d.ts +27 -0
  97. package/provision-database/resolve.js +53 -0
  98. package/records/meta.d.ts +41 -0
  99. package/records/meta.js +172 -0
  100. package/run-codegen/barrels.d.ts +3 -0
  101. package/run-codegen/barrels.js +54 -0
  102. package/run-codegen/endpoints.d.ts +8 -0
  103. package/run-codegen/endpoints.js +51 -0
  104. package/schema-resolve.d.ts +23 -0
  105. package/schema-resolve.js +75 -0
  106. package/tool-schema.d.ts +3 -0
  107. package/tool-schema.js +13 -0
  108. package/tools/add-policies.d.ts +24 -0
  109. package/tools/add-policies.js +97 -0
  110. package/tools/add-records.d.ts +18 -0
  111. package/tools/add-records.js +125 -0
  112. package/tools/add-relation-schema.d.ts +29 -0
  113. package/tools/add-relation-schema.js +60 -0
  114. package/tools/add-relation.d.ts +10 -0
  115. package/tools/add-relation.js +94 -0
  116. package/tools/create-api-key.d.ts +25 -0
  117. package/tools/create-api-key.js +220 -0
  118. package/tools/describe-schema.d.ts +19 -0
  119. package/tools/describe-schema.js +133 -0
  120. package/tools/manage-entity-types.d.ts +40 -0
  121. package/tools/manage-entity-types.js +206 -0
  122. package/tools/mutations.d.ts +35 -0
  123. package/tools/mutations.js +233 -0
  124. package/tools/provision-blueprint.d.ts +21 -0
  125. package/tools/provision-blueprint.js +112 -0
  126. package/tools/provision-database.d.ts +18 -0
  127. package/tools/provision-database.js +266 -0
  128. package/tools/run-codegen.d.ts +12 -0
  129. package/tools/run-codegen.js +141 -0
  130. package/tools/templates.d.ts +71 -0
  131. package/tools/templates.js +335 -0
@@ -0,0 +1,109 @@
1
+ import { BlueprintZod, expandBlueprintDefaults, filterInternalPolicies, } from '@agentic-kit/harness';
2
+ import { resolveProjectContext } from '../context';
3
+ function formatText(name, details) {
4
+ if (details.error)
5
+ return `Failed to provision "${name}": ${details.error}`;
6
+ const lines = [`Created ${details.created} table${details.created === 1 ? '' : 's'} from "${name}":`];
7
+ for (const table of details.tables) {
8
+ const parts = [`${table.fields.length} field${table.fields.length === 1 ? '' : 's'}`];
9
+ if (table.relationCount > 0) {
10
+ parts.push(`${table.relationCount} relation${table.relationCount === 1 ? '' : 's'}`);
11
+ }
12
+ if (table.policies.length > 0) {
13
+ parts.push(`policies: ${table.policies.map((policy) => policy.replace(/^Authz/, '')).join(', ')}`);
14
+ }
15
+ lines.push(` - ${table.name} (${parts.join(', ')})`);
16
+ }
17
+ return lines.join('\n');
18
+ }
19
+ export const provisionBlueprintTool = {
20
+ name: 'provision_blueprint',
21
+ label: 'Provision blueprint',
22
+ description: 'Create one or more related tables (with fields, RLS policies, and relations) in the project database from a blueprint definition. Always put related tables in a SINGLE call so relations are created together.',
23
+ promptSnippet: 'provision_blueprint: create new tables from scratch in a single call (fields + policies + relations). Call describe_schema first.',
24
+ parameters: BlueprintZod,
25
+ async execute(params, ctx) {
26
+ const empty = { created: 0, total: 0, tables: [], error: null };
27
+ const resolved = await resolveProjectContext(ctx.cwd);
28
+ if (!resolved.context) {
29
+ return { content: [{ type: 'text', text: resolved.reason }], details: empty };
30
+ }
31
+ const { modules, databaseId, schemaId, ownerId } = resolved.context;
32
+ if (!ownerId) {
33
+ return {
34
+ content: [{ type: 'text', text: 'Not authenticated (missing OWNER_ID in .env).' }],
35
+ details: empty,
36
+ };
37
+ }
38
+ const definition = expandBlueprintDefaults(params.definition);
39
+ const uniqueName = `${params.name}_${Date.now()}`;
40
+ try {
41
+ const createResult = await modules.blueprint
42
+ .create({
43
+ data: {
44
+ ownerId,
45
+ databaseId,
46
+ name: uniqueName,
47
+ displayName: params.name,
48
+ description: params.description,
49
+ definition,
50
+ },
51
+ select: { id: true, name: true },
52
+ })
53
+ .unwrap();
54
+ const blueprintId = createResult.createBlueprint?.blueprint?.id;
55
+ if (!blueprintId)
56
+ throw new Error('Failed to create blueprint');
57
+ const constructResult = await modules.mutation
58
+ .constructBlueprint({ input: { blueprintId, schemaId } }, { select: { result: true } })
59
+ .unwrap();
60
+ const result = constructResult.constructBlueprint?.result;
61
+ if (!result) {
62
+ const constructions = await modules.blueprintConstruction
63
+ .findMany({
64
+ where: { blueprintId: { equalTo: blueprintId } },
65
+ orderBy: ['ID_DESC'],
66
+ first: 1,
67
+ select: { status: true, errorDetails: true },
68
+ })
69
+ .unwrap();
70
+ const error = constructions?.blueprintConstructions?.nodes?.[0]?.errorDetails ?? 'Unknown error';
71
+ const details = {
72
+ created: 0,
73
+ total: params.definition.tables.length,
74
+ tables: [],
75
+ error: typeof error === 'string' ? error : JSON.stringify(error),
76
+ };
77
+ return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
78
+ }
79
+ const relations = params.definition.relations ?? [];
80
+ const details = {
81
+ created: params.definition.tables.length,
82
+ total: params.definition.tables.length,
83
+ tables: params.definition.tables.map((t) => ({
84
+ name: t.table_name,
85
+ fields: (t.fields ?? []).map((f) => ({
86
+ name: f.name,
87
+ type: f.type,
88
+ isRequired: f.is_required ?? false,
89
+ defaultValue: f.default ?? null,
90
+ })),
91
+ policies: filterInternalPolicies(t.policies.map((p) => p.$type)),
92
+ relationCount: relations.filter((r) => r.source_table === t.table_name).length,
93
+ })),
94
+ error: null,
95
+ };
96
+ return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
97
+ }
98
+ catch (err) {
99
+ const message = err instanceof Error ? err.message : 'Failed to provision blueprint';
100
+ const details = {
101
+ created: 0,
102
+ total: params.definition.tables.length,
103
+ tables: [],
104
+ error: message,
105
+ };
106
+ return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
107
+ }
108
+ },
109
+ };
@@ -0,0 +1,18 @@
1
+ import type { HarnessTool } from '@agentic-kit/harness';
2
+ import { z } from 'zod';
3
+ declare const ProvisionDatabaseZod: z.ZodObject<{
4
+ database_name: z.ZodString;
5
+ reprovision: z.ZodOptional<z.ZodBoolean>;
6
+ }, z.core.$strip>;
7
+ export type ProvisionDatabaseDetails = {
8
+ success: boolean;
9
+ message: string;
10
+ databaseId?: string;
11
+ databaseName?: string;
12
+ ownerId?: string;
13
+ fixupNote?: string;
14
+ /** True when an existing live binding was kept — nothing changed. */
15
+ skipped?: boolean;
16
+ };
17
+ export declare const provisionDatabaseTool: HarnessTool<typeof ProvisionDatabaseZod, ProvisionDatabaseDetails>;
18
+ export {};
@@ -0,0 +1,260 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { prewarmAppWorkspace } from '../app-workspace';
6
+ import { probeDatabase } from '../db-probe';
7
+ import { getHost } from '../host';
8
+ import { selectProvisionCredential } from '../provision-database/credential';
9
+ import { archiveBindingKeys, ARCHIVED_BINDING_KEYS, mergeEnv, provisionEnvVars, } from '../provision-database/env-file';
10
+ import { loadProvisionManifest } from '../provision-database/manifest';
11
+ import { applySqlFixups } from '../provision-database/pg-fixups';
12
+ import { selectProvisionRequest } from '../provision-database/preset-match';
13
+ import { requestDatabaseProvision } from '../provision-database/request-database';
14
+ import { resolveProvisionModules } from '../provision-database/resolve';
15
+ const DEFAULT_API_ENDPOINT = 'http://api.localhost:3000/graphql';
16
+ const DEFAULT_MODULES_ENDPOINT = 'http://modules.localhost:3000/graphql';
17
+ // The per-DB endpoints are subdomain.<domain>; the provisioning domain is the api
18
+ // endpoint's host minus its first label (api.localhost -> localhost,
19
+ // api.launchql.dev -> launchql.dev), so dev and devnet both provision correctly.
20
+ function provisionDomain(apiEndpoint) {
21
+ try {
22
+ const { hostname } = new URL(apiEndpoint);
23
+ // A bare IP host has no domain hierarchy to strip: dropping its first label
24
+ // ('192.168.1.10' -> '168.1.10') would yield a garbage domain. Use it verbatim.
25
+ if (hostname.includes(':') || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname))
26
+ return hostname;
27
+ const parts = hostname.split('.');
28
+ return parts.length > 1 ? parts.slice(1).join('.') : parts.join('.');
29
+ }
30
+ catch {
31
+ return 'localhost';
32
+ }
33
+ }
34
+ const ProvisionDatabaseZod = z.object({
35
+ database_name: z
36
+ .string()
37
+ .describe('Name for the app database (lowercase, alphanumeric + underscores). Doubles as the deterministic provisioning subdomain (api-<name>/auth-<name>/app-<name>.localhost), so keep it short and URL-safe.'),
38
+ reprovision: z
39
+ .boolean()
40
+ .describe('Mint a fresh database even though the project already carries a binding — use when the bound database no longer exists on this backend (refreshed backend, deleted database), when it belongs to a different account than the one signed in, or when the user asks for a clean rebuild. The old .env keys are archived as comments and the old database is never deleted server-side. The schema must be rebuilt afterwards (provision_blueprint + run_codegen); records do not carry over.')
41
+ .optional(),
42
+ });
43
+ function fail(message) {
44
+ return { content: [{ type: 'text', text: message }], details: { success: false, message } };
45
+ }
46
+ // Minimal .env reader for the idempotency check (full parsing lives in context.ts).
47
+ function parseEnvKeys(source) {
48
+ const env = {};
49
+ for (const rawLine of source.split('\n')) {
50
+ const line = rawLine.trim();
51
+ if (!line || line.startsWith('#'))
52
+ continue;
53
+ const eq = line.indexOf('=');
54
+ if (eq === -1)
55
+ continue;
56
+ env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
57
+ }
58
+ return env;
59
+ }
60
+ export const provisionDatabaseTool = {
61
+ name: 'provision_database',
62
+ label: 'Provision database',
63
+ description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set, enable membership defaults, and write credentials (DATABASE_ID, ACCESS_TOKEN, etc.) to the project .env. Run this ONCE before any schema/record tools. If the project is already bound to a live database under the signed-in account it skips; if the bound database no longer exists on this backend (refreshed/deleted) or belongs to a different account, pass reprovision: true to mint a fresh one (old keys archived in .env, old database kept; rebuild the schema afterwards).',
64
+ promptSnippet: 'provision_database: one-time bootstrap of the project database (owner + modules + .env). Run before describe_schema/provision_blueprint. Skips when the existing binding is live under the signed-in account; reprovision: true replaces a dead or foreign-account binding (archives old keys, never deletes the old db). Gated.',
65
+ parameters: ProvisionDatabaseZod,
66
+ async execute(params, ctx) {
67
+ const databaseName = params.database_name.trim();
68
+ if (!databaseName)
69
+ return fail('database_name is required.');
70
+ const envPath = path.join(ctx.cwd, '.env');
71
+ let existing = '';
72
+ try {
73
+ existing = await readFile(envPath, 'utf8');
74
+ }
75
+ catch {
76
+ /* no existing .env — fine */
77
+ }
78
+ // Unify endpoints onto the app's backend-config store (environment-aware:
79
+ // *.localhost:3000 in dev, *.launchql.dev packaged). A process.env override
80
+ // still wins for ad-hoc dev; the hardcoded default is a last resort if the
81
+ // store isn't ready.
82
+ const host = getHost();
83
+ const backend = host.backendConfig();
84
+ const apiEndpoint = process.env.API_ENDPOINT || backend?.apiEndpoint || DEFAULT_API_ENDPOINT;
85
+ const modulesEndpoint = process.env.MODULES_ENDPOINT || backend?.modulesEndpoint || DEFAULT_MODULES_ENDPOINT;
86
+ // Every new project provisions UNDER the account (requestDatabase owns the
87
+ // database to the JWT user), so it is account-owned and enumerable. The
88
+ // account bearer is the single credential: it authenticates the provision
89
+ // mutation, the idempotency
90
+ // probe below, and is the ACCESS_TOKEN written to .env for project-local
91
+ // scripts. It expires with the login session — a relogin plus any provision
92
+ // run (including the skip path) refreshes the .env copy. A signed-in session
93
+ // with no usable bearer errors out here rather than silently minting a
94
+ // throwaway owner. Gate BEFORE prewarm so an error return doesn't leak a
95
+ // detached background scaffold/install.
96
+ const credential = selectProvisionCredential(host.account(), host.signInHint);
97
+ if (credential.mode === 'error') {
98
+ return fail(`Cannot provision a database: ${credential.reason}`);
99
+ }
100
+ const ownerId = credential.ownerId;
101
+ // Idempotency keyed on binding liveness AND ownership: a binding is done only
102
+ // when its database still answers and belongs to the signed-in account
103
+ // (schemas are account-scoped). A dead binding (backend refreshed, database
104
+ // deleted, key revoked) or a live one under another account points at the
105
+ // reprovision path; an unreachable backend is a retry, never a reprovision.
106
+ const existingEnv = parseEnvKeys(existing);
107
+ const hasBinding = Boolean(existingEnv.DATABASE_ID && existingEnv.ACCESS_TOKEN);
108
+ if (hasBinding && !params.reprovision) {
109
+ // The probe carries the account bearer, so it only ever targets the
110
+ // app-configured backend — never a .env-pinned endpoint, which an
111
+ // untrusted cloned project controls.
112
+ const probe = await probeDatabase({
113
+ endpoint: apiEndpoint,
114
+ bearer: credential.bearer,
115
+ databaseId: existingEnv.DATABASE_ID,
116
+ signInHint: host.signInHint,
117
+ });
118
+ if (probe.outcome === 'unreachable') {
119
+ return fail(`Cannot verify the existing database binding: backend unreachable (${probe.detail}). Check the Constructive backend is running, then retry — do not reprovision on an unreachable backend.`);
120
+ }
121
+ if (probe.outcome === 'missing') {
122
+ return fail(`Project carries a binding (DATABASE_ID=${existingEnv.DATABASE_ID}) but that database no longer exists on this backend. Re-run with reprovision: true to mint a fresh database (old keys archived in .env, old database untouched), then rebuild the schema (provision_blueprint + run_codegen); records do not carry over.`);
123
+ }
124
+ const sessionUserId = host.account()?.userId;
125
+ if (probe.ownerId && sessionUserId && probe.ownerId !== sessionUserId) {
126
+ return fail(`Project carries a binding (DATABASE_ID=${existingEnv.DATABASE_ID}) but that database was provisioned under a different account than the one signed in. Re-run with reprovision: true to mint a fresh database under this account (old keys archived in .env, old database untouched), then rebuild the schema (provision_blueprint + run_codegen); records do not carry over.`);
127
+ }
128
+ // Heal .env on the skip path: a stale token (relogin) or missing/stale
129
+ // endpoint pins (project provisioned before pins existed, or backend
130
+ // config changed) refresh to the current session + backend.
131
+ const refresh = {};
132
+ if (existingEnv.ACCESS_TOKEN !== credential.bearer)
133
+ refresh.ACCESS_TOKEN = credential.bearer;
134
+ if (existingEnv.API_ENDPOINT !== apiEndpoint)
135
+ refresh.API_ENDPOINT = apiEndpoint;
136
+ if (existingEnv.MODULES_ENDPOINT !== modulesEndpoint) {
137
+ refresh.MODULES_ENDPOINT = modulesEndpoint;
138
+ }
139
+ let tokenNote = '';
140
+ if (Object.keys(refresh).length > 0) {
141
+ const keys = Object.keys(refresh).join(', ');
142
+ try {
143
+ await writeFile(envPath, mergeEnv(existing, refresh));
144
+ tokenNote = ` Refreshed in .env from the signed-in session: ${keys}.`;
145
+ }
146
+ catch (err) {
147
+ tokenNote = ` Could not refresh ${keys} in .env: ${err instanceof Error ? err.message : String(err)}.`;
148
+ }
149
+ }
150
+ const message = `Project already provisioned (DATABASE_ID=${existingEnv.DATABASE_ID}) and the database is live under this account. Skipping — pass reprovision: true only for an explicit clean rebuild.${tokenNote}`;
151
+ return {
152
+ content: [{ type: 'text', text: message }],
153
+ details: {
154
+ success: true,
155
+ message,
156
+ databaseId: existingEnv.DATABASE_ID,
157
+ databaseName: existingEnv.DATABASE_NAME,
158
+ ownerId: existingEnv.OWNER_ID,
159
+ skipped: true,
160
+ },
161
+ };
162
+ }
163
+ if (hasBinding && params.reprovision) {
164
+ existing = archiveBindingKeys(existing, ARCHIVED_BINDING_KEYS, new Date().toISOString().slice(0, 10));
165
+ }
166
+ // The packages/app scaffold + pnpm install are database-INDEPENDENT, so kick
167
+ // them off now to run concurrently with the provisioning request below
168
+ // (near-instant on a warm-pool hit, up to minutes on the cold path).
169
+ // This keeps clone + install off run_codegen's critical path. Best-effort:
170
+ // run_codegen re-runs the same idempotent steps, so a prewarm failure is
171
+ // harmless. Never let it reject (we await it before returning).
172
+ const prewarm = prewarmAppWorkspace(ctx.cwd).catch((err) => ({
173
+ ok: false,
174
+ out: err instanceof Error ? err.message : String(err),
175
+ }));
176
+ // Resolve the module set: pinned base preset from node-type-registry, then
177
+ // ordered overlays (host default < project-local provision.json). No list is
178
+ // hand-copied here; overlays are pure data. A bad preset/manifest fails the
179
+ // run rather than provisioning a wrong module set.
180
+ let modules;
181
+ try {
182
+ const layers = [];
183
+ const hostOverlay = await host.provisionOverlay?.();
184
+ if (hostOverlay)
185
+ layers.push(hostOverlay);
186
+ const projectOverlay = await loadProvisionManifest(ctx.cwd);
187
+ if (projectOverlay)
188
+ layers.push(projectOverlay);
189
+ modules = resolveProvisionModules(layers);
190
+ }
191
+ catch (err) {
192
+ return fail(`Cannot resolve provision modules: ${err instanceof Error ? err.message : String(err)}`);
193
+ }
194
+ const physicalDb = process.env.CONSTRUCTIVE_DB || 'constructive';
195
+ // Provision on the API endpoint: requestDatabase claims a warm-pool
196
+ // database when the resolved module set matches a cataloged preset
197
+ // (near-instant) and cold-provisions asynchronously otherwise; the ticket
198
+ // is polled on the modules endpoint until the database AND its deferred
199
+ // owner bootstrap complete. No retry wrapper: a pending ticket is the
200
+ // normal first response, and transient poll failures are absorbed inside
201
+ // the poll loop. The domain still derives from the api endpoint's host
202
+ // (per-DB endpoints live under it), and an explicit subdomain
203
+ // (= databaseName) keeps them deterministic (SUBDOMAIN-001).
204
+ let databaseId;
205
+ try {
206
+ ({ databaseId } = await requestDatabaseProvision({
207
+ apiEndpoint,
208
+ modulesEndpoint,
209
+ bearer: credential.bearer,
210
+ databaseName,
211
+ domain: provisionDomain(apiEndpoint),
212
+ request: selectProvisionRequest(modules),
213
+ }));
214
+ }
215
+ catch (err) {
216
+ const detail = err instanceof Error ? err.message : String(err);
217
+ const nameTakenHint = /already exists|already taken|already in use|duplicate/i.test(detail)
218
+ ? ' The database name is already taken on the backend — re-run with a different database_name.'
219
+ : '';
220
+ return fail(`Database provisioning failed: ${detail}.${nameTakenHint}`);
221
+ }
222
+ // Enable membership defaults + naming settings at the SQL level. Best-effort:
223
+ // provisioning already succeeded, so a fixup failure is a warning, not an error.
224
+ const fixup = await applySqlFixups({ databaseName, physicalDb });
225
+ // Persist the binding to the project .env (upsert, preserving other keys).
226
+ const merged = mergeEnv(existing, provisionEnvVars({
227
+ databaseId,
228
+ databaseName,
229
+ ownerId,
230
+ accessToken: credential.bearer,
231
+ apiEndpoint,
232
+ modulesEndpoint,
233
+ }));
234
+ try {
235
+ await writeFile(envPath, merged);
236
+ }
237
+ catch (err) {
238
+ return fail(`Database provisioned (ID: ${databaseId}) but writing .env failed: ${err instanceof Error ? err.message : String(err)}`);
239
+ }
240
+ // Settle the concurrent prewarm so the scaffold + install are in place before
241
+ // run_codegen runs. A failure here is non-fatal — run_codegen redoes the work.
242
+ const prewarmResult = await prewarm;
243
+ const prewarmNote = prewarmResult.ok ? ' packages/app prewarmed.' : '';
244
+ const reprovisionNote = hasBinding && params.reprovision
245
+ ? ' Previous binding archived in .env (old database kept); rebuild the schema with provision_blueprint + run_codegen.'
246
+ : '';
247
+ const message = `Provisioned database "${databaseName}" (ID: ${databaseId}). Credentials written to .env. ${fixup.note}${prewarmNote}${reprovisionNote}`;
248
+ return {
249
+ content: [{ type: 'text', text: message }],
250
+ details: {
251
+ success: true,
252
+ message,
253
+ databaseId,
254
+ databaseName,
255
+ ownerId,
256
+ fixupNote: fixup.note,
257
+ },
258
+ };
259
+ },
260
+ };
@@ -0,0 +1,12 @@
1
+ import type { HarnessTool } from '@agentic-kit/harness';
2
+ import { z } from 'zod';
3
+ import { prewarmAppWorkspace } from '../app-workspace';
4
+ declare const RunCodegenZod: z.ZodObject<{}, z.core.$strip>;
5
+ export type RunCodegenDetails = {
6
+ success: boolean;
7
+ message: string;
8
+ barrelsRewritten?: number;
9
+ generatedSubmodules?: string[];
10
+ };
11
+ export declare const runCodegenTool: HarnessTool<typeof RunCodegenZod, RunCodegenDetails>;
12
+ export { prewarmAppWorkspace };
@@ -0,0 +1,137 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, rm, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { ensureAppScaffold, ensureWorkspaceConfig, IGNORED_BUILDS_RE, pinCodegenLatest, prewarmAppWorkspace, run, } from '../app-workspace';
6
+ import { getHost } from '../host';
7
+ import { normalizeSdkBarrels } from '../run-codegen/barrels';
8
+ import { codegenEndpointEnv, derivePlaneEndpoints, envLocalContent } from '../run-codegen/endpoints';
9
+ const DEFAULT_API_ENDPOINT = 'http://api.localhost:3000/graphql';
10
+ const RunCodegenZod = z.object({});
11
+ function fail(message) {
12
+ return { content: [{ type: 'text', text: message }], details: { success: false, message } };
13
+ }
14
+ const FETCH_RESET_RE = /Failed to fetch schema|Connection reset|ECONNRESET|socket hang up/i;
15
+ // Read the binding provision_database wrote to the project .env. The
16
+ // API_ENDPOINT pin identifies which backend owns the binding — it wins over
17
+ // the app's current backend config, matching context.ts data-plane precedence.
18
+ async function readProjectEnv(cwd) {
19
+ try {
20
+ const env = await readFile(path.join(cwd, '.env'), 'utf8');
21
+ const read = (key) => env.match(new RegExp(`^${key}=(.+)$`, 'm'))?.[1]?.trim();
22
+ return { databaseName: read('DATABASE_NAME'), apiEndpoint: read('API_ENDPOINT') };
23
+ }
24
+ catch {
25
+ return {};
26
+ }
27
+ }
28
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
29
+ // The codegen CLI introspects three live vhosts (admin/auth/app). Under load the
30
+ // Constructive backend intermittently resets a connection mid-introspection
31
+ // ("Failed to fetch schema: Connection reset"), which is transient — a retry
32
+ // almost always clears it. Re-run the whole generate (it rebuilds all targets)
33
+ // up to `attempts` times, only on a fetch/reset failure; any other failure is
34
+ // real and returned immediately (CODEGEN-RETRY-001).
35
+ async function runCodegenWithRetry(appDir, env, attempts = 4) {
36
+ const sdk = path.join(appDir, 'src', 'graphql', 'sdk');
37
+ let last = { ok: false, out: 'codegen never ran' };
38
+ for (let i = 1; i <= attempts; i++) {
39
+ for (const sub of ['admin', 'auth', 'app']) {
40
+ await rm(path.join(sdk, sub), { recursive: true, force: true });
41
+ }
42
+ last = await run('npx', ['@constructive-io/graphql-codegen', 'generate', '--config', './graphql-codegen.config.ts'], appDir, env);
43
+ if (last.ok)
44
+ return last;
45
+ if (!FETCH_RESET_RE.test(last.out))
46
+ return last;
47
+ if (i < attempts)
48
+ await sleep(2000 * i);
49
+ }
50
+ return last;
51
+ }
52
+ export const runCodegenTool = {
53
+ name: 'run_codegen',
54
+ label: 'Run codegen',
55
+ 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. 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.",
56
+ promptSnippet: 'run_codegen: scaffold packages/app (if missing) + regenerate the typed SDK (workspace-config + clean install + codegen-with-retry + barrel-normalize). Run after schema changes. Gated.',
57
+ parameters: RunCodegenZod,
58
+ async execute(_params, ctx) {
59
+ const cwd = ctx.cwd;
60
+ const appDir = path.join(cwd, 'packages', 'app');
61
+ // Materialize packages/app deterministically if it isn't there yet — this
62
+ // replaces the flaky `pgpm init` scaffold step (PGPM-001). When
63
+ // provision_database prewarmed it, this no-ops.
64
+ const scaffold = await ensureAppScaffold(cwd);
65
+ if (!scaffold.ok) {
66
+ return fail(scaffold.out);
67
+ }
68
+ const { databaseName: dbName, apiEndpoint: envApiEndpoint } = await readProjectEnv(cwd);
69
+ if (!dbName) {
70
+ return fail('DATABASE_NAME missing from .env — provision the database first, then re-run.');
71
+ }
72
+ const backend = getHost().backendConfig();
73
+ const apiEndpoint = envApiEndpoint || backend?.apiEndpoint || DEFAULT_API_ENDPOINT;
74
+ const planes = derivePlaneEndpoints(apiEndpoint, dbName);
75
+ // The dev server reads .env.local (NEXT_PUBLIC_DB_NAME + per-DB endpoint
76
+ // overrides so it doesn't fall back to localhost vhosts on a remote
77
+ // backend); the codegen config reads process.env (passed directly below).
78
+ try {
79
+ await writeFile(path.join(appDir, '.env.local'), envLocalContent(dbName, planes));
80
+ }
81
+ catch (err) {
82
+ return fail(`Failed to write packages/app/.env.local: ${err instanceof Error ? err.message : String(err)}`);
83
+ }
84
+ // Hoist the graphql override to the root workspace (PNPM-GRAPHQL-OVERRIDE-001)
85
+ // and pin codegen to latest (TS-001) before the single clean install. When
86
+ // prewarmed by provision_database these are idempotent and the install is a
87
+ // fast no-op; otherwise this is the first install (PNPM-BUILDS-001).
88
+ await ensureWorkspaceConfig(cwd);
89
+ await pinCodegenLatest(appDir);
90
+ const install = await run('pnpm', ['install', '--no-frozen-lockfile'], cwd);
91
+ if (!install.ok && !IGNORED_BUILDS_RE.test(install.out)) {
92
+ return fail(`pnpm install failed:\n${install.out}`);
93
+ }
94
+ const codegen = await runCodegenWithRetry(appDir, {
95
+ NEXT_PUBLIC_DB_NAME: dbName,
96
+ ...(planes ? codegenEndpointEnv(planes) : {}),
97
+ });
98
+ if (!codegen.ok) {
99
+ // A reset that survives every internal retry is a backend OUTAGE, not a code
100
+ // or install problem — re-running run_codegen cannot fix it. Say so explicitly
101
+ // so the agent marks sdk-codegen `blocked` instead of looping the tool to the
102
+ // time cap (CODEGEN-OUTAGE-001 / THRASH-001).
103
+ if (FETCH_RESET_RE.test(codegen.out)) {
104
+ return fail('codegen failed: BACKEND OUTAGE — the Constructive backend reset the connection ' +
105
+ 'during schema introspection, and it stayed down across every internal retry. ' +
106
+ 'This is an EXTERNAL outage, not a code or install problem; re-running run_codegen ' +
107
+ 'will NOT fix it. Call run_preflight once — if the backend is down, mark ' +
108
+ 'sdk-codegen `blocked` (SERVER-001, BLOCKED-PROCEED-001) and hand back to ' +
109
+ 'build-orchestrator. Do NOT loop on run_codegen (THRASH-001).\n\n' +
110
+ codegen.out);
111
+ }
112
+ return fail(`codegen failed:\n${codegen.out}`);
113
+ }
114
+ // Normalize directory barrels so Turbopack can resolve them (TURBOPACK-BARREL-001).
115
+ const sdkRoot = path.join(appDir, 'src', 'graphql', 'sdk');
116
+ const barrelsRewritten = normalizeSdkBarrels(sdkRoot);
117
+ // Report which app submodules actually generated — a bare scaffold with only
118
+ // index.ts means codegen had no schema to generate against.
119
+ const appSdk = path.join(sdkRoot, 'app');
120
+ const generatedSubmodules = ['hooks', 'orm', 'types'].filter((sub) => existsSync(path.join(appSdk, sub)));
121
+ const message = generatedSubmodules.length > 0
122
+ ? `Codegen complete. Generated app submodules: ${generatedSubmodules.join(', ')}. Normalized ${barrelsRewritten} barrel file(s).`
123
+ : `Codegen ran, but no app submodules (hooks/orm/types) were generated — the database may have no entity tables yet. Normalized ${barrelsRewritten} barrel file(s).`;
124
+ return {
125
+ content: [{ type: 'text', text: message }],
126
+ details: {
127
+ success: generatedSubmodules.length > 0,
128
+ message,
129
+ barrelsRewritten,
130
+ generatedSubmodules,
131
+ },
132
+ };
133
+ },
134
+ };
135
+ // Re-exported so provision_database can prewarm the same deterministic scaffold +
136
+ // install concurrently with its backend mutation (kept off run_codegen's path).
137
+ export { prewarmAppWorkspace };
@@ -0,0 +1,71 @@
1
+ import { type ConfirmPreviewTable, type HarnessTool } from '@agentic-kit/harness';
2
+ import { z } from 'zod';
3
+ import type { ProjectContext } from '../context';
4
+ export type TemplateDetails = {
5
+ success: boolean;
6
+ message: string;
7
+ };
8
+ export type CreateTemplateDetails = TemplateDetails & {
9
+ displayName?: string;
10
+ blueprintName?: string;
11
+ tables?: ConfirmPreviewTable[];
12
+ };
13
+ type TemplateField = {
14
+ name: string;
15
+ type: string;
16
+ isRequired: boolean;
17
+ defaultValue: string | null;
18
+ };
19
+ type TemplateTable = {
20
+ name: string;
21
+ fields: TemplateField[];
22
+ policies: string[];
23
+ relationCount: number;
24
+ };
25
+ type TemplateInfo = {
26
+ displayName: string;
27
+ description: string | null;
28
+ categories: string[];
29
+ tables: TemplateTable[];
30
+ };
31
+ export type ListTemplatesDetails = {
32
+ templates: TemplateInfo[];
33
+ };
34
+ export type CreateTemplatePreview = {
35
+ blueprintName: string;
36
+ tables: ConfirmPreviewTable[];
37
+ };
38
+ export declare function createTemplatePreviewTables(context: ProjectContext, blueprintName: string | undefined): Promise<CreateTemplatePreview>;
39
+ declare const ListTemplatesZod: z.ZodObject<{}, z.core.$strip>;
40
+ export declare const listTemplatesTool: HarnessTool<typeof ListTemplatesZod, ListTemplatesDetails>;
41
+ declare const CreateTemplateZod: z.ZodObject<{
42
+ displayName: z.ZodString;
43
+ blueprintName: z.ZodOptional<z.ZodString>;
44
+ description: z.ZodOptional<z.ZodString>;
45
+ categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
46
+ }, z.core.$strip>;
47
+ export declare const createTemplateTool: HarnessTool<typeof CreateTemplateZod, CreateTemplateDetails>;
48
+ declare const ApplyTemplateZod: z.ZodObject<{
49
+ templateName: z.ZodString;
50
+ nameOverride: z.ZodOptional<z.ZodString>;
51
+ }, z.core.$strip>;
52
+ export declare const applyTemplateTool: HarnessTool<typeof ApplyTemplateZod, TemplateDetails>;
53
+ declare const UpdateTemplateZod: z.ZodObject<{
54
+ templateName: z.ZodString;
55
+ patch: z.ZodObject<{
56
+ displayName: z.ZodOptional<z.ZodString>;
57
+ description: z.ZodOptional<z.ZodString>;
58
+ categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
59
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
60
+ visibility: z.ZodOptional<z.ZodEnum<{
61
+ public: "public";
62
+ private: "private";
63
+ }>>;
64
+ }, z.core.$strip>;
65
+ }, z.core.$strip>;
66
+ export declare const updateTemplateTool: HarnessTool<typeof UpdateTemplateZod, TemplateDetails>;
67
+ declare const DeleteTemplateZod: z.ZodObject<{
68
+ templateName: z.ZodString;
69
+ }, z.core.$strip>;
70
+ export declare const deleteTemplateTool: HarnessTool<typeof DeleteTemplateZod, TemplateDetails>;
71
+ export {};