@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
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ // A project's binding: which database a directory works on, kept in <dir>/.constructive/project.json. Only the tools
3
+ // write it. It names no endpoint and holds no secret, so the file of a cloned project can't send a token anywhere.
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.recordAbandoned = exports.abandonedTickets = exports.archivePendingTicket = exports.clearPendingTicket = exports.recordPendingTicket = exports.isEndpoint = exports.isUuid = exports.isDatabaseName = exports.DATABASE_NAME_PATTERN = exports.PROJECT_FILE = void 0;
9
+ exports.readProjectFile = readProjectFile;
10
+ exports.updateProjectFile = updateProjectFile;
11
+ exports.bindProject = bindProject;
12
+ const node_crypto_1 = require("node:crypto");
13
+ const promises_1 = require("node:fs/promises");
14
+ const node_path_1 = __importDefault(require("node:path"));
15
+ /** The binding's file, relative to the project directory. */
16
+ exports.PROJECT_FILE = node_path_1.default.join('.constructive', 'project.json');
17
+ /** The binding is the person's own, for their account and backend, so git leaves it out (other .constructive files stay). */
18
+ const GITIGNORE = node_path_1.default.join('.constructive', '.gitignore');
19
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20
+ /** The backend's own check on a database name, which is 3 to 63 characters long. */
21
+ exports.DATABASE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
22
+ const isDatabaseName = (value) => typeof value === 'string' && value.length >= 3 && value.length <= 63 && exports.DATABASE_NAME_PATTERN.test(value);
23
+ exports.isDatabaseName = isDatabaseName;
24
+ const isUuid = (value) => typeof value === 'string' && UUID.test(value);
25
+ exports.isUuid = isUuid;
26
+ const isEndpoint = (value) => {
27
+ if (typeof value !== 'string')
28
+ return false;
29
+ try {
30
+ return ['http:', 'https:'].includes(new URL(value).protocol);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
36
+ exports.isEndpoint = isEndpoint;
37
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ /** The keys of a parsed file whose value is not of its form; such a file is never used, and its values never shown. */
39
+ function invalidKeys(file) {
40
+ const invalid = [];
41
+ const check = (key, ok) => {
42
+ if (!ok)
43
+ invalid.push(key);
44
+ };
45
+ if (file.backend !== undefined)
46
+ check('backend', (0, exports.isEndpoint)(file.backend));
47
+ if (file.database !== undefined) {
48
+ const database = file.database;
49
+ check('database', isObject(database));
50
+ if (isObject(database)) {
51
+ check('database.id', (0, exports.isUuid)(database.id));
52
+ if (database.name !== undefined)
53
+ check('database.name', (0, exports.isDatabaseName)(database.name));
54
+ if (database.ownerId !== undefined)
55
+ check('database.ownerId', (0, exports.isUuid)(database.ownerId));
56
+ }
57
+ }
58
+ if (file.agent !== undefined)
59
+ check('agent', typeof file.agent === 'string');
60
+ if (file.pending !== undefined) {
61
+ const pending = file.pending;
62
+ check('pending', isObject(pending));
63
+ if (isObject(pending)) {
64
+ check('pending.ticketId', (0, exports.isUuid)(pending.ticketId));
65
+ check('pending.databaseName', (0, exports.isDatabaseName)(pending.databaseName));
66
+ check('pending.apiEndpoint', (0, exports.isEndpoint)(pending.apiEndpoint));
67
+ check('pending.userId', (0, exports.isUuid)(pending.userId));
68
+ check('pending.attempts', Number.isInteger(pending.attempts) && pending.attempts >= 0);
69
+ }
70
+ }
71
+ if (file.abandoned !== undefined)
72
+ check('abandoned', Array.isArray(file.abandoned) && file.abandoned.every(exports.isUuid));
73
+ if (file.archived !== undefined)
74
+ check('archived', Array.isArray(file.archived) && file.archived.every(isObject));
75
+ return invalid;
76
+ }
77
+ /**
78
+ * The binding of `cwd`: null when the directory has none, a failure when the file is not JSON or a value is not of its
79
+ * form. A cloned project's file is not the person's text, so a value that fails its check is never used, sent or shown.
80
+ */
81
+ async function readProjectFile(cwd) {
82
+ let text;
83
+ try {
84
+ text = await (0, promises_1.readFile)(node_path_1.default.join(cwd, exports.PROJECT_FILE), 'utf8');
85
+ }
86
+ catch (err) {
87
+ if (err.code === 'ENOENT')
88
+ return { kind: 'ok', value: null };
89
+ return { kind: 'failed', failure: { code: 'missing-credentials', message: `${exports.PROJECT_FILE} could not be read (${err.message}).` } };
90
+ }
91
+ let parsed;
92
+ try {
93
+ parsed = JSON.parse(text);
94
+ }
95
+ catch {
96
+ parsed = undefined;
97
+ }
98
+ if (!isObject(parsed)) {
99
+ return {
100
+ kind: 'failed',
101
+ failure: {
102
+ code: 'missing-credentials',
103
+ message: `${exports.PROJECT_FILE} is not a JSON object, so this directory's binding can't be read.`,
104
+ hint: 'Remove the file and bind the directory again (the person approves it).',
105
+ },
106
+ };
107
+ }
108
+ const invalid = invalidKeys(parsed);
109
+ if (invalid.length) {
110
+ return {
111
+ kind: 'failed',
112
+ failure: {
113
+ code: 'missing-credentials',
114
+ message: `${exports.PROJECT_FILE} has values that are not of their form (${invalid.join(', ')}), so none of it is used.`,
115
+ hint: 'Remove the file and bind the directory again (the person approves it).',
116
+ },
117
+ };
118
+ }
119
+ return { kind: 'ok', value: parsed };
120
+ }
121
+ /**
122
+ * Change the binding of `cwd` from its current content, read right before the write, so a change another tool or the
123
+ * person made while this call waited on the backend is kept. The write replaces the file in one step. The first write
124
+ * also tells git to leave the file out. A file that can't be read is left as it is, and the edit throws, as it does
125
+ * when .constructive links outside the project.
126
+ */
127
+ async function updateProjectFile(cwd, edit) {
128
+ const current = await readProjectFile(cwd);
129
+ if (current.kind === 'failed')
130
+ throw new Error(current.failure.message);
131
+ const file = node_path_1.default.join(cwd, exports.PROJECT_FILE);
132
+ await (0, promises_1.mkdir)(node_path_1.default.dirname(file), { recursive: true });
133
+ const inside = node_path_1.default.relative(await (0, promises_1.realpath)(cwd), await (0, promises_1.realpath)(node_path_1.default.dirname(file)));
134
+ if (inside.startsWith('..') || node_path_1.default.isAbsolute(inside))
135
+ throw new Error(`${exports.PROJECT_FILE} was not written: .constructive links outside the project.`);
136
+ if (current.value === null)
137
+ await (0, promises_1.writeFile)(node_path_1.default.join(cwd, GITIGNORE), 'project.json\n', { flag: 'wx' }).catch(() => undefined);
138
+ const temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomBytes)(4).toString('hex')}.tmp`;
139
+ try {
140
+ await (0, promises_1.writeFile)(temporary, `${JSON.stringify(edit(current.value ?? {}), null, 2)}\n`, { flag: 'wx' });
141
+ await (0, promises_1.rename)(temporary, file);
142
+ }
143
+ catch (err) {
144
+ await (0, promises_1.rm)(temporary, { force: true });
145
+ throw err;
146
+ }
147
+ }
148
+ /** The newest abandoned ids kept; older ones are long finished or failed. */
149
+ const MAX_ABANDONED = 10;
150
+ const without = (file, key) => {
151
+ const rest = { ...file };
152
+ delete rest[key];
153
+ return rest;
154
+ };
155
+ const recordPendingTicket = (file, ticket) => ({ ...file, pending: ticket });
156
+ exports.recordPendingTicket = recordPendingTicket;
157
+ const clearPendingTicket = (file) => without(file, 'pending');
158
+ exports.clearPendingTicket = clearPendingTicket;
159
+ /** Keep the recorded request readable in the archive, and record no request. */
160
+ const archivePendingTicket = (file, archivedOn) => file.pending ? { ...without(file, 'pending'), archived: [...(file.archived ?? []), { archivedOn, pending: file.pending }] } : file;
161
+ exports.archivePendingTicket = archivePendingTicket;
162
+ const abandonedTickets = (file) => new Set(file.abandoned ?? []);
163
+ exports.abandonedTickets = abandonedTickets;
164
+ /** Add ticket ids to the abandoned list. */
165
+ const recordAbandoned = (file, ticketIds) => ({
166
+ ...file,
167
+ abandoned: [...new Set([...(file.abandoned ?? []), ...ticketIds])].slice(-MAX_ABANDONED),
168
+ });
169
+ exports.recordAbandoned = recordAbandoned;
170
+ /**
171
+ * Bind the directory to `database` on `backend`, with no recorded request. A binding it replaces is kept readable in
172
+ * the archive.
173
+ */
174
+ function bindProject(file, binding) {
175
+ const replaced = file.database && file.database.id !== binding.database.id;
176
+ const archived = replaced ? [...(file.archived ?? []), { archivedOn: binding.archivedOn, backend: file.backend, database: file.database }] : file.archived;
177
+ return { ...without(file, 'pending'), backend: binding.backend, database: binding.database, ...(archived ? { archived } : {}) };
178
+ }
@@ -18,7 +18,7 @@ export type ProvisionInput = {
18
18
  */
19
19
  adopt?: string;
20
20
  };
21
- export type ProvisionFailureCode = 'signed-out' | 'backend-unreachable' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'binding-live' | 'binding-changed' | 'pending-other' | 'ticket-lost' | 'provision-stuck' | 'name-taken' | 'binding-not-saved' | 'env-write-failed' | 'reprovision-not-allowed' | 'no-backend' | 'invalid-input' | 'missing-credentials' | 'plan-required' | 'limit-reached' | 'failed';
21
+ export type ProvisionFailureCode = 'signed-out' | 'backend-unreachable' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'binding-live' | 'binding-changed' | 'pending-other' | 'ticket-lost' | 'provision-stuck' | 'name-taken' | 'binding-not-saved' | 'binding-write-failed' | 'reprovision-not-allowed' | 'no-backend' | 'invalid-input' | 'missing-credentials' | 'plan-required' | 'limit-reached' | 'failed';
22
22
  export type ProvisionDatabaseDetails = {
23
23
  success: boolean;
24
24
  message: string;
@@ -38,7 +38,7 @@ export type ProvisionDatabaseDetails = {
38
38
  ticketId?: string;
39
39
  /** True when this call finished a provision an earlier call had started. */
40
40
  resumed?: boolean;
41
- /** True when that provision was found on the backend by name, not in `.env`. */
41
+ /** True when that provision was found on the backend by name, not in the project file. */
42
42
  recovered?: boolean;
43
43
  /** The database the new binding replaced (replace mode). */
44
44
  replaced?: string;
@@ -55,7 +55,12 @@ export type ProvisionDatabaseDetails = {
55
55
  appWorkspacePrepared?: boolean;
56
56
  };
57
57
  type Details = ProvisionDatabaseDetails;
58
- /** The DATABASE_ID in a project's `.env`, if it has one of the form a database id takes. */
58
+ /**
59
+ * Pending results recorded for one ticket before provision_database stops
60
+ * following it. At the default 240 s deadline that is about 20 minutes.
61
+ */
62
+ export declare const MAX_PENDING_ATTEMPTS = 5;
63
+ /** The id of the database `cwd` is bound to, if its binding can be read. */
59
64
  export declare function boundDatabaseId(cwd: string): Promise<string | undefined>;
60
65
  /**
61
66
  * What provision_database and replace_database check before they change
@@ -8,27 +8,26 @@
8
8
  // - a recorded ticket that reads back empty, or a call that lost its ticket,
9
9
  // finds an in-flight provision of the same name before anything new is
10
10
  // requested, and a completed one is only reported (binding it is `adopt`);
11
- // - the host saves the binding before `.env` is written.
11
+ // - the host saves the binding before the project file is written.
12
12
  var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  return (mod && mod.__esModule) ? mod : { "default": mod };
14
14
  };
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.MAX_PENDING_ATTEMPTS = void 0;
16
17
  exports.boundDatabaseId = boundDatabaseId;
17
18
  exports.provisionDatabaseReady = provisionDatabaseReady;
18
19
  exports.provisionDatabase = provisionDatabase;
19
20
  exports.provisionFromTool = provisionFromTool;
20
21
  const node_fs_1 = require("node:fs");
21
- const promises_1 = require("node:fs/promises");
22
22
  const node_path_1 = __importDefault(require("node:path"));
23
23
  const app_workspace_1 = require("../app-workspace");
24
24
  const db_probe_1 = require("../db-probe");
25
25
  const failure_1 = require("../failure");
26
26
  const graphql_http_1 = require("../graphql-http");
27
27
  const host_1 = require("../host");
28
+ const project_file_1 = require("../project-file");
28
29
  const credential_1 = require("./credential");
29
- const env_file_1 = require("./env-file");
30
30
  const manifest_1 = require("./manifest");
31
- const pending_ticket_1 = require("./pending-ticket");
32
31
  const preset_match_1 = require("./preset-match");
33
32
  const request_database_1 = require("./request-database");
34
33
  const resolve_1 = require("./resolve");
@@ -48,38 +47,28 @@ function unanswered(probe, message, hint, extra = {}) {
48
47
  }
49
48
  const today = () => new Date().toISOString().slice(0, 10);
50
49
  const noop = () => undefined;
51
- async function readText(file) {
52
- try {
53
- return await (0, promises_1.readFile)(file, 'utf8');
54
- }
55
- catch {
56
- return '';
57
- }
58
- }
59
- // Edit .env from its current content, read right before the write, so changes
60
- // made while this call waited on the backend (by another tool or the user)
61
- // aren't overwritten with what the file held when the call started.
62
- async function updateEnvFile(envPath, edit) {
63
- await (0, promises_1.writeFile)(envPath, edit(await readText(envPath)));
64
- }
65
- /** A project's `.env`, with each binding value checked: one that is not of its form is never used, sent or shown. */
66
- async function readBinding(envPath) {
67
- const env = (0, env_file_1.readEnv)(await readText(envPath));
68
- const invalid = (0, env_file_1.invalidBindingKeys)(env);
69
- return invalid.length ? { kind: 'failed', failure: (0, failure_1.invalidBinding)(invalid) } : { kind: 'ok', value: env };
50
+ /**
51
+ * Pending results recorded for one ticket before provision_database stops
52
+ * following it. At the default 240 s deadline that is about 20 minutes.
53
+ */
54
+ exports.MAX_PENDING_ATTEMPTS = 5;
55
+ /** The binding of `cwd`, empty when it has none; a file with a value not of its form is a failure. */
56
+ async function readBinding(cwd) {
57
+ const file = await (0, project_file_1.readProjectFile)(cwd);
58
+ return file.kind === 'failed' ? file : { kind: 'ok', value: file.value ?? {} };
70
59
  }
71
- /** The DATABASE_ID in a project's `.env`, if it has one of the form a database id takes. */
60
+ /** The id of the database `cwd` is bound to, if its binding can be read. */
72
61
  async function boundDatabaseId(cwd) {
73
62
  const binding = await boundDatabase(cwd);
74
63
  return binding.kind === 'ok' ? binding.value?.id : undefined;
75
64
  }
76
- /** The database the `.env` of `cwd` binds, as a plan names it. */
65
+ /** The database `cwd` is bound to, as a plan names it. */
77
66
  async function boundDatabase(cwd) {
78
- const binding = await readBinding(node_path_1.default.join(cwd, '.env'));
67
+ const binding = await readBinding(cwd);
79
68
  if (binding.kind === 'failed')
80
69
  return binding;
81
- const env = binding.value;
82
- return { kind: 'ok', value: env.DATABASE_ID ? { name: env.DATABASE_NAME ?? '', id: env.DATABASE_ID } : undefined };
70
+ const { database } = binding.value;
71
+ return { kind: 'ok', value: database ? { name: database.name ?? '', id: database.id } : undefined };
83
72
  }
84
73
  /**
85
74
  * The backend and the account a provision runs with, or why it cannot run.
@@ -98,7 +87,7 @@ async function provisionAccess(host) {
98
87
  const noBackend = (0, failure_1.noBackendFailure)(host.signInHint);
99
88
  return { kind: 'failed', failure: { ...noBackend, message: `Cannot provision a database: ${noBackend.message}` } };
100
89
  }
101
- const accountRead = await (0, host_1.readAccount)(host);
90
+ const accountRead = await (0, host_1.readAccount)(host, backendRead.value);
102
91
  if (accountRead.kind === 'failed')
103
92
  return { kind: 'failed', failure: { ...accountRead.failure, code: 'signed-out' } };
104
93
  const credential = (0, credential_1.selectProvisionCredential)(accountRead.value, host.signInHint);
@@ -219,16 +208,14 @@ async function provision(input, cwd, exec, viaTool) {
219
208
  return refuse(code, why);
220
209
  }
221
210
  const { apiEndpoint, modulesEndpoint, credential } = access.value;
222
- const envPath = node_path_1.default.join(cwd, '.env');
223
- const binding = await readBinding(envPath);
211
+ const binding = await readBinding(cwd);
224
212
  if (binding.kind === 'failed')
225
213
  return refuse('missing-credentials', binding.failure);
226
- const env = binding.value;
227
- const bound = env.DATABASE_ID || undefined;
214
+ const file = binding.value;
215
+ const bound = file.database?.id;
228
216
  const r = {
229
217
  host,
230
218
  cwd,
231
- envPath,
232
219
  name,
233
220
  mode: input.mode ?? 'ensure',
234
221
  apiEndpoint,
@@ -238,7 +225,7 @@ async function provision(input, cwd, exec, viaTool) {
238
225
  viaTool,
239
226
  executor: (0, request_database_1.createProvisionExecutor)({ apiEndpoint, modulesEndpoint, bearer: credential.bearer }),
240
227
  // The probe carries the account bearer, so it only ever targets the
241
- // app-configured backend, never a .env-pinned endpoint.
228
+ // app-configured backend.
242
229
  probe: (databaseId) => (0, db_probe_1.probeDatabase)({ endpoint: apiEndpoint, bearer: credential.bearer, databaseId, signInHint: host.signInHint }),
243
230
  };
244
231
  let replaced;
@@ -249,30 +236,30 @@ async function provision(input, cwd, exec, viaTool) {
249
236
  replaced = bound;
250
237
  }
251
238
  else if (bound) {
252
- return keepBinding(r, env, bound, input.adopt);
239
+ return keepBinding(r, file, bound, input.adopt);
253
240
  }
254
241
  if (input.adopt) {
255
242
  const prewarm = startPrewarm(r, exec);
256
243
  return afterPrewarm(await bindDatabase(r, { databaseId: input.adopt, replaced, adopted: true }, prewarm), prewarm);
257
244
  }
258
- return requestAndBind(r, input, env, replaced, exec);
245
+ return requestAndBind(r, input, file, replaced, exec);
259
246
  }
260
247
  // ---- ensure: keep the binding --------------------------------------------
261
- async function keepBinding(r, env, bound, adopt) {
248
+ async function keepBinding(r, file, bound, adopt) {
262
249
  const probe = await r.probe(bound);
263
250
  if (probe.status === 'unreachable') {
264
- 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 });
251
+ 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 });
265
252
  }
266
253
  if (probe.status === 'missing') {
267
254
  return refuse('db-missing', {
268
- message: `Project carries a binding (DATABASE_ID=${bound}) but that database no longer exists on this backend, or this account lost access to it.`,
255
+ message: `This project is bound to a database (ID ${bound}) that no longer exists on this backend, or that this account lost access to.`,
269
256
  hint: (0, host_1.reprovisionAdvice)(r.host),
270
257
  ...(0, host_1.replaceCall)(r.host),
271
258
  }, { databaseId: bound });
272
259
  }
273
260
  if (probe.ownerId && probe.ownerId !== r.ownerId) {
274
261
  return refuse('account-mismatch', {
275
- message: `Project carries a binding (DATABASE_ID=${bound}) but that database was provisioned under a different account than the one signed in.`,
262
+ message: `This project is bound to a database (ID ${bound}) that was provisioned under a different account than the one signed in.`,
276
263
  hint: (0, host_1.reprovisionAdvice)(r.host),
277
264
  ...(0, host_1.replaceCall)(r.host),
278
265
  }, { databaseId: bound });
@@ -282,24 +269,14 @@ async function keepBinding(r, env, bound, adopt) {
282
269
  }
283
270
  if (adopt && adopt !== bound) {
284
271
  return refuse('binding-live', {
285
- message: `The project is bound to a live database (DATABASE_ID=${bound}); adopt binds only an unbound project.`,
272
+ message: `This project is bound to a live database already (ID ${bound}), so it cannot be bound to another one.`,
286
273
  hint: 'Use replace mode to swap it.',
287
274
  }, { databaseId: bound });
288
275
  }
289
- // Heal stale endpoint pins and missing binding keys on the skip path.
290
- const databaseName = env.DATABASE_NAME || probe.name || '';
276
+ // The database answered on this backend under this account, so the binding names this backend and that database.
277
+ const databaseName = probe.name || file.database?.name || '';
291
278
  const ownerId = probe.ownerId ?? r.ownerId;
292
- const refresh = {};
293
- if (env.API_ENDPOINT !== r.apiEndpoint)
294
- refresh.API_ENDPOINT = r.apiEndpoint;
295
- if (env.MODULES_ENDPOINT !== r.modulesEndpoint)
296
- refresh.MODULES_ENDPOINT = r.modulesEndpoint;
297
- if (!env.DATABASE_NAME && databaseName)
298
- refresh.DATABASE_NAME = databaseName;
299
- if (!env.PGDATABASE && databaseName)
300
- refresh.PGDATABASE = databaseName;
301
- if (!env.OWNER_ID)
302
- refresh.OWNER_ID = ownerId;
279
+ const stale = file.backend !== r.apiEndpoint || file.database?.name !== databaseName || file.database?.ownerId !== ownerId;
303
280
  const saved = await saveBinding(r, {
304
281
  cwd: r.cwd,
305
282
  databaseId: bound,
@@ -312,20 +289,19 @@ async function keepBinding(r, env, bound, adopt) {
312
289
  if (saved)
313
290
  return saved;
314
291
  let note = '';
315
- if (Object.keys(refresh).length > 0) {
316
- const keys = Object.keys(refresh).join(', ');
292
+ if (stale && databaseName) {
317
293
  try {
318
- await updateEnvFile(r.envPath, (content) => (0, env_file_1.mergeEnv)(content, refresh));
319
- note = ` Refreshed in .env: ${keys}.`;
294
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => ({ ...current, backend: r.apiEndpoint, database: { id: bound, name: databaseName, ownerId } }));
295
+ note = ` Refreshed the binding in ${project_file_1.PROJECT_FILE}.`;
320
296
  }
321
297
  catch (err) {
322
- note = ` Could not refresh ${keys} in .env: ${(0, graphql_http_1.thrownText)(err)}.`;
298
+ note = ` Could not refresh the binding in ${project_file_1.PROJECT_FILE}: ${(0, graphql_http_1.thrownText)(err)}.`;
323
299
  }
324
300
  }
325
301
  const advice = r.host.toolReprovision === false ? '' : ' Replacing it with a new database is a separate change, only for an explicit clean rebuild.';
326
302
  return {
327
303
  success: true,
328
- message: `Project already provisioned (DATABASE_ID=${bound}) and the database is live under this account. Skipping.${advice}${note}`,
304
+ message: `This project is bound already to a live database of this account (ID ${bound}), so nothing was created.${advice}${note}`,
329
305
  databaseId: bound,
330
306
  databaseName,
331
307
  ownerId,
@@ -334,7 +310,7 @@ async function keepBinding(r, env, bound, adopt) {
334
310
  }
335
311
  function suspendedText(databaseId, probe) {
336
312
  const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
337
- 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.`;
313
+ 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.`;
338
314
  }
339
315
  // ---- replace: compare and swap -------------------------------------------
340
316
  async function checkReplace(r, input, bound) {
@@ -347,14 +323,14 @@ async function checkReplace(r, input, bound) {
347
323
  const expected = input.replaces === undefined ? bound : input.replaces || undefined;
348
324
  if ((expected ?? '') !== (bound ?? '')) {
349
325
  return refuse('binding-changed', {
350
- message: `The project's binding changed (DATABASE_ID is ${bound ?? 'unset'}, expected ${expected ?? 'unset'}), so nothing was replaced.`,
326
+ 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.`,
351
327
  }, { databaseId: bound });
352
328
  }
353
329
  if (!bound)
354
330
  return null;
355
331
  const probe = await r.probe(bound);
356
332
  if (probe.status === 'unreachable') {
357
- return unanswered(probe, `Cannot verify the binding being replaced (DATABASE_ID=${bound}): ${probe.detail}.`, 'Retry once the backend answers.', { databaseId: bound });
333
+ return unanswered(probe, `Cannot verify the database being replaced (ID ${bound}): ${probe.detail}.`, 'Retry once the backend answers.', { databaseId: bound });
358
334
  }
359
335
  if (probe.status === 'suspended') {
360
336
  return refuse('db-suspended', { message: suspendedText(bound, probe) }, { databaseId: bound });
@@ -362,7 +338,7 @@ async function checkReplace(r, input, bound) {
362
338
  // A missing or foreign-owned binding is replaced; a live one of this account
363
339
  // only through the tool's explicit rebuild.
364
340
  if (probe.status === 'found' && (!probe.ownerId || probe.ownerId === r.ownerId) && !r.viaTool) {
365
- return refuse('binding-live', { message: `The bound database (DATABASE_ID=${bound}) is live under this account, so it wasn't replaced.` }, { databaseId: bound });
341
+ 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 });
366
342
  }
367
343
  return null;
368
344
  }
@@ -424,21 +400,21 @@ async function afterPrewarm(outcome, prewarm) {
424
400
  };
425
401
  return { ...outcome, failure, message: (0, failure_1.failureText)(failure), appWorkspacePrepared: true };
426
402
  }
427
- async function requestAndBind(r, input, env, replaced, exec) {
428
- const abandoned = (0, pending_ticket_1.abandonedTickets)(env);
403
+ async function requestAndBind(r, input, file, replaced, exec) {
404
+ const abandoned = (0, project_file_1.abandonedTickets)(file);
429
405
  const abandon = async (ids) => {
430
406
  for (const id of ids)
431
407
  abandoned.add(id);
432
- await updateEnvFile(r.envPath, (content) => (0, pending_ticket_1.recordAbandoned)((0, pending_ticket_1.clearPendingTicket)(content), ids)).catch(noop);
408
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.recordAbandoned)((0, project_file_1.clearPendingTicket)(current), ids)).catch(noop);
433
409
  };
434
410
  // A ticket an earlier call stopped waiting on.
435
411
  let current;
436
412
  let recovered = false;
437
- const recorded = (0, pending_ticket_1.recordedTicket)(env);
413
+ const recorded = file.pending;
438
414
  if (recorded) {
439
415
  if (recorded.apiEndpoint !== r.apiEndpoint || recorded.userId !== r.ownerId) {
440
416
  // Requested on another backend or by another account: not ours to follow.
441
- await updateEnvFile(r.envPath, (content) => (0, pending_ticket_1.archivePendingTicket)(content, today())).catch(noop);
417
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.archivePendingTicket)(current, today())).catch(noop);
442
418
  }
443
419
  else if (input.abandonPending) {
444
420
  await abandon([recorded.ticketId]);
@@ -516,7 +492,7 @@ async function sendRequest(r, request, prewarm) {
516
492
  request: (0, preset_match_1.selectProvisionRequest)(modules),
517
493
  executor: r.executor,
518
494
  // Past the attempt cap one read says whether it finished; no more waiting.
519
- pollDeadlineMs: current && current.attempts >= pending_ticket_1.MAX_PENDING_ATTEMPTS ? 0 : pollDeadline(r.host.provisionPollDeadlineMs),
495
+ pollDeadlineMs: current && current.attempts >= exports.MAX_PENDING_ATTEMPTS ? 0 : pollDeadline(r.host.provisionPollDeadlineMs),
520
496
  resumeTicketId: current?.ticketId,
521
497
  });
522
498
  break;
@@ -540,7 +516,7 @@ async function sendRequest(r, request, prewarm) {
540
516
  recovered = true;
541
517
  continue;
542
518
  }
543
- await updateEnvFile(r.envPath, pending_ticket_1.clearPendingTicket).catch(noop);
519
+ await (0, project_file_1.updateProjectFile)(r.cwd, project_file_1.clearPendingTicket).catch(noop);
544
520
  const checked = lookup.problem
545
521
  ? `the backend couldn't be asked for another one (${lookup.problem})`
546
522
  : 'no other provision of that name is in progress';
@@ -552,7 +528,7 @@ async function sendRequest(r, request, prewarm) {
552
528
  }
553
529
  // A definitive failure ends the recorded request, so forget it.
554
530
  if (current)
555
- await updateEnvFile(r.envPath, pending_ticket_1.clearPendingTicket).catch(noop);
531
+ await (0, project_file_1.updateProjectFile)(r.cwd, project_file_1.clearPendingTicket).catch(noop);
556
532
  return requestFailure(r, err);
557
533
  }
558
534
  }
@@ -572,21 +548,21 @@ async function pendingResult(r, ticket, reason, recovered) {
572
548
  const { ticketId } = ticket;
573
549
  let recordedOk = true;
574
550
  try {
575
- await updateEnvFile(r.envPath, (content) => (0, pending_ticket_1.recordPendingTicket)(content, ticket));
551
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.recordPendingTicket)(current, ticket));
576
552
  }
577
553
  catch {
578
554
  recordedOk = false;
579
555
  }
580
- if (ticket.attempts > pending_ticket_1.MAX_PENDING_ATTEMPTS) {
556
+ if (ticket.attempts > exports.MAX_PENDING_ATTEMPTS) {
581
557
  return refuse('provision-stuck', {
582
- message: `Database "${r.name}" is still not ready after ${pending_ticket_1.MAX_PENDING_ATTEMPTS} waits (${reason}). Its request (ticket ${ticketId}) stays recorded, and no other database is requested while it is in progress.`,
558
+ message: `Database "${r.name}" is still not ready after ${exports.MAX_PENDING_ATTEMPTS} waits (${reason}). Its request (ticket ${ticketId}) stays recorded, and no other database is requested while it is in progress.`,
583
559
  hint: "Check the backend's provisioning jobs.",
584
560
  }, { ticketId });
585
561
  }
586
562
  const waiting = `call again with the same name, "${r.name}", to keep waiting on it`;
587
563
  const message = recordedOk
588
- ? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in .env; ${waiting}. Don't change the name: that starts a second database.`
589
- : `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.`;
564
+ ? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in ${project_file_1.PROJECT_FILE}; ${waiting}. Don't change the name: that starts a second database.`
565
+ : `Database "${r.name}" is still provisioning (${reason}). Recording its ticket in ${project_file_1.PROJECT_FILE} failed, but the backend still has it: ${waiting}. Don't change the name: that starts a second database.`;
590
566
  return {
591
567
  success: false,
592
568
  message,
@@ -627,10 +603,10 @@ const anotherName = (r) => (0, failure_1.suggest)(againTool(r), {}, 'Request the
627
603
  // The backend refused a read of the provision because the sign-in ended. The provision may still be running, so its
628
604
  // ticket stays recorded, and the next call after a sign-in waits on it instead of requesting another database.
629
605
  async function signedOutWaiting(r, ticket, reason) {
630
- const recorded = await updateEnvFile(r.envPath, (content) => (0, pending_ticket_1.recordPendingTicket)(content, ticket)).then(() => true, () => false);
606
+ const recorded = await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.recordPendingTicket)(current, ticket)).then(() => true, () => false);
631
607
  return refuse('signed-out', {
632
608
  message: `The backend did not accept the account credential while it read the provision of "${r.name}" (ticket ${ticket.ticketId}): ${reason}. ` +
633
- `The database may still be on its way${recorded ? ', and the request stays recorded in .env' : ''}.`,
609
+ `The database may still be on its way${recorded ? `, and the request stays recorded in ${project_file_1.PROJECT_FILE}` : ''}.`,
634
610
  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.`,
635
611
  calls: [again(r, 'Keep waiting on the recorded request once signed in')],
636
612
  }, { ticketId: ticket.ticketId });
@@ -713,9 +689,9 @@ async function saveBinding(r, binding, ticket) {
713
689
  catch (err) {
714
690
  // Keep the ticket recorded, so the next call resumes it and binds it.
715
691
  if (ticket)
716
- await updateEnvFile(r.envPath, (content) => (0, pending_ticket_1.recordPendingTicket)(content, ticket)).catch(noop);
692
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.recordPendingTicket)(current, ticket)).catch(noop);
717
693
  return refuse('binding-not-saved', {
718
- message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${(0, graphql_http_1.thrownText)(err)}), so .env was left unchanged.`,
694
+ message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${(0, graphql_http_1.thrownText)(err)}), so ${project_file_1.PROJECT_FILE} was left unchanged.`,
719
695
  ...(ticket
720
696
  ? {
721
697
  hint: 'Calling again with the same name binds it.',
@@ -739,7 +715,7 @@ async function bindDatabase(r, bind, prewarm) {
739
715
  const visible = owner.status !== 'missing';
740
716
  if (!visible || owner.ownerId !== r.ownerId) {
741
717
  if (ticket)
742
- await updateEnvFile(r.envPath, pending_ticket_1.clearPendingTicket).catch(noop);
718
+ await (0, project_file_1.updateProjectFile)(r.cwd, project_file_1.clearPendingTicket).catch(noop);
743
719
  const why = visible ? "it isn't owned by" : "it isn't visible to";
744
720
  if (bind.adopted) {
745
721
  return refuse(visible ? 'account-mismatch' : 'db-missing', {
@@ -766,19 +742,13 @@ async function bindDatabase(r, bind, prewarm) {
766
742
  }, ticket);
767
743
  if (saved)
768
744
  return saved;
769
- // Write the binding into .env (upsert, preserving other keys), dropping any
770
- // recorded pending request: the project is bound now.
745
+ // Write the binding, dropping any recorded pending request: the project is bound now. A binding it replaces stays
746
+ // readable in the archive.
771
747
  try {
772
- await updateEnvFile(r.envPath, (content) => (0, env_file_1.mergeEnv)((0, pending_ticket_1.clearPendingTicket)(bind.replaced ? (0, env_file_1.archiveBindingKeys)(content, env_file_1.ARCHIVED_BINDING_KEYS, today()) : content), (0, env_file_1.provisionEnvVars)({
773
- databaseId,
774
- databaseName: r.name,
775
- ownerId: r.ownerId,
776
- apiEndpoint: r.apiEndpoint,
777
- modulesEndpoint: r.modulesEndpoint,
778
- })));
748
+ await (0, project_file_1.updateProjectFile)(r.cwd, (current) => (0, project_file_1.bindProject)(current, { database: { id: databaseId, name: r.name, ownerId: r.ownerId }, backend: r.apiEndpoint, archivedOn: today() }));
779
749
  }
780
750
  catch (err) {
781
- return refuse('env-write-failed', { message: `Database provisioned (ID: ${databaseId}) but writing .env failed: ${(0, graphql_http_1.thrownText)(err)}` }, { databaseId });
751
+ return refuse('binding-write-failed', { message: `Database provisioned (ID: ${databaseId}) but writing ${project_file_1.PROJECT_FILE} failed: ${(0, graphql_http_1.thrownText)(err)}` }, { databaseId });
782
752
  }
783
753
  // Settle the concurrent prewarm so the scaffold + install are in place before
784
754
  // run_codegen runs. A failure here is non-fatal: run_codegen redoes the work.
@@ -787,12 +757,12 @@ async function bindDatabase(r, bind, prewarm) {
787
757
  bind.resumed ? ' Finished an earlier request.' : '',
788
758
  bind.recovered ? ' Found it on the backend by name.' : '',
789
759
  prewarmed,
790
- bind.replaced ? ' The old binding is archived in .env, and the old database keeps its data. Build the schema again here.' : '',
760
+ bind.replaced ? ` The old binding is archived in ${project_file_1.PROJECT_FILE}, and the old database keeps its data. Build the schema again here.` : '',
791
761
  ].join('');
792
762
  const named = `${r.name} (${databaseId.slice(0, 8)})`;
793
763
  const message = bind.adopted
794
- ? `Bound this directory to ${named}. Wrote .env.${notes}`
795
- : `Created ${named} and bound this directory to it. Wrote .env.${notes}`;
764
+ ? `Bound this directory to ${named}. Wrote ${project_file_1.PROJECT_FILE}.${notes}`
765
+ : `Created ${named} and bound this directory to it. Wrote ${project_file_1.PROJECT_FILE}.${notes}`;
796
766
  return {
797
767
  success: true,
798
768
  message,
package/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
  }>>;