@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
@@ -63,10 +63,29 @@ export declare class ProvisionPendingError extends Error {
63
63
  * see it. Nothing says the provision stopped, so a caller must not request
64
64
  * the same database again on this alone.
65
65
  */
66
+ /** A ticket read the backend refused because the sign-in has ended: the provision may still be running. */
67
+ export declare class ProvisionSignedOutError extends Error {
68
+ readonly ticketId: string;
69
+ constructor(message: string, ticketId: string, options?: {
70
+ cause?: unknown;
71
+ });
72
+ }
66
73
  export declare class ProvisionTicketLostError extends Error {
67
74
  readonly ticketId: string;
68
75
  constructor(message: string, ticketId: string);
69
76
  }
77
+ /**
78
+ * The provision ticket failed. `ticketError` is the text the backend's job
79
+ * stored on the ticket, a column rather than a GraphQL error, so it carries no
80
+ * extensions: a refusal the job raised reads as its code ("[run]
81
+ * BILLING_PLAN_REQUIRED", or "LIMIT_REACHED"), anything else as the job's own
82
+ * text, which is for decisions only. The message names the ticket instead,
83
+ * which the backend operator can look up.
84
+ */
85
+ export declare class ProvisionJobError extends Error {
86
+ readonly ticketError: string;
87
+ constructor(ticketError: string, step: 'provisioning' | 'owner bootstrap', ticketId: string);
88
+ }
70
89
  export declare function createProvisionExecutor(args: {
71
90
  apiEndpoint: string;
72
91
  modulesEndpoint: string;
@@ -77,9 +96,9 @@ export declare function isTicketInFlight(ticket: ProvisionTicket): boolean;
77
96
  /**
78
97
  * Whether an error reading or requesting a ticket says only that the backend
79
98
  * couldn't be reached or failed: a network error thrown before any response,
80
- * or an HTTP 5xx/429 the adapter reports as the only error. A GraphQL error
81
- * (validation, permission, an expired or rejected token) is an answer, so the
82
- * ticket can't be followed any further.
99
+ * or errors that all carry an HTTP 5xx or 429 (inside the error, or from the
100
+ * adapter). Any other GraphQL error (validation, permission, an expired or
101
+ * rejected token) is an answer, so the ticket can't be followed any further.
83
102
  */
84
103
  export declare function isTransientProvisionError(err: unknown): boolean;
85
104
  /**
@@ -9,9 +9,10 @@
9
9
  // bootstrap completes the new database has zero users, so its per-DB API
10
10
  // would reject the owner token under RLS. requestDatabase owns the database
11
11
  // to the JWT user — there is no owner input. The generated ORM's default
12
- // adapter is plain fetch, so the SDK's FetchAdapter is injected to keep
13
- // *.localhost DNS/Host routing working in Node.
12
+ // adapter is plain fetch, so the SDK's FetchAdapter is injected to keep the
13
+ // routing of per-database subdomains working in Node.
14
14
  import { api, modules } from '@constructive-io/sdk';
15
+ import { answersSignedOut, statusOf, thrownText } from '../graphql-http';
15
16
  export const POLL_INTERVAL_MS = 2_000;
16
17
  /** Stays under airpage's 5-minute per-tool timeout. */
17
18
  export const POLL_DEADLINE_MS = 240_000;
@@ -40,6 +41,15 @@ export class ProvisionPendingError extends Error {
40
41
  * see it. Nothing says the provision stopped, so a caller must not request
41
42
  * the same database again on this alone.
42
43
  */
44
+ /** A ticket read the backend refused because the sign-in has ended: the provision may still be running. */
45
+ export class ProvisionSignedOutError extends Error {
46
+ ticketId;
47
+ constructor(message, ticketId, options) {
48
+ super(message, options);
49
+ this.ticketId = ticketId;
50
+ this.name = 'ProvisionSignedOutError';
51
+ }
52
+ }
43
53
  export class ProvisionTicketLostError extends Error {
44
54
  ticketId;
45
55
  constructor(message, ticketId) {
@@ -48,6 +58,22 @@ export class ProvisionTicketLostError extends Error {
48
58
  this.name = 'ProvisionTicketLostError';
49
59
  }
50
60
  }
61
+ /**
62
+ * The provision ticket failed. `ticketError` is the text the backend's job
63
+ * stored on the ticket, a column rather than a GraphQL error, so it carries no
64
+ * extensions: a refusal the job raised reads as its code ("[run]
65
+ * BILLING_PLAN_REQUIRED", or "LIMIT_REACHED"), anything else as the job's own
66
+ * text, which is for decisions only. The message names the ticket instead,
67
+ * which the backend operator can look up.
68
+ */
69
+ export class ProvisionJobError extends Error {
70
+ ticketError;
71
+ constructor(ticketError, step, ticketId) {
72
+ super(`the backend's ${step} job failed (ticket ${ticketId})`);
73
+ this.ticketError = ticketError;
74
+ this.name = 'ProvisionJobError';
75
+ }
76
+ }
51
77
  const TICKET_SELECT = {
52
78
  id: true,
53
79
  status: true,
@@ -111,21 +137,24 @@ const NETWORK_ERROR_RE = /fetch failed|network|socket hang up|ECONNRESET|ECONNRE
111
137
  /**
112
138
  * Whether an error reading or requesting a ticket says only that the backend
113
139
  * couldn't be reached or failed: a network error thrown before any response,
114
- * or an HTTP 5xx/429 the adapter reports as the only error. A GraphQL error
115
- * (validation, permission, an expired or rejected token) is an answer, so the
116
- * ticket can't be followed any further.
140
+ * or errors that all carry an HTTP 5xx or 429 (inside the error, or from the
141
+ * adapter). Any other GraphQL error (validation, permission, an expired or
142
+ * rejected token) is an answer, so the ticket can't be followed any further.
117
143
  */
118
144
  export function isTransientProvisionError(err) {
119
145
  const errors = err?.errors;
120
146
  if (Array.isArray(errors)) {
121
- return errors.length > 0 && errors.every((e) => /^HTTP (5\d\d|429)\b/.test(e?.message ?? ''));
147
+ return (errors.length > 0 &&
148
+ errors.every((e) => {
149
+ const status = statusOf(e);
150
+ return status !== undefined && (status >= 500 || status === 429);
151
+ }));
122
152
  }
123
153
  if (!(err instanceof Error))
124
154
  return false;
125
155
  const code = err.cause?.code;
126
156
  return NETWORK_ERROR_RE.test(`${err.message} ${typeof code === 'string' ? code : ''}`);
127
157
  }
128
- const errorText = (err) => (err instanceof Error ? err.message : String(err));
129
158
  function sleep(ms) {
130
159
  return new Promise((resolve) => setTimeout(resolve, ms));
131
160
  }
@@ -161,9 +190,11 @@ export async function requestDatabaseProvision(args) {
161
190
  }
162
191
  catch (err) {
163
192
  if (isTransientProvisionError(err)) {
164
- throw new ProvisionPendingError(errorText(err), args.resumeTicketId, { cause: err });
193
+ throw new ProvisionPendingError(thrownText(err), args.resumeTicketId, { cause: err });
165
194
  }
166
- throw new Error(`provision ticket ${args.resumeTicketId} could not be read: ${errorText(err)}`, {
195
+ if (answersSignedOut(err))
196
+ throw new ProvisionSignedOutError(thrownText(err), args.resumeTicketId, { cause: err });
197
+ throw new Error(`provision ticket ${args.resumeTicketId} could not be read: ${thrownText(err)}`, {
167
198
  cause: err,
168
199
  });
169
200
  }
@@ -186,10 +217,10 @@ export async function requestDatabaseProvision(args) {
186
217
  let failures = 0;
187
218
  for (;;) {
188
219
  if (ticket.status === 'failed') {
189
- throw new Error(ticket.errorMessage ?? 'provisioning failed');
220
+ throw new ProvisionJobError(ticket.errorMessage ?? '', 'provisioning', ticketId);
190
221
  }
191
222
  if (ticket.bootstrapStatus === 'failed') {
192
- throw new Error(ticket.bootstrapError ?? 'owner bootstrap failed');
223
+ throw new ProvisionJobError(ticket.bootstrapError ?? '', 'owner bootstrap', ticketId);
193
224
  }
194
225
  if (ticket.status === 'completed' && ticket.bootstrapStatus === 'completed') {
195
226
  if (!ticket.databaseId)
@@ -209,13 +240,15 @@ export async function requestDatabaseProvision(args) {
209
240
  polled = await executor.poll(ticketId);
210
241
  }
211
242
  catch (err) {
243
+ if (answersSignedOut(err))
244
+ throw new ProvisionSignedOutError(thrownText(err), ticketId, { cause: err });
212
245
  if (!isTransientProvisionError(err)) {
213
- throw new Error(`provision ticket ${ticketId} could not be read: ${errorText(err)}`, {
246
+ throw new Error(`provision ticket ${ticketId} could not be read: ${thrownText(err)}`, {
214
247
  cause: err,
215
248
  });
216
249
  }
217
250
  if (++failures > MAX_CONSECUTIVE_POLL_FAILURES) {
218
- throw new ProvisionPendingError(errorText(err), ticketId, { cause: err });
251
+ throw new ProvisionPendingError(thrownText(err), ticketId, { cause: err });
219
252
  }
220
253
  continue;
221
254
  }
package/esm/ready.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { PlanTarget } from '@agentic-kit/harness';
2
+ import { type ProjectContext } from './context';
3
+ import { type Result } from './failure';
4
+ /** The bound database a change goes to, at the backend and as the account the context resolved. */
5
+ export declare function databaseTarget(context: ProjectContext, appUserId?: string): Extract<PlanTarget, {
6
+ kind: 'database';
7
+ }>;
8
+ /** A change to what the account owns beside its databases (its templates), at the context's backend. */
9
+ export declare function accountTarget(context: ProjectContext): PlanTarget;
10
+ /** The project context of `cwd`, on the plane the tool acts on. */
11
+ export declare function projectReady(cwd: string, plane?: 'control' | 'data'): Promise<Result<ProjectContext>>;
12
+ /** The control-plane context of a project whose binding names its owner. */
13
+ export declare function ownedProjectReady(cwd: string): Promise<Result<ProjectContext & {
14
+ ownerId: string;
15
+ }>>;
16
+ /** A data-plane token of the person signed in to the app. */
17
+ export declare function appSessionReady(context: ProjectContext): Promise<Result<{
18
+ token: string;
19
+ userId?: string;
20
+ }>>;
package/esm/ready.js ADDED
@@ -0,0 +1,45 @@
1
+ // What a tool resolves before it changes anything. A tool runs its check first
2
+ // and stops with the failure; the gate runs the very same check
3
+ // (`toolPreconditions` in ./tools) and blocks the call with that failure, so
4
+ // the gate and the tool cannot disagree about whether a call can run.
5
+ import { resolveDataToken, resolveProjectContext } from './context';
6
+ import { MISSING_OWNER } from './failure';
7
+ const accountOf = (context) => ({
8
+ userId: context.accountUserId,
9
+ ...(context.accountEmail ? { email: context.accountEmail } : {}),
10
+ ...(context.accountAgent ? { agent: context.accountAgent } : {}),
11
+ });
12
+ /** The bound database a change goes to, at the backend and as the account the context resolved. */
13
+ export function databaseTarget(context, appUserId) {
14
+ return {
15
+ kind: 'database',
16
+ database: { name: context.databaseName, id: context.databaseId },
17
+ apiEndpoint: context.controlApiEndpoint,
18
+ account: accountOf(context),
19
+ ...(appUserId ? { appUserId } : {}),
20
+ };
21
+ }
22
+ /** A change to what the account owns beside its databases (its templates), at the context's backend. */
23
+ export function accountTarget(context) {
24
+ return { kind: 'account', apiEndpoint: context.controlApiEndpoint, account: accountOf(context) };
25
+ }
26
+ /** The project context of `cwd`, on the plane the tool acts on. */
27
+ export async function projectReady(cwd, plane = 'control') {
28
+ const resolved = await resolveProjectContext(cwd, { plane });
29
+ return resolved.context ? { kind: 'ok', value: resolved.context } : { kind: 'failed', failure: resolved.failure };
30
+ }
31
+ /** The control-plane context of a project whose binding names its owner. */
32
+ export async function ownedProjectReady(cwd) {
33
+ const ready = await projectReady(cwd);
34
+ if (ready.kind === 'failed')
35
+ return ready;
36
+ const { ownerId } = ready.value;
37
+ return ownerId ? { kind: 'ok', value: { ...ready.value, ownerId } } : { kind: 'failed', failure: MISSING_OWNER };
38
+ }
39
+ /** A data-plane token of the person signed in to the app. */
40
+ export async function appSessionReady(context) {
41
+ const token = await resolveDataToken(context);
42
+ return token.token
43
+ ? { kind: 'ok', value: { token: token.token, userId: token.userId } }
44
+ : { kind: 'failed', failure: token.failure };
45
+ }
@@ -1,4 +1,4 @@
1
- // Turbopack barrel normalization (TURBOPACK-BARREL-001).
1
+ // Turbopack barrel normalization.
2
2
  //
3
3
  // Codegen emits directory barrel re-exports like `export * from './hooks'` where
4
4
  // `./hooks` is a directory with an index.ts. Next.js 16's Turbopack cannot
@@ -1,9 +1,8 @@
1
- // Codegen and the Next.js dev server default every per-DB vhost to
2
- // *-<db>.localhost:3000, which only exists on a local backend. Derive the real
3
- // vhosts from the api endpoint the binding belongs to by swapping its first
4
- // host label (api.launchql.dev -> admin-<db>.launchql.dev) — the same scheme
5
- // context.ts uses for the data plane. The app DATA plane is `api-<db>`, not
6
- // `app-<db>` (SUBDOMAIN-001).
1
+ // Codegen and the Next.js dev server default every per-DB vhost to a local
2
+ // host, which only exists on a local backend. Derive the real vhosts from the
3
+ // api endpoint the binding belongs to by swapping its first host label
4
+ // (api.example.com -> admin-<db>.example.com) — the same scheme context.ts uses
5
+ // for the data plane. The app DATA plane is `api-<db>`, not `app-<db>`.
7
6
  export function derivePlaneEndpoints(apiEndpoint, databaseName) {
8
7
  const derive = (label) => {
9
8
  try {
@@ -1,6 +1,6 @@
1
1
  // Pure readers for the metaschema's stored shapes: field types, structured
2
2
  // defaults, check expressions (Postgres AST JSON) and foreign key actions.
3
- import { fieldTypeToTypeName, toFieldDefault } from '@agentic-kit/harness';
3
+ import { fieldTypeToTypeName, toFieldDefault } from '../blueprint/field-type';
4
4
  const TYPE_ALIASES = {
5
5
  int: 'integer',
6
6
  int4: 'integer',
@@ -2,8 +2,8 @@
2
2
  // piece: every APP table with every field (whatever its category), keys,
3
3
  // checks, foreign keys and policies. The ids are the metaschema's own, so they
4
4
  // stay put across renames.
5
- import { isInternalPolicy } from '@agentic-kit/harness';
6
- import { errorsText } from './graphql-http';
5
+ import { isInternalPolicy } from './blueprint/internal-policies';
6
+ import { answerText, thrownText } from './graphql-http';
7
7
  import { columnDefault, fkAction, normalizeType, readCheck } from './schema-model/normalize';
8
8
  /** A read failed, so there is no model: a partial one would look like columns dropped outside. */
9
9
  export class SchemaReadError extends Error {
@@ -81,10 +81,10 @@ async function read(step, query) {
81
81
  result = await query.execute();
82
82
  }
83
83
  catch (err) {
84
- throw new SchemaReadError(`Could not read ${step}: ${err instanceof Error ? err.message : String(err)}`, step);
84
+ throw new SchemaReadError(`Could not read ${step}: ${thrownText(err)}`, step);
85
85
  }
86
86
  if (!result.ok) {
87
- throw new SchemaReadError(`Could not read ${step}: ${errorsText(result.errors ?? [])}`, step, result.errors);
87
+ throw new SchemaReadError(`Could not read ${step}: ${answerText(result.errors ?? [])}`, step, result.errors);
88
88
  }
89
89
  return result.data;
90
90
  }
@@ -262,7 +262,6 @@ export async function readSchemaModel(context) {
262
262
  })
263
263
  .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));
264
264
  const policies = (policiesByTable.get(table.id) ?? [])
265
- .filter((policy) => !isInternalPolicy(policy.policyType))
266
265
  .map((policy) => ({
267
266
  id: policy.id,
268
267
  type: policy.policyType ?? '',
@@ -1,3 +1,4 @@
1
+ import type { ToolFailure } from '@agentic-kit/harness';
1
2
  import type { ProjectContext } from './context';
2
3
  export type ResolvedField = {
3
4
  id: string;
@@ -18,6 +19,55 @@ export type ResolvedSchema = {
18
19
  tables: ResolvedTable[];
19
20
  };
20
21
  export declare function resolveSchema(context: ProjectContext): Promise<ResolvedSchema>;
22
+ /**
23
+ * A name that is not found, and the stored form of it when one of `names` has
24
+ * it: a person often asks for a table or field by the name they made it with.
25
+ */
26
+ export declare function notFound(what: 'Table' | 'Field', name: string, message: string, names: readonly string[]): ToolFailure;
21
27
  export declare function resolveTable(schema: ResolvedSchema, tableName: string): ResolvedTable;
22
28
  export declare function resolveField(table: ResolvedTable, fieldName: string): ResolvedField;
23
29
  export declare function findUniqueConstraintId(table: ResolvedTable, fieldId: string): string | undefined;
30
+ /**
31
+ * The name the backend stores for a new table or field named `name`, as it
32
+ * rewrites every new name: a capital starts a word, separators become one
33
+ * underscore, and a word of one letter joins its neighbour (`r2_rows_a` is
34
+ * stored as `r2_rowsa`). Undefined for a
35
+ * name with a character outside ASCII, which the backend strips of accents
36
+ * first (unaccent), so this cannot say.
37
+ */
38
+ export declare function storedName(name: string): string | undefined;
39
+ /** The name the backend stores for `name`, when it differs from it. */
40
+ export declare function renamed(name: string): string | undefined;
41
+ /** What a plan says about a new table or field name the backend stores differently, or cannot say. */
42
+ export declare function renameNote(what: 'table' | 'field', name: string): string | undefined;
43
+ /**
44
+ * A not-found failure for each table a blueprint's relations name that
45
+ * neither the blueprint makes nor the project database has, or null. An end
46
+ * given as a module's table names no table here.
47
+ */
48
+ export declare function relationTablesMissing(context: ProjectContext, made: readonly string[], relations: ReadonlyArray<{
49
+ source_table?: string;
50
+ source_schema?: string;
51
+ target_table?: string;
52
+ target_schema?: string;
53
+ }>, schemas: ReadonlyMap<string, string>): Promise<ToolFailure | null>;
54
+ /** The stored names of the tables of `ids`, read back from the control plane. */
55
+ export declare function storedTableNames(context: ProjectContext, ids: string[]): Promise<Map<string, string>>;
56
+ /** The schemas of the project database by name: the default one of the project (app_public) and any other. */
57
+ export declare function readSchemas(context: ProjectContext): Promise<{
58
+ kind: 'ok';
59
+ value: Map<string, string>;
60
+ } | {
61
+ kind: 'failed';
62
+ failure: ToolFailure;
63
+ }>;
64
+ /** A not-found failure for each schema a blueprint names that the project database does not have, or null. */
65
+ export declare function schemasMissing(named: readonly string[], schemas: ReadonlyMap<string, string>): ToolFailure | null;
66
+ /**
67
+ * A `name-taken` failure for the tables of `tables` that their schema already has (the project's own, app_public,
68
+ * when a table names none; `schemas` maps the others' names to ids), or null when none does.
69
+ */
70
+ export declare function tablesTaken(context: ProjectContext, tables: ReadonlyArray<{
71
+ name: string;
72
+ schema?: string;
73
+ }>, schemas?: ReadonlyMap<string, string>): Promise<ToolFailure | null>;
@@ -1,15 +1,14 @@
1
+ import { DESCRIBE_SCHEMA, failureFromError, failureFromErrors, ToolFailureError } from './failure';
1
2
  export async function resolveSchema(context) {
2
- const { api, databaseId } = context;
3
+ const { api, databaseId, schemaId } = context;
3
4
  const tablesResult = await api.table
4
5
  .findMany({
5
6
  select: { id: true, name: true },
6
- where: { databaseId: { equalTo: databaseId } },
7
+ where: { databaseId: { equalTo: databaseId }, schemaId: { equalTo: schemaId } },
7
8
  })
8
9
  .execute();
9
- if (!tablesResult.ok) {
10
- const message = tablesResult.errors.map((e) => e.message).join('; ');
11
- throw new Error(`Failed to read tables: ${message}`);
12
- }
10
+ if (!tablesResult.ok)
11
+ throw new ToolFailureError(failureFromErrors(tablesResult.errors, 'Failed to read tables'));
13
12
  const tableNodes = tablesResult.data.tables?.nodes ?? [];
14
13
  const tableIds = tableNodes.map((t) => t.id);
15
14
  const fieldsByTable = new Map();
@@ -21,10 +20,8 @@ export async function resolveSchema(context) {
21
20
  where: { tableId: { in: tableIds } },
22
21
  })
23
22
  .execute();
24
- if (!fieldsResult.ok) {
25
- const message = fieldsResult.errors.map((e) => e.message).join('; ');
26
- throw new Error(`Failed to read fields: ${message}`);
27
- }
23
+ if (!fieldsResult.ok)
24
+ throw new ToolFailureError(failureFromErrors(fieldsResult.errors, 'Failed to read fields'));
28
25
  for (const field of fieldsResult.data.fields?.nodes ?? []) {
29
26
  const list = fieldsByTable.get(field.tableId) ?? [];
30
27
  list.push({ id: field.id, name: field.name, tableId: field.tableId });
@@ -52,18 +49,207 @@ export async function resolveSchema(context) {
52
49
  }));
53
50
  return { tables };
54
51
  }
52
+ /**
53
+ * A name that is not found, and the stored form of it when one of `names` has
54
+ * it: a person often asks for a table or field by the name they made it with.
55
+ */
56
+ export function notFound(what, name, message, names) {
57
+ const stored = renamed(name);
58
+ if (stored !== undefined && names.includes(stored)) {
59
+ return {
60
+ code: 'not-found',
61
+ message: `${message} The backend stores that name as "${stored}", and a ${what.toLowerCase()} of that name exists.`,
62
+ hint: `Call again with the name "${stored}".`,
63
+ calls: [DESCRIBE_SCHEMA],
64
+ };
65
+ }
66
+ return { code: 'not-found', message, hint: `Check the ${what.toLowerCase()} names that exist, then retry.`, calls: [DESCRIBE_SCHEMA] };
67
+ }
55
68
  export function resolveTable(schema, tableName) {
56
69
  const table = schema.tables.find((t) => t.name === tableName);
57
- if (!table)
58
- throw new Error(`Table "${tableName}" not found in current schema`);
70
+ if (!table) {
71
+ const names = schema.tables.map((t) => t.name);
72
+ throw new ToolFailureError(notFound('Table', tableName, `Table "${tableName}" not found in current schema.`, names));
73
+ }
59
74
  return table;
60
75
  }
61
76
  export function resolveField(table, fieldName) {
62
77
  const field = table.fields.find((f) => f.name === fieldName);
63
- if (!field)
64
- throw new Error(`Field "${fieldName}" not found in table "${table.name}"`);
78
+ if (!field) {
79
+ const names = table.fields.map((f) => f.name);
80
+ throw new ToolFailureError(notFound('Field', fieldName, `Field "${fieldName}" not found in table "${table.name}".`, names));
81
+ }
65
82
  return field;
66
83
  }
67
84
  export function findUniqueConstraintId(table, fieldId) {
68
85
  return table.uniqueConstraints.find((c) => c.fieldIds.includes(fieldId))?.id;
69
86
  }
87
+ // PostgreSQL's `FOR m IN SELECT regexp_matches(str, re, 'g') LOOP str = replace(str, from, to)`: the matches
88
+ // are found once in the input, and each replace changes every place the matched text is.
89
+ function replaceMatches(str, re, change) {
90
+ let out = str;
91
+ for (const match of str.matchAll(re)) {
92
+ const [from, to] = change(match);
93
+ out = out.split(from).join(to);
94
+ }
95
+ return out;
96
+ }
97
+ const lowerTail = (match) => [match[1] + match[2], match[1] + match[2].toLowerCase()];
98
+ // inflection.pg_slugify(value, false), less unaccent: storedName answers only for ASCII.
99
+ function slugify(value) {
100
+ const caps = replaceMatches(replaceMatches(value, /([A-Z])([A-Z]+$)/g, lowerTail), /([A-Z])([A-Z]+)[A-Z][a-z]/g, lowerTail);
101
+ return caps
102
+ .replace(/[^\w\s-]/gi, '')
103
+ .replace(/^ +| +$/g, '')
104
+ .replace(/[-\s]+/g, '-')
105
+ .replace(/-+/g, '_')
106
+ .replace(/_+/g, '_');
107
+ }
108
+ /**
109
+ * The name the backend stores for a new table or field named `name`, as it
110
+ * rewrites every new name: a capital starts a word, separators become one
111
+ * underscore, and a word of one letter joins its neighbour (`r2_rows_a` is
112
+ * stored as `r2_rowsa`). Undefined for a
113
+ * name with a character outside ASCII, which the backend strips of accents
114
+ * first (unaccent), so this cannot say.
115
+ */
116
+ export function storedName(name) {
117
+ // eslint-disable-next-line no-control-regex
118
+ if (/[^\x00-\x7f]/.test(name))
119
+ return undefined;
120
+ const words = slugify(name)
121
+ .replace(/([A-Z])/g, '_$1')
122
+ .toLowerCase()
123
+ .replace(/^_/, '')
124
+ .replace(/_+/g, '_')
125
+ .replace(/([a-z])_$/i, '$1')
126
+ .replace(/^_([a-z])/i, '$1');
127
+ // inflection.no_single_underscores: at the start, at the end, then in the middle.
128
+ const start = replaceMatches(words, /(^[a-z])(_)/g, (match) => [match[1] + match[2], match[1]]);
129
+ const end = replaceMatches(start, /(_)([a-z]$)/g, (match) => [match[1] + match[2], match[2]]);
130
+ const middle = replaceMatches(end, /(_)([a-z]_)/g, (match) => [match[1] + match[2], match[2]]);
131
+ return [...middle].slice(0, 63).join('');
132
+ }
133
+ /** The name the backend stores for `name`, when it differs from it. */
134
+ export function renamed(name) {
135
+ const stored = storedName(name);
136
+ return stored !== undefined && stored !== name ? stored : undefined;
137
+ }
138
+ /** What a plan says about a new table or field name the backend stores differently, or cannot say. */
139
+ export function renameNote(what, name) {
140
+ if (storedName(name) === undefined) {
141
+ 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.`;
142
+ }
143
+ const stored = renamed(name);
144
+ return stored === undefined ? undefined : `The backend stores the ${what} name "${name}" as "${stored}".`;
145
+ }
146
+ /**
147
+ * A not-found failure for each table a blueprint's relations name that
148
+ * neither the blueprint makes nor the project database has, or null. An end
149
+ * given as a module's table names no table here.
150
+ */
151
+ export async function relationTablesMissing(context, made, relations, schemas) {
152
+ const named = relations.flatMap((relation) => [
153
+ { name: relation.source_table, schema: relation.source_schema },
154
+ { name: relation.target_table, schema: relation.target_schema },
155
+ ]).filter((table) => typeof table.name === 'string');
156
+ if (named.length === 0)
157
+ return null;
158
+ const key = (name, schemaId) => JSON.stringify([schemaId, name]);
159
+ const normalize = (name) => storedName(name) ?? name;
160
+ const created = new Set(made.map(normalize));
161
+ const known = new Set();
162
+ const names = new Set();
163
+ try {
164
+ const result = await context.api.table.findMany({ select: { name: true, schemaId: true }, where: { databaseId: { equalTo: context.databaseId } } }).execute();
165
+ if (!result.ok)
166
+ return failureFromErrors(result.errors, 'Failed to read the tables of the project database');
167
+ for (const table of result.data.tables?.nodes ?? []) {
168
+ names.add(table.name);
169
+ known.add(key(table.name, table.schemaId));
170
+ }
171
+ }
172
+ catch (err) {
173
+ return failureFromError(err, 'Failed to read the tables of the project database');
174
+ }
175
+ const missing = [...new Set(named.filter(({ name, schema }) => {
176
+ const stored = normalize(name);
177
+ return !created.has(stored) && !(schema === undefined ? names.has(stored) : known.has(key(stored, schemas.get(schema))));
178
+ })
179
+ .map(({ name, schema }) => schema === undefined ? name : `${schema}.${name}`))];
180
+ if (missing.length === 0)
181
+ return null;
182
+ return {
183
+ code: 'not-found',
184
+ message: missing.map((name) => `A relation of the blueprint names the table "${name}", which neither the blueprint makes nor the project database has.`).join(' '),
185
+ hint: 'Add the table to the blueprint, or name a table that exists.',
186
+ calls: [DESCRIBE_SCHEMA],
187
+ };
188
+ }
189
+ /** The stored names of the tables of `ids`, read back from the control plane. */
190
+ export async function storedTableNames(context, ids) {
191
+ if (ids.length === 0)
192
+ return new Map();
193
+ const result = await context.api.table.findMany({ select: { id: true, name: true }, where: { id: { in: ids } } }).execute();
194
+ return new Map(result.ok ? (result.data.tables?.nodes ?? []).map((table) => [table.id, table.name]) : []);
195
+ }
196
+ /** The schemas of the project database by name: the default one of the project (app_public) and any other. */
197
+ export async function readSchemas(context) {
198
+ try {
199
+ const result = await context.api.schema.findMany({ select: { id: true, name: true }, where: { databaseId: { equalTo: context.databaseId } } }).execute();
200
+ if (!result.ok)
201
+ return { kind: 'failed', failure: failureFromErrors(result.errors, 'Failed to read the schemas of the project database') };
202
+ return { kind: 'ok', value: new Map((result.data.schemas?.nodes ?? []).map((schema) => [schema.name, schema.id])) };
203
+ }
204
+ catch (err) {
205
+ return { kind: 'failed', failure: failureFromError(err, 'Failed to read the schemas of the project database') };
206
+ }
207
+ }
208
+ /** A not-found failure for each schema a blueprint names that the project database does not have, or null. */
209
+ export function schemasMissing(named, schemas) {
210
+ const missing = [...new Set(named)].filter((name) => !schemas.has(name));
211
+ if (missing.length === 0)
212
+ return null;
213
+ return {
214
+ code: 'not-found',
215
+ 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(', ')}.`,
216
+ hint: 'Name a schema the project database has, or leave the schema out for the default one.',
217
+ };
218
+ }
219
+ /**
220
+ * A `name-taken` failure for the tables of `tables` that their schema already has (the project's own, app_public,
221
+ * when a table names none; `schemas` maps the others' names to ids), or null when none does.
222
+ */
223
+ export async function tablesTaken(context, tables, schemas = new Map()) {
224
+ const bySchema = new Map();
225
+ for (const { name, schema } of tables) {
226
+ const schemaId = schema === undefined ? context.schemaId : schemas.get(schema);
227
+ if (schemaId !== undefined)
228
+ bySchema.set(schemaId, [...(bySchema.get(schemaId) ?? []), name]);
229
+ }
230
+ const taken = [];
231
+ for (const [schemaId, names] of bySchema) {
232
+ try {
233
+ const result = await context.api.table
234
+ .findMany({ select: { name: true }, where: { databaseId: { equalTo: context.databaseId }, schemaId: { equalTo: schemaId } } })
235
+ .execute();
236
+ if (!result.ok)
237
+ return failureFromErrors(result.errors, 'Failed to read the tables of the project database');
238
+ const existing = new Set((result.data.tables?.nodes ?? []).map((table) => table.name));
239
+ taken.push(...names.filter((name) => existing.has(storedName(name) ?? name)));
240
+ }
241
+ catch (err) {
242
+ return failureFromError(err, 'Failed to read the tables of the project database');
243
+ }
244
+ }
245
+ const names = [...new Set(taken)];
246
+ if (names.length === 0)
247
+ return null;
248
+ const listed = names.map((name) => (renamed(name) ? `"${renamed(name)}", which is how the backend stores "${name}"` : `"${name}"`)).join(', ');
249
+ return {
250
+ code: 'name-taken',
251
+ message: `The project database already has ${names.length === 1 ? 'a table' : 'tables'} named ${listed}.`,
252
+ hint: 'Choose another table name, or change the table that exists instead of creating it.',
253
+ calls: [DESCRIBE_SCHEMA],
254
+ };
255
+ }