@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
@@ -0,0 +1,437 @@
1
+ "use strict";
2
+ // The access of the tables of a bound database, read once from the control
3
+ // plane: their columns, policies, grants and row-security state, which is the
4
+ // whole input the words and the findings of a table need. A part that cannot
5
+ // be read fails the read, so no report leaves a part out.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.changeMeaning = exports.columnPlan = exports.accessState = exports.tableField = exports.canonical = void 0;
8
+ exports.readTables = readTables;
9
+ exports.readTable = readTable;
10
+ exports.defaultText = defaultText;
11
+ exports.accessInputOf = accessInputOf;
12
+ exports.ruleWords = ruleWords;
13
+ exports.asWritten = asWritten;
14
+ exports.planRule = planRule;
15
+ exports.grantWords = grantWords;
16
+ exports.planTableAccess = planTableAccess;
17
+ exports.columnChange = columnChange;
18
+ exports.rowsConflict = rowsConflict;
19
+ const harness_1 = require("@agentic-kit/harness");
20
+ const access_1 = require("./access");
21
+ const policies_1 = require("./access/policies");
22
+ const field_type_1 = require("./blueprint/field-type");
23
+ const failure_1 = require("./failure");
24
+ const schema_resolve_1 = require("./schema-resolve");
25
+ const PRIVILEGE_ORDER = ['all', 'select', 'insert', 'update', 'delete'];
26
+ const PRIVILEGES = new Set(['select', 'insert', 'update', 'delete']);
27
+ /** A canonical JSON text, so two rules with the same data in another key order are one rule. */
28
+ const canonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
29
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)))
30
+ : item);
31
+ exports.canonical = canonical;
32
+ // The stored WITH CHECK override: {"$type": "Authz...", "data": {...}}, or none.
33
+ function withCheckOf(value) {
34
+ if (!value || typeof value !== 'object' || typeof value.$type !== 'string')
35
+ return undefined;
36
+ const { $type, data } = value;
37
+ return { type: $type, data: data && typeof data === 'object' ? data : {} };
38
+ }
39
+ function policyRules(rows) {
40
+ const rules = new Map();
41
+ for (const row of rows) {
42
+ const withCheck = withCheckOf(row.withCheck);
43
+ const rule = {
44
+ type: row.policyType ?? '',
45
+ privileges: [],
46
+ permissive: row.permissive !== false,
47
+ role: row.granteeName ?? '',
48
+ data: row.data && typeof row.data === 'object' ? row.data : {},
49
+ ...(row.disabled ? { disabled: true } : {}),
50
+ ...(withCheck ? { withCheck } : {}),
51
+ };
52
+ const key = (0, exports.canonical)([rule.type, rule.permissive, rule.role, rule.disabled ?? false, rule.data, rule.withCheck ?? null]);
53
+ const kept = rules.get(key) ?? rule;
54
+ const privilege = (row.privilege ?? '').toLowerCase();
55
+ if (privilege && !kept.privileges.includes(privilege))
56
+ kept.privileges.push(privilege);
57
+ rules.set(key, kept);
58
+ }
59
+ for (const rule of rules.values()) {
60
+ rule.privileges.sort((a, b) => PRIVILEGE_ORDER.indexOf(a) - PRIVILEGE_ORDER.indexOf(b));
61
+ }
62
+ return [...rules.values()];
63
+ }
64
+ // The grants of one table in the blueprint shape the registry reads: per role, [privilege, columns or '*'].
65
+ function tableGrants(rows, fieldNames) {
66
+ const byRole = new Map();
67
+ for (const row of rows) {
68
+ if (row.isGrant === false || !row.granteeName || !row.privilege)
69
+ continue;
70
+ const columns = row.fieldIds?.length ? row.fieldIds.map((id) => fieldNames.get(id) ?? id) : '*';
71
+ byRole.set(row.granteeName, [...(byRole.get(row.granteeName) ?? []), [row.privilege.toLowerCase(), columns]]);
72
+ }
73
+ return [...byRole].map(([role, privileges]) => ({ roles: [role], privileges }));
74
+ }
75
+ function toDefaultValueString(value) {
76
+ if (value == null)
77
+ return null;
78
+ if (typeof value === 'string')
79
+ return value;
80
+ return JSON.stringify(value);
81
+ }
82
+ const groupBy = (rows) => {
83
+ const groups = new Map();
84
+ for (const row of rows)
85
+ groups.set(row.tableId, [...(groups.get(row.tableId) ?? []), row]);
86
+ return groups;
87
+ };
88
+ /** The application tables of the bound database (every one, or those named), with all their access parts. */
89
+ async function readTables(context, names, schemaId) {
90
+ const { api, databaseId } = context;
91
+ try {
92
+ const tablesResult = await api.table
93
+ .findMany({
94
+ select: { id: true, name: true, category: true, useRls: true },
95
+ where: {
96
+ databaseId: { equalTo: databaseId },
97
+ ...(schemaId ? { schemaId: { equalTo: schemaId } } : {}),
98
+ or: [{ category: { equalTo: 'APP' } }, { name: { equalTo: 'users' } }],
99
+ ...(names ? { name: { in: names } } : {}),
100
+ },
101
+ orderBy: ['NAME_ASC'],
102
+ })
103
+ .execute();
104
+ if (!tablesResult.ok)
105
+ return { kind: 'failed', failure: (0, failure_1.failureFromErrors)(tablesResult.errors, 'Failed to read schema') };
106
+ const tableNodes = tablesResult.data.tables?.nodes ?? [];
107
+ const tableIds = tableNodes.map((table) => table.id);
108
+ if (tableIds.length === 0)
109
+ return { kind: 'ok', value: [] };
110
+ const where = { tableId: { in: tableIds } };
111
+ const [fieldsResult, policiesResult, grantsResult] = await Promise.all([
112
+ api.field
113
+ .findMany({ select: { id: true, name: true, type: true, isRequired: true, defaultValue: true, tableId: true }, where })
114
+ .execute(),
115
+ api.policy
116
+ .findMany({
117
+ select: { tableId: true, name: true, policyType: true, privilege: true, permissive: true, granteeName: true, disabled: true, data: true, withCheck: true },
118
+ where,
119
+ })
120
+ .execute(),
121
+ api.tableGrant.findMany({ select: { tableId: true, privilege: true, granteeName: true, fieldIds: true, isGrant: true }, where }).execute(),
122
+ ]);
123
+ if (!fieldsResult.ok)
124
+ return { kind: 'failed', failure: (0, failure_1.failureFromErrors)(fieldsResult.errors, 'Failed to read fields') };
125
+ if (!policiesResult.ok)
126
+ return { kind: 'failed', failure: (0, failure_1.failureFromErrors)(policiesResult.errors, 'Failed to read policies') };
127
+ if (!grantsResult.ok)
128
+ return { kind: 'failed', failure: (0, failure_1.failureFromErrors)(grantsResult.errors, 'Failed to read grants') };
129
+ const fieldRows = fieldsResult.data.fields?.nodes ?? [];
130
+ const fieldNames = new Map(fieldRows.map((field) => [field.id, field.name]));
131
+ const fields = groupBy(fieldRows);
132
+ const policies = groupBy((policiesResult.data.policies?.nodes ?? []));
133
+ const grants = groupBy((grantsResult.data.tableGrants?.nodes ?? []));
134
+ return {
135
+ kind: 'ok',
136
+ value: tableNodes.map((table) => ({
137
+ id: table.id,
138
+ name: table.name,
139
+ fields: (fields.get(table.id) ?? []).map((field) => ({
140
+ name: field.name,
141
+ type: (0, field_type_1.fieldTypeToTypeName)(field.type),
142
+ isRequired: Boolean(field.isRequired),
143
+ defaultValue: toDefaultValueString(field.defaultValue),
144
+ })),
145
+ policyRules: policyRules(policies.get(table.id) ?? []),
146
+ policyNames: (policies.get(table.id) ?? []).flatMap((row) => (row.name ? [row.name] : [])),
147
+ grants: tableGrants(grants.get(table.id) ?? [], fieldNames),
148
+ rlsEnabled: table.useRls === true,
149
+ })),
150
+ };
151
+ }
152
+ catch (err) {
153
+ return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to read schema') };
154
+ }
155
+ }
156
+ /** One table of the bound database by name, or `not-found` naming the call that lists them. */
157
+ async function readTable(context, name) {
158
+ const stored = (0, schema_resolve_1.renamed)(name);
159
+ const read = await readTables(context, stored ? [name, stored] : [name], context.schemaId);
160
+ if (read.kind === 'failed')
161
+ return read;
162
+ const table = read.value.find((candidate) => candidate.name === name);
163
+ if (table)
164
+ return { kind: 'ok', value: table };
165
+ const message = `Table "${name}" was not found in the project database.`;
166
+ return { kind: 'failed', failure: (0, schema_resolve_1.notFound)('Table', name, message, read.value.map((candidate) => candidate.name)) };
167
+ }
168
+ // A stored field default: the JSON of a FieldDefault (as readTables keeps it), or SQL text this tool cannot read.
169
+ function storedDefault(value) {
170
+ if (value === null)
171
+ return null;
172
+ try {
173
+ const parsed = JSON.parse(value);
174
+ return parsed !== null && typeof parsed === 'object' ? parsed : 'unknown';
175
+ }
176
+ catch {
177
+ return 'unknown';
178
+ }
179
+ }
180
+ /** A stored field default as the SQL it stands for (`now()`, `0`), or as stored when this tool cannot read it. */
181
+ function defaultText(value) {
182
+ const parsed = storedDefault(value);
183
+ if (parsed === null)
184
+ return '';
185
+ if (parsed === 'unknown')
186
+ return value;
187
+ return 'generated' in parsed ? `generated (${parsed.generated})` : defaultSql(parsed);
188
+ }
189
+ /** A column as the registry reads it: its default decides, for example, whose team a new row names. */
190
+ const tableField = (field) => ({
191
+ name: field.name,
192
+ required: field.isRequired,
193
+ default: storedDefault(field.defaultValue),
194
+ type: field.type,
195
+ });
196
+ exports.tableField = tableField;
197
+ /** A column a Data node adds, as the registry reads it. */
198
+ const addedField = (column) => ({ name: column.name, required: !column.nullable, default: column.default, type: column.type });
199
+ /**
200
+ * What the registry reads for one live table: every policy (a role of
201
+ * `public` counts for every role) with its WITH CHECK override, the grants,
202
+ * the row-security state and the columns. A disabled policy does not apply,
203
+ * so it is left out.
204
+ */
205
+ function accessInputOf(table) {
206
+ return {
207
+ policies: table.policyRules
208
+ .filter((rule) => !rule.disabled)
209
+ .map((rule) => ({
210
+ type: rule.type,
211
+ privileges: rule.privileges.filter((privilege) => PRIVILEGES.has(privilege)),
212
+ permissive: rule.permissive,
213
+ role: rule.role || 'authenticated',
214
+ data: rule.data,
215
+ ...(rule.withCheck ? { with_check: rule.withCheck } : {}),
216
+ })),
217
+ grants: table.grants,
218
+ rls_enabled: table.rlsEnabled,
219
+ fields: table.fields.map(exports.tableField),
220
+ };
221
+ }
222
+ /** One rule in plain words, with the related columns the reader read; a rule the words cannot describe says so instead. */
223
+ function ruleWords(type, data, related) {
224
+ if (!policies_1.AUTHZ_NODES.has(type))
225
+ return `A rule of the type ${type}, which these words do not describe.`;
226
+ try {
227
+ return (0, access_1.explainPolicy)(type, data ?? {}, related);
228
+ }
229
+ catch {
230
+ return `A ${type} rule whose stored data these words cannot read.`;
231
+ }
232
+ }
233
+ const EXPRESSION = { format: 'authz-expression' };
234
+ // A part of an Authz expression: AND and OR hold a list of expressions, NOT holds one, and a node holds its own data.
235
+ function expressionPart(key) {
236
+ if (key === 'AND' || key === 'OR')
237
+ return { items: EXPRESSION };
238
+ if (key === 'NOT')
239
+ return EXPRESSION;
240
+ return policies_1.AUTHZ_NODES.get(key)?.parameter_schema;
241
+ }
242
+ // `value` under `schema` without the keys the schema marks readOnly, which the backend or the platform sets, nested
243
+ // Authz nodes included: the parse trees, the member lists the backend resolves, and the table it records.
244
+ function withoutStoredOnly(schema, value) {
245
+ if (!schema)
246
+ return value;
247
+ if (Array.isArray(value)) {
248
+ const items = schema.items && !Array.isArray(schema.items) ? schema.items : undefined;
249
+ return items ? value.map((item) => withoutStoredOnly(items, item)) : value;
250
+ }
251
+ if (!(0, policies_1.isObject)(value))
252
+ return value;
253
+ return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {
254
+ const part = schema.properties?.[key] ?? (schema.format === 'authz-expression' ? expressionPart(key) : undefined);
255
+ return part?.readOnly ? [] : [[key, withoutStoredOnly(part, item)]];
256
+ }));
257
+ }
258
+ const writtenData = (type, data) => withoutStoredOnly(policies_1.AUTHZ_NODES.get(type)?.parameter_schema, data ?? {});
259
+ /**
260
+ * A stored rule as every read returns it: the keys a caller writes (`$type`, `privileges`, `permissive`,
261
+ * `policy_role`, `data`, and `with_check` for an update rule with its own check), with each key the closed
262
+ * parameter_schema marks readOnly left out, so no read carries a part the closed world refuses.
263
+ */
264
+ function asWritten(policy) {
265
+ return {
266
+ $type: policy.type,
267
+ privileges: [...policy.privileges],
268
+ permissive: policy.permissive !== false,
269
+ policy_role: policy.role || 'authenticated',
270
+ data: writtenData(policy.type, policy.data),
271
+ ...(policy.with_check ? { with_check: { $type: policy.with_check.type, data: writtenData(policy.with_check.type, policy.with_check.data) } } : {}),
272
+ };
273
+ }
274
+ /** 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. */
275
+ function planRule(policy, related) {
276
+ const check = policy.with_check ? ` A changed row must pass instead: ${ruleWords(policy.with_check.type, policy.with_check.data ?? {}, related)}` : '';
277
+ const rule = {
278
+ $type: policy.type,
279
+ privileges: policy.privileges,
280
+ permissive: policy.permissive !== false,
281
+ policy_role: policy.role || 'authenticated',
282
+ words: `${ruleWords(policy.type, policy.data, related)}${check}`,
283
+ };
284
+ return Object.defineProperty(rule, 'comparisonKey', { value: (0, policies_1.part)(policy).key });
285
+ }
286
+ /** A table's grants in words, one entry per role: "select, insert, update and delete to authenticated", "update (title) to editor". */
287
+ function grantWords(grants) {
288
+ const byRole = new Map();
289
+ for (const grant of grants ?? []) {
290
+ for (const role of grant.roles) {
291
+ for (const entry of grant.privileges) {
292
+ const [privilege, columns] = Array.isArray(entry) ? entry : [entry, '*'];
293
+ const what = `${String(privilege).toLowerCase()}${Array.isArray(columns) && columns.length ? ` (${columns.join(', ')})` : ''}`;
294
+ const known = byRole.get(role) ?? [];
295
+ if (!known.includes(what))
296
+ byRole.set(role, [...known, what]);
297
+ }
298
+ }
299
+ }
300
+ return [...byRole].map(([role, privileges]) => {
301
+ const ordered = [...privileges].sort((a, b) => PRIVILEGE_ORDER.indexOf(a.split(' ')[0]) - PRIVILEGE_ORDER.indexOf(b.split(' ')[0]));
302
+ return `${(0, harness_1.listed)(ordered)} to ${role}`;
303
+ });
304
+ }
305
+ /** A table's access at one moment, as a plan names it. */
306
+ const accessState = (input) => ({
307
+ rules: input.policies.map((policy) => planRule(policy, input.related)),
308
+ grants: grantWords(input.grants),
309
+ rowSecurity: input.rls_enabled !== false,
310
+ });
311
+ exports.accessState = accessState;
312
+ /**
313
+ * The access of one table a plan creates (`before` absent) or changes: the rules, grants and row security now and
314
+ * after, one sentence per rule, and the findings the change brings and removes.
315
+ */
316
+ function planTableAccess(table, before, after) {
317
+ const next = (0, access_1.accessFindings)(after);
318
+ const now = before ? (0, access_1.accessFindings)(before) : [];
319
+ const ids = (findings) => new Set(findings.map((finding) => finding.id));
320
+ const [wasIds, willIds] = [ids(now), ids(next)];
321
+ const short = ({ id, level, summary, columns, details }) => ({
322
+ id,
323
+ level,
324
+ summary,
325
+ ...(columns?.length ? { columns } : {}),
326
+ ...(details?.length ? { details } : {}),
327
+ });
328
+ return {
329
+ table,
330
+ ...(before ? { before: (0, exports.accessState)(before) } : {}),
331
+ after: (0, exports.accessState)(after),
332
+ findingsAdded: next.filter((finding) => !wasIds.has(finding.id)).map(short),
333
+ findingsRemoved: now.filter((finding) => !willIds.has(finding.id)).map(short),
334
+ };
335
+ }
336
+ const sqlLiteral = (value) => (typeof value === 'string' ? `'${value.replace(/'/g, "''")}'` : JSON.stringify(value));
337
+ // A default as the SQL it stands for: `false`, `jwt_public.current_user_id()`, `now()`.
338
+ function defaultSql(value) {
339
+ if (value.sql_keyword)
340
+ return value.sql_keyword;
341
+ if (value.operator && value.left && value.right)
342
+ return `${defaultSql(value.left)} ${value.operator} ${defaultSql(value.right)}`;
343
+ const base = value.function
344
+ ? `${value.schema ? `${value.schema}.` : ''}${value.function}(${(value.args ?? []).map((arg) => (arg !== null && typeof arg === 'object' ? defaultSql(arg) : sqlLiteral(arg))).join(', ')})`
345
+ : sqlLiteral(value.value ?? null);
346
+ return value.cast ? `${base}::${value.cast.name}` : base;
347
+ }
348
+ function planColumn(column) {
349
+ const base = { name: column.name, type: column.type, required: !column.nullable };
350
+ if (column.default === 'unknown')
351
+ return base;
352
+ if (column.default === null)
353
+ return { ...base, default: null };
354
+ if ('generated' in column.default)
355
+ return { ...base, default: `generated by PostgreSQL (${column.default.generated})` };
356
+ const fills = (0, access_1.defaultFills)(column.default);
357
+ return { ...base, default: defaultSql(column.default), ...(fills.existing_rows === false ? { computed: true } : {}) };
358
+ }
359
+ // A required column fails on the rows the table has when its default does not fill them (the registry's defaultFills).
360
+ const failsOnRows = (column) => !column.nullable && (0, access_1.defaultFills)(column.default).existing_rows === false;
361
+ function missingColumns(table, missing) {
362
+ const columns = [...new Set(missing.map((entry) => entry.column))];
363
+ const sentences = missing.map(({ type, column }) => `${type} reads the column "${column}", which table "${table}" does not have and this change does not add, so the backend cannot build the rule.`);
364
+ return {
365
+ code: 'invalid-input',
366
+ message: [...new Set(sentences)].join(' '),
367
+ hint: `Add ${(0, harness_1.listed)(columns)} to the table first, or name a column the table has.`,
368
+ calls: [...columns.map((column) => (0, failure_1.suggest)('create_field', { table_name: table, field_name: column }, `Add the column ${column} the rule reads`, ['type'])), failure_1.DESCRIBE_SCHEMA],
369
+ };
370
+ }
371
+ // A column the table has, as the plan says it: its own type, NOT NULL and default (stored as the JSON of a FieldDefault).
372
+ function existingColumn(field) {
373
+ let stored = field.defaultValue;
374
+ try {
375
+ stored = field.defaultValue === null ? null : JSON.parse(field.defaultValue);
376
+ }
377
+ catch {
378
+ // A default the backend gave as text is the SQL itself.
379
+ }
380
+ const sql = stored === null ? null : typeof stored === 'object' ? defaultSql(stored) : String(stored);
381
+ return { name: field.name, type: field.type, required: field.isRequired, default: sql };
382
+ }
383
+ /**
384
+ * The columns `nodes` add to a table that has `fields`, and the ones they
385
+ * reuse (a generator keeps a column of the same name as it is), refused when
386
+ * a rule reads a column the table has not and no node of the change adds: the
387
+ * backend cannot build that rule. Where a node's columns, or the columns a
388
+ * rule reads, are not known, the plan says what it cannot check instead.
389
+ */
390
+ function columnChange(table, fields, nodes, rules) {
391
+ const { fields: columns, unknown } = (0, access_1.fieldsAddedByNodes)(nodes);
392
+ const has = new Map(fields.map((field) => [field.name, field]));
393
+ const adds = columns.filter((column) => !has.has(column.name));
394
+ const reused = columns.flatMap((column) => {
395
+ const field = has.get(column.name);
396
+ return field && 'type' in field ? [existingColumn(field)] : [];
397
+ });
398
+ const known = new Set([...has.keys(), ...adds.map((column) => column.name)]);
399
+ const read = (0, access_1.columnsReadByPolicies)(rules.map((rule) => ({ ...rule, data: rule.data ?? {} })));
400
+ const missing = read.columns.filter((entry) => !known.has(entry.column));
401
+ const notes = unknown.length ? [`The columns ${unknown.join(', ')} add${unknown.length === 1 ? 's' : ''} are not known to the registry, so this plan cannot list them.`] : [];
402
+ if (read.unknown.length) {
403
+ notes.push(`The registry cannot tell which columns ${(0, harness_1.listed)(read.unknown)} reads (a stored expression, or data it does not describe), so this plan cannot check that table "${table}" has them.`);
404
+ }
405
+ if (missing.length && !unknown.length)
406
+ return { kind: 'failed', failure: missingColumns(table, missing) };
407
+ for (const { type, column } of missing)
408
+ notes.push(`${type} reads the column "${column}", which table "${table}" does not have; this plan cannot tell whether ${(0, harness_1.listed)(unknown)} adds it.`);
409
+ const added = adds.map(planColumn);
410
+ return { kind: 'ok', value: { added, reused, failsIfRows: added.filter((_column, index) => failsOnRows(adds[index])), fields: adds.map(addedField), notes } };
411
+ }
412
+ /** 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. */
413
+ const columnPlan = (change, existing) => ({
414
+ ...(change.added.length ? { columnsAdded: change.added } : {}),
415
+ ...(change.reused.length ? { columnsReused: change.reused } : {}),
416
+ ...(existing && change.failsIfRows.length ? { failsIfRows: change.failsIfRows.map((column) => column.name) } : {}),
417
+ });
418
+ exports.columnPlan = columnPlan;
419
+ /** Why a change that adds `columns` cannot apply to `table` while it has rows, and the fix. */
420
+ function rowsConflict(table, columns) {
421
+ const names = (0, harness_1.listed)(columns.map((column) => column.name));
422
+ const many = columns.length === 1 ? '' : 's';
423
+ return {
424
+ message: `table "${table}" has rows, and the change adds the required column${many} ${names} with no value for them.`,
425
+ hint: `Add ${names} first as ${columns.length === 1 ? 'an optional column' : 'optional columns'}, give the rows a value, then make the change again: it keeps a column that exists, as it is.`,
426
+ calls: columns.map((column) => (0, failure_1.suggest)('create_field', { table_name: table, field_name: column.name, type: column.type, is_required: false }, `Add ${column.name} as an optional column first, so the rows can get a value`)),
427
+ };
428
+ }
429
+ /**
430
+ * What a refusal of a change to `table` means: a refused NOT NULL is the rows the added columns get no value for,
431
+ * and a refused rule is one of the caller's own `rules` (a preset's are the registry's, so they are left out).
432
+ */
433
+ const changeMeaning = (table, change, rules) => ({
434
+ ...(change.failsIfRows.length ? { notNull: rowsConflict(table, change.failsIfRows) } : {}),
435
+ ...(rules ? { policyTypes: rules.map((rule) => rule.type) } : {}),
436
+ });
437
+ exports.changeMeaning = changeMeaning;
@@ -0,0 +1,218 @@
1
+ import { type HarnessTool, type PlanRule, type ToolCallSuggestion, type ToolFailure } from '@agentic-kit/harness';
2
+ import { type BlueprintNode, type BlueprintPolicy } from 'node-type-registry';
3
+ import { z } from 'zod';
4
+ import { type AccessFinding, type MembershipScope, type ResolvedPolicy, type TableAccessInput, type TablePolicy } from '../access';
5
+ import type { RuleContext } from '../access/rule-check';
6
+ import { type RelatedColumns } from '../access/words';
7
+ import { type AccessPolicy } from '../blueprint/blueprint-schema';
8
+ import type { ProjectContext } from '../context';
9
+ import { type FailureMeaning, type Result } from '../failure';
10
+ import { type ColumnChange, type Rule, type TableRecord, type WrittenRule } from '../table-access';
11
+ declare const DescribePolicyTypeZod: z.ZodObject<{
12
+ type: z.ZodOptional<z.ZodEnum<{
13
+ [x: string]: string;
14
+ }>>;
15
+ }, z.core.$strict>;
16
+ type PolicyTypeSummary = {
17
+ name: string;
18
+ summary?: string;
19
+ tableKind?: string;
20
+ };
21
+ type PolicyTypeDetail = PolicyTypeSummary & {
22
+ parameterSchema: unknown;
23
+ useWhen: string[];
24
+ avoidWhen: string[];
25
+ risks: string[];
26
+ dataNode?: unknown;
27
+ };
28
+ export declare const describePolicyTypeTool: HarnessTool<typeof DescribePolicyTypeZod, {
29
+ types?: PolicyTypeSummary[];
30
+ type?: PolicyTypeDetail;
31
+ }>;
32
+ declare const ExplainAccessZod: z.ZodObject<{
33
+ table_name: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$strict>;
35
+ /** One stored rule: in the shape a caller writes it, with its words. */
36
+ export type ExplainedRule = WrittenRule & Pick<PlanRule, 'words'>;
37
+ /** The access of one live table: each rule in words, the grants, row security, and what may be wrong. */
38
+ export type ExplainedTable = {
39
+ name: string;
40
+ rules: ExplainedRule[];
41
+ grants: string[];
42
+ rowSecurity: boolean;
43
+ findings: AccessFinding[];
44
+ };
45
+ export declare const explainAccessTool: HarnessTool<typeof ExplainAccessZod, {
46
+ tables: ExplainedTable[];
47
+ }>;
48
+ declare const SetAccessZod: z.ZodObject<{
49
+ table_name: z.ZodString;
50
+ policies: z.ZodArray<z.ZodObject<{
51
+ $type: z.ZodString;
52
+ privileges: z.ZodOptional<z.ZodArray<z.ZodString>>;
53
+ permissive: z.ZodOptional<z.ZodBoolean>;
54
+ policy_role: z.ZodOptional<z.ZodString>;
55
+ policy_name: z.ZodOptional<z.ZodString>;
56
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
57
+ }, z.core.$loose>>;
58
+ }, z.core.$strict>;
59
+ type SetAccessParams = z.infer<typeof SetAccessZod>;
60
+ /** What one change of a table's access installs; `owns` names what it replaces instead of adding to. */
61
+ export type Provision = {
62
+ nodes: BlueprintNode[];
63
+ policies: BlueprintPolicy[];
64
+ grants?: unknown;
65
+ owns?: Array<'policies' | 'grants'>;
66
+ };
67
+ /**
68
+ * What a change does to the columns of an existing table, refused before
69
+ * anything changes when the backend cannot apply it: a rule reads a column
70
+ * nothing gives the table, or a required column would be added to a table
71
+ * whose rows this tool can see.
72
+ */
73
+ export declare function existingTableChange(context: ProjectContext, table: TableRecord, nodes: BlueprintNode[], rules: readonly Rule[]): Promise<Result<ColumnChange>>;
74
+ /** Installs `provision` on the table in one request: the backend applies it in one transaction. */
75
+ export declare function applyProvision(context: ProjectContext, table: {
76
+ id: string;
77
+ name: string;
78
+ }, provision: Provision, action: string, meaning: FailureMeaning): Promise<ToolFailure | null>;
79
+ /** What the table holds after a change that is not what its plan said, by meaning. */
80
+ export type AccessDifference = {
81
+ unplanned: TablePolicy[];
82
+ missing: TablePolicy[];
83
+ grants?: {
84
+ unplanned: string[];
85
+ missing: string[];
86
+ };
87
+ rowSecurityOff?: true;
88
+ columnsMissing?: string[];
89
+ };
90
+ /** The table after a change: as its plan said, different, or not readable. */
91
+ export type ReadBack = {
92
+ kind: 'same';
93
+ table: TableRecord;
94
+ } | {
95
+ kind: 'different' | 'unverified';
96
+ failure: ToolFailure;
97
+ };
98
+ /**
99
+ * Reads the access of a table again after a change returned, and compares it
100
+ * by meaning with the after state of the plan: `policyDifference` decides for
101
+ * the rules (order, duplicates, defaults, derived keys and the backend's own
102
+ * copy of the read-only block do not count), then the grants, row security
103
+ * and the columns the change added. A change made at the same moment by
104
+ * another call is what this finds: the backend's replace does not wait for
105
+ * one. `again` is the call that makes the table as the plan said, when there
106
+ * is one.
107
+ */
108
+ export declare function readBack(context: ProjectContext, table: string, planned: PlannedAccess, added: string[], again?: ToolCallSuggestion): Promise<ReadBack>;
109
+ /** A table's access after a change, as its plan says: its rules in the form the backend stores them. */
110
+ export type PlannedAccess = Omit<TableAccessInput, 'policies'> & {
111
+ policies: ResolvedPolicy[];
112
+ };
113
+ export type SetAccessReady = {
114
+ context: ProjectContext;
115
+ table: TableRecord;
116
+ provision: Provision;
117
+ after: PlannedAccess;
118
+ notes: string[];
119
+ /** The columns the change adds. */
120
+ columns: ColumnChange;
121
+ /** What a refusal of the change means. */
122
+ meaning: FailureMeaning;
123
+ };
124
+ /**
125
+ * The rule the backend adds by itself beside the first team-membership rule of a change that grants writes: a
126
+ * restrictive `AuthzNotReadOnly` for those writes. A plan's after state holds it, so the plan and the read-back after
127
+ * the change both count it.
128
+ */
129
+ export declare function addedByBackend(policies: readonly BlueprintPolicy[], grants: TableAccessInput['grants'] | undefined): TablePolicy[];
130
+ /** What a plan says about the read-only limit beside a team rule: the backend adds it only for a change that grants writes. */
131
+ export declare function readOnlyNotes(policies: readonly BlueprintPolicy[], grants: TableAccessInput['grants'] | undefined): string[];
132
+ /** The roles a rule can name: the request roles every API has, and the roles the database's APIs run as, read only when a rule names another. */
133
+ export declare function rolesFor(context: ProjectContext, policies: ReadonlyArray<{
134
+ policy_role?: string;
135
+ }>): Promise<Result<string[] | undefined>>;
136
+ /**
137
+ * The problems of the rules a caller wrote, as one failure: each rule's shape against the registry's `BlueprintPolicy`
138
+ * (`with_check` only where `withCheck` allows it), and its data against its policy type with the rule's context; each
139
+ * problem with its rule, and the calls that describe the nodes it is in.
140
+ */
141
+ export declare function ruleProblems(policies: ReadonlyArray<{
142
+ $type: string;
143
+ data?: unknown;
144
+ policy_role?: string;
145
+ }>, context: Omit<RuleContext, 'role'> & {
146
+ withCheck?: boolean;
147
+ }, label: (index: number) => string): ToolFailure | null;
148
+ /**
149
+ * The columns of the database's application tables, by id and by name, read only when a rule needs another table's
150
+ * columns; `tables` are tables already read.
151
+ */
152
+ export declare function relatedColumns(context: ProjectContext, policies: ReadonlyArray<{
153
+ type?: string;
154
+ $type?: string;
155
+ data?: unknown;
156
+ }>, tables?: TableRecord[]): Promise<Result<RelatedColumns | undefined>>;
157
+ /**
158
+ * The rules a change sends, as the backend creates them, or the failure that names the first rule the backend would
159
+ * skip or refuse. Rules of one policy type, role, kind and data become one rule with all their privileges (in lower
160
+ * case). Beside an earlier rule or one the table keeps (`table`, for an add), a rule is refused when the backend keeps
161
+ * only one of its type and data, or when it names a policy row the same way: the role's first four letters, the
162
+ * privilege's first three, and the rule's name. Every tool that sends rules sends them through this.
163
+ */
164
+ export declare function rulesToSend(given: readonly BlueprintPolicy[], { table, defaultRole, label }: {
165
+ table?: TableRecord;
166
+ defaultRole: string;
167
+ label: (index: number) => string;
168
+ }): Result<BlueprintPolicy[]>;
169
+ /** The rules a change sends, as the backend will store them, the team kinds their entity_type names, and the columns of other tables they read. */
170
+ export type StoredRules = {
171
+ policies: BlueprintPolicy[];
172
+ scopes: MembershipScope[];
173
+ related?: RelatedColumns;
174
+ };
175
+ /**
176
+ * The rules a change sends, checked before the plan: each rule's shape and data, with the role it names and the
177
+ * columns of the other tables it reads; every `entity_type` becomes the team kind the backend stores; and the rules
178
+ * go through `rulesToSend`, beside the rules the table keeps (`table`, for an add). `live` is the table the plan shows
179
+ * now, whose rules may read other tables too.
180
+ */
181
+ export declare function storedRules(context: ProjectContext, given: AccessPolicy[], { table, grants, live }: {
182
+ table?: TableRecord;
183
+ grants?: TableAccessInput['grants'];
184
+ live?: TableRecord;
185
+ }): Promise<Result<StoredRules>>;
186
+ /** The access a change leaves: `kept` (the table's rules an add keeps) and `sent`, with the rule the backend adds itself. */
187
+ export declare function plannedPolicies(kept: TablePolicy[], sent: BlueprintPolicy[], grants: TableAccessInput['grants'] | undefined, scopes: MembershipScope[]): ResolvedPolicy[];
188
+ /** The Data nodes the rules need for the columns `table` lacks, or the failure that says which rule names a column its node cannot add. */
189
+ export declare function neededNodes(policies: readonly BlueprintPolicy[], table: TableRecord): Result<BlueprintNode[]>;
190
+ /** The calls that fix a required column no rule sets: make it optional, or drop it. */
191
+ export declare const columnFixes: (table: string, column: string) => ToolCallSuggestion[];
192
+ /**
193
+ * What set_access checks before it changes anything: a list of rules, the
194
+ * table, and the columns the rules need. It resolves the replacement and the
195
+ * access the table will have.
196
+ */
197
+ export declare function setAccessReady(params: SetAccessParams, cwd: string): Promise<Result<SetAccessReady>>;
198
+ /** The plan's access for set_access: the live table now, and after the replace, with the columns it adds. */
199
+ export declare const setAccessPlan: ({ table, after, notes, columns }: SetAccessReady) => {
200
+ notes?: string[];
201
+ columnsAdded?: import("@agentic-kit/harness").PlanColumn[];
202
+ columnsReused?: import("@agentic-kit/harness").PlanColumn[];
203
+ failsIfRows?: string[];
204
+ table: string;
205
+ schema?: string;
206
+ before?: import("@agentic-kit/harness").PlanAccessState;
207
+ after: import("@agentic-kit/harness").PlanAccessState;
208
+ findingsAdded: import("@agentic-kit/harness").PlanFinding[];
209
+ findingsRemoved: import("@agentic-kit/harness").PlanFinding[];
210
+ }[];
211
+ type SetAccessDetails = {
212
+ success: boolean;
213
+ message: string;
214
+ table?: string;
215
+ access?: ExplainedTable;
216
+ };
217
+ export declare const setAccessTool: HarnessTool<typeof SetAccessZod, SetAccessDetails>;
218
+ export {};