@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
package/schema-resolve.js CHANGED
@@ -1,21 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveSchema = resolveSchema;
4
+ exports.notFound = notFound;
4
5
  exports.resolveTable = resolveTable;
5
6
  exports.resolveField = resolveField;
6
7
  exports.findUniqueConstraintId = findUniqueConstraintId;
8
+ exports.storedName = storedName;
9
+ exports.renamed = renamed;
10
+ exports.renameNote = renameNote;
11
+ exports.relationTablesMissing = relationTablesMissing;
12
+ exports.storedTableNames = storedTableNames;
13
+ exports.readSchemas = readSchemas;
14
+ exports.schemasMissing = schemasMissing;
15
+ exports.tablesTaken = tablesTaken;
16
+ const failure_1 = require("./failure");
7
17
  async function resolveSchema(context) {
8
- const { api, databaseId } = context;
18
+ const { api, databaseId, schemaId } = context;
9
19
  const tablesResult = await api.table
10
20
  .findMany({
11
21
  select: { id: true, name: true },
12
- where: { databaseId: { equalTo: databaseId } },
22
+ where: { databaseId: { equalTo: databaseId }, schemaId: { equalTo: schemaId } },
13
23
  })
14
24
  .execute();
15
- if (!tablesResult.ok) {
16
- const message = tablesResult.errors.map((e) => e.message).join('; ');
17
- throw new Error(`Failed to read tables: ${message}`);
18
- }
25
+ if (!tablesResult.ok)
26
+ throw new failure_1.ToolFailureError((0, failure_1.failureFromErrors)(tablesResult.errors, 'Failed to read tables'));
19
27
  const tableNodes = tablesResult.data.tables?.nodes ?? [];
20
28
  const tableIds = tableNodes.map((t) => t.id);
21
29
  const fieldsByTable = new Map();
@@ -27,10 +35,8 @@ async function resolveSchema(context) {
27
35
  where: { tableId: { in: tableIds } },
28
36
  })
29
37
  .execute();
30
- if (!fieldsResult.ok) {
31
- const message = fieldsResult.errors.map((e) => e.message).join('; ');
32
- throw new Error(`Failed to read fields: ${message}`);
33
- }
38
+ if (!fieldsResult.ok)
39
+ throw new failure_1.ToolFailureError((0, failure_1.failureFromErrors)(fieldsResult.errors, 'Failed to read fields'));
34
40
  for (const field of fieldsResult.data.fields?.nodes ?? []) {
35
41
  const list = fieldsByTable.get(field.tableId) ?? [];
36
42
  list.push({ id: field.id, name: field.name, tableId: field.tableId });
@@ -58,18 +64,207 @@ async function resolveSchema(context) {
58
64
  }));
59
65
  return { tables };
60
66
  }
67
+ /**
68
+ * A name that is not found, and the stored form of it when one of `names` has
69
+ * it: a person often asks for a table or field by the name they made it with.
70
+ */
71
+ function notFound(what, name, message, names) {
72
+ const stored = renamed(name);
73
+ if (stored !== undefined && names.includes(stored)) {
74
+ return {
75
+ code: 'not-found',
76
+ message: `${message} The backend stores that name as "${stored}", and a ${what.toLowerCase()} of that name exists.`,
77
+ hint: `Call again with the name "${stored}".`,
78
+ calls: [failure_1.DESCRIBE_SCHEMA],
79
+ };
80
+ }
81
+ return { code: 'not-found', message, hint: `Check the ${what.toLowerCase()} names that exist, then retry.`, calls: [failure_1.DESCRIBE_SCHEMA] };
82
+ }
61
83
  function resolveTable(schema, tableName) {
62
84
  const table = schema.tables.find((t) => t.name === tableName);
63
- if (!table)
64
- throw new Error(`Table "${tableName}" not found in current schema`);
85
+ if (!table) {
86
+ const names = schema.tables.map((t) => t.name);
87
+ throw new failure_1.ToolFailureError(notFound('Table', tableName, `Table "${tableName}" not found in current schema.`, names));
88
+ }
65
89
  return table;
66
90
  }
67
91
  function resolveField(table, fieldName) {
68
92
  const field = table.fields.find((f) => f.name === fieldName);
69
- if (!field)
70
- throw new Error(`Field "${fieldName}" not found in table "${table.name}"`);
93
+ if (!field) {
94
+ const names = table.fields.map((f) => f.name);
95
+ throw new failure_1.ToolFailureError(notFound('Field', fieldName, `Field "${fieldName}" not found in table "${table.name}".`, names));
96
+ }
71
97
  return field;
72
98
  }
73
99
  function findUniqueConstraintId(table, fieldId) {
74
100
  return table.uniqueConstraints.find((c) => c.fieldIds.includes(fieldId))?.id;
75
101
  }
102
+ // PostgreSQL's `FOR m IN SELECT regexp_matches(str, re, 'g') LOOP str = replace(str, from, to)`: the matches
103
+ // are found once in the input, and each replace changes every place the matched text is.
104
+ function replaceMatches(str, re, change) {
105
+ let out = str;
106
+ for (const match of str.matchAll(re)) {
107
+ const [from, to] = change(match);
108
+ out = out.split(from).join(to);
109
+ }
110
+ return out;
111
+ }
112
+ const lowerTail = (match) => [match[1] + match[2], match[1] + match[2].toLowerCase()];
113
+ // inflection.pg_slugify(value, false), less unaccent: storedName answers only for ASCII.
114
+ function slugify(value) {
115
+ const caps = replaceMatches(replaceMatches(value, /([A-Z])([A-Z]+$)/g, lowerTail), /([A-Z])([A-Z]+)[A-Z][a-z]/g, lowerTail);
116
+ return caps
117
+ .replace(/[^\w\s-]/gi, '')
118
+ .replace(/^ +| +$/g, '')
119
+ .replace(/[-\s]+/g, '-')
120
+ .replace(/-+/g, '_')
121
+ .replace(/_+/g, '_');
122
+ }
123
+ /**
124
+ * The name the backend stores for a new table or field named `name`, as it
125
+ * rewrites every new name: a capital starts a word, separators become one
126
+ * underscore, and a word of one letter joins its neighbour (`r2_rows_a` is
127
+ * stored as `r2_rowsa`). Undefined for a
128
+ * name with a character outside ASCII, which the backend strips of accents
129
+ * first (unaccent), so this cannot say.
130
+ */
131
+ function storedName(name) {
132
+ // eslint-disable-next-line no-control-regex
133
+ if (/[^\x00-\x7f]/.test(name))
134
+ return undefined;
135
+ const words = slugify(name)
136
+ .replace(/([A-Z])/g, '_$1')
137
+ .toLowerCase()
138
+ .replace(/^_/, '')
139
+ .replace(/_+/g, '_')
140
+ .replace(/([a-z])_$/i, '$1')
141
+ .replace(/^_([a-z])/i, '$1');
142
+ // inflection.no_single_underscores: at the start, at the end, then in the middle.
143
+ const start = replaceMatches(words, /(^[a-z])(_)/g, (match) => [match[1] + match[2], match[1]]);
144
+ const end = replaceMatches(start, /(_)([a-z]$)/g, (match) => [match[1] + match[2], match[2]]);
145
+ const middle = replaceMatches(end, /(_)([a-z]_)/g, (match) => [match[1] + match[2], match[2]]);
146
+ return [...middle].slice(0, 63).join('');
147
+ }
148
+ /** The name the backend stores for `name`, when it differs from it. */
149
+ function renamed(name) {
150
+ const stored = storedName(name);
151
+ return stored !== undefined && stored !== name ? stored : undefined;
152
+ }
153
+ /** What a plan says about a new table or field name the backend stores differently, or cannot say. */
154
+ function renameNote(what, name) {
155
+ if (storedName(name) === undefined) {
156
+ return `The backend removes the accents of the ${what} name "${name}" before it stores it, so the stored name may differ; the result names it as stored.`;
157
+ }
158
+ const stored = renamed(name);
159
+ return stored === undefined ? undefined : `The backend stores the ${what} name "${name}" as "${stored}".`;
160
+ }
161
+ /**
162
+ * A not-found failure for each table a blueprint's relations name that
163
+ * neither the blueprint makes nor the project database has, or null. An end
164
+ * given as a module's table names no table here.
165
+ */
166
+ async function relationTablesMissing(context, made, relations, schemas) {
167
+ const named = relations.flatMap((relation) => [
168
+ { name: relation.source_table, schema: relation.source_schema },
169
+ { name: relation.target_table, schema: relation.target_schema },
170
+ ]).filter((table) => typeof table.name === 'string');
171
+ if (named.length === 0)
172
+ return null;
173
+ const key = (name, schemaId) => JSON.stringify([schemaId, name]);
174
+ const normalize = (name) => storedName(name) ?? name;
175
+ const created = new Set(made.map(normalize));
176
+ const known = new Set();
177
+ const names = new Set();
178
+ try {
179
+ const result = await context.api.table.findMany({ select: { name: true, schemaId: true }, where: { databaseId: { equalTo: context.databaseId } } }).execute();
180
+ if (!result.ok)
181
+ return (0, failure_1.failureFromErrors)(result.errors, 'Failed to read the tables of the project database');
182
+ for (const table of result.data.tables?.nodes ?? []) {
183
+ names.add(table.name);
184
+ known.add(key(table.name, table.schemaId));
185
+ }
186
+ }
187
+ catch (err) {
188
+ return (0, failure_1.failureFromError)(err, 'Failed to read the tables of the project database');
189
+ }
190
+ const missing = [...new Set(named.filter(({ name, schema }) => {
191
+ const stored = normalize(name);
192
+ return !created.has(stored) && !(schema === undefined ? names.has(stored) : known.has(key(stored, schemas.get(schema))));
193
+ })
194
+ .map(({ name, schema }) => schema === undefined ? name : `${schema}.${name}`))];
195
+ if (missing.length === 0)
196
+ return null;
197
+ return {
198
+ code: 'not-found',
199
+ message: missing.map((name) => `A relation of the blueprint names the table "${name}", which neither the blueprint makes nor the project database has.`).join(' '),
200
+ hint: 'Add the table to the blueprint, or name a table that exists.',
201
+ calls: [failure_1.DESCRIBE_SCHEMA],
202
+ };
203
+ }
204
+ /** The stored names of the tables of `ids`, read back from the control plane. */
205
+ async function storedTableNames(context, ids) {
206
+ if (ids.length === 0)
207
+ return new Map();
208
+ const result = await context.api.table.findMany({ select: { id: true, name: true }, where: { id: { in: ids } } }).execute();
209
+ return new Map(result.ok ? (result.data.tables?.nodes ?? []).map((table) => [table.id, table.name]) : []);
210
+ }
211
+ /** The schemas of the project database by name: the default one of the project (app_public) and any other. */
212
+ async function readSchemas(context) {
213
+ try {
214
+ const result = await context.api.schema.findMany({ select: { id: true, name: true }, where: { databaseId: { equalTo: context.databaseId } } }).execute();
215
+ if (!result.ok)
216
+ return { kind: 'failed', failure: (0, failure_1.failureFromErrors)(result.errors, 'Failed to read the schemas of the project database') };
217
+ return { kind: 'ok', value: new Map((result.data.schemas?.nodes ?? []).map((schema) => [schema.name, schema.id])) };
218
+ }
219
+ catch (err) {
220
+ return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to read the schemas of the project database') };
221
+ }
222
+ }
223
+ /** A not-found failure for each schema a blueprint names that the project database does not have, or null. */
224
+ function schemasMissing(named, schemas) {
225
+ const missing = [...new Set(named)].filter((name) => !schemas.has(name));
226
+ if (missing.length === 0)
227
+ return null;
228
+ return {
229
+ code: 'not-found',
230
+ message: `The blueprint names the schema${missing.length === 1 ? '' : 's'} ${missing.map((name) => `"${name}"`).join(', ')}, which the project database does not have; it has ${[...schemas.keys()].map((name) => `"${name}"`).join(', ')}.`,
231
+ hint: 'Name a schema the project database has, or leave the schema out for the default one.',
232
+ };
233
+ }
234
+ /**
235
+ * A `name-taken` failure for the tables of `tables` that their schema already has (the project's own, app_public,
236
+ * when a table names none; `schemas` maps the others' names to ids), or null when none does.
237
+ */
238
+ async function tablesTaken(context, tables, schemas = new Map()) {
239
+ const bySchema = new Map();
240
+ for (const { name, schema } of tables) {
241
+ const schemaId = schema === undefined ? context.schemaId : schemas.get(schema);
242
+ if (schemaId !== undefined)
243
+ bySchema.set(schemaId, [...(bySchema.get(schemaId) ?? []), name]);
244
+ }
245
+ const taken = [];
246
+ for (const [schemaId, names] of bySchema) {
247
+ try {
248
+ const result = await context.api.table
249
+ .findMany({ select: { name: true }, where: { databaseId: { equalTo: context.databaseId }, schemaId: { equalTo: schemaId } } })
250
+ .execute();
251
+ if (!result.ok)
252
+ return (0, failure_1.failureFromErrors)(result.errors, 'Failed to read the tables of the project database');
253
+ const existing = new Set((result.data.tables?.nodes ?? []).map((table) => table.name));
254
+ taken.push(...names.filter((name) => existing.has(storedName(name) ?? name)));
255
+ }
256
+ catch (err) {
257
+ return (0, failure_1.failureFromError)(err, 'Failed to read the tables of the project database');
258
+ }
259
+ }
260
+ const names = [...new Set(taken)];
261
+ if (names.length === 0)
262
+ return null;
263
+ const listed = names.map((name) => (renamed(name) ? `"${renamed(name)}", which is how the backend stores "${name}"` : `"${name}"`)).join(', ');
264
+ return {
265
+ code: 'name-taken',
266
+ message: `The project database already has ${names.length === 1 ? 'a table' : 'tables'} named ${listed}.`,
267
+ hint: 'Choose another table name, or change the table that exists instead of creating it.',
268
+ calls: [failure_1.DESCRIBE_SCHEMA],
269
+ };
270
+ }
@@ -0,0 +1,116 @@
1
+ import { type PlanAccessState, type PlanColumn, type PlanRule, type PlanTableAccess, type ToolCallSuggestion } from '@agentic-kit/harness';
2
+ import type { BlueprintPolicy } from 'node-type-registry';
3
+ import { type TableAccessInput, type TableField, type TablePolicy } from './access';
4
+ import type { ProjectContext } from './context';
5
+ import { type FailureMeaning, type Result } from './failure';
6
+ export type SchemaField = {
7
+ name: string;
8
+ type: string;
9
+ isRequired: boolean;
10
+ defaultValue: string | null;
11
+ };
12
+ /** One access rule of a table: the policy rows that differ only by privilege, as one. */
13
+ export type SchemaPolicy = {
14
+ type: string;
15
+ privileges: string[];
16
+ /** False for a restrictive rule, which every row must also pass. */
17
+ permissive: boolean;
18
+ role: string;
19
+ data: Record<string, unknown>;
20
+ disabled?: true;
21
+ /** UPDATE only: the rule a changed row must pass instead of this one, as the backend stores it. */
22
+ withCheck?: {
23
+ type: string;
24
+ data: Record<string, unknown>;
25
+ };
26
+ };
27
+ export type TableGrants = NonNullable<TableAccessInput['grants']>;
28
+ export type TableRecord = {
29
+ id: string;
30
+ name: string;
31
+ fields: SchemaField[];
32
+ policyRules: SchemaPolicy[];
33
+ /** The names of its policy rows: PostgreSQL keeps a policy name unique per table. */
34
+ policyNames: string[];
35
+ grants: TableGrants;
36
+ rlsEnabled: boolean;
37
+ };
38
+ /** A canonical JSON text, so two rules with the same data in another key order are one rule. */
39
+ export declare const canonical: (value: unknown) => string;
40
+ /** The application tables of the bound database (every one, or those named), with all their access parts. */
41
+ export declare function readTables(context: ProjectContext, names?: string[], schemaId?: string): Promise<Result<TableRecord[]>>;
42
+ /** One table of the bound database by name, or `not-found` naming the call that lists them. */
43
+ export declare function readTable(context: ProjectContext, name: string): Promise<Result<TableRecord>>;
44
+ /** A stored field default as the SQL it stands for (`now()`, `0`), or as stored when this tool cannot read it. */
45
+ export declare function defaultText(value: string | null): string;
46
+ /** A column as the registry reads it: its default decides, for example, whose team a new row names. */
47
+ export declare const tableField: (field: SchemaField) => TableField;
48
+ /**
49
+ * What the registry reads for one live table: every policy (a role of
50
+ * `public` counts for every role) with its WITH CHECK override, the grants,
51
+ * the row-security state and the columns. A disabled policy does not apply,
52
+ * so it is left out.
53
+ */
54
+ export declare function accessInputOf(table: TableRecord): TableAccessInput;
55
+ /** One rule in plain words, with the related columns the reader read; a rule the words cannot describe says so instead. */
56
+ export declare function ruleWords(type: string, data: Record<string, unknown>, related?: TableAccessInput['related']): string;
57
+ /** A stored rule in the shape a caller writes one, so a rule that is read can be written back. */
58
+ export type WrittenRule = Omit<BlueprintPolicy, 'policy_name'> & Required<Pick<BlueprintPolicy, 'privileges' | 'permissive' | 'policy_role' | 'data'>>;
59
+ /**
60
+ * A stored rule as every read returns it: the keys a caller writes (`$type`, `privileges`, `permissive`,
61
+ * `policy_role`, `data`, and `with_check` for an update rule with its own check), with each key the closed
62
+ * parameter_schema marks readOnly left out, so no read carries a part the closed world refuses.
63
+ */
64
+ export declare function asWritten(policy: TablePolicy): WrittenRule;
65
+ /** One rule as a plan names it, under the keys a caller writes: its own sentence, and for an update rule with its own check of the changed row, that one too. */
66
+ export declare function planRule(policy: TablePolicy, related?: TableAccessInput['related']): PlanRule;
67
+ /** A table's grants in words, one entry per role: "select, insert, update and delete to authenticated", "update (title) to editor". */
68
+ export declare function grantWords(grants: TableAccessInput['grants']): string[];
69
+ /** A table's access at one moment, as a plan names it. */
70
+ export declare const accessState: (input: TableAccessInput) => PlanAccessState;
71
+ /**
72
+ * The access of one table a plan creates (`before` absent) or changes: the rules, grants and row security now and
73
+ * after, one sentence per rule, and the findings the change brings and removes.
74
+ */
75
+ export declare function planTableAccess(table: string, before: TableAccessInput | undefined, after: TableAccessInput): PlanTableAccess;
76
+ /** One rule as the registry reads it: its policy type, its data, and the WITH CHECK override of an update. */
77
+ export type Rule = Pick<TablePolicy, 'type' | 'data' | 'with_check'>;
78
+ /** What a change does to the columns of one table. */
79
+ export type ColumnChange = {
80
+ /** The columns its nodes add that the table does not have. */
81
+ added: PlanColumn[];
82
+ /** The columns its nodes would add that the table has: a generator keeps each as it is, its own default too. */
83
+ reused: PlanColumn[];
84
+ /** The added columns the rows there now would get no value for: the change fails if the table has rows. */
85
+ failsIfRows: PlanColumn[];
86
+ /** The added columns as the registry reads them, for the access after the change. */
87
+ fields: TableField[];
88
+ /** What the plan says about columns the registry does not know. */
89
+ notes: string[];
90
+ };
91
+ /**
92
+ * The columns `nodes` add to a table that has `fields`, and the ones they
93
+ * reuse (a generator keeps a column of the same name as it is), refused when
94
+ * a rule reads a column the table has not and no node of the change adds: the
95
+ * backend cannot build that rule. Where a node's columns, or the columns a
96
+ * rule reads, are not known, the plan says what it cannot check instead.
97
+ */
98
+ export declare function columnChange(table: string, fields: ReadonlyArray<SchemaField | {
99
+ name: string;
100
+ }>, nodes: Array<string | {
101
+ $type: string;
102
+ data?: object;
103
+ }>, rules: readonly Rule[]): Result<ColumnChange>;
104
+ /** The plan's parts for a column change: the columns it adds and reuses, and the ones that fail on rows of an existing table. */
105
+ export declare const columnPlan: (change: ColumnChange, existing: boolean) => Pick<PlanTableAccess, "columnsAdded" | "columnsReused" | "failsIfRows">;
106
+ /** Why a change that adds `columns` cannot apply to `table` while it has rows, and the fix. */
107
+ export declare function rowsConflict(table: string, columns: PlanColumn[]): {
108
+ message: string;
109
+ hint: string;
110
+ calls: ToolCallSuggestion[];
111
+ };
112
+ /**
113
+ * What a refusal of a change to `table` means: a refused NOT NULL is the rows the added columns get no value for,
114
+ * and a refused rule is one of the caller's own `rules` (a preset's are the registry's, so they are left out).
115
+ */
116
+ export declare const changeMeaning: (table: string, change: ColumnChange, rules: readonly Rule[] | undefined) => FailureMeaning;