@agentic-kit/db-tools 0.12.46 → 0.13.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 (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,15 +1,164 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.provisionBlueprintTool = void 0;
4
- const harness_1 = require("@agentic-kit/harness");
4
+ exports.provisionBlueprintReady = provisionBlueprintReady;
5
+ const access_1 = require("../access");
6
+ const words_1 = require("../access/words");
7
+ const blueprint_defaults_1 = require("../blueprint/blueprint-defaults");
8
+ const blueprint_schema_1 = require("../blueprint/blueprint-schema");
9
+ const field_type_1 = require("../blueprint/field-type");
5
10
  const blueprint_construction_1 = require("../blueprint-construction");
6
- const context_1 = require("../context");
11
+ const failure_1 = require("../failure");
12
+ const ready_1 = require("../ready");
13
+ const schema_resolve_1 = require("../schema-resolve");
14
+ const table_access_1 = require("../table-access");
15
+ const access_2 = require("./access");
16
+ // The rules of a table entry that are rule objects; anything else in the list is the schema's to refuse.
17
+ const rulesOf = (table) => (Array.isArray(table.policies) ? table.policies : []).filter((policy) => typeof policy === 'object' && policy !== null && typeof policy.$type === 'string');
18
+ // The new tables of a blueprint: the entries that name a table (an entry may attach to a module's table instead).
19
+ const newTables = (definition) => definition.tables.filter((table) => typeof table.table_name === 'string');
20
+ // The columns of each new table, by its name: its own fields, the row id, and the columns its nodes add.
21
+ function newTableColumns(definition) {
22
+ return Object.fromEntries(newTables(definition).map((table) => [
23
+ table.table_name,
24
+ [...new Set([access_1.ROW_ID, ...(table.fields ?? []).map((field) => field.name), ...(0, access_1.fieldsAddedByNodes)(table.nodes ?? []).fields.map((column) => column.name)])],
25
+ ]));
26
+ }
27
+ /**
28
+ * A field of a new table that a node of the table also adds, when the backend cannot keep it: the row id, which the
29
+ * table's own id node makes, or a column of another type than the node's. The backend creates a field before the
30
+ * nodes, and a node keeps a column that exists as it is.
31
+ */
32
+ function fieldNodeClash(table) {
33
+ const added = (0, access_1.fieldsAddedByNodes)(table.nodes ?? []).fields;
34
+ for (const field of table.fields ?? []) {
35
+ const column = added.find((entry) => entry.name === field.name);
36
+ if (field.name === access_1.ROW_ID) {
37
+ return {
38
+ code: 'invalid-input',
39
+ message: `Table "${table.table_name}": the field ${access_1.ROW_ID} is the row id, which every table gets. Leave it out of the fields.`,
40
+ };
41
+ }
42
+ const type = (0, field_type_1.fieldTypeToTypeName)(field.type);
43
+ if (column && column.type !== type) {
44
+ return {
45
+ code: 'invalid-input',
46
+ message: `Table "${table.table_name}": the field ${field.name} is ${type}, and ${column.node} adds ${field.name} as ${column.type} for the table's rules or nodes; ` +
47
+ 'the backend keeps the field as given, so they cannot work on it.',
48
+ hint: `Leave ${field.name} out of the fields so ${column.node} adds it, or give it the type ${column.type}.`,
49
+ };
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * The checks of a blueprint that need no backend: each rule's shape and data against its node (the columns of the
56
+ * other tables it reads included), the rules each table sends (`rulesToSend`), the registry's blueprint JSON Schema
57
+ * over what the backend would receive, and for each new table its fields beside its nodes, the columns its rules read
58
+ * and the Data nodes that add them. It answers the definition with each table's rules as the backend creates them.
59
+ */
60
+ function blueprintChecks(definition, context) {
61
+ const tables = [];
62
+ for (const table of definition.tables) {
63
+ const name = table.table_name ?? 'of the module';
64
+ const policies = rulesOf(table);
65
+ // A rule list that is not a list of rules is the schema's to say.
66
+ if (policies.length !== (Array.isArray(table.policies) ? table.policies.length : 0)) {
67
+ tables.push(table);
68
+ continue;
69
+ }
70
+ const label = (index) => `Table "${name}", rule ${index + 1} (${policies[index].$type})`;
71
+ const rules = (0, access_2.ruleProblems)(policies, { roles: context.roles, inBlueprint: true, withCheck: true, columnsOf: (0, words_1.columnsOf)(context.related) }, label);
72
+ if (rules)
73
+ return { kind: 'failed', failure: rules };
74
+ const sent = (0, access_2.rulesToSend)(policies, { defaultRole: 'authenticated', label });
75
+ if (sent.kind === 'failed')
76
+ return sent;
77
+ tables.push(Array.isArray(table.policies) ? { ...table, policies: sent.value } : table);
78
+ }
79
+ const checked = { ...definition, tables };
80
+ const problems = (0, blueprint_schema_1.blueprintProblems)(checked);
81
+ if (problems.length) {
82
+ return {
83
+ kind: 'failed',
84
+ failure: {
85
+ code: 'invalid-input',
86
+ message: `The blueprint is not valid: ${problems.join(' ')}`,
87
+ hint: 'Fix each place the message names; the blueprint JSON Schema of node-type-registry describes every key.',
88
+ },
89
+ };
90
+ }
91
+ for (const table of newTables(checked)) {
92
+ const clash = fieldNodeClash(table);
93
+ if (clash)
94
+ return { kind: 'failed', failure: clash };
95
+ const rules = (table.policies ?? []).map(access_1.tablePolicyFromBlueprint);
96
+ const needed = (0, access_1.dataNodesForPolicies)(rules.flatMap((rule) => rule.with_check ? [rule, { type: rule.with_check.type, data: rule.with_check.data ?? {} }] : [rule]), new Set((table.fields ?? []).map(({ name }) => name)));
97
+ if (needed.problems.length)
98
+ return { kind: 'failed', failure: { code: 'invalid-input', message: `Table "${table.table_name}": ${needed.problems.join(' ')}` } };
99
+ const change = (0, table_access_1.columnChange)(table.table_name, (table.fields ?? []).map(({ name }) => ({ name })), table.nodes ?? [], rules);
100
+ if (change.kind === 'failed')
101
+ return { kind: 'failed', failure: { ...change.failure, message: `Table "${table.table_name}": ${change.failure.message}` } };
102
+ }
103
+ return { kind: 'ok', value: checked };
104
+ }
105
+ // Each schema the blueprint names: a table's own, an end of a relation, and the table of a top-level index or constraint.
106
+ function schemasNamed(definition) {
107
+ const items = [definition.indexes, definition.unique_constraints, definition.check_constraints, definition.full_text_searches].flatMap((list) => (list ?? []));
108
+ return [
109
+ ...definition.tables.map((table) => table.schema_name),
110
+ ...(definition.relations ?? []).flatMap((relation) => [relation.source_schema, relation.target_schema]),
111
+ ...items.map((item) => item.schema_name),
112
+ ].filter((name) => typeof name === 'string');
113
+ }
114
+ /**
115
+ * What provision_blueprint checks before it changes anything: an owned
116
+ * project, a blueprint the registry's JSON Schema takes once its defaults are
117
+ * filled in, rules that fit their nodes and the roles of the database, the
118
+ * schemas it names, none of its new tables yet, and the tables its relations
119
+ * name.
120
+ */
121
+ async function provisionBlueprintReady(params, cwd) {
122
+ const ready = await (0, ready_1.ownedProjectReady)(cwd);
123
+ if (ready.kind === 'failed')
124
+ return ready;
125
+ const expanded = (0, blueprint_defaults_1.expandBlueprintDefaults)(params.definition);
126
+ const rules = expanded.tables.flatMap(rulesOf);
127
+ const roles = await (0, access_2.rolesFor)(ready.value, rules);
128
+ if (roles.kind === 'failed')
129
+ return roles;
130
+ const existing = await (0, access_2.relatedColumns)(ready.value, rules);
131
+ if (existing.kind === 'failed')
132
+ return existing;
133
+ const related = existing.value ? { ...existing.value, ...newTableColumns(expanded) } : undefined;
134
+ const checked = blueprintChecks(expanded, { roles: roles.value, related });
135
+ if (checked.kind === 'failed')
136
+ return checked;
137
+ const definition = checked.value;
138
+ const named = schemasNamed(definition);
139
+ const schemas = named.length ? await (0, schema_resolve_1.readSchemas)(ready.value) : { kind: 'ok', value: new Map() };
140
+ if (schemas.kind === 'failed')
141
+ return schemas;
142
+ const missingSchema = named.length ? (0, schema_resolve_1.schemasMissing)(named, schemas.value) : null;
143
+ if (missingSchema)
144
+ return { kind: 'failed', failure: missingSchema };
145
+ const made = newTables(definition);
146
+ const taken = await (0, schema_resolve_1.tablesTaken)(ready.value, made.map((table) => ({ name: table.table_name, ...(table.schema_name ? { schema: table.schema_name } : {}) })), schemas.value);
147
+ if (taken)
148
+ return { kind: 'failed', failure: taken };
149
+ const missing = await (0, schema_resolve_1.relationTablesMissing)(ready.value, made.map((table) => table.table_name), (definition.relations ?? []), schemas.value);
150
+ if (missing)
151
+ return { kind: 'failed', failure: missing };
152
+ return { kind: 'ok', value: { ...ready.value, definition, ...(related ? { related } : {}) } };
153
+ }
7
154
  function formatText(name, details) {
8
- if (details.error)
9
- return `Failed to provision "${name}": ${details.error}`;
10
155
  const lines = [`Created ${details.created} table${details.created === 1 ? '' : 's'} from "${name}":`];
11
156
  for (const table of details.tables) {
12
- const parts = [`${table.fields.length} field${table.fields.length === 1 ? '' : 's'}`];
157
+ const parts = [
158
+ ...(table.requestedName ? [`stored from "${table.requestedName}"`] : []),
159
+ `${table.fields.length} field${table.fields.length === 1 ? '' : 's'}`,
160
+ ...table.fields.filter((field) => field.requestedName).map((field) => `field ${field.name} stored from "${field.requestedName}"`),
161
+ ];
13
162
  if (table.relationCount > 0) {
14
163
  parts.push(`${table.relationCount} relation${table.relationCount === 1 ? '' : 's'}`);
15
164
  }
@@ -20,13 +169,17 @@ function formatText(name, details) {
20
169
  }
21
170
  return lines.join('\n');
22
171
  }
172
+ const typeText = (type) => (typeof type === 'string' ? type : JSON.stringify(type));
173
+ const defaultText = (value) => (value == null ? null : typeof value === 'string' ? value : JSON.stringify(value));
23
174
  exports.provisionBlueprintTool = {
24
175
  name: 'provision_blueprint',
25
176
  label: 'Provision blueprint',
26
- 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.',
27
- promptSnippet: 'provision_blueprint: create new tables from scratch in a single call (fields + policies + relations). Call describe_schema first.',
28
- parameters: harness_1.BlueprintZod,
29
- async execute(params, ctx) {
177
+ description: 'Create one or more related tables (with fields, access rules, relations, indexes and constraints) in the project database from a blueprint definition. Always put related tables in a SINGLE call so relations are created together.',
178
+ promptSnippet: 'provision_blueprint: create new tables from scratch in a single call (fields, rules, relations, indexes). Read the schema first. Gated.',
179
+ parameters: blueprint_schema_1.BlueprintZod,
180
+ effect: 'write',
181
+ async execute(input, ctx) {
182
+ const params = input;
30
183
  const empty = {
31
184
  created: 0,
32
185
  total: 0,
@@ -34,19 +187,12 @@ exports.provisionBlueprintTool = {
34
187
  error: null,
35
188
  constructionId: null,
36
189
  };
37
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
38
- if (!resolved.context) {
39
- return { content: [{ type: 'text', text: resolved.reason }], details: empty };
40
- }
41
- const { modules, databaseId, schemaId, ownerId } = resolved.context;
42
- if (!ownerId) {
43
- return {
44
- content: [{ type: 'text', text: 'Not authenticated (missing OWNER_ID in .env).' }],
45
- details: empty,
46
- };
47
- }
48
- const definition = (0, harness_1.expandBlueprintDefaults)(params.definition);
190
+ const ready = await provisionBlueprintReady(params, ctx.cwd);
191
+ if (ready.kind === 'failed')
192
+ return (0, failure_1.failedResult)(ready.failure, empty);
193
+ const { modules, databaseId, schemaId, ownerId, definition } = ready.value;
49
194
  const uniqueName = `${params.name}_${Date.now()}`;
195
+ const made = newTables(definition);
50
196
  try {
51
197
  const createResult = await modules.blueprint
52
198
  .create({
@@ -56,29 +202,27 @@ exports.provisionBlueprintTool = {
56
202
  name: uniqueName,
57
203
  displayName: params.name,
58
204
  description: params.description,
59
- definition,
205
+ definition: definition,
60
206
  },
61
207
  select: { id: true, name: true },
62
208
  })
63
209
  .unwrap();
64
210
  const blueprintId = createResult.createBlueprint?.blueprint?.id;
65
211
  if (!blueprintId)
66
- throw new Error('Failed to create blueprint');
67
- const { constructionId } = await (0, blueprint_construction_1.buildBlueprint)(modules, { blueprintId, schemaId }, { signal: ctx.signal });
68
- const relations = params.definition.relations ?? [];
212
+ return (0, failure_1.failedResult)((0, failure_1.noRowCreated)(`Failed to create the blueprint "${params.name}"`, failure_1.DESCRIBE_SCHEMA), empty);
213
+ const { constructionId, tables } = await (0, blueprint_construction_1.buildBlueprint)(modules, { blueprintId, schemaId }, { signal: ctx.signal });
214
+ // The construction maps each table name of the blueprint to its id; the stored name is read back by id.
215
+ const stored = await (0, schema_resolve_1.storedTableNames)(ready.value, Object.values(tables)).catch(() => new Map());
216
+ const named = (given, as, rest) => as && as !== given ? { name: as, requestedName: given, ...rest } : { name: given, ...rest };
217
+ const relations = (definition.relations ?? []);
218
+ const given = new Map(params.definition.tables.filter((table) => typeof table.table_name === 'string').map((table) => [table.table_name, table]));
69
219
  const details = {
70
- created: params.definition.tables.length,
71
- total: params.definition.tables.length,
72
- tables: params.definition.tables.map((t) => ({
73
- name: t.table_name,
74
- fields: (t.fields ?? []).map((f) => ({
75
- name: f.name,
76
- type: f.type,
77
- isRequired: f.is_required ?? false,
78
- defaultValue: f.default ?? null,
79
- })),
80
- policies: (0, harness_1.filterInternalPolicies)(t.policies.map((p) => p.$type)),
81
- relationCount: relations.filter((r) => r.source_table === t.table_name).length,
220
+ created: made.length,
221
+ total: made.length,
222
+ tables: made.map((table) => named(table.table_name, stored.get(tables[table.table_name]) ?? (0, schema_resolve_1.storedName)(table.table_name), {
223
+ fields: (given.get(table.table_name)?.fields ?? []).map((field) => named(field.name, (0, schema_resolve_1.storedName)(field.name), { type: typeText(field.type), isRequired: field.is_required ?? false, defaultValue: defaultText(field.default) })),
224
+ policies: [...new Set((table.policies ?? []).map((policy) => policy.$type))],
225
+ relationCount: relations.filter((relation) => relation.source_table === table.table_name).length,
82
226
  })),
83
227
  error: null,
84
228
  constructionId,
@@ -86,15 +230,14 @@ exports.provisionBlueprintTool = {
86
230
  return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
87
231
  }
88
232
  catch (err) {
89
- const message = err instanceof Error ? err.message : 'Failed to provision blueprint';
90
- const details = {
233
+ const failure = (0, failure_1.failureFromError)(err, `Failed to provision "${params.name}"`);
234
+ return (0, failure_1.failedResult)(failure, {
91
235
  created: 0,
92
- total: params.definition.tables.length,
236
+ total: made.length,
93
237
  tables: [],
94
- error: message,
238
+ error: failure.message,
95
239
  constructionId: err instanceof blueprint_construction_1.BlueprintBuildError ? err.constructionId : null,
96
- };
97
- return { content: [{ type: 'text', text: formatText(params.name, details) }], details };
240
+ });
98
241
  }
99
242
  },
100
243
  };
@@ -1,14 +1,16 @@
1
- import type { HarnessTool } from '@agentic-kit/harness';
1
+ import { type HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
3
  import { type RunCommand } from '../app-workspace';
4
4
  import { type ProvisionDatabaseDetails } from '../provision-database/provision';
5
5
  export type { ProvisionDatabaseDetails };
6
6
  declare const ProvisionDatabaseZod: z.ZodObject<{
7
7
  database_name: z.ZodString;
8
- reprovision: z.ZodOptional<z.ZodBoolean>;
9
- }, z.core.$strip>;
8
+ }, z.core.$strict>;
10
9
  export declare function createProvisionDatabaseTool(exec?: RunCommand): HarnessTool<typeof ProvisionDatabaseZod, ProvisionDatabaseDetails>;
10
+ export declare function createReplaceDatabaseTool(exec?: RunCommand): HarnessTool<typeof ProvisionDatabaseZod, ProvisionDatabaseDetails>;
11
11
  export declare const provisionDatabaseTool: HarnessTool<z.ZodObject<{
12
12
  database_name: z.ZodString;
13
- reprovision: z.ZodOptional<z.ZodBoolean>;
14
- }, z.core.$strip>, ProvisionDatabaseDetails>;
13
+ }, z.core.$strict>, ProvisionDatabaseDetails>;
14
+ export declare const replaceDatabaseTool: HarnessTool<z.ZodObject<{
15
+ database_name: z.ZodString;
16
+ }, z.core.$strict>, ProvisionDatabaseDetails>;
@@ -1,38 +1,53 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.provisionDatabaseTool = void 0;
3
+ exports.replaceDatabaseTool = exports.provisionDatabaseTool = void 0;
4
4
  exports.createProvisionDatabaseTool = createProvisionDatabaseTool;
5
+ exports.createReplaceDatabaseTool = createReplaceDatabaseTool;
6
+ const harness_1 = require("@agentic-kit/harness");
5
7
  const zod_1 = require("zod");
6
8
  const app_workspace_1 = require("../app-workspace");
9
+ const env_file_1 = require("../provision-database/env-file");
7
10
  const provision_1 = require("../provision-database/provision");
8
- const ProvisionDatabaseZod = zod_1.z.object({
11
+ const ProvisionDatabaseZod = (0, harness_1.strictObject)('the input', {
9
12
  database_name: zod_1.z
10
13
  .string()
11
- .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.'),
12
- reprovision: zod_1.z
13
- .boolean()
14
- .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.')
15
- .optional(),
14
+ .min(3)
15
+ .max(63)
16
+ .regex(env_file_1.DATABASE_NAME_PATTERN, { message: 'must start with a letter and hold only letters, digits, _ and -' })
17
+ .describe('3 to 63 characters: a letter, then letters, digits, _ or -. It becomes the subdomain (api-<name>.<domain>), so keep it short and lowercase.'),
16
18
  });
17
19
  // `exec` runs the prewarm's child processes (clone, install); tests inject it.
18
20
  function createProvisionDatabaseTool(exec = app_workspace_1.run) {
19
21
  return {
20
22
  name: 'provision_database',
21
23
  label: 'Provision database',
22
- description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set and write the database binding (DATABASE_ID, DATABASE_NAME, 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 binding archived in .env, old database kept; rebuild the schema afterwards). If a call returns while the database is still provisioning, call it again with the same database_name to keep waiting; a different name starts a second database.',
23
- 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.',
24
+ description: 'Bootstrap a new Constructive database for the project under your account: provision the standard module set and write the database binding (DATABASE_ID, DATABASE_NAME, etc.) to the project .env. Run this ONCE before the schema and record tools. If the project is already bound to a live database under the signed-in account it skips. If a call returns while the database is still provisioning, call it again with the same name to keep waiting; a different name starts a second database.',
25
+ promptSnippet: 'provision_database: one-time bootstrap of the project database (owner + modules + .env), before any schema change. Skips when the existing binding is live under the signed-in account. Gated.',
24
26
  parameters: ProvisionDatabaseZod,
27
+ effect: 'write',
25
28
  async execute(params, ctx) {
26
- // reprovision: true replaces the binding the project has right now; one
27
- // that changes while this call waits for the project lock is not replaced.
28
- const replace = params.reprovision === true;
29
- const details = await (0, provision_1.provisionFromTool)({
30
- databaseName: params.database_name,
31
- mode: replace ? 'replace' : 'ensure',
32
- replaces: replace ? ((await (0, provision_1.boundDatabaseId)(ctx.cwd)) ?? null) : undefined,
33
- }, ctx, exec);
34
- return { content: [{ type: 'text', text: details.message }], details };
29
+ const { details, failure } = await (0, provision_1.provisionFromTool)({ databaseName: params.database_name, mode: 'ensure' }, ctx, exec);
30
+ return { content: [{ type: 'text', text: details.message }], details, ...(failure ? { failure } : {}) };
31
+ },
32
+ };
33
+ }
34
+ // `exec` runs the prewarm's child processes (clone, install); tests inject it.
35
+ function createReplaceDatabaseTool(exec = app_workspace_1.run) {
36
+ return {
37
+ name: 'replace_database',
38
+ label: 'Replace database',
39
+ description: 'Bind the project to a new, empty database in place of the one it is bound to: for a bound database that no longer exists on this backend, one that belongs to another account, or a clean rebuild the user asks for. The old .env keys are archived as comments and the old database is kept on the backend; the schema must be built again in the new one, and records do not carry over. Destructive.',
40
+ promptSnippet: 'replace_database: bind the project to a new, empty database in place of a dead, foreign-account or unwanted one (old keys archived, old database kept). Destructive — gated.',
41
+ parameters: ProvisionDatabaseZod,
42
+ effect: 'destructive',
43
+ async execute(params, ctx) {
44
+ // A replace swaps the binding the project has right now; one that changes while this call waits for the project
45
+ // lock is not replaced.
46
+ const replaces = (await (0, provision_1.boundDatabaseId)(ctx.cwd)) ?? null;
47
+ const { details, failure } = await (0, provision_1.provisionFromTool)({ databaseName: params.database_name, mode: 'replace', replaces }, ctx, exec);
48
+ return { content: [{ type: 'text', text: details.message }], details, ...(failure ? { failure } : {}) };
35
49
  },
36
50
  };
37
51
  }
38
52
  exports.provisionDatabaseTool = createProvisionDatabaseTool();
53
+ exports.replaceDatabaseTool = createReplaceDatabaseTool();
@@ -1,7 +1,9 @@
1
- import type { HarnessTool } from '@agentic-kit/harness';
1
+ import { type HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
- import { prewarmAppWorkspace, type RunCommand } from '../app-workspace';
4
- declare const RunCodegenZod: z.ZodObject<{}, z.core.$strip>;
3
+ import { type AppKind, prewarmAppWorkspace, type RunCommand } from '../app-workspace';
4
+ import type { ProjectContext } from '../context';
5
+ import { type Result } from '../failure';
6
+ declare const RunCodegenZod: z.ZodObject<{}, z.core.$strict>;
5
7
  /** Wall-clock milliseconds per step; a step that didn't run reports 0. */
6
8
  export type RunCodegenTimings = {
7
9
  scaffoldMs: number;
@@ -23,7 +25,28 @@ export type RunCodegenDetails = {
23
25
  timings?: RunCodegenTimings;
24
26
  /** The app API answered ACCESS_SUSPENDED: the database is deleted or suspended. */
25
27
  code?: 'database-unavailable';
28
+ /** With `app-missing`: the app data plane endpoint the SDK is generated from. */
29
+ appEndpoint?: string;
26
30
  };
31
+ /** What run_codegen runs on: the project's database, the app in packages/app, and what it does to the app first. */
32
+ export type RunCodegenReady = {
33
+ context: ProjectContext;
34
+ app: Exclude<AppKind, {
35
+ kind: 'invalid';
36
+ }>;
37
+ /** Whether this host lets run_codegen create packages/app and install its packages (`ToolsHost.prewarmApp`). */
38
+ preparesApp: boolean;
39
+ /** What the plan says it runs, in words: the project's own code generator, and the steps it takes on the app first when the host prepares the app. */
40
+ notes: string[];
41
+ };
42
+ /**
43
+ * What run_codegen checks before it changes anything: the project's database
44
+ * on the data plane (codegen reads the app's own API, as the Preview does), by
45
+ * name, and the app in packages/app. Its API endpoint is the .env pin when
46
+ * there is one, as the data plane resolves it. A host that prepares no app
47
+ * (`prewarmApp: false`) needs an app there, installed when it is composed.
48
+ */
49
+ export declare function runCodegenReady(cwd: string): Promise<Result<RunCodegenReady>>;
27
50
  export declare function createRunCodegenTool(exec?: RunCommand): HarnessTool<typeof RunCodegenZod, RunCodegenDetails>;
28
- export declare const runCodegenTool: HarnessTool<z.ZodObject<{}, z.core.$strip>, RunCodegenDetails>;
51
+ export declare const runCodegenTool: HarnessTool<z.ZodObject<{}, z.core.$strict>, RunCodegenDetails>;
29
52
  export { prewarmAppWorkspace };