@agentic-kit/db-tools 0.15.0 → 0.16.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 (74) hide show
  1. package/README.md +4 -4
  2. package/blueprint/blueprint-schema.js +3 -1
  3. package/context.d.ts +9 -9
  4. package/context.js +92 -54
  5. package/db-probe.js +2 -2
  6. package/esm/blueprint/blueprint-schema.js +3 -1
  7. package/esm/context.d.ts +9 -9
  8. package/esm/context.js +91 -54
  9. package/esm/db-probe.js +2 -2
  10. package/esm/failure.d.ts +1 -1
  11. package/esm/failure.js +2 -2
  12. package/esm/gate.js +1 -1
  13. package/esm/graphql-http.d.ts +3 -2
  14. package/esm/graphql-http.js +26 -7
  15. package/esm/host.d.ts +20 -7
  16. package/esm/host.js +7 -2
  17. package/esm/index.d.ts +175 -14
  18. package/esm/index.js +5 -15
  19. package/esm/project-file.d.ts +72 -0
  20. package/esm/project-file.js +161 -0
  21. package/esm/provision-database/provision.d.ts +8 -3
  22. package/esm/provision-database/provision.js +63 -94
  23. package/esm/ready.d.ts +7 -3
  24. package/esm/ready.js +3 -3
  25. package/esm/records/rows.d.ts +1 -0
  26. package/esm/records/rows.js +9 -6
  27. package/esm/tools/access.js +1 -1
  28. package/esm/tools/create-api-key.js +2 -2
  29. package/esm/tools/delete-records.d.ts +1 -1
  30. package/esm/tools/delete-records.js +7 -7
  31. package/esm/tools/index.d.ts +195 -2
  32. package/esm/tools/index.js +25 -15
  33. package/esm/tools/mutations.js +7 -6
  34. package/esm/tools/provision-database.js +4 -4
  35. package/esm/tools/run-codegen.d.ts +2 -2
  36. package/esm/tools/run-codegen.js +10 -11
  37. package/esm/tools/update-records.js +1 -1
  38. package/failure.d.ts +1 -1
  39. package/failure.js +2 -2
  40. package/gate.js +1 -1
  41. package/graphql-http.d.ts +3 -2
  42. package/graphql-http.js +26 -7
  43. package/host.d.ts +20 -7
  44. package/host.js +7 -2
  45. package/index.d.ts +175 -14
  46. package/index.js +9 -45
  47. package/package.json +19 -16
  48. package/project-file.d.ts +72 -0
  49. package/project-file.js +178 -0
  50. package/provision-database/provision.d.ts +8 -3
  51. package/provision-database/provision.js +66 -96
  52. package/ready.d.ts +7 -3
  53. package/ready.js +3 -3
  54. package/records/rows.d.ts +1 -0
  55. package/records/rows.js +8 -5
  56. package/tools/access.js +1 -1
  57. package/tools/create-api-key.js +2 -2
  58. package/tools/delete-records.d.ts +1 -1
  59. package/tools/delete-records.js +8 -8
  60. package/tools/index.d.ts +195 -2
  61. package/tools/index.js +53 -43
  62. package/tools/mutations.js +6 -5
  63. package/tools/provision-database.js +5 -5
  64. package/tools/run-codegen.d.ts +2 -2
  65. package/tools/run-codegen.js +8 -9
  66. package/tools/update-records.js +1 -1
  67. package/esm/provision-database/env-file.d.ts +0 -62
  68. package/esm/provision-database/env-file.js +0 -170
  69. package/esm/provision-database/pending-ticket.d.ts +0 -33
  70. package/esm/provision-database/pending-ticket.js +0 -63
  71. package/provision-database/env-file.d.ts +0 -62
  72. package/provision-database/env-file.js +0 -179
  73. package/provision-database/pending-ticket.d.ts +0 -33
  74. package/provision-database/pending-ticket.js +0 -72
@@ -7,19 +7,17 @@
7
7
  // - a recorded ticket that reads back empty, or a call that lost its ticket,
8
8
  // finds an in-flight provision of the same name before anything new is
9
9
  // requested, and a completed one is only reported (binding it is `adopt`);
10
- // - the host saves the binding before `.env` is written.
10
+ // - the host saves the binding before the project file is written.
11
11
  import { realpathSync } from 'node:fs';
12
- import { readFile, writeFile } from 'node:fs/promises';
13
12
  import path from 'node:path';
14
13
  import { prewarmAppWorkspace, run } from '../app-workspace';
15
14
  import { probeDatabase } from '../db-probe';
16
- import { failureText, invalidBinding, noBackendFailure, suggest } from '../failure';
15
+ import { failureText, noBackendFailure, suggest } from '../failure';
17
16
  import { answersSignedOut, thrownText } from '../graphql-http';
18
17
  import { getHost, readAccount, readBackendConfig, replaceCall, reprovisionAdvice } from '../host';
18
+ import { abandonedTickets, archivePendingTicket, bindProject, clearPendingTicket, PROJECT_FILE, readProjectFile, recordAbandoned, recordPendingTicket, updateProjectFile, } from '../project-file';
19
19
  import { selectProvisionCredential } from './credential';
20
- import { archiveBindingKeys, ARCHIVED_BINDING_KEYS, invalidBindingKeys, mergeEnv, provisionEnvVars, readEnv } from './env-file';
21
20
  import { loadProvisionManifest } from './manifest';
22
- import { abandonedTickets, archivePendingTicket, clearPendingTicket, MAX_PENDING_ATTEMPTS, recordAbandoned, recordedTicket, recordPendingTicket, } from './pending-ticket';
23
21
  import { selectProvisionRequest } from './preset-match';
24
22
  import { createProvisionExecutor, isTicketInFlight, isTransientProvisionError, ProvisionJobError, ProvisionPendingError, ProvisionSignedOutError, ProvisionTicketLostError, requestDatabaseProvision, } from './request-database';
25
23
  import { resolveProvisionModules } from './resolve';
@@ -39,38 +37,28 @@ function unanswered(probe, message, hint, extra = {}) {
39
37
  }
40
38
  const today = () => new Date().toISOString().slice(0, 10);
41
39
  const noop = () => undefined;
42
- async function readText(file) {
43
- try {
44
- return await readFile(file, 'utf8');
45
- }
46
- catch {
47
- return '';
48
- }
49
- }
50
- // Edit .env from its current content, read right before the write, so changes
51
- // made while this call waited on the backend (by another tool or the user)
52
- // aren't overwritten with what the file held when the call started.
53
- async function updateEnvFile(envPath, edit) {
54
- await writeFile(envPath, edit(await readText(envPath)));
55
- }
56
- /** A project's `.env`, with each binding value checked: one that is not of its form is never used, sent or shown. */
57
- async function readBinding(envPath) {
58
- const env = readEnv(await readText(envPath));
59
- const invalid = invalidBindingKeys(env);
60
- return invalid.length ? { kind: 'failed', failure: invalidBinding(invalid) } : { kind: 'ok', value: env };
40
+ /**
41
+ * Pending results recorded for one ticket before provision_database stops
42
+ * following it. At the default 240 s deadline that is about 20 minutes.
43
+ */
44
+ export const MAX_PENDING_ATTEMPTS = 5;
45
+ /** The binding of `cwd`, empty when it has none; a file with a value not of its form is a failure. */
46
+ async function readBinding(cwd) {
47
+ const file = await readProjectFile(cwd);
48
+ return file.kind === 'failed' ? file : { kind: 'ok', value: file.value ?? {} };
61
49
  }
62
- /** The DATABASE_ID in a project's `.env`, if it has one of the form a database id takes. */
50
+ /** The id of the database `cwd` is bound to, if its binding can be read. */
63
51
  export async function boundDatabaseId(cwd) {
64
52
  const binding = await boundDatabase(cwd);
65
53
  return binding.kind === 'ok' ? binding.value?.id : undefined;
66
54
  }
67
- /** The database the `.env` of `cwd` binds, as a plan names it. */
55
+ /** The database `cwd` is bound to, as a plan names it. */
68
56
  async function boundDatabase(cwd) {
69
- const binding = await readBinding(path.join(cwd, '.env'));
57
+ const binding = await readBinding(cwd);
70
58
  if (binding.kind === 'failed')
71
59
  return binding;
72
- const env = binding.value;
73
- return { kind: 'ok', value: env.DATABASE_ID ? { name: env.DATABASE_NAME ?? '', id: env.DATABASE_ID } : undefined };
60
+ const { database } = binding.value;
61
+ return { kind: 'ok', value: database ? { name: database.name ?? '', id: database.id } : undefined };
74
62
  }
75
63
  /**
76
64
  * The backend and the account a provision runs with, or why it cannot run.
@@ -89,7 +77,7 @@ async function provisionAccess(host) {
89
77
  const noBackend = noBackendFailure(host.signInHint);
90
78
  return { kind: 'failed', failure: { ...noBackend, message: `Cannot provision a database: ${noBackend.message}` } };
91
79
  }
92
- const accountRead = await readAccount(host);
80
+ const accountRead = await readAccount(host, backendRead.value);
93
81
  if (accountRead.kind === 'failed')
94
82
  return { kind: 'failed', failure: { ...accountRead.failure, code: 'signed-out' } };
95
83
  const credential = selectProvisionCredential(accountRead.value, host.signInHint);
@@ -210,16 +198,14 @@ async function provision(input, cwd, exec, viaTool) {
210
198
  return refuse(code, why);
211
199
  }
212
200
  const { apiEndpoint, modulesEndpoint, credential } = access.value;
213
- const envPath = path.join(cwd, '.env');
214
- const binding = await readBinding(envPath);
201
+ const binding = await readBinding(cwd);
215
202
  if (binding.kind === 'failed')
216
203
  return refuse('missing-credentials', binding.failure);
217
- const env = binding.value;
218
- const bound = env.DATABASE_ID || undefined;
204
+ const file = binding.value;
205
+ const bound = file.database?.id;
219
206
  const r = {
220
207
  host,
221
208
  cwd,
222
- envPath,
223
209
  name,
224
210
  mode: input.mode ?? 'ensure',
225
211
  apiEndpoint,
@@ -229,7 +215,7 @@ async function provision(input, cwd, exec, viaTool) {
229
215
  viaTool,
230
216
  executor: createProvisionExecutor({ apiEndpoint, modulesEndpoint, bearer: credential.bearer }),
231
217
  // The probe carries the account bearer, so it only ever targets the
232
- // app-configured backend, never a .env-pinned endpoint.
218
+ // app-configured backend.
233
219
  probe: (databaseId) => probeDatabase({ endpoint: apiEndpoint, bearer: credential.bearer, databaseId, signInHint: host.signInHint }),
234
220
  };
235
221
  let replaced;
@@ -240,30 +226,30 @@ async function provision(input, cwd, exec, viaTool) {
240
226
  replaced = bound;
241
227
  }
242
228
  else if (bound) {
243
- return keepBinding(r, env, bound, input.adopt);
229
+ return keepBinding(r, file, bound, input.adopt);
244
230
  }
245
231
  if (input.adopt) {
246
232
  const prewarm = startPrewarm(r, exec);
247
233
  return afterPrewarm(await bindDatabase(r, { databaseId: input.adopt, replaced, adopted: true }, prewarm), prewarm);
248
234
  }
249
- return requestAndBind(r, input, env, replaced, exec);
235
+ return requestAndBind(r, input, file, replaced, exec);
250
236
  }
251
237
  // ---- ensure: keep the binding --------------------------------------------
252
- async function keepBinding(r, env, bound, adopt) {
238
+ async function keepBinding(r, file, bound, adopt) {
253
239
  const probe = await r.probe(bound);
254
240
  if (probe.status === 'unreachable') {
255
- return unanswered(probe, `Cannot verify the existing database binding (DATABASE_ID=${bound}): ${probe.detail}.`, "Retry once the backend answers; don't reprovision on an unreachable backend.", { databaseId: bound });
241
+ return unanswered(probe, `Cannot verify the database this project is bound to (ID ${bound}): ${probe.detail}.`, "Retry once the backend answers; don't reprovision on an unreachable backend.", { databaseId: bound });
256
242
  }
257
243
  if (probe.status === 'missing') {
258
244
  return refuse('db-missing', {
259
- message: `Project carries a binding (DATABASE_ID=${bound}) but that database no longer exists on this backend, or this account lost access to it.`,
245
+ message: `This project is bound to a database (ID ${bound}) that no longer exists on this backend, or that this account lost access to.`,
260
246
  hint: reprovisionAdvice(r.host),
261
247
  ...replaceCall(r.host),
262
248
  }, { databaseId: bound });
263
249
  }
264
250
  if (probe.ownerId && probe.ownerId !== r.ownerId) {
265
251
  return refuse('account-mismatch', {
266
- message: `Project carries a binding (DATABASE_ID=${bound}) but that database was provisioned under a different account than the one signed in.`,
252
+ message: `This project is bound to a database (ID ${bound}) that was provisioned under a different account than the one signed in.`,
267
253
  hint: reprovisionAdvice(r.host),
268
254
  ...replaceCall(r.host),
269
255
  }, { databaseId: bound });
@@ -273,24 +259,14 @@ async function keepBinding(r, env, bound, adopt) {
273
259
  }
274
260
  if (adopt && adopt !== bound) {
275
261
  return refuse('binding-live', {
276
- message: `The project is bound to a live database (DATABASE_ID=${bound}); adopt binds only an unbound project.`,
262
+ message: `This project is bound to a live database already (ID ${bound}), so it cannot be bound to another one.`,
277
263
  hint: 'Use replace mode to swap it.',
278
264
  }, { databaseId: bound });
279
265
  }
280
- // Heal stale endpoint pins and missing binding keys on the skip path.
281
- const databaseName = env.DATABASE_NAME || probe.name || '';
266
+ // The database answered on this backend under this account, so the binding names this backend and that database.
267
+ const databaseName = probe.name || file.database?.name || '';
282
268
  const ownerId = probe.ownerId ?? r.ownerId;
283
- const refresh = {};
284
- if (env.API_ENDPOINT !== r.apiEndpoint)
285
- refresh.API_ENDPOINT = r.apiEndpoint;
286
- if (env.MODULES_ENDPOINT !== r.modulesEndpoint)
287
- refresh.MODULES_ENDPOINT = r.modulesEndpoint;
288
- if (!env.DATABASE_NAME && databaseName)
289
- refresh.DATABASE_NAME = databaseName;
290
- if (!env.PGDATABASE && databaseName)
291
- refresh.PGDATABASE = databaseName;
292
- if (!env.OWNER_ID)
293
- refresh.OWNER_ID = ownerId;
269
+ const stale = file.backend !== r.apiEndpoint || file.database?.name !== databaseName || file.database?.ownerId !== ownerId;
294
270
  const saved = await saveBinding(r, {
295
271
  cwd: r.cwd,
296
272
  databaseId: bound,
@@ -303,20 +279,19 @@ async function keepBinding(r, env, bound, adopt) {
303
279
  if (saved)
304
280
  return saved;
305
281
  let note = '';
306
- if (Object.keys(refresh).length > 0) {
307
- const keys = Object.keys(refresh).join(', ');
282
+ if (stale && databaseName) {
308
283
  try {
309
- await updateEnvFile(r.envPath, (content) => mergeEnv(content, refresh));
310
- note = ` Refreshed in .env: ${keys}.`;
284
+ await updateProjectFile(r.cwd, (current) => ({ ...current, backend: r.apiEndpoint, database: { id: bound, name: databaseName, ownerId } }));
285
+ note = ` Refreshed the binding in ${PROJECT_FILE}.`;
311
286
  }
312
287
  catch (err) {
313
- note = ` Could not refresh ${keys} in .env: ${thrownText(err)}.`;
288
+ note = ` Could not refresh the binding in ${PROJECT_FILE}: ${thrownText(err)}.`;
314
289
  }
315
290
  }
316
291
  const advice = r.host.toolReprovision === false ? '' : ' Replacing it with a new database is a separate change, only for an explicit clean rebuild.';
317
292
  return {
318
293
  success: true,
319
- message: `Project already provisioned (DATABASE_ID=${bound}) and the database is live under this account. Skipping.${advice}${note}`,
294
+ message: `This project is bound already to a live database of this account (ID ${bound}), so nothing was created.${advice}${note}`,
320
295
  databaseId: bound,
321
296
  databaseName,
322
297
  ownerId,
@@ -325,7 +300,7 @@ async function keepBinding(r, env, bound, adopt) {
325
300
  }
326
301
  function suspendedText(databaseId, probe) {
327
302
  const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
328
- return `The bound database (DATABASE_ID=${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, so it isn't replaced; nothing can read or change it until the suspension is lifted.`;
303
+ return `The database this project is bound to (ID ${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, so it isn't replaced; nothing can read or change it until the suspension is lifted.`;
329
304
  }
330
305
  // ---- replace: compare and swap -------------------------------------------
331
306
  async function checkReplace(r, input, bound) {
@@ -338,14 +313,14 @@ async function checkReplace(r, input, bound) {
338
313
  const expected = input.replaces === undefined ? bound : input.replaces || undefined;
339
314
  if ((expected ?? '') !== (bound ?? '')) {
340
315
  return refuse('binding-changed', {
341
- message: `The project's binding changed (DATABASE_ID is ${bound ?? 'unset'}, expected ${expected ?? 'unset'}), so nothing was replaced.`,
316
+ message: `This project's binding changed (it names ${bound ? `database ${bound}` : 'no database'}, and the plan expected ${expected ? `database ${expected}` : 'none'}), so nothing was replaced.`,
342
317
  }, { databaseId: bound });
343
318
  }
344
319
  if (!bound)
345
320
  return null;
346
321
  const probe = await r.probe(bound);
347
322
  if (probe.status === 'unreachable') {
348
- return unanswered(probe, `Cannot verify the binding being replaced (DATABASE_ID=${bound}): ${probe.detail}.`, 'Retry once the backend answers.', { databaseId: bound });
323
+ return unanswered(probe, `Cannot verify the database being replaced (ID ${bound}): ${probe.detail}.`, 'Retry once the backend answers.', { databaseId: bound });
349
324
  }
350
325
  if (probe.status === 'suspended') {
351
326
  return refuse('db-suspended', { message: suspendedText(bound, probe) }, { databaseId: bound });
@@ -353,7 +328,7 @@ async function checkReplace(r, input, bound) {
353
328
  // A missing or foreign-owned binding is replaced; a live one of this account
354
329
  // only through the tool's explicit rebuild.
355
330
  if (probe.status === 'found' && (!probe.ownerId || probe.ownerId === r.ownerId) && !r.viaTool) {
356
- return refuse('binding-live', { message: `The bound database (DATABASE_ID=${bound}) is live under this account, so it wasn't replaced.` }, { databaseId: bound });
331
+ return refuse('binding-live', { message: `The database this project is bound to (ID ${bound}) is live under this account, so it wasn't replaced.` }, { databaseId: bound });
357
332
  }
358
333
  return null;
359
334
  }
@@ -415,21 +390,21 @@ async function afterPrewarm(outcome, prewarm) {
415
390
  };
416
391
  return { ...outcome, failure, message: failureText(failure), appWorkspacePrepared: true };
417
392
  }
418
- async function requestAndBind(r, input, env, replaced, exec) {
419
- const abandoned = abandonedTickets(env);
393
+ async function requestAndBind(r, input, file, replaced, exec) {
394
+ const abandoned = abandonedTickets(file);
420
395
  const abandon = async (ids) => {
421
396
  for (const id of ids)
422
397
  abandoned.add(id);
423
- await updateEnvFile(r.envPath, (content) => recordAbandoned(clearPendingTicket(content), ids)).catch(noop);
398
+ await updateProjectFile(r.cwd, (current) => recordAbandoned(clearPendingTicket(current), ids)).catch(noop);
424
399
  };
425
400
  // A ticket an earlier call stopped waiting on.
426
401
  let current;
427
402
  let recovered = false;
428
- const recorded = recordedTicket(env);
403
+ const recorded = file.pending;
429
404
  if (recorded) {
430
405
  if (recorded.apiEndpoint !== r.apiEndpoint || recorded.userId !== r.ownerId) {
431
406
  // Requested on another backend or by another account: not ours to follow.
432
- await updateEnvFile(r.envPath, (content) => archivePendingTicket(content, today())).catch(noop);
407
+ await updateProjectFile(r.cwd, (current) => archivePendingTicket(current, today())).catch(noop);
433
408
  }
434
409
  else if (input.abandonPending) {
435
410
  await abandon([recorded.ticketId]);
@@ -531,7 +506,7 @@ async function sendRequest(r, request, prewarm) {
531
506
  recovered = true;
532
507
  continue;
533
508
  }
534
- await updateEnvFile(r.envPath, clearPendingTicket).catch(noop);
509
+ await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
535
510
  const checked = lookup.problem
536
511
  ? `the backend couldn't be asked for another one (${lookup.problem})`
537
512
  : 'no other provision of that name is in progress';
@@ -543,7 +518,7 @@ async function sendRequest(r, request, prewarm) {
543
518
  }
544
519
  // A definitive failure ends the recorded request, so forget it.
545
520
  if (current)
546
- await updateEnvFile(r.envPath, clearPendingTicket).catch(noop);
521
+ await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
547
522
  return requestFailure(r, err);
548
523
  }
549
524
  }
@@ -563,7 +538,7 @@ async function pendingResult(r, ticket, reason, recovered) {
563
538
  const { ticketId } = ticket;
564
539
  let recordedOk = true;
565
540
  try {
566
- await updateEnvFile(r.envPath, (content) => recordPendingTicket(content, ticket));
541
+ await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket));
567
542
  }
568
543
  catch {
569
544
  recordedOk = false;
@@ -576,8 +551,8 @@ async function pendingResult(r, ticket, reason, recovered) {
576
551
  }
577
552
  const waiting = `call again with the same name, "${r.name}", to keep waiting on it`;
578
553
  const message = recordedOk
579
- ? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in .env; ${waiting}. Don't change the name: that starts a second database.`
580
- : `Database "${r.name}" is still provisioning (${reason}). Recording its ticket in .env failed, but the backend still has it: ${waiting}. Don't change the name: that starts a second database.`;
554
+ ? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in ${PROJECT_FILE}; ${waiting}. Don't change the name: that starts a second database.`
555
+ : `Database "${r.name}" is still provisioning (${reason}). Recording its ticket in ${PROJECT_FILE} failed, but the backend still has it: ${waiting}. Don't change the name: that starts a second database.`;
581
556
  return {
582
557
  success: false,
583
558
  message,
@@ -618,10 +593,10 @@ const anotherName = (r) => suggest(againTool(r), {}, 'Request the database under
618
593
  // The backend refused a read of the provision because the sign-in ended. The provision may still be running, so its
619
594
  // ticket stays recorded, and the next call after a sign-in waits on it instead of requesting another database.
620
595
  async function signedOutWaiting(r, ticket, reason) {
621
- const recorded = await updateEnvFile(r.envPath, (content) => recordPendingTicket(content, ticket)).then(() => true, () => false);
596
+ const recorded = await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket)).then(() => true, () => false);
622
597
  return refuse('signed-out', {
623
598
  message: `The backend did not accept the account credential while it read the provision of "${r.name}" (ticket ${ticket.ticketId}): ${reason}. ` +
624
- `The database may still be on its way${recorded ? ', and the request stays recorded in .env' : ''}.`,
599
+ `The database may still be on its way${recorded ? `, and the request stays recorded in ${PROJECT_FILE}` : ''}.`,
625
600
  hint: `${r.host.signInHint ?? 'Sign in again'}, then call again with the same name to keep waiting on it. Don't change the name: that starts a second database.`,
626
601
  calls: [again(r, 'Keep waiting on the recorded request once signed in')],
627
602
  }, { ticketId: ticket.ticketId });
@@ -704,9 +679,9 @@ async function saveBinding(r, binding, ticket) {
704
679
  catch (err) {
705
680
  // Keep the ticket recorded, so the next call resumes it and binds it.
706
681
  if (ticket)
707
- await updateEnvFile(r.envPath, (content) => recordPendingTicket(content, ticket)).catch(noop);
682
+ await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket)).catch(noop);
708
683
  return refuse('binding-not-saved', {
709
- message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${thrownText(err)}), so .env was left unchanged.`,
684
+ message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${thrownText(err)}), so ${PROJECT_FILE} was left unchanged.`,
710
685
  ...(ticket
711
686
  ? {
712
687
  hint: 'Calling again with the same name binds it.',
@@ -730,7 +705,7 @@ async function bindDatabase(r, bind, prewarm) {
730
705
  const visible = owner.status !== 'missing';
731
706
  if (!visible || owner.ownerId !== r.ownerId) {
732
707
  if (ticket)
733
- await updateEnvFile(r.envPath, clearPendingTicket).catch(noop);
708
+ await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
734
709
  const why = visible ? "it isn't owned by" : "it isn't visible to";
735
710
  if (bind.adopted) {
736
711
  return refuse(visible ? 'account-mismatch' : 'db-missing', {
@@ -757,19 +732,13 @@ async function bindDatabase(r, bind, prewarm) {
757
732
  }, ticket);
758
733
  if (saved)
759
734
  return saved;
760
- // Write the binding into .env (upsert, preserving other keys), dropping any
761
- // recorded pending request: the project is bound now.
735
+ // Write the binding, dropping any recorded pending request: the project is bound now. A binding it replaces stays
736
+ // readable in the archive.
762
737
  try {
763
- await updateEnvFile(r.envPath, (content) => mergeEnv(clearPendingTicket(bind.replaced ? archiveBindingKeys(content, ARCHIVED_BINDING_KEYS, today()) : content), provisionEnvVars({
764
- databaseId,
765
- databaseName: r.name,
766
- ownerId: r.ownerId,
767
- apiEndpoint: r.apiEndpoint,
768
- modulesEndpoint: r.modulesEndpoint,
769
- })));
738
+ await updateProjectFile(r.cwd, (current) => bindProject(current, { database: { id: databaseId, name: r.name, ownerId: r.ownerId }, backend: r.apiEndpoint, archivedOn: today() }));
770
739
  }
771
740
  catch (err) {
772
- return refuse('env-write-failed', { message: `Database provisioned (ID: ${databaseId}) but writing .env failed: ${thrownText(err)}` }, { databaseId });
741
+ return refuse('binding-write-failed', { message: `Database provisioned (ID: ${databaseId}) but writing ${PROJECT_FILE} failed: ${thrownText(err)}` }, { databaseId });
773
742
  }
774
743
  // Settle the concurrent prewarm so the scaffold + install are in place before
775
744
  // run_codegen runs. A failure here is non-fatal: run_codegen redoes the work.
@@ -778,12 +747,12 @@ async function bindDatabase(r, bind, prewarm) {
778
747
  bind.resumed ? ' Finished an earlier request.' : '',
779
748
  bind.recovered ? ' Found it on the backend by name.' : '',
780
749
  prewarmed,
781
- bind.replaced ? ' The old binding is archived in .env, and the old database keeps its data. Build the schema again here.' : '',
750
+ bind.replaced ? ` The old binding is archived in ${PROJECT_FILE}, and the old database keeps its data. Build the schema again here.` : '',
782
751
  ].join('');
783
752
  const named = `${r.name} (${databaseId.slice(0, 8)})`;
784
753
  const message = bind.adopted
785
- ? `Bound this directory to ${named}. Wrote .env.${notes}`
786
- : `Created ${named} and bound this directory to it. Wrote .env.${notes}`;
754
+ ? `Bound this directory to ${named}. Wrote ${PROJECT_FILE}.${notes}`
755
+ : `Created ${named} and bound this directory to it. Wrote ${PROJECT_FILE}.${notes}`;
787
756
  return {
788
757
  success: true,
789
758
  message,
package/esm/ready.d.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import type { PlanTarget } from '@agentic-kit/harness';
2
2
  import { type ProjectContext } from './context';
3
3
  import { type Result } from './failure';
4
+ /** The app user a change of rows is made as. */
5
+ export type AppUser = {
6
+ userId?: string;
7
+ email?: string;
8
+ };
4
9
  /** 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, {
10
+ export declare function databaseTarget(context: ProjectContext, appUser?: AppUser): Extract<PlanTarget, {
6
11
  kind: 'database';
7
12
  }>;
8
13
  /** A change to what the account owns beside its databases (its templates), at the context's backend. */
@@ -14,7 +19,6 @@ export declare function ownedProjectReady(cwd: string): Promise<Result<ProjectCo
14
19
  ownerId: string;
15
20
  }>>;
16
21
  /** A data-plane token of the person signed in to the app. */
17
- export declare function appSessionReady(context: ProjectContext): Promise<Result<{
22
+ export declare function appSessionReady(context: ProjectContext): Promise<Result<AppUser & {
18
23
  token: string;
19
- userId?: string;
20
24
  }>>;
package/esm/ready.js CHANGED
@@ -10,13 +10,13 @@ const accountOf = (context) => ({
10
10
  ...(context.accountAgent ? { agent: context.accountAgent } : {}),
11
11
  });
12
12
  /** The bound database a change goes to, at the backend and as the account the context resolved. */
13
- export function databaseTarget(context, appUserId) {
13
+ export function databaseTarget(context, appUser = {}) {
14
14
  return {
15
15
  kind: 'database',
16
16
  database: { name: context.databaseName, id: context.databaseId },
17
17
  apiEndpoint: context.controlApiEndpoint,
18
18
  account: accountOf(context),
19
- ...(appUserId ? { appUserId } : {}),
19
+ ...(appUser.userId ? { appUserId: appUser.userId, ...(appUser.email ? { appUserEmail: appUser.email } : {}) } : {}),
20
20
  };
21
21
  }
22
22
  /** A change to what the account owns beside its databases (its templates), at the context's backend. */
@@ -40,6 +40,6 @@ export async function ownedProjectReady(cwd) {
40
40
  export async function appSessionReady(context) {
41
41
  const token = await resolveDataToken(context);
42
42
  return token.token
43
- ? { kind: 'ok', value: { token: token.token, userId: token.userId } }
43
+ ? { kind: 'ok', value: { token: token.token, userId: token.userId, email: token.email } }
44
44
  : { kind: 'failed', failure: token.failure };
45
45
  }
@@ -36,6 +36,7 @@ export type AppReady = {
36
36
  context: ProjectContext;
37
37
  token: string;
38
38
  userId?: string;
39
+ email?: string;
39
40
  /** The app's own API, as the person signed in to the app. */
40
41
  adapter: ReturnType<typeof statusAdapter>;
41
42
  tables: RawMetaTable[];
@@ -1,7 +1,7 @@
1
1
  // What the record tools share: the app tables, read from the app API's `_meta` as the person signed in to the app;
2
2
  // each record's keys as the API's field names, with "@<table>[<index>]" as the id of a sample row the host seeded;
3
3
  // and one write per row, with what each row's answer was.
4
- import { listed, nearestName } from '@agentic-kit/harness';
4
+ import { listed, nearestName, plural } from '@agentic-kit/harness';
5
5
  import { toCamelCaseSingular } from '@constructive-io/graphql-query/generators';
6
6
  import { DESCRIBE_SCHEMA, explainAccessCall, failedResult, failureFromError, failureFromErrors, failureText, NO_NEW_ROW, noRowCreated, noRowsChanged, } from '../failure';
7
7
  import { answerText, classifyBackendErrors, statusAdapter, thrownText } from '../graphql-http';
@@ -48,8 +48,8 @@ export async function appReady(cwd, done) {
48
48
  kind: 'failed',
49
49
  failure: {
50
50
  code: 'missing-credentials',
51
- message: 'Cannot resolve the app data endpoint (DATABASE_NAME missing from .env).',
52
- hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
51
+ message: 'Cannot resolve the app data endpoint (the project binding names no database).',
52
+ hint: 'Bind this directory to its database again (the person approves it), then retry.',
53
53
  },
54
54
  };
55
55
  }
@@ -225,7 +225,7 @@ export async function writeRecords(verb, tableName, { adapter, table: rawTable }
225
225
  };
226
226
  const failed = (failure) => recordsFailed(failure, { ...(rows.length > 0 ? details : {}), ...(failedRows.length > 0 ? { failedRows } : {}) });
227
227
  if (suspended) {
228
- const message = rows.length > 0 ? `${UNAVAILABLE} ${rows.length} row(s) were ${done} before it stopped.` : `${UNAVAILABLE} No rows were ${done}.`;
228
+ const message = rows.length > 0 ? `${UNAVAILABLE} ${plural(rows.length, 'row')} ${rows.length === 1 ? 'was' : 'were'} ${done} before it stopped.` : `${UNAVAILABLE} No rows were ${done}.`;
229
229
  return failed({ code: 'database-unavailable', message });
230
230
  }
231
231
  if (rows.length === 0) {
@@ -240,11 +240,14 @@ export async function writeRecords(verb, tableName, { adapter, table: rawTable }
240
240
  hint: `Fix the rows listed in details.failedRows, then call again with only those rows: the ${done} rows stay.`,
241
241
  });
242
242
  }
243
- const message = `${words.done} ${rows.length} row(s) ${words.into} ${tableName}.${verb === 'insert' ? keysLine(rows, primaryKeyOf(rawTable)?.name) : ''}`;
243
+ const message = `${words.done} ${plural(rows.length, 'row')} ${words.into} ${tableName}.${verb === 'insert' ? keysLine(rows, primaryKeyOf(rawTable)?.name) : ''}`;
244
244
  return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
245
245
  }
246
246
  /** The line that gives the new rows' keys, so a later call can point another row at one. */
247
247
  function keysLine(rows, key) {
248
248
  const keys = key ? rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null) : [];
249
- return keys.length ? `\nThe new rows' ${key} values, in insert order: ${keys.map((value) => JSON.stringify(value)).join(', ')}.` : '';
249
+ const values = keys.map((value) => JSON.stringify(value)).join(', ');
250
+ if (keys.length === 0)
251
+ return '';
252
+ return keys.length === 1 ? `\nThe new row's ${key} value: ${values}.` : `\nThe new rows' ${key} values, in insert order: ${values}.`;
250
253
  }
@@ -620,7 +620,7 @@ export const setAccessTool = {
620
620
  description: 'Replace every access rule of a table with a list of rules, in one change; the grants stay, and the columns the rules need are added. The plan marks each rule as kept, added or removed.',
621
621
  promptSnippet: 'set_access: replace the access rules of a table with a list of rules. Gated.',
622
622
  parameters: SetAccessZod,
623
- effect: 'write',
623
+ effect: 'destructive',
624
624
  async execute(params, ctx) {
625
625
  const ready = await setAccessReady(params, ctx.cwd);
626
626
  if (ready.kind === 'failed')
@@ -89,8 +89,8 @@ export async function createApiKeyReady(params, cwd) {
89
89
  kind: 'failed',
90
90
  failure: {
91
91
  code: 'missing-credentials',
92
- message: 'Cannot resolve the app auth endpoint (DATABASE_NAME missing from .env).',
93
- hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
92
+ message: 'Cannot resolve the app auth endpoint (the project binding names no database).',
93
+ hint: 'Bind this directory to its database again (the person approves it), then retry.',
94
94
  },
95
95
  };
96
96
  }
@@ -28,6 +28,6 @@ export type DeleteRecordsDetails = {
28
28
  code?: 'database-unavailable';
29
29
  };
30
30
  /** The plan of a records delete: the exact rows as the target, and the card's preview. */
31
- export declare function deleteRecordsPlan({ context, userId, selection, notes }: DeleteRecordsReady): Resolved;
31
+ export declare function deleteRecordsPlan(ready: DeleteRecordsReady): Resolved;
32
32
  export declare const deleteRecordsTool: HarnessTool<typeof DeleteRecordsZod, DeleteRecordsDetails>;
33
33
  export {};
@@ -1,4 +1,4 @@
1
- import { identifierParam, listed, strictObject, takeApprovedTable } from '@agentic-kit/harness';
1
+ import { identifierParam, listed, plural, strictObject } from '@agentic-kit/harness';
2
2
  import { buildPostGraphileDelete, toDeleteMutationName } from '@constructive-io/graphql-query/generators';
3
3
  import { z } from 'zod';
4
4
  import { DESCRIBE_SCHEMA, failureFromErrors, noRowsChanged } from '../failure';
@@ -30,9 +30,10 @@ const DeleteRecordsZod = strictObject('the input', {
30
30
  .describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'),
31
31
  });
32
32
  /** The plan of a records delete: the exact rows as the target, and the card's preview. */
33
- export function deleteRecordsPlan({ context, userId, selection, notes }) {
33
+ export function deleteRecordsPlan(ready) {
34
+ const { context, selection, notes } = ready;
34
35
  return {
35
- target: { ...databaseTarget(context, userId), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
36
+ target: { ...databaseTarget(context, ready), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
36
37
  preview: { kind: 'delete-records', ...selection },
37
38
  ...(notes.length ? { notes } : {}),
38
39
  };
@@ -59,7 +60,6 @@ function plannedRows(tables, rows) {
59
60
  }
60
61
  return { kind: 'ok', value: planned };
61
62
  }
62
- const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
63
63
  const NO_ROW_DELETED = 'The backend answered without the deleted row, so it does not exist, or this account may not delete it.';
64
64
  /** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */
65
65
  async function deleteRows({ adapter, tables }, planned, kept) {
@@ -154,9 +154,9 @@ export const deleteRecordsTool = {
154
154
  description: "Delete rows from one or more tables in the project's app database: rows named by primary key, the rows whose columns have given values, the sample rows seeded when the app was built, or every row. One call for every table: the person sees the exact rows first and can keep any table.",
155
155
  promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.',
156
156
  parameters: DeleteRecordsZod,
157
- effect: 'write',
157
+ effect: 'destructive',
158
158
  async execute(params, ctx) {
159
- const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined;
159
+ const approved = ctx.approved?.kind === 'database' ? ctx.approved : undefined;
160
160
  const fail = (failure) => recordsFailed(failure, { deletedCount: 0, tables: [] });
161
161
  if (!approved?.rows) {
162
162
  // The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes
@@ -172,7 +172,7 @@ export const deleteRecordsTool = {
172
172
  const ready = await appReady(ctx.cwd, 'deleted');
173
173
  if (ready.kind === 'failed')
174
174
  return fail(ready.failure);
175
- if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value.userId))) {
175
+ if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value))) {
176
176
  return fail({
177
177
  code: 'failed',
178
178
  message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.',