@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,7 +1,9 @@
1
- import { filterInternalPolicies } from '@agentic-kit/harness';
1
+ import { alignColumns, strictObject, textParam } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
3
  import { buildBlueprint } from '../blueprint-construction';
4
- import { resolveProjectContext } from '../context';
4
+ import { DESCRIBE_SCHEMA, failedResult, failureFromError, failureFromErrors, failureText, noRowCreated, noRowsChanged, suggest, ToolFailureError, } from '../failure';
5
+ import { ownedProjectReady, projectReady } from '../ready';
6
+ import { readSchemas, schemasMissing, storedTableNames, tablesTaken } from '../schema-resolve';
5
7
  // A stored blueprint field's `type` is an expanded object (`{ name: 'text' }`),
6
8
  // not the bare string the agent passes to provision_blueprint. Flatten it to the
7
9
  // type name so the renderer gets a string, never an object (which React can't
@@ -39,23 +41,24 @@ function parseTemplateTables(definition) {
39
41
  defaultValue: typeof field.default === 'string' ? field.default : null,
40
42
  };
41
43
  }),
42
- policies: filterInternalPolicies(policies.map((policy) => policy.$type ?? '').filter(Boolean)),
44
+ policies: [...new Set(policies.map((policy) => policy.$type ?? '').filter(Boolean))],
43
45
  relationCount: relations.filter((relation) => relation.source_table === table.table_name).length,
44
46
  };
45
47
  });
46
48
  }
47
49
  function formatTemplatesText(templates) {
48
50
  if (templates.length === 0)
49
- return 'No blueprint templates available.';
50
- const lines = [`Available blueprint templates (${templates.length}):`];
51
- for (const template of templates) {
52
- const cats = template.categories.length ? ` [${template.categories.join(', ')}]` : '';
53
- lines.push(` ${template.displayName} — ${template.tables.length} tables${cats}`);
54
- for (const table of template.tables) {
55
- lines.push(` - ${table.name} (${table.fields.length} field${table.fields.length === 1 ? '' : 's'})`);
56
- }
57
- }
58
- return lines.join('\n');
51
+ return 'No templates yet.';
52
+ return alignColumns([
53
+ ['NAME', 'VERSION', 'TABLES', 'TAGS', 'ID'],
54
+ ...templates.map((template) => [
55
+ template.displayName || '(no name)',
56
+ template.version ?? '',
57
+ String(template.tables.length),
58
+ template.categories.join(', '),
59
+ template.id,
60
+ ]),
61
+ ]).join('\n');
59
62
  }
60
63
  // The latest project blueprint (or a named one) — the definition source for
61
64
  // create_template, and for the confirm preview of the tables it will template.
@@ -100,54 +103,80 @@ export async function createTemplatePreviewTables(context, blueprintName) {
100
103
  return { blueprintName: '', tables: [] };
101
104
  }
102
105
  }
103
- async function resolveTemplateId(client, displayName) {
106
+ async function findTemplate(client, displayName) {
104
107
  const result = await client.blueprintTemplate
105
108
  .findMany({
106
- select: { id: true, displayName: true },
109
+ select: { id: true, displayName: true, definition: true },
107
110
  where: { displayName: { equalTo: displayName } },
108
111
  first: 1,
109
112
  })
110
113
  .unwrap();
111
114
  const template = result.blueprintTemplates?.nodes?.[0];
112
- if (!template?.id)
113
- throw new Error(`Template "${displayName}" not found`);
114
- return template.id;
115
+ if (!template?.id) {
116
+ throw new ToolFailureError({
117
+ code: 'not-found',
118
+ message: `Template "${displayName}" not found.`,
119
+ hint: 'Check the template names that exist, then retry.',
120
+ calls: [suggest('list_templates', {}, 'See the templates that exist')],
121
+ });
122
+ }
123
+ return { id: template.id, definition: template.definition };
124
+ }
125
+ /** What update_template and delete_template check before they change anything: the project, and the template. */
126
+ export async function templateReady(params, cwd) {
127
+ const ready = await projectReady(cwd);
128
+ if (ready.kind === 'failed')
129
+ return ready;
130
+ try {
131
+ return { kind: 'ok', value: { context: ready.value, templateId: (await findTemplate(ready.value.modules, params.templateName)).id } };
132
+ }
133
+ catch (err) {
134
+ return { kind: 'failed', failure: failureFromError(err, `Failed to read the template "${params.templateName}"`) };
135
+ }
136
+ }
137
+ function done(message) {
138
+ return { content: [{ type: 'text', text: message }], details: { success: true, message } };
115
139
  }
116
- function done(success, message) {
117
- return { content: [{ type: 'text', text: message }], details: { success, message } };
140
+ function fail(failure) {
141
+ return failedResult(failure, { success: false, message: failureText(failure) });
118
142
  }
119
143
  // ── list_templates ────────────────────────────────────────────────────────
120
- const ListTemplatesZod = z.object({});
144
+ const ListTemplatesZod = strictObject('the input', {});
121
145
  export const listTemplatesTool = {
122
146
  name: 'list_templates',
123
147
  label: 'List templates',
124
- description: 'List the blueprint templates available to provision into the project database (display name, description, categories, table count). Read-only — these are a global catalog, not the project schema.',
148
+ description: 'List the blueprint templates this account can apply to the project database: its own and the public ones (display name, description, categories, table count). Read-only — these are a template catalog, not the project schema.',
125
149
  promptSnippet: 'list_templates: list the available blueprint templates to apply. Read-only — call before apply_template.',
126
150
  parameters: ListTemplatesZod,
151
+ effect: 'read',
127
152
  async execute(_params, ctx) {
128
- const resolved = await resolveProjectContext(ctx.cwd);
129
- if (!resolved.context) {
130
- return { content: [{ type: 'text', text: resolved.reason }], details: { templates: [] } };
153
+ const ready = await projectReady(ctx.cwd);
154
+ if (ready.kind === 'failed')
155
+ return failedResult(ready.failure, { templates: [] });
156
+ let result;
157
+ try {
158
+ result = await ready.value.modules.blueprintTemplate
159
+ .findMany({
160
+ select: {
161
+ id: true,
162
+ version: true,
163
+ displayName: true,
164
+ description: true,
165
+ categories: true,
166
+ definition: true,
167
+ },
168
+ orderBy: ['NAME_ASC'],
169
+ })
170
+ .execute();
131
171
  }
132
- const result = await resolved.context.modules.blueprintTemplate
133
- .findMany({
134
- select: {
135
- displayName: true,
136
- description: true,
137
- categories: true,
138
- definition: true,
139
- },
140
- orderBy: ['NAME_ASC'],
141
- })
142
- .execute();
143
- if (!result.ok) {
144
- const message = result.errors.map((e) => e.message).join('; ');
145
- return {
146
- content: [{ type: 'text', text: `Failed to read templates: ${message}` }],
147
- details: { templates: [] },
148
- };
172
+ catch (err) {
173
+ return failedResult(failureFromError(err, 'Failed to read templates'), { templates: [] });
149
174
  }
175
+ if (!result.ok)
176
+ return failedResult(failureFromErrors(result.errors, 'Failed to read templates'), { templates: [] });
150
177
  const templates = (result.data.blueprintTemplates?.nodes ?? []).map((template) => ({
178
+ id: template.id,
179
+ version: template.version ?? null,
151
180
  displayName: template.displayName ?? '',
152
181
  description: template.description ?? null,
153
182
  categories: Array.isArray(template.categories) ? template.categories : [],
@@ -160,39 +189,41 @@ export const listTemplatesTool = {
160
189
  },
161
190
  };
162
191
  // ── create_template ───────────────────────────────────────────────────────
163
- const CreateTemplateZod = z.object({
164
- displayName: z.string().describe('Display name for the new blueprint template'),
165
- blueprintName: z
166
- .string()
192
+ const CreateTemplateZod = strictObject('the input', {
193
+ displayName: textParam().describe('Display name for the new blueprint template'),
194
+ blueprintName: textParam()
167
195
  .describe('Display name of an existing project blueprint to save as the template. Defaults to the most recently provisioned blueprint.')
168
196
  .optional(),
169
197
  description: z.string().describe('Description shown in the template catalog').optional(),
170
198
  categories: z
171
- .array(z.string())
199
+ .array(textParam())
172
200
  .describe('Categories for catalog grouping and discovery')
173
201
  .optional(),
174
202
  });
175
203
  export const createTemplateTool = {
176
204
  name: 'create_template',
177
205
  label: 'Create template',
178
- description: 'Save an existing project blueprint into the global template catalog as a reusable blueprint template. Defaults to the most recently provisioned blueprint; pass blueprintName to pick a specific one by display name. Gated.',
206
+ description: 'Save an existing project blueprint as a reusable blueprint template in the account\'s template catalog; it stays private until it is made public. Defaults to the most recently provisioned blueprint; give the display name of a blueprint to pick a specific one. Gated.',
179
207
  promptSnippet: 'create_template: save a project blueprint to the reusable template catalog. Gated.',
180
208
  parameters: CreateTemplateZod,
209
+ effect: 'write',
181
210
  async execute(params, ctx) {
182
- const resolved = await resolveProjectContext(ctx.cwd);
183
- if (!resolved.context)
184
- return done(false, resolved.reason);
185
- const { modules, ownerId } = resolved.context;
186
- if (!ownerId)
187
- return done(false, 'Not authenticated (missing OWNER_ID in .env).');
211
+ const ready = await ownedProjectReady(ctx.cwd);
212
+ if (ready.kind === 'failed')
213
+ return fail(ready.failure);
214
+ const { modules, ownerId } = ready.value;
188
215
  try {
189
- const blueprint = await findProjectBlueprint(resolved.context, params.blueprintName);
216
+ const blueprint = await findProjectBlueprint(ready.value, params.blueprintName);
190
217
  if (!blueprint) {
191
218
  const which = params.blueprintName ? `"${params.blueprintName}"` : 'any blueprint';
192
- return done(false, `No project blueprint found (${which}). Provision a blueprint first.`);
219
+ return fail({
220
+ code: 'not-found',
221
+ message: `No project blueprint found (${which}).`,
222
+ hint: 'Create tables from a blueprint first, then retry.',
223
+ });
193
224
  }
194
225
  const base = params.displayName.toLowerCase().replace(/\s+/g, '_');
195
- await modules.blueprintTemplate
226
+ const created = await modules.blueprintTemplate
196
227
  .create({
197
228
  data: {
198
229
  ownerId,
@@ -205,6 +236,9 @@ export const createTemplateTool = {
205
236
  select: { id: true, displayName: true },
206
237
  })
207
238
  .unwrap();
239
+ if (!created.createBlueprintTemplate?.blueprintTemplate) {
240
+ return fail(noRowCreated(`Failed to create template "${params.displayName}"`, suggest('list_templates', {}, 'See the templates that exist')));
241
+ }
208
242
  const message = `Created template "${params.displayName}"`;
209
243
  return {
210
244
  content: [{ type: 'text', text: message }],
@@ -218,33 +252,56 @@ export const createTemplateTool = {
218
252
  };
219
253
  }
220
254
  catch (err) {
221
- return done(false, err instanceof Error ? err.message : 'Failed to create template');
255
+ return fail(failureFromError(err, `Failed to create template "${params.displayName}"`));
222
256
  }
223
257
  },
224
258
  };
225
259
  // ── apply_template ────────────────────────────────────────────────────────
226
- const ApplyTemplateZod = z.object({
227
- templateName: z.string().describe('The display name of the blueprint template to apply'),
228
- nameOverride: z
229
- .string()
260
+ const ApplyTemplateZod = strictObject('the input', {
261
+ templateName: textParam().describe('The display name of the blueprint template to apply'),
262
+ nameOverride: textParam()
230
263
  .describe('Optional name override for the created blueprint (snake_case). Defaults to template name.')
231
264
  .optional(),
232
265
  });
266
+ /**
267
+ * What apply_template checks before it changes anything: an owned project,
268
+ * the template, and none of its tables in the project yet.
269
+ */
270
+ export async function applyTemplateReady(params, cwd) {
271
+ const ready = await ownedProjectReady(cwd);
272
+ if (ready.kind === 'failed')
273
+ return ready;
274
+ let template;
275
+ try {
276
+ template = await findTemplate(ready.value.modules, params.templateName);
277
+ }
278
+ catch (err) {
279
+ return { kind: 'failed', failure: failureFromError(err, `Failed to read the template "${params.templateName}"`) };
280
+ }
281
+ const raw = template.definition;
282
+ const definition = { ...raw, tables: Array.isArray(raw?.tables) ? raw.tables : [] };
283
+ const tables = definition.tables.flatMap((table) => typeof table.table_name === 'string' ? [{ name: table.table_name, schema: table.schema_name }] : []);
284
+ const named = tables.flatMap(({ schema }) => schema === undefined ? [] : [schema]);
285
+ const schemas = named.length ? await readSchemas(ready.value) : { kind: 'ok', value: new Map() };
286
+ if (schemas.kind === 'failed')
287
+ return schemas;
288
+ const conflict = schemasMissing(named, schemas.value) ?? await tablesTaken(ready.value, tables, schemas.value);
289
+ return conflict ? { kind: 'failed', failure: conflict } : { kind: 'ok', value: { context: ready.value, templateId: template.id, definition } };
290
+ }
233
291
  export const applyTemplateTool = {
234
292
  name: 'apply_template',
235
293
  label: 'Apply template',
236
- description: 'Apply an existing blueprint template to the project database, creating its tables. Use the template display name (from list_templates).',
294
+ description: 'Apply an existing blueprint template to the project database, creating its tables. Use the template display name, as the template list gives it.',
237
295
  promptSnippet: 'apply_template: provision a saved blueprint template by display name. Gated.',
238
296
  parameters: ApplyTemplateZod,
297
+ effect: 'write',
239
298
  async execute(params, ctx) {
240
- const resolved = await resolveProjectContext(ctx.cwd);
241
- if (!resolved.context)
242
- return done(false, resolved.reason);
243
- const { modules, databaseId, schemaId, ownerId } = resolved.context;
244
- if (!ownerId)
245
- return done(false, 'Not authenticated (missing OWNER_ID in .env).');
299
+ const ready = await applyTemplateReady(params, ctx.cwd);
300
+ if (ready.kind === 'failed')
301
+ return fail(ready.failure);
302
+ const { context, templateId } = ready.value;
303
+ const { modules, databaseId, schemaId, ownerId } = context;
246
304
  try {
247
- const templateId = await resolveTemplateId(modules, params.templateName);
248
305
  const base = params.nameOverride ?? params.templateName.toLowerCase().replace(/\s+/g, '_');
249
306
  const nameOverride = `${base}_${Date.now()}`;
250
307
  const copyResult = await modules.mutation
@@ -252,24 +309,30 @@ export const applyTemplateTool = {
252
309
  .unwrap();
253
310
  const blueprintId = copyResult.copyTemplateToBlueprint?.result;
254
311
  if (!blueprintId)
255
- throw new Error('Failed to copy template');
312
+ return fail(noRowCreated(`Failed to apply template "${params.templateName}"`, DESCRIBE_SCHEMA));
256
313
  const { tables } = await buildBlueprint(modules, { blueprintId, schemaId }, { signal: ctx.signal });
257
314
  const createdCount = Object.keys(tables).length;
258
- return done(true, `Applied template "${params.templateName}" — created ${createdCount} table${createdCount === 1 ? '' : 's'}`);
315
+ // The construction maps the template's table names to ids; the backend may store a name in another form.
316
+ const stored = await storedTableNames(context, Object.values(tables)).catch(() => new Map());
317
+ const names = Object.entries(tables).map(([given, id]) => {
318
+ const as = stored.get(id) ?? given;
319
+ return as === given ? as : `${as} (stored from "${given}")`;
320
+ });
321
+ return done(`Applied template "${params.templateName}" — created ${createdCount} table${createdCount === 1 ? '' : 's'}${names.length ? `: ${names.join(', ')}` : ''}`);
259
322
  }
260
323
  catch (err) {
261
- return done(false, err instanceof Error ? err.message : 'Failed to apply template');
324
+ return fail(failureFromError(err, `Failed to apply template "${params.templateName}"`));
262
325
  }
263
326
  },
264
327
  };
265
328
  // ── update_template ───────────────────────────────────────────────────────
266
- const UpdateTemplateZod = z.object({
267
- templateName: z.string().describe('The display name of the blueprint template to update'),
268
- patch: z.object({
269
- displayName: z.string().describe('New display name').optional(),
329
+ const UpdateTemplateZod = strictObject('the input', {
330
+ templateName: textParam().describe('The display name of the blueprint template to update'),
331
+ patch: strictObject('a patch', {
332
+ displayName: textParam().describe('New display name').optional(),
270
333
  description: z.string().describe('New description').optional(),
271
- categories: z.array(z.string()).describe('New categories').optional(),
272
- tags: z.array(z.string()).describe('New tags').optional(),
334
+ categories: z.array(textParam()).describe('New categories').optional(),
335
+ tags: z.array(textParam()).describe('New tags').optional(),
273
336
  visibility: z.enum(['private', 'public']).describe('New visibility').optional(),
274
337
  }),
275
338
  });
@@ -279,29 +342,33 @@ export const updateTemplateTool = {
279
342
  description: 'Update a blueprint template’s metadata (display name, description, categories, tags, visibility).',
280
343
  promptSnippet: 'update_template: edit a saved template’s metadata by display name. Gated.',
281
344
  parameters: UpdateTemplateZod,
345
+ effect: 'write',
282
346
  async execute(params, ctx) {
283
- const resolved = await resolveProjectContext(ctx.cwd);
284
- if (!resolved.context)
285
- return done(false, resolved.reason);
347
+ const ready = await templateReady(params, ctx.cwd);
348
+ if (ready.kind === 'failed')
349
+ return fail(ready.failure);
350
+ const { context, templateId } = ready.value;
286
351
  try {
287
- const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
288
- await resolved.context.modules.blueprintTemplate
352
+ const result = await context.modules.blueprintTemplate
289
353
  .update({
290
354
  where: { id: templateId },
291
355
  data: params.patch,
292
356
  select: { id: true, displayName: true },
293
357
  })
294
358
  .unwrap();
295
- return done(true, `Updated template "${params.templateName}"`);
359
+ if (!result.updateBlueprintTemplate?.blueprintTemplate) {
360
+ return fail(noRowsChanged(`Failed to update template "${params.templateName}"`, suggest('list_templates', {}, 'See the templates that exist')));
361
+ }
362
+ return done(`Updated template "${params.templateName}"`);
296
363
  }
297
364
  catch (err) {
298
- return done(false, err instanceof Error ? err.message : 'Failed to update template');
365
+ return fail(failureFromError(err, `Failed to update template "${params.templateName}"`));
299
366
  }
300
367
  },
301
368
  };
302
369
  // ── delete_template ───────────────────────────────────────────────────────
303
- const DeleteTemplateZod = z.object({
304
- templateName: z.string().describe('The display name of the blueprint template to delete'),
370
+ const DeleteTemplateZod = strictObject('the input', {
371
+ templateName: textParam().describe('The display name of the blueprint template to delete'),
305
372
  });
306
373
  export const deleteTemplateTool = {
307
374
  name: 'delete_template',
@@ -309,19 +376,23 @@ export const deleteTemplateTool = {
309
376
  description: 'Permanently delete a blueprint template by its display name.',
310
377
  promptSnippet: 'delete_template: remove a saved template by display name. Destructive — gated.',
311
378
  parameters: DeleteTemplateZod,
379
+ effect: 'destructive',
312
380
  async execute(params, ctx) {
313
- const resolved = await resolveProjectContext(ctx.cwd);
314
- if (!resolved.context)
315
- return done(false, resolved.reason);
381
+ const ready = await templateReady(params, ctx.cwd);
382
+ if (ready.kind === 'failed')
383
+ return fail(ready.failure);
384
+ const { context, templateId } = ready.value;
316
385
  try {
317
- const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
318
- await resolved.context.modules.blueprintTemplate
386
+ const result = await context.modules.blueprintTemplate
319
387
  .delete({ where: { id: templateId }, select: { id: true } })
320
388
  .unwrap();
321
- return done(true, `Deleted template "${params.templateName}"`);
389
+ if (!result.deleteBlueprintTemplate?.blueprintTemplate) {
390
+ return fail(noRowsChanged(`Failed to delete template "${params.templateName}"`, suggest('list_templates', {}, 'See the templates that exist')));
391
+ }
392
+ return done(`Deleted template "${params.templateName}"`);
322
393
  }
323
394
  catch (err) {
324
- return done(false, err instanceof Error ? err.message : 'Failed to delete template');
395
+ return fail(failureFromError(err, `Failed to delete template "${params.templateName}"`));
325
396
  }
326
397
  },
327
398
  };
package/failure.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { failureText, type HarnessToolResult, type ToolCallSuggestion, type ToolFailure } from '@agentic-kit/harness';
2
+ import { type GraphQLError } from './graphql-http';
3
+ export { failureText };
4
+ /** A value, or the failure that says why there is none. */
5
+ export type Result<T> = {
6
+ kind: 'ok';
7
+ value: T;
8
+ } | {
9
+ kind: 'failed';
10
+ failure: ToolFailure;
11
+ };
12
+ /** A failure a helper raises for the tool that called it to report as is. */
13
+ export declare class ToolFailureError extends Error {
14
+ readonly failure: ToolFailure;
15
+ constructor(failure: ToolFailure);
16
+ }
17
+ /** A failed call, with the tool's own `details`. */
18
+ export declare function failedResult<TDetails>(failure: ToolFailure, details: TDetails): HarnessToolResult<TDetails>;
19
+ export declare function noBackendFailure(hint?: string): ToolFailure;
20
+ /** A call to suggest; `choose` names the inputs the caller must still choose, which `why` explains. */
21
+ export declare const suggest: (tool: string, input: Record<string, unknown>, why: string, choose?: string[]) => ToolCallSuggestion;
22
+ export declare const DESCRIBE_SCHEMA: ToolCallSuggestion;
23
+ /** No database is bound yet: the call that makes one, with its name left to choose. */
24
+ export declare const NEW_DATABASE: ToolCallSuggestion;
25
+ /**
26
+ * An update or delete the backend answered without an error but with no row in
27
+ * its payload: on the latest server that is how row-level security answers for
28
+ * a row this account cannot see, and how any server answers for a row that is
29
+ * gone. `check` is the call that lists what exists.
30
+ */
31
+ export declare function noRowsChanged(action: string, check: ToolCallSuggestion): ToolFailure;
32
+ /** What a row the backend answered without is, in a row's own record (add_records' failedRows). */
33
+ export declare const NO_NEW_ROW = "The backend answered without the new row, so it may not exist, or this account may not read it.";
34
+ /**
35
+ * A create the backend answered without an error but without the new row:
36
+ * the row may not exist, or a policy lets this account create it but not
37
+ * read it back. `check` is the call that shows whether it exists, when a tool
38
+ * has one.
39
+ */
40
+ export declare function noRowCreated(action: string, check?: ToolCallSuggestion): ToolFailure;
41
+ /**
42
+ * A project binding with values that are not of their form (`keys`, in `where`): none of them is used, sent or shown,
43
+ * so the project acts as bound to no database until the person fixes them.
44
+ */
45
+ export declare function invalidBinding(keys: readonly string[], where?: string): ToolFailure;
46
+ export declare const MISSING_OWNER: ToolFailure;
47
+ /**
48
+ * What the call means, when it knows. `taken` names a unique value that is
49
+ * already taken ('a field named "slug" already exists on "posts"'), and
50
+ * `check` the read that shows what exists; without `taken`, a duplicate is a
51
+ * `conflict` with other rows. `rows` names the app table a call on rows acts
52
+ * on, so a refusal suggests the read of its rules; a refusal on the control
53
+ * plane is about the account's rights on the database, which those rules do
54
+ * not decide. `notNull` is what a refused NOT NULL means for a call that adds
55
+ * required columns to a table that may have rows. `policyTypes` are the policy
56
+ * types a call that builds access rules sends, for the calls that show their
57
+ * parameters when a rule is refused.
58
+ */
59
+ export type FailureMeaning = {
60
+ taken?: string;
61
+ check?: ToolCallSuggestion;
62
+ rows?: {
63
+ table: string;
64
+ };
65
+ notNull?: {
66
+ message: string;
67
+ hint: string;
68
+ calls: ToolCallSuggestion[];
69
+ };
70
+ policyTypes?: readonly string[];
71
+ };
72
+ /** The read of a table's rules, for a refusal on its rows. */
73
+ export declare const explainAccessCall: (table: string) => ToolCallSuggestion;
74
+ /** The next step of a refusal on the rows of an app table, in words. */
75
+ export declare const ROWS_REFUSED_HINT = "The table's rules or grants refuse this person: read the rules of the table to see who they let in.";
76
+ /**
77
+ * A failed backend answer as a failure. `action` says what was attempted
78
+ * ("Failed to delete table \"posts\""); the meaning of the code follows it, or,
79
+ * for a code with no sentence here, the code itself. The public code decides
80
+ * first (packages/errors/src/registry.ts), then the HTTP status (the one the
81
+ * server put inside the error first), then a masked internal error with its
82
+ * id. A message's text never decides and is never shown.
83
+ */
84
+ export declare function failureFromErrors(errors: readonly GraphQLError[], action: string, meaning?: FailureMeaning): ToolFailure;
85
+ /**
86
+ * A thrown error as a failure: a `ToolFailureError` keeps its own, an SDK
87
+ * error is classified by its GraphQL errors, anything else is `failed`.
88
+ */
89
+ export declare function failureFromError(err: unknown, action: string, meaning?: FailureMeaning): ToolFailure;