Public: anyone can read this; the crew can change it.

Nothing that destroys data runs from a chat #16295

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

talk/fix-no-delete-from-chat → main 0 commits 1 thread · 1 unresolved

  • Merged. talk/fix-no-delete-from-chat was merged into main as d6afc74.

Review

Sign in to review this change.
30 files changed +562 −9
docs/features/conversation-fence.md +5
@@ -54,6 +54,11 @@ it. For a via token, and only for one:
5454 ("do not close" is no ask), and every value it is given: the repository's
5555 name, every other string as written (a label, a branch, `into`, a
5656 collaborator, a body), and every whole number (`src/core/fence.ts`, `named`).
57 - **A destroying call is never held.** A call of a tool marked `tier: "delete"`
58 (a branch, a board, a key, a secret, where backups go) is refused at once
59 with the page a person does it on, fence up or down, and a Do it on a row
60 held before that rule answers 409 `delete`. The list and the rule for a
61 new tool are in [danger-confirms.md](danger-confirms.md).
5762
5863 A person's own token, an agent's run token and an `ro` token answer as before.
5964
docs/features/danger-confirms.md +36
@@ -10,3 +10,39 @@ Pressing "Stop running as an app" or "Delete this repository" (Settings → Dang
1010 - **Delete this repository:** issues, pulls, comments, webhooks and git objects go; there is no way back, forks are detached first and keep working.
1111
1212 The words live once in `src/web/danger_words.ts` (`DANGERS`, `dangerDetail`). Terminal: the repository's `:` palette → "Delete this repository" shows the same two sentences before asking for the name (`src/tui/screens/deleterepo.ts`). Test: `test/danger-words.test.ts` fails if an entry lacks either line.
13
14 ## Nothing that destroys data runs from a chat
15
16 The forge's own agent, speaking for a person in Talk, never makes a call that destroys data, and no Do it runs one. A tool says so on its own definition (`src/http/mcp/shared.ts`, `Tool`): `tier: "delete"`, `deletes` for the calls that destroy (absent, every call that writes) and `where`, the page a person does it on.
17
18 - **Refused at once, never held.** Such a call from the agent answers `forbidden:` with one sentence naming the page, at the door where `refusedToAgent` refuses, before anything is asked first or held. No confirm is drawn. A plan (`dryRun`) and the tool's other calls go on as before.
19 - **A Do it refuses it too.** A row held before this rule answers 409 `delete` on yes, from the page, the API (`POST /api/v1/conversation-confirms/:id`) and the terminal's confirms screen (`src/tui/screens/confirms.ts`). The confirm is spent, nothing runs, and a line in the thread says where to do it.
20 - **A person's own token is not refused.** The rule is for the agent in a conversation; a person calling the tool, or using the page, meets the tool's own checks.
21
22 What counts as destroying, and where a person does each themselves:
23
24 | Tool | The calls | Where |
25 | --- | --- | --- |
26 | `agent` | `action: remove` | Settings → Crew (`/settings/crew`) |
27 | `app_data_import` | every call | their own token: `POST /api/v1/repos/<owner>/<name>/data-import` (no page) |
28 | `app_domains` | `action: remove` | the app's settings (`/<owner>/<name>/settings/app`), Domains |
29 | `app_env` | `action: unset` | the app's settings (`/<owner>/<name>/settings/app`), Environment |
30 | `backups_destination`, `mirror_set` | every call | Settings → Backups (`/settings/backups`) |
31 | `board_delete` | every call | the board's page (`/boards/<slug>`) |
32 | `branches` | `action: delete` | the repository's Branches page |
33 | `cloud_account` | `verb: remove` | Settings → Cloud (`/settings/cloud`) |
34 | `drop` | `action: remove` | the app's Drop page (`/<owner>/<name>/drop`) |
35 | `forges` | `archive` | the Forges page (`/forges`) |
36 | `hooks`, `prompts`, `repo_labels` | `action: remove` | the repository's settings: Webhooks, Prompts, Labels |
37 | `migrate_data` | `apply` or `undo` | the app's data move page (`/<owner>/<name>/data-move`) |
38 | `org_teams` | `action: remove` | the team's page (`/<org>/-/teams/<team>`) |
39 | `origin_apps` | `action: remove` | Settings → Origins (`/settings/origins`) |
40 | `proposal_tokens` | `verb: revoke` | the repository's settings, Proposal tokens |
41 | `secrets` | `action: remove` | Settings → Secrets (`/settings/secrets`) |
42 | `ssh_keys` | `action: remove` | Settings → SSH keys (`/settings/keys`) |
43 | `subscription_delete` | every call | Settings → Subscriptions (`/settings/subscriptions`) |
44 | `whoami_can` | `remove` (a passkey) | Settings → Passkeys |
45
46 Only deleting a repository asks for its typed name today; the other pages confirm in their own way.
47
48 **A new tool.** One that deletes, removes, imports over, or changes where backups go is marked with `tier: "delete"`, `deletes` when only some calls destroy, and `where`. `test/delete-tier.test.ts` walks every write tool: a name or description that says it destroys needs the mark or a line in the test's short `SPARED` list with the reason, and every marked tool needs a destroying call in `SAMPLES`, which the test sends through `/mcp` and a Do it.
src/actions/conversation_confirms.ts +11 −3
@@ -19,7 +19,7 @@ import { getIssue } from "../core/issues.ts";
1919 import { getRepo } from "../core/repos.ts";
2020 import { answerHeld, countWaiting, HELD_TTL_MS, waitingFor, type YesRefusal } from "../core/fence.ts";
2121 import type { User } from "../core/users.ts";
22 import { argumentsShown, keptOf, undoOf } from "../crew/conversation_confirm.ts";
22 import { argumentsShown, destroysData, destroysSentence, keptOf, undoOf } from "../crew/conversation_confirm.ts";
2323 import { confirmSentence } from "../crew/conversation_ask.ts";
2424 import { outcomeWords } from "../crew/conversation_answered.ts";
2525 import { reportAnswered } from "../crew/conversation.ts";
@@ -58,7 +58,8 @@ export function waitingCount(ctx: Pick<Ctx, "app">, user: User, now: number = Da
5858 export const CONFIRM_ID = /^[0-9a-z]{1,40}$/;
5959
6060 /** Why a yes did nothing, in words, with the status the API answers. */
61 export const REFUSED: Readonly<Record<YesRefusal | "forbidden", readonly [number, string]>> = {
61 export const REFUSED: Readonly<Record<YesRefusal | "forbidden" | "delete", readonly [number, string]>> = {
62 delete: [409, "this destroys data, so it never runs from a conversation: do it yourself on its own page, which the thread now names"],
6263 not_found: [404, "no such confirm of yours"],
6364 answered: [409, "this confirm was already answered; it does nothing twice"],
6465 expired: [410, "this confirm is past its 10 minutes; ask the agent again"],
@@ -67,7 +68,7 @@ export const REFUSED: Readonly<Record<YesRefusal | "forbidden", readonly [number
6768
6869 /** What a yes did: `turn` as the conversation keeps it, `result` as the person sees it once. */
6970 export type Yes =
70 | { ok: false; error: YesRefusal | "forbidden" }
71 | { ok: false; error: YesRefusal | "forbidden" | "delete" }
7172 | { ok: true; done: boolean; turn: Record<string, unknown>; result?: unknown };
7273
7374 /** The result as the turn keeps it: whole when it fits, cut when it would not. */
@@ -99,6 +100,13 @@ export async function sayYes(ctx: Ctx, user: User, confirmId: string): Promise<Y
99100 // What the person may no longer do is not done on an old yes.
100101 if (tool === undefined || ((tool.adminOnly === true || tool.needsAdminScope === true) && !user.isAdmin))
101102 return { ok: false, error: "forbidden" };
103 // A destroying call is never run by a Do it, even one held before the rule (#10262): the
104 // confirm is spent, nothing runs, and the thread says where the person does it themselves.
105 if (destroysData(tool, held.args)) {
106 const refused = { confirm: held.id, tool: held.tool, done: false, error: "delete", message: destroysSentence(tool), says: destroysSentence(tool) };
107 appendTurn(ctx.app.db, user.id, conversationOfVia(ctx.app.db, user.id, held.via).id, { role: "tool", text: JSON.stringify(refused) });
108 return { ok: false, error: "delete" };
109 }
102110 // The session's own authority, as a token would carry it: admin scope
103111 // for an admin only, as only an admin mints an admin token.
104112 const asPerson: Ctx = { ...ctx, auth: { ...ctx.auth, user, scope: user.isAdmin ? "admin" : "rw" } };
src/crew/conversation_confirm.ts +18
@@ -197,6 +197,24 @@ export function undoableWork(tool: string, args: Args): Work | undefined {
197197 return work === undefined || work.only?.(args) === false ? undefined : work;
198198 }
199199
200 /** A tool as the delete rule reads it (`http/mcp/shared.ts`, `Tool`). */
201 export interface Destroying {
202 readonly name: string;
203 readonly tier?: "delete";
204 readonly deletes?: (args: Args) => boolean;
205 readonly where?: string;
206 }
207
208 /**
209 * Whether this call of a tool marked `tier: "delete"` is one that destroys data (#10262): never
210 * held, never run by a Do it.
211 */
212 export const destroysData = (tool: Destroying, args: Args): boolean => tool.tier === "delete" && (tool.deletes?.(args) ?? true);
213
214 /** The one sentence a destroying call is refused with: what it is, and where the person does it. */
215 export const destroysSentence = (tool: Destroying): string =>
216 `\`${tool.name}\` destroys data, so it never runs from a conversation and nothing was kept: the person does it themselves ${tool.where ?? "on its own page"}.`;

Document this rule in docs/features/danger-confirms.md and conversation-fence.md. The pull has no docs change.

217
200218 /** Whether this call of `tool` asks first, scope aside. */
201219 export function asksFirst(tool: string, args: Args): boolean {
202220 const asking = ASKING[tool];
src/http/mcp.ts +3 −2
@@ -47,7 +47,7 @@ import { CONTRIBUTE_TOKEN_HINT, CONTRIBUTE_TOKEN_WORDS, mintContributeToken } fr
4747 import { BODY_MAX, REQUEST_MAX, TITLE_MAX } from "../core/reports.ts";
4848 import { adminRefusal, everydayOf } from "../core/everyday.ts";
4949 import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts";
50 import { type Args, alreadyDone, notAdminTool, listable, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, readThrough, type ToolShape } from "./mcp/shared.ts";
50 import { type Args, alreadyDone, notAdminTool, listable, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, destroysTo, readThrough, type ToolShape } from "./mcp/shared.ts";
5151 import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts";
5252 import { recordCard, shownLine } from "../core/talk_voice.ts";
5353 import { stepOf } from "../core/talk_steps.ts";
@@ -275,7 +275,8 @@ function rpcOne(
275275 // steered to is held as a confirm too, not merely refused (#7649), and
276276 // one the person asked for waits for their yes (#7650).
277277 // What the forge's own agent may never do is refused to it at once: never held, never a yes.
278 const never = ctx.auth.through === undefined ? undefined : tool?.refusedToAgent?.(args);
278 const never =
279 ctx.auth.through === undefined || tool === undefined ? undefined : (tool.refusedToAgent?.(args) ?? destroysTo(user, tool, args));
279280 if (never !== undefined)
280281 return reply({ content: [{ type: "text", text: `forbidden: ${never}` }], isError: true, hint: hintForCode("forbidden") });
281282 // A write the tool would refuse this person anyway is answered as refused now, in its own
src/http/mcp/shared.ts +29 −2
@@ -15,7 +15,7 @@ import { BOARD_NOT_SAVED } from "../../actions/board_words.ts";
1515 import { askedFor, fence, fenceTag, fenceUp, hold, named, readFenced } from "../../core/fence.ts";
1616 import { appendTurn, conversationOfVia, proposalBefore } from "../../core/conversations.ts";
1717 import { writesThisTurn } from "../../core/conversation_writes.ts";
18 import { argumentsShown, asksFirst, tooBigToApprove, undoableWork } from "../../crew/conversation_confirm.ts";
18 import { argumentsShown, asksFirst, destroysData, destroysSentence, tooBigToApprove, undoableWork } from "../../crew/conversation_confirm.ts";
1919 import { confirmSentence, SAID_MAX } from "../../crew/conversation_ask.ts";
2020
2121 export type Args = Record<string, unknown>;
@@ -90,6 +90,18 @@ export interface Tool {
9090 readonly inputSchema: Record<string, unknown>;
9191 /** Whether it changes anything: `rw` scope, and said so to the client. */
9292 readonly writes: boolean;
93 /**
94 * `delete`: it destroys data or what it removes cannot be put back (a repository's branch, a
95 * board, a key, a secret, a subscription, where backups go, an import over an app's data). The
96 * forge's own agent never makes such a call and no confirm holds one: it is refused at once,
97 * as `refusedToAgent` refuses, with the page in `where`, and a Do it refuses it too
98 * (`destroysTo`, `sayYes`). `test/delete-tier.test.ts` walks every write tool for the mark.
99 */
100 readonly tier?: "delete";
101 /** With `tier: "delete"`: the calls that destroy; absent, every call that writes. */
102 readonly deletes?: (args: Args) => boolean;
103 /** With `tier: "delete"`: where a person does it themselves, as the refusal ends ("on …"). */
104 readonly where?: string;
93105 /**
94106 * Listed, and callable, for a forge admin only: anyone else's call is answered at the door
95107 * (`notAdminTool`), with how to reach an admin, before the tool runs. Use it when the tool has
@@ -160,6 +172,19 @@ export const plansOnly = (tool: ToolShape, args: Args): boolean =>
160172 (tool.readsWithout !== undefined && [tool.readsWithout].flat().every((k) => args[k] === undefined)) ||
161173 tool.readsWhen?.(args) === true;
162174
175 /** Whether this call destroys data (`tier: "delete"`): a plan or a read of the same tool does not. */
176 const destroys = (tool: ToolShape, args: Args): boolean => tool.writes && !plansOnly(tool, args) && destroysData(tool, args);
177
178 /**
179 * The owner's rule (#10262): nothing is deleted without the person's own hand on its page. What
180 * the forge's own agent is refused a destroying call with, beside a tool's own `refusedToAgent`
181 * and at the same place: the sentence that sends the person to that page, before anything is
182 * asked first or held. What the person may not do stays unknown to their agent: an admin-scope
183 * tool of someone who is no admin is left to the refusal every caller meets. Undefined: go on.
184 */
185 export const destroysTo = (user: User, tool: ToolShape, args: Args): string | undefined =>
186 destroys(tool, args) && !(tool.needsAdminScope === true && !user.isAdmin) ? destroysSentence(tool) : undefined;
187
163188 /** What a held write tells the forge's agent, beside the confirm's id. */
164189 export const NEEDS_CONFIRM =
165190 "this write follows text read as data and the person's newest words do not ask for it, so nothing was done. With an id in `needs_confirm`, Do it and Not now buttons are already in the thread: say in one sentence what it would do and point at them. With null nothing was kept: say so, and do not call it held";
@@ -212,7 +237,8 @@ function askedWork(ctx: Ctx, user: User, via: string, tool: ToolShape, args: Arg
212237 */
213238 export function heldWrite(ctx: Ctx, user: User, tool: ToolShape, args: Args): Record<string, unknown> | undefined {
214239 const via = ctx.auth.through;
215 if (via === undefined || !tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true) return undefined;
240 // A destroying call is never held (`destroysTo` refuses it, or the door does for a non-admin).
241 if (via === undefined || !tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true || destroys(tool, args)) return undefined;
216242 const words = fenceUp(ctx.app.db, via);
217243 if (words === undefined || named(words, tool.name, args, user.username) || askedWork(ctx, user, via, tool, args, words)) return undefined;
218244 if (tooBigToApprove(args)) return tooBig(tool.name);
@@ -283,6 +309,7 @@ export function askedFirst(ctx: Ctx, user: User, tool: ToolShape, args: Args): R
283309 // An admin-only tool is refused before this, in mcp.ts (#11818).
284310 if (tool.needsAdminScope === true && !user.isAdmin) return undefined;
285311 const short = tool.needsAdminScope === true && !scopeAllows(ctx.auth.scope ?? "ro", "admin");
312 if (destroys(tool, args)) return undefined;
286313 if (!short && (!tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true || !asksFirst(tool.name, args))) return undefined;
287314 if (tooBigToApprove(args)) return tooBig(tool.name);
288315 const confirm = hold(ctx.app.db, via, user.id, tool.name, args);
src/http/mcp/tools/agent.ts +3
@@ -20,6 +20,9 @@ export const tool: Tool = {
2020 required: ["action", "username"],
2121 },
2222 writes: true,
23 tier: "delete",
24 deletes: (args) => args["action"] === "remove",
25 where: "in Settings → Crew (/settings/crew), with the agent's Delete button",
2326 adminOnly: true,
2427 needsAdminScope: true,
2528 async run(ctx, user, args) {
src/http/mcp/tools/app_data_import.ts +2
@@ -18,6 +18,8 @@ export const tool: Tool = {
1818 required: ["repo", "dump"],
1919 },
2020 writes: true,
21 tier: "delete",
22 where: "with their own token, as POST /api/v1/repos/<owner>/<name>/data-import: no page imports over an app's data",
2123 async run(ctx, user, args) {
2224 const repo = repoArg(ctx, user, args);
2325 if (isAnswer(repo)) return repo;
src/http/mcp/tools/app_domains.ts +3
@@ -35,6 +35,9 @@ export const tool: Tool = {
3535 },
3636 },
3737 writes: true,
38 tier: "delete",
39 deletes: (args) => args["action"] === "remove",
40 where: "on the app's settings page (/<owner>/<name>/settings/app), under Domains",
3841 needsAdminScope: true,
3942 async run(ctx, user, args) {
4043 const repo = repoArg(ctx, user, args);
src/http/mcp/tools/app_env.ts +3
@@ -21,6 +21,9 @@ export const tool: Tool = {
2121 required: ["repo", "action"],
2222 },
2323 writes: true,
24 tier: "delete",
25 deletes: (args) => args["action"] === "unset",
26 where: "on the app's settings page (/<owner>/<name>/settings/app), under Environment",
2427 // Its listing is a read: the forge's agent is never held on it; a read-only token is still
2528 // refused.
2629 heldNotWhen: (args) => args["action"] === "list",
src/http/mcp/tools/backups_destination.ts +2
@@ -20,6 +20,8 @@ export const tool: Tool = {
2020 required: ["action"],
2121 },
2222 writes: true,
23 tier: "delete",
24 where: "on Settings → Backups (/settings/backups)",
2325 adminOnly: true,
2426 needsAdminScope: true,
2527 run(ctx, user, args) {
src/http/mcp/tools/board_delete.ts +2
@@ -13,6 +13,8 @@ export const tool: Tool = {
1313 required: ["slug"],
1414 },
1515 writes: true,
16 tier: "delete",
17 where: "on the board's own page (/boards/<slug>), with its Delete button",
1618 async run(ctx, user, args) {
1719 if (!mayBoards(user)) return boardRefused();
1820 const done = await deleteBoard(ctx.app, user, str(args["slug"]));
src/http/mcp/tools/branches.ts +3
@@ -24,6 +24,9 @@ export const tool: Tool = {
2424 required: ["repo"],
2525 },
2626 writes: true,
27 tier: "delete",
28 deletes: (args) => args["action"] === "delete",
29 where: "on the repository's Branches page (/<owner>/<name>/branches)",
2730 readsWithout: "name",
2831 async run(ctx, user, args) {
2932 const kind = args["kind"] ?? "branches";
src/http/mcp/tools/cloud_account.ts +3
@@ -23,6 +23,9 @@ export const tool: Tool = {
2323 required: ["verb", "provider", "name"],
2424 },
2525 writes: true,
26 tier: "delete",
27 deletes: (args) => args["verb"] === "remove",
28 where: "on Settings → Cloud (/settings/cloud)",
2629 async run(ctx, user, args) {
2730 if (!user.isAdmin) return bad("not_found", "no such tool here");
2831 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
src/http/mcp/tools/drop.ts +3
@@ -21,6 +21,9 @@ export const tool: Tool = {
2121 required: ["repo"],
2222 },
2323 writes: true,
24 tier: "delete",
25 deletes: (args) => args["action"] === "remove",
26 where: "on the app's Drop page (/<owner>/<name>/drop)",
2427 readsWhen: (args) => args["action"] === undefined || args["action"] === "list" || args["action"] === "read",
2528 async run(ctx, user, args) {
2629 const repo = repoArg(ctx, user, args);
src/http/mcp/tools/forges.ts +3
@@ -23,6 +23,9 @@ export const tool: Tool = {
2323 "Forges sent from here (admin), clients, a forge plan or size.",
2424 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused", "clients"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
2525 writes: true,
26 tier: "delete",
27 deletes: (args) => args["archive"] !== undefined,
28 where: "on the Forges page (/forges), which asks before it archives",
2629 dryByDefault: true,
2730 readsWithout: ["forge", "plan", "size", "code", "revoke", "archive", "restore"],
2831 async run(ctx, user, args) {
src/http/mcp/tools/hooks.ts +3
@@ -38,6 +38,9 @@ export const tool: Tool = {
3838 required: ["repo", "action"],
3939 },
4040 writes: true,
41 tier: "delete",
42 deletes: (args) => args["action"] === "remove",
43 where: "in the repository's Webhooks settings (/<owner>/<name>/settings/hooks)",
4144 needsAdminScope: true,
4245 run(ctx, user, args) {
4346 const repo = repoArg(ctx, user, args);
src/http/mcp/tools/migrate_data.ts +3
@@ -18,6 +18,9 @@ export const tool: Tool = {
1818 required: ["repo"],
1919 },
2020 writes: true,
21 tier: "delete",
22 deletes: (args) => args["apply"] === true || args["undo"] === true,
23 where: "on the app's data move page (/<owner>/<name>/data-move)",
2124 readsWhen: (args) => args["undo"] !== true && args["apply"] !== true,
2225 run(ctx, user, args) {
2326 const repo = repoArg(ctx, user, args);
src/http/mcp/tools/mirror_set.ts +2
@@ -18,6 +18,8 @@ export const tool: Tool = {
1818 },
1919 },
2020 writes: true,
21 tier: "delete",
22 where: "on Settings → Backups (/settings/backups)",
2123 adminOnly: true,
2224 needsAdminScope: true,
2325 run(ctx, user, args) {
src/http/mcp/tools/org_teams.ts +3
@@ -24,6 +24,9 @@ export const tool: Tool = {
2424 required: ["org", "team"],
2525 },
2626 writes: true,
27 tier: "delete",
28 deletes: (args) => args["action"] === "remove",
29 where: "on the team's page (/<org>/-/teams/<team>)",
2730 needsAdminScope: true,
2831 run(ctx, user, args) {
2932 const org = getOrg(ctx.app.db, typeof args["org"] === "string" ? args["org"] : "");
src/http/mcp/tools/origin_apps.ts +3
@@ -20,6 +20,9 @@ export const tool: Tool = {
2020 },
2121 },
2222 writes: true,
23 tier: "delete",
24 deletes: (args) => args["action"] === "remove",
25 where: "on Settings → Origins (/settings/origins)",
2326 async run(ctx, user, args) {
2427 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2528 return bad("forbidden", "origin apps need an admin-scope token");
src/http/mcp/tools/prompts.ts +3
@@ -19,6 +19,9 @@ export const tool: Tool = {
1919 required: ["repo", "action"],
2020 },
2121 writes: true,
22 tier: "delete",
23 deletes: (args) => args["action"] === "remove",
24 where: "in the repository's Prompts settings (/<owner>/<name>/settings/prompts)",
2225 needsAdminScope: true,
2326 async run(ctx, user, args) {
2427 const repo = repoArg(ctx, user, args);
src/http/mcp/tools/proposal_tokens.ts +3
@@ -19,6 +19,9 @@ export const tool: Tool = {
1919 required: ["repo", "verb"],
2020 },
2121 writes: true,
22 tier: "delete",
23 deletes: (args) => args["verb"] === "revoke",
24 where: "in the repository's settings (/<owner>/<name>/settings), under Proposal tokens",
2225 // Its listing is a read: the forge's agent is never held on it; a read-only token is still
2326 // refused.
2427 heldNotWhen: (args) => args["verb"] === "list",
src/http/mcp/tools/repo_labels.ts +3
@@ -25,6 +25,9 @@ export const tool: Tool = {
2525 required: ["repo"],
2626 },
2727 writes: true,
28 tier: "delete",
29 deletes: (args) => args["action"] === "remove",
30 where: "in the repository's Labels settings (/<owner>/<name>/settings/labels)",
2831 // Listing, named or by default, is a read: a read-only token may.
2932 readsWhen: (args) => args["action"] === undefined || args["action"] === "list",
3033 run(ctx, user, args) {
src/http/mcp/tools/secrets.ts +3
@@ -17,6 +17,9 @@ export const tool: Tool = {
1717 },
1818 },
1919 writes: true,
20 tier: "delete",
21 deletes: (args) => args["action"] === "remove",
22 where: "on Settings → Secrets (/settings/secrets)",
2023 adminOnly: true,
2124 run(ctx, user, args) {
2225 // The API asks for an admin token on all three routes; so does this.
src/http/mcp/tools/ssh_keys.ts +3
@@ -18,6 +18,9 @@ export const tool: Tool = {
1818 },
1919 needsSwitch: "ssh",
2020 writes: true,
21 tier: "delete",
22 deletes: (args) => args["action"] === "remove",
23 where: "on Settings → SSH keys (/settings/keys)",
2124 readsWhen: (args) => (args["action"] ?? "list") === "list",
2225 run(ctx, user, args) {
2326 const action = args["action"] ?? "list";
src/http/mcp/tools/subscription_delete.ts +2
@@ -8,6 +8,8 @@ export const tool: Tool = {
88 description: "Remove a subscription, with its grants.",
99 inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
1010 writes: true,
11 tier: "delete",
12 where: "on Settings → Subscriptions (/settings/subscriptions)",
1113 adminOnly: true,
1214 needsAdminScope: true,
1315 run(ctx, _user, args) {
src/http/mcp/tools/whoami_can.ts +2
@@ -19,6 +19,8 @@ export const tool: Tool = {
1919 },
2020 },
2121 writes: true,
22 tier: "delete",
23 where: "on Settings → Passkeys",
2224 readsWithout: "remove",
2325 // A passkey is a way in: the person removes one on Settings → Passkeys, never their agent, not
2426 // even after a yes.
test/conversation-holds.test.ts +5 −2
@@ -237,9 +237,12 @@ describe("what nobody asked for stays held, with buttons", () => {
237237 for (const tool of Object.keys(UNDOABLE)) expect(ASKING[tool]).toBeUndefined();
238238 });
239239
240 test("deleting a branch is not the undoable kind", async () => {
240 test("deleting a branch is not the undoable kind: it is refused at once, never held (test/delete-tier.test.ts)", async () => {
241241 const w = await world(undefined, "create a branch named old in REPO, then delete it");
242 await held(w, "branches", { repo: w.repo, name: "old", action: "delete" });
242 const answer = await call(w.token, "branches", { repo: w.repo, name: "old", action: "delete" });
243 expect(answer.text).toContain("never runs from a conversation");
244 expect(answer.text).not.toContain("needs_confirm");
245 expect(confirmsIn(w.id)).toEqual([]);
243246 });
244247 });
245248
test/delete-tier.test.ts added +395
@@ -0,0 +1,395 @@
1 /**
2 * What may never run from a chat (#7650, #10262). The owner's rule: "never like delete data and
3 * stuff without showing like a red button and a delete dialog where they type the name". A tool
4 * that destroys data says so on its own definition (`tier: "delete"`, `deletes` for the calls
5 * that do, `where` for the page a person does it on). For the forge's own agent such a call is
6 * refused at once with one sentence naming that page: never held as a confirm, and never run by
7 * a Do it, even for a row held before this rule.
8 */
9
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { writeBoard } from "../src/actions/boards.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { createApp, type App } from "../src/app.ts";
17 import { readBoard } from "../src/boards/store.ts";
18 import { createConversation, listTurns } from "../src/core/conversations.ts";
19 import { heldIn, hold, readFenced } from "../src/core/fence.ts";
20 import { addKey, listKeys, parseAuthorizedKey } from "../src/core/keys.ts";
21 import { createSession } from "../src/core/sessions.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { mintViaToken } from "../src/core/via_token.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { TOOLS } from "../src/http/mcp/tools.ts";
26 import type { Tool } from "../src/http/mcp/shared.ts";
27 import { promote } from "./helpers/members.ts";
28
29 type Args = Record<string, unknown>;
30
31 /** A call of each marked tool that destroys, and one of the same tool that does not (when it has one). */
32 const SAMPLES: Readonly<
33 Record<string, { readonly destroys: Args; readonly spares?: Args }>
34 > = {
35 agent: {
36 destroys: { action: "remove", username: "builder" },
37 spares: { action: "update", username: "builder", brief: "x" },
38 },
39 app_data_import: {
40 destroys: { repo: "alice/shop", dump: "CREATE TABLE t (a);" },
41 },
42 app_domains: {
43 destroys: { repo: "alice/shop", action: "remove", host: "shop.example" },
44 spares: { repo: "alice/shop", action: "add", host: "shop.example" },
45 },
46 app_env: {
47 destroys: { repo: "alice/shop", action: "unset", name: "KEY" },
48 spares: { repo: "alice/shop", action: "set", name: "KEY", value: "v" },
49 },
50 backups_destination: { destroys: { action: "forget" } },
51 board_delete: { destroys: { slug: "ops" } },
52 branches: {
53 destroys: { repo: "alice/shop", name: "old", action: "delete" },
54 spares: { repo: "alice/shop", name: "new", action: "create" },
55 },
56 cloud_account: {
57 destroys: { verb: "remove", provider: "hetzner", name: "main" },
58 spares: { verb: "verify", provider: "hetzner", name: "main" },
59 },
60 drop: {
61 destroys: { repo: "alice/shop", action: "remove", name: "a.csv" },
62 spares: { repo: "alice/shop", action: "put", name: "a.csv", text: "a" },
63 },
64 forges: {
65 destroys: { archive: "child", dryRun: false },
66 spares: { restore: "child", dryRun: false },
67 },
68 hooks: {
69 destroys: { repo: "alice/shop", action: "remove", id: "h1" },
70 spares: { repo: "alice/shop", action: "pause", id: "h1" },
71 },
72 migrate_data: {
73 destroys: { repo: "alice/shop", dump: "old.sql", apply: true },
74 spares: { repo: "alice/shop", dump: "old.sql" },
75 },
76 mirror_set: { destroys: { action: "forget" } },
77 org_teams: {
78 destroys: { org: "acme", action: "remove", team: "core" },
79 spares: { org: "acme", action: "create", team: "core" },
80 },
81 origin_apps: {
82 destroys: { action: "remove", id: "o1" },
83 spares: { action: "add", host: "git.example" },
84 },
85 prompts: {
86 destroys: { repo: "alice/shop", action: "remove", id: "p1" },
87 spares: { repo: "alice/shop", action: "run", id: "p1" },
88 },
89 proposal_tokens: {
90 destroys: { repo: "alice/shop", verb: "revoke", id: "t1" },
91 spares: {
92 repo: "alice/shop",
93 verb: "mint",
94 child: "kid",
95 origin: "https://kid.example",
96 },
97 },
98 repo_labels: {
99 destroys: { repo: "alice/shop", action: "remove", id: "l1" },
100 spares: { repo: "alice/shop", action: "create", name: "bug" },
101 },
102 secrets: {
103 destroys: { scope: "forge", action: "remove", name: "KEY" },
104 spares: { scope: "forge", action: "set", name: "KEY", value: "v" },
105 },
106 ssh_keys: {
107 destroys: { action: "remove", id: "k1" },
108 spares: { action: "add", key: "ssh-ed25519 AAAA" },
109 },
110 subscription_delete: { destroys: { id: "s1" } },
111 whoami_can: { destroys: { kind: "passkeys", remove: "p1" } },
112 };
113
114 /**
115 * Write tools whose name or description uses a destroying word and that destroy nothing a person
116 * cannot put back: each with its reason. Anything else that says such a word carries the mark.
117 */
118 const SPARED: Readonly<Record<string, string>> = {
119 account_access: "a reset mints a one-use link; the person's password and passkeys stand until they use it",
120 claim_link: "a revoked claim link is restored by `undo`, and a new one can always be revealed",
121 crew: "an agent taken off a repository's crew is seated again with `add`; nothing it did is lost",
122 egress_grants: "a revoked grant is granted again by the same tool; no data goes with it",
123 invites: "a revoked invite is an unused link; a new one is minted in its place",
124 sever: "it unlinks and, as it says, deletes nothing: both sides keep all they hold",
125 };
126
127 /**
128 * Words that say a tool destroys something. "Clear" and "replace" are left out: they name a
129 * setting put back to its default or set again in one call, which is nothing lost.
130 */
131 const SAYS_DESTROYS = /delet|remov|purg|wip(e|ing)|reset|eras|destroy|forget|revok|unset|(^|[^a-z])import(s|ed|ing)?(?![a-z])|overwrit/i;
132
133 /** The mark as the door reads it. */
134 const marked = (t: Tool): boolean => (t as { tier?: string }).tier === "delete";
135 const destroys = (t: Tool, args: Args): boolean =>
136 marked(t) &&
137 ((t as { deletes?: (a: Args) => boolean }).deletes?.(args) ?? true);
138 const whereOf = (t: Tool): string => (t as { where?: string }).where ?? "";
139
140 describe("every tool that destroys data says so", () => {
141 const writes = TOOLS.filter((t) => t.writes);
142
143 test("a write whose name or description says it destroys carries the mark, or a reason it does not", () => {
144 const unmarked = writes
145 .filter(
146 (t) =>
147 SAYS_DESTROYS.test(`${t.name} ${t.description}`) &&
148 !marked(t) &&
149 SPARED[t.name] === undefined,
150 )
151 .map((t) => t.name);
152 expect(
153 unmarked,
154 'mark each `tier: "delete"` with `where`, or add it to SPARED with the reason',
155 ).toEqual([]);
156 });
157
158 test("the spared list holds only live, unmarked write tools that do say such a word", () => {
159 for (const [name, why] of Object.entries(SPARED)) {
160 const tool = writes.find((t) => t.name === name);
161 expect(tool, `${name} is not a write tool`).toBeDefined();
162 expect(marked(tool!), `${name} is marked and spared`).toBe(false);
163 expect(
164 SAYS_DESTROYS.test(`${name} ${tool!.description}`),
165 `${name} no longer needs sparing`,
166 ).toBe(true);
167 expect(why.length, name).toBeGreaterThan(20);
168 }
169 });
170
171 test("the marked tools are exactly the ones this test holds a destroying call for", () => {
172 expect(
173 TOOLS.filter(marked)
174 .map((t) => t.name)
175 .toSorted(),
176 ).toEqual(Object.keys(SAMPLES).toSorted());
177 for (const name of [
178 "board_delete",
179 "app_data_import",
180 "subscription_delete",
181 "backups_destination",
182 "mirror_set",
183 "whoami_can",
184 ])
185 expect(SAMPLES[name], name).toBeDefined();
186 });
187
188 test("a marked tool writes, names where a person does it, and marks only its destroying calls", () => {
189 for (const t of TOOLS.filter(marked)) {
190 expect(t.writes, t.name).toBe(true);
191 expect(whereOf(t).length, `${t.name} names no page`).toBeGreaterThan(10);
192 const sample = SAMPLES[t.name]!;
193 expect(destroys(t, sample.destroys), `${t.name} destroying call`).toBe(
194 true,
195 );
196 if (sample.spares !== undefined)
197 expect(destroys(t, sample.spares), `${t.name} other call`).toBe(false);
198 }
199 });
200 });
201
202 const KEY =
203 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDo alice";
204
205 let dir: string;
206 let app: App;
207 let servers: Servers;
208 let olive: User;
209 let alice: User;
210 let rpc = 1;
211
212 const call = async (token: string, name: string, args: Args) => {
213 const res = await fetch(`${servers.url}/mcp`, {
214 method: "POST",
215 headers: {
216 "content-type": "application/json",
217 accept: "application/json, text/event-stream",
218 authorization: `Bearer ${token}`,
219 },
220 body: JSON.stringify({
221 jsonrpc: "2.0",
222 id: rpc++,
223 method: "tools/call",
224 params: { name, arguments: args },
225 }),
226 });
227 const body = (await res.json()) as {
228 result?: { content?: { text: string }[]; isError?: boolean };
229 error?: { message: string };
230 };
231 return {
232 text: body.result?.content?.[0]?.text ?? body.error?.message ?? "",
233 isError: body.result?.isError === true || body.error !== undefined,
234 };
235 };
236
237 /** A conversation of `who`'s and the token its agent speaks with. */
238 function talk(who: User, words = "tidy up for me") {
239 const c = createConversation(app.db, who.id);
240 if (!c.ok) throw new Error(c.error);
241 const via = `conversation:${c.value.id}`;
242 const minted = mintViaToken(
243 app.db,
244 who.id,
245 via,
246 words,
247 new Date(Date.now() + 600_000).toISOString(),
248 );
249 if (!minted.ok) throw new Error(minted.error);
250 return { id: c.value.id, via, token: minted.value.token };
251 }
252
253 /** The person's Do it, as their browser sends it. */
254 const yes = (confirm: string, who: User) =>
255 fetch(`${servers.url}/api/v1/conversation-confirms/${confirm}`, {
256 method: "POST",
257 headers: {
258 origin: servers.url,
259 cookie: `forge_session=${createSession(app.db, who.id).token}`,
260 },
261 });
262
263 const confirmTurns = (who: User, conversationId: string) => {
264 const turns = listTurns(app.db, who.id, conversationId, { limit: 50 });
265 return turns.ok ? turns.value.filter((t) => t.role === "confirm") : [];
266 };
267
268 beforeAll(async () => {
269 dir = await mkdtemp(join(tmpdir(), "forge-delete-tier-"));
270 app = createApp({ dataDir: dir, port: 0 });
271 servers = await serve(app);
272 const mk = async (username: string, first = false) => {
273 const u = await createUser(app.db, {
274 origin: "seed",
275 trusted: true,
276 username,
277 email: `${username}@forge.local`,
278 password: "a-good-passphrase",
279 adminIfFirst: first,
280 });
281 if (!u.ok) throw new Error(u.error);
282 promote(app.db, u.value);
283 return u.value;
284 };
285 olive = await mk("olive", true);
286 alice = await mk("alice");
287 const made = await createRepo(app, alice, {
288 name: "shop",
289 visibility: "public",
290 });
291 if (!made.ok) throw new Error(String(made.error));
292 });
293
294 afterAll(async () => {
295 await servers.stop();
296 app.close();
297 await rm(dir, { recursive: true, force: true });
298 });
299
300 describe("a destroying call from a conversation is refused at once, never held", () => {
301 test.each(Object.keys(SAMPLES))(
302 "%s: one sentence naming the page, no confirm, fence down or up",
303 async (name) => {
304 const tool = TOOLS.find((t) => t.name === name)!;
305 for (const up of [false, true]) {
306 // The forge's admin, so nothing but the mark stands between the agent and the tool.
307 const t = talk(olive);
308 if (up) readFenced(app.db, t.via);
309 const answer = await call(t.token, name, SAMPLES[name]!.destroys);
310 expect(
311 answer.isError,
312 `${name} ${up ? "fence up" : "fence down"}: ${answer.text}`,
313 ).toBe(true);
314 // Refused as `refusedToAgent` refuses: a tool with a sentence of its own keeps it.
315 expect(answer.text.startsWith("forbidden: ")).toBe(true);
316 if (tool.refusedToAgent === undefined) expect(answer.text).toContain("never runs from a conversation");
317 expect(answer.text).toContain(whereOf(tool));
318 expect(heldIn(app.db, t.via)).toEqual([]);
319 expect(confirmTurns(olive, t.id)).toEqual([]);
320 }
321 },
322 );
323
324 test("an everyday account's agent holds nothing either, and learns of no admin tool", async () => {
325 for (const name of Object.keys(SAMPLES)) {
326 const t = talk(alice);
327 readFenced(app.db, t.via);
328 const answer = await call(t.token, name, SAMPLES[name]!.destroys);
329 expect(answer.isError, name).toBe(true);
330 expect(heldIn(app.db, t.via), name).toEqual([]);
331 const tool = TOOLS.find((x) => x.name === name)!;
332 if (tool.adminOnly === true || tool.needsAdminScope === true)
333 expect(answer.text, name).not.toContain(
334 "never runs from a conversation",
335 );
336 }
337 });
338
339 test("the same tool's other calls are held or run as before", async () => {
340 const t = talk(alice);
341 // Setting a variable still asks first, with its buttons; only unsetting one is refused.
342 const asked = await call(t.token, "app_env", { repo: "alice/shop", action: "set", name: "KEY", value: "v" });
343 expect(typeof JSON.parse(asked.text).needs_confirm).toBe("string");
344 expect(heldIn(app.db, t.via).map((h) => h.tool)).toEqual(["app_env"]);
345 // Creating a branch is not a delete: whatever it answers, it is not this refusal.
346 const made = await call(t.token, "branches", { repo: "alice/shop", name: "next", action: "create" });
347 expect(made.text).not.toContain("never runs from a conversation");
348 });
349 });
350
351 describe("Do it never runs a destroying call", () => {
352 test("a key removal held before this rule is refused on yes: the key stays, and the thread says where to remove it", async () => {
353 const parsed = parseAuthorizedKey(KEY);
354 if (!parsed.ok) throw new Error("key");
355 const key = addKey(app.db, alice.id, "laptop", parsed.value);
356 if (!key.ok) throw new Error("key not added");
357 const t = talk(alice);
358 // The row as the door kept it before the mark existed.
359 const held = hold(app.db, t.via, alice.id, "ssh_keys", {
360 action: "remove",
361 id: key.value.id,
362 });
363 if (held === null) throw new Error("not held");
364 const said = await yes(held, alice);
365 expect(said.status).toBe(409);
366 expect(((await said.json()) as { error: string }).error).toBe("delete");
367 expect(listKeys(app.db, alice.id).map((k) => k.id)).toContain(key.value.id);
368 const turns = listTurns(app.db, alice.id, t.id, { limit: 50 });
369 const last = turns.ok ? turns.value.at(-1) : undefined;
370 expect(last?.role).toBe("tool");
371 expect(last?.text).toContain("/settings/keys");
372 expect(JSON.parse(last!.text).done).toBe(false);
373 // Claimed all the same: it cannot be said yes to again.
374 expect((await yes(held, alice)).status).toBe(409);
375 expect(
376 heldIn(app.db, t.via).every((h) => Object.keys(h.args).length === 0),
377 ).toBe(true);
378 });
379
380 test("a held board_delete is refused on yes and the board stays", async () => {
381 const made = await writeBoard(app, olive, "ops", {
382 title: "Ops",
383 range: "all",
384 refresh: "off",
385 panels: [],
386 });
387 if (!made.ok) throw new Error(`board: ${JSON.stringify(made.error)}`);
388 const t = talk(olive);
389 const held = hold(app.db, t.via, olive.id, "board_delete", { slug: "ops" });
390 if (held === null) throw new Error("not held");
391 const said = await yes(held, olive);
392 expect(said.status).toBe(409);
393 expect(await readBoard(app.reposRoot, "ops")).toBeDefined();
394 });
395 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs