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

A Talk build starts no crew run and no review, and only a person publishes it #17803

opened this

Merged 8h 18m ago, live in production

cf/talk-build-no-crew → main 0 commits

  • Merged. cf/talk-build-no-crew was merged into main as cd1d5b7.

Review

Sign in to review this change.
9 files changed +201 −7
docs/features/talk.md +1
@@ -194,6 +194,7 @@ An empty conversation offers Build an app among its starters (#15734); it opens
194194
195195 - **Versions** are the branch's commits past main, numbered v1, v2 from the oldest (`src/actions/build.ts`); nothing about them is stored twice. The first one opens the branch's pull, which is what gives it a preview: it opens when a turn ends, or on Restore or Publish; a read never writes. `?v=N` shows that version's files changed; **Restore** makes a new version holding exactly its tree, history kept.
196196 - **Publish** merges the pull to the default branch, which deploys production; the production URL then shows as a link. Only a person publishes.
197 - **The crew** has no part in a new app until then: the conversation's agent is its builder. No issue is opened, no crew is seated, no run starts, and the build's pull is checked but sent to no review and landed by nothing but Publish. Publish seats a builder and a reviewer and turns autonomy on, as a new app made the ordinary way has from the start. It needs no review of its own unless the owner requires reviews. `test/talk-build-no-crew.test.ts`.
197198 - **API:** `POST /api/v1/builds {prompt, template?, model?}`, `GET /api/v1/conversations/:id/build`, `GET …/build/versions/:n/diff`, `POST …/build/restore {version}`, `POST …/build/publish`. Web forms: `POST /talk/build`, `/talk/:id/build/restore`, `/talk/:id/build/publish`.
198199 - **Limits:** five builds an hour and ten unpublished at once, per person (`BUILDS_PER_HOUR`, `UNPUBLISHED_MAX`); a template must be one on offer to that person, on the API as on the page; a start that fails takes back the repository and conversation it made.
199200 - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template, `m` the model), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `U` restores the chosen version, `P` publishes, `R` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read.
src/actions/apps.ts +6 −1
@@ -290,6 +290,11 @@ export interface NewAppInput {
290290 * also given.
291291 */
292292 pickAgent?: boolean;
293 /**
294 * A conversation builds this app (`actions/build.ts`): no issue is opened and no crew is seated, so no
295 * run starts on it. Publish seats the crew.
296 */
297 builtInTalk?: boolean;
293298 /** `owner/name` of a repository the actor can read: its tip is copied instead of the starter app. */
294299 template?: string;
295300 /**
@@ -450,7 +455,7 @@ export async function newApp(
450455 payload: { names: secrets.map((x) => x.name), scope: "all" },
451456 });
452457
453 const description = brief;
458 const description = input.builtInTalk === true ? "" : brief;
454459 let chosen = agent;
455460 let body = description;
456461 let picked: NewAppResult["plan"];
src/actions/build.ts +9 −3
@@ -32,6 +32,7 @@ import { createBranch } from "./branches.ts";
3232 import { ensureBuildPull, type Version, versionsIn } from "./build_pull.ts";
3333 import { mergePull, readyPull } from "./pulls.ts";
3434 import { deleteRepo } from "./repos.ts";
35 import { seatEmptyCrew } from "./seat_crew.ts";
3536 import { TALK_WORDS, talk } from "./talk.ts";
3637
3738 export { VERSIONS_MAX, type Version } from "./build_pull.ts";
@@ -119,7 +120,7 @@ export async function startBuild(
119120 const conversation = createConversation(app.db, user.value.id);
120121 if (!conversation.ok) return err("failed");
121122 if (input.model !== undefined) setChoice(app.db, user.value, conversation.value.id, input.model);
122 const made = await newAppFromSentence(app, user.value, { sentence: input.prompt, ...(template === undefined ? {} : { template }) });
123 const made = await newAppFromSentence(app, user.value, { sentence: input.prompt, builtInTalk: true, ...(template === undefined ? {} : { template }) });
123124 if (!made.ok) {
124125 dropConversation(app.db, user.value.id, conversation.value.id);
125126 // Words that name nothing cost nothing, so they do not use up the hour.
@@ -288,10 +289,15 @@ export async function publishBuild(app: App, actor: User | undefined, conversati
288289 const pull = getPull(app.db, repo.id, build.pullNumber);
289290 if (pull === undefined) return err("not_found");
290291 if (build.lane) return shipLane(app, writer.value, repo, pull, conversationId);
291 // A brand-new app's pull is no draft: it merges exactly as it always has.
292 const merged = await mergePull(app, user.value, repo, pull, "merge");
292 // A brand-new app's pull is no draft: it merges as any pull does, but for the review a seated
293 // reviewer asks for. The crew was never sent this one: publishing it is the person's own call. An
294 // owner who requires reviews (`requireReview`) still has them.
295 const merged = await mergePull(app, user.value, repo, pull, "merge", undefined, { pastReviews: true });
293296 if (!merged.ok) return err("failed");
294297 setBuildPublished(app.db, conversationId);
298 // From here the app is the crew's to work on: seated now, not while Talk was writing it. It is
299 // published whether or not a crew could be seated; the app's page offers the seat again.
300 await seatEmptyCrew(app, user.value, repo).catch((error: unknown) => app.log.warn("the crew was not seated on a published build", { repo: repo.name, error: String(error) }));
295301 const after = await buildState(app, user.value, conversationId);
296302 return ok({ productionUrl: after.ok ? after.value.productionUrl : null });
297303 }
src/actions/pulls.ts +2 −1
@@ -623,7 +623,8 @@ export async function mergePull(
623623 requireChecks: repo.requireChecks && opts.pastGate !== true,
624624 freshGreen: opts.pastGate !== true,
625625 waiveUnavailable: reason !== undefined,
626 // Only an app's first change, which the crew's gate decided (`crew/first_change.ts`); never a person's own call.
626 // Only an app's first change, which the crew's gate decided (`crew/first_change.ts`), and a new app's
627 // Publish (`actions/build.ts`); never a press of Merge.
627628 ...(opts.pastReviews === true && !repo.requireReview ? { pastReviews: true } : {}),
628629 // A named team with a reviewer here reads this head first (#10080).
629630 ...(opts.pastGate === true
src/core/chat_build.ts +11
@@ -57,6 +57,17 @@ export function setBuildPublished(db: Database, conversationId: string): void {
5757 db.query("UPDATE chat_build SET published_at = ?2 WHERE conversation_id = ?1").run(conversationId, new Date().toISOString());
5858 }
5959
60 /**
61 * Whether a conversation is still building this new app: its agent is the builder, so the crew starts
62 * nothing there by itself until the person publishes. A lane build is in an app the crew already has.
63 */
64 export const builtInTalk = (db: Database, repoId: string): boolean =>
65 db.query("SELECT 1 FROM chat_build WHERE repo_id = ?1 AND lane = 0 AND published_at IS NULL LIMIT 1").get(repoId) !== null;
66
67 /** Whether the pull is a build its conversation is still writing: no review reads it and nothing lands it but Publish. */
68 export const isUnpublishedBuild = (db: Database, pull: { readonly repoId: string; readonly number: number }): boolean =>
69 db.query("SELECT 1 FROM chat_build WHERE repo_id = ?1 AND pull_number = ?2 AND published_at IS NULL LIMIT 1").get(pull.repoId, pull.number) !== null;
70
6071 /**
6172 * What the agent is told before every message of a building conversation:
6273 * where to work. Server text, so it is not fenced; the names in it are the
src/crew/drive.ts +3 −1
@@ -8,6 +8,7 @@ import { assignIssue } from "../actions/issues.ts";
88 import { walkOwed } from "../actions/journey_walk.ts";
99 import type { App } from "../app.ts";
1010 import { type Agent, type CrewRole, listCrewRoles } from "../core/agents.ts";
11 import { builtInTalk } from "../core/chat_build.ts";
1112 import { type Ranked, readyNow, repoGraph } from "../core/dependencies.ts";
1213 import { getIssueById, type Issue } from "../core/issues.ts";
1314 import { getRepoById, type Repo } from "../core/repos.ts";
@@ -70,7 +71,8 @@ async function driveOnce(
7071 taken: Set<string>,
7172 picked: TickPicks,
7273 ): Promise<Drove> {
73 if (repo.autonomy === "off") return "off";
74 // An app a conversation is still building has its builder: the crew starts when it is published.
75 if (repo.autonomy === "off" || builtInTalk(app.db, repo.id)) return "off";
7476 tickBets(app, repo, now);
7577 // Journeys are walked apart from the tick: a browser and a model call never hold the crew back.
7678 void walkOwed(app, repo, now).catch(() => undefined);
src/crew/land_admit.ts +3
@@ -12,6 +12,7 @@ import { addLearned } from "../checks/learned.ts";
1212 import type { Queued } from "../checks/queue.ts";
1313 import { wallOf, wallPlain, wallSentence } from "../contract/policy.ts";
1414 import { latestDecision, recordDecision, stopStands } from "../core/decisions.ts";
15 import { isUnpublishedBuild } from "../core/chat_build.ts";
1516 import { getHold } from "../core/holds.ts";
1617 import { getIssueById } from "../core/issues.ts";
1718 import { getPull, type Pull, pullDir, reviewGate } from "../core/pulls.ts";
@@ -59,6 +60,8 @@ export async function admit(
5960 // released — no landing, no review sent, no run to bring the branch up
6061 // to date (`core/holds.ts`).
6162 if (getHold(app.db, pull.id) !== undefined) return err("held");
63 // A build its conversation is still writing lands when its person publishes it, never on green.
64 if (isUnpublishedBuild(app.db, pull)) return err("held");
6265 // Only work the crew wrote, or a writer's, lands on green by itself: a
6366 // reader's pull — from a fork, say — waits for a person, outsiders
6467 // switch or not; not from here is it sent to the crew's reviewer (#619),
src/crew/review.ts +3 −1
@@ -22,6 +22,7 @@ import type { App } from "../app.ts";
2222 import { crewWithRole, type Agent } from "../core/agents.ts";
2323 import { getHold, holdsFor, lastReleasesFor } from "../core/holds.ts";
2424 import { getIssueById, LIST_LIMIT_MAX } from "../core/issues.ts";
25 import { isUnpublishedBuild } from "../core/chat_build.ts";
2526 import { isDraft, listPulls, pullDiff, type Pull, pullDir} from "../core/pulls.ts";
2627 import { getRepoById, PILLAR_MAX, type Repo } from "../core/repos.ts";
2728 import { teamsOfPull, teamVerdicts } from "../core/issue_teams.ts";
@@ -652,7 +653,8 @@ export async function sendToReview(
652653 // A paused reviewer reads like an empty seat: the pull waits for a person, and says so.
653654 if (reviewers.length === 0 || reviewerPaused(repo)) return "none";
654655 // A draft is a first build still being written (`crew/early.ts`): it waits for its run to end.
655 if (isDraft(pull)) return "wait";
656 // So does a build its conversation is still writing (`core/chat_build.ts`): it waits for Publish.
657 if (isDraft(pull) || isUnpublishedBuild(app.db, pull)) return "wait";
656658 // A stranger's pull is the crew's to filter on an autonomous repository
657659 // (#9575); anywhere else a guest waits for a person's word before the
658660 // crew touches it (`origins/guest.ts`).
test/talk-build-no-crew.test.ts added +163
@@ -0,0 +1,163 @@
1 /**
2 * An app Talk builds has one builder, the conversation's agent: until Publish no issue is opened, no
3 * crew is seated, no run of any kind starts, and nothing reviews or lands its pull. After it the crew
4 * works on the app. An app asked of the crew starts a run as before.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { chmodSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { newApp } from "../src/actions/apps.ts";
10 import { startBuild } from "../src/actions/build.ts";
11 import { buildTurnEnded } from "../src/actions/build_pull.ts";
12 import { commitToBranch } from "../src/actions/repos.ts";
13 import { chatBuildOf, isUnpublishedBuild } from "../src/core/chat_build.ts";
14 import { addCrew, createAgentRow, listCrewRoles } from "../src/core/agents.ts";
15 import { listIssues } from "../src/core/issues.ts";
16 import { getPull, type Pull } from "../src/core/pulls.ts";
17 import { getRepo, getRepoById, updateRepoSettings, type Repo } from "../src/core/repos.ts";
18 import { listRuns } from "../src/core/runs.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createToken } from "../src/core/tokens.ts";
21 import { createUser } from "../src/core/users.ts";
22 import { configureConversation } from "../src/crew/conversation.ts";
23 import { driveRepo } from "../src/crew/drive.ts";
24 import { landIfGreen } from "../src/crew/land_queue.ts";
25 import { greenHead, sendToReview } from "../src/crew/review.ts";
26 import { ok } from "../src/kernel/result.ts";
27 import { agentRunSettled, startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29 import { pollUntil } from "./helpers/poll.ts";
30
31 quietLogs();
32
33 let s: StandInCrew;
34 let token = "";
35 /** A build of the first test, kept for the last: a person starts at most five an hour. */
36 let kept = "";
37 const KEY = process.env["ANTHROPIC_API_KEY"];
38
39 beforeAll(async () => {
40 process.env["ANTHROPIC_API_KEY"] = "made-up-key";
41 s = await startStandInCrew({ tickMs: 50, autonomyEveryMs: 100, checkStep: async () => ok() });
42 token = createToken(s.app.db, s.alice.id, "personal", "rw").token;
43 // The conversation's agent: it answers, and the test commits what it would have.
44 const bin = join(s.dataDir, "talk-claude");
45 writeFileSync(bin, `#!/bin/sh
46 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
47 IFS= read -r first
48 echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}'
49 echo '{"type":"result","subtype":"success","is_error":false,"result":"Built.","total_cost_usd":0,"num_turns":1,"session_id":"s1","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
50 `);
51 chmodSync(bin, 0o755);
52 configureConversation(s.app, { binary: bin, localUrl: s.servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal });
53 }, 60_000);
54 afterAll(async () => {
55 await stopStandInCrew(s);
56 if (KEY === undefined) delete process.env["ANTHROPIC_API_KEY"];
57 else process.env["ANTHROPIC_API_KEY"] = KEY;
58 });
59
60 const json = { "content-type": "application/json" };
61 const api = async (path: string, body: unknown): Promise<Record<string, unknown>> => {
62 const res = await fetch(`${s.servers.url}${path}`, { method: "POST", headers: { ...json, accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });
63 expect(res.status).toBeLessThan(300);
64 return (await res.json()) as Record<string, unknown>;
65 };
66 /** Each door to a build, answering with its conversation. The terminal's screen calls `startBuild` itself. */
67 const doors: Record<string, (prompt: string) => Promise<string>> = {
68 "the API": async (prompt) => String((await api("/api/v1/builds", { prompt }))["conversation"]),
69 "the web form": async (prompt) => {
70 const res = await fetch(`${s.servers.url}/talk/build`, {
71 method: "POST", redirect: "manual", body: new URLSearchParams({ prompt }),
72 headers: { origin: s.servers.url, cookie: `forge_session=${createSession(s.app.db, s.alice.id).token}` },
73 });
74 return res.headers.get("location")!.slice("/talk/".length);
75 },
76 "the MCP say tool": async (prompt) => {
77 const answer = (await api("/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "say", arguments: { action: "build", text: prompt } } })) as { result: { content: { text: string }[] } };
78 return String((JSON.parse(answer.result.content[0]!.text) as { conversation: string }).conversation);
79 },
80 "the terminal's call": async (prompt) => {
81 const made = await startBuild(s.app, s.alice, { prompt });
82 if (!made.ok) throw new Error(made.error);
83 return made.value.build.conversationId;
84 },
85 };
86 const repoOf = (conversation: string): Repo => getRepoById(s.app.db, chatBuildOf(s.app.db, conversation)!.repoId)!;
87 const agentRuns = (repo: Repo) => listRuns(s.app.db, repo.id, { kind: "agent" });
88 /** Two versions, as two turns of the agent leave them, and the build's pull with its check green. */
89 async function versions(conversation: string): Promise<{ repo: Repo; pull: () => Pull }> {
90 const repo = repoOf(conversation);
91 const build = chatBuildOf(s.app.db, conversation)!;
92 const pull = (): Pull => getPull(s.app.db, repo.id, chatBuildOf(s.app.db, conversation)!.pullNumber!)!;
93 for (const v of ["one", "two"]) {
94 const done = await commitToBranch(s.app, s.alice, repo, { branch: build.branch, message: `Add ${v}`, files: [{ path: "page.txt", content: `${v}\n` }] });
95 if (!done.ok) throw new Error(JSON.stringify(done.error));
96 await buildTurnEnded(s.app, s.alice.id, conversation);
97 await pollUntil(() => greenHead(s.app.db, pull()), `the check of version ${v}`);
98 }
99 return { repo, pull };
100 }
101
102 const built: Repo[] = [];
103 const THINGS: Record<string, string> = { "the API": "lantern", "the web form": "compass", "the MCP say tool": "teapot", "the terminal's call": "ladder" };
104 for (const [door, start] of Object.entries(doors)) {
105 test(`through ${door}, over two green versions: no issue and no crew`, async () => {
106 kept = await start(`a ${THINGS[door]!} catalogue`);
107 const { repo } = await versions(kept);
108 expect(listCrewRoles(s.app.db, repo.id)).toEqual([]);
109 expect(listIssues(s.app.db, repo.id, { kind: "issue", state: "all" })).toEqual([]);
110 expect(repo.autonomy).toBe("off");
111 built.push(repo);
112 }, 120_000);
113 }
114
115 test("no run and no review started in any of them, while an app asked of the crew starts its run", async () => {
116 expect(built).toHaveLength(Object.keys(doors).length);
117 // Asked of the crew after them all: its run settling says the dispatcher has been past the builds' events.
118 const asked = await newApp(s.app, s.alice, { name: "asked-of-the-crew", description: "Count the birds in the garden." });
119 if (!asked.ok) throw new Error(String(asked.error));
120 expect(asked.value.issue?.assigneeName).toBeDefined();
121 await agentRunSettled(s.app, asked.value.repo, (r) => r.reason === "assigned");
122 for (const repo of built) expect(agentRuns(repo), repo.name).toEqual([]);
123 }, 120_000);
124
125 test("with a reviewer seated and autonomy on, as a spawned forge seats a new repository: no review, no landing, no pick; Publish still merges and the crew is free to work", async () => {
126 const conversation = await doors["the API"]!("a harbour notebook");
127 const fresh = repoOf(conversation);
128 const made = await createUser(s.app.db, { username: "reader", email: "[email protected]", agent: true, origin: "spawn" });
129 if (!made.ok) throw new Error(made.error);
130 createAgentRow(s.app.db, { userId: made.value.id, roles: ["reviewer"] });
131 addCrew(s.app.db, fresh.id, s.bot.id, s.alice.id, "builder");
132 addCrew(s.app.db, fresh.id, made.value.id, s.alice.id, "reviewer");
133 updateRepoSettings(s.app.db, fresh, { autonomy: "autonomous", autonomyBy: s.alice.id });
134 const { pull } = await versions(conversation);
135 const repo = repoOf(conversation);
136 expect(isUnpublishedBuild(s.app.db, pull())).toBe(true);
137 expect(await sendToReview(s.app, repo, pull())).toBe("wait");
138 expect(await landIfGreen(s.app, repo, pull())).toBe(false);
139 expect(await driveRepo(s.app, repo)).toBe("off");
140 expect(pull().mergedAt).toBeNull();
141 expect(agentRuns(repo)).toEqual([]);
142 const published = await api(`/api/v1/conversations/${conversation}/build/publish`, {});
143 expect(published["published"]).toBe(true);
144 expect(pull().mergedAt).not.toBeNull();
145 expect(isUnpublishedBuild(s.app.db, pull())).toBe(false);
146 expect(await driveRepo(s.app, repo)).not.toBe("off");
147 }, 120_000);
148
149 test("an owner who requires reviews has them: Publish does not merge past that", async () => {
150 const conversation = kept;
151 const pull = (): Pull => getPull(s.app.db, repoOf(conversation).id, chatBuildOf(s.app.db, conversation)!.pullNumber!)!;
152 updateRepoSettings(s.app.db, repoOf(conversation), { requireReview: true });
153 const res = await fetch(`${s.servers.url}/api/v1/conversations/${conversation}/build/publish`, { method: "POST", headers: { ...json, authorization: `Bearer ${token}` }, body: "{}" });
154 expect(res.status).toBeGreaterThanOrEqual(400);
155 expect(pull().mergedAt).toBeNull();
156 // Publishing the ordinary way seats the crew and turns autonomy on.
157 updateRepoSettings(s.app.db, repoOf(conversation), { requireReview: false });
158 expect((await api(`/api/v1/conversations/${conversation}/build/publish`, {}))["published"]).toBe(true);
159 const repo = getRepo(s.app.db, "alice", repoOf(conversation).name)!;
160 expect(listCrewRoles(s.app.db, repo.id).map((c) => c.role).sort()).toEqual(["builder", "reviewer"]);
161 expect(repo.autonomy).toBe("autonomous");
162 expect(repo.autonomyBy).toBe(s.alice.id);
163 }, 120_000);

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

Keyboard shortcuts

Docs