@agentic-kit/db-tools 0.14.0 → 0.15.1

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.
@@ -1,6 +1,6 @@
1
- // What add_records and update_records share: the app table a call names, read from the app API's `_meta` as the
2
- // person signed in to the app; each record's keys as the API's field names, with "@<table>[<index>]" as the id of a
3
- // sample row the host seeded; and one write per row, with what each row's answer was.
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
+ // each record's keys as the API's field names, with "@<table>[<index>]" as the id of a sample row the host seeded;
3
+ // and one write per row, with what each row's answer was.
4
4
  import { listed, nearestName } 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';
@@ -31,20 +31,15 @@ const WORDS = {
31
31
  noRows: (action, tableName) => noRowsChanged(action, explainAccessCall(tableName)),
32
32
  },
33
33
  };
34
- const UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
35
- const isSuspended = (errors) => classifyBackendErrors(errors) === 'suspended';
34
+ export const UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
35
+ export const isSuspended = (errors) => classifyBackendErrors(errors) === 'suspended';
36
36
  export function recordsFailed(failure, extra = {}) {
37
37
  const flag = failure.code === 'app-signed-out' ? { needsAuth: true } : failure.code === 'database-unavailable' ? { code: failure.code } : {};
38
38
  return failedResult(failure, { success: false, message: failureText(failure), ...flag, ...extra });
39
39
  }
40
40
  export const invalid = (message) => ({ kind: 'failed', failure: { code: 'invalid-input', message, calls: [DESCRIBE_SCHEMA] } });
41
- /**
42
- * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
43
- * sign-in, the table on the app's API, and every record's keys and seeded-row values.
44
- */
45
- export async function recordsReady(verb, params, cwd) {
46
- if (params.records.length === 0)
47
- return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
41
+ /** The project, its data endpoint, an app sign-in, and the tables of the app's API; `done` ends a suspended message. */
42
+ export async function appReady(cwd, done) {
48
43
  const ready = await projectReady(cwd);
49
44
  if (ready.kind === 'failed')
50
45
  return ready;
@@ -68,7 +63,7 @@ export async function recordsReady(verb, params, cwd) {
68
63
  const meta = await adapter.execute(META_QUERY);
69
64
  if (!meta.ok) {
70
65
  const failure = isSuspended(meta.errors)
71
- ? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were ${WORDS[verb].done.toLowerCase()}.` }
66
+ ? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were ${done}.` }
72
67
  : failureFromErrors(meta.errors, 'Failed to read schema from the app database');
73
68
  return { kind: 'failed', failure };
74
69
  }
@@ -77,7 +72,19 @@ export async function recordsReady(verb, params, cwd) {
77
72
  catch (err) {
78
73
  return { kind: 'failed', failure: failureFromError(err, 'Failed to query the app database schema') };
79
74
  }
80
- const table = findMetaTable(tables, params.table_name);
75
+ return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables } };
76
+ }
77
+ /**
78
+ * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
79
+ * sign-in, the table on the app's API, and every record's keys and seeded-row values.
80
+ */
81
+ export async function recordsReady(verb, params, cwd) {
82
+ if (params.records.length === 0)
83
+ return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
84
+ const ready = await appReady(cwd, WORDS[verb].done.toLowerCase());
85
+ if (ready.kind === 'failed')
86
+ return ready;
87
+ const table = findMetaTable(ready.value.tables, params.table_name);
81
88
  if (!table) {
82
89
  return {
83
90
  kind: 'failed',
@@ -89,7 +96,8 @@ export async function recordsReady(verb, params, cwd) {
89
96
  },
90
97
  };
91
98
  }
92
- const seeded = await seededIds(params.records, cwd);
99
+ const named = params.records.some((record) => Object.values(record).some(isRowRef));
100
+ const seeded = named ? await seededIds(cwd) : { kind: 'ok', value: new Map() };
93
101
  if (seeded.kind === 'failed')
94
102
  return seeded;
95
103
  const records = [];
@@ -99,7 +107,7 @@ export async function recordsReady(verb, params, cwd) {
99
107
  return row;
100
108
  records.push(row.value);
101
109
  }
102
- return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables, table, records } };
110
+ return { kind: 'ok', value: { ...ready.value, table, records } };
103
111
  }
104
112
  export const fieldsOf = (table) => (table.fields ?? []).filter((f) => Boolean(f));
105
113
  export const columnOf = (field) => field.columnName ?? field.name;
@@ -109,12 +117,12 @@ export function primaryKeyOf(table) {
109
117
  return keys.length === 1 ? keys[0] : undefined;
110
118
  }
111
119
  const ROW_REF = /^@([a-z][a-z0-9_]*)\[(\d+)\]$/i;
112
- const tableKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
113
- /** The ids of the sample rows the host seeded, by `tableKey`, read only when a record names one. */
114
- async function seededIds(records, cwd) {
115
- const named = records.some((record) => Object.values(record).some((value) => typeof value === 'string' && ROW_REF.test(value)));
120
+ export const isRowRef = (value) => typeof value === 'string' && ROW_REF.test(value);
121
+ export const tableKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
122
+ /** The ids of the sample rows the host seeded, by `tableKey`; none on a host that seeds no rows. */
123
+ export async function seededIds(cwd) {
116
124
  const host = getHost();
117
- if (!named || !host.seededRows)
125
+ if (!host.seededRows)
118
126
  return { kind: 'ok', value: new Map() };
119
127
  try {
120
128
  const rows = (await host.seededRows(cwd)) ?? {};
@@ -133,14 +141,9 @@ const isEmpty = (value) => value === undefined || value === null || value === ''
133
141
  */
134
142
  export function recordAsFields(table, tableName, index, record, seeded, clear) {
135
143
  const fields = fieldsOf(table);
136
- const names = new Set(fields.flatMap((field) => [field.name, columnOf(field)]));
137
- const unknown = Object.keys(record).find((key) => !names.has(key));
138
- if (unknown !== undefined) {
139
- const columns = fields.map(columnOf);
140
- const nearest = nearestName(unknown, columns);
141
- const next = nearest ? `use "${nearest}".` : `its columns are ${listed(columns.map((c) => `"${c}"`))}.`;
142
- return invalid(`Row ${index} names "${unknown}", which is not a column of ${tableName}: ${next}`);
143
- }
144
+ const unknown = notAColumn(table, tableName, Object.keys(record));
145
+ if (unknown)
146
+ return invalid(`Row ${index} names ${unknown}`);
144
147
  const row = {};
145
148
  for (const field of fields) {
146
149
  const given = [field.name, columnOf(field)].filter((key) => Object.hasOwn(record, key)).map((key) => record[key]);
@@ -152,18 +155,32 @@ export function recordAsFields(table, tableName, index, record, seeded, clear) {
152
155
  row[field.name] = null;
153
156
  continue;
154
157
  }
155
- const ref = typeof value === 'string' ? value.match(ROW_REF) : null;
156
- if (!ref) {
157
- row[field.name] = value;
158
- continue;
159
- }
160
- const id = seeded.get(tableKey(ref[1]))?.[Number(ref[2])];
161
- if (!id)
158
+ const id = seededValue(value, seeded);
159
+ if (id === undefined)
162
160
  return invalid(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`);
163
161
  row[field.name] = id;
164
162
  }
165
163
  return { kind: 'ok', value: row };
166
164
  }
165
+ /** The value, or the id of the seeded row a "@<table>[<index>]" value names: undefined when none was seeded there. */
166
+ export function seededValue(value, seeded) {
167
+ const ref = typeof value === 'string' ? value.match(ROW_REF) : null;
168
+ return ref ? seeded.get(tableKey(ref[1]))?.[Number(ref[2])] ?? undefined : value;
169
+ }
170
+ /** The first key that names no column (or field) of the table, with the column to use instead, as the end of a sentence. */
171
+ export function notAColumn(table, tableName, keys) {
172
+ const fields = fieldsOf(table);
173
+ const names = new Set(fields.flatMap((field) => [field.name, columnOf(field)]));
174
+ const unknown = keys.find((key) => !names.has(key));
175
+ if (unknown === undefined)
176
+ return undefined;
177
+ const columns = fields.map(columnOf);
178
+ const nearest = nearestName(unknown, columns);
179
+ const next = nearest ? `use "${nearest}".` : `its columns are ${listed(columns.map((c) => `"${c}"`))}.`;
180
+ return `"${unknown}", which is not a column of ${tableName}: ${next}`;
181
+ }
182
+ /** The field a key names, by its field name or its column name. */
183
+ export const fieldNamed = (table, key) => fieldsOf(table).find((field) => field.name === key) ?? fieldsOf(table).find((field) => columnOf(field) === key);
167
184
  /** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
168
185
  export async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutation, mutationName, inputs) {
169
186
  const words = WORDS[verb];
@@ -54,6 +54,8 @@ export type ModelForeignKey = {
54
54
  targetCategory: ObjectCategory | null;
55
55
  targetColumns: string[];
56
56
  onDelete: FkAction;
57
+ /** The columns a delete of the target row sets to null or their default, when the key names only some of its own. */
58
+ deleteSetColumns?: string[];
57
59
  onUpdate: FkAction;
58
60
  };
59
61
  export type ModelPolicy = {
@@ -185,6 +185,7 @@ export async function readSchemaModel(context) {
185
185
  refTableId: true,
186
186
  refFieldIds: true,
187
187
  deleteAction: true,
188
+ deleteSetFieldIds: true,
188
189
  updateAction: true,
189
190
  },
190
191
  where: inApp,
@@ -290,6 +291,7 @@ export async function readSchemaModel(context) {
290
291
  targetCategory: target?.category ?? null,
291
292
  targetColumns: names(fk.refFieldIds),
292
293
  onDelete: fkAction(fk.deleteAction),
294
+ ...(fk.deleteSetFieldIds?.length ? { deleteSetColumns: names(fk.deleteSetFieldIds) } : {}),
293
295
  onUpdate: fkAction(fk.updateAction),
294
296
  };
295
297
  }),
@@ -1,10 +1,10 @@
1
1
  import type { BlueprintRelation } from 'node-type-registry';
2
2
  import { z } from 'zod';
3
3
  export declare const DeleteAction: z.ZodEnum<{
4
- a: "a";
5
4
  c: "c";
6
- r: "r";
7
5
  n: "n";
6
+ r: "r";
7
+ a: "a";
8
8
  d: "d";
9
9
  }>;
10
10
  export declare const AddRelationZod: z.ZodObject<{
@@ -17,10 +17,10 @@ export declare const AddRelationZod: z.ZodObject<{
17
17
  field_name: z.ZodOptional<z.ZodString>;
18
18
  junction_table_name: z.ZodOptional<z.ZodString>;
19
19
  delete_action: z.ZodOptional<z.ZodEnum<{
20
- a: "a";
21
20
  c: "c";
22
- r: "r";
23
21
  n: "n";
22
+ r: "r";
23
+ a: "a";
24
24
  d: "d";
25
25
  }>>;
26
26
  is_required: z.ZodOptional<z.ZodBoolean>;
@@ -0,0 +1,33 @@
1
+ import { type HarnessTool } from '@agentic-kit/harness';
2
+ import { z } from 'zod';
3
+ import { type DeleteRecordsReady } from '../records/delete-selection';
4
+ import type { Resolved } from './index';
5
+ declare const DeleteRecordsZod: z.ZodObject<{
6
+ tables: z.ZodArray<z.ZodObject<{
7
+ table_name: z.ZodString;
8
+ rows: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
9
+ where: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
10
+ sample: z.ZodOptional<z.ZodLiteral<true>>;
11
+ all: z.ZodOptional<z.ZodLiteral<true>>;
12
+ }, z.core.$strict>>;
13
+ }, z.core.$strict>;
14
+ export type DeleteRecordsDetails = {
15
+ success: boolean;
16
+ message: string;
17
+ deletedCount: number;
18
+ tables: Array<{
19
+ tableName: string;
20
+ deleted: number;
21
+ kept?: true;
22
+ failed: Array<{
23
+ key: string | number;
24
+ message: string;
25
+ }>;
26
+ }>;
27
+ needsAuth?: boolean;
28
+ code?: 'database-unavailable';
29
+ };
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;
32
+ export declare const deleteRecordsTool: HarnessTool<typeof DeleteRecordsZod, DeleteRecordsDetails>;
33
+ export {};
@@ -0,0 +1,208 @@
1
+ import { identifierParam, listed, strictObject, takeApprovedTable } from '@agentic-kit/harness';
2
+ import { buildPostGraphileDelete, toDeleteMutationName } from '@constructive-io/graphql-query/generators';
3
+ import { z } from 'zod';
4
+ import { DESCRIBE_SCHEMA, failureFromErrors, noRowsChanged } from '../failure';
5
+ import { answerText, thrownText } from '../graphql-http';
6
+ import { databaseTarget } from '../ready';
7
+ import { deleteEffects, pointOf, rowsOf, sqlName, tablesNotChecked } from '../records/delete-effects';
8
+ import { deleteRecordsReady } from '../records/delete-selection';
9
+ import { cleanTable, findMetaTable } from '../records/meta';
10
+ import { appReady, isSuspended, primaryKeyOf, recordsFailed, UNAVAILABLE } from '../records/rows';
11
+ const DeleteTableZod = strictObject('a table', {
12
+ table_name: identifierParam().describe('Name of the table to delete rows from (snake_case, singular or plural).'),
13
+ rows: z
14
+ .array(z.union([z.string(), z.number()]))
15
+ .min(1)
16
+ .describe('The rows to delete, by primary key, or "@<table>[<index>]" for a sample row seeded when the app was built.')
17
+ .optional(),
18
+ where: z
19
+ .record(z.string(), z.unknown())
20
+ .describe('Delete every row whose columns have these values: column name (snake_case) -> value; null matches an empty column.')
21
+ .optional(),
22
+ sample: z.literal(true).describe('Delete every sample row seeded when the app was built that is still there.').optional(),
23
+ all: z.literal(true).describe('Delete every row of the table that the person signed in to the app can see.').optional(),
24
+ });
25
+ const DeleteRecordsZod = strictObject('the input', {
26
+ tables: z
27
+ .array(DeleteTableZod)
28
+ .min(1)
29
+ .max(20)
30
+ .describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'),
31
+ });
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 }) {
34
+ return {
35
+ target: { ...databaseTarget(context, userId), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
36
+ preview: { kind: 'delete-records', ...selection },
37
+ ...(notes.length ? { notes } : {}),
38
+ };
39
+ }
40
+ const sameTarget = (a, b) => a.database.id === b.database.id && a.apiEndpoint === b.apiEndpoint && a.account.userId === b.account.userId &&
41
+ a.account.agent?.principalId === b.account.agent?.principalId && a.appUserId === b.appUserId;
42
+ /** The app table and key of each table of the rows to delete, still on the app API with a delete. */
43
+ function plannedRows(tables, rows) {
44
+ const planned = [];
45
+ for (const { tableName, keys } of rows) {
46
+ const table = tables.find((candidate) => sqlName(candidate) === tableName);
47
+ const key = table && primaryKeyOf(table);
48
+ if (!table || !key || !table.query?.delete) {
49
+ return {
50
+ kind: 'failed',
51
+ failure: {
52
+ code: 'failed',
53
+ message: `${tableName} changed on the app API after its rows were chosen, so nothing was deleted.`,
54
+ hint: 'Review the rows and approve a new request.',
55
+ },
56
+ };
57
+ }
58
+ planned.push({ tableName, table, keyName: key.name, keys });
59
+ }
60
+ return { kind: 'ok', value: planned };
61
+ }
62
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
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
+ /** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */
65
+ async function deleteRows({ adapter, tables }, planned, kept) {
66
+ const all = tables.map(cleanTable);
67
+ const results = [];
68
+ const errors = [];
69
+ let suspended = false;
70
+ for (const { tableName, table: rawTable, keyName, keys } of planned) {
71
+ if (suspended)
72
+ break;
73
+ const table = cleanTable(rawTable);
74
+ const mutation = buildPostGraphileDelete(table, all).toString();
75
+ const mutationName = toDeleteMutationName(table.name, table);
76
+ const result = { tableName, deleted: 0, failed: [] };
77
+ results.push(result);
78
+ for (const key of keys) {
79
+ let rowErrors;
80
+ try {
81
+ const answer = await adapter.execute(mutation, { input: { [keyName]: key } });
82
+ if (answer.ok) {
83
+ if (answer.data?.[mutationName])
84
+ result.deleted += 1;
85
+ else
86
+ result.failed.push({ key, message: NO_ROW_DELETED });
87
+ continue;
88
+ }
89
+ if (isSuspended(answer.errors)) {
90
+ suspended = true;
91
+ break;
92
+ }
93
+ rowErrors = answer.errors;
94
+ }
95
+ catch (err) {
96
+ // The request threw before any answer came back, so the error is the local one.
97
+ rowErrors = [{ message: thrownText(err), extensions: { code: 'NETWORK' } }];
98
+ }
99
+ errors.push(...rowErrors);
100
+ result.failed.push({ key, message: answerText(rowErrors) });
101
+ }
102
+ }
103
+ const deletedCount = results.reduce((sum, result) => sum + result.deleted, 0);
104
+ const failedCount = results.reduce((sum, result) => sum + result.failed.length, 0);
105
+ const details = { deletedCount, tables: [...results, ...kept.map((tableName) => ({ tableName, deleted: 0, kept: true, failed: [] }))] };
106
+ const done = results.filter((result) => result.deleted > 0);
107
+ const message = [
108
+ done.length ? `Deleted ${listed(done.map((result, index) => `${index === 0 ? plural(result.deleted, 'row') : result.deleted} from ${result.tableName}`))}.` : '',
109
+ ...results.filter((result) => result.failed.length > 0).map(({ tableName, failed: [first, ...rest] }) => `${plural(rest.length + 1, 'row')} of ${tableName} ${rest.length ? 'were' : 'was'} not deleted (${first.key}: ${first.message}).`),
110
+ kept.length ? `Nothing was deleted from ${listed(kept)}: the person unticked ${kept.length === 1 ? 'it, or it' : 'them, or they'} had no rows to delete.` : '',
111
+ ].filter(Boolean).join(' ');
112
+ const failed = (failure) => recordsFailed(failure, details);
113
+ if (suspended) {
114
+ const before = deletedCount === 0 ? 'No rows were deleted.' : `${deletedCount === 1 ? '1 row was' : `${deletedCount} rows were`} deleted before it stopped.`;
115
+ return failed({ code: 'database-unavailable', message: `${UNAVAILABLE} ${before}` });
116
+ }
117
+ if (failedCount > 0 && deletedCount === 0) {
118
+ const action = `Failed to delete rows from ${listed(results.map((result) => result.tableName))}`;
119
+ return failed(errors.length ? failureFromErrors(errors, action, { rows: { table: results[0].tableName } }) : noRowsChanged(action, DESCRIBE_SCHEMA));
120
+ }
121
+ if (failedCount > 0) {
122
+ return failed({
123
+ code: 'partial',
124
+ message,
125
+ hint: 'Fix what the backend said about the rows in details.tables, then call again with only those rows: the deleted rows are gone.',
126
+ });
127
+ }
128
+ return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
129
+ }
130
+ /** Why the approved rows cannot go while the person keeps the table that `effect` reaches, and what to do instead. */
131
+ function keptReached(effect) {
132
+ const { parent, child } = effect;
133
+ const what = effect.effect === 'cascade'
134
+ ? `deleting ${parent} deletes them too`
135
+ : effect.effect === 'set_null'
136
+ ? `deleting ${parent} clears ${listed(effect.columns)} on them`
137
+ : effect.effect === 'set_default'
138
+ ? `deleting ${parent} sets ${listed(effect.columns)} to ${effect.columns.length === 1 ? 'its default' : 'their defaults'} on them`
139
+ : `${parent} rows can't be deleted while they're there`;
140
+ return `You kept ${child}, but ${rowsOf(effect)} ${pointOf(effect)} at ${parent} you'd delete, and ${what}. Approve again with ${child} ticked, or keep ${parent} too.`;
141
+ }
142
+ /** Why the check could not rule out that the approved rows reach `table`, which the person kept, and what to do. */
143
+ function keptNotChecked(effect, table) {
144
+ if (effect.upTo)
145
+ return `Nothing was deleted: there are too many related rows to check that ${table} stays untouched. Delete in smaller steps, or tick ${table}.`;
146
+ const why = effect.uncounted
147
+ ? `the ${effect.child} rows that point at ${effect.parent} can't be counted`
148
+ : `the rows that point at the ${effect.child} rows it deletes can't be followed`;
149
+ return `Nothing was deleted: ${why}, so it can't check that ${table} stays untouched. Tick ${table}, or keep ${effect.parent} too.`;
150
+ }
151
+ export const deleteRecordsTool = {
152
+ name: 'delete_records',
153
+ label: 'Delete records',
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
+ promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.',
156
+ parameters: DeleteRecordsZod,
157
+ effect: 'write',
158
+ async execute(params, ctx) {
159
+ const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined;
160
+ const fail = (failure) => recordsFailed(failure, { deletedCount: 0, tables: [] });
161
+ if (!approved?.rows) {
162
+ // The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes
163
+ // nothing, because only an approved target says which rows the person saw and kept.
164
+ const ready = await deleteRecordsReady(params, ctx.cwd);
165
+ if (ready.kind === 'failed')
166
+ return fail(ready.failure);
167
+ return fail({
168
+ code: 'failed',
169
+ message: 'This delete has no approval (it may have expired), so nothing was deleted. Ask again to see the rows and approve them.',
170
+ });
171
+ }
172
+ const ready = await appReady(ctx.cwd, 'deleted');
173
+ if (ready.kind === 'failed')
174
+ return fail(ready.failure);
175
+ if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value.userId))) {
176
+ return fail({
177
+ code: 'failed',
178
+ message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.',
179
+ hint: 'Review the rows and approve a new request.',
180
+ });
181
+ }
182
+ const planned = plannedRows(ready.value.tables, approved.rows);
183
+ if (planned.kind === 'failed')
184
+ return fail(planned.failure);
185
+ // A table of the input that the approved rows leave out was unticked, or had no rows when the card was built.
186
+ const approvedTables = new Set(planned.value.map((entry) => entry.table));
187
+ const kept = params.tables
188
+ .map((input) => findMetaTable(ready.value.tables, input.table_name))
189
+ .filter((table) => Boolean(table) && !approvedTables.has(table))
190
+ .map(sqlName);
191
+ if (kept.length > 0) {
192
+ const found = await deleteEffects(ready.value, approved.rows);
193
+ if (found.kind === 'failed')
194
+ return fail(found.failure);
195
+ const { effects, model } = found.value;
196
+ const reached = effects.find((effect) => !effect.uncounted && kept.includes(effect.child));
197
+ if (reached)
198
+ return fail({ code: 'conflict', message: keptReached(reached) });
199
+ // An effect the check could not count or follow may still reach a kept table, so it counts as reaching it.
200
+ for (const effect of effects) {
201
+ const table = tablesNotChecked(effect, model).find((name) => kept.includes(name));
202
+ if (table)
203
+ return fail({ code: 'conflict', message: keptNotChecked(effect, table) });
204
+ }
205
+ }
206
+ return deleteRows(ready.value, planned.value, kept);
207
+ },
208
+ };
@@ -1,4 +1,4 @@
1
- import type { AnyHarnessTool, PlanTableAccess, PlanTarget } from '@agentic-kit/harness';
1
+ import type { AnyHarnessTool, ConfirmPreview, PlanTableAccess, PlanTarget } from '@agentic-kit/harness';
2
2
  import type { Result } from '../failure';
3
3
  /**
4
4
  * The Constructive database tools, in registration order.
@@ -8,11 +8,15 @@ import type { Result } from '../failure';
8
8
  * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
9
9
  */
10
10
  export declare const constructiveDbTools: readonly AnyHarnessTool[];
11
- /** What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, and what it must say that the input does not. */
11
+ /**
12
+ * What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, what
13
+ * it must say that the input does not, and the card's preview when only the check can build it.
14
+ */
12
15
  export type Resolved = {
13
16
  target: PlanTarget;
14
17
  access?: PlanTableAccess[];
15
18
  notes?: string[];
19
+ preview?: ConfirmPreview;
16
20
  };
17
21
  type Precondition = (params: any, cwd: string) => Promise<Result<Resolved>>;
18
22
  /**
@@ -2,6 +2,7 @@ import { tablePolicyFromBlueprint } from '../access';
2
2
  import { fieldTypeToTypeName, toFieldDefault } from '../blueprint/field-type';
3
3
  import { provisionDatabaseReady } from '../provision-database/provision';
4
4
  import { accountTarget, databaseTarget, ownedProjectReady, projectReady } from '../ready';
5
+ import { deleteRecordsReady } from '../records/delete-selection';
5
6
  import { renameNote } from '../schema-resolve';
6
7
  import { columnChange, columnPlan, planTableAccess } from '../table-access';
7
8
  import { addedByBackend, describePolicyTypeTool, explainAccessTool, readOnlyNotes, setAccessPlan, setAccessReady, setAccessTool } from './access';
@@ -9,6 +10,7 @@ import { addPoliciesPlan, addPoliciesReady, addPoliciesTool } from './add-polici
9
10
  import { addRecordsReady, addRecordsTool } from './add-records';
10
11
  import { addRelationReady, addRelationTool } from './add-relation';
11
12
  import { createApiKeyReady, createApiKeyTool } from './create-api-key';
13
+ import { deleteRecordsPlan, deleteRecordsTool } from './delete-records';
12
14
  import { describeSchemaTool } from './describe-schema';
13
15
  import { createEntityTypeReady, createEntityTypeTool, deleteEntityTypeReady, deleteEntityTypeTool, listEntityTypesTool } from './entity-types';
14
16
  import { createFieldReady, createFieldTool, deleteFieldReady, deleteFieldTool, deleteTableReady, deleteTableTool, retypeFieldReady, retypeFieldTool, updateFieldReady, updateFieldTool, } from './mutations';
@@ -43,6 +45,7 @@ export const constructiveDbTools = [
43
45
  deleteTemplateTool,
44
46
  addRecordsTool,
45
47
  updateRecordsTool,
48
+ deleteRecordsTool,
46
49
  listEntityTypesTool,
47
50
  createEntityTypeTool,
48
51
  deleteEntityTypeTool,
@@ -135,6 +138,13 @@ export const toolPreconditions = new Map([
135
138
  [deleteTemplateTool.name, targeting(templateReady, ({ context }) => accountTarget(context))],
136
139
  [addRecordsTool.name, targeting(addRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
137
140
  [updateRecordsTool.name, targeting(updateRecordsReady, ({ context, userId }) => databaseTarget(context, userId))],
141
+ [
142
+ deleteRecordsTool.name,
143
+ async (params, cwd) => {
144
+ const ready = await deleteRecordsReady(params, cwd);
145
+ return ready.kind === 'failed' ? ready : { kind: 'ok', value: deleteRecordsPlan(ready.value) };
146
+ },
147
+ ],
138
148
  [listEntityTypesTool.name, onDatabase(project)],
139
149
  [createEntityTypeTool.name, onDatabase(createEntityTypeReady)],
140
150
  [deleteEntityTypeTool.name, onDatabase(deleteEntityTypeReady)],
package/host.d.ts CHANGED
@@ -179,7 +179,8 @@ export interface ToolsHost {
179
179
  persistBinding?(binding: ProjectBinding): Promise<void>;
180
180
  /**
181
181
  * The ids of the sample rows the host seeded into the project's database, by table name, in seed order (null for
182
- * a row that did not land). A record value "@<table>[<index>]" in add_records or update_records names one of them.
182
+ * a row that did not land). A value "@<table>[<index>]" in add_records, update_records or delete_records names one of them, and delete_records
183
+ * can delete every seeded row of a table that is still there.
183
184
  * A host that seeds no rows leaves it out, and such a value then fails.
184
185
  */
185
186
  seededRows?(cwd: string): Promise<Readonly<Record<string, readonly (string | null)[]>> | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentic-kit/db-tools",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "author": "Constructive <developers@constructive.io>",
5
5
  "description": "harness-neutral Constructive database tools — provisioning, schema, policies, records, templates and codegen as HarnessTools any adapter can bind",
6
6
  "main": "index.js",
@@ -23,10 +23,10 @@
23
23
  "ajv": "^8.20.0",
24
24
  "zod": "^4.4.3",
25
25
  "12factor-env": "^1.34.1",
26
+ "@agentic-kit/harness": "^0.21.0",
26
27
  "@constructive-io/graphql-query": "^4.26.0",
27
28
  "@constructive-io/sdk": "^1.22.2",
28
- "node-type-registry": "^1.24.0",
29
- "@agentic-kit/harness": "^0.20.0"
29
+ "node-type-registry": "^1.24.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "typebox": "^1.0.0"
@@ -0,0 +1,64 @@
1
+ import { type DeleteRecordsLink } from '@agentic-kit/harness';
2
+ import { type Result } from '../failure';
3
+ import { type SchemaModel } from '../schema-model';
4
+ import { type RawMetaTable } from './meta';
5
+ import { type AppReady } from './rows';
6
+ /** The most rows one call deletes, over all its tables, and the most rows its effects read. */
7
+ export declare const MAX_DELETED_ROWS = 500;
8
+ /** The SQL name of an app table, as the person and the schema model name it. */
9
+ export declare const sqlName: (table: RawMetaTable) => string;
10
+ export type Read = {
11
+ total: number;
12
+ nodes: Record<string, unknown>[];
13
+ };
14
+ /** The first rows the filter selects, with the given fields, and how many it selects in all. */
15
+ export declare function readRows(ready: AppReady, { name, table }: {
16
+ name: string;
17
+ table: RawMetaTable;
18
+ }, filter: Record<string, unknown> | undefined, select: string[], first: number): Promise<Result<Read>>;
19
+ export type Effect = 'cascade' | 'set_null' | 'set_default' | 'restrict';
20
+ /**
21
+ * Rows of `child` that point at rows of `parent` the delete removes and that the delete does not select: what happens
22
+ * to them, by which columns, how many there are, and how many of the parent rows they point at. `upTo` is set when
23
+ * there were more than the read could take: then the count is at most that many. `unfollowed` is set when the rows go
24
+ * and other rows point at them, but `child` has no single-column key to follow them by. `uncounted` is set when the
25
+ * rows cannot be read on the app API, or the values the key points at cannot be read from the deleted rows.
26
+ */
27
+ export type DeleteEffect = {
28
+ parent: string;
29
+ child: string;
30
+ effect: Effect;
31
+ columns: string[];
32
+ rows: number;
33
+ parents: number;
34
+ upTo?: number;
35
+ unfollowed?: true;
36
+ uncounted?: true;
37
+ };
38
+ export declare const rowsOf: (effect: DeleteEffect) => string;
39
+ /** "points" for one row, "point" for more. */
40
+ export declare const pointOf: (effect: DeleteEffect) => string;
41
+ /** One plain line for the card. */
42
+ export declare function effectLine(effect: DeleteEffect): string;
43
+ /** The foreign keys between the tables a delete names, one for each child, parent and effect, for the card to warn with. */
44
+ export declare function linksOf(names: readonly string[], model: SchemaModel): DeleteRecordsLink[];
45
+ /**
46
+ * The tables an effect may change that it does not count: its own table when its rows were not counted, and when its
47
+ * rows go and were not all followed, every table whose rows point at them.
48
+ */
49
+ export declare function tablesNotChecked(effect: DeleteEffect, model: SchemaModel): string[];
50
+ type Key = string | number;
51
+ /**
52
+ * The schema model, and what deleting the selected rows does to the rows that point at them and are not selected, and
53
+ * through a cascade to the rows that point at those, each row followed once, over at most 500 rows read: one
54
+ * effect for each table, kind of effect and table it points at, with the union of the columns. A search chunk table the
55
+ * backend keeps is left out, because its rows always go with their parent row. A table with no rows there gives none.
56
+ */
57
+ export declare function deleteEffects(ready: AppReady, selected: ReadonlyArray<{
58
+ tableName: string;
59
+ keys: readonly Key[];
60
+ }>): Promise<Result<{
61
+ model: SchemaModel;
62
+ effects: DeleteEffect[];
63
+ }>>;
64
+ export {};