@agentic-kit/db-tools 0.12.47 → 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
@@ -2,10 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteTemplateTool = exports.updateTemplateTool = exports.applyTemplateTool = exports.createTemplateTool = exports.listTemplatesTool = void 0;
4
4
  exports.createTemplatePreviewTables = createTemplatePreviewTables;
5
+ exports.templateReady = templateReady;
6
+ exports.applyTemplateReady = applyTemplateReady;
5
7
  const harness_1 = require("@agentic-kit/harness");
6
8
  const zod_1 = require("zod");
7
9
  const blueprint_construction_1 = require("../blueprint-construction");
8
- const context_1 = require("../context");
10
+ const failure_1 = require("../failure");
11
+ const ready_1 = require("../ready");
12
+ const schema_resolve_1 = require("../schema-resolve");
9
13
  // A stored blueprint field's `type` is an expanded object (`{ name: 'text' }`),
10
14
  // not the bare string the agent passes to provision_blueprint. Flatten it to the
11
15
  // type name so the renderer gets a string, never an object (which React can't
@@ -43,23 +47,24 @@ function parseTemplateTables(definition) {
43
47
  defaultValue: typeof field.default === 'string' ? field.default : null,
44
48
  };
45
49
  }),
46
- policies: (0, harness_1.filterInternalPolicies)(policies.map((policy) => policy.$type ?? '').filter(Boolean)),
50
+ policies: [...new Set(policies.map((policy) => policy.$type ?? '').filter(Boolean))],
47
51
  relationCount: relations.filter((relation) => relation.source_table === table.table_name).length,
48
52
  };
49
53
  });
50
54
  }
51
55
  function formatTemplatesText(templates) {
52
56
  if (templates.length === 0)
53
- return 'No blueprint templates available.';
54
- const lines = [`Available blueprint templates (${templates.length}):`];
55
- for (const template of templates) {
56
- const cats = template.categories.length ? ` [${template.categories.join(', ')}]` : '';
57
- lines.push(` ${template.displayName} — ${template.tables.length} tables${cats}`);
58
- for (const table of template.tables) {
59
- lines.push(` - ${table.name} (${table.fields.length} field${table.fields.length === 1 ? '' : 's'})`);
60
- }
61
- }
62
- return lines.join('\n');
57
+ return 'No templates yet.';
58
+ return (0, harness_1.alignColumns)([
59
+ ['NAME', 'VERSION', 'TABLES', 'TAGS', 'ID'],
60
+ ...templates.map((template) => [
61
+ template.displayName || '(no name)',
62
+ template.version ?? '',
63
+ String(template.tables.length),
64
+ template.categories.join(', '),
65
+ template.id,
66
+ ]),
67
+ ]).join('\n');
63
68
  }
64
69
  // The latest project blueprint (or a named one) — the definition source for
65
70
  // create_template, and for the confirm preview of the tables it will template.
@@ -104,54 +109,80 @@ async function createTemplatePreviewTables(context, blueprintName) {
104
109
  return { blueprintName: '', tables: [] };
105
110
  }
106
111
  }
107
- async function resolveTemplateId(client, displayName) {
112
+ async function findTemplate(client, displayName) {
108
113
  const result = await client.blueprintTemplate
109
114
  .findMany({
110
- select: { id: true, displayName: true },
115
+ select: { id: true, displayName: true, definition: true },
111
116
  where: { displayName: { equalTo: displayName } },
112
117
  first: 1,
113
118
  })
114
119
  .unwrap();
115
120
  const template = result.blueprintTemplates?.nodes?.[0];
116
- if (!template?.id)
117
- throw new Error(`Template "${displayName}" not found`);
118
- return template.id;
121
+ if (!template?.id) {
122
+ throw new failure_1.ToolFailureError({
123
+ code: 'not-found',
124
+ message: `Template "${displayName}" not found.`,
125
+ hint: 'Check the template names that exist, then retry.',
126
+ calls: [(0, failure_1.suggest)('list_templates', {}, 'See the templates that exist')],
127
+ });
128
+ }
129
+ return { id: template.id, definition: template.definition };
130
+ }
131
+ /** What update_template and delete_template check before they change anything: the project, and the template. */
132
+ async function templateReady(params, cwd) {
133
+ const ready = await (0, ready_1.projectReady)(cwd);
134
+ if (ready.kind === 'failed')
135
+ return ready;
136
+ try {
137
+ return { kind: 'ok', value: { context: ready.value, templateId: (await findTemplate(ready.value.modules, params.templateName)).id } };
138
+ }
139
+ catch (err) {
140
+ return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, `Failed to read the template "${params.templateName}"`) };
141
+ }
142
+ }
143
+ function done(message) {
144
+ return { content: [{ type: 'text', text: message }], details: { success: true, message } };
119
145
  }
120
- function done(success, message) {
121
- return { content: [{ type: 'text', text: message }], details: { success, message } };
146
+ function fail(failure) {
147
+ return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure) });
122
148
  }
123
149
  // ── list_templates ────────────────────────────────────────────────────────
124
- const ListTemplatesZod = zod_1.z.object({});
150
+ const ListTemplatesZod = (0, harness_1.strictObject)('the input', {});
125
151
  exports.listTemplatesTool = {
126
152
  name: 'list_templates',
127
153
  label: 'List templates',
128
- 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.',
154
+ 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.',
129
155
  promptSnippet: 'list_templates: list the available blueprint templates to apply. Read-only — call before apply_template.',
130
156
  parameters: ListTemplatesZod,
157
+ effect: 'read',
131
158
  async execute(_params, ctx) {
132
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
133
- if (!resolved.context) {
134
- return { content: [{ type: 'text', text: resolved.reason }], details: { templates: [] } };
159
+ const ready = await (0, ready_1.projectReady)(ctx.cwd);
160
+ if (ready.kind === 'failed')
161
+ return (0, failure_1.failedResult)(ready.failure, { templates: [] });
162
+ let result;
163
+ try {
164
+ result = await ready.value.modules.blueprintTemplate
165
+ .findMany({
166
+ select: {
167
+ id: true,
168
+ version: true,
169
+ displayName: true,
170
+ description: true,
171
+ categories: true,
172
+ definition: true,
173
+ },
174
+ orderBy: ['NAME_ASC'],
175
+ })
176
+ .execute();
135
177
  }
136
- const result = await resolved.context.modules.blueprintTemplate
137
- .findMany({
138
- select: {
139
- displayName: true,
140
- description: true,
141
- categories: true,
142
- definition: true,
143
- },
144
- orderBy: ['NAME_ASC'],
145
- })
146
- .execute();
147
- if (!result.ok) {
148
- const message = result.errors.map((e) => e.message).join('; ');
149
- return {
150
- content: [{ type: 'text', text: `Failed to read templates: ${message}` }],
151
- details: { templates: [] },
152
- };
178
+ catch (err) {
179
+ return (0, failure_1.failedResult)((0, failure_1.failureFromError)(err, 'Failed to read templates'), { templates: [] });
153
180
  }
181
+ if (!result.ok)
182
+ return (0, failure_1.failedResult)((0, failure_1.failureFromErrors)(result.errors, 'Failed to read templates'), { templates: [] });
154
183
  const templates = (result.data.blueprintTemplates?.nodes ?? []).map((template) => ({
184
+ id: template.id,
185
+ version: template.version ?? null,
155
186
  displayName: template.displayName ?? '',
156
187
  description: template.description ?? null,
157
188
  categories: Array.isArray(template.categories) ? template.categories : [],
@@ -164,39 +195,41 @@ exports.listTemplatesTool = {
164
195
  },
165
196
  };
166
197
  // ── create_template ───────────────────────────────────────────────────────
167
- const CreateTemplateZod = zod_1.z.object({
168
- displayName: zod_1.z.string().describe('Display name for the new blueprint template'),
169
- blueprintName: zod_1.z
170
- .string()
198
+ const CreateTemplateZod = (0, harness_1.strictObject)('the input', {
199
+ displayName: (0, harness_1.textParam)().describe('Display name for the new blueprint template'),
200
+ blueprintName: (0, harness_1.textParam)()
171
201
  .describe('Display name of an existing project blueprint to save as the template. Defaults to the most recently provisioned blueprint.')
172
202
  .optional(),
173
203
  description: zod_1.z.string().describe('Description shown in the template catalog').optional(),
174
204
  categories: zod_1.z
175
- .array(zod_1.z.string())
205
+ .array((0, harness_1.textParam)())
176
206
  .describe('Categories for catalog grouping and discovery')
177
207
  .optional(),
178
208
  });
179
209
  exports.createTemplateTool = {
180
210
  name: 'create_template',
181
211
  label: 'Create template',
182
- 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.',
212
+ 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.',
183
213
  promptSnippet: 'create_template: save a project blueprint to the reusable template catalog. Gated.',
184
214
  parameters: CreateTemplateZod,
215
+ effect: 'write',
185
216
  async execute(params, ctx) {
186
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
187
- if (!resolved.context)
188
- return done(false, resolved.reason);
189
- const { modules, ownerId } = resolved.context;
190
- if (!ownerId)
191
- return done(false, 'Not authenticated (missing OWNER_ID in .env).');
217
+ const ready = await (0, ready_1.ownedProjectReady)(ctx.cwd);
218
+ if (ready.kind === 'failed')
219
+ return fail(ready.failure);
220
+ const { modules, ownerId } = ready.value;
192
221
  try {
193
- const blueprint = await findProjectBlueprint(resolved.context, params.blueprintName);
222
+ const blueprint = await findProjectBlueprint(ready.value, params.blueprintName);
194
223
  if (!blueprint) {
195
224
  const which = params.blueprintName ? `"${params.blueprintName}"` : 'any blueprint';
196
- return done(false, `No project blueprint found (${which}). Provision a blueprint first.`);
225
+ return fail({
226
+ code: 'not-found',
227
+ message: `No project blueprint found (${which}).`,
228
+ hint: 'Create tables from a blueprint first, then retry.',
229
+ });
197
230
  }
198
231
  const base = params.displayName.toLowerCase().replace(/\s+/g, '_');
199
- await modules.blueprintTemplate
232
+ const created = await modules.blueprintTemplate
200
233
  .create({
201
234
  data: {
202
235
  ownerId,
@@ -209,6 +242,9 @@ exports.createTemplateTool = {
209
242
  select: { id: true, displayName: true },
210
243
  })
211
244
  .unwrap();
245
+ if (!created.createBlueprintTemplate?.blueprintTemplate) {
246
+ return fail((0, failure_1.noRowCreated)(`Failed to create template "${params.displayName}"`, (0, failure_1.suggest)('list_templates', {}, 'See the templates that exist')));
247
+ }
212
248
  const message = `Created template "${params.displayName}"`;
213
249
  return {
214
250
  content: [{ type: 'text', text: message }],
@@ -222,33 +258,56 @@ exports.createTemplateTool = {
222
258
  };
223
259
  }
224
260
  catch (err) {
225
- return done(false, err instanceof Error ? err.message : 'Failed to create template');
261
+ return fail((0, failure_1.failureFromError)(err, `Failed to create template "${params.displayName}"`));
226
262
  }
227
263
  },
228
264
  };
229
265
  // ── apply_template ────────────────────────────────────────────────────────
230
- const ApplyTemplateZod = zod_1.z.object({
231
- templateName: zod_1.z.string().describe('The display name of the blueprint template to apply'),
232
- nameOverride: zod_1.z
233
- .string()
266
+ const ApplyTemplateZod = (0, harness_1.strictObject)('the input', {
267
+ templateName: (0, harness_1.textParam)().describe('The display name of the blueprint template to apply'),
268
+ nameOverride: (0, harness_1.textParam)()
234
269
  .describe('Optional name override for the created blueprint (snake_case). Defaults to template name.')
235
270
  .optional(),
236
271
  });
272
+ /**
273
+ * What apply_template checks before it changes anything: an owned project,
274
+ * the template, and none of its tables in the project yet.
275
+ */
276
+ async function applyTemplateReady(params, cwd) {
277
+ const ready = await (0, ready_1.ownedProjectReady)(cwd);
278
+ if (ready.kind === 'failed')
279
+ return ready;
280
+ let template;
281
+ try {
282
+ template = await findTemplate(ready.value.modules, params.templateName);
283
+ }
284
+ catch (err) {
285
+ return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, `Failed to read the template "${params.templateName}"`) };
286
+ }
287
+ const raw = template.definition;
288
+ const definition = { ...raw, tables: Array.isArray(raw?.tables) ? raw.tables : [] };
289
+ const tables = definition.tables.flatMap((table) => typeof table.table_name === 'string' ? [{ name: table.table_name, schema: table.schema_name }] : []);
290
+ const named = tables.flatMap(({ schema }) => schema === undefined ? [] : [schema]);
291
+ const schemas = named.length ? await (0, schema_resolve_1.readSchemas)(ready.value) : { kind: 'ok', value: new Map() };
292
+ if (schemas.kind === 'failed')
293
+ return schemas;
294
+ const conflict = (0, schema_resolve_1.schemasMissing)(named, schemas.value) ?? await (0, schema_resolve_1.tablesTaken)(ready.value, tables, schemas.value);
295
+ return conflict ? { kind: 'failed', failure: conflict } : { kind: 'ok', value: { context: ready.value, templateId: template.id, definition } };
296
+ }
237
297
  exports.applyTemplateTool = {
238
298
  name: 'apply_template',
239
299
  label: 'Apply template',
240
- description: 'Apply an existing blueprint template to the project database, creating its tables. Use the template display name (from list_templates).',
300
+ description: 'Apply an existing blueprint template to the project database, creating its tables. Use the template display name, as the template list gives it.',
241
301
  promptSnippet: 'apply_template: provision a saved blueprint template by display name. Gated.',
242
302
  parameters: ApplyTemplateZod,
303
+ effect: 'write',
243
304
  async execute(params, ctx) {
244
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
245
- if (!resolved.context)
246
- return done(false, resolved.reason);
247
- const { modules, databaseId, schemaId, ownerId } = resolved.context;
248
- if (!ownerId)
249
- return done(false, 'Not authenticated (missing OWNER_ID in .env).');
305
+ const ready = await applyTemplateReady(params, ctx.cwd);
306
+ if (ready.kind === 'failed')
307
+ return fail(ready.failure);
308
+ const { context, templateId } = ready.value;
309
+ const { modules, databaseId, schemaId, ownerId } = context;
250
310
  try {
251
- const templateId = await resolveTemplateId(modules, params.templateName);
252
311
  const base = params.nameOverride ?? params.templateName.toLowerCase().replace(/\s+/g, '_');
253
312
  const nameOverride = `${base}_${Date.now()}`;
254
313
  const copyResult = await modules.mutation
@@ -256,24 +315,30 @@ exports.applyTemplateTool = {
256
315
  .unwrap();
257
316
  const blueprintId = copyResult.copyTemplateToBlueprint?.result;
258
317
  if (!blueprintId)
259
- throw new Error('Failed to copy template');
318
+ return fail((0, failure_1.noRowCreated)(`Failed to apply template "${params.templateName}"`, failure_1.DESCRIBE_SCHEMA));
260
319
  const { tables } = await (0, blueprint_construction_1.buildBlueprint)(modules, { blueprintId, schemaId }, { signal: ctx.signal });
261
320
  const createdCount = Object.keys(tables).length;
262
- return done(true, `Applied template "${params.templateName}" — created ${createdCount} table${createdCount === 1 ? '' : 's'}`);
321
+ // The construction maps the template's table names to ids; the backend may store a name in another form.
322
+ const stored = await (0, schema_resolve_1.storedTableNames)(context, Object.values(tables)).catch(() => new Map());
323
+ const names = Object.entries(tables).map(([given, id]) => {
324
+ const as = stored.get(id) ?? given;
325
+ return as === given ? as : `${as} (stored from "${given}")`;
326
+ });
327
+ return done(`Applied template "${params.templateName}" — created ${createdCount} table${createdCount === 1 ? '' : 's'}${names.length ? `: ${names.join(', ')}` : ''}`);
263
328
  }
264
329
  catch (err) {
265
- return done(false, err instanceof Error ? err.message : 'Failed to apply template');
330
+ return fail((0, failure_1.failureFromError)(err, `Failed to apply template "${params.templateName}"`));
266
331
  }
267
332
  },
268
333
  };
269
334
  // ── update_template ───────────────────────────────────────────────────────
270
- const UpdateTemplateZod = zod_1.z.object({
271
- templateName: zod_1.z.string().describe('The display name of the blueprint template to update'),
272
- patch: zod_1.z.object({
273
- displayName: zod_1.z.string().describe('New display name').optional(),
335
+ const UpdateTemplateZod = (0, harness_1.strictObject)('the input', {
336
+ templateName: (0, harness_1.textParam)().describe('The display name of the blueprint template to update'),
337
+ patch: (0, harness_1.strictObject)('a patch', {
338
+ displayName: (0, harness_1.textParam)().describe('New display name').optional(),
274
339
  description: zod_1.z.string().describe('New description').optional(),
275
- categories: zod_1.z.array(zod_1.z.string()).describe('New categories').optional(),
276
- tags: zod_1.z.array(zod_1.z.string()).describe('New tags').optional(),
340
+ categories: zod_1.z.array((0, harness_1.textParam)()).describe('New categories').optional(),
341
+ tags: zod_1.z.array((0, harness_1.textParam)()).describe('New tags').optional(),
277
342
  visibility: zod_1.z.enum(['private', 'public']).describe('New visibility').optional(),
278
343
  }),
279
344
  });
@@ -283,29 +348,33 @@ exports.updateTemplateTool = {
283
348
  description: 'Update a blueprint template’s metadata (display name, description, categories, tags, visibility).',
284
349
  promptSnippet: 'update_template: edit a saved template’s metadata by display name. Gated.',
285
350
  parameters: UpdateTemplateZod,
351
+ effect: 'write',
286
352
  async execute(params, ctx) {
287
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
288
- if (!resolved.context)
289
- return done(false, resolved.reason);
353
+ const ready = await templateReady(params, ctx.cwd);
354
+ if (ready.kind === 'failed')
355
+ return fail(ready.failure);
356
+ const { context, templateId } = ready.value;
290
357
  try {
291
- const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
292
- await resolved.context.modules.blueprintTemplate
358
+ const result = await context.modules.blueprintTemplate
293
359
  .update({
294
360
  where: { id: templateId },
295
361
  data: params.patch,
296
362
  select: { id: true, displayName: true },
297
363
  })
298
364
  .unwrap();
299
- return done(true, `Updated template "${params.templateName}"`);
365
+ if (!result.updateBlueprintTemplate?.blueprintTemplate) {
366
+ return fail((0, failure_1.noRowsChanged)(`Failed to update template "${params.templateName}"`, (0, failure_1.suggest)('list_templates', {}, 'See the templates that exist')));
367
+ }
368
+ return done(`Updated template "${params.templateName}"`);
300
369
  }
301
370
  catch (err) {
302
- return done(false, err instanceof Error ? err.message : 'Failed to update template');
371
+ return fail((0, failure_1.failureFromError)(err, `Failed to update template "${params.templateName}"`));
303
372
  }
304
373
  },
305
374
  };
306
375
  // ── delete_template ───────────────────────────────────────────────────────
307
- const DeleteTemplateZod = zod_1.z.object({
308
- templateName: zod_1.z.string().describe('The display name of the blueprint template to delete'),
376
+ const DeleteTemplateZod = (0, harness_1.strictObject)('the input', {
377
+ templateName: (0, harness_1.textParam)().describe('The display name of the blueprint template to delete'),
309
378
  });
310
379
  exports.deleteTemplateTool = {
311
380
  name: 'delete_template',
@@ -313,19 +382,23 @@ exports.deleteTemplateTool = {
313
382
  description: 'Permanently delete a blueprint template by its display name.',
314
383
  promptSnippet: 'delete_template: remove a saved template by display name. Destructive — gated.',
315
384
  parameters: DeleteTemplateZod,
385
+ effect: 'destructive',
316
386
  async execute(params, ctx) {
317
- const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
318
- if (!resolved.context)
319
- return done(false, resolved.reason);
387
+ const ready = await templateReady(params, ctx.cwd);
388
+ if (ready.kind === 'failed')
389
+ return fail(ready.failure);
390
+ const { context, templateId } = ready.value;
320
391
  try {
321
- const templateId = await resolveTemplateId(resolved.context.modules, params.templateName);
322
- await resolved.context.modules.blueprintTemplate
392
+ const result = await context.modules.blueprintTemplate
323
393
  .delete({ where: { id: templateId }, select: { id: true } })
324
394
  .unwrap();
325
- return done(true, `Deleted template "${params.templateName}"`);
395
+ if (!result.deleteBlueprintTemplate?.blueprintTemplate) {
396
+ return fail((0, failure_1.noRowsChanged)(`Failed to delete template "${params.templateName}"`, (0, failure_1.suggest)('list_templates', {}, 'See the templates that exist')));
397
+ }
398
+ return done(`Deleted template "${params.templateName}"`);
326
399
  }
327
400
  catch (err) {
328
- return done(false, err instanceof Error ? err.message : 'Failed to delete template');
401
+ return fail((0, failure_1.failureFromError)(err, `Failed to delete template "${params.templateName}"`));
329
402
  }
330
403
  },
331
404
  };
@@ -1,26 +0,0 @@
1
- import { type PolicyProvisioningCategory } from '@agentic-kit/harness';
2
- import type { ModulesClient } from '../context';
3
- import { type CrudOperation, type CrudPolicyConfigs } from './provision-helpers';
4
- export interface AddPoliciesToTablePolicyEntry {
5
- policyType: string;
6
- dataNodeType?: string;
7
- nodeData?: Record<string, unknown>;
8
- sharedPolicyData: Record<string, unknown>;
9
- operations: CrudPolicyConfigs;
10
- enabledOperations?: CrudOperation[];
11
- }
12
- export interface AddPoliciesToTableInput {
13
- client: ModulesClient;
14
- databaseId: string;
15
- schemaId: string;
16
- tableId: string;
17
- policies: AddPoliciesToTablePolicyEntry[];
18
- }
19
- export declare class UnsupportedPolicyCategoryError extends Error {
20
- readonly policyType: string;
21
- readonly category: PolicyProvisioningCategory;
22
- constructor(policyType: string, category: PolicyProvisioningCategory);
23
- }
24
- export declare function addPoliciesToExistingTable(input: AddPoliciesToTableInput): Promise<{
25
- success: true;
26
- }>;
@@ -1,66 +0,0 @@
1
- import { getPolicyCategory } from '@agentic-kit/harness';
2
- import { buildGrants, buildPolicyEntry, CRUD_OPERATIONS, groupOperationsByConfig, } from './provision-helpers';
3
- const SUPPORTED_CATEGORIES = new Set([
4
- 'has-module',
5
- 'no-fields',
6
- 'needs-table',
7
- ]);
8
- export class UnsupportedPolicyCategoryError extends Error {
9
- policyType;
10
- category;
11
- constructor(policyType, category) {
12
- super(`Policy type "${policyType}" has category "${category}" which requires column creation or composite handling — use the policies UI instead.`);
13
- this.policyType = policyType;
14
- this.category = category;
15
- this.name = 'UnsupportedPolicyCategoryError';
16
- }
17
- }
18
- export async function addPoliciesToExistingTable(input) {
19
- const { client } = input;
20
- for (const entry of input.policies) {
21
- const category = getPolicyCategory(entry.policyType);
22
- if (!SUPPORTED_CATEGORIES.has(category)) {
23
- throw new UnsupportedPolicyCategoryError(entry.policyType, category);
24
- }
25
- }
26
- const policiesArray = [];
27
- const nodesByType = new Map();
28
- for (const entry of input.policies) {
29
- const groups = groupOperationsByConfig(entry.enabledOperations ?? CRUD_OPERATIONS, entry.operations);
30
- for (const group of groups) {
31
- const ops = group.privileges.join('_');
32
- const rand = Math.random().toString(36).slice(2, 8);
33
- policiesArray.push(buildPolicyEntry(entry.policyType, {
34
- privileges: group.privileges,
35
- policy_role: group.roleName,
36
- permissive: group.isPermissive,
37
- data: entry.sharedPolicyData,
38
- policy_name: `${ops}_${rand}`,
39
- }));
40
- }
41
- if (entry.dataNodeType && !nodesByType.has(entry.dataNodeType)) {
42
- const nodeData = entry.nodeData ?? {};
43
- nodesByType.set(entry.dataNodeType, {
44
- $type: entry.dataNodeType,
45
- ...(Object.keys(nodeData).length > 0 ? { data: nodeData } : {}),
46
- });
47
- }
48
- }
49
- const provisionInput = {
50
- databaseId: input.databaseId,
51
- schemaId: input.schemaId,
52
- tableId: input.tableId,
53
- grants: buildGrants(),
54
- policies: policiesArray,
55
- };
56
- if (nodesByType.size > 0) {
57
- provisionInput.nodes = [...nodesByType.values()];
58
- }
59
- await client.secureTableProvision
60
- .create({
61
- data: provisionInput,
62
- select: { id: true, tableId: true, tableName: true },
63
- })
64
- .unwrap();
65
- return { success: true };
66
- }
@@ -1,38 +0,0 @@
1
- export type CrudOperation = 'create' | 'read' | 'update' | 'delete';
2
- export interface OperationPolicyConfig {
3
- roleName: string;
4
- isPermissive: boolean;
5
- policyData: Record<string, unknown>;
6
- isCustomized: boolean;
7
- }
8
- export interface CrudPolicyConfigs {
9
- create: OperationPolicyConfig;
10
- read: OperationPolicyConfig;
11
- update: OperationPolicyConfig;
12
- delete: OperationPolicyConfig;
13
- }
14
- export declare const CRUD_OPERATIONS: CrudOperation[];
15
- export type GrantPrivilege = [string, string | string[]];
16
- export interface GrantEntry {
17
- roles: string[];
18
- privileges: GrantPrivilege[];
19
- }
20
- export interface PolicyEntry {
21
- $type: string;
22
- data?: Record<string, unknown>;
23
- privileges?: string[];
24
- policy_role?: string;
25
- permissive?: boolean;
26
- policy_name?: string;
27
- }
28
- export declare const ALL_CRUD_PRIVILEGES: GrantPrivilege[];
29
- export declare function crudOpToPrivilege(op: CrudOperation): string;
30
- export declare function crudOpsToPrivileges(ops: readonly CrudOperation[]): string[];
31
- export declare function buildGrants(roles?: string[], privileges?: GrantPrivilege[]): GrantEntry[];
32
- export declare function buildPolicyEntry(type: string, opts?: Partial<Omit<PolicyEntry, '$type'>>): PolicyEntry;
33
- export interface OperationGroup {
34
- roleName: string;
35
- isPermissive: boolean;
36
- privileges: string[];
37
- }
38
- export declare function groupOperationsByConfig(enabledOperations: readonly CrudOperation[], operations: CrudPolicyConfigs): OperationGroup[];
@@ -1,50 +0,0 @@
1
- export const CRUD_OPERATIONS = ['create', 'read', 'update', 'delete'];
2
- export const ALL_CRUD_PRIVILEGES = [
3
- ['select', '*'],
4
- ['insert', '*'],
5
- ['update', '*'],
6
- ['delete', '*'],
7
- ];
8
- const CRUD_OP_TO_LOWER_PRIVILEGE = {
9
- create: 'insert',
10
- read: 'select',
11
- update: 'update',
12
- delete: 'delete',
13
- };
14
- export function crudOpToPrivilege(op) {
15
- return CRUD_OP_TO_LOWER_PRIVILEGE[op];
16
- }
17
- export function crudOpsToPrivileges(ops) {
18
- return ops.map(crudOpToPrivilege);
19
- }
20
- export function buildGrants(roles = ['authenticated'], privileges = ALL_CRUD_PRIVILEGES) {
21
- return [{ roles, privileges }];
22
- }
23
- export function buildPolicyEntry(type, opts = {}) {
24
- const entry = { $type: type };
25
- if (opts.data && Object.keys(opts.data).length > 0)
26
- entry.data = opts.data;
27
- if (opts.privileges && opts.privileges.length > 0)
28
- entry.privileges = opts.privileges;
29
- if (opts.policy_role)
30
- entry.policy_role = opts.policy_role;
31
- if (opts.permissive !== undefined)
32
- entry.permissive = opts.permissive;
33
- if (opts.policy_name)
34
- entry.policy_name = opts.policy_name;
35
- return entry;
36
- }
37
- export function groupOperationsByConfig(enabledOperations, operations) {
38
- const groupMap = new Map();
39
- for (const op of enabledOperations) {
40
- const config = operations[op];
41
- const key = `${config.roleName}:${config.isPermissive}`;
42
- let group = groupMap.get(key);
43
- if (!group) {
44
- group = { roleName: config.roleName, isPermissive: config.isPermissive, privileges: [] };
45
- groupMap.set(key, group);
46
- }
47
- group.privileges.push(...crudOpsToPrivileges([op]));
48
- }
49
- return [...groupMap.values()];
50
- }
@@ -1,40 +0,0 @@
1
- import type { HarnessTool } from '@agentic-kit/harness';
2
- import { z } from 'zod';
3
- declare const ManageEntityTypesZod: z.ZodObject<{
4
- action: z.ZodEnum<{
5
- delete: "delete";
6
- create: "create";
7
- list: "list";
8
- }>;
9
- name: z.ZodOptional<z.ZodString>;
10
- entity_type_id: z.ZodOptional<z.ZodString>;
11
- description: z.ZodOptional<z.ZodString>;
12
- prefix: z.ZodOptional<z.ZodString>;
13
- parent_entity: z.ZodOptional<z.ZodString>;
14
- is_visible: z.ZodOptional<z.ZodBoolean>;
15
- has_invites: z.ZodOptional<z.ZodBoolean>;
16
- has_profiles: z.ZodOptional<z.ZodBoolean>;
17
- has_limits: z.ZodOptional<z.ZodBoolean>;
18
- has_levels: z.ZodOptional<z.ZodBoolean>;
19
- has_storage: z.ZodOptional<z.ZodBoolean>;
20
- }, z.core.$strip>;
21
- export type EntityTypeSummary = {
22
- id: string;
23
- name: string | null;
24
- description: string | null;
25
- prefix: string | null;
26
- parentEntity: string | null;
27
- isVisible: boolean | null;
28
- entityTableName: string | null;
29
- installedModules: string[] | null;
30
- };
31
- export type ManageEntityTypesDetails = {
32
- success: boolean;
33
- message: string;
34
- entityTypes?: EntityTypeSummary[];
35
- };
36
- export declare function defaultPrefix(name: string): string;
37
- type Params = z.infer<typeof ManageEntityTypesZod>;
38
- export declare function validateManageEntityTypes(params: Params): string | null;
39
- export declare const manageEntityTypesTool: HarnessTool<typeof ManageEntityTypesZod, ManageEntityTypesDetails>;
40
- export {};