@agentic-kit/db-tools 0.12.47 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
@@ -1,77 +1,130 @@
1
- import { toFieldDefault, toFieldType } from '@agentic-kit/harness';
1
+ import { identifierParam, strictObject, takeApprovedTable, textParam } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
- import { resolveProjectContext } from '../context';
4
- import { findUniqueConstraintId, resolveField, resolveSchema, resolveTable } from '../schema-resolve';
3
+ import { toFieldDefault, toFieldType } from '../blueprint/field-type';
4
+ import { DESCRIBE_SCHEMA, failedResult, failureFromError, failureText, noRowCreated, noRowsChanged, suggest } from '../failure';
5
+ import { projectReady } from '../ready';
6
+ import { findUniqueConstraintId, resolveField, resolveSchema, resolveTable, storedName, } from '../schema-resolve';
5
7
  function ok(message) {
6
8
  return {
7
9
  content: [{ type: 'text', text: message }],
8
10
  details: { success: true, message },
9
11
  };
10
12
  }
11
- function fail(message) {
13
+ function fail(failure, errors) {
14
+ return failedResult(failure, {
15
+ success: false,
16
+ message: failureText(failure),
17
+ ...(errors ? { errors } : {}),
18
+ });
19
+ }
20
+ // The main change happened and the unique constraint step did not.
21
+ function partial(done, constraint, hint, retry) {
22
+ return fail({ code: 'partial', message: `${done} ${constraint.message.replace(/\.?$/, '.')}`, hint, calls: [retry] }, [constraint.message]);
23
+ }
24
+ async function namedReady(cwd, tableName, fieldName) {
25
+ const ready = await projectReady(cwd);
26
+ if (ready.kind === 'failed')
27
+ return ready;
28
+ try {
29
+ const table = resolveTable(await resolveSchema(ready.value), tableName);
30
+ return { kind: 'ok', value: { context: ready.value, table, ...(fieldName === undefined ? {} : { field: resolveField(table, fieldName) }) } };
31
+ }
32
+ catch (err) {
33
+ return { kind: 'failed', failure: failureFromError(err, 'Failed to read the schema of the project database') };
34
+ }
35
+ }
36
+ // A new field's name is free when the table has no field of the name the backend stores it under.
37
+ function fieldTaken(table, given, stored, except) {
38
+ if (!table.fields.some((field) => field.name === stored && field.id !== except))
39
+ return null;
40
+ const how = stored === given ? '' : `, which is how the backend stores "${given}"`;
12
41
  return {
13
- content: [{ type: 'text', text: message }],
14
- details: { success: false, message },
42
+ code: 'name-taken',
43
+ message: `Table "${table.name}" already has a field named "${stored}"${how}.`,
44
+ hint: 'Choose another field name; check the names that exist.',
45
+ calls: [DESCRIBE_SCHEMA],
15
46
  };
16
47
  }
17
48
  // ── delete_table ──────────────────────────────────────────────────────────
18
- const DeleteTableZod = z.object({
19
- table_name: z.string().describe('Name of the table to delete (snake_case)'),
49
+ const DeleteTableZod = strictObject('the input', {
50
+ table_name: identifierParam().describe('Name of the table to delete (snake_case)'),
20
51
  });
52
+ /** What delete_table checks before it changes anything: the project, and the table. */
53
+ export const deleteTableReady = (params, cwd) => namedReady(cwd, params.table_name);
21
54
  export const deleteTableTool = {
22
55
  name: 'delete_table',
23
56
  label: 'Delete table',
24
57
  description: 'Permanently delete a table and its data from the project database.',
25
58
  promptSnippet: 'delete_table: drop an existing table by name. Destructive — gated.',
26
59
  parameters: DeleteTableZod,
60
+ effect: 'destructive',
27
61
  async execute(params, ctx) {
28
- const resolved = await resolveProjectContext(ctx.cwd);
29
- if (!resolved.context)
30
- return fail(resolved.reason);
62
+ const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined;
63
+ const ready = await deleteTableReady(params, ctx.cwd);
64
+ if (ready.kind === 'failed')
65
+ return fail(ready.failure);
66
+ const { context, table } = ready.value;
67
+ if (ctx.toolCallId && (!approved || approved.database.id !== context.databaseId || approved.apiEndpoint !== context.controlApiEndpoint ||
68
+ approved.account.userId !== context.accountUserId || approved.account.agent?.principalId !== context.accountAgent?.principalId ||
69
+ approved.table?.schemaId !== context.schemaId || approved.table.id !== table.id)) {
70
+ return fail({
71
+ code: 'failed',
72
+ message: 'The current table and project do not match the approved delete target.',
73
+ hint: 'Review the current target and approve a new request.',
74
+ });
75
+ }
31
76
  try {
32
- const schema = await resolveSchema(resolved.context);
33
- const table = resolveTable(schema, params.table_name);
34
- await resolved.context.api.table
77
+ const result = await context.api.table
35
78
  .delete({ where: { id: table.id }, select: { id: true } })
36
79
  .unwrap();
80
+ if (!result.deleteTable?.table) {
81
+ return fail(noRowsChanged(`Failed to delete table "${params.table_name}"`, DESCRIBE_SCHEMA));
82
+ }
37
83
  return ok(`Deleted table ${params.table_name}`);
38
84
  }
39
85
  catch (err) {
40
- return fail(err instanceof Error ? err.message : 'Failed to delete table');
86
+ return fail(failureFromError(err, `Failed to delete table "${params.table_name}"`));
41
87
  }
42
88
  },
43
89
  };
44
90
  // ── create_field ──────────────────────────────────────────────────────────
45
- const CreateFieldZod = z.object({
46
- table_name: z.string().describe('Name of the table to add the field to'),
47
- field_name: z.string().describe('Field name in snake_case'),
48
- type: z
49
- .string()
91
+ const CreateFieldZod = strictObject('the input', {
92
+ table_name: identifierParam().describe('Name of the table to add the field to'),
93
+ field_name: identifierParam().describe('Field name in snake_case'),
94
+ type: textParam()
50
95
  .describe('PostgreSQL type: text, integer, smallint, numeric, boolean, date, timestamp, timestamptz, time, json, jsonb, inet, email, url, image, upload'),
51
96
  is_required: z.boolean().describe('Whether the field is NOT NULL. Defaults to false.').optional(),
52
97
  default_value: z
53
- .union([z.string(), z.null()])
54
- .describe('SQL default expression, e.g. "now()", "\'draft\'"')
98
+ .union([z.string(), z.number(), z.boolean(), z.null()])
99
+ .describe('SQL default expression as text, e.g. "now()", "\'draft\'"; or a number, true or false for a constant')
55
100
  .optional(),
56
101
  is_unique: z
57
102
  .boolean()
58
103
  .describe('Whether the field has a unique constraint. Defaults to false.')
59
104
  .optional(),
60
105
  });
106
+ /** What create_field checks before it changes anything: the project, the table, and that the field's stored name is free. */
107
+ export async function createFieldReady(params, cwd) {
108
+ const ready = await namedReady(cwd, params.table_name);
109
+ if (ready.kind === 'failed')
110
+ return ready;
111
+ const taken = fieldTaken(ready.value.table, params.field_name, storedName(params.field_name) ?? params.field_name);
112
+ return taken ? { kind: 'failed', failure: taken } : ready;
113
+ }
61
114
  export const createFieldTool = {
62
115
  name: 'create_field',
63
116
  label: 'Create field',
64
117
  description: 'Add a new field (column) to an existing table in the project database.',
65
118
  promptSnippet: 'create_field: add a column to an existing table. Gated.',
66
119
  parameters: CreateFieldZod,
120
+ effect: 'write',
67
121
  async execute(params, ctx) {
68
- const resolved = await resolveProjectContext(ctx.cwd);
69
- if (!resolved.context)
70
- return fail(resolved.reason);
71
- const { api, databaseId } = resolved.context;
122
+ const ready = await createFieldReady(params, ctx.cwd);
123
+ if (ready.kind === 'failed')
124
+ return fail(ready.failure);
125
+ const { context, table } = ready.value;
126
+ const { api, databaseId } = context;
72
127
  try {
73
- const schema = await resolveSchema(resolved.context);
74
- const table = resolveTable(schema, params.table_name);
75
128
  const result = await api.field
76
129
  .create({
77
130
  data: {
@@ -86,145 +139,238 @@ export const createFieldTool = {
86
139
  })
87
140
  .unwrap();
88
141
  const createdId = result.createField?.field?.id;
89
- if (params.is_unique && createdId) {
142
+ if (!createdId) {
143
+ return fail(noRowCreated(`Failed to add field "${params.field_name}" to "${params.table_name}"`, DESCRIBE_SCHEMA));
144
+ }
145
+ // The backend stores the name it was given in its own form (inflection.underscore).
146
+ const stored = result.createField.field.name ?? params.field_name;
147
+ const field = stored === params.field_name ? stored : `${stored} (stored from "${params.field_name}")`;
148
+ const added = `Added field ${table.name}.${field}.`;
149
+ if (params.is_unique) {
150
+ const hint = 'Add the unique constraint to the field again.';
151
+ const retry = suggest('update_field', { table_name: table.name, field_name: stored, is_unique: true }, 'Add the unique constraint');
90
152
  try {
91
- await api.uniqueConstraint
153
+ const constraint = await api.uniqueConstraint
92
154
  .create({
93
155
  data: {
94
156
  tableId: table.id,
95
157
  databaseId,
96
158
  fieldIds: [createdId],
97
- name: `${table.name}_${params.field_name}_key`,
159
+ name: `${table.name}_${stored}_key`,
98
160
  type: 'u',
99
161
  },
100
162
  select: { id: true },
101
163
  })
102
164
  .unwrap();
165
+ if (!constraint.createUniqueConstraint?.uniqueConstraint) {
166
+ return partial(added, noRowCreated('The unique constraint was not created'), hint, retry);
167
+ }
103
168
  }
104
169
  catch (err) {
105
- console.warn('Failed to create unique constraint:', err);
170
+ return partial(added, failureFromError(err, 'The unique constraint was not created'), hint, retry);
106
171
  }
107
172
  }
108
- return ok(`Added field ${params.table_name}.${params.field_name}`);
173
+ return ok(added);
109
174
  }
110
175
  catch (err) {
111
- return fail(err instanceof Error ? err.message : 'Failed to create field');
176
+ return fail(failureFromError(err, `Failed to add field "${params.field_name}" to "${params.table_name}"`, {
177
+ taken: `a field named "${params.field_name}" already exists on "${params.table_name}".`,
178
+ check: DESCRIBE_SCHEMA,
179
+ }));
112
180
  }
113
181
  },
114
182
  };
115
183
  // ── update_field ──────────────────────────────────────────────────────────
116
- const UpdateFieldZod = z.object({
117
- table_name: z.string().describe('Name of the table containing the field'),
118
- field_name: z.string().describe('Current field name'),
119
- new_name: z.string().describe('New field name in snake_case (if renaming)').optional(),
120
- new_type: z.string().describe('New PostgreSQL type (if changing type)').optional(),
184
+ const UpdateFieldZod = strictObject('the input', {
185
+ table_name: identifierParam().describe('Name of the table containing the field'),
186
+ field_name: identifierParam().describe('Current field name'),
187
+ new_name: identifierParam().describe('New field name in snake_case (if renaming)').optional(),
121
188
  is_required: z.boolean().describe('Set NOT NULL constraint').optional(),
122
189
  default_value: z
123
- .union([z.string(), z.null()])
124
- .describe('New SQL default expression, or null to remove')
190
+ .union([z.string(), z.number(), z.boolean(), z.null()])
191
+ .describe('New SQL default expression as text, a number, true or false for a constant, or null to remove')
125
192
  .optional(),
126
193
  is_unique: z.boolean().describe('Set or remove unique constraint').optional(),
127
194
  });
195
+ const UPDATE_FIELD_CHANGES = ['new_name', 'is_required', 'default_value', 'is_unique'];
196
+ /** What update_field checks before it changes anything: a change to make, and the project. */
197
+ export async function updateFieldReady(params, cwd) {
198
+ if (!UPDATE_FIELD_CHANGES.some((key) => params[key] !== undefined)) {
199
+ return {
200
+ kind: 'failed',
201
+ failure: {
202
+ code: 'invalid-input',
203
+ message: 'The call gives no change: rename the field, or set whether it is required or unique, or its default.',
204
+ },
205
+ };
206
+ }
207
+ const ready = await namedReady(cwd, params.table_name, params.field_name);
208
+ if (ready.kind === 'failed')
209
+ return ready;
210
+ const { table, field } = ready.value;
211
+ // The backend keeps a new name of a field as it is given.
212
+ const taken = params.new_name ? fieldTaken(table, params.new_name, params.new_name, field.id) : null;
213
+ return taken ? { kind: 'failed', failure: taken } : { kind: 'ok', value: { ...ready.value, field } };
214
+ }
215
+ /** Adds or removes the field's unique constraint as asked: whether it changed, or why it could not. */
216
+ async function setUnique(context, table, field, params) {
217
+ if (params.is_unique === undefined)
218
+ return 'unchanged';
219
+ const existingUniqueId = findUniqueConstraintId(table, field.id);
220
+ try {
221
+ if (params.is_unique && !existingUniqueId) {
222
+ const result = await context.api.uniqueConstraint
223
+ .create({
224
+ data: {
225
+ tableId: table.id,
226
+ databaseId: context.databaseId,
227
+ fieldIds: [field.id],
228
+ name: `${table.name}_${params.new_name ?? field.name}_key`,
229
+ type: 'u',
230
+ },
231
+ select: { id: true },
232
+ })
233
+ .unwrap();
234
+ if (!result.createUniqueConstraint?.uniqueConstraint)
235
+ return noRowCreated('The unique constraint was not added', DESCRIBE_SCHEMA);
236
+ return 'changed';
237
+ }
238
+ if (!params.is_unique && existingUniqueId) {
239
+ const result = await context.api.uniqueConstraint
240
+ .delete({ where: { id: existingUniqueId }, select: { id: true } })
241
+ .unwrap();
242
+ if (!result.deleteUniqueConstraint?.uniqueConstraint) {
243
+ return noRowsChanged('The unique constraint was not removed', DESCRIBE_SCHEMA);
244
+ }
245
+ return 'changed';
246
+ }
247
+ return 'unchanged';
248
+ }
249
+ catch (err) {
250
+ return failureFromError(err, `The unique constraint was not ${params.is_unique ? 'added' : 'removed'}`);
251
+ }
252
+ }
128
253
  export const updateFieldTool = {
129
254
  name: 'update_field',
130
255
  label: 'Update field',
131
- description: 'Modify an existing field: rename, change type, toggle required/unique, or set default.',
132
- promptSnippet: 'update_field: rename/retype/toggle an existing column. Gated.',
256
+ description: 'Modify an existing field: rename it, toggle required or unique, or set or remove its default. Its data stays.',
257
+ promptSnippet: 'update_field: rename an existing column, or change whether it is required or unique, or its default. Gated.',
133
258
  parameters: UpdateFieldZod,
259
+ effect: 'write',
134
260
  async execute(params, ctx) {
135
- const resolved = await resolveProjectContext(ctx.cwd);
136
- if (!resolved.context)
137
- return fail(resolved.reason);
138
- const { api, databaseId } = resolved.context;
261
+ const ready = await updateFieldReady(params, ctx.cwd);
262
+ if (ready.kind === 'failed')
263
+ return fail(ready.failure);
264
+ const { context, table, field } = ready.value;
265
+ const target = `${params.table_name}.${params.field_name}`;
139
266
  try {
140
- const schema = await resolveSchema(resolved.context);
141
- const table = resolveTable(schema, params.table_name);
142
- const field = resolveField(table, params.field_name);
143
267
  const patch = {};
144
268
  if (params.new_name)
145
269
  patch.name = params.new_name;
146
- if (params.new_type)
147
- patch.type = toFieldType(params.new_type);
148
270
  if (params.is_required !== undefined)
149
271
  patch.isRequired = params.is_required;
150
272
  if (params.default_value !== undefined) {
151
273
  patch.defaultValue =
152
274
  params.default_value === null ? null : (toFieldDefault(params.default_value) ?? null);
153
275
  }
154
- if (Object.keys(patch).length > 0) {
155
- await api.field
276
+ const patched = Object.keys(patch).length > 0;
277
+ if (patched) {
278
+ const result = await context.api.field
156
279
  .update({
157
280
  where: { id: field.id },
158
281
  data: patch,
159
282
  select: { id: true, name: true, type: true },
160
283
  })
161
284
  .unwrap();
162
- }
163
- if (params.is_unique !== undefined) {
164
- const existingUniqueId = findUniqueConstraintId(table, field.id);
165
- if (params.is_unique && !existingUniqueId) {
166
- try {
167
- await api.uniqueConstraint
168
- .create({
169
- data: {
170
- tableId: table.id,
171
- databaseId,
172
- fieldIds: [field.id],
173
- name: `${table.name}_${params.new_name ?? field.name}_key`,
174
- type: 'u',
175
- },
176
- select: { id: true },
177
- })
178
- .unwrap();
179
- }
180
- catch (err) {
181
- console.warn('Failed to create unique constraint:', err);
182
- }
183
- }
184
- else if (!params.is_unique && existingUniqueId) {
185
- try {
186
- await api.uniqueConstraint
187
- .delete({ where: { id: existingUniqueId }, select: { id: true } })
188
- .unwrap();
189
- }
190
- catch (err) {
191
- console.warn('Failed to delete unique constraint:', err);
192
- }
285
+ if (!result.updateField?.field) {
286
+ return fail(noRowsChanged(`Failed to update field "${params.field_name}" on "${params.table_name}"`, DESCRIBE_SCHEMA));
193
287
  }
194
288
  }
195
- return ok(`Updated field ${params.table_name}.${params.field_name}`);
289
+ const unique = await setUnique(context, table, field, params);
290
+ if (typeof unique === 'object') {
291
+ if (!patched)
292
+ return fail(unique, [unique.message]);
293
+ const retry = suggest('update_field', { table_name: params.table_name, field_name: params.new_name ?? params.field_name, is_unique: params.is_unique }, 'Retry the unique constraint alone');
294
+ return partial(`Updated field ${target}.`, unique, `Retry the unique constraint alone; the other changes are made.`, retry);
295
+ }
296
+ if (!patched && unique === 'unchanged') {
297
+ return ok(`Field ${target} is already ${params.is_unique ? 'unique' : 'not unique'}; nothing changed.`);
298
+ }
299
+ return ok(`Updated field ${target}`);
196
300
  }
197
301
  catch (err) {
198
- return fail(err instanceof Error ? err.message : 'Failed to update field');
302
+ return fail(failureFromError(err, `Failed to update field "${params.field_name}" on "${params.table_name}"`, {
303
+ ...(params.new_name
304
+ ? { taken: `a field named "${params.new_name}" already exists on "${params.table_name}".`, check: DESCRIBE_SCHEMA }
305
+ : {}),
306
+ }));
307
+ }
308
+ },
309
+ };
310
+ // ── retype_field ──────────────────────────────────────────────────────────
311
+ const RetypeFieldZod = strictObject('the input', {
312
+ table_name: identifierParam().describe('Name of the table containing the field'),
313
+ field_name: identifierParam().describe('Name of the field'),
314
+ type: textParam().describe('The new PostgreSQL type, for example integer or text[]'),
315
+ });
316
+ /** What retype_field checks before it changes anything: the project, the table and the field. */
317
+ export const retypeFieldReady = (params, cwd) => namedReady(cwd, params.table_name, params.field_name);
318
+ export const retypeFieldTool = {
319
+ name: 'retype_field',
320
+ label: 'Retype field',
321
+ description: 'Change the type of an existing field. Every value is converted; a value that does not fit fails the change or loses data. Destructive.',
322
+ promptSnippet: 'retype_field: change the type of an existing column; the cast can lose data. Destructive — gated.',
323
+ parameters: RetypeFieldZod,
324
+ effect: 'destructive',
325
+ async execute(params, ctx) {
326
+ const ready = await retypeFieldReady(params, ctx.cwd);
327
+ if (ready.kind === 'failed')
328
+ return fail(ready.failure);
329
+ const { context, field } = ready.value;
330
+ const action = `Failed to change the type of field "${params.field_name}" on "${params.table_name}"`;
331
+ try {
332
+ const result = await context.api.field
333
+ .update({ where: { id: field.id }, data: { type: toFieldType(params.type) }, select: { id: true } })
334
+ .unwrap();
335
+ if (!result.updateField?.field)
336
+ return fail(noRowsChanged(action, DESCRIBE_SCHEMA));
337
+ return ok(`Changed the type of field ${params.table_name}.${params.field_name} to ${params.type}.`);
338
+ }
339
+ catch (err) {
340
+ return fail(failureFromError(err, action));
199
341
  }
200
342
  },
201
343
  };
202
344
  // ── delete_field ──────────────────────────────────────────────────────────
203
- const DeleteFieldZod = z.object({
204
- table_name: z.string().describe('Name of the table containing the field'),
205
- field_name: z.string().describe('Name of the field to delete'),
345
+ const DeleteFieldZod = strictObject('the input', {
346
+ table_name: identifierParam().describe('Name of the table containing the field'),
347
+ field_name: identifierParam().describe('Name of the field to delete'),
206
348
  });
349
+ /** What delete_field checks before it changes anything: the project, the table and the field. */
350
+ export const deleteFieldReady = (params, cwd) => namedReady(cwd, params.table_name, params.field_name);
207
351
  export const deleteFieldTool = {
208
352
  name: 'delete_field',
209
353
  label: 'Delete field',
210
354
  description: 'Permanently delete a field (column) from an existing table.',
211
355
  promptSnippet: 'delete_field: drop a column from a table by name. Destructive — gated.',
212
356
  parameters: DeleteFieldZod,
357
+ effect: 'destructive',
213
358
  async execute(params, ctx) {
214
- const resolved = await resolveProjectContext(ctx.cwd);
215
- if (!resolved.context)
216
- return fail(resolved.reason);
359
+ const ready = await deleteFieldReady(params, ctx.cwd);
360
+ if (ready.kind === 'failed')
361
+ return fail(ready.failure);
362
+ const { context, field } = ready.value;
217
363
  try {
218
- const schema = await resolveSchema(resolved.context);
219
- const table = resolveTable(schema, params.table_name);
220
- const field = resolveField(table, params.field_name);
221
- await resolved.context.api.field
364
+ const result = await context.api.field
222
365
  .delete({ where: { id: field.id }, select: { id: true } })
223
366
  .unwrap();
224
- return ok(`Deleted field ${params.table_name}.${params.field_name}`);
367
+ if (!result.deleteField?.field) {
368
+ return fail(noRowsChanged(`Failed to delete field "${params.field_name}" from "${params.table_name}"`, DESCRIBE_SCHEMA));
369
+ }
370
+ return ok(`Deleted field ${params.table_name}.${params.field_name}.`);
225
371
  }
226
372
  catch (err) {
227
- return fail(err instanceof Error ? err.message : 'Failed to delete field');
373
+ return fail(failureFromError(err, `Failed to delete field "${params.field_name}" from "${params.table_name}"`));
228
374
  }
229
375
  },
230
376
  };
@@ -1,12 +1,36 @@
1
- import { BlueprintZod, type HarnessTool } from '@agentic-kit/harness';
1
+ import type { HarnessTool } from '@agentic-kit/harness';
2
+ import type { BlueprintDefinition } from 'node-type-registry';
3
+ import { type RelatedColumns } from '../access/words';
4
+ import { type Blueprint, BlueprintZod } from '../blueprint/blueprint-schema';
5
+ import type { ProjectContext } from '../context';
6
+ import { type Result } from '../failure';
7
+ export type ProvisionBlueprintReady = ProjectContext & {
8
+ ownerId: string;
9
+ definition: BlueprintDefinition;
10
+ related?: RelatedColumns;
11
+ };
12
+ /**
13
+ * What provision_blueprint checks before it changes anything: an owned
14
+ * project, a blueprint the registry's JSON Schema takes once its defaults are
15
+ * filled in, rules that fit their nodes and the roles of the database, the
16
+ * schemas it names, none of its new tables yet, and the tables its relations
17
+ * name.
18
+ */
19
+ export declare function provisionBlueprintReady(params: Blueprint, cwd: string): Promise<Result<ProvisionBlueprintReady>>;
2
20
  type ProvisionedField = {
21
+ /** As the backend stored it. */
3
22
  name: string;
23
+ /** The name the blueprint gave, when the backend stored another. */
24
+ requestedName?: string;
4
25
  type: string;
5
26
  isRequired: boolean;
6
27
  defaultValue: string | null;
7
28
  };
8
29
  type ProvisionedTable = {
30
+ /** As the backend stored it. */
9
31
  name: string;
32
+ /** The name the blueprint gave, when the backend stored another. */
33
+ requestedName?: string;
10
34
  fields: ProvisionedField[];
11
35
  policies: string[];
12
36
  relationCount: number;