Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 50 additions & 24 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,11 @@ durable.
(`AgentLink.catalog`): from the moment the person's accounts change it is no longer what the
client offers, and only a report through a launch prepared since counts again, named in
`catalogLaunch` by a client offering `catalog-launches`, never one through an earlier launch.
An end, a replacement or a session's close is in force in the
process the moment it is asked, before storage deletes the rows (`#ending`), an end
An end or a session's close is in force in the
process the moment it is asked, before storage deletes the rows (`#ending`), while a
session launch replaced by renewal stays live for a two-minute grace period
(`REPLACED_LAUNCH_GRACE_MS` in `apps/server/src/harness/remote/link.ts`) and ends at
once if the session does; an end
storage refuses is retried, and the writer lease's holder ends launches nothing owns
as it starts serving and with each sweep (`AiCredentials.retire`). A key refused as
invalid, or a Copilot seat GitHub confirms lost or back, tells the person's lasting
Expand Down Expand Up @@ -326,7 +329,11 @@ durable.
message, except one sent once the turn is being stopped or finishing, which starts
its next turn. Chopin keeps no workflow runs of a client's and draws no run cards: a session
outlives its turn only while it waits on a question it asked or on an answer its client has not
received. Signing out the owner's login, its expiry, or a Planner reset closes the link. A lost
received (whether the turn finished or failed, so a failing reply never withdraws open
Decisions). A routine renewal of the owner's GitHub credential rebinds a running or retained
remote session (`ownerSignal` and `rebindRetained` in `chat/service.ts`) without aborting the
turn or withdrawing its questions; only signing out, an unrenewable credential, or a Planner
reset closes the link. A lost
connection never ends work by itself: a link that offered
`resumable-sessions` and then dropped unexpectedly keeps its sessions that hold
an open question or an answer its client has not acknowledged, however long it stays away.
Expand Down Expand Up @@ -654,26 +661,45 @@ means a former target can no longer be identified safely.

## Planner-created documents

The Planner's `create_document` host tool (every harness) makes new top-level
documents, one per piece of work that splits naturally, each with its own Chat,
Decisions and Planner. Only a turn a person's message (in Chat or a thread)
drives may call it: that person is the creator, and their own live browser login
is rechecked for write access as for `chat:send`; a turn nobody typed and
background jobs are refused. It reuses MCP `create_document`'s draft validation,
visual assessment and creation (`createDocument` in `apps/server/src/mcp/hosted.ts`),
keeps the creating document's repository and base branch, with an idempotency
key scoped to the creating document and no per-turn or hourly cap. The creating
document's model choice is stored in the transaction that creates the new one
(`CreateChannel.modelChoice`), so a retry never overwrites a choice made since.
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. 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
The Planner's `create_document` host tool (every harness) opens one top-level
document per piece of work, each with its own Chat, Decisions, and Planner.
Only a turn driven by a person's message (in Chat or a thread) may call it:
that person is the creator, and their live browser login is rechecked for write
access as for `chat:send`. Turns nobody typed and background jobs are refused.

`create_document` reuses MCP's draft validation, visual assessment, and
creation transaction (`createDocument` in `apps/server/src/mcp/hosted.ts`),
keeping the creating document's repository and base branch with a
source-scoped idempotency key and no per-turn or hourly cap. The creating
document's model choice is saved in the same transaction
(`CreateChannel.modelChoice`), so retries never overwrite a choice made since.
Retries compare against the recorded base and post the linked Chat line only if
the first call could not save it. The document is stored before the sidebar,
the asking Chat's linked line (`Entry.document`), or its optional first
instruction (posted as the creator's message, as `invoke_planner` does) hear of
it.

Each created document records its parent in `ChannelRecord.createdFrom`
(migration 054; cleared when the parent is deleted, keeping the child). The
Planner's `orchestrate` host tool (`apps/server/src/agent/orchestrate.ts`,
`orchestrate-index.ts`) is offered under the same permissions and reaches only
unarchived top-level documents in the same repository whose `createdFrom` is
this document:

- `open`: creates up to 20 documents at once, each with `create_document`
semantics.
- `list`: returns each created document's link, Planner state (`working`,
`idle`, `stopped`), open Decisions count, and build state.
- `instruct`: posts one instruction as the person's message to all or named
(`targets`) created documents, starting stopped Planners.
- `index`: writes or updates a table under `## Documents created from this one`
(`open` and `list` refresh an existing table; unchanged tables are not
rewritten).

Limits: documents created before migration 054 have no `createdFrom` link and
are invisible to `orchestrate`; the index refreshes only when `open`, `list`,
or `index` runs; `list`, `instruct`, and `index` cover up to 200 created
documents. See
[Creating documents](docs/hosted-agent.md#creating-documents).

## Research requests and child documents
Expand Down Expand Up @@ -993,7 +1019,7 @@ run `bun run ci` and validate relative links with exact casing.
When a disposable Planner session is created, diagnostics report available tool
names and the external GitHub MCP contribution. Counts vary with SDK and remote
MCP versions. A healthy boundary includes Chopin's document tools (currently
plan-named), `create_document`, child document tools, repository tools, and allowed pull-request
plan-named), `create_document`, `orchestrate`, child document tools, repository tools, and allowed pull-request
tools, and excludes ambient capabilities such as `bash`, filesystem access, URL
fetch, host Git, issues, and unrestricted search. The exception is an `atomic`
Planner session, which deliberately adds Atomic's builtins and coding tools but
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/agent/job-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const WRITE_TOOLS: ReadonlySet<string> = new Set([
"edit_implementation_graph",
"create_research_workspace",
"create_document",
"fan_out",
"orchestrate",
"propose_investigation",
"set_investigation_build_blocker",
"revise_open_decision",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ 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 { CreatedDocumentState, IndexOutcome } from "./orchestrate";
import type { DocumentRoom } from "./tools";

export const INDEX_HEADING = "Documents created from this one";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ 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 { buildState, MAX_OPEN, orchestrate, orchestrateArguments } from "./orchestrate";
import { INDEX_HEADING, writeIndex } from "./orchestrate-index";
import { documentRoom } from "./heading-harness.test-fixtures";

import type { AuthenticatedSession } from "../auth/session";
Expand All @@ -16,11 +16,11 @@ import type { NewDocumentArguments } from "./new-documents";
import type {
BuildState,
CreatedDocumentState,
FanOutArguments,
FanOutDeps,
IndexWriter,
OrchestrateArguments,
OrchestrateDeps,
PlannerState,
} from "./fan-out";
} from "./orchestrate";
import type { BuildRequest } from "@chopin/protocol/implementation";

const NOW = new Date("2026-11-16T12:00:00.000Z");
Expand Down Expand Up @@ -85,7 +85,7 @@ async function fixture(
let planners = new Map<string, PlannerState>();
let builds = new Map<string, BuildState>();
let push = options.push ?? true;
let deps: FanOutDeps = {
let deps: OrchestrateDeps = {
channel: id => storage.channels.get(id),
deleting: () => false,
login: async () => login(),
Expand All @@ -110,8 +110,8 @@ async function fixture(
indexed.push({ documents, create });
return create ? { state: "written" } : { state: "absent" };
};
let call = (args: FanOutArguments) =>
fanOut(deps, {
let call = (args: OrchestrateArguments) =>
orchestrate(deps, {
sourceId: source.id,
creator: { userId: "U_mona", handle: "mona" },
arguments: args,
Expand All @@ -134,42 +134,44 @@ function byTitle<T extends { title: string }>(documents: T[]): T[] {
return documents.toSorted((left, right) => left.title.localeCompare(right.title));
}

describe("fan_out arguments", () => {
describe("orchestrate arguments", () => {
test("take each operation's own fields only", () => {
expect(fanOutArguments({ operation: "list" })).toEqual({ operation: "list" });
expect(fanOutArguments({ operation: "instruct", instruction: "Resume." })).toEqual({
expect(orchestrateArguments({ operation: "list" })).toEqual({ operation: "list" });
expect(orchestrateArguments({ operation: "instruct", instruction: "Resume." })).toEqual({
operation: "instruct",
instruction: "Resume.",
});
expect(() => fanOutArguments({ operation: "list", instruction: "Resume." })).toThrow(
"fan_out list does not take `instruction`",
expect(() => orchestrateArguments({ operation: "list", instruction: "Resume." })).toThrow(
"orchestrate 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: [] }))
expect(() => orchestrateArguments({ operation: "close" })).toThrow("operation must be one of");
expect(() => orchestrateArguments({ operation: "instruct" })).toThrow("instruction");
expect(() => orchestrateArguments({ 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(() => orchestrateArguments({ operation: "open", documents: [] })).toThrow(
"at least one",
);
expect(() =>
fanOutArguments({
orchestrateArguments({
operation: "open",
documents: [piece("login-page", "Login"), { title: "x" }],
})
).toThrow("documents[1]: idempotencyKey");
expect(() =>
fanOutArguments({
orchestrateArguments({
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");
expect(() => orchestrateArguments({ operation: "open", documents: many })).toThrow("at most");
});
});

describe("fanOut", () => {
describe("orchestrate", () => {
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(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* The Planner's `fan_out`: one document's Planner working with the documents it created.
* The Planner's `orchestrate`: 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
Expand Down Expand Up @@ -35,20 +35,20 @@ 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 const ORCHESTRATE_OPERATIONS = ["open", "list", "instruct", "index"] as const;

export type FanOutArguments =
export type OrchestrateArguments =
| { operation: "open"; documents: NewDocumentArguments[] }
| { operation: "list" }
| { operation: "instruct"; instruction: string; targets?: string[] }
| { operation: "index" };

export const FAN_OUT_SCHEMA = {
export const ORCHESTRATE_SCHEMA = {
type: "object",
properties: {
operation: {
type: "string",
enum: [...FAN_OUT_OPERATIONS],
enum: [...ORCHESTRATE_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 "
Expand Down Expand Up @@ -81,26 +81,26 @@ export const FAN_OUT_SCHEMA = {
additionalProperties: false,
};

const FIELDS: Record<FanOutArguments["operation"], string[]> = {
const FIELDS: Record<OrchestrateArguments["operation"], string[]> = {
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 {
export function orchestrateArguments(raw: unknown): OrchestrateArguments {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new Error("fan_out arguments must be an object");
throw new Error("orchestrate arguments must be an object");
}
let args = raw as Record<string, unknown>;
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(", ")}`);
if (!ORCHESTRATE_OPERATIONS.includes(operation as OrchestrateArguments["operation"])) {
throw new Error(`operation must be one of ${ORCHESTRATE_OPERATIONS.join(", ")}`);
}
let op = operation as FanOutArguments["operation"];
let op = operation as OrchestrateArguments["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 (unknown) throw new Error(`orchestrate ${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");
Expand Down Expand Up @@ -176,23 +176,23 @@ export type IndexWriter = (
create: boolean,
) => Promise<IndexOutcome>;

export type FanOutDeps = NewDocumentDeps & {
export type OrchestrateDeps = NewDocumentDeps & {
/** Unarchived documents created from a document, oldest first. */
createdFrom: (sourceId: string, limit: number) => Promise<ChannelRecord[]>;
planner: (channelId: string) => PlannerState;
build: (channelId: string) => Promise<BuildState>;
};

export type FanOutRequest = Omit<NewDocumentRequest, "arguments"> & {
arguments: FanOutArguments;
export type OrchestrateRequest = Omit<NewDocumentRequest, "arguments"> & {
arguments: OrchestrateArguments;
index: IndexWriter;
};

type Instructed =
& Pick<CreatedDocumentState, "id" | "title" | "url">
& ({ started: true } | { started: false; reason: string; message?: string });

export type FanOutResult =
export type OrchestrateResult =
| {
ok: true;
operation: "open";
Expand Down Expand Up @@ -220,7 +220,7 @@ const REFUSALS: Record<string, string> = {
"nothing-created": "No document was created from this one, so there is nothing to instruct.",
};

function refused(reason: string): FanOutResult {
function refused(reason: string): OrchestrateResult {
return { ok: false, reason, message: REFUSALS[reason]! };
}

Expand All @@ -238,22 +238,25 @@ async function bounded<T, R>(items: T[], work: (item: T) => Promise<R>): Promise
return results;
}

function url(deps: FanOutDeps, channel: ChannelRecord): string {
function url(deps: OrchestrateDeps, 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<ChannelRecord[]> {
async function created(deps: OrchestrateDeps, source: ChannelRecord): Promise<ChannelRecord[]> {
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<CreatedDocumentState[]> {
async function states(
deps: OrchestrateDeps,
source: ChannelRecord,
): Promise<CreatedDocumentState[]> {
return Promise.all((await created(deps, source)).map(async channel => ({
id: channel.id,
title: channel.title,
Expand All @@ -265,18 +268,18 @@ async function states(deps: FanOutDeps, source: ChannelRecord): Promise<CreatedD
}

/** Whether `wanted`, an id or a url, names `channel`. */
function names(deps: FanOutDeps, channel: ChannelRecord, wanted: string): boolean {
function names(deps: OrchestrateDeps, 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,
deps: OrchestrateDeps,
request: OrchestrateRequest,
source: ChannelRecord,
args: Extract<FanOutArguments, { operation: "instruct" }>,
): Promise<FanOutResult> {
args: Extract<OrchestrateArguments, { operation: "instruct" }>,
): Promise<OrchestrateResult> {
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)));
Expand Down Expand Up @@ -327,7 +330,10 @@ async function instruct(
};
}

export async function fanOut(deps: FanOutDeps, request: FanOutRequest): Promise<FanOutResult> {
export async function orchestrate(
deps: OrchestrateDeps,
request: OrchestrateRequest,
): Promise<OrchestrateResult> {
let source = await deps.channel(request.sourceId);
if (!source || source.archivedAt || deps.deleting(source.id) || source.parentChannelId) {
return refused("document-unavailable");
Expand Down
Loading
Loading