diff --git a/agentic/cli/README.md b/agentic/cli/README.md index 02eb1464da..f55376e50e 100644 --- a/agentic/cli/README.md +++ b/agentic/cli/README.md @@ -26,7 +26,7 @@ On startup, `agent` assembles the harness skill tree and drops you into an inter 1. **Base layer** — [`constructive-io/constructive-skills`](https://github.com/constructive-io/constructive-skills), fetched as a git tag/branch/SHA tarball into `~/.constructive/data/skills//` (default ref: `main`; offline fallback: newest cached release). 2. **Local overlay** — `~/.constructive/config/skills-overlay//SKILL.md` (agentskills.io layout), highest precedence: a same-name skill replaces the base skill wholesale. -3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, and `run_codegen`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records`, `update_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools. +3. **Typed db tools** — the [`@agentic-kit/pi`](https://www.npmjs.com/package/@agentic-kit/pi) extension (including `provision_database`, `provision_blueprint`, `describe_schema`, and `run_codegen`) is materialized into the agent dir and loaded by pi automatically. The CLI does not register `add_records`, `update_records`, `delete_records` or `create_api_key`; it has no tenant sign-in or secret-delivery integration for those tools. The merged tree is materialized into the appstash-owned agent dir, so the session picks the skills up natively. All harness state lives in the [appstash](https://github.com/constructive-io/appstash) `~/.constructive/` layout; project directories are untouched. diff --git a/agentic/cli/__tests__/db-tools.test.ts b/agentic/cli/__tests__/db-tools.test.ts index 933ccaa596..fdba1f86f0 100644 --- a/agentic/cli/__tests__/db-tools.test.ts +++ b/agentic/cli/__tests__/db-tools.test.ts @@ -57,8 +57,9 @@ describe('materializeDbTools', () => { expect(registered).toContain('provision_database'); expect(registered).not.toContain('add_records'); expect(registered).not.toContain('update_records'); + expect(registered).not.toContain('delete_records'); expect(registered).not.toContain('create_api_key'); - const excluded = ['add_records', 'update_records', 'create_api_key']; + const excluded = ['add_records', 'update_records', 'delete_records', 'create_api_key']; const expected = constructiveDbTools.map((tool) => tool.name).filter((name) => !excluded.includes(name)); expect(registered.sort()).toEqual(expected.sort()); }); diff --git a/agentic/cli/src/db-tools.ts b/agentic/cli/src/db-tools.ts index 19e0c41728..021f1d0253 100644 --- a/agentic/cli/src/db-tools.ts +++ b/agentic/cli/src/db-tools.ts @@ -36,7 +36,7 @@ module.exports = createDbTools({ account: resolveAccount, backendConfig: resolveBackendConfig, signInHint: 'Run \`agent login\` to sign in.' -}, { excludeTools: ['add_records', 'update_records', 'create_api_key'] }); +}, { excludeTools: ['add_records', 'update_records', 'delete_records', 'create_api_key'] }); `; } diff --git a/agentic/db-tools/README.md b/agentic/db-tools/README.md index c73c53a1dd..1dd6e8c01a 100644 --- a/agentic/db-tools/README.md +++ b/agentic/db-tools/README.md @@ -27,11 +27,11 @@ npm install @agentic-kit/db-tools ## What's inside -- **26 typed db tools** — `provision_database` / `replace_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `retype_field` / `delete_field`, `add_policies`, `add_records` / `update_records`, `list_entity_types` / `create_entity_type` / `delete_entity_type`, `create_api_key`, `run_codegen`, the template suite (`list` / `create` / `apply` / `update` / `delete`), the access tools (`explain_access`, `set_access`), and `describe_policy_type`. `constructiveDbTools` is the list, in registration order. Each states one effect (`read`, `write` or `destructive`) for every call; a change whose effect differs is its own tool (`retype_field` beside `update_field`, `replace_database` beside `provision_database`). Every failing call returns a `failure` (code, message, hint) beside the `details` it always had. A message or hint names no tool and no parameter: the calls that help travel as data (`failure.calls`, `result.calls`). Every object of a tool's own input refuses a key it does not have and names the nearest known one, instead of dropping it; Every change that names a table, a field, a template or an entity type finds it, or finds a new name's stored form free, before there is a plan to approve. A call that did only part of what was asked (a field without its unique constraint, some of the rows) returns the code `partial`, and its `details` hold the errors of the part that failed. Backend errors are read by their `extensions.code` and `extensions.class`, then the HTTP status (`extensions.http` first: the server answers HTTP 200 and puts the status there), then a masked internal error with its `errorId`; message text never decides, because the server masks the text it does not mean to show. `failureFromErrors(errors, action, meaning?)` is that mapping, exported for code that sends its own GraphQL (`postGraphQL`, which takes an `operationName`), and `FailureMeaning` names what a unique violation means for the call. +- **27 typed db tools** — `provision_database` / `replace_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `retype_field` / `delete_field`, `add_policies`, `add_records` / `update_records` / `delete_records`, `list_entity_types` / `create_entity_type` / `delete_entity_type`, `create_api_key`, `run_codegen`, the template suite (`list` / `create` / `apply` / `update` / `delete`), the access tools (`explain_access`, `set_access`), and `describe_policy_type`. `constructiveDbTools` is the list, in registration order. Each states one effect (`read`, `write` or `destructive`) for every call; a change whose effect differs is its own tool (`retype_field` beside `update_field`, `replace_database` beside `provision_database`). Every failing call returns a `failure` (code, message, hint) beside the `details` it always had. A message or hint names no tool and no parameter: the calls that help travel as data (`failure.calls`, `result.calls`). Every object of a tool's own input refuses a key it does not have and names the nearest known one, instead of dropping it; Every change that names a table, a field, a template or an entity type finds it, or finds a new name's stored form free, before there is a plan to approve. A call that did only part of what was asked (a field without its unique constraint, some of the rows) returns the code `partial`, and its `details` hold the errors of the part that failed. Backend errors are read by their `extensions.code` and `extensions.class`, then the HTTP status (`extensions.http` first: the server answers HTTP 200 and puts the status there), then a masked internal error with its `errorId`; message text never decides, because the server masks the text it does not mean to show. `failureFromErrors(errors, action, meaning?)` is that mapping, exported for code that sends its own GraphQL (`postGraphQL`, which takes an `operationName`), and `FailureMeaning` names what a unique violation means for the call. The public `extensions.context` of the error that decided goes into `failure.context`: a query over the backend's request limits (`QUERY_TOO_COSTLY`, `QUERY_TOO_DEEP`, `PAGE_SIZE_TOO_LARGE`, `REQUEST_TOO_LARGE`) is `query-too-large` with its numbers there, for example `{ cost, limit }`. An update or delete that answers with no row in its payload changed nothing: that is how row-level security answers for a row this account cannot see, so every tool that updates or deletes fails `no-rows-changed` there instead of reporting success. A create that answers without the new row fails `no-rows-changed` as well: the row may not exist, or a policy lets the account create it but not read it, and the hint names the call that shows whether it exists. `STEP_UP_REQUIRED` is `step-up-required`: the change needs a recent sign-in. - `constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. + `constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. For `delete_records` the check resolves the exact rows once, as the person signed in to the app: each table's rows by key, by column values (`where`), its sample rows still there, or all its rows, at most 500 in all, ordered so a row goes before the rows it points at, with what the delete does to the rows it does not select: the rows that point at them, counted on the app API by the foreign keys and followed through each cascade (search chunk tables left out). The target names those rows (`rows`) and the card's preview shows them (`delete-records`). The tool then deletes only the rows the approved target names (`takeApprovedTable`). When a host leaves tables out of the target, the tool counts the effects of the approved rows again first, and deletes nothing when they would delete, clear or be blocked by rows of a table the person kept, or when it can't count or follow the rows that could reach one (too many related rows, a table with no single-column key, a key it can't read). **Access.** The access of a table is its stored rules, grants and row security (`readTables`), and nothing here says who can or cannot reach a row. `explain_access` gives one plain sentence per stored rule (`explainPolicy`, from the words of the rule's Authz node), the grants, row security and the structural findings (`accessFindings`), each of which says what may happen. It and `describe_schema` return each stored rule through `asWritten`, in the one shape a caller writes (`{ $type, privileges, permissive, policy_role, data, with_check? }`), with every key the node's closed `parameter_schema` marks `readOnly` left out, nested nodes included, so a read carries no part the closed world refuses. A plan's rules use the same keys, with `words` in place of `data`. `set_access` replaces every rule of a table in one change with `owns: ['policies']`; the grants stay, and the Data nodes the rules need add their columns when the table lacks them. `add_policies` adds rules without replacing any. Both take rules only in the registry's blueprint shape (`{ $type, privileges, permissive, policy_role, policy_name, data }`, `AccessPolicyZod`), check each rule's shape against the registry's `BlueprintPolicy`, and check its data with `checkRule` (ajv over the node's closed `parameter_schema`, and the rule shapes these tools do not support) and its role before any plan. Every tool that sends rules, `provision_blueprint` included, sends them through `rulesToSend`: rules of one policy type, role, kind and data become one rule with all their privileges, and a rule the backend would skip (the same policy type and data as another) or refuse (a second policy row of one role, privilege and name) is refused before the plan. The plan holds the rules, grants and row security now and after, one sentence per rule, the findings the change adds and removes, the columns it adds (name, type, required, default) and the ones it reuses as they are. A reused column of another type than its Data node needs is blocked before the change (`conflict`, with `retype_field` and `delete_field`). When the person signed in to the app sees a row, a change that adds a required column with no value for the rows is blocked before anything is sent; otherwise the backend's refused NOT NULL comes back as a `conflict` with the `create_field` call that adds the column as optional first. After the change, the table is read back and compared with the plan by meaning (`policyDifference`); a difference is a `conflict`, and a read that fails is `unverified`. A refusal on the rows of an app table (`add_records`) suggests the read of its rules; a refusal on the control plane does not, because it is about the account's rights on the database. @@ -76,7 +76,7 @@ const result = await describeSchemaTool.execute({ database_name: 'my-app' }, { c Only `missing` means the database is gone. On a backend without `hash`, the probe retries once without it and `hash` is undefined. `resolveProjectContext` reports the same states as `db-missing`, `db-suspended`, `account-mismatch` and `backend-unreachable` (with `cause`), and a resolved context carries `hash`. -Tenant APIs answer `ACCESS_SUSPENDED` (a 403 with a JSON body) for a deleted or suspended database. The SDK's `FetchAdapter` drops that body, so `postGraphQL` and `statusAdapter` (a drop-in ORM adapter) keep each error's `extensions.code` and HTTP status, and `classifyBackendErrors` sorts them into `suspended`, `network`, `server`, `auth`, `forbidden` or `graphql`. `add_records`, `run_codegen` and `create_api_key` return `details.code: 'database-unavailable'` on `ACCESS_SUSPENDED`, and `run_codegen` doesn't retry a refused introspection. +Tenant APIs answer `ACCESS_SUSPENDED` (a 403 with a JSON body) for a deleted or suspended database. The SDK's `FetchAdapter` drops that body, so `postGraphQL` and `statusAdapter` (a drop-in ORM adapter) keep each error's `extensions.code` and HTTP status, and `classifyBackendErrors` sorts them into `suspended`, `network`, `server`, `auth`, `forbidden` or `graphql`. `add_records`, `update_records`, `delete_records`, `run_codegen` and `create_api_key` return `details.code: 'database-unavailable'` on `ACCESS_SUSPENDED`, and `run_codegen` doesn't retry a refused introspection. ## The live schema diff --git a/agentic/db-tools/__tests__/delete-records.test.ts b/agentic/db-tools/__tests__/delete-records.test.ts new file mode 100644 index 0000000000..bb72adc38b --- /dev/null +++ b/agentic/db-tools/__tests__/delete-records.test.ts @@ -0,0 +1,339 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { type GateReadiness, rememberApprovedTable } from '@agentic-kit/harness'; + +import { constructiveGateDeps } from '../src/gate'; +import { configureHost, type ToolsHost } from '../src/host'; +import { deleteRecordsTool } from '../src/tools/delete-records'; +import { DATABASE_ID, type FakeBackend, type GraphQLAnswer, projectAnswer, startFakeBackend } from './fake-backend'; + +const field = (name: string, columnName: string, extra: Record = {}) => ({ + name, + columnName, + type: { gqlType: name === 'id' || name.endsWith('Id') ? 'UUID' : 'String', isArray: false }, + ...extra, +}); + +const appTable = (name: string, tableName: string, all: string, fields: ReturnType[]) => ({ + name, + tableName, + query: { all, one: name.toLowerCase(), create: `create${name}`, update: `update${name}`, delete: `delete${name}` }, + inflection: { tableType: name }, + fields: [field('id', 'id', { isPrimaryKey: true }), ...fields], +}); + +// The app's own API: contacts and notes point at companies. +const BASE_TABLES = [ + appTable('Company', 'companies', 'companies', [field('name', 'name')]), + appTable('Contact', 'contacts', 'contacts', [field('name', 'name'), field('companyId', 'company_id')]), + appTable('Note', 'notes', 'notes', [field('body', 'body'), field('companyId', 'company_id'), field('contactId', 'contact_id')]), + appTable('Deal', 'deals', 'deals', [field('name', 'name'), field('stage', 'stage')]), +]; + +// The metaschema, as the account reads it: a contact keeps its company (restrict), and a note goes with it (cascade). +const fk = (tableId: string, deleteAction: string, fieldIds = ['f-company'], refTableId = 't-companies') => + ({ id: `fk-${tableId}-${fieldIds.join('-')}`, tableId, fieldIds, refTableId, refFieldIds: ['f-id'], deleteAction, updateAction: 'a' }); +const BASE_MODEL: Record = { + databases: [{ id: DATABASE_ID, hash: 'h' }], + tables: ['companies', 'contacts', 'notes', 'deals'].map((name) => ({ id: `t-${name}`, name, category: 'APP' })), + fields: [ + { id: 'f-company', name: 'company_id', tableId: 't-contacts' }, + { id: 'f-entity', name: 'entity_id', tableId: 't-contacts' }, + { id: 'f-contact', name: 'contact_id', tableId: 't-notes' }, + { id: 'f-id', name: 'id', tableId: 't-companies' }, + ], + primaryKeyConstraints: [], + uniqueConstraints: [], + checkConstraints: [], + foreignKeyConstraints: [fk('t-contacts', 'r'), fk('t-notes', 'c')], + policies: [], + embeddingChunks: [], +}; +let MODEL: Record; + +let TABLES: typeof BASE_TABLES; +let rows: Record[]>; + +const rootField = (query: string) => query.match(/\{\s*(\w+)/)?.[1] ?? ''; + +function matches(row: Record, where: Record> | undefined): boolean { + return Object.entries(where ?? {}).every(([name, test]) => + 'equalTo' in test ? row[name] === test.equalTo : 'in' in test ? (test.in as unknown[]).includes(row[name]) : row[name] == null); +} + +function appBackend(query: string, variables: Record): GraphQLAnswer { + if (/DbToolsMeta/.test(query)) return { data: { _meta: { tables: TABLES } } }; + const root = rootField(query); + if (/^mutation/.test(query.trim())) { + const table = TABLES.find((candidate) => candidate.query.delete === root)!; + const list = rows[table.tableName]; + const at = list.findIndex((row) => row.id === (variables.input as { id: unknown }).id); + if (at < 0) return { data: null, errors: [{ message: 'No values were deleted.' }] }; + list.splice(at, 1); + return { data: { [root]: { clientMutationId: null } } }; + } + const table = TABLES.find((candidate) => candidate.query.all === root)!; + const found = rows[table.tableName].filter((row) => matches(row, variables.where as never)); + return { data: { [root]: { totalCount: found.length, nodes: found.slice(0, variables.first as number) } } }; +} + +let cwd: string; +let backend: FakeBackend; + +const host = (extra: Partial = {}): ToolsHost => ({ + account: () => ({ userId: 'ME', accessToken: 'account-bearer' }), + backendConfig: () => ({ apiEndpoint: backend.endpoint(), modulesEndpoint: backend.endpoint('modules.localhost') }), + previewToken: async () => ({ accessToken: 'app-user-token', userId: 'U1' }), + ...extra, +}); + +beforeEach(async () => { + MODEL = structuredClone(BASE_MODEL); + TABLES = structuredClone(BASE_TABLES); + rows = { + companies: [{ id: 'k1', name: 'Acme' }], + contacts: [{ id: 'c1', name: 'Ada', companyId: 'k1' }, { id: 'c2', name: 'Bo', companyId: 'k1' }], + notes: [], + deals: [], + people: [], + }; + cwd = mkdtempSync(path.join(os.tmpdir(), 'db-delete-records-')); + writeFileSync(path.join(cwd, '.env'), `DATABASE_ID=${DATABASE_ID}\nDATABASE_NAME=mydb\n`); + backend = await startFakeBackend(({ host: to, query, variables }) => { + const project = projectAnswer(query, 'ME'); + if (project) return project; + if (to.startsWith('api-mydb.')) return appBackend(query, variables); + const root = rootField(query); + return { data: { [root]: { nodes: MODEL[root] ?? [] } } }; + }); + configureHost(host()); +}); +afterEach(async () => { + rmSync(cwd, { recursive: true, force: true }); + await backend.close(); +}); + +const appRequests = () => backend.requests.filter((request) => request.host.startsWith('api-mydb.') && !/DbToolsMeta/.test(request.query)); +const precondition = (tables: Record[]) => constructiveGateDeps().precondition('delete_records', { tables }, cwd); +const ready = (readiness: GateReadiness) => { + if (readiness.kind !== 'ready') throw new Error(`blocked: ${readiness.failure.message}`); + return readiness; +}; + +describe('delete_records resolution', () => { + it('orders the tables so a row goes before the rows it points at, names the keys between them, and counts what it does to rows the call leaves out', async () => { + rows.notes = [{ id: 'n1', body: 'Call back', companyId: 'k1' }]; + const { target, preview } = ready(await precondition([{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }])); + + expect(target).toMatchObject({ rows: [{ tableName: 'contacts', keys: ['c1', 'c2'] }, { tableName: 'companies', keys: ['k1'] }] }); + expect(preview).toMatchObject({ + kind: 'delete-records', + tables: [{ tableName: 'contacts', count: 2 }, { tableName: 'companies', count: 1 }], + effects: ['Also deletes 1 notes row that points at the companies you delete.'], + links: [{ parent: 'companies', child: 'contacts', effect: 'restrict' }], + }); + }); + + it('says nothing about a search chunk table the backend keeps for a listed table', async () => { + MODEL.tables.push({ id: 't-companies_chunks', name: 'companies_chunks', category: 'APP' }); + MODEL.foreignKeyConstraints.push(fk('t-companies_chunks', 'c')); + MODEL.embeddingChunks = [{ id: 'ec-1', tableId: 't-companies', chunksTableId: 't-companies_chunks' }]; + rows.notes = [{ id: 'n1', body: 'Call back', companyId: 'k1' }]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }])); + + expect(preview).toMatchObject({ effects: ['Also deletes 1 notes row that points at the companies you delete.'] }); + }); + + it('gives one line for each table, kind of effect and table it points at, with only the columns the keys clear', async () => { + // The backend's scoped key: (company_id, entity_id) references companies, and a delete sets only company_id to null. + MODEL.foreignKeyConstraints = [fk('t-contacts', 'n'), { ...fk('t-contacts', 'n', ['f-company', 'f-entity']), deleteSetFieldIds: ['f-company'] }]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }])); + + expect(preview).toMatchObject({ effects: ['Clears company_id on 2 contacts rows that point at the companies you delete.'] }); + }); + + it('counts the rows of a named table that point at the rows it deletes but are not selected', async () => { + MODEL.foreignKeyConstraints = [fk('t-contacts', 'c')]; + + const { preview } = ready(await precondition([{ table_name: 'companies', rows: ['k1'] }, { table_name: 'contacts', rows: ['c1'] }])); + + expect(preview).toMatchObject({ effects: ['Also deletes 1 contacts row that points at the companies you delete.'] }); + }); + + it('follows a cascade through a table the call does not name', async () => { + MODEL.foreignKeyConstraints = [fk('t-contacts', 'c'), fk('t-notes', 'c', ['f-contact'], 't-contacts')]; + rows.notes = [{ id: 'n1', body: 'Call back', contactId: 'c1' }]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }])); + + expect(preview).toMatchObject({ + effects: ['Also deletes 2 contacts rows that point at the companies you delete.', 'Also deletes 1 notes row that points at the contacts you delete.'], + }); + }); + + it('counts the rows of a table with no single-column key, and says the rows that point at those are not counted', async () => { + TABLES.push({ + ...appTable('Membership', 'memberships', 'memberships', []), + fields: [field('companyId', 'company_id', { isPrimaryKey: true }), field('userId', 'user_id', { isPrimaryKey: true })], + }); + rows.memberships = [{ companyId: 'k1', userId: 'u1' }, { companyId: 'k1', userId: 'u2' }]; + MODEL.tables.push({ id: 't-memberships', name: 'memberships', category: 'APP' }, { id: 't-membership_logs', name: 'membership_logs', category: 'APP' }); + MODEL.fields.push({ id: 'f-member-company', name: 'company_id', tableId: 't-memberships' }); + MODEL.foreignKeyConstraints = [fk('t-memberships', 'c', ['f-member-company']), { ...fk('t-membership_logs', 'c', []), refTableId: 't-memberships' }]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }])); + + expect(preview).toMatchObject({ + effects: ['Also deletes 2 memberships rows that point at the companies you delete, and the rows that point at those go too, not counted.'], + }); + }); + + it('counts the rows whose key points at a unique column of the deleted rows that is not their primary key', async () => { + TABLES.find((table) => table.tableName === 'companies')!.fields.push(field('code', 'code')); + TABLES.find((table) => table.tableName === 'contacts')!.fields.push(field('companyCode', 'company_code')); + rows.companies = [{ id: 'k1', name: 'Acme', code: 'ACME' }]; + rows.contacts = [{ id: 'c1', name: 'Ada', companyCode: 'ACME' }, { id: 'c2', name: 'Bo', companyCode: 'OTHER' }]; + MODEL.fields.push({ id: 'f-code', name: 'code', tableId: 't-companies' }, { id: 'f-company-code', name: 'company_code', tableId: 't-contacts' }); + MODEL.foreignKeyConstraints = [{ ...fk('t-contacts', 'c', ['f-company-code']), refFieldIds: ['f-code'] }]; + + const { preview } = ready(await precondition([{ table_name: 'companies', rows: ['k1'] }])); + + expect(preview).toMatchObject({ effects: ['Also deletes 1 contacts row that points at the companies you delete.'] }); + }); + + it('counts the rows a set-default key changes', async () => { + MODEL.foreignKeyConstraints = [fk('t-contacts', 'd')]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }])); + + expect(preview).toMatchObject({ effects: ['Sets company_id to its default on 2 contacts rows that point at the companies you delete.'] }); + }); + + it('does not count a table with no single-column key that has two keys to the deleted table', async () => { + TABLES.push({ + ...appTable('Pairing', 'pairings', 'pairings', []), + fields: [field('sourceId', 'source_id', { isPrimaryKey: true }), field('targetId', 'target_id', { isPrimaryKey: true })], + }); + rows.pairings = [{ sourceId: 'k1', targetId: 'k9' }, { sourceId: 'k9', targetId: 'k1' }]; + MODEL.tables.push({ id: 't-pairings', name: 'pairings', category: 'APP' }); + MODEL.fields.push({ id: 'f-source', name: 'source_id', tableId: 't-pairings' }, { id: 'f-target', name: 'target_id', tableId: 't-pairings' }); + MODEL.foreignKeyConstraints = [fk('t-pairings', 'c', ['f-source']), fk('t-pairings', 'c', ['f-target'])]; + + const { preview } = ready(await precondition([{ table_name: 'companies', all: true }])); + + expect(preview).toMatchObject({ effects: ['Deleting companies may also change the pairings rows that point at them (not counted).'] }); + }); + + it('takes the sample rows the build seeded that are still there, and notes a table with none left', async () => { + configureHost(host({ seededRows: async () => ({ deals: ['d1', 'd2', null], companies: [] }) })); + rows.deals = [{ id: 'd1', name: 'Arcadia' }, { id: 'd3', name: 'Added by hand' }]; + + const { target, notes } = ready(await precondition([{ table_name: 'deals', sample: true }, { table_name: 'companies', sample: true }])); + + expect(target).toMatchObject({ rows: [{ tableName: 'deals', keys: ['d1'] }] }); + expect(notes).toEqual(['companies has no sample rows left.']); + }); + + it('refuses a where column that is not there, with the nearest column, before it reads any row', async () => { + const result = await deleteRecordsTool.execute({ tables: [{ table_name: 'deals', where: { stag: 'won' } }] }, { cwd }); + + expect(result.failure).toMatchObject({ code: 'invalid-input', message: 'The where of deals names "stag", which is not a column of deals: use "stage".' }); + expect(appRequests()).toEqual([]); + }); + + it('refuses more than 500 rows over all the tables', async () => { + rows.companies = Array.from({ length: 300 }, (_, index) => ({ id: `k${index}`, name: `Company ${index}` })); + rows.contacts = Array.from({ length: 201 }, (_, index) => ({ id: `c${index}`, name: `Contact ${index}` })); + + const readiness = await precondition([{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }]); + + expect(readiness).toMatchObject({ kind: 'blocked', failure: { code: 'invalid-input', message: expect.stringMatching(/^The call selects 501 rows in all, more than the 500 one call deletes: narrow it/) } }); + }); +}); + +describe('delete_records', () => { + it('deletes nothing without an approved target, as when the approval expired', async () => { + const result = await deleteRecordsTool.execute({ tables: [{ table_name: 'contacts', all: true }] }, { cwd, toolCallId: 'tc-expired' }); + + expect(result.failure).toMatchObject({ + message: 'This delete has no approval (it may have expired), so nothing was deleted. Ask again to see the rows and approve them.', + }); + expect(rows.contacts.map((row) => row.id)).toEqual(['c1', 'c2']); + }); + + it('deletes from the table the card named, when another table goes by that name on the app API', async () => { + // people's API collection is called contacts; contacts' own collection is called contactRows. + TABLES.unshift(appTable('Person', 'people', 'contacts', [field('name', 'name')])); + TABLES.find((table) => table.tableName === 'contacts')!.query.all = 'contactRows'; + rows.people = [{ id: 'c1', name: 'Same key, other table' }]; + const tables = [{ table_name: 'contact_rows', all: true as const }]; + const { target } = ready(await precondition(tables)); + rememberApprovedTable('tc-1', cwd, target); + + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + + expect(result.failure).toBeUndefined(); + expect(rows.contacts).toEqual([]); + expect(rows.people.map((row) => row.id)).toEqual(['c1']); + }); + + it('deletes nothing when the rows it would delete reach rows of a table the person kept', async () => { + MODEL.foreignKeyConstraints = [fk('t-contacts', 'c')]; + const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'contacts', all: true as const }]; + const { target } = ready(await precondition(tables)); + if (target.kind !== 'database') throw new Error('not a database target'); + rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }); + + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + + expect(result.failure).toMatchObject({ + code: 'conflict', + message: "You kept contacts, but 2 contacts rows point at companies you'd delete, and deleting companies deletes them too. Approve again with contacts ticked, or keep companies too.", + }); + expect(rows.companies.map((row) => row.id)).toEqual(['k1']); + expect(rows.contacts.map((row) => row.id)).toEqual(['c1', 'c2']); + }); + + it('deletes nothing when there are too many related rows to check that a table the person kept stays untouched', async () => { + MODEL.foreignKeyConstraints = [fk('t-contacts', 'c'), fk('t-notes', 'c', ['f-contact'], 't-contacts')]; + rows.contacts = Array.from({ length: 502 }, (_, index) => ({ id: `c${index}`, name: `Contact ${index}`, companyId: 'k1' })); + rows.notes = [{ id: 'n1', body: 'Call back', contactId: 'c0' }]; + const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'notes', all: true as const }]; + const { target } = ready(await precondition(tables)); + if (target.kind !== 'database') throw new Error('not a database target'); + rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'companies') }); + + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + + expect(result.failure).toMatchObject({ + code: 'conflict', + message: 'Nothing was deleted: there are too many related rows to check that notes stays untouched. Delete in smaller steps, or tick notes.', + }); + expect(rows.companies.map((row) => row.id)).toEqual(['k1']); + }); + + it('deletes only the rows of the approved target, and leaves a table the person unticked alone', async () => { + const tables = [{ table_name: 'companies', all: true as const }, { table_name: 'contacts', all: true as const }]; + const { target } = ready(await precondition(tables)); + if (target.kind !== 'database') throw new Error('not a database target'); + rememberApprovedTable('tc-1', cwd, { ...target, rows: target.rows!.filter((entry) => entry.tableName === 'contacts') }); + // A row added after the card was approved is not one the person saw. + rows.contacts.push({ id: 'c3', name: 'Cy', companyId: 'k1' }); + + const result = await deleteRecordsTool.execute({ tables }, { cwd, toolCallId: 'tc-1' }); + + expect(result.failure).toBeUndefined(); + expect(rows.contacts.map((row) => row.id)).toEqual(['c3']); + expect(rows.companies.map((row) => row.id)).toEqual(['k1']); + expect(result.details).toEqual({ + success: true, + message: 'Deleted 2 rows from contacts. Nothing was deleted from companies: the person unticked it, or it had no rows to delete.', + deletedCount: 2, + tables: [{ tableName: 'contacts', deleted: 2, failed: [] }, { tableName: 'companies', deleted: 0, kept: true, failed: [] }], + }); + }); +}); diff --git a/agentic/db-tools/__tests__/host.test.ts b/agentic/db-tools/__tests__/host.test.ts index ddcd5c08bc..a3ad8c0b30 100644 --- a/agentic/db-tools/__tests__/host.test.ts +++ b/agentic/db-tools/__tests__/host.test.ts @@ -50,7 +50,7 @@ describe('toolSchema', () => { }); describe('constructiveDbTools', () => { - it('is the 25 db tools, harness-neutral', () => { + it('is the 27 db tools, harness-neutral', () => { expect(constructiveDbTools.map((tool) => tool.name)).toEqual([ 'provision_database', 'replace_database', @@ -70,6 +70,7 @@ describe('constructiveDbTools', () => { 'delete_template', 'add_records', 'update_records', + 'delete_records', 'list_entity_types', 'create_entity_type', 'delete_entity_type', diff --git a/agentic/db-tools/__tests__/schema-checks.test.ts b/agentic/db-tools/__tests__/schema-checks.test.ts index 6d36d47252..a83e82ffee 100644 --- a/agentic/db-tools/__tests__/schema-checks.test.ts +++ b/agentic/db-tools/__tests__/schema-checks.test.ts @@ -214,6 +214,7 @@ describe('no plan for a change that cannot work', () => { ['add_relation', { source_table: 'no_such_table', target_table: 'users', field_name: 'owner_id' }, 'not-found', 'Table "no_such_table" not found'], ['add_records', { table_name: 'no_such_table', records: [{ title: 'x' }] }, 'not-found', 'Table "no_such_table" was not found in the app database'], ['update_records', { table_name: 'no_such_table', records: [{ id: 'x', title: 'x' }] }, 'not-found', 'Table "no_such_table" was not found in the app database'], + ['delete_records', { tables: [{ table_name: 'no_such_table', all: true }] }, 'not-found', 'Table "no_such_table" was not found in the app database'], [ 'provision_blueprint', { diff --git a/agentic/db-tools/__tests__/tool-contract.test.ts b/agentic/db-tools/__tests__/tool-contract.test.ts index e472103bb2..b95fccc33d 100644 --- a/agentic/db-tools/__tests__/tool-contract.test.ts +++ b/agentic/db-tools/__tests__/tool-contract.test.ts @@ -58,6 +58,7 @@ const CALLS: [string, Record, ToolEffect][] = [ ['delete_template', { templateName: 'CRM' }, 'destructive'], ['add_records', { table_name: 'posts', records: [{ title: 'Hello' }] }, 'write'], ['update_records', { table_name: 'posts', records: [{ id: UUID, title: 'Hello' }] }, 'write'], + ['delete_records', { tables: [{ table_name: 'posts', sample: true }] }, 'write'], ['list_entity_types', {}, 'read'], ['create_entity_type', { name: 'team' }, 'write'], ['delete_entity_type', { entity_type_id: UUID }, 'destructive'], @@ -105,6 +106,7 @@ describe('the Constructive gate policy', () => { 'delete_template', 'add_records', 'update_records', + 'delete_records', 'create_entity_type', 'delete_entity_type', 'create_api_key', diff --git a/agentic/db-tools/src/host.ts b/agentic/db-tools/src/host.ts index 178a9cac94..53334e3eea 100644 --- a/agentic/db-tools/src/host.ts +++ b/agentic/db-tools/src/host.ts @@ -199,7 +199,8 @@ export interface ToolsHost { persistBinding?(binding: ProjectBinding): Promise; /** * The ids of the sample rows the host seeded into the project's database, by table name, in seed order (null for - * a row that did not land). A record value "@[]" in add_records or update_records names one of them. + * a row that did not land). A value "@
[]" in add_records, update_records or delete_records names one of them, and delete_records + * can delete every seeded row of a table that is still there. * A host that seeds no rows leaves it out, and such a value then fails. */ seededRows?(cwd: string): Promise> | null>; diff --git a/agentic/db-tools/src/records/delete-effects.ts b/agentic/db-tools/src/records/delete-effects.ts new file mode 100644 index 0000000000..394b57030c --- /dev/null +++ b/agentic/db-tools/src/records/delete-effects.ts @@ -0,0 +1,287 @@ +// What a records delete does to rows it does not select, counted on the app API as the person signed in to the app: +// the rows that point at the deleted rows, by the foreign keys the schema model reads. + +import { type DeleteRecordsLink, listed } from '@agentic-kit/harness'; +import { buildSelect, toCamelCasePlural } from '@constructive-io/graphql-query/generators'; + +import { failureFromError, failureFromErrors, type Result } from '../failure'; +import { type ModelForeignKey, readSchemaModel, type SchemaModel } from '../schema-model'; +import { cleanTable, type RawField, type RawMetaTable } from './meta'; +import { type AppReady, columnOf, fieldNamed, isSuspended, primaryKeyOf, UNAVAILABLE } from './rows'; + +/** The most rows one call deletes, over all its tables, and the most rows its effects read. */ +export const MAX_DELETED_ROWS = 500; + +/** The SQL name of an app table, as the person and the schema model name it. */ +export const sqlName = (table: RawMetaTable): string => table.tableName ?? table.name; + +type Connection = { totalCount?: number | null; nodes?: (Record | null)[] }; + +export type Read = { total: number; nodes: Record[] }; + +/** The first rows the filter selects, with the given fields, and how many it selects in all. */ +export async function readRows( + ready: AppReady, + { name, table }: { name: string; table: RawMetaTable }, + filter: Record | undefined, + select: string[], + first: number, +): Promise> { + const clean = cleanTable(table); + const variables = { first, ...(filter ? { where: filter } : {}) }; + const query = buildSelect(clean, ready.tables.map(cleanTable), { ...variables, fieldSelection: { select } }).toString(); + const action = `Failed to read the rows of ${name}`; + try { + const result = await ready.adapter.execute>(query, variables); + if (!result.ok) { + const failure = isSuspended(result.errors) + ? { code: 'database-unavailable' as const, message: `${UNAVAILABLE} No rows were deleted.` } + : failureFromErrors(result.errors, action, { rows: { table: name } }); + return { kind: 'failed', failure }; + } + const connection = result.data?.[toCamelCasePlural(clean.name, clean)]; + const nodes = (connection?.nodes ?? []).filter((node): node is Record => Boolean(node)); + return { kind: 'ok', value: { total: connection?.totalCount ?? nodes.length, nodes } }; + } catch (err) { + return { kind: 'failed', failure: failureFromError(err, action) }; + } +} + +export type Effect = 'cascade' | 'set_null' | 'set_default' | 'restrict'; + +const EFFECTS: Record = { + cascade: 'cascade', + set_null: 'set_null', + set_default: 'set_default', + restrict: 'restrict', + no_action: 'restrict', +}; + +/** + * Rows of `child` that point at rows of `parent` the delete removes and that the delete does not select: what happens + * to them, by which columns, how many there are, and how many of the parent rows they point at. `upTo` is set when + * there were more than the read could take: then the count is at most that many. `unfollowed` is set when the rows go + * and other rows point at them, but `child` has no single-column key to follow them by. `uncounted` is set when the + * rows cannot be read on the app API, or the values the key points at cannot be read from the deleted rows. + */ +export type DeleteEffect = { + parent: string; + child: string; + effect: Effect; + columns: string[]; + rows: number; + parents: number; + upTo?: number; + unfollowed?: true; + uncounted?: true; +}; + +export const rowsOf = (effect: DeleteEffect): string => { + const count = effect.upTo ?? effect.rows; + return `${effect.upTo ? 'up to ' : ''}${count} ${effect.child} row${count === 1 ? '' : 's'}`; +}; + +const one = (effect: DeleteEffect) => !effect.upTo && effect.rows === 1; + +/** "points" for one row, "point" for more. */ +export const pointOf = (effect: DeleteEffect): string => (one(effect) ? 'points' : 'point'); + +/** One plain line for the card. */ +export function effectLine(effect: DeleteEffect): string { + if (effect.uncounted) return `Deleting ${effect.parent} may also change the ${effect.child} rows that point at them (not counted).`; + const point = pointOf(effect); + switch (effect.effect) { + case 'cascade': { + const further = effect.unfollowed ? ', and the rows that point at those go too, not counted' : ''; + return `Also deletes ${rowsOf(effect)} that ${point} at the ${effect.parent} you delete${further}.`; + } + case 'set_null': + return `Clears ${listed(effect.columns)} on ${rowsOf(effect)} that ${point} at the ${effect.parent} you delete.`; + case 'set_default': { + const defaults = effect.columns.length === 1 ? 'its default' : 'their defaults'; + return `Sets ${listed(effect.columns)} to ${defaults} on ${rowsOf(effect)} that ${point} at the ${effect.parent} you delete.`; + } + case 'restrict': { + const parents = effect.upTo ? `Some ${effect.parent} rows` : `${effect.parents} ${effect.parent} row${effect.parents === 1 ? '' : 's'}`; + return `${parents} can't be deleted while ${rowsOf(effect)} ${point} at ${effect.parents === 1 && !effect.upTo ? 'it' : 'them'}.`; + } + } +} + +/** The foreign keys between the tables a delete names, one for each child, parent and effect, for the card to warn with. */ +export function linksOf(names: readonly string[], model: SchemaModel): DeleteRecordsLink[] { + const named = new Set(names); + const links = new Map(); + for (const child of model.tables.filter((table) => named.has(table.name))) { + for (const fk of child.foreignKeys) { + const effect = EFFECTS[fk.onDelete]; + if (fk.targetTable === child.name || !named.has(fk.targetTable)) continue; + // A set-default key loses its link the way a set-null key does, which is what the card warns about. + const link = effect === 'set_default' ? 'set_null' : effect; + links.set(JSON.stringify([fk.targetTable, child.name, link]), { parent: fk.targetTable, child: child.name, effect: link }); + } + } + return [...links.values()]; +} + +/** Every table whose rows point at rows of `table`, directly or through other tables. */ +function pointingAt(table: string, model: SchemaModel): Set { + const reached = new Set(); + const queue = [table]; + while (queue.length > 0) { + const parent = queue.shift()!; + for (const child of model.tables.filter((other) => other.foreignKeys.some((fk) => fk.targetTable === parent))) { + if (reached.has(child.name)) continue; + reached.add(child.name); + queue.push(child.name); + } + } + return reached; +} + +/** + * The tables an effect may change that it does not count: its own table when its rows were not counted, and when its + * rows go and were not all followed, every table whose rows point at them. + */ +export function tablesNotChecked(effect: DeleteEffect, model: SchemaModel): string[] { + const own = effect.uncounted ? [effect.child] : []; + const further: Iterable = effect.effect === 'cascade' && (effect.uncounted || effect.upTo || effect.unfollowed) ? pointingAt(effect.child, model) : []; + return [...new Set([...own, ...further])]; +} + +/** The ids of the search chunk tables the backend keeps for the database's tables (`embedding_chunks`). */ +async function chunkTableIds({ api, databaseId }: AppReady['context']): Promise> { + const data = await api.embeddingChunk + .findMany({ select: { chunksTableId: true }, where: { databaseId: { equalTo: databaseId } } }) + .unwrap(); + return new Set((data.embeddingChunks?.nodes ?? []).flatMap((node) => (node?.chunksTableId ? [node.chunksTableId] : []))); +} + +type Key = string | number; + +const isKey = (value: unknown): value is Key => typeof value === 'string' || typeof value === 'number'; + +/** + * The child field the key sets, and the values it has on the rows that point at the deleted parent rows: their keys, + * or for a key on another unique column, that column read from them. Null when the key cannot be read that way. + */ +async function linkValues( + ready: AppReady, + parent: { name: string; table: RawMetaTable; key: RawField }, + keys: readonly Key[], + fk: ModelForeignKey, + childTable: RawMetaTable, +): Promise> { + const at = fk.targetColumns.indexOf(columnOf(parent.key)); + if (at >= 0) { + const field = fieldNamed(childTable, fk.columns[at]); + return { kind: 'ok', value: field ? { field, values: [...keys] } : null }; + } + const target = fk.targetColumns.length === 1 ? fieldNamed(parent.table, fk.targetColumns[0]) : undefined; + const field = fieldNamed(childTable, fk.columns[0]); + if (!target || !field) return { kind: 'ok', value: null }; + const read = await readRows(ready, parent, { [parent.key.name]: { in: keys } }, [target.name], keys.length + 1); + if (read.kind === 'failed') return read; + return { kind: 'ok', value: { field, values: read.value.nodes.map((node) => node[target.name]).filter((value) => value !== null && value !== undefined) } }; +} + +type Found = { effect: DeleteEffect; rows: Set; keyless: number; parents: Set; columns: Set; uncounted?: true }; + +const entryOf = (parent: string, child: string, effect: Effect): Found => ({ + effect: { parent, child, effect, columns: [], rows: 0, parents: 0 }, + rows: new Set(), + keyless: 0, + parents: new Set(), + columns: new Set(), +}); + +/** + * The schema model, and what deleting the selected rows does to the rows that point at them and are not selected, and + * through a cascade to the rows that point at those, each row followed once, over at most 500 rows read: one + * effect for each table, kind of effect and table it points at, with the union of the columns. A search chunk table the + * backend keeps is left out, because its rows always go with their parent row. A table with no rows there gives none. + */ +export async function deleteEffects( + ready: AppReady, + selected: ReadonlyArray<{ tableName: string; keys: readonly Key[] }>, +): Promise> { + let model: SchemaModel; + let chunks: Set; + try { + [model, chunks] = await Promise.all([readSchemaModel(ready.context), chunkTableIds(ready.context)]); + } catch (err) { + return { kind: 'failed', failure: failureFromError(err, 'Failed to read the foreign keys of the project database') }; + } + const tables = new Map(ready.tables.map((table) => [sqlName(table), table])); + const going = new Map(selected.map(({ tableName, keys }) => [tableName, new Set(keys)])); + const queue = selected.map(({ tableName, keys }) => ({ parent: tableName, keys: [...keys] })); + const found = new Map(); + const pointedAt = (table: string) => model.tables.some((other) => !chunks.has(other.id) && other.foreignKeys.some((fk) => fk.targetTable === table)); + let budget = MAX_DELETED_ROWS; + + while (queue.length > 0) { + const { parent, keys } = queue.shift()!; + const parentTable = tables.get(parent); + const parentKey = parentTable && primaryKeyOf(parentTable); + if (!parentKey) continue; + for (const child of model.tables.filter((table) => !chunks.has(table.id))) { + const childTable = tables.get(child.name); + // Without a single-column key the rows are counted, but they cannot be told apart or followed further. + const childKey = childTable && primaryKeyOf(childTable); + const toParent = child.foreignKeys.filter((key) => key.targetTable === parent); + // Rows without a key cannot be told apart, so two keys to the parent could count one row twice. + const countable = childTable && (childKey || toParent.length === 1); + for (const fk of toParent) { + const effect = EFFECTS[fk.onDelete]; + const id = JSON.stringify([parent, child.name, effect]); + const link = countable ? await linkValues(ready, { name: parent, table: parentTable, key: parentKey }, keys, fk, childTable) : undefined; + if (link?.kind === 'failed') return link; + if (!childTable || !link?.value) { + found.set(id, { ...(found.get(id) ?? entryOf(parent, child.name, effect)), uncounted: true }); + continue; + } + const { field, values } = link.value; + if (values.length === 0) continue; + const select = childKey ? [childKey.name, field.name] : [field.name]; + const read = await readRows(ready, { name: child.name, table: childTable }, { [field.name]: { in: values } }, select, budget + 1); + if (read.kind === 'failed') return read; + budget = Math.max(0, budget - read.value.nodes.length); + const own = going.get(child.name); + const outside = childKey ? read.value.nodes.filter((node) => !own?.has(node[childKey.name] as Key)) : read.value.nodes; + const truncated = childKey !== undefined && read.value.total > read.value.nodes.length; + if (outside.length === 0 && !truncated) continue; + + const entry = found.get(id) ?? entryOf(parent, child.name, effect); + found.set(id, entry); + (fk.deleteSetColumns ?? fk.columns).forEach((column) => entry.columns.add(column)); + for (const node of outside) { + if (childKey && isKey(node[childKey.name])) entry.rows.add(node[childKey.name] as Key); + if (isKey(node[field.name])) entry.parents.add(node[field.name] as Key); + } + if (!childKey) { + entry.keyless += read.value.total; + if (effect === 'cascade' && pointedAt(child.name)) entry.effect.unfollowed = true; + continue; + } + if (truncated) { + // Past the read limit the count is only an upper bound, so this branch stops here. + entry.effect.upTo = Math.max(entry.effect.upTo ?? 0, read.value.total); + continue; + } + if (effect !== 'cascade') continue; + // The cascaded rows go too, so the rows that point at them are followed once each. + const cascaded = outside.map((node) => node[childKey.name]).filter(isKey); + going.set(child.name, new Set([...(own ?? []), ...cascaded])); + queue.push({ parent: child.name, keys: cascaded }); + } + } + } + const effects = [...found.values()].map(({ effect, rows, keyless, parents, columns, uncounted }) => ({ + ...effect, + columns: [...columns], + rows: rows.size + keyless, + parents: parents.size, + ...(uncounted ? { uncounted } : {}), + })); + return { kind: 'ok', value: { model, effects } }; +} diff --git a/agentic/db-tools/src/records/delete-selection.ts b/agentic/db-tools/src/records/delete-selection.ts new file mode 100644 index 0000000000..3fee3fdd9c --- /dev/null +++ b/agentic/db-tools/src/records/delete-selection.ts @@ -0,0 +1,186 @@ +// The rows a records delete removes, resolved once from the call's input as the person signed in to the app: the +// gate's precondition and the tool both use `deleteRecordsReady`, so the card and the delete cannot disagree. + +import { type DeleteRecordsLink, type DeleteRecordsTable, listed, nearestName } from '@agentic-kit/harness'; + +import { DESCRIBE_SCHEMA, explainAccessCall, type Result } from '../failure'; +import type { SchemaModel } from '../schema-model'; +import { deleteEffects, effectLine, linksOf, MAX_DELETED_ROWS, readRows, sqlName } from './delete-effects'; +import { findMetaTable, type RawField, type RawMetaTable } from './meta'; +import { type AppReady, appReady, fieldNamed, fieldsOf, invalid, isRowRef, notAColumn, primaryKeyOf, type SeededIds, seededIds, seededValue, tableKey } from './rows'; + +export type DeleteTableInput = { + table_name: string; + rows?: Array; + where?: Record; + sample?: true; + all?: true; +}; + +const SELECTORS = ['rows', 'where', 'sample', 'all'] as const; + +export type DeleteSelection = { tables: DeleteRecordsTable[]; effects: string[]; links: DeleteRecordsLink[] }; + +export type DeleteRecordsReady = AppReady & { + selection: DeleteSelection; + /** A table the input names that has no rows to delete, one sentence each. */ + notes: string[]; +}; + +type Picked = { input: DeleteTableInput; table: RawMetaTable; name: string; key: RawField }; + +/** The filter that selects the rows the input names, null when it names none, or why the input is not valid. */ +function filterOf({ input, table, name, key }: Picked, seeded: SeededIds): Result | undefined | null> { + if (input.rows) { + const keys = input.rows.map((value) => seededValue(value, seeded)); + const missing = input.rows.find((_, index) => keys[index] === undefined); + if (missing !== undefined) return invalid(`${name} names "${missing}", but no sample row was seeded there: use the row's ${key.columnName ?? key.name}.`); + return { kind: 'ok', value: { [key.name]: { in: keys } } }; + } + if (input.where) { + const unknown = notAColumn(table, name, Object.keys(input.where)); + if (unknown) return invalid(`The where of ${name} names ${unknown}`); + const filter: Record = {}; + for (const [column, given] of Object.entries(input.where)) { + const value = seededValue(given, seeded); + if (value === undefined) return invalid(`The where of ${name} names "${given}", but no sample row was seeded there: use the row's id.`); + filter[fieldNamed(table, column)!.name] = value === null ? { isNull: true } : { equalTo: value }; + } + return { kind: 'ok', value: filter }; + } + if (input.sample) { + const ids = (seeded.get(tableKey(name)) ?? seeded.get(tableKey(input.table_name)) ?? []).filter((id): id is string => Boolean(id)); + return { kind: 'ok', value: ids.length ? { [key.name]: { in: ids } } : null }; + } + return { kind: 'ok', value: undefined }; +} + +const NONE_LEFT = { + rows: (name: string) => `${name} has none of the rows given.`, + where: (name: string) => `${name} has no rows that match.`, + sample: (name: string) => `${name} has no sample rows left.`, + all: (name: string) => `${name} has no rows.`, +}; + +const selectorOf = (input: DeleteTableInput) => SELECTORS.find((selector) => input[selector] !== undefined) ?? 'all'; + +const READABLE_TYPES = new Set(['String', 'Int', 'Float', 'BigFloat', 'BigInt', 'Boolean', 'Date', 'Datetime']); + +/** Up to three columns that tell rows apart on the card, text first; keys of other rows say nothing to a person. */ +function readableFields(table: RawMetaTable, key: RawField): RawField[] { + return fieldsOf(table) + .filter((field) => field !== key && !field.type.isArray && READABLE_TYPES.has(field.type.gqlType) && !/Id$/.test(field.name)) + .sort((a, b) => Number(b.type.gqlType === 'String') - Number(a.type.gqlType === 'String')) + .slice(0, 3); +} + +/** The tables in an order that deletes a row before the rows it points at: each table before the listed tables it points at. */ +function childrenFirst(tables: readonly T[], model: SchemaModel): T[] { + const pointsAt = new Map(model.tables.map((table) => [table.name, new Set(table.foreignKeys.map((fk) => fk.targetTable))])); + const left = [...tables]; + const ordered: T[] = []; + while (left.length > 0) { + const pointedAt = (table: T) => left.some((other) => other !== table && pointsAt.get(other.tableName)?.has(table.tableName)); + // A cycle leaves no table that nothing points at, so the rest keep the order of the input. + const next = left.find((table) => !pointedAt(table)) ?? left[0]; + ordered.push(next); + left.splice(left.indexOf(next), 1); + } + return ordered; +} + +/** Every table the input names on the app API, once each, with a key the API deletes by. */ +function pickTables(tables: RawMetaTable[], inputs: readonly DeleteTableInput[]): Result { + const picked: Picked[] = []; + for (const input of inputs) { + const table = findMetaTable(tables, input.table_name); + if (!table) { + const nearest = nearestName(input.table_name, tables.map(sqlName)); + return { + kind: 'failed', + failure: { + code: 'not-found', + message: `Table "${input.table_name}" was not found in the app database${nearest ? `: use "${nearest}".` : '.'}`, + hint: 'Check the table names that exist, then retry.', + calls: [DESCRIBE_SCHEMA], + }, + }; + } + const name = sqlName(table); + const twice = picked.find((other) => other.table === table); + if (twice) return invalid(`The call names ${name} twice ("${twice.input.table_name}" and "${input.table_name}"): name each table once, with all its rows in one selection.`); + const key = primaryKeyOf(table); + if (!key) return { kind: 'failed', failure: { code: 'unsupported', message: `${name} has no single-column primary key, so its rows can't be named.` } }; + if (!table.query?.delete) { + return { + kind: 'failed', + failure: { + code: 'unsupported', + message: `The app API can't delete ${name} rows.`, + hint: 'The rules of the table may let no one delete rows: read them to see who they let delete.', + calls: [explainAccessCall(name)], + }, + }; + } + picked.push({ input, table, name, key }); + } + return { kind: 'ok', value: picked }; +} + +/** + * What a records delete checks before it deletes anything, and the exact rows it deletes: one selector for each + * table, the project, an app sign-in, each table on the app's API with a key and a delete, the rows each selector + * names that are there (no more than 500 in all), the order that deletes a row before the rows it points at, and + * what the delete does to the rows it does not select. + */ +export async function deleteRecordsReady(params: { tables: DeleteTableInput[] }, cwd: string): Promise> { + for (const input of params.tables) { + const given = SELECTORS.filter((selector) => input[selector] !== undefined); + if (given.length === 0) return invalid(`Nothing says which rows of ${input.table_name} to delete: give one of rows, where, sample or all.`); + if (given.length > 1) return invalid(`${input.table_name} gives ${listed(given)}: give only one of rows, where, sample and all.`); + if (input.where && Object.keys(input.where).length === 0) { + return invalid(`The where of ${input.table_name} names no column: give a column and the value its rows have, or use all for every row.`); + } + } + const ready = await appReady(cwd, 'deleted'); + if (ready.kind === 'failed') return ready; + const picked = pickTables(ready.value.tables, params.tables); + if (picked.kind === 'failed') return picked; + + const needsSeeded = params.tables.some((input) => input.sample || input.rows?.some(isRowRef) || Object.values(input.where ?? {}).some(isRowRef)); + const seeded = needsSeeded ? await seededIds(cwd) : ({ kind: 'ok', value: new Map() } as const); + if (seeded.kind === 'failed') return seeded; + + const tables: DeleteRecordsTable[] = []; + const notes: string[] = []; + let total = 0; + for (const pick of picked.value) { + const filter = filterOf(pick, seeded.value); + if (filter.kind === 'failed') return filter; + const select = [pick.key.name, ...readableFields(pick.table, pick.key).map((field) => field.name)]; + const read = filter.value === null + ? ({ kind: 'ok', value: { total: 0, nodes: [] } } as const) + : await readRows(ready.value, pick, filter.value, select, MAX_DELETED_ROWS + 1); + if (read.kind === 'failed') return read; + total += read.value.total; + const keys = read.value.nodes.map((node) => node[pick.key.name]).filter((key): key is string | number => typeof key === 'string' || typeof key === 'number'); + if (keys.length === 0) { + notes.push(NONE_LEFT[selectorOf(pick.input)](pick.name)); + continue; + } + const missing = new Set(pick.input.rows ?? []).size - keys.length; + if (missing > 0) notes.push(`${missing} of the rows given for ${pick.name} ${missing === 1 ? 'is' : 'are'} not there, so the delete leaves ${missing === 1 ? 'it' : 'them'} out.`); + tables.push({ tableName: pick.name, keyName: pick.key.name, keys, count: keys.length, rows: read.value.nodes.slice(0, 5) }); + } + if (total > MAX_DELETED_ROWS) { + return invalid(`The call selects ${total} rows in all, more than the ${MAX_DELETED_ROWS} one call deletes: narrow it with rows or where, or delete the tables in several calls.`); + } + if (tables.length === 0) return { kind: 'failed', failure: { code: 'not-found', message: notes.join(' ') } }; + + const found = await deleteEffects(ready.value, tables); + if (found.kind === 'failed') return found; + const { model, effects } = found.value; + const ordered = childrenFirst(tables, model); + const links = linksOf(ordered.map((table) => table.tableName), model); + return { kind: 'ok', value: { ...ready.value, selection: { tables: ordered, effects: effects.map(effectLine), links }, notes } }; +} diff --git a/agentic/db-tools/src/records/rows.ts b/agentic/db-tools/src/records/rows.ts index 0022149dbd..deffb51eaa 100644 --- a/agentic/db-tools/src/records/rows.ts +++ b/agentic/db-tools/src/records/rows.ts @@ -1,6 +1,6 @@ -// What add_records and update_records share: the app table a call names, read from the app API's `_meta` as the -// person signed in to the app; each record's keys as the API's field names, with "@
[]" as the id of a -// sample row the host seeded; and one write per row, with what each row's answer was. +// What the record tools share: the app tables, read from the app API's `_meta` as the person signed in to the app; +// each record's keys as the API's field names, with "@
[]" as the id of a sample row the host seeded; +// and one write per row, with what each row's answer was. import { type HarnessToolResult, listed, nearestName, type ToolFailure } from '@agentic-kit/harness'; import { toCamelCaseSingular } from '@constructive-io/graphql-query/generators'; @@ -68,40 +68,38 @@ const WORDS = { }, } as const; -const UNAVAILABLE = +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."; -const isSuspended = (errors: readonly GraphQLError[]) => classifyBackendErrors(errors) === 'suspended'; +export const isSuspended = (errors: readonly GraphQLError[]) => classifyBackendErrors(errors) === 'suspended'; -export function recordsFailed(failure: ToolFailure, extra: Partial = {}): HarnessToolResult { +type RecordsFlags = { success: boolean; message: string; needsAuth?: boolean; code?: 'database-unavailable' }; + +export function recordsFailed(failure: ToolFailure, extra: Partial> = {}): HarnessToolResult { const flag = failure.code === 'app-signed-out' ? { needsAuth: true } : failure.code === 'database-unavailable' ? { code: failure.code } : {}; - return failedResult(failure, { success: false, message: failureText(failure), ...flag, ...extra }); + return failedResult(failure, { success: false, message: failureText(failure), ...flag, ...extra } as D); } export const invalid = (message: string): Result => ({ kind: 'failed', failure: { code: 'invalid-input', message, calls: [DESCRIBE_SCHEMA] } }); -export type RecordsReady = { +/** The app's tables as the person signed in to the app sees them, and the API to reach them. */ +export type AppReady = { context: ProjectContext; token: string; userId?: string; /** The app's own API, as the person signed in to the app. */ adapter: ReturnType; tables: RawMetaTable[]; +}; + +export type RecordsReady = AppReady & { table: RawMetaTable; /** The records with each key as the API's field name. */ records: Record[]; }; -/** - * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app - * sign-in, the table on the app's API, and every record's keys and seeded-row values. - */ -export async function recordsReady( - verb: Verb, - params: { table_name: string; records: Record[] }, - cwd: string, -): Promise> { - if (params.records.length === 0) return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } }; +/** The project, its data endpoint, an app sign-in, and the tables of the app's API; `done` ends a suspended message. */ +export async function appReady(cwd: string, done: string): Promise> { const ready = await projectReady(cwd); if (ready.kind === 'failed') return ready; if (!ready.value.dataEndpoint) { @@ -123,7 +121,7 @@ export async function recordsReady( const meta = await adapter.execute(META_QUERY); if (!meta.ok) { const failure = isSuspended(meta.errors) - ? { code: 'database-unavailable' as const, message: `${UNAVAILABLE} No rows were ${WORDS[verb].done.toLowerCase()}.` } + ? { code: 'database-unavailable' as const, message: `${UNAVAILABLE} No rows were ${done}.` } : failureFromErrors(meta.errors, 'Failed to read schema from the app database'); return { kind: 'failed', failure }; } @@ -131,7 +129,22 @@ export async function recordsReady( } catch (err) { return { kind: 'failed', failure: failureFromError(err, 'Failed to query the app database schema') }; } - const table = findMetaTable(tables, params.table_name); + return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables } }; +} + +/** + * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app + * sign-in, the table on the app's API, and every record's keys and seeded-row values. + */ +export async function recordsReady( + verb: Verb, + params: { table_name: string; records: Record[] }, + cwd: string, +): Promise> { + if (params.records.length === 0) return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } }; + const ready = await appReady(cwd, WORDS[verb].done.toLowerCase()); + if (ready.kind === 'failed') return ready; + const table = findMetaTable(ready.value.tables, params.table_name); if (!table) { return { kind: 'failed', @@ -143,7 +156,8 @@ export async function recordsReady( }, }; } - const seeded = await seededIds(params.records, cwd); + const named = params.records.some((record) => Object.values(record).some(isRowRef)); + const seeded = named ? await seededIds(cwd) : ({ kind: 'ok', value: new Map() } as const); if (seeded.kind === 'failed') return seeded; const records: Record[] = []; for (const [index, record] of params.records.entries()) { @@ -151,7 +165,7 @@ export async function recordsReady( if (row.kind === 'failed') return row; records.push(row.value); } - return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables, table, records } }; + return { kind: 'ok', value: { ...ready.value, table, records } }; } export const fieldsOf = (table: RawMetaTable): RawField[] => (table.fields ?? []).filter((f): f is RawField => Boolean(f)); @@ -166,15 +180,16 @@ export function primaryKeyOf(table: RawMetaTable): RawField | undefined { const ROW_REF = /^@([a-z][a-z0-9_]*)\[(\d+)\]$/i; -const tableKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, ''); +export const isRowRef = (value: unknown): value is string => typeof value === 'string' && ROW_REF.test(value); + +export const tableKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, ''); -type SeededIds = ReadonlyMap; +export type SeededIds = ReadonlyMap; -/** The ids of the sample rows the host seeded, by `tableKey`, read only when a record names one. */ -async function seededIds(records: readonly Record[], cwd: string): Promise> { - const named = records.some((record) => Object.values(record).some((value) => typeof value === 'string' && ROW_REF.test(value))); +/** The ids of the sample rows the host seeded, by `tableKey`; none on a host that seeds no rows. */ +export async function seededIds(cwd: string): Promise> { const host = getHost(); - if (!named || !host.seededRows) return { kind: 'ok', value: new Map() }; + if (!host.seededRows) return { kind: 'ok', value: new Map() }; try { const rows = (await host.seededRows(cwd)) ?? {}; return { kind: 'ok', value: new Map(Object.entries(rows).map(([table, ids]) => [tableKey(table), ids])) }; @@ -200,14 +215,8 @@ export function recordAsFields( clear: boolean, ): Result> { const fields = fieldsOf(table); - const names = new Set(fields.flatMap((field) => [field.name, columnOf(field)])); - const unknown = Object.keys(record).find((key) => !names.has(key)); - if (unknown !== undefined) { - const columns = fields.map(columnOf); - const nearest = nearestName(unknown, columns); - const next = nearest ? `use "${nearest}".` : `its columns are ${listed(columns.map((c) => `"${c}"`))}.`; - return invalid(`Row ${index} names "${unknown}", which is not a column of ${tableName}: ${next}`); - } + const unknown = notAColumn(table, tableName, Object.keys(record)); + if (unknown) return invalid(`Row ${index} names ${unknown}`); const row: Record = {}; for (const field of fields) { const given = [field.name, columnOf(field)].filter((key) => Object.hasOwn(record, key)).map((key) => record[key]); @@ -217,18 +226,35 @@ export function recordAsFields( if (clear) row[field.name] = null; continue; } - const ref = typeof value === 'string' ? value.match(ROW_REF) : null; - if (!ref) { - row[field.name] = value; - continue; - } - const id = seeded.get(tableKey(ref[1]))?.[Number(ref[2])]; - if (!id) return invalid(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`); + const id = seededValue(value, seeded); + if (id === undefined) return invalid(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`); row[field.name] = id; } return { kind: 'ok', value: row }; } +/** The value, or the id of the seeded row a "@
[]" value names: undefined when none was seeded there. */ +export function seededValue(value: unknown, seeded: SeededIds): unknown { + const ref = typeof value === 'string' ? value.match(ROW_REF) : null; + return ref ? seeded.get(tableKey(ref[1]))?.[Number(ref[2])] ?? undefined : value; +} + +/** The first key that names no column (or field) of the table, with the column to use instead, as the end of a sentence. */ +export function notAColumn(table: RawMetaTable, tableName: string, keys: readonly string[]): string | undefined { + const fields = fieldsOf(table); + const names = new Set(fields.flatMap((field) => [field.name, columnOf(field)])); + const unknown = keys.find((key) => !names.has(key)); + if (unknown === undefined) return undefined; + const columns = fields.map(columnOf); + const nearest = nearestName(unknown, columns); + const next = nearest ? `use "${nearest}".` : `its columns are ${listed(columns.map((c) => `"${c}"`))}.`; + return `"${unknown}", which is not a column of ${tableName}: ${next}`; +} + +/** The field a key names, by its field name or its column name. */ +export const fieldNamed = (table: RawMetaTable, key: string): RawField | undefined => + fieldsOf(table).find((field) => field.name === key) ?? fieldsOf(table).find((field) => columnOf(field) === key); + /** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */ export async function writeRecords( verb: Verb, diff --git a/agentic/db-tools/src/schema-model.ts b/agentic/db-tools/src/schema-model.ts index 1187cfb7c3..2f6dd129f3 100644 --- a/agentic/db-tools/src/schema-model.ts +++ b/agentic/db-tools/src/schema-model.ts @@ -58,6 +58,8 @@ export type ModelForeignKey = { targetCategory: ObjectCategory | null; targetColumns: string[]; onDelete: FkAction; + /** The columns a delete of the target row sets to null or their default, when the key names only some of its own. */ + deleteSetColumns?: string[]; onUpdate: FkAction; }; @@ -311,6 +313,7 @@ export async function readSchemaModel(context: ProjectContext): Promise[]" for a sample row seeded when the app was built.') + .optional(), + where: z + .record(z.string(), z.unknown()) + .describe('Delete every row whose columns have these values: column name (snake_case) -> value; null matches an empty column.') + .optional(), + sample: z.literal(true).describe('Delete every sample row seeded when the app was built that is still there.').optional(), + all: z.literal(true).describe('Delete every row of the table that the person signed in to the app can see.').optional(), +}); + +const DeleteRecordsZod = strictObject('the input', { + tables: z + .array(DeleteTableZod) + .min(1) + .max(20) + .describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'), +}); + +type DeleteRecordsParams = z.infer; + +export type DeleteRecordsDetails = { + success: boolean; + message: string; + deletedCount: number; + tables: Array<{ tableName: string; deleted: number; kept?: true; failed: Array<{ key: string | number; message: string }> }>; + needsAuth?: boolean; + code?: 'database-unavailable'; +}; + +type TableResult = DeleteRecordsDetails['tables'][number]; + +/** The plan of a records delete: the exact rows as the target, and the card's preview. */ +export function deleteRecordsPlan({ context, userId, selection, notes }: DeleteRecordsReady): Resolved { + return { + target: { ...databaseTarget(context, userId), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) }, + preview: { kind: 'delete-records', ...selection }, + ...(notes.length ? { notes } : {}), + }; +} + +type DatabaseTarget = Extract; + +const sameTarget = (a: DatabaseTarget, b: DatabaseTarget): boolean => + a.database.id === b.database.id && a.apiEndpoint === b.apiEndpoint && a.account.userId === b.account.userId && + a.account.agent?.principalId === b.account.agent?.principalId && a.appUserId === b.appUserId; + +type Planned = { tableName: string; table: RawMetaTable; keyName: string; keys: Array }; + +/** The app table and key of each table of the rows to delete, still on the app API with a delete. */ +function plannedRows(tables: RawMetaTable[], rows: ReadonlyArray<{ tableName: string; keys: Array }>): Result { + const planned: Planned[] = []; + for (const { tableName, keys } of rows) { + const table = tables.find((candidate) => sqlName(candidate) === tableName); + const key = table && primaryKeyOf(table); + if (!table || !key || !table.query?.delete) { + return { + kind: 'failed', + failure: { + code: 'failed', + message: `${tableName} changed on the app API after its rows were chosen, so nothing was deleted.`, + hint: 'Review the rows and approve a new request.', + }, + }; + } + planned.push({ tableName, table, keyName: key.name, keys }); + } + return { kind: 'ok', value: planned }; +} + +const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`; + +const NO_ROW_DELETED = 'The backend answered without the deleted row, so it does not exist, or this account may not delete it.'; + +/** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */ +async function deleteRows({ adapter, tables }: AppReady, planned: readonly Planned[], kept: readonly string[]): Promise> { + const all = tables.map(cleanTable); + const results: TableResult[] = []; + const errors: GraphQLError[] = []; + let suspended = false; + for (const { tableName, table: rawTable, keyName, keys } of planned) { + if (suspended) break; + const table = cleanTable(rawTable); + const mutation = buildPostGraphileDelete(table, all).toString(); + const mutationName = toDeleteMutationName(table.name, table); + const result: TableResult = { tableName, deleted: 0, failed: [] }; + results.push(result); + for (const key of keys) { + let rowErrors: GraphQLError[]; + try { + const answer = await adapter.execute>(mutation, { input: { [keyName]: key } }); + if (answer.ok) { + if (answer.data?.[mutationName]) result.deleted += 1; + else result.failed.push({ key, message: NO_ROW_DELETED }); + continue; + } + if (isSuspended(answer.errors)) { + suspended = true; + break; + } + rowErrors = answer.errors; + } catch (err) { + // The request threw before any answer came back, so the error is the local one. + rowErrors = [{ message: thrownText(err), extensions: { code: 'NETWORK' } }]; + } + errors.push(...rowErrors); + result.failed.push({ key, message: answerText(rowErrors) }); + } + } + + const deletedCount = results.reduce((sum, result) => sum + result.deleted, 0); + const failedCount = results.reduce((sum, result) => sum + result.failed.length, 0); + const details = { deletedCount, tables: [...results, ...kept.map((tableName): TableResult => ({ tableName, deleted: 0, kept: true, failed: [] }))] }; + const done = results.filter((result) => result.deleted > 0); + const message = [ + done.length ? `Deleted ${listed(done.map((result, index) => `${index === 0 ? plural(result.deleted, 'row') : result.deleted} from ${result.tableName}`))}.` : '', + ...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}).`), + 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.` : '', + ].filter(Boolean).join(' '); + + const failed = (failure: ToolFailure) => recordsFailed(failure, details); + if (suspended) { + const before = deletedCount === 0 ? 'No rows were deleted.' : `${deletedCount === 1 ? '1 row was' : `${deletedCount} rows were`} deleted before it stopped.`; + return failed({ code: 'database-unavailable', message: `${UNAVAILABLE} ${before}` }); + } + if (failedCount > 0 && deletedCount === 0) { + const action = `Failed to delete rows from ${listed(results.map((result) => result.tableName))}`; + return failed(errors.length ? failureFromErrors(errors, action, { rows: { table: results[0].tableName } }) : noRowsChanged(action, DESCRIBE_SCHEMA)); + } + if (failedCount > 0) { + return failed({ + code: 'partial', + message, + hint: 'Fix what the backend said about the rows in details.tables, then call again with only those rows: the deleted rows are gone.', + }); + } + return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } }; +} + +/** Why the approved rows cannot go while the person keeps the table that `effect` reaches, and what to do instead. */ +function keptReached(effect: DeleteEffect): string { + const { parent, child } = effect; + const what = effect.effect === 'cascade' + ? `deleting ${parent} deletes them too` + : effect.effect === 'set_null' + ? `deleting ${parent} clears ${listed(effect.columns)} on them` + : effect.effect === 'set_default' + ? `deleting ${parent} sets ${listed(effect.columns)} to ${effect.columns.length === 1 ? 'its default' : 'their defaults'} on them` + : `${parent} rows can't be deleted while they're there`; + 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.`; +} + +/** Why the check could not rule out that the approved rows reach `table`, which the person kept, and what to do. */ +function keptNotChecked(effect: DeleteEffect, table: string): string { + if (effect.upTo) return `Nothing was deleted: there are too many related rows to check that ${table} stays untouched. Delete in smaller steps, or tick ${table}.`; + const why = effect.uncounted + ? `the ${effect.child} rows that point at ${effect.parent} can't be counted` + : `the rows that point at the ${effect.child} rows it deletes can't be followed`; + return `Nothing was deleted: ${why}, so it can't check that ${table} stays untouched. Tick ${table}, or keep ${effect.parent} too.`; +} + +export const deleteRecordsTool: HarnessTool = { + name: 'delete_records', + label: 'Delete records', + 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.", + promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.', + parameters: DeleteRecordsZod, + effect: 'write', + async execute(params: DeleteRecordsParams, ctx) { + const approved = ctx.toolCallId ? takeApprovedTable(ctx.toolCallId, ctx.cwd) : undefined; + const fail = (failure: ToolFailure) => recordsFailed(failure, { deletedCount: 0, tables: [] }); + if (!approved?.rows) { + // The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes + // nothing, because only an approved target says which rows the person saw and kept. + const ready = await deleteRecordsReady(params, ctx.cwd); + if (ready.kind === 'failed') return fail(ready.failure); + return fail({ + code: 'failed', + message: 'This delete has no approval (it may have expired), so nothing was deleted. Ask again to see the rows and approve them.', + }); + } + + const ready = await appReady(ctx.cwd, 'deleted'); + if (ready.kind === 'failed') return fail(ready.failure); + if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value.userId))) { + return fail({ + code: 'failed', + message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.', + hint: 'Review the rows and approve a new request.', + }); + } + const planned = plannedRows(ready.value.tables, approved.rows); + if (planned.kind === 'failed') return fail(planned.failure); + // A table of the input that the approved rows leave out was unticked, or had no rows when the card was built. + const approvedTables = new Set(planned.value.map((entry) => entry.table)); + const kept = params.tables + .map((input) => findMetaTable(ready.value.tables, input.table_name)) + .filter((table): table is RawMetaTable => Boolean(table) && !approvedTables.has(table!)) + .map(sqlName); + if (kept.length > 0) { + const found = await deleteEffects(ready.value, approved.rows); + if (found.kind === 'failed') return fail(found.failure); + const { effects, model } = found.value; + const reached = effects.find((effect) => !effect.uncounted && kept.includes(effect.child)); + if (reached) return fail({ code: 'conflict', message: keptReached(reached) }); + // An effect the check could not count or follow may still reach a kept table, so it counts as reaching it. + for (const effect of effects) { + const table = tablesNotChecked(effect, model).find((name) => kept.includes(name)); + if (table) return fail({ code: 'conflict', message: keptNotChecked(effect, table) }); + } + } + return deleteRows(ready.value, planned.value, kept); + }, +}; diff --git a/agentic/db-tools/src/tools/index.ts b/agentic/db-tools/src/tools/index.ts index 2a4e14f2f9..1730cf4db8 100644 --- a/agentic/db-tools/src/tools/index.ts +++ b/agentic/db-tools/src/tools/index.ts @@ -1,4 +1,4 @@ -import type { AnyHarnessTool, PlanTableAccess, PlanTarget } from '@agentic-kit/harness'; +import type { AnyHarnessTool, ConfirmPreview, PlanTableAccess, PlanTarget } from '@agentic-kit/harness'; import type { BlueprintPolicy } from 'node-type-registry'; import { type TableAccessInput, tablePolicyFromBlueprint } from '../access'; @@ -7,6 +7,7 @@ import type { ProjectContext } from '../context'; import type { Result } from '../failure'; import { provisionDatabaseReady } from '../provision-database/provision'; import { accountTarget, databaseTarget, ownedProjectReady, projectReady } from '../ready'; +import { deleteRecordsReady } from '../records/delete-selection'; import { renameNote } from '../schema-resolve'; import { columnChange, columnPlan, planTableAccess } from '../table-access'; import { addedByBackend, describePolicyTypeTool, explainAccessTool, readOnlyNotes, setAccessPlan, setAccessReady, setAccessTool } from './access'; @@ -14,6 +15,7 @@ import { addPoliciesPlan, addPoliciesReady, addPoliciesTool } from './add-polici import { addRecordsReady, addRecordsTool } from './add-records'; import { addRelationReady, addRelationTool } from './add-relation'; import { createApiKeyReady, createApiKeyTool } from './create-api-key'; +import { deleteRecordsPlan, deleteRecordsTool } from './delete-records'; import { describeSchemaTool } from './describe-schema'; import { createEntityTypeReady, createEntityTypeTool, deleteEntityTypeReady, deleteEntityTypeTool, listEntityTypesTool } from './entity-types'; import { @@ -68,6 +70,7 @@ export const constructiveDbTools: readonly AnyHarnessTool[] = [ deleteTemplateTool, addRecordsTool, updateRecordsTool, + deleteRecordsTool, listEntityTypesTool, createEntityTypeTool, deleteEntityTypeTool, @@ -78,8 +81,11 @@ export const constructiveDbTools: readonly AnyHarnessTool[] = [ describePolicyTypeTool, ]; -/** 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. */ -export type Resolved = { target: PlanTarget; access?: PlanTableAccess[]; notes?: string[] }; +/** + * What a plan names that the tool's check resolved: its target, the access of the tables it creates or changes, what + * it must say that the input does not, and the card's preview when only the check can build it. + */ +export type Resolved = { target: PlanTarget; access?: PlanTableAccess[]; notes?: string[]; preview?: ConfirmPreview }; type Precondition = (params: any, cwd: string) => Promise>; @@ -174,6 +180,13 @@ export const toolPreconditions: ReadonlyMap = new Map accountTarget(context))], [addRecordsTool.name, targeting(addRecordsReady, ({ context, userId }) => databaseTarget(context, userId))], [updateRecordsTool.name, targeting(updateRecordsReady, ({ context, userId }) => databaseTarget(context, userId))], + [ + deleteRecordsTool.name, + async (params, cwd) => { + const ready = await deleteRecordsReady(params, cwd); + return ready.kind === 'failed' ? ready : { kind: 'ok', value: deleteRecordsPlan(ready.value) }; + }, + ], [listEntityTypesTool.name, onDatabase(project)], [createEntityTypeTool.name, onDatabase(createEntityTypeReady)], [deleteEntityTypeTool.name, onDatabase(deleteEntityTypeReady)], diff --git a/agentic/harness/__tests__/plan.test.ts b/agentic/harness/__tests__/plan.test.ts index 03cfb40f3b..79555adc31 100644 --- a/agentic/harness/__tests__/plan.test.ts +++ b/agentic/harness/__tests__/plan.test.ts @@ -1,5 +1,5 @@ import { createConstructiveGatePolicy } from '../src/gating/constructive-policy'; -import { type ConfirmPreviewTable, type PlanTarget, renderPlan } from '../src/gating/preview'; +import { type ConfirmPreview, type ConfirmPreviewTable, type PlanTarget, renderPlan } from '../src/gating/preview'; import { buildConfirmPrompt } from '../src/gating/prompts'; const API = 'http://api.localhost:3000/graphql'; @@ -83,6 +83,45 @@ describe('the rows of update_records', () => { }); }); +describe('the rows of delete_records', () => { + const table = (tableName: string, keys: string[]) => ({ tableName, keyName: 'id', keys, count: keys.length, rows: keys.map((id) => ({ id })) }); + + it('counts the rows of each table in the order it resolved, then each effect, from the preview the precondition built', async () => { + const preview = { + kind: 'delete-records' as const, + tables: [table('contacts', ['c1', 'c2']), table('companies', ['k1'])], + effects: ['Deleting companies also deletes the notes rows that point at them.'], + links: [{ parent: 'companies', child: 'contacts', effect: 'restrict' as const }], + }; + const policy = createConstructiveGatePolicy({ + effectOf: () => 'write', + precondition: async () => ({ kind: 'ready', target: TARGET, preview, notes: ['deals has no sample rows left.'] }), + resolveTemplatePreview: async () => undefined, + }); + const input = { tables: [{ table_name: 'companies', all: true }, { table_name: 'contacts', all: true }, { table_name: 'deals', sample: true }] }; + const decision = await policy.resolvePrompt({ toolName: 'delete_records', toolCallId: 'tc-1', input }, '/tmp/project'); + expect(decision).toEqual({ + kind: 'ask', + prompt: expect.objectContaining({ + title: 'Delete 3 rows from 2 tables', + message: [ + '- 2 rows from contacts', + '- 1 row from companies', + '! Deleting companies also deletes the notes rows that point at them.', + '! This cannot be undone.', + 'Note: deals has no sample rows left.', + ].join('\n'), + preview, + }), + }); + }); + + it('names the one table in the title', () => { + const preview: ConfirmPreview = { kind: 'delete-records', tables: [table('deals', ['d1', 'd2'])], effects: [], links: [] }; + expect(buildConfirmPrompt('delete_records', {}, { target: TARGET, preview }).title).toBe('Delete 2 rows from deals'); + }); +}); + describe('the tables of create_template', () => { it('lists the tables the template takes under the change, one line each', async () => { const policy = createConstructiveGatePolicy({ diff --git a/agentic/harness/src/gating/confirm-gate.ts b/agentic/harness/src/gating/confirm-gate.ts index 504b70c326..c1deca55f2 100644 --- a/agentic/harness/src/gating/confirm-gate.ts +++ b/agentic/harness/src/gating/confirm-gate.ts @@ -23,11 +23,13 @@ export type GateResult = { block: true; reason: string; failure?: ToolFailure } const approvedTables = new Map>(); /** - * Remember the table a person approved for a call, so the tool acts only on that table (`takeApprovedTable`). Every - * approval path calls it once the call is approved: this gate, and a host that asks through its own approval channel. + * Remember the table, or the rows, a person approved for a call, so the tool acts only on what the card named + * (`takeApprovedTable`). Every approval path calls it once the call is approved: this gate, and a host that asks + * through its own approval channel. A host that lets the person leave tables of a records delete out passes the + * target with only the tables they kept ticked in `rows`. */ export function rememberApprovedTable(toolCallId: string, cwd: string, target: PlanTarget): void { - if (target.kind !== 'database' || !target.table) return; + if (target.kind !== 'database' || (!target.table && !target.rows)) return; const key = JSON.stringify([cwd, toolCallId]); const approved = structuredClone(target); approvedTables.set(key, approved); diff --git a/agentic/harness/src/gating/constructive-policy.ts b/agentic/harness/src/gating/constructive-policy.ts index d28c06ba20..555d96aaa7 100644 --- a/agentic/harness/src/gating/constructive-policy.ts +++ b/agentic/harness/src/gating/constructive-policy.ts @@ -7,11 +7,12 @@ import { buildConfirmPrompt } from './prompts'; /** * What the precondition step resolved: why the call cannot run, or what it acts * on, for a call that creates or changes the access of a table, that access, - * and what the plan must say that the input does not. + * what the plan must say that the input does not, and the card's preview when + * only the precondition can build it (the rows a delete removes). */ export type GateReadiness = | { kind: 'blocked'; failure: ToolFailure } - | { kind: 'ready'; target: PlanTarget; access?: PlanTableAccess[]; notes?: string[] }; + | { kind: 'ready'; target: PlanTarget; access?: PlanTableAccess[]; notes?: string[]; preview?: ConfirmPreview }; /** * Host capabilities the Constructive database policy needs. These are @@ -64,7 +65,12 @@ export function createConstructiveGatePolicy(deps: ConstructiveGateDeps): GatePo const ready = await deps.precondition(event.toolName, input, cwd); if (ready.kind === 'blocked') return { kind: 'blocked', failure: ready.failure }; - const prompt = buildConfirmPrompt(event.toolName, input, { target: ready.target, access: ready.access, notes: ready.notes }); + const prompt = buildConfirmPrompt(event.toolName, input, { + target: ready.target, + access: ready.access, + notes: ready.notes, + preview: ready.preview, + }); if (event.toolName === 'create_template') { const blueprintName = typeof input?.blueprintName === 'string' ? input.blueprintName : undefined; diff --git a/agentic/harness/src/gating/preview.ts b/agentic/harness/src/gating/preview.ts index 740861d204..ec44209c31 100644 --- a/agentic/harness/src/gating/preview.ts +++ b/agentic/harness/src/gating/preview.ts @@ -19,8 +19,22 @@ export type ConfirmPreviewTable = { relationCount: number; }; +/** One table of a records delete, as the gate resolved it: the exact rows, children before the tables they point at. */ +export type DeleteRecordsTable = { + tableName: string; + keyName: string; + keys: Array; + count: number; + /** For the card: the key and up to 3 readable columns, at most 5 rows. */ + rows: Record[]; +}; + +/** A foreign key between two tables of a records delete: the rows of `child` point at rows of `parent`. */ +export type DeleteRecordsLink = { parent: string; child: string; effect: 'cascade' | 'set_null' | 'restrict' }; + export type ConfirmPreview = | { kind: 'records'; tableName: string; rows: Record[] } + | { kind: 'delete-records'; tables: DeleteRecordsTable[]; effects: string[]; links: DeleteRecordsLink[] } | { kind: 'blueprint'; tables: ConfirmPreviewTable[] } | { kind: 'template'; displayName: string; blueprintName?: string; tables: ConfirmPreviewTable[] } | { kind: 'policies'; tableName: string; policies: string[] } @@ -42,6 +56,7 @@ export type PlanAccount = { userId: string; email?: string; agent?: PlanAgent }; * * - `database`: a change to the bound database. `appUserId` is set when the * change is made as the person signed in to the app (rows), not as the account. + * `rows` names the exact rows a records delete removes, by table. * - `account`: a change that no bound database receives: a new database * (`replaces` names the one the directory leaves), or the account's templates. * - `no-credential`: a request to an endpoint with no one signed in, so it @@ -50,7 +65,8 @@ export type PlanAccount = { userId: string; email?: string; agent?: PlanAgent }; * backend (a host's own policy that gates a shell command). */ export type PlanTarget = - | { kind: 'database'; database: PlanDatabase; apiEndpoint: string; account: PlanAccount; appUserId?: string; table?: { id: string; schemaId: string } } + | { kind: 'database'; database: PlanDatabase; apiEndpoint: string; account: PlanAccount; appUserId?: string; + table?: { id: string; schemaId: string }; rows?: Array<{ tableName: string; keys: Array }> } | { kind: 'account'; apiEndpoint: string; account: PlanAccount; replaces?: PlanDatabase } | { kind: 'no-credential'; endpoint: string } | { kind: 'workspace'; cwd: string }; diff --git a/agentic/harness/src/gating/prompts.ts b/agentic/harness/src/gating/prompts.ts index 3a74c156e8..f231f719d0 100644 --- a/agentic/harness/src/gating/prompts.ts +++ b/agentic/harness/src/gating/prompts.ts @@ -1,4 +1,4 @@ -import type { ConfirmPreviewField, ConfirmPreviewTable, ConfirmPrompt, PlanTableAccess, PlanTarget } from './preview'; +import type { ConfirmPreview, ConfirmPreviewField, ConfirmPreviewTable, ConfirmPrompt, PlanTableAccess, PlanTarget } from './preview'; import { databaseWords, newTableFieldLines, planAccessLines, rowLines } from './preview'; // A default as the input gives it: SQL text, or a constant number or boolean; undefined for none (null removes one). @@ -128,9 +128,9 @@ const UNDONE = '! This cannot be undone.'; export function buildConfirmPrompt( toolName: string, input: Record | undefined, - resolved: { target: PlanTarget; access?: PlanTableAccess[]; notes?: string[] }, + resolved: { target: PlanTarget; access?: PlanTableAccess[]; notes?: string[]; preview?: ConfirmPreview }, ): ConfirmPrompt { - const call = describeCall(toolName, input, resolved.access, resolved.target); + const call = describeCall(toolName, input, resolved.access, resolved.target, resolved.preview); const notes = resolved.notes ?? []; return { ...call, @@ -146,6 +146,7 @@ function describeCall( input: Record | undefined, access: PlanTableAccess[] | undefined, target: PlanTarget, + resolvedPreview: ConfirmPreview | undefined, ): Omit { switch (toolName) { case 'provision_database': { @@ -260,6 +261,20 @@ function describeCall( preview: rows.length > 0 ? { kind: 'records', tableName, rows } : undefined, }; } + case 'delete_records': { + const preview = resolvedPreview?.kind === 'delete-records' ? resolvedPreview : { kind: 'delete-records' as const, tables: [], effects: [], links: [] }; + const { tables, effects } = preview; + const count = plural(tables.reduce((sum, table) => sum + table.count, 0), 'row'); + return { + title: tables.length === 1 ? `Delete ${count} from ${tables[0].tableName}` : `Delete ${count} from ${plural(tables.length, 'table')}`, + message: [ + ...tables.map((table) => `- ${plural(table.count, 'row')} from ${table.tableName}`), + ...effects.map((effect) => `! ${effect}`), + UNDONE, + ].join('\n'), + preview, + }; + } case 'create_entity_type': { const name = str(input, 'name') ?? '?'; return { title: `Create entity type ${name}`, message: `+ entity type ${name} a table for its rows, and tables for who belongs to each one` }; diff --git a/agentic/pi/__tests__/pi-tool.test.ts b/agentic/pi/__tests__/pi-tool.test.ts index feee138b65..7f95f459f5 100644 --- a/agentic/pi/__tests__/pi-tool.test.ts +++ b/agentic/pi/__tests__/pi-tool.test.ts @@ -90,7 +90,7 @@ describe('dbTools', () => { expect(registered.map((tool) => tool.name)).toEqual( constructiveDbTools.map((tool) => tool.name), ); - expect(registered).toHaveLength(26); + expect(registered).toHaveLength(27); for (const tool of registered) { expect(typeof tool.execute).toBe('function'); expect(tool.parameters).toMatchObject({ type: 'object' });