diff --git a/AGENTS.md b/AGENTS.md index 40229518f..7cf710b0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -669,7 +669,11 @@ A retry is found in storage, is compared against the base the first call recorded, and posts the linked line only if the first call could not save it. The document is stored before the sidebar, the asking Chat's one linked line (`Entry.document`) or its optional first instruction (posted as -the creator's message, as `invoke_planner` does) hear of it. See +the creator's message, as `invoke_planner` does) hear of it. Each records the +document it was created from (`ChannelRecord.createdFrom`), and the Planner's +`fan_out` tool opens several at once, lists their state, instructs their Planners +and keeps a table of them in the creating document, reaching only documents whose +`createdFrom` is its own. See [Creating documents](docs/hosted-agent.md#creating-documents). ## Research requests and child documents diff --git a/apps/server/src/agent/fan-out-index.ts b/apps/server/src/agent/fan-out-index.ts new file mode 100644 index 000000000..9ad7bd23f --- /dev/null +++ b/apps/server/src/agent/fan-out-index.ts @@ -0,0 +1,100 @@ +/** + * The table of the documents a document created, kept in that document under its own heading: the + * heading and the one block after it are Chopin's, and every other block is left alone. Written as + * an ordinary validated, persisted-before-published edit, and not at all when nothing changed. + */ +import * as edit from "../plan/edit"; +import { admitBlockEdit, applyBlockEdit } from "./document-ops"; +import { implementationActive } from "../plan/service"; + +import type { CreatedDocumentState, IndexOutcome } from "./fan-out"; +import type { DocumentRoom } from "./tools"; + +export const INDEX_HEADING = "Documents created from this one"; +const EMPTY = "No document has been created from this one yet."; +/** A batch that finds the document moved on between its read and its write is tried this often. */ +const ATTEMPTS = 3; + +function cell(text: string): string { + return text.replace(/\s+/g, " ").replace(/([\\|[\]])/g, "\\$1").trim(); +} + +/** The section's body: one table row per document, or a sentence when there are none. */ +export function indexBody(documents: CreatedDocumentState[]): string { + if (documents.length === 0) return EMPTY; + return [ + "| Document | Planner | Open decisions | Build |", + "| --- | --- | --- | --- |", + ...documents.map(document => + `| [${cell(document.title)}](${document.url}) | ${document.planner} | ` + + `${document.openDecisions} | ${document.build} |` + ), + ].join("\n"); +} + +type Located = + | { state: "absent" | "unchanged" } + | { state: "refused"; reason: string; message?: string } + | { state: "edit"; revision: number; operations: edit.Operation[] }; + +function locate(plan: DocumentRoom["plan"], body: string, create: boolean): Located { + if (implementationActive(plan)) return { state: "refused", reason: "locked" }; + let blocks = edit.outline(plan); + let heading = blocks.findIndex(block => + block.type === "heading" && block.preview.trim() === INDEX_HEADING + ); + if (heading < 0 && !create) return { state: "absent" }; + let next = blocks[heading + 1]; + let owned = !!next && (next.type === "table" || next.preview.trim() === EMPTY); + let operations: edit.Operation[] = heading < 0 + ? [{ op: "insert_root", source: `## ${INDEX_HEADING}\n\n${body}\n` }] + : owned + ? [{ op: "replace", index: heading + 1, source: `${body}\n` }] + : [{ op: "insert", index: heading, source: `${body}\n` }]; + let prepared = edit.prepare(plan, plan.revision, operations); + if (!prepared.ok) { + return { + state: "refused", + reason: prepared.reason, + ...("message" in prepared ? { message: prepared.message } : {}), + }; + } + if (prepared.source === edit.source(plan)) return { state: "unchanged" }; + return { state: "edit", revision: plan.revision, operations }; +} + +/** Writes or refreshes `room`'s table of `documents`; with `create` false, only one already there. */ +export async function writeIndex( + room: DocumentRoom, + documents: CreatedDocumentState[], + create: boolean, + signal?: AbortSignal, +): Promise { + let body = indexBody(documents); + for (let attempt = 0; attempt < ATTEMPTS; attempt++) { + if (signal?.aborted) return { state: "refused", reason: "cancelled" }; + let located = await room.exclusive(async () => locate(room.plan, body, create)); + if (located.state !== "edit") return located; + let args = { revision: located.revision, operations: located.operations }; + let refusal = await admitBlockEdit(room, args, signal); + if (refusal) { + if (refusal.reason === "stale") continue; + return { + state: "refused", + reason: refusal.reason, + ...("message" in refusal && typeof refusal.message === "string" + ? { message: refusal.message } + : {}), + }; + } + let result = await room.exclusive(() => applyBlockEdit(room, args, { signal })); + if (result.ok) return { state: "written" }; + if (result.reason === "stale") continue; + return { + state: "refused", + reason: result.reason, + ...("message" in result ? { message: result.message } : {}), + }; + } + return { state: "refused", reason: "stale" }; +} diff --git a/apps/server/src/agent/fan-out.test.ts b/apps/server/src/agent/fan-out.test.ts new file mode 100644 index 000000000..9abea6e67 --- /dev/null +++ b/apps/server/src/agent/fan-out.test.ts @@ -0,0 +1,373 @@ +import { describe, expect, test } from "bun:test"; + +import { MemoryStorage } from "../storage/memory/adapter"; +import { createDocument } from "../mcp/hosted"; +import { openPlan } from "../testing/plan"; +import * as edit from "../plan/edit"; +import { buildState, fanOut, fanOutArguments, MAX_OPEN } from "./fan-out"; +import { INDEX_HEADING, writeIndex } from "./fan-out-index"; +import { documentRoom } from "./heading-harness.test-fixtures"; + +import type { AuthenticatedSession } from "../auth/session"; +import type { Repository } from "../github/client"; +import type { PlannerInvocation } from "../mcp/hosted"; +import type { InvokePlannerError } from "../mcp"; +import type { NewDocumentArguments } from "./new-documents"; +import type { + BuildState, + CreatedDocumentState, + FanOutArguments, + FanOutDeps, + IndexWriter, + PlannerState, +} from "./fan-out"; +import type { BuildRequest } from "@chopin/protocol/implementation"; + +const NOW = new Date("2026-11-16T12:00:00.000Z"); +const HEAD = "0123456789abcdef0123456789abcdef01234567"; + +let brief = { + goal: "Verify one part of the app.", + constraints: [], + settledDecisions: [], + openQuestions: [], + repositoryFindings: [], +}; + +function piece(key: string, title: string, instruction?: string): NewDocumentArguments { + return { + idempotencyKey: key, + title, + brief, + document: `# ${title}\n\nOne part of the app.\n`, + ...(instruction ? { instruction } : {}), + }; +} + +function login(): AuthenticatedSession { + return { + session: { id: "session-U_mona", userId: "U_mona" }, + user: { id: "U_mona", login: "mona", avatarUrl: "", createdAt: NOW, updatedAt: NOW }, + } as unknown as AuthenticatedSession; +} + +function repository(push = true): Repository { + return { + id: "R_app", + owner: "octo", + name: "app", + fullName: "octo/app", + private: true, + url: "https://github.test/octo/app", + defaultBranch: "trunk", + permissions: { pull: true, push, admin: false }, + }; +} + +async function fixture( + options: { push?: boolean; refuse?: Record } = {}, +) { + let storage = new MemoryStorage(); + await storage.users.put({ id: "U_mona", login: "mona", avatarUrl: "", now: NOW }); + let fields = { + repositoryId: "R_app", + repositoryOwner: "octo", + repositoryName: "app", + createdBy: "U_mona", + now: NOW, + }; + let source = await storage.channels.create({ + ...fields, + id: crypto.randomUUID(), + title: "Whole app", + }); + let invocations: PlannerInvocation[] = []; + let planners = new Map(); + let builds = new Map(); + let push = options.push ?? true; + let deps: FanOutDeps = { + channel: id => storage.channels.get(id), + deleting: () => false, + login: async () => login(), + repository: async () => repository(push), + branchHead: async () => HEAD, + origin: async () => undefined, + created: async () => undefined, + create: (creator, input) => createDocument({ storage, clock: () => NOW }, {}, creator, input), + modelChoice: async () => undefined, + invoke: async input => { + invocations.push(input); + return options.refuse?.[input.channel.title]; + }, + refusal: async code => code === "planner-busy" ? "It is answering someone now." : undefined, + appOrigin: "https://chopin.test", + createdFrom: (sourceId, limit) => storage.channels.createdFrom(sourceId, limit), + planner: id => planners.get(id) ?? "stopped", + build: async id => builds.get(id) ?? "not built", + }; + let indexed: Array<{ documents: CreatedDocumentState[]; create: boolean }> = []; + let index: IndexWriter = async (documents, create) => { + indexed.push({ documents, create }); + return create ? { state: "written" } : { state: "absent" }; + }; + let call = (args: FanOutArguments) => + fanOut(deps, { + sourceId: source.id, + creator: { userId: "U_mona", handle: "mona" }, + arguments: args, + announce: async () => {}, + index, + }); + let open = async (...documents: NewDocumentArguments[]) => { + let result = await call({ operation: "open", documents }); + if (!result.ok || result.operation !== "open") throw new Error("open failed"); + return result.documents.map(document => { + if (!document.ok) throw new Error(document.message); + return document.document; + }); + }; + return { storage, source, fields, deps, invocations, planners, builds, indexed, call, open }; +} + +/** Documents created at the same moment are listed in no promised order. */ +function byTitle(documents: T[]): T[] { + return documents.toSorted((left, right) => left.title.localeCompare(right.title)); +} + +describe("fan_out arguments", () => { + test("take each operation's own fields only", () => { + expect(fanOutArguments({ operation: "list" })).toEqual({ operation: "list" }); + expect(fanOutArguments({ operation: "instruct", instruction: "Resume." })).toEqual({ + operation: "instruct", + instruction: "Resume.", + }); + expect(() => fanOutArguments({ operation: "list", instruction: "Resume." })).toThrow( + "fan_out list does not take `instruction`", + ); + expect(() => fanOutArguments({ operation: "close" })).toThrow("operation must be one of"); + expect(() => fanOutArguments({ operation: "instruct" })).toThrow("instruction"); + expect(() => fanOutArguments({ operation: "instruct", instruction: "Go.", targets: [] })) + .toThrow("targets"); + }); + + test("open checks every document as create_document does, and needs distinct keys", () => { + expect(() => fanOutArguments({ operation: "open", documents: [] })).toThrow("at least one"); + expect(() => + fanOutArguments({ + operation: "open", + documents: [piece("login-page", "Login"), { title: "x" }], + }) + ).toThrow("documents[1]: idempotencyKey"); + expect(() => + fanOutArguments({ + operation: "open", + documents: [piece("login-page", "Login"), piece("login-page", "Login again")], + }) + ).toThrow("its own idempotencyKey"); + let many = Array.from({ length: MAX_OPEN + 1 }, (_, n) => piece(`document-${n}`, `D${n}`)); + expect(() => fanOutArguments({ operation: "open", documents: many })).toThrow("at most"); + }); +}); + +describe("fanOut", () => { + test("open creates each document linked to this one, and a retry makes none twice", async () => { + let context = await fixture(); + let opened = await context.open( + piece("login-page", "Login", "Plan the login page."), + piece("checkout-flow", "Checkout"), + ); + expect(opened.map(document => document.title)).toEqual(["Login", "Checkout"]); + for (let document of opened) { + expect((await context.storage.channels.get(document.id))?.createdFrom).toBe( + context.source.id, + ); + } + expect(context.invocations.map(invocation => invocation.instruction)).toEqual([ + "Plan the login page.", + ]); + let again = await context.call({ + operation: "open", + documents: [piece("login-page", "Login")], + }); + expect(again).toMatchObject({ ok: true, documents: [{ replayed: true, document: opened[0] }] }); + expect(await context.storage.channels.createdFrom(context.source.id, 10)).toHaveLength(2); + expect(context.indexed.map(item => item.create)).toEqual([false, false]); + }); + + test("list reports what this document created, with each Planner, open Decisions and build", async () => { + let context = await fixture(); + let [login, checkout] = await context.open( + piece("login-page", "Login"), + piece("checkout-flow", "Checkout"), + ); + await context.storage.channels.create({ + ...context.fields, + id: crypto.randomUUID(), + title: "Made by a person", + }); + context.planners.set(login!.id, "working"); + context.builds.set(checkout!.id, "built"); + let listed = await context.call({ operation: "list" }); + if (!listed.ok || listed.operation !== "list") throw new Error("list failed"); + expect(byTitle(listed.documents)).toEqual([ + { + id: checkout!.id, + title: "Checkout", + url: checkout!.url, + planner: "stopped", + openDecisions: 0, + build: "built", + }, + { + id: login!.id, + title: "Login", + url: login!.url, + planner: "working", + openDecisions: 0, + build: "not built", + }, + ]); + expect(listed).not.toHaveProperty("index"); + expect(context.indexed).toHaveLength(2); + expect(context.indexed.at(-1)).toMatchObject({ create: false }); + }); + + test("instruct hands every created Planner the instruction as the person's message", async () => { + let context = await fixture({ refuse: { Checkout: "planner-busy" } }); + let [login, checkout] = await context.open( + piece("login-page", "Login"), + piece("checkout-flow", "Checkout"), + ); + let result = await context.call({ operation: "instruct", instruction: "Resume your plan." }); + if (!result.ok || result.operation !== "instruct") throw new Error("instruct failed"); + expect(byTitle(result.documents)).toMatchObject([ + { + id: checkout!.id, + started: false, + reason: "planner-busy", + message: "It is answering someone now.", + }, + { id: login!.id, started: true }, + ]); + let invoked = context.invocations.toSorted((left, right) => + left.channel.title.localeCompare(right.channel.title) + ); + expect(invoked).toMatchObject([ + { channel: { id: checkout!.id }, instruction: "Resume your plan." }, + { channel: { id: login!.id }, instruction: "Resume your plan.", user: { id: "U_mona" } }, + ]); + expect(invoked.every(invocation => invocation.system === undefined)).toBe(true); + }); + + test("instruct reaches only the named documents this one created, and names any it did not", async () => { + let context = await fixture(); + let [login] = await context.open( + piece("login-page", "Login"), + piece("checkout-flow", "Checkout"), + ); + let stranger = await context.storage.channels.create({ + ...context.fields, + id: crypto.randomUUID(), + title: "Made by a person", + }); + let result = await context.call({ + operation: "instruct", + instruction: "Resume.", + targets: [login!.url, stranger.id], + }); + expect(result).toMatchObject({ + ok: true, + documents: [{ id: login!.id, started: true }], + unknown: [stranger.id], + }); + expect(context.invocations.map(invocation => invocation.channel.id)).toEqual([login!.id]); + }); + + test("instruct is refused for a person who can't write the repository", async () => { + let context = await fixture({ push: false }); + await context.storage.channels.create({ + ...context.fields, + id: crypto.randomUUID(), + title: "Login", + createdFrom: context.source.id, + }); + let result = await context.call({ operation: "instruct", instruction: "Resume." }); + expect(result).toMatchObject({ ok: false, reason: "repository-forbidden" }); + expect(context.invocations).toEqual([]); + }); + + test("instruct with nothing created says so", async () => { + let context = await fixture(); + expect(await context.call({ operation: "instruct", instruction: "Resume." })).toMatchObject({ + ok: false, + reason: "nothing-created", + }); + }); + + test("index writes the table even before it exists", async () => { + let context = await fixture(); + await context.open(piece("login-page", "Login")); + let result = await context.call({ operation: "index" }); + expect(result).toMatchObject({ ok: true, operation: "index", index: { state: "written" } }); + expect(context.indexed.at(-1)).toMatchObject({ create: true, documents: [{ title: "Login" }] }); + }); +}); + +describe("buildState", () => { + let build = (state: BuildRequest["state"], createdAt: string) => + ({ state, createdAt }) as BuildRequest; + + test("a running build, a delivered one, then how the last one ended", () => { + expect(buildState({ builds: [] })).toBe("not built"); + expect(buildState({ builds: [build("failed", "1"), build("running", "2")] })).toBe("building"); + expect(buildState({ builds: [build("failed", "1")], live: { buildId: "b" } })).toBe("built"); + expect(buildState({ builds: [build("stopped", "2"), build("failed", "1")] })).toBe("stopped"); + }); +}); + +function documents(planner: PlannerState): CreatedDocumentState[] { + return [{ + id: "D1", + title: "Login | sign in", + url: "https://chopin.test/documents/octo/app/login", + planner, + openDecisions: 2, + build: "not built", + }]; +} + +describe("writeIndex", () => { + test("adds its section once, refreshes only its own table, and leaves the rest alone", async () => { + let context = await openPlan("# Whole app\n\nWhat the app does.\n"); + let room = documentRoom(context); + expect(await writeIndex(room, documents("idle"), false)).toEqual({ state: "absent" }); + expect(edit.source(context.plan)).not.toContain(INDEX_HEADING); + + expect(await writeIndex(room, documents("idle"), true)).toEqual({ state: "written" }); + let written = edit.source(context.plan); + expect(written).toContain("What the app does."); + expect(written).toContain(`## ${INDEX_HEADING}`); + expect(written).toContain("[Login \\| sign in](https://chopin.test/documents/octo/app/login)"); + expect(written).toContain("| idle"); + let revision = context.plan.revision; + + expect(await writeIndex(room, documents("idle"), false)).toEqual({ state: "unchanged" }); + expect(context.plan.revision).toBe(revision); + + expect(await writeIndex(room, documents("working"), false)).toEqual({ state: "written" }); + let refreshed = edit.source(context.plan); + expect(refreshed).toContain("| working"); + expect(refreshed).not.toContain("| idle"); + expect(refreshed.split(INDEX_HEADING)).toHaveLength(2); + expect(refreshed).toContain("What the app does."); + }); + + test("says when nothing has been created yet", async () => { + let context = await openPlan("# Whole app\n\nWhat the app does.\n"); + let room = documentRoom(context); + expect(await writeIndex(room, [], true)).toEqual({ state: "written" }); + expect(edit.source(context.plan)).toContain("No document has been created from this one yet."); + expect(await writeIndex(room, documents("idle"), false)).toEqual({ state: "written" }); + expect(edit.source(context.plan)).not.toContain("No document has been created"); + }); +}); diff --git a/apps/server/src/agent/fan-out.ts b/apps/server/src/agent/fan-out.ts new file mode 100644 index 000000000..c9b02b9b9 --- /dev/null +++ b/apps/server/src/agent/fan-out.ts @@ -0,0 +1,357 @@ +/** + * The Planner's `fan_out`: one document's Planner working with the documents it created. + * + * `open` creates several documents at once, each exactly as `create_document` would; `list` reads + * each created document's state as Chopin holds it; `instruct` hands their Planners one instruction + * as the requesting person's message, starting any that is not running; `index` keeps a table of + * them in this document. A document belongs here only while its stored `createdFrom` names this + * one, so a turn can never reach a document it did not create. + */ +import { documentPath } from "@chopin/protocol/document-url"; + +import { + createNewDocument, + MAX_INSTRUCTION_BYTES, + NEW_DOCUMENT_SCHEMA, + newDocumentArguments, + writes, +} from "./new-documents"; + +import type { BuildRequest } from "@chopin/protocol/implementation"; +import type { HostedRepository } from "./repository"; +import type { InvokePlannerError } from "../mcp"; +import type { + NewDocumentArguments, + NewDocumentDeps, + NewDocumentRequest, + NewDocumentResult, +} from "./new-documents"; +import type { ChannelRecord } from "../storage/model"; + +/** Most documents one `open` creates. */ +export const MAX_OPEN = 20; +/** Most created documents one call lists, instructs or indexes. */ +export const MAX_CREATED = 200; +/** How many documents are created, or Planners instructed, at once. */ +const CONCURRENCY = 4; + +export const FAN_OUT_OPERATIONS = ["open", "list", "instruct", "index"] as const; + +export type FanOutArguments = + | { operation: "open"; documents: NewDocumentArguments[] } + | { operation: "list" } + | { operation: "instruct"; instruction: string; targets?: string[] } + | { operation: "index" }; + +export const FAN_OUT_SCHEMA = { + type: "object", + properties: { + operation: { + type: "string", + enum: [...FAN_OUT_OPERATIONS], + description: "`open` creates documents from `documents`; `list` reports every document " + + "this one created, with its Planner, open Decisions and build; `instruct` sends " + + "`instruction` to their Planners; `index` writes or refreshes their table in this " + + "document.", + }, + documents: { + type: "array", + minItems: 1, + maxItems: MAX_OPEN, + items: NEW_DOCUMENT_SCHEMA, + description: "For `open` only: each new document, exactly as `create_document` takes it, " + + "with its own idempotencyKey.", + }, + instruction: { + type: "string", + minLength: 1, + description: "For `instruct` only: what each document's Planner should do now. It is " + + "posted in each document's Chat as the requesting person's message.", + }, + targets: { + type: "array", + minItems: 1, + maxItems: MAX_CREATED, + items: { type: "string", minLength: 1 }, + description: "For `instruct` only: the documents to instruct, each by the id or url " + + "`list` gives. Omit to instruct every document this one created.", + }, + }, + required: ["operation"], + additionalProperties: false, +}; + +const FIELDS: Record = { + open: ["documents"], + list: [], + instruct: ["instruction", "targets"], + index: [], +}; + +/** The tool's arguments, checked; throws with a sentence the model can act on. */ +export function fanOutArguments(raw: unknown): FanOutArguments { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new Error("fan_out arguments must be an object"); + } + let args = raw as Record; + let operation = args.operation; + if (!FAN_OUT_OPERATIONS.includes(operation as FanOutArguments["operation"])) { + throw new Error(`operation must be one of ${FAN_OUT_OPERATIONS.join(", ")}`); + } + let op = operation as FanOutArguments["operation"]; + let unknown = Object.keys(args).find(key => key !== "operation" && !FIELDS[op].includes(key)); + if (unknown) throw new Error(`fan_out ${op} does not take \`${unknown}\``); + if (op === "open") { + if (!Array.isArray(args.documents) || args.documents.length === 0) { + throw new Error("open needs documents, at least one"); + } + if (args.documents.length > MAX_OPEN) { + throw new Error(`open creates at most ${MAX_OPEN} documents at once`); + } + let documents = args.documents.map((value, index) => { + try { + return newDocumentArguments(value); + } catch (err) { + throw new Error(`documents[${index}]: ${err instanceof Error ? err.message : err}`, { + cause: err, + }); + } + }); + let keys = new Set(documents.map(document => document.idempotencyKey)); + if (keys.size !== documents.length) { + throw new Error("each document needs its own idempotencyKey"); + } + return { operation: op, documents }; + } + if (op === "instruct") { + let instruction = args.instruction; + if ( + typeof instruction !== "string" || !instruction.trim() + || Buffer.byteLength(instruction, "utf8") > MAX_INSTRUCTION_BYTES + ) throw new Error("instruct needs an instruction of non-empty text of at most 64 KiB"); + if (args.targets === undefined) return { operation: op, instruction }; + if ( + !Array.isArray(args.targets) || args.targets.length === 0 + || args.targets.length > MAX_CREATED + || args.targets.some(target => typeof target !== "string" || !target.trim()) + ) throw new Error("targets must list the documents to instruct, each by id or url"); + return { operation: op, instruction, targets: args.targets as string[] }; + } + return { operation: op }; +} + +export type PlannerState = "working" | "idle" | "stopped"; +export type BuildState = "not built" | "building" | "built" | "failed" | "stopped"; + +/** A document this one created, as Chopin holds it now. */ +export type CreatedDocumentState = { + id: string; + title: string; + url: string; + planner: PlannerState; + openDecisions: number; + build: BuildState; +}; + +/** Whether a build of the document runs now, else whether one delivered, else how the last ended. */ +export function buildState(plan: { builds: BuildRequest[]; live?: unknown }): BuildState { + if (plan.builds.some(build => !["stopped", "failed"].includes(build.state))) return "building"; + if (plan.live) return "built"; + let last = plan.builds.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)) + .at(-1); + return last ? last.state as "stopped" | "failed" : "not built"; +} + +export type IndexOutcome = + | { state: "written" | "unchanged" } + | { state: "absent" } + | { state: "refused"; reason: string; message?: string }; + +/** + * Writes the table of `documents` into the creating document. `create` false refreshes a table + * already there and writes none where there is none. + */ +export type IndexWriter = ( + documents: CreatedDocumentState[], + create: boolean, +) => Promise; + +export type FanOutDeps = NewDocumentDeps & { + /** Unarchived documents created from a document, oldest first. */ + createdFrom: (sourceId: string, limit: number) => Promise; + planner: (channelId: string) => PlannerState; + build: (channelId: string) => Promise; +}; + +export type FanOutRequest = Omit & { + arguments: FanOutArguments; + index: IndexWriter; +}; + +type Instructed = + & Pick + & ({ started: true } | { started: false; reason: string; message?: string }); + +export type FanOutResult = + | { + ok: true; + operation: "open"; + documents: Array<{ idempotencyKey: string } & NewDocumentResult>; + index?: IndexOutcome; + next: string; + } + | { ok: true; operation: "list"; documents: CreatedDocumentState[]; index?: IndexOutcome } + | { + ok: true; + operation: "instruct"; + documents: Instructed[]; + unknown?: string[]; + next: string; + } + | { ok: true; operation: "index"; documents: CreatedDocumentState[]; index: IndexOutcome } + | { ok: false; reason: string; message: string }; + +const REFUSALS: Record = { + "sign-in-required": "The person who asked has no live Chopin login in a browser, so their " + + "access can't be checked. Ask them to open Chopin and try again.", + "repository-forbidden": "The person who asked can't write to this repository, so no Planner " + + "was instructed.", + "document-unavailable": "This document is archived, deleted or closing.", + "nothing-created": "No document was created from this one, so there is nothing to instruct.", +}; + +function refused(reason: string): FanOutResult { + return { ok: false, reason, message: REFUSALS[reason]! }; +} + +/** `work` over `items`, at most `CONCURRENCY` at once, results in the items' order. */ +async function bounded(items: T[], work: (item: T) => Promise): Promise { + let results: R[] = []; + let next = 0; + let worker = async () => { + while (next < items.length) { + let index = next++; + results[index] = await work(items[index]!); + } + }; + await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, worker)); + return results; +} + +function url(deps: FanOutDeps, channel: ChannelRecord): string { + return new URL( + documentPath(channel.repositoryOwner, channel.repositoryName, channel.slug), + deps.appOrigin, + ).href; +} + +/** The documents `source` created that are still its repository's, top-level and unarchived. */ +async function created(deps: FanOutDeps, source: ChannelRecord): Promise { + return (await deps.createdFrom(source.id, MAX_CREATED)).filter(channel => + channel.createdFrom === source.id && channel.repositoryId === source.repositoryId + && !channel.parentChannelId && !channel.archivedAt && !deps.deleting(channel.id) + ); +} + +async function states(deps: FanOutDeps, source: ChannelRecord): Promise { + return Promise.all((await created(deps, source)).map(async channel => ({ + id: channel.id, + title: channel.title, + url: url(deps, channel), + planner: deps.planner(channel.id), + openDecisions: channel.unansweredDecisions, + build: await deps.build(channel.id), + }))); +} + +/** Whether `wanted`, an id or a url, names `channel`. */ +function names(deps: FanOutDeps, channel: ChannelRecord, wanted: string): boolean { + let key = wanted.trim().replace(/\/+$/, ""); + return key === channel.id || key === url(deps, channel) + || key === documentPath(channel.repositoryOwner, channel.repositoryName, channel.slug); +} + +async function instruct( + deps: FanOutDeps, + request: FanOutRequest, + source: ChannelRecord, + args: Extract, +): Promise { + let all = await created(deps, source); + if (all.length === 0) return refused("nothing-created"); + let unknown = args.targets?.filter(wanted => !all.some(channel => names(deps, channel, wanted))); + let chosen = args.targets + ? all.filter(channel => args.targets!.some(wanted => names(deps, channel, wanted))) + : all; + let { creator } = request; + let login = await deps.login(creator.userId, creator.claimantSessionId); + if (!login || login.user.id !== creator.userId) return refused("sign-in-required"); + let repository = await deps.repository(login, source.repositoryOwner, source.repositoryName); + if (!repository || !writes(repository, source.repositoryId)) { + return refused("repository-forbidden"); + } + let hosted: HostedRepository = { + id: repository.id, + owner: repository.owner, + name: repository.name, + defaultBranch: repository.defaultBranch, + }; + let documents = await bounded(chosen, async (channel): Promise => { + let shown = { id: channel.id, title: channel.title, url: url(deps, channel) }; + if (request.signal?.aborted) return { ...shown, started: false, reason: "cancelled" }; + let code: InvokePlannerError | undefined; + try { + code = await deps.invoke({ + channel, + repository: hosted, + user: { id: login.user.id, login: login.user.login, avatarUrl: login.user.avatarUrl }, + session: login, + instruction: args.instruction, + }); + } catch (err) { + console.error("[chat] instructing a created document's Planner failed:", err); + code = "planner-unavailable"; + } + if (!code) return { ...shown, started: true }; + let message = await deps.refusal?.(code, channel, shown.url); + return { ...shown, started: false, reason: code, ...(message ? { message } : {}) }; + }); + return { + ok: true, + operation: "instruct", + documents, + ...(unknown?.length ? { unknown } : {}), + next: "Each started Planner runs on its own; this turn need not wait for them. Tell the " + + "person which started, with their links, and why any did not. A Planner refused as " + + "busy can be instructed again once its turn ends.", + }; +} + +export async function fanOut(deps: FanOutDeps, request: FanOutRequest): Promise { + let source = await deps.channel(request.sourceId); + if (!source || source.archivedAt || deps.deleting(source.id) || source.parentChannelId) { + return refused("document-unavailable"); + } + let args = request.arguments; + if (args.operation === "open") { + let documents = await bounded(args.documents, async document => ({ + idempotencyKey: document.idempotencyKey, + ...await createNewDocument(deps, { ...request, arguments: document }), + })); + let index = await request.index(await states(deps, source), false); + return { + ok: true, + operation: "open", + documents, + ...(index.state === "absent" ? {} : { index }), + next: "Tell the person what was created, with each link. A document refused can be " + + "opened again with the same idempotencyKey; one already made is returned, not made " + + "twice.", + }; + } + if (args.operation === "instruct") return instruct(deps, request, source, args); + let documents = await states(deps, source); + let index = await request.index(documents, args.operation === "index"); + if (args.operation === "index") return { ok: true, operation: "index", documents, index }; + return { ok: true, operation: "list", documents, ...(index.state === "absent" ? {} : { index }) }; +} diff --git a/apps/server/src/agent/job-scope.ts b/apps/server/src/agent/job-scope.ts index 6b8a86d59..6d9c56ee5 100644 --- a/apps/server/src/agent/job-scope.ts +++ b/apps/server/src/agent/job-scope.ts @@ -24,6 +24,7 @@ export const WRITE_TOOLS: ReadonlySet = new Set([ "edit_implementation_graph", "create_research_workspace", "create_document", + "fan_out", "propose_investigation", "set_investigation_build_blocker", "revise_open_decision", diff --git a/apps/server/src/agent/new-documents.test.ts b/apps/server/src/agent/new-documents.test.ts index 6b3f83d26..eb8b4b12a 100644 --- a/apps/server/src/agent/new-documents.test.ts +++ b/apps/server/src/agent/new-documents.test.ts @@ -202,6 +202,7 @@ describe("createNewDocument", () => { repositoryId: "R_app", createdBy: "U_mona", title: "Settings page", + createdFrom: context.source.id, }); expect(channel?.parentChannelId).toBeUndefined(); expect(result.document.url).toBe( diff --git a/apps/server/src/agent/new-documents.ts b/apps/server/src/agent/new-documents.ts index 219d4ad13..1779d3f75 100644 --- a/apps/server/src/agent/new-documents.ts +++ b/apps/server/src/agent/new-documents.ts @@ -187,7 +187,8 @@ function refused(reason: string, issues?: Issue[]): NewDocumentResult { }; } -function writes(repository: GitHubRepository | undefined, id: string): boolean { +/** Whether `repository`, as a login reads it on GitHub, is the stored one and that login may push. */ +export function writes(repository: GitHubRepository | undefined, id: string): boolean { return !!repository && repository.id === id && (repository.permissions.push || repository.permissions.admin); } @@ -246,6 +247,7 @@ export async function createNewDocument( && writes(await deps.repository(current, owner, name), source.repositoryId); }, modelChoice: () => deps.modelChoice(sourceId, creator.userId), + createdFrom: sourceId, ...(request.signal ? { signal: request.signal } : {}), }, prepared.input, diff --git a/apps/server/src/agent/planner.ts b/apps/server/src/agent/planner.ts index 7553fe4ea..cbcd56260 100644 --- a/apps/server/src/agent/planner.ts +++ b/apps/server/src/agent/planner.ts @@ -214,7 +214,11 @@ and an \`instruction\` when its own Planner should start on it now. One document holding every piece is too large to review; write one only when the member asks for it. Each new document has its own Chat and Planner and shares nothing with this one, so its draft and instruction must carry everything it needs. Tell the -member what you created, with each link from the result. +member what you created, with each link from the result. \`fan_out\` works with +the documents this one created: \`open\` creates several at once, \`list\` shows +each one's Planner, open Decisions and build, \`instruct\` hands their Planners one +instruction (to resume or change their work), and \`index\` keeps a table of them +here. Even when intent is sparse, write a short provisional account of the known problem and what remains unknown. Then capture the missing intent as a written decision beside that paragraph. diff --git a/apps/server/src/agent/tools.test.ts b/apps/server/src/agent/tools.test.ts index b9c4d72e6..464a278ed 100644 --- a/apps/server/src/agent/tools.test.ts +++ b/apps/server/src/agent/tools.test.ts @@ -8,6 +8,7 @@ import { forgetWorkspaces, rememberCheckout } from "../harness/atomic/workspace" import { Admission } from "../auth/admission"; import { Sessions } from "../auth/session"; import * as Chat from "../chat/service"; +import * as edit from "../plan/edit"; import * as room from "../plan/room"; import * as Service from "../plan/service"; import * as Store from "../questions/store"; @@ -86,6 +87,7 @@ test("document tool names and schemas remain available to the Planner", async () "read_background_job", "create_research_workspace", "create_document", + "fan_out", "upload_plan_image", "assess_visual", "edit_plan", @@ -273,6 +275,54 @@ test("read_plan and edit_plan give a child document its nested canonical URL", a expect(edited).toMatchObject({ ok: true, document: identity }); }); +async function callFanOut(tools: ReturnType, raw: unknown) { + let fanOut = tools.find(tool => tool.name === "fan_out"); + if (!fanOut?.handler) throw new Error("fan_out is missing"); + let text = String(await fanOut.handler(raw as never, { toolCallId: "call" })); + return text.startsWith("Error: ") ? text : JSON.parse(text); +} + +test("fan_out hands checked arguments and this room's index to the member turn, and refuses without one", async () => { + let { plan, server } = await opened("# Whole app\n\nWhat the app does.\n"); + let room = { + plan, + server, + room: "test", + persist: () => Service.persist(plan), + exclusive: (action: () => Promise) => Service.exclusive(plan, action), + async publish() {}, + anchors() {}, + changes() {}, + }; + expect(await callFanOut(fixtureTools(room), { operation: "list" })).toEqual({ + ok: false, + reason: "member-request-required", + message: "Only a turn a person asked for in Chat can work with created documents.", + }); + let received: unknown[] = []; + let tools = fixtureTools({ + ...room, + fanOut: async (args, index) => { + received.push(args); + let written = await index([{ + id: "doc", + title: "Login", + url: "https://chopin.test/d", + planner: "idle", + openDecisions: 0, + build: "not built", + }], true); + return { ok: true, operation: "index", documents: [], index: written }; + }, + }); + expect(await callFanOut(tools, { operation: "index" })).toMatchObject({ + ok: true, + index: { state: "written" }, + }); + expect(received).toEqual([{ operation: "index" }]); + expect(edit.source(plan)).toContain("[Login](https://chopin.test/d)"); +}); + test("create_document hands checked arguments to the member turn and refuses without one", async () => { let { plan, server } = await opened("Split context.\n"); let room = { diff --git a/apps/server/src/agent/tools.ts b/apps/server/src/agent/tools.ts index c1ca3bdda..343ab2a7d 100644 --- a/apps/server/src/agent/tools.ts +++ b/apps/server/src/agent/tools.ts @@ -35,6 +35,9 @@ import { experimentTools } from "./experiment-tools"; import { planImage } from "./plan-images"; import { NEW_DOCUMENT_SCHEMA, newDocumentArguments } from "./new-documents"; import type { NewDocumentArguments, NewDocumentResult } from "./new-documents"; +import { FAN_OUT_SCHEMA, fanOutArguments } from "./fan-out"; +import { writeIndex } from "./fan-out-index"; +import type { FanOutArguments, FanOutResult, IndexWriter } from "./fan-out"; import type { InvestigationTools } from "./experiment-tools"; import type { ActiveOwnerBinding } from "./active-owner"; @@ -194,6 +197,15 @@ export type DocumentRoom = { args: NewDocumentArguments, signal?: AbortSignal, ) => Promise; + /** + * Works with the documents this one created, for the person whose message drives the current + * turn; absent, or refusing, where `createDocument` is. + */ + fanOut?: ( + args: FanOutArguments, + index: IndexWriter, + signal?: AbortSignal, + ) => Promise; /** Starts the exact research request represented by the current member turn. */ createResearch?: (question: string) => Promise; /** Reads one reference retained by this room's active Planner session. */ @@ -364,6 +376,37 @@ export const documentTools = { }), }), + fan_out: tool({ + contextSchema: roomContext, + description: "Work with the documents this document created, each with its own Chat, " + + "Decisions and Planner. `open` creates several at once, each exactly as " + + "`create_document` would, remembered as created from this document. `list` gives each " + + "one's link, whether its Planner is working, idle or stopped, its open Decisions and " + + "its build. `instruct` sends one instruction to their Planners, or only to `targets`, " + + "as the person's message in each document's Chat, starting a Planner that isn't " + + "running; use it when the person asks to resume, continue or change the work in them. " + + "`index` writes a table of them, kept current by later calls, under its own heading in " + + "this document. Only a turn a person asked for can use it, and it reaches only the " + + "documents this one created.", + inputSchema: jsonSchema(FAN_OUT_SCHEMA), + execute: (raw, { context: { room: context }, abortSignal }) => + answer("fan_out", async () => { + let args = fanOutArguments(raw); + if (!context.fanOut) { + return { + ok: false, + reason: "member-request-required", + message: "Only a turn a person asked for in Chat can work with created documents.", + }; + } + return context.fanOut( + args, + (documents, create) => writeIndex(context, documents, create, abortSignal), + abortSignal, + ); + }), + }), + upload_plan_image: tool({ contextSchema: roomContext, description: "Store an image you made, a PNG, JPEG, WebP or GIF of at most 16 MiB (one over " diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index aa3d03769..52cfacb8b 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -39,6 +39,7 @@ import type { AiAccountRefusal } from "../ai/account-check"; import type { ActiveOwnerBinding } from "../agent/active-owner"; import type { DocumentRoom, ResearchWorkspaceRequest } from "../agent/tools"; import type { NewDocumentRequest, NewDocumentResult } from "../agent/new-documents"; +import type { FanOutRequest, FanOutResult } from "../agent/fan-out"; import type { VisualAdmission } from "../agent/visual-admission"; import type { ChildDocuments } from "./children"; import type { TellChat } from "./thread-notes"; @@ -924,6 +925,8 @@ export type Room = { }) => Promise; /** Creates a top-level document for the person whose message drives the turn. */ createDocument?: (request: Omit) => Promise; + /** Works with the documents this one created, for the person whose message drives the turn. */ + fanOut?: (request: Omit) => Promise; /** Keeps the room loaded while a retained Planner still waits on a question; returns the release. */ hold?: () => () => void; /** The task draft the turn being started carries. */ @@ -2573,27 +2576,28 @@ export function documentRoom(context: Room): DocumentRoom { }, ...(!chat.job && context.createDocument && !context.rootChannelId && { createDocument: async (args, signal) => { - let active = currentMemberRequest(chat); - if (chat.job || !active) { + let request = creatorRequest(context, signal); + if (!request) { return { ok: false, reason: "member-request-required", message: "Only a turn a person asked for in Chat can create documents.", }; } - let signals = [signal, chat.turnController?.signal].filter( - (value): value is AbortSignal => !!value, - ); - return context.createDocument!({ - creator: { - userId: active.userId, - handle: active.handle, - ...(active.claimantSessionId ? { claimantSessionId: active.claimantSessionId } : {}), - }, - arguments: args, - ...(signals.length ? { signal: AbortSignal.any(signals) } : {}), - announce: document => createdNotice(context, active.handle, document), - }); + return context.createDocument!({ ...request, arguments: args }); + }, + }), + ...(!chat.job && context.fanOut && !context.rootChannelId && { + fanOut: async (args, index, signal) => { + let request = creatorRequest(context, signal); + if (!request) { + return { + ok: false, + reason: "member-request-required", + message: "Only a turn a person asked for in Chat can work with created documents.", + }; + } + return context.fanOut!({ ...request, arguments: args, index }); }, }), createResearch: async _question => { @@ -2616,6 +2620,31 @@ export function documentRoom(context: Room): DocumentRoom { }; } +/** + * Who creates or instructs documents for the current turn: the person whose message drives it, + * with the turn's cancellation. Undefined in a turn nobody typed and in a background job. + */ +function creatorRequest( + context: Room, + signal: AbortSignal | undefined, +): Omit | undefined { + let { chat } = context; + let active = currentMemberRequest(chat); + if (chat.job || !active) return undefined; + let signals = [signal, chat.turnController?.signal].filter( + (value): value is AbortSignal => !!value, + ); + return { + creator: { + userId: active.userId, + handle: active.handle, + ...(active.claimantSessionId ? { claimantSessionId: active.claimantSessionId } : {}), + }, + ...(signals.length ? { signal: AbortSignal.any(signals) } : {}), + announce: document => createdNotice(context, active.handle, document), + }; +} + /** * Saves, then shows, the line naming a document the Planner created in the Chat or thread whose * turn asked, unless it already holds one. diff --git a/apps/server/src/chat/threads.ts b/apps/server/src/chat/threads.ts index cd4d04ef6..1316e9fe9 100644 --- a/apps/server/src/chat/threads.ts +++ b/apps/server/src/chat/threads.ts @@ -666,6 +666,7 @@ function buildThreadRoom( hold: topContext.hold, children: topContext.children, createDocument: topContext.createDocument, + fanOut: topContext.fanOut, // A reaction saves the transcript it is about to make, before it changes the live one. persist: async next => { await saveThreadRecord(topContext, managed, override, next?.().entries); diff --git a/apps/server/src/harness/tool-names.ts b/apps/server/src/harness/tool-names.ts index ae4cca4b1..3563e79f0 100644 --- a/apps/server/src/harness/tool-names.ts +++ b/apps/server/src/harness/tool-names.ts @@ -12,6 +12,7 @@ export const PLANNER_TOOL_NAMES = [ "read_background_job", "create_research_workspace", "create_document", + "fan_out", "upload_plan_image", "edit_plan", "open_decision", diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 1c482aff0..3b0e0f9ff 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -122,7 +122,10 @@ import { JobService } from "./jobs/service"; import { DocumentSummaryCoordinator } from "./jobs/summary-coordinator"; import { invokeRouted, SystemTurns } from "./mcp/invoke"; import { createNewDocument } from "./agent/new-documents"; +import { buildState, fanOut } from "./agent/fan-out"; import type { NewDocumentDeps } from "./agent/new-documents"; +import type { FanOutDeps } from "./agent/fan-out"; +import type { BuildRequest } from "@chopin/protocol/implementation"; import { liveClassifier } from "./tasks/live-gate"; import { LiveSyncCoordinator } from "./tasks/live-sync"; import { heuristicJudge, jevJudge, SpikeScout } from "./experiments/spike-scout"; @@ -1110,6 +1113,9 @@ function conversation( createDocument: config.agent ? request => createNewDocument(plannerDocuments(), { ...request, sourceId: room.id }) : undefined, + fanOut: config.agent + ? request => fanOut(createdDocuments(), { ...request, sourceId: room.id }) + : undefined, createResearch: config.agent ? async request => { let service = researchService; @@ -2751,6 +2757,28 @@ function plannerDocuments(): NewDocumentDeps { }; } +/** The Planner's `fan_out`: `create_document`'s rules, and the state of what a document created. */ +function createdDocuments(): FanOutDeps { + return { + ...plannerDocuments(), + createdFrom: (sourceId, limit) => storage.channels.createdFrom(sourceId, limit), + planner: channelId => { + let chat = Rooms.get(channelId)?.plan?.chat; + if (chat?.busy || chat?.starting) return "working"; + if (chat?.agent || plannerAttachments?.holding(channelId)?.attached) return "idle"; + return "stopped"; + }, + build: async channelId => { + let plan = Rooms.get(channelId)?.plan; + if (plan) return buildState(plan); + let stored = await storage.collaboration.load(channelId, hostedAuth.clock()); + let sidecar = stored?.sidecar as { builds?: unknown; live?: unknown } | null | undefined; + let builds = Array.isArray(sidecar?.builds) ? sidecar.builds as BuildRequest[] : []; + return buildState({ builds, live: sidecar?.live }); + }, + }; +} + /** Tell every sidebar watching the document's repository that its documents changed. */ function announceCatalogue(channel: Pick): void { if (!server || cutting) return; diff --git a/apps/server/src/mcp/hosted.ts b/apps/server/src/mcp/hosted.ts index 5d416b1f8..d7c0ea59e 100644 --- a/apps/server/src/mcp/hosted.ts +++ b/apps/server/src/mcp/hosted.ts @@ -295,6 +295,8 @@ export type DocumentCreator = { stillWrites: () => Promise; /** The Planner model choice to store in the transaction that creates the document. */ modelChoice?: () => Promise; + /** The document whose Planner creates this one, stored as its `createdFrom`. */ + createdFrom?: string; signal?: AbortSignal; }; @@ -387,6 +389,7 @@ export async function createDocument( now: auth.clock(), initial, ...(modelChoice ? { modelChoice } : {}), + ...(creator.createdFrom ? { createdFrom: creator.createdFrom } : {}), }); } catch (err) { if (!(err instanceof StorageError) || err.failure !== "conflict") throw err; diff --git a/apps/server/src/storage/contract.ts b/apps/server/src/storage/contract.ts index e3264e678..9cca56a11 100644 --- a/apps/server/src/storage/contract.ts +++ b/apps/server/src/storage/contract.ts @@ -1,5 +1,6 @@ import { researchWorkspace } from "./research-inline-contract-fixtures"; import { childChannelContract } from "./child-channel-contract"; +import { createdFromContract } from "./created-from-contract"; import { experimentContract } from "./experiment-contract"; import { chatAttachmentContract } from "./chat-attachment-contract"; import { imageContract } from "./image-contract"; @@ -62,6 +63,7 @@ export function storageContract(name: string, factory: Factory): void { versionContract(name, factory); machineContract(name, factory); childChannelContract(name, factory); + createdFromContract(name, factory); plannerAttachmentContract(name, factory); plannerHoldContract(name, factory); plannerModelChoiceContract(name, factory); diff --git a/apps/server/src/storage/created-from-contract.ts b/apps/server/src/storage/created-from-contract.ts new file mode 100644 index 000000000..47a976808 --- /dev/null +++ b/apps/server/src/storage/created-from-contract.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from "bun:test"; + +import { contractId as id, openedStorage, testLease, userAndChannel } from "./contract-support"; + +import type { StorageFactory } from "./contract-support"; + +export function createdFromContract(name: string, factory: StorageFactory) { + describe(`${name} documents created from a document`, () => { + test("links each to the document it was created from and lists them oldest first", async () => { + let storage = await openedStorage(factory); + try { + let { userId, channelId, repositoryId } = await userAndChannel(storage); + let fields = { + repositoryId, + repositoryOwner: "octo-org", + repositoryName: "score", + createdBy: userId, + }; + let later = await storage.channels.create({ + ...fields, + id: id("later"), + title: "Checkout", + createdFrom: channelId, + now: new Date("2026-01-03T00:00:00.000Z"), + }); + let earlier = await storage.channels.create({ + ...fields, + id: id("earlier"), + title: "Login", + createdFrom: channelId, + now: new Date("2026-01-02T12:00:00.000Z"), + }); + let unrelated = await storage.channels.create({ + ...fields, + id: id("unrelated"), + title: "Unrelated", + now: new Date("2026-01-02T13:00:00.000Z"), + }); + expect(later.createdFrom).toBe(channelId); + expect((await storage.channels.get(earlier.id))!.createdFrom).toBe(channelId); + expect(unrelated.createdFrom).toBeUndefined(); + expect((await storage.channels.createdFrom(channelId, 10)).map(item => item.title)) + .toEqual(["Login", "Checkout"]); + expect((await storage.channels.createdFrom(channelId, 1)).map(item => item.title)) + .toEqual(["Login"]); + + await storage.channels.archive({ + id: earlier.id, + now: new Date("2026-01-04T00:00:00.000Z"), + lease: await testLease(storage), + }); + expect((await storage.channels.createdFrom(channelId, 10)).map(item => item.title)) + .toEqual(["Checkout"]); + } finally { + await storage.close(); + } + }); + + test("refuses a link to a document of another repository or one that does not exist", async () => { + let storage = await openedStorage(factory); + try { + let { userId, channelId } = await userAndChannel(storage); + let fields = { + repositoryOwner: "octo-org", + repositoryName: "other", + createdBy: userId, + now: new Date("2026-01-03T00:00:00.000Z"), + }; + await expect(storage.channels.create({ + ...fields, + id: id("elsewhere"), + repositoryId: id("repository"), + title: "Elsewhere", + createdFrom: channelId, + })).rejects.toMatchObject({ failure: "conflict" }); + await expect(storage.channels.create({ + ...fields, + id: id("orphan"), + repositoryId: id("repository"), + title: "Orphan", + createdFrom: id("missing"), + })).rejects.toMatchObject({ failure: "missing" }); + } finally { + await storage.close(); + } + }); + + test("keeps the documents a deleted document created, unlinked", async () => { + let storage = await openedStorage(factory); + try { + let { userId, channelId, repositoryId } = await userAndChannel(storage); + let created = await storage.channels.create({ + id: id("created"), + repositoryId, + repositoryOwner: "octo-org", + repositoryName: "score", + title: "Checkout", + createdBy: userId, + createdFrom: channelId, + now: new Date("2026-01-03T00:00:00.000Z"), + }); + await storage.channels.delete({ id: channelId, lease: await testLease(storage) }); + let kept = await storage.channels.get(created.id); + expect(kept?.title).toBe("Checkout"); + expect(kept?.createdFrom).toBeUndefined(); + expect(await storage.channels.createdFrom(channelId, 10)).toEqual([]); + } finally { + await storage.close(); + } + }); + }); +} diff --git a/apps/server/src/storage/memory/adapter.ts b/apps/server/src/storage/memory/adapter.ts index 3df4ed575..e7ee34eb5 100644 --- a/apps/server/src/storage/memory/adapter.ts +++ b/apps/server/src/storage/memory/adapter.ts @@ -440,16 +440,9 @@ export class MemoryStorage implements StorageAdapter { create: async input => this.#createChannel(input), get: id => Promise.resolve(this.#channels.get(id)).then(value => value && channel(value)), children: (parentId, limit) => - Promise.resolve( - [...this.#channels.values()] - .filter(value => value.parentChannelId === parentId && !value.archivedAt) - .sort((left, right) => - left.createdAt.getTime() - right.createdAt.getTime() - || left.id.localeCompare(right.id) - ) - .slice(0, limit) - .map(value => channel(value)), - ), + this.#channelsWhere(value => value.parentChannelId === parentId, limit), + createdFrom: (sourceId, limit) => + this.#channelsWhere(value => value.createdFrom === sourceId, limit), resolve: (repositoryId, slug) => { let id = this.#channelSlugs.get(repositoryId)?.get(slug); let found = id ? this.#channels.get(id) : undefined; @@ -645,6 +638,22 @@ export class MemoryStorage implements StorageAdapter { return this.#setLastDocument(input.userId, input.documentId, input.now); } + /** Unarchived channels that match, oldest first, at most `limit`. */ + #channelsWhere( + matches: (value: ChannelRecord) => boolean, + limit: number, + ): Promise { + return Promise.resolve( + [...this.#channels.values()] + .filter(value => matches(value) && !value.archivedAt) + .sort((left, right) => + left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id) + ) + .slice(0, limit) + .map(value => channel(value)), + ); + } + #createChannel(input: CreateChannel): ChannelRecord { if (input.modelChoice) { try { @@ -670,6 +679,13 @@ export class MemoryStorage implements StorageAdapter { throw conflict(`channel ${input.parentChannelId} cannot parent another child`); } } + if (input.createdFrom !== undefined) { + let source = this.#channels.get(input.createdFrom); + if (!source) throw missing(`channel ${input.createdFrom} does not exist`); + if (source.repositoryId !== input.repositoryId || source.parentChannelId) { + throw conflict(`channel ${input.id} must be created from a document of its repository`); + } + } let { initial, now, modelChoice: _modelChoice, ...record } = input; let slug = this.#reserveSlug(input.repositoryId, input.id, input.title); let saved: ChannelRecord = { @@ -810,6 +826,11 @@ export class MemoryStorage implements StorageAdapter { this.#navigation.set(userId, { ...saved, lastDocumentId: undefined }); } } + for (let created of this.#channels.values()) { + if (created.createdFrom !== id) continue; + let { createdFrom: _, ...unlinked } = created; + this.#channels.set(created.id, unlinked); + } } // Research staging is queued behind writes already under way, which find the document gone. for (let item of deleted) await this.#research.deleteChannel(item.id); diff --git a/apps/server/src/storage/model.ts b/apps/server/src/storage/model.ts index 050487b6c..aa9b05e67 100644 --- a/apps/server/src/storage/model.ts +++ b/apps/server/src/storage/model.ts @@ -253,6 +253,11 @@ export type ChannelRecord = { repositoryOwner: string; repositoryName: string; parentChannelId?: string; + /** + * The top-level document whose Planner created this one, in the same repository; absent for one + * a person created, and once that document is deleted. + */ + createdFrom?: string; title: string; slug: string; createdBy: string; diff --git a/apps/server/src/storage/port.ts b/apps/server/src/storage/port.ts index b3da97e99..0ac414ac6 100644 --- a/apps/server/src/storage/port.ts +++ b/apps/server/src/storage/port.ts @@ -296,6 +296,8 @@ export interface ChannelStore { get(id: string): Promise; /** Unarchived direct children of one channel, oldest first, at most `limit`. */ children(parentId: string, limit: number): Promise; + /** Unarchived documents created from `sourceId` (see `ChannelRecord.createdFrom`), oldest first. */ + createdFrom(sourceId: string, limit: number): Promise; resolve(repositoryId: string, slug: string): Promise; /** Slugs a document had before a rename, which still resolve to it, newest first by first use. */ earlierSlugs(id: string): Promise; diff --git a/apps/server/src/storage/postgres/adapter.test.ts b/apps/server/src/storage/postgres/adapter.test.ts index 688ad7a19..eee289a3d 100644 --- a/apps/server/src/storage/postgres/adapter.test.ts +++ b/apps/server/src/storage/postgres/adapter.test.ts @@ -1115,6 +1115,7 @@ if (url) { "051_machine_vm_problem", "052_planner_reset", "053_planner_catalogs_latest", + "054_documents_created_from", ]); expect([ ...await sql<{ table: string | null }[]>`SELECT to_regclass('channel_slugs') AS table`, diff --git a/apps/server/src/storage/postgres/adapter.ts b/apps/server/src/storage/postgres/adapter.ts index 89532ebc4..54fe22df7 100644 --- a/apps/server/src/storage/postgres/adapter.ts +++ b/apps/server/src/storage/postgres/adapter.ts @@ -102,6 +102,7 @@ type ChannelRow = { repositoryOwner: string; repositoryName: string; parentChannelId: string | null; + createdFrom: string | null; title: string; slug?: string; createdBy: string; @@ -253,6 +254,7 @@ function channel(row: ChannelRow): ChannelRecord { archivedAt, fullWidth, parentChannelId, + createdFrom, description, descriptionRevision, descriptionPlanRevision, @@ -298,6 +300,7 @@ function channel(row: ChannelRow): ChannelRecord { return { ...record, ...(parentChannelId === null ? {} : { parentChannelId }), + ...(createdFrom === null ? {} : { createdFrom }), slug: row.slug, revision: integer(row.revision, "channel revision"), createdAt: date(row.createdAt, "channel creation time"), @@ -395,6 +398,7 @@ const CHANNEL_COLUMNS = ` channels.repository_owner AS "repositoryOwner", channels.repository_name AS "repositoryName", channels.parent_channel_id AS "parentChannelId", + channels.created_from AS "createdFrom", channels.title, ( SELECT channel_slugs.slug @@ -427,6 +431,7 @@ const CHANNEL_RETURNING = ` repository_owner AS "repositoryOwner", repository_name AS "repositoryName", parent_channel_id AS "parentChannelId", + created_from AS "createdFrom", title, created_by AS "createdBy", revision, @@ -838,6 +843,17 @@ export class PostgresStorage implements StorageAdapter { `; return rows.map(channel); }), + createdFrom: (sourceId, limit) => + this.#run("list documents created from a document", async () => { + let rows = await this.#sql` + SELECT ${this.#sql.unsafe(CHANNEL_COLUMNS)} + FROM channels + WHERE created_from = ${sourceId} AND archived_at IS NULL + ORDER BY created_at, id + LIMIT ${limit} + `; + return rows.map(channel); + }), resolve: (repositoryId, slug) => this.#run("resolve channel slug", async () => { let [found] = await this.#sql` @@ -967,13 +983,31 @@ export class PostgresStorage implements StorageAdapter { throw conflict(`channel ${input.parentChannelId} cannot parent another child`); } } + if (input.createdFrom !== undefined) { + let [source] = await transaction<{ + parentChannelId: string | null; + repositoryId: string; + }[]>` + SELECT + parent_channel_id AS "parentChannelId", + repository_id AS "repositoryId" + FROM channels + WHERE id = ${input.createdFrom} + FOR KEY SHARE + `; + if (!source) throw missing(`channel ${input.createdFrom} does not exist`); + if (source.repositoryId !== input.repositoryId || source.parentChannelId !== null) { + throw conflict(`channel ${input.id} must be created from a document of its repository`); + } + } let [saved] = await transaction` INSERT INTO channels ( - id, repository_id, repository_owner, repository_name, parent_channel_id, title, - created_by, revision, next_sequence, created_at, updated_at + id, repository_id, repository_owner, repository_name, parent_channel_id, created_from, + title, created_by, revision, next_sequence, created_at, updated_at ) VALUES ( ${input.id}, ${input.repositoryId}, ${input.repositoryOwner}, - ${input.repositoryName}, ${input.parentChannelId ?? null}, ${input.title}, + ${input.repositoryName}, ${input.parentChannelId ?? null}, ${input.createdFrom ?? null}, + ${input.title}, ${input.createdBy}, 0, 1, ${input.now}, ${input.now} ) diff --git a/apps/server/src/storage/postgres/migrations.ts b/apps/server/src/storage/postgres/migrations.ts index 0df42b7e9..ef421aa2a 100644 --- a/apps/server/src/storage/postgres/migrations.ts +++ b/apps/server/src/storage/postgres/migrations.ts @@ -181,6 +181,9 @@ const MIGRATIONS = [{ }, { id: "053_planner_catalogs_latest", path: join(import.meta.dir, "migrations/053_planner_catalogs_latest.sql"), +}, { + id: "054_documents_created_from", + path: join(import.meta.dir, "migrations/054_documents_created_from.sql"), }] satisfies Migration[]; /** Navigation shipped as 002 before document slugs claimed that number on main. */ diff --git a/apps/server/src/storage/postgres/migrations/054_documents_created_from.sql b/apps/server/src/storage/postgres/migrations/054_documents_created_from.sql new file mode 100644 index 000000000..8ca34debd --- /dev/null +++ b/apps/server/src/storage/postgres/migrations/054_documents_created_from.sql @@ -0,0 +1,7 @@ +-- The top-level document whose Planner created a document, so that Planner can list and instruct the +-- documents it created. Additive: an earlier release ignores the column. Deleting the creating +-- document unlinks the documents it created rather than deleting them. +ALTER TABLE channels + ADD COLUMN created_from text REFERENCES channels (id) ON DELETE SET NULL; +CREATE INDEX channels_created_from ON channels (created_from, created_at, id) + WHERE created_from IS NOT NULL; diff --git a/docs/hosted-agent.md b/docs/hosted-agent.md index df7f9e73a..101c45ca1 100644 --- a/docs/hosted-agent.md +++ b/docs/hosted-agent.md @@ -371,8 +371,10 @@ Chopin's tools available to the Planner under every harness are: never offered to background jobs, and unexpected storage errors reach the model only as a generic message; - `create_document`, which makes new top-level documents for the person whose - message drives the turn (see [Creating documents](#creating-documents)); it is - never offered to background jobs; + message drives the turn, and `fan_out`, which opens, lists, instructs and + indexes the documents this one created (see + [Creating documents](#creating-documents)); neither is offered to background + jobs; - bounded file and tree reads plus commit history using the session's default branch, or an explicitly supplied full commit ID when inspecting investigation evidence; - repository-scoped code search, post-filtered by repository node ID; and @@ -2006,6 +2008,37 @@ holds its rules: The result gives each new document's `id` and absolute `url`, so the model, or a workflow it started, can follow up on it. +Each document the Planner creates records the document it was created from +(`ChannelRecord.createdFrom`, migration 054). It is cleared, and the document +kept, when the creating document is deleted. + +### Working with created documents + +`fan_out` (`apps/server/src/agent/fan-out.ts`) is the Planner's tool for the +documents its document created. It is offered with `create_document`, under the +same rules: only a turn a person's message drives may call it, that person's live +browser login is rechecked for write access, and it reaches only unarchived +top-level documents of the same repository whose `createdFrom` is this document. +It takes one `operation`: + +- `open` creates up to 20 documents at once from `documents`, each exactly as + `create_document` takes and creates it, with its own idempotency key. Results + come back in the order given. +- `list` gives each created document's `id`, `title`, `url`, its Planner + (`working` while a turn runs, `idle` while a session or attached machine holds + it, otherwise `stopped`), its open Decisions, and its build (`building`, + `built`, `failed`, `stopped` or `not built`). +- `instruct` posts one `instruction` in every created document's Chat, or only in + the `targets` named by id or url, as the person's message, exactly as + `invoke_planner` does, starting a Planner that isn't running. Each document's + outcome is reported; a busy Planner is refused and can be instructed again + later. A target that is not a document this one created is named in `unknown`. +- `index` writes a table of the created documents under the heading "Documents + created from this one" in the creating document. The heading and the one block + after it are Chopin's; the rest of the document is left alone. `open` and + `list` refresh a table already there, and nothing is written when it would not + change. + ## Background jobs Background jobs are durable Chopin requests, not child Planner turns. Registered