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

Every write from a game-door conversation waits for the person's yes (#18247) #18253

opened this

Conflicts with main in 3 files

src/games/chat.ts · src/http/mcp/shared.ts · test/game-door.test.ts

sold/game-door-writes-held → main 1 commit

Review

Sign in to review this change.
6 files changed +113 −14
src/core/conversations.ts +18
@@ -349,6 +349,24 @@ export function conversationOfVia(db: Database, userId: string, via: string): Co
349349 return getConversation(db, userId, via.slice("conversation:".length)) ?? openConversation(db, userId);
350350 }
351351
352 /**
353 * The door a conversation took words through other than the web and the app (#18247): `game` once
354 * a game player's words reached it. The mark stays for the conversation's life, for what a game
355 * said stays in its context.
356 */
357 export type Door = "game";
358
359 /** Mark a person's conversation as taking words through `door`. */
360 export function markDoor(db: Database, userId: string, conversationId: string, door: Door): void {
361 db.query("UPDATE conversation SET door = ?3 WHERE id = ?1 AND user_id = ?2").run(conversationId, userId, door);
362 }
363
364 /** Whether the conversation a via token writes to took a game player's words. */
365 export function viaFromGame(db: Database, userId: string, via: string): boolean {
366 const id = conversationOfVia(db, userId, via).id;
367 return db.query<{ door: string }, [string]>("SELECT door FROM conversation WHERE id = ?1").get(id)?.door === "game";
368 }
369
352370 /**
353371 * What the agent last said to the person before the words `words`, when they
354372 * are the person's newest turn in the conversation the via names and that
src/core/migration-pins/20261204162000-conversation-door.pin added +1
@@ -0,0 +1,1 @@
1 9450ecb62eae3be9503b7e36a82ab46123cd183dae87bda257af149178b650c0
src/core/migrations/20261204162000-conversation-door.ts added +6
@@ -0,0 +1,6 @@
1 // The door a conversation took words through (#18247): 'game' once a game player's words reached
2 // it, and every write its agent makes then waits for the person's yes. Additive; every
3 // conversation before this reads '', the web's and the app's, and nothing about them changes.
4 export default `
5 ALTER TABLE conversation ADD COLUMN door TEXT NOT NULL DEFAULT '';
6 `;
src/games/chat.ts +6 −2
@@ -27,7 +27,7 @@
2727 import type { App } from "../app.ts";
2828 import { waitingConfirms } from "../actions/conversation_confirms.ts";
2929 import { talk } from "../actions/talk.ts";
30 import { createConversation, listTurns } from "../core/conversations.ts";
30 import { createConversation, listTurns, markDoor } from "../core/conversations.ts";
3131 import { readReceipt } from "../crew/receipt.ts";
3232 import { publicOrigin } from "../core/public_origin.ts";
3333 import { getUserById, isActive, type User } from "../core/users.ts";
@@ -695,7 +695,11 @@ function ask(app: App, box: GameBox, job: Job, user: User): void {
695695 const kept = door
696696 ? db.query<{ conversation: string }, [string, string]>("SELECT conversation FROM game_talk WHERE box_id = ?1 AND user_id = ?2").get(box.id, user.id)?.conversation
697697 : undefined;
698 const into = (id: string) => talk(app, user, job.words, [], "inject", id);
698 // Marked before the words go in, so no write of the turn they start runs without a yes.
699 const into = (id: string) => {
700 markDoor(db, user.id, id, "game");
701 return talk(app, user, job.words, [], "inject", id);
702 };
699703 let id = kept;
700704 let sent = kept === undefined ? undefined : into(kept);
701705 const gone = sent !== undefined && !sent.ok && sent.error === "not_found";
src/http/mcp/shared.ts +6 −3
@@ -19,7 +19,7 @@ import type { BoardError } from "../../actions/boards.ts";
1919 import { BOARD_NOT_SAVED } from "../../actions/board_words.ts";
2020 import { askedFor, fence, fenceTag, fenceUp, hold, named, readFenced, supersedeHeld } from "../../core/fence.ts";
2121 import { laneUnheld } from "../../core/talk_lane.ts";
22 import { appendTurn, conversationOfVia, proposalBefore } from "../../core/conversations.ts";
22 import { appendTurn, conversationOfVia, proposalBefore, viaFromGame } from "../../core/conversations.ts";
2323 import { writesThisTurn } from "../../core/conversation_writes.ts";
2424 import { argumentsShown, asksFirst, destroysData, destroysSentence, tooBigToApprove, undoableWork } from "../../crew/conversation_confirm.ts";
2525 import { confirmSentence, SAID_MAX } from "../../crew/conversation_ask.ts";
@@ -368,7 +368,9 @@ export const ASKS_FIRST =
368368 * list in `crew/conversation_confirm.ts` — and any call of an admin-scope
369369 * tool its rw token cannot reach, when the person is an admin — is kept as a
370370 * confirm with one sentence of what it will do, written to the person's
371 * conversation as a `confirm` turn, and not done. Undefined: go on.
371 * conversation as a `confirm` turn, and not done. In a conversation a game
372 * player's words reached, every write asks (#18247): what was typed in a game
373 * changes nothing until the person says yes. Undefined: go on.
372374 */
373375 export function askedFirst(ctx: Ctx, user: User, tool: ToolShape, args: Args): Record<string, unknown> | undefined {
374376 const via = ctx.auth.through;
@@ -378,7 +380,8 @@ export function askedFirst(ctx: Ctx, user: User, tool: ToolShape, args: Args): R
378380 if (tool.needsAdminScope === true && !adminAccount(ctx.app.db, user)) return undefined;
379381 const short = tool.needsAdminScope === true && !scopeAllows(ctx.auth.scope ?? "ro", "admin");
380382 if (destroys(tool, args)) return undefined;
381 if (!short && (!tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true || !asksFirst(tool.name, args))) return undefined;
383 if (!short && (!tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true || !(asksFirst(tool.name, args) || viaFromGame(ctx.app.db, user.id, via))))
384 return undefined;
382385 if (tooBigToApprove(args)) return tooBig(tool.name);
383386 const confirm = hold(ctx.app.db, via, user.id, tool.name, args);
384387 const does = confirm === null ? "" : drawConfirm(ctx, user, via, confirm, tool, args);
test/game-door.test.ts +76 −9
@@ -10,7 +10,9 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1212 import { createApp, type App } from "../src/app.ts";
13 import { appendTurn } from "../src/core/conversations.ts";
13 import { appendTurn, createConversation } from "../src/core/conversations.ts";
14 import { createIssue, getIssue } from "../src/core/issues.ts";
15 import { getRepo } from "../src/core/repos.ts";
1416 import { hold, waitingFor } from "../src/core/fence.ts";
1517 import { createSession } from "../src/core/sessions.ts";
1618 import { mintViaToken } from "../src/core/via_token.ts";
@@ -316,11 +318,9 @@ test("a change in any phrasing goes to Talk as words, and the door itself change
316318 }
317319 });
318320
319 test("what a crew turn does for a game player: the games tool and an admin write are held, never run (the forge's one policy, as in Talk)", async () => {
320 await toldFor("restart the hub");
321 const id = conversation()!;
322 const via = `conversation:${id}`;
323 const minted = mintViaToken(app.db, ada.id, via, "", new Date(Date.now() + 10 * 60_000).toISOString());
321 /** The forge's own agent's tool calls in the conversation `id`, as its via token makes them. */
322 async function agentIn(id: string) {
323 const minted = mintViaToken(app.db, ada.id, `conversation:${id}`, "", new Date(Date.now() + 10 * 60_000).toISOString());
324324 if (!minted.ok) throw new Error(minted.error);
325325 const servers = await serve(app);
326326 const tool = async (name: string, args: Record<string, unknown>) => {
@@ -329,9 +329,32 @@ test("what a crew turn does for a game player: the games tool and an admin write
329329 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${minted.value.token}` },
330330 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
331331 });
332 const body = (await res.json()) as { result?: { content?: { text?: string }[]; isError?: boolean } };
333 return JSON.parse(body.result?.content?.[0]?.text ?? "{}") as Record<string, unknown>;
332 const body = (await res.json()) as { result?: { content?: { text?: string }[] } };
333 const text = body.result?.content?.[0]?.text ?? "{}";
334 try {
335 return JSON.parse(text) as Record<string, unknown>;
336 } catch {
337 return { text };
338 }
334339 };
340 return { tool, stop: () => servers.stop() };
341 }
342
343 /** Reversible writes that run at once with an Undo in Talk, each a call a crew turn could make. */
344 const undoable = (issue: number): [string, Record<string, unknown>][] => [
345 ["merge", { repo: "ada/net", number: issue, dryRun: false }],
346 ["edit", { repo: "ada/net", number: issue, title: "Renamed by the crew" }],
347 ["write_file", { repo: "ada/net", branch: "from-talk", path: "note.txt", content: "a note", message: "Add a note" }],
348 ["tell", { repo: "ada/net", text: "Make the hub start faster" }],
349 ["open_pull", { repo: "ada/net", title: "A note", files: [{ path: "note.txt", content: "a note" }] }],
350 ];
351 const rowsOf = (repoId: string): number => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?1").get(repoId)!.n;
352 const writesBy = (id: string): number => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM conversation_write WHERE via = ?1").get(`conversation:${id}`)!.n;
353
354 test("what a crew turn does for a game player: the games tool and an admin write are held, never run (the forge's one policy, as in Talk)", async () => {
355 await toldFor("restart the hub");
356 const id = conversation()!;
357 const { tool, stop } = await agentIn(id);
335358 try {
336359 const waiting = () => waitingFor(app.db, ada.id).length;
337360 for (const args of [
@@ -354,10 +377,54 @@ test("what a crew turn does for a game player: the games tool and an admin write
354377 // A read is not held.
355378 expect((await tool("games", { action: "list" }))["needs_confirm"]).toBeUndefined();
356379 } finally {
357 servers.stop();
380 stop();
358381 }
359382 }, 30_000);
360383
384 test("from a game turn every write waits for the person's yes and does nothing; a read runs (#18247)", async () => {
385 await toldFor("tidy up the net repo");
386 const id = conversation()!;
387 const net = getRepo(app.db, "ada", "net")!;
388 const issue = createIssue(app.db, { repoId: net.id, authorId: ada.id, title: "The hub lags" });
389 if (!issue.ok) throw new Error(issue.error);
390 const rows = rowsOf(net.id);
391 const { tool, stop } = await agentIn(id);
392 try {
393 for (const [name, args] of undoable(issue.value.number)) {
394 const before = waitingFor(app.db, ada.id).length;
395 const said = await tool(name, args);
396 expect(said["needs_confirm"], name).toEqual(expect.any(String));
397 expect(waitingFor(app.db, ada.id).length, name).toBe(before + 1);
398 }
399 // Nothing ran: no write recorded, the issue as it was, no issue or pull made.
400 expect(writesBy(id)).toBe(0);
401 expect(getIssue(app.db, net.id, issue.value.number)?.title).toBe("The hub lags");
402 expect(rowsOf(net.id)).toBe(rows);
403 // A read is not held.
404 expect((await tool("games", { action: "list" }))["needs_confirm"]).toBeUndefined();
405 } finally {
406 stop();
407 }
408 }, 30_000);
409
410 test("the same writes from a web conversation run at once, as before", async () => {
411 const net = getRepo(app.db, "ada", "net")!;
412 const issue = createIssue(app.db, { repoId: net.id, authorId: ada.id, title: "The proxy lags" });
413 if (!issue.ok) throw new Error(issue.error);
414 // Each the first call of its own conversation, as the first write of a web turn is.
415 for (const [name, args] of undoable(issue.value.number)) {
416 const id = createConversation(app.db, ada.id).value.id;
417 const { tool, stop } = await agentIn(id);
418 try {
419 expect((await tool(name, args))["needs_confirm"], name).toBeUndefined();
420 } finally {
421 stop();
422 }
423 }
424 expect(waitingFor(app.db, ada.id)).toHaveLength(0);
425 expect(getIssue(app.db, net.id, issue.value.number)?.title).toBe("Renamed by the crew");
426 }, 30_000);
427
361428 test("the reply ends with a held action and a reversible change it made, each said, and the link last", async () => {
362429 await toldFor("close the first issue and archive the repo");
363430 const id = conversation()!;

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs