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

Distilled posts: a wave or a milestone that landed goes out as one short post on X, read before it goes if the owner wants #1889

Parked opened this in answer to
Closed without merging

scout/forge:scout/1084-distilled-posts-a-wave-or-a-milestone-th → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +2264 −1
docs/STORY.md added +59
@@ -0,0 +1,59 @@
1 # Story: saying what landed
2
3 Waves (`waves/<version>.md`, cut by `actions/cut_wave.ts`) are the forge's
4 record of what changed and why. A **channel** carries a wave outside: today,
5 one short post on X (#1084).
6
7 ## The channel
8
9 Under **Settings → Channels** a repository admin connects one X account per
10 repository (the table `channel`, kind `x`). The page takes the client id and
11 secret of an X app, then sends the browser to X for OAuth 2.0 with PKCE; X
12 redirects to `/oauth/x/callback` on the forge. The secret and the tokens are
13 one blob sealed under the forge's key and bound to the row, never listed,
14 never shown again; the forge refreshes the access token itself
15 (`offline.access`) when it is about to end, and keeps the new refresh token.
16
17 When a wave lands on the default branch, or a milestone someone watches
18 lands, the routine (`crew/channels.ts`, every minute) drafts one post:
19
20 - **Review before posting** (on by default): the draft is held. It is one
21 decision in the owner's feed and a row in the log on the page, with
22 **Post** and **Not this one**.
23 - Off: it posts at once.
24
25 Connecting posts nothing of history: what had already landed is marked seen.
26 Each subject (`wave:<version>`, `milestone:<issue>`) has one row in
27 `channel_post`, so nothing is drafted or posted twice; a send is claimed
28 atomically before X is called. A failure is a sentence on the page and the
29 draft stays for another **Post**; a token X no longer accepts disconnects the
30 channel and says to connect again. **A private repository never posts**: it
31 is not drafted for, and a draft held before the repository turned private is
32 refused at the moment of sending.
33
34 API: `GET/POST /api/v1/repos/:o/:n/channels` (POST with
35 `clientId`, `clientSecret` begins the authorization and answers with
36 `authorizeUrl`; with `reviewBeforePosting` or `hashtags` it changes those),
37 `DELETE …/channels/:id`, `POST …/channels/:id/post` (`{post?, decision:
38 "post"|"pass"}`: sends or passes the held draft). MCP: `posts { app }`.
39
40 ## The writing standard
41
42 The post is what a person would be happy to hear: the thing that changed and
43 why it matters, in their words — the wave's headline, the first sentence of
44 the first highlight's why, and a link to the wave. Under 240 characters
45 including the link; no hashtags unless the owner set up to three; no commit
46 language. It is drafted from the wave's note, never from pulls. A note still
47 carrying its `TODO` placeholders is not drafted. A milestone's post is
48 "Done: <name>." and the first sentence of the issue's body.
49
50 ## What the owner makes at X
51
52 1. At developers.x.com, a project and an app.
53 2. OAuth 2.0 with user authentication, type **Web App** (a confidential
54 client), with read and write permissions.
55 3. The callback URL, exactly: `<forge url>/oauth/x/callback` (the page prints
56 it).
57 4. The client id and secret, pasted on the Channels page; then **Authorize at
58 X**. The forge asks for `tweet.read tweet.write users.read offline.access`
59 (X requires `tweet.read` to post).
scripts/gate.ts +1
@@ -97,6 +97,7 @@ export const GATE: readonly string[] = [
9797 "test/themes.test.ts",
9898 "test/waves.test.ts",
9999 "test/cut-wave.test.ts",
100 "test/channels.test.ts",
100101 "test/crew-wrapup.test.ts",
101102 "test/crew-limits.test.ts",
102103 "test/crew-parks.test.ts",
src/actions/channels.ts added +338
@@ -0,0 +1,338 @@
1 /**
2 * Channel actions (#1084): connect an X account (the OAuth dance with PKCE,
3 * the redirect landing on the forge), choose whether a draft waits for the
4 * owner, send or pass a held draft, disconnect. Admin over the repository,
5 * like Prompts. The drafting is the routine's (`crew/channels.ts`).
6 */
7
8 import type { App } from "../app.ts";
9 import {
10 channelByState,
11 channelOf,
12 getChannel,
13 getPost,
14 heldPosts,
15 isClientId,
16 isClientSecret,
17 listPosts,
18 markConnected,
19 openSecrets,
20 parseHashtags,
21 pendingState,
22 removeChannel as deleteChannel,
23 createChannel,
24 finishPost,
25 setPending,
26 setSettings,
27 storeSecrets,
28 type Channel,
29 type ChannelPost,
30 } from "../core/channels.ts";
31 import { canAdmin, getRepoById, type Repo } from "../core/repos.ts";
32 import type { User } from "../core/users.ts";
33 import { channelsFor, sendPost } from "../crew/channels.ts";
34 import {
35 authorizeUrl,
36 newState,
37 newVerifier,
38 XError,
39 } from "../crew/x.ts";
40 import { err, ok, type Result } from "../kernel/result.ts";
41 import { requireRepoAdmin } from "./access.ts";
42
43 export interface PostView {
44 readonly id: string;
45 readonly subject: string;
46 readonly text: string;
47 readonly link: string;
48 readonly state: ChannelPost["state"];
49 readonly xId: string | null;
50 readonly said: string;
51 readonly at: string;
52 readonly postedAt: string | null;
53 }
54
55 export interface ChannelView {
56 readonly id: string;
57 readonly kind: "x";
58 readonly clientId: string;
59 readonly connected: boolean;
60 readonly refreshedAt: string | null;
61 readonly reviewBeforePosting: boolean;
62 readonly hashtags: string;
63 readonly lastPostedAt: string | null;
64 readonly lastSaid: string;
65 /** Where the owner authorizes, while an authorization waits. */
66 readonly authorizeUrl: string | null;
67 /** The address to register at X as the callback. */
68 readonly redirectUri: string;
69 readonly posts: readonly PostView[];
70 }
71
72 export const redirectUriFor = (app: App): string =>
73 `${(app.config.url ?? `http://localhost:${app.config.port}`).replace(/\/+$/, "")}/oauth/x/callback`;
74
75 const postView = (p: ChannelPost): PostView => ({
76 id: p.id,
77 subject: p.subject,
78 text: p.text,
79 link: p.link,
80 state: p.state,
81 xId: p.externalId,
82 said: p.said,
83 at: p.createdAt,
84 postedAt: p.postedAt,
85 });
86
87 function viewOf(app: App, c: Channel): ChannelView {
88 let url: string | null = null;
89 const state = pendingState(app.db, c.id);
90 if (state !== null) {
91 const secrets = openSecrets(app.db, app.config.dataDir, c.id);
92 if (secrets.ok && secrets.value.verifier !== undefined)
93 url = authorizeUrl({
94 clientId: c.clientId,
95 redirectUri: redirectUriFor(app),
96 state,
97 verifier: secrets.value.verifier,
98 });
99 }
100 return {
101 id: c.id,
102 kind: c.kind,
103 clientId: c.clientId,
104 connected: c.connected,
105 refreshedAt: c.refreshedAt,
106 reviewBeforePosting: c.reviewBeforePosting,
107 hashtags: c.hashtags,
108 lastPostedAt: c.lastPostedAt,
109 lastSaid: c.lastSaid,
110 authorizeUrl: url,
111 redirectUri: redirectUriFor(app),
112 posts: listPosts(app.db, c.id).map(postView),
113 };
114 }
115
116 export type ChannelError =
117 | "not_found"
118 | "invalid_kind"
119 | "invalid_client_id"
120 | "invalid_client_secret"
121 | "invalid_hashtags"
122 | "no_credentials"
123 | "no_such_channel"
124 | "no_such_post"
125 | "not_connected"
126 | "not_running";
127
128 const owned = (app: App, repo: Repo, channelId: string): Channel | undefined => {
129 const c = getChannel(app.db, channelId);
130 return c?.repoId === repo.id ? c : undefined;
131 };
132
133 export function listChannels(
134 app: App,
135 actor: User | undefined,
136 repo: Repo,
137 ): Result<ChannelView[], "not_found"> {
138 const admin = requireRepoAdmin(app, actor, repo);
139 if (!admin.ok) return admin;
140 const c = channelOf(app.db, repo.id);
141 return ok(c ? [viewOf(app, c)] : []);
142 }
143
144 export interface ConnectInput {
145 readonly kind: string;
146 readonly clientId?: string | undefined;
147 readonly clientSecret?: string | undefined;
148 readonly review?: boolean | undefined;
149 readonly hashtags?: string | undefined;
150 }
151
152 /**
153 * Connect, or change. With credentials: they are sealed and an
154 * authorization begins (the view carries the address to authorize at).
155 * Without: only the review toggle and hashtags change. One X channel per
156 * repository, so a second call is the same channel.
157 */
158 export function connectChannel(
159 app: App,
160 actor: User | undefined,
161 repo: Repo,
162 input: ConnectInput,
163 ): Result<{ channel: ChannelView; created: boolean }, ChannelError> {
164 const admin = requireRepoAdmin(app, actor, repo);
165 if (!admin.ok) return admin;
166 if (input.kind !== "x") return err("invalid_kind");
167 const hashtags =
168 input.hashtags === undefined ? undefined : parseHashtags(input.hashtags);
169 if (input.hashtags !== undefined && hashtags === undefined)
170 return err("invalid_hashtags");
171 const clientId = input.clientId?.trim() ?? "";
172 const clientSecret = input.clientSecret?.trim() ?? "";
173 const given = clientId !== "" || clientSecret !== "";
174 if (given && !isClientId(clientId)) return err("invalid_client_id");
175 if (given && !isClientSecret(clientSecret)) return err("invalid_client_secret");
176 let channel = channelOf(app.db, repo.id);
177 let created = false;
178 if (channel === undefined) {
179 if (!given) return err("no_credentials");
180 channel = createChannel(app.db, app.config.dataDir, {
181 repoId: repo.id,
182 clientId,
183 clientSecret,
184 createdBy: admin.value.id,
185 });
186 created = true;
187 }
188 setSettings(app.db, channel.id, { review: input.review, hashtags });
189 if (given) {
190 const verifier = newVerifier();
191 storeSecrets(app.db, app.config.dataDir, channel.id, { clientSecret, verifier });
192 app.db
193 .query("UPDATE channel SET client_id = ?2 WHERE id = ?1")
194 .run(channel.id, clientId);
195 setPending(app.db, channel.id, newState(), false);
196 }
197 app.bus.append({
198 kind: created ? "channel.added" : "channel.updated",
199 repoId: repo.id,
200 actorId: admin.value.id,
201 payload: { channel: channel.id, kind: "x" },
202 });
203 return ok({ channel: viewOf(app, getChannel(app.db, channel.id)!), created });
204 }
205
206 /**
207 * The browser comes back from X with a code and the state it was given. The
208 * state finds the channel (single use), the signed-in admin must administer
209 * that repository, and the code is traded for tokens, which are sealed.
210 * The reason is a sentence for the page.
211 */
212 export async function finishConnect(
213 app: App,
214 actor: User | undefined,
215 query: { state: string; code: string; error: string },
216 ): Promise<Result<Repo, string>> {
217 const channel = channelByState(app.db, query.state);
218 const repo = channel ? getRepoById(app.db, channel.repoId) : undefined;
219 if (!channel || !repo || !actor || !canAdmin(app.db, repo, actor))
220 return err("That authorization is not waiting here. Start again from Settings → Channels.");
221 const routine = channelsFor(app);
222 if (!routine) return err("This forge is not set up to post to X.");
223 if (query.error !== "" || query.code === "") {
224 setPending(app.db, channel.id, "", false);
225 app.db.query("UPDATE channel SET pending_state = NULL WHERE id = ?1").run(channel.id);
226 return err("X did not authorize the connection. Connect again when ready.");
227 }
228 const secrets = openSecrets(app.db, app.config.dataDir, channel.id);
229 if (!secrets.ok || secrets.value.verifier === undefined)
230 return err("That authorization expired. Connect again.");
231 try {
232 const tokens = await routine.client.exchange({
233 clientId: channel.clientId,
234 clientSecret: secrets.value.clientSecret,
235 code: query.code,
236 verifier: secrets.value.verifier,
237 redirectUri: redirectUriFor(app),
238 });
239 const now = routine.now();
240 storeSecrets(app.db, app.config.dataDir, channel.id, {
241 clientSecret: secrets.value.clientSecret,
242 access: tokens.access,
243 ...(tokens.refresh === undefined ? {} : { refresh: tokens.refresh }),
244 expiresAt: new Date(now.getTime() + tokens.expiresInS * 1000).toISOString(),
245 });
246 markConnected(app.db, channel.id, now, "Connected to X.");
247 } catch (error) {
248 app.db.query("UPDATE channel SET pending_state = NULL WHERE id = ?1").run(channel.id);
249 return err(
250 error instanceof XError && error.kind === "rejected"
251 ? "X did not accept the client id and secret or the code. Connect again."
252 : "X could not be reached. Connect again in a moment.",
253 );
254 }
255 app.bus.append({
256 kind: "channel.connected",
257 repoId: repo.id,
258 actorId: actor.id,
259 payload: { channel: channel.id, kind: "x" },
260 });
261 await routine.sweepOne(channel.id);
262 return ok(repo);
263 }
264
265 /** Change what a connected channel does with a landing. */
266 export function updateChannel(
267 app: App,
268 actor: User | undefined,
269 repo: Repo,
270 channelId: string,
271 input: { review?: boolean | undefined; hashtags?: string | undefined },
272 ): Result<ChannelView, ChannelError> {
273 const admin = requireRepoAdmin(app, actor, repo);
274 if (!admin.ok) return admin;
275 const channel = owned(app, repo, channelId);
276 if (!channel) return err("no_such_channel");
277 const hashtags =
278 input.hashtags === undefined ? undefined : parseHashtags(input.hashtags);
279 if (input.hashtags !== undefined && hashtags === undefined)
280 return err("invalid_hashtags");
281 setSettings(app.db, channel.id, { review: input.review, hashtags });
282 return ok(viewOf(app, getChannel(app.db, channel.id)!));
283 }
284
285 /**
286 * Decide a held draft: send it, or pass on it. With no post named, the
287 * oldest waiting one. A send that fails is a sentence in the result and the
288 * log, the draft kept so Post can be pressed again.
289 */
290 export async function decidePost(
291 app: App,
292 actor: User | undefined,
293 repo: Repo,
294 channelId: string,
295 input: { post?: string | undefined; decision: "post" | "pass" },
296 ): Promise<Result<{ said: string; ok: boolean; post: PostView }, ChannelError>> {
297 const admin = requireRepoAdmin(app, actor, repo);
298 if (!admin.ok) return admin;
299 const channel = owned(app, repo, channelId);
300 if (!channel) return err("no_such_channel");
301 const post =
302 input.post === undefined
303 ? heldPosts(app.db, channel.id)[0]
304 : getPost(app.db, input.post);
305 if (!post || post.channelId !== channel.id) return err("no_such_post");
306 const now = channelsFor(app)?.now() ?? new Date();
307 if (input.decision === "pass") {
308 if (post.state !== "held" && post.state !== "failed") return err("no_such_post");
309 const said = "Passed: this one will not be posted.";
310 finishPost(app.db, post.id, { state: "passed", said, now });
311 return ok({ said, ok: true, post: postView(getPost(app.db, post.id)!) });
312 }
313 const routine = channelsFor(app);
314 if (!routine) return err("not_running");
315 if (!channel.connected) return err("not_connected");
316 const sent = await sendPost(app, routine.client, channel, post, now);
317 return ok({ ...sent, post: postView(getPost(app.db, post.id)!) });
318 }
319
320 /** Disconnect. The tokens are forgotten, and the log with them. */
321 export function removeChannel(
322 app: App,
323 actor: User | undefined,
324 repo: Repo,
325 channelId: string,
326 ): Result<void, ChannelError> {
327 const admin = requireRepoAdmin(app, actor, repo);
328 if (!admin.ok) return admin;
329 const channel = owned(app, repo, channelId);
330 if (!channel || !deleteChannel(app.db, channel.id)) return err("no_such_channel");
331 app.bus.append({
332 kind: "channel.removed",
333 repoId: repo.id,
334 actorId: admin.value.id,
335 payload: { channel: channel.id, kind: "x" },
336 });
337 return ok();
338 }
src/actions/cut_wave.ts +1 −1
@@ -21,7 +21,7 @@ export interface CutDone {
2121 }
2222
2323 /** The waves on the default branch, as files. */
24 async function readWaves(app: App, repo: Repo): Promise<WaveFile[]> {
24 export async function readWaves(app: App, repo: Repo): Promise<WaveFile[]> {
2525 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
2626 const tree = await listTree(dir, repo.defaultBranch, "waves");
2727 if (!tree.ok) return [];
src/core/channels.ts added +451
@@ -0,0 +1,451 @@
1 /**
2 * Channels: where a landed wave or milestone is said outside the forge.
3 * One kind so far — an X account, one per repository (#1084). The client
4 * secret and the tokens are one blob sealed under the forge's key, bound to
5 * the row, opened only to talk to X; nothing here returns them in a listing.
6 * `channel_post` is the log and the dedupe: one row per subject, so a wave
7 * is drafted once and posted once. Pure data: no X, no authz, no events.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { id } from "../kernel/id.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import { open, seal } from "../kernel/secret.ts";
14
15 export type ChannelKind = "x";
16 export type PostState =
17 | "held"
18 | "posting"
19 | "posted"
20 | "passed"
21 | "failed"
22 | "seen";
23
24 export interface Channel {
25 readonly id: string;
26 readonly repoId: string;
27 readonly kind: ChannelKind;
28 readonly clientId: string;
29 /** True once the owner has authorized in the browser and X handed tokens. */
30 readonly connected: boolean;
31 readonly refreshedAt: string | null;
32 readonly reviewBeforePosting: boolean;
33 /** Hashtags the owner chose, space-separated; empty means none. */
34 readonly hashtags: string;
35 readonly seeded: boolean;
36 readonly lastPostedAt: string | null;
37 /** What last happened, one sentence for a person. */
38 readonly lastSaid: string;
39 readonly createdAt: string;
40 }
41
42 export interface ChannelPost {
43 readonly id: string;
44 readonly channelId: string;
45 /** `wave:<version>` or `milestone:<issue id>`. */
46 readonly subject: string;
47 readonly text: string;
48 readonly link: string;
49 readonly state: PostState;
50 /** X's id for the post, once posted. */
51 readonly externalId: string | null;
52 readonly said: string;
53 readonly createdAt: string;
54 readonly postedAt: string | null;
55 }
56
57 /** What is sealed: everything secret about the connection. */
58 export interface ChannelSecrets {
59 clientSecret: string;
60 access?: string;
61 refresh?: string;
62 /** ISO time the access token stops working. */
63 expiresAt?: string;
64 /** The PKCE verifier of the authorization in flight. */
65 verifier?: string;
66 }
67
68 interface Row {
69 id: string;
70 repo_id: string;
71 kind: string;
72 client_id: string;
73 connected: number;
74 refreshed_at: string | null;
75 review_before_posting: number;
76 hashtags: string;
77 seeded: number;
78 last_posted_at: string | null;
79 last_said: string;
80 created_at: string;
81 }
82 interface PostRow {
83 id: string;
84 channel_id: string;
85 subject: string;
86 text: string;
87 link: string;
88 state: string;
89 external_id: string | null;
90 said: string;
91 created_at: string;
92 posted_at: string | null;
93 }
94
95 const COLUMNS = `id, repo_id, kind, client_id, connected, refreshed_at, review_before_posting,
96 hashtags, seeded, last_posted_at, last_said, created_at`;
97 const POST_COLUMNS = `id, channel_id, subject, text, link, state, external_id, said, created_at, posted_at`;
98
99 const toChannel = (r: Row): Channel => ({
100 id: r.id,
101 repoId: r.repo_id,
102 kind: "x",
103 clientId: r.client_id,
104 connected: r.connected === 1,
105 refreshedAt: r.refreshed_at,
106 reviewBeforePosting: r.review_before_posting === 1,
107 hashtags: r.hashtags,
108 seeded: r.seeded === 1,
109 lastPostedAt: r.last_posted_at,
110 lastSaid: r.last_said,
111 createdAt: r.created_at,
112 });
113 const toPost = (r: PostRow): ChannelPost => ({
114 id: r.id,
115 channelId: r.channel_id,
116 subject: r.subject,
117 text: r.text,
118 link: r.link,
119 state: r.state as PostState,
120 externalId: r.external_id,
121 said: r.said,
122 createdAt: r.created_at,
123 postedAt: r.posted_at,
124 });
125
126 const aad = (channelId: string): string => `channel:${channelId}`;
127
128 const printable = (s: string, max: number): boolean =>
129 s.length > 0 && s.length <= max && /^[\x21-\x7e]+$/.test(s);
130 export const isClientId = (s: string): boolean => printable(s, 200);
131 export const isClientSecret = (s: string): boolean => printable(s, 300);
132
133 /** Up to three `#tags`, space-separated; empty for none. */
134 export function parseHashtags(raw: string): string | undefined {
135 const text = raw.trim();
136 if (text === "") return "";
137 const tags = text.split(/\s+/);
138 if (tags.length > 3 || !tags.every((t) => /^#[\p{L}\p{N}_]{1,30}$/u.test(t)))
139 return undefined;
140 return tags.join(" ");
141 }
142
143 export function getChannel(db: Database, channelId: string): Channel | undefined {
144 const row = db
145 .query<Row, [string]>(`SELECT ${COLUMNS} FROM channel WHERE id = ?1`)
146 .get(channelId);
147 return row ? toChannel(row) : undefined;
148 }
149
150 export function channelOf(db: Database, repoId: string): Channel | undefined {
151 const row = db
152 .query<Row, [string]>(
153 `SELECT ${COLUMNS} FROM channel WHERE repo_id = ?1 AND kind = 'x'`,
154 )
155 .get(repoId);
156 return row ? toChannel(row) : undefined;
157 }
158
159 /** Every connected channel, for the sweep. */
160 export function connectedChannels(db: Database): Channel[] {
161 return db
162 .query<Row, []>(
163 `SELECT ${COLUMNS} FROM channel WHERE connected = 1 ORDER BY created_at, id`,
164 )
165 .all()
166 .map(toChannel);
167 }
168
169 export function openSecrets(
170 db: Database,
171 dataDir: string,
172 channelId: string,
173 ): Result<ChannelSecrets, "not_found" | "unreadable"> {
174 const row = db
175 .query<{ tokens_enc: string }, [string]>(
176 "SELECT tokens_enc FROM channel WHERE id = ?1",
177 )
178 .get(channelId);
179 if (!row) return err("not_found");
180 const opened = open(dataDir, row.tokens_enc, aad(channelId));
181 if (!opened.ok) return err("unreadable");
182 try {
183 return ok(JSON.parse(opened.value) as ChannelSecrets);
184 } catch {
185 return err("unreadable");
186 }
187 }
188
189 export function storeSecrets(
190 db: Database,
191 dataDir: string,
192 channelId: string,
193 secrets: ChannelSecrets,
194 ): void {
195 db.query("UPDATE channel SET tokens_enc = ?2 WHERE id = ?1").run(
196 channelId,
197 seal(dataDir, JSON.stringify(secrets), aad(channelId)),
198 );
199 }
200
201 export function createChannel(
202 db: Database,
203 dataDir: string,
204 input: {
205 repoId: string;
206 clientId: string;
207 clientSecret: string;
208 createdBy?: string | undefined;
209 now?: Date | undefined;
210 },
211 ): Channel {
212 const channelId = id();
213 db.query(
214 `INSERT INTO channel (id, repo_id, kind, client_id, tokens_enc, created_by, created_at)
215 VALUES (?1, ?2, 'x', ?3, ?4, ?5, ?6)`,
216 ).run(
217 channelId,
218 input.repoId,
219 input.clientId,
220 seal(
221 dataDir,
222 JSON.stringify({ clientSecret: input.clientSecret }),
223 aad(channelId),
224 ),
225 input.createdBy ?? null,
226 (input.now ?? new Date()).toISOString(),
227 );
228 return getChannel(db, channelId)!;
229 }
230
231 /** Begin an authorization: the state is findable, the verifier is sealed. */
232 export function setPending(
233 db: Database,
234 channelId: string,
235 state: string,
236 connected: boolean,
237 ): void {
238 db.query(
239 "UPDATE channel SET pending_state = ?2, connected = ?3 WHERE id = ?1",
240 ).run(channelId, state, connected ? 1 : 0);
241 }
242
243 export function pendingState(db: Database, channelId: string): string | null {
244 return (
245 db
246 .query<{ pending_state: string | null }, [string]>(
247 "SELECT pending_state FROM channel WHERE id = ?1",
248 )
249 .get(channelId)?.pending_state ?? null
250 );
251 }
252
253 /** The channel waiting on this state; the state is single use. */
254 export function channelByState(db: Database, state: string): Channel | undefined {
255 if (state === "") return undefined;
256 const row = db
257 .query<Row, [string]>(
258 `SELECT ${COLUMNS} FROM channel WHERE pending_state = ?1`,
259 )
260 .get(state);
261 return row ? toChannel(row) : undefined;
262 }
263
264 export function markConnected(
265 db: Database,
266 channelId: string,
267 now: Date,
268 said: string,
269 ): void {
270 db.query(
271 `UPDATE channel SET connected = 1, pending_state = NULL, refreshed_at = ?2, last_said = ?3 WHERE id = ?1`,
272 ).run(channelId, now.toISOString(), said.slice(0, 400));
273 }
274
275 export function markRefreshed(db: Database, channelId: string, now: Date): void {
276 db.query("UPDATE channel SET refreshed_at = ?2 WHERE id = ?1").run(
277 channelId,
278 now.toISOString(),
279 );
280 }
281
282 /** X no longer takes the connection: not connected, and why. */
283 export function markDisconnected(
284 db: Database,
285 channelId: string,
286 said: string,
287 ): void {
288 db.query("UPDATE channel SET connected = 0, last_said = ?2 WHERE id = ?1").run(
289 channelId,
290 said.slice(0, 400),
291 );
292 }
293
294 export function setSettings(
295 db: Database,
296 channelId: string,
297 s: { review?: boolean | undefined; hashtags?: string | undefined },
298 ): void {
299 if (s.review !== undefined)
300 db.query("UPDATE channel SET review_before_posting = ?2 WHERE id = ?1").run(
301 channelId,
302 s.review ? 1 : 0,
303 );
304 if (s.hashtags !== undefined)
305 db.query("UPDATE channel SET hashtags = ?2 WHERE id = ?1").run(
306 channelId,
307 s.hashtags,
308 );
309 }
310
311 export function markSeeded(db: Database, channelId: string): void {
312 db.query("UPDATE channel SET seeded = 1 WHERE id = ?1").run(channelId);
313 }
314
315 export function saySomething(db: Database, channelId: string, said: string): void {
316 db.query("UPDATE channel SET last_said = ?2 WHERE id = ?1").run(
317 channelId,
318 said.slice(0, 400),
319 );
320 }
321
322 export function removeChannel(db: Database, channelId: string): boolean {
323 return db.query("DELETE FROM channel WHERE id = ?1").run(channelId).changes > 0;
324 }
325
326 /** Record a subject once. False when it already has a row: nothing twice. */
327 export function addPost(
328 db: Database,
329 input: {
330 channelId: string;
331 subject: string;
332 text: string;
333 link: string;
334 state: "held" | "seen";
335 now: Date;
336 },
337 ): ChannelPost | undefined {
338 const postId = id();
339 const made = db
340 .query(
341 `INSERT OR IGNORE INTO channel_post (id, channel_id, subject, text, link, state, created_at)
342 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
343 )
344 .run(
345 postId,
346 input.channelId,
347 input.subject,
348 input.text,
349 input.link,
350 input.state,
351 input.now.toISOString(),
352 );
353 return made.changes === 1 ? getPost(db, postId) : undefined;
354 }
355
356 export function getPost(db: Database, postId: string): ChannelPost | undefined {
357 const row = db
358 .query<PostRow, [string]>(
359 `SELECT ${POST_COLUMNS} FROM channel_post WHERE id = ?1`,
360 )
361 .get(postId);
362 return row ? toPost(row) : undefined;
363 }
364
365 /** The log, newest first, without the subjects only seen. */
366 export function listPosts(db: Database, channelId: string, limit = 30): ChannelPost[] {
367 return db
368 .query<PostRow, [string, number]>(
369 `SELECT ${POST_COLUMNS} FROM channel_post WHERE channel_id = ?1 AND state <> 'seen'
370 ORDER BY created_at DESC, id DESC LIMIT ?2`,
371 )
372 .all(channelId, limit)
373 .map(toPost);
374 }
375
376 export function postForSubject(
377 db: Database,
378 channelId: string,
379 subject: string,
380 ): ChannelPost | undefined {
381 const row = db
382 .query<PostRow, [string, string]>(
383 `SELECT ${POST_COLUMNS} FROM channel_post WHERE channel_id = ?1 AND subject = ?2`,
384 )
385 .get(channelId, subject);
386 return row ? toPost(row) : undefined;
387 }
388
389 /** Held drafts of one channel, oldest first. */
390 export function heldPosts(db: Database, channelId: string): ChannelPost[] {
391 return db
392 .query<PostRow, [string]>(
393 `SELECT ${POST_COLUMNS} FROM channel_post WHERE channel_id = ?1 AND state IN ('held','failed')
394 ORDER BY created_at, id`,
395 )
396 .all(channelId)
397 .map(toPost);
398 }
399
400 /**
401 * Claim a draft for sending, atomically: only a held or failed one moves to
402 * `posting`. False means another send has it, or it was passed or posted.
403 */
404 export function claimPost(db: Database, postId: string): boolean {
405 return (
406 db
407 .query(
408 "UPDATE channel_post SET state = 'posting' WHERE id = ?1 AND state IN ('held','failed')",
409 )
410 .run(postId).changes === 1
411 );
412 }
413
414 export function finishPost(
415 db: Database,
416 postId: string,
417 r: {
418 state: "posted" | "failed" | "passed" | "held";
419 said: string;
420 externalId?: string | undefined;
421 now: Date;
422 },
423 ): void {
424 db.query(
425 `UPDATE channel_post SET state = ?2, said = ?3, external_id = COALESCE(?4, external_id),
426 posted_at = CASE WHEN ?2 = 'posted' THEN ?5 ELSE posted_at END WHERE id = ?1`,
427 ).run(postId, r.state, r.said.slice(0, 400), r.externalId ?? null, r.now.toISOString());
428 if (r.state === "posted")
429 db.query(
430 `UPDATE channel SET last_posted_at = ?2 WHERE id = (SELECT channel_id FROM channel_post WHERE id = ?1)`,
431 ).run(postId, r.now.toISOString());
432 }
433
434 /** Held drafts on this repositories' channels, for the feed. */
435 export function heldForRepos(
436 db: Database,
437 repoIds: readonly string[],
438 ): (ChannelPost & { repoId: string })[] {
439 if (repoIds.length === 0) return [];
440 const marks = repoIds.map(() => "?").join(",");
441 return db
442 .query<PostRow & { repo_id: string }, string[]>(
443 `SELECT p.id, p.channel_id, p.subject, p.text, p.link, p.state, p.external_id, p.said,
444 p.created_at, p.posted_at, c.repo_id
445 FROM channel_post p JOIN channel c ON c.id = p.channel_id
446 WHERE p.state = 'held' AND c.repo_id IN (${marks})
447 ORDER BY p.created_at, p.id`,
448 )
449 .all(...repoIds)
450 .map((r) => ({ ...toPost(r), repoId: r.repo_id }));
451 }
src/core/migrations/20261015230000-channels-x.ts added +39
@@ -0,0 +1,39 @@
1 // where a landed wave or milestone is said outside (#1084): one X
2 // account per repository. The client secret and the tokens are one sealed
3 // blob bound to the row; `pending_state` is the authorization in flight.
4 // `channel_post` is the log: one row per subject (`wave:0.7.1`), so
5 // nothing is drafted or posted twice.
6 export default `
7 CREATE TABLE channel (
8 id TEXT PRIMARY KEY,
9 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
10 kind TEXT NOT NULL CHECK (kind IN ('x')),
11 client_id TEXT NOT NULL,
12 tokens_enc TEXT NOT NULL,
13 pending_state TEXT,
14 connected INTEGER NOT NULL DEFAULT 0,
15 refreshed_at TEXT,
16 review_before_posting INTEGER NOT NULL DEFAULT 1,
17 hashtags TEXT NOT NULL DEFAULT '',
18 seeded INTEGER NOT NULL DEFAULT 0,
19 last_posted_at TEXT,
20 last_said TEXT NOT NULL DEFAULT '',
21 created_by TEXT REFERENCES user(id) ON DELETE SET NULL,
22 created_at TEXT NOT NULL,
23 UNIQUE (repo_id, kind)
24 );
25 CREATE UNIQUE INDEX channel_pending ON channel(pending_state) WHERE pending_state IS NOT NULL;
26 CREATE TABLE channel_post (
27 id TEXT PRIMARY KEY,
28 channel_id TEXT NOT NULL REFERENCES channel(id) ON DELETE CASCADE,
29 subject TEXT NOT NULL,
30 text TEXT NOT NULL,
31 link TEXT NOT NULL,
32 state TEXT NOT NULL CHECK (state IN ('held','posting','posted','passed','failed','seen')),
33 external_id TEXT,
34 said TEXT NOT NULL DEFAULT '',
35 created_at TEXT NOT NULL,
36 posted_at TEXT,
37 UNIQUE (channel_id, subject)
38 );
39 `;
src/crew/channels.ts added +291
@@ -0,0 +1,291 @@
1 /**
2 * The channel routine (#1084): when a wave or a watched milestone has
3 * landed on a repository that connected X, it is drafted once — from the
4 * wave's note, never from pulls — and either held for the owner to read
5 * ("Post" / "Not this one" in the feed) or posted at once. Every minute the
6 * connected channels are looked at; a subject already in the log is never
7 * drafted again, so nothing is posted twice. A public repository only:
8 * nothing about a private one is drafted, held or posted, checked again at
9 * the moment of sending. A failure is a sentence on the page, never a throw.
10 */
11
12 import type { App } from "../app.ts";
13 import { readWaves } from "../actions/cut_wave.ts";
14 import {
15 addPost,
16 claimPost,
17 connectedChannels,
18 finishPost,
19 getChannel,
20 markDisconnected,
21 markRefreshed,
22 markSeeded,
23 openSecrets,
24 postForSubject,
25 saySomething,
26 storeSecrets,
27 type Channel,
28 type ChannelPost,
29 } from "../core/channels.ts";
30 import { readPlan } from "../core/milestones.ts";
31 import { getRepoById, type Repo } from "../core/repos.ts";
32 import { createLog } from "../kernel/log.ts";
33 import { postForMilestone, postForWave } from "../story/post.ts";
34 import { parseWave } from "../story/wave.ts";
35 import { XError, type XClient } from "./x.ts";
36
37 const log = createLog("channels");
38 const TICK_MS = 60_000;
39 const STOP_DEADLINE_MS = 15_000;
40 /** A token this close to its end is refreshed first. */
41 const REFRESH_MARGIN_MS = 120_000;
42
43 export const CONNECT_AGAIN =
44 "X no longer accepts this connection. Connect again.";
45
46 export interface ChannelRoutineOptions {
47 readonly client: XClient;
48 readonly now?: (() => Date) | undefined;
49 /** @default a minute */
50 readonly everyMs?: number | undefined;
51 }
52
53 export interface ChannelRoutineHandle {
54 readonly client: XClient;
55 readonly now: () => Date;
56 /** Look at every connected channel once. */
57 readonly sweep: () => Promise<void>;
58 /** Draft for one channel now (after connecting). */
59 readonly sweepOne: (channelId: string) => Promise<void>;
60 readonly stop: () => Promise<void>;
61 }
62
63 const handles = new WeakMap<App, ChannelRoutineHandle>();
64 export const channelsFor = (app: App): ChannelRoutineHandle | undefined =>
65 handles.get(app);
66
67 export function startChannelRoutine(
68 app: App,
69 options: ChannelRoutineOptions,
70 ): ChannelRoutineHandle {
71 const now = options.now ?? (() => new Date());
72 let stopped = false;
73 let line: Promise<unknown> = Promise.resolve();
74 const enqueue = <T>(work: () => Promise<T>): Promise<T> => {
75 const next = line.then(work);
76 line = next.catch(() => undefined);
77 return next;
78 };
79 const one = async (channelId: string): Promise<void> => {
80 const channel = getChannel(app.db, channelId);
81 if (channel?.connected) await sweepChannel(app, options.client, channel, now());
82 };
83 const sweep = (): Promise<void> =>
84 enqueue(async () => {
85 for (const c of connectedChannels(app.db)) {
86 if (stopped) return;
87 await one(c.id).catch((error) =>
88 log.error("channel sweep failed", { error: String(error) }),
89 );
90 }
91 });
92 const timer = setInterval(() => {
93 if (!stopped) void sweep();
94 }, options.everyMs ?? TICK_MS);
95 const handle: ChannelRoutineHandle = {
96 client: options.client,
97 now,
98 sweep,
99 sweepOne: (channelId) => enqueue(() => one(channelId)),
100 stop: async () => {
101 stopped = true;
102 clearInterval(timer);
103 await Promise.race([line, Bun.sleep(STOP_DEADLINE_MS)]);
104 if (handles.get(app) === handle) handles.delete(app);
105 },
106 };
107 handles.set(app, handle);
108 return handle;
109 }
110
111 const repoUrl = (app: App, repo: Repo): string =>
112 `${(app.config.url ?? `http://localhost:${app.config.port}`).replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}`;
113
114 interface Draft {
115 readonly subject: string;
116 readonly text: string;
117 readonly link: string;
118 }
119
120 /** Everything that has landed and could be said, as drafts. */
121 export async function landedDrafts(
122 app: App,
123 repo: Repo,
124 hashtags: string,
125 ): Promise<Draft[]> {
126 const out: Draft[] = [];
127 const base = repoUrl(app, repo);
128 for (const file of await readWaves(app, repo)) {
129 const wave = parseWave(file.path, file.text);
130 if (!wave.ok) continue;
131 const link = `${base}/blob/${encodeURIComponent(repo.defaultBranch)}/${file.path}`;
132 const text = postForWave(wave.value, link, hashtags);
133 if (text !== undefined)
134 out.push({ subject: `wave:${wave.value.version}`, text, link });
135 }
136 const watched = app.db
137 .query<{ number: number }, [string]>(
138 `SELECT DISTINCT i.number FROM milestone_watch w JOIN issue i ON i.id = w.issue_id
139 WHERE i.repo_id = ?1 ORDER BY i.number`,
140 )
141 .all(repo.id);
142 if (watched.length > 0) {
143 const plan = readPlan(app.db, repo, { spend: false });
144 for (const { number } of watched) {
145 const m = plan.milestone(number);
146 if (m === undefined) continue;
147 const { issue, weight } = m;
148 const landed =
149 issue.state === "closed"
150 ? issue.closeReason !== "dropped" && issue.closeReason !== "split"
151 : weight.total > 0 && weight.open === 0;
152 if (!landed) continue;
153 const link = `${base}/milestones/${number}`;
154 const text = postForMilestone({ name: m.name, body: issue.body }, link, hashtags);
155 if (text !== undefined)
156 out.push({ subject: `milestone:${issue.id}`, text, link });
157 }
158 }
159 return out;
160 }
161
162 /**
163 * One channel: on the first look everything already landed is marked seen,
164 * so connecting does not post history; after that each new subject is held
165 * or posted.
166 */
167 export async function sweepChannel(
168 app: App,
169 client: XClient,
170 channel: Channel,
171 at: Date,
172 ): Promise<void> {
173 const repo = getRepoById(app.db, channel.repoId);
174 if (repo === undefined || repo.visibility !== "public") return;
175 const drafts = await landedDrafts(app, repo, channel.hashtags);
176 if (!channel.seeded) {
177 for (const d of drafts)
178 addPost(app.db, { channelId: channel.id, ...d, state: "seen", now: at });
179 markSeeded(app.db, channel.id);
180 return;
181 }
182 for (const d of drafts) {
183 if (postForSubject(app.db, channel.id, d.subject) !== undefined) continue;
184 const post = addPost(app.db, {
185 channelId: channel.id,
186 ...d,
187 state: "held",
188 now: at,
189 });
190 if (post === undefined) continue;
191 app.bus.append({
192 kind: "channel.drafted",
193 repoId: repo.id,
194 payload: { channel: channel.id, subject: d.subject },
195 });
196 if (!channel.reviewBeforePosting) await sendPost(app, client, channel, post, at);
197 }
198 }
199
200 /** A valid access token, refreshed first when it is about to end. */
201 async function accessFor(
202 app: App,
203 client: XClient,
204 channel: Channel,
205 at: Date,
206 ): Promise<string> {
207 const opened = openSecrets(app.db, app.config.dataDir, channel.id);
208 if (!opened.ok) throw new XError("rejected", CONNECT_AGAIN);
209 const s = opened.value;
210 if (
211 s.access !== undefined &&
212 s.expiresAt !== undefined &&
213 Date.parse(s.expiresAt) - at.getTime() > REFRESH_MARGIN_MS
214 )
215 return s.access;
216 if (s.refresh === undefined) throw new XError("rejected", CONNECT_AGAIN);
217 const fresh = await client.refresh({
218 clientId: channel.clientId,
219 clientSecret: s.clientSecret,
220 refresh: s.refresh,
221 });
222 storeSecrets(app.db, app.config.dataDir, channel.id, {
223 clientSecret: s.clientSecret,
224 access: fresh.access,
225 ...(fresh.refresh === undefined
226 ? s.refresh === undefined
227 ? {}
228 : { refresh: s.refresh }
229 : { refresh: fresh.refresh }),
230 expiresAt: new Date(at.getTime() + fresh.expiresInS * 1000).toISOString(),
231 });
232 markRefreshed(app.db, channel.id, at);
233 return fresh.access;
234 }
235
236 /**
237 * Send a held (or failed) draft. Claimed first, so two sends cannot both
238 * reach X. The sentence is what the page shows; nothing here throws.
239 */
240 export async function sendPost(
241 app: App,
242 client: XClient,
243 channel: Channel,
244 post: ChannelPost,
245 at: Date,
246 ): Promise<{ ok: boolean; said: string }> {
247 const repo = getRepoById(app.db, channel.repoId);
248 if (repo === undefined || repo.visibility !== "public") {
249 finishPost(app.db, post.id, {
250 state: "passed",
251 said: "A private repository is never posted.",
252 now: at,
253 });
254 return { ok: false, said: "A private repository is never posted." };
255 }
256 if (!channel.connected) return { ok: false, said: CONNECT_AGAIN };
257 if (!claimPost(app.db, post.id))
258 return { ok: false, said: "That post is not waiting to be sent." };
259 try {
260 const access = await accessFor(app, client, channel, at);
261 const sent = await client.post({ access, text: post.text });
262 const said = `Posted to X (${sent.id}).`;
263 finishPost(app.db, post.id, {
264 state: "posted",
265 said,
266 externalId: sent.id,
267 now: at,
268 });
269 saySomething(app.db, channel.id, said);
270 app.bus.append({
271 kind: "channel.posted",
272 repoId: repo.id,
273 payload: { channel: channel.id, subject: post.subject, id: sent.id },
274 });
275 return { ok: true, said };
276 } catch (error) {
277 const rejected = error instanceof XError && error.kind === "rejected";
278 const said =
279 error instanceof XError
280 ? rejected
281 ? CONNECT_AGAIN
282 : error.message
283 : "The post could not be sent.";
284 if (!(error instanceof XError))
285 log.error("post failed", { error: String(error) });
286 finishPost(app.db, post.id, { state: "failed", said, now: at });
287 if (rejected) markDisconnected(app.db, channel.id, said);
288 else saySomething(app.db, channel.id, said);
289 return { ok: false, said };
290 }
291 }
src/crew/x.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * X, the one place the forge talks to it (#1084): OAuth 2.0 with PKCE for a
3 * user context, a refresh, and `POST /2/tweets`. Each call returns plain
4 * data or throws an `XError` the caller turns into a sentence; `fetch` is
5 * injectable so tests never touch the network.
6 */
7
8 import { createHash, randomBytes } from "node:crypto";
9
10 export const X_SCOPES = "tweet.read tweet.write users.read offline.access";
11 const AUTHORIZE = "https://x.com/i/oauth2/authorize";
12 const TOKEN = "https://api.x.com/2/oauth2/token";
13 const TWEETS = "https://api.x.com/2/tweets";
14
15 export interface XTokens {
16 readonly access: string;
17 readonly refresh: string | undefined;
18 readonly expiresInS: number;
19 }
20
21 export interface XClient {
22 exchange(o: {
23 clientId: string;
24 clientSecret: string;
25 code: string;
26 verifier: string;
27 redirectUri: string;
28 }): Promise<XTokens>;
29 refresh(o: {
30 clientId: string;
31 clientSecret: string;
32 refresh: string;
33 }): Promise<XTokens>;
34 post(o: { access: string; text: string }): Promise<{ id: string }>;
35 }
36
37 /** `rejected`: X no longer accepts the credentials. `failed`: anything else. */
38 export class XError extends Error {
39 constructor(
40 readonly kind: "rejected" | "failed",
41 message: string,
42 ) {
43 super(message);
44 }
45 }
46
47 const b64url = (b: Buffer): string => b.toString("base64url");
48
49 export const newVerifier = (): string => b64url(randomBytes(48));
50 export const newState = (): string => b64url(randomBytes(24));
51 export const challengeOf = (verifier: string): string =>
52 b64url(createHash("sha256").update(verifier).digest());
53
54 export function authorizeUrl(o: {
55 clientId: string;
56 redirectUri: string;
57 state: string;
58 verifier: string;
59 }): string {
60 const q = new URLSearchParams({
61 response_type: "code",
62 client_id: o.clientId,
63 redirect_uri: o.redirectUri,
64 scope: X_SCOPES,
65 state: o.state,
66 code_challenge: challengeOf(o.verifier),
67 code_challenge_method: "S256",
68 });
69 return `${AUTHORIZE}?${q}`;
70 }
71
72 type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
73
74 export function httpX(fetcher: Fetch = fetch): XClient {
75 const call = async (url: string, init: RequestInit): Promise<Response> => {
76 try {
77 return await fetcher(url, { ...init, signal: AbortSignal.timeout(15_000) });
78 } catch {
79 throw new XError("failed", "X could not be reached.");
80 }
81 };
82 const tokens = async (
83 clientId: string,
84 clientSecret: string,
85 form: Record<string, string>,
86 ): Promise<XTokens> => {
87 const res = await call(TOKEN, {
88 method: "POST",
89 headers: {
90 "content-type": "application/x-www-form-urlencoded",
91 authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
92 },
93 body: new URLSearchParams({ ...form, client_id: clientId }).toString(),
94 });
95 const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
96 if (!res.ok || typeof data["access_token"] !== "string") {
97 const rejected =
98 res.status === 400 || res.status === 401 || res.status === 403;
99 throw new XError(
100 rejected ? "rejected" : "failed",
101 rejected
102 ? "X did not accept the credentials."
103 : `X answered ${res.status}.`,
104 );
105 }
106 return {
107 access: data["access_token"],
108 refresh:
109 typeof data["refresh_token"] === "string"
110 ? data["refresh_token"]
111 : undefined,
112 expiresInS:
113 typeof data["expires_in"] === "number" ? data["expires_in"] : 7200,
114 };
115 };
116 return {
117 exchange: (o) =>
118 tokens(o.clientId, o.clientSecret, {
119 grant_type: "authorization_code",
120 code: o.code,
121 redirect_uri: o.redirectUri,
122 code_verifier: o.verifier,
123 }),
124 refresh: (o) =>
125 tokens(o.clientId, o.clientSecret, {
126 grant_type: "refresh_token",
127 refresh_token: o.refresh,
128 }),
129 async post(o) {
130 const res = await call(TWEETS, {
131 method: "POST",
132 headers: {
133 "content-type": "application/json",
134 authorization: `Bearer ${o.access}`,
135 },
136 body: JSON.stringify({ text: o.text }),
137 });
138 const data = (await res.json().catch(() => ({}))) as {
139 data?: { id?: unknown };
140 detail?: unknown;
141 };
142 if (res.status === 401)
143 throw new XError("rejected", "X no longer accepts the token.");
144 const id = data.data?.id;
145 if (!res.ok || typeof id !== "string")
146 throw new XError(
147 "failed",
148 res.status === 429
149 ? "X says to slow down; try again later."
150 : `X refused the post (${res.status}).`,
151 );
152 return { id };
153 },
154 };
155 }
src/design/activity.ts +6
@@ -134,4 +134,10 @@ const WORDS: Record<string, string> = {
134134 "app.deleted": "stopped serving it as an app",
135135 "prompt.source_added": "connected an Instagram account to prompt the crew",
136136 "prompt.source_removed": "disconnected the Instagram account",
137 "channel.added": "added an X account to say what lands",
138 "channel.updated": "changed how the X account is used",
139 "channel.connected": "connected an X account",
140 "channel.removed": "disconnected the X account",
141 "channel.drafted": "drafted a post for X",
142 "channel.posted": "posted to X",
137143 };
src/feed/items.ts +41
@@ -7,6 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { heldForRepos } from "../core/channels.ts";
1011 import { listDecidedIn } from "../core/decisions.ts";
1112 import { audienceFilter } from "../core/event_audience.ts";
1213 import { listEventsVisibleTo, type ForgeEvent } from "../core/events.ts";
@@ -18,6 +19,7 @@ import {
1819 } from "../core/origins.ts";
1920 import { getPull, toldBy } from "../core/pulls.ts";
2021 import {
22 canAdmin,
2123 canSeeOwnerFacts,
2224 getReposByIds,
2325 listReposWritableTo,
@@ -127,6 +129,44 @@ function watchedCandidates(db: Database, viewer: User, now: number): Candidate[]
127129 return out;
128130 }
129131
132 /**
133 * A post drafted for X that waits for its owner (#1084): the text as it
134 * would go, and Post / Not this one. Only an admin of the repository is
135 * asked; the buttons are on Settings → Channels, where it is sent.
136 */
137 function heldPostCandidates(
138 db: Database,
139 viewer: User,
140 writable: readonly Repo[],
141 ): Candidate[] {
142 const admin = writable.filter((r) => canAdmin(db, r, viewer));
143 const byId = new Map(admin.map((r) => [r.id, r]));
144 const out: Candidate[] = [];
145 for (const p of heldForRepos(db, [...byId.keys()])) {
146 const repo = byId.get(p.repoId)!;
147 out.push({
148 id: `post:${p.id}`,
149 kind: "ask",
150 repoId: repo.id,
151 app: slug(repo),
152 actorId: null,
153 actor: null,
154 at: p.createdAt,
155 link: `${base(repo)}/settings/channels`,
156 what: `a post for X waits for you: ${clip(p.text, 200)}`,
157 urgency: ASK_URGENCY_FLOOR,
158 ask: {
159 decision: `Post this to X? ${clip(p.text, 240)}`,
160 options: ["Post", "Not this one"],
161 ifNothing: "It stays held; nothing is posted.",
162 rank: 0,
163 why: "You asked to read each post before it goes.",
164 },
165 });
166 }
167 return out;
168 }
169
130170 /**
131171 * What froze on the viewer, as decisions only they can make (#1090): an
132172 * origin of theirs whose credential died, with the mirrors that stopped
@@ -260,6 +300,7 @@ export function candidatesFor(
260300 out.push(...watchedCandidates(db, viewer, now));
261301 out.push(...frozenCandidates(db, viewer, now));
262302 out.push(...chooseCandidates(db, writable));
303 out.push(...heldPostCandidates(db, viewer, writable));
263304 for (const d of decided) {
264305 const repo = repos.get(d.repoId);
265306 if (!repo) continue;
src/http/api.ts +79
@@ -242,6 +242,12 @@ import {
242242 removePromptSource,
243243 runPromptSource,
244244 } from "../actions/prompts.ts";
245 import {
246 connectChannel,
247 decidePost,
248 listChannels,
249 removeChannel,
250 } from "../actions/channels.ts";
245251 import { listDomains } from "../core/domains.ts";
246252 import type { Database } from "bun:sqlite";
247253 import {
@@ -4561,6 +4567,79 @@ export function apiRoutes(router: Router<Handler>): void {
45614567 return json({}, 200);
45624568 });
45634569
4570 // Where a landed wave is said outside (#1084): one X account per
4571 // repository. Admin scope and admin over the repository; the client
4572 // secret goes in once and never comes back out.
4573 router.add("GET", "/api/v1/repos/:owner/:name/channels", (ctx) => {
4574 const denied = requireScope(ctx, "admin");
4575 if (denied) return denied;
4576 const repo = loadRepo(ctx);
4577 if (!repo) return notFound();
4578 const listed = listChannels(ctx.app, ctx.auth.user, repo);
4579 if (!listed.ok) return respondAccess(listed.error, 422);
4580 return json({ items: listed.value, next_cursor: null });
4581 });
4582
4583 router.add("POST", "/api/v1/repos/:owner/:name/channels", async (ctx) => {
4584 const denied = requireScope(ctx, "admin");
4585 if (denied) return denied;
4586 const repo = loadRepo(ctx);
4587 if (!repo) return notFound();
4588 const input = await body(ctx.request);
4589 const done = connectChannel(ctx.app, ctx.auth.user, repo, {
4590 kind: str(input.kind) || "x",
4591 clientId: str(input.clientId),
4592 clientSecret: str(input.clientSecret),
4593 review:
4594 typeof input.reviewBeforePosting === "boolean"
4595 ? input.reviewBeforePosting
4596 : undefined,
4597 hashtags:
4598 typeof input.hashtags === "string" ? input.hashtags : undefined,
4599 });
4600 if (!done.ok) return respondAccess(done.error, 422);
4601 return json(done.value.channel, done.value.created ? 201 : 200);
4602 });
4603
4604 router.add(
4605 "POST",
4606 "/api/v1/repos/:owner/:name/channels/:id/post",
4607 async (ctx) => {
4608 const denied = requireScope(ctx, "admin");
4609 if (denied) return denied;
4610 const repo = loadRepo(ctx);
4611 if (!repo) return notFound();
4612 const input = await body(ctx.request);
4613 const done = await decidePost(
4614 ctx.app,
4615 ctx.auth.user,
4616 repo,
4617 ctx.params.id ?? "",
4618 {
4619 ...(typeof input.post === "string" ? { post: input.post } : {}),
4620 decision: input.decision === "pass" ? "pass" : "post",
4621 },
4622 );
4623 if (!done.ok) return respondAccess(done.error, 422);
4624 return json(done.value, done.value.ok ? 200 : 502);
4625 },
4626 );
4627
4628 router.add("DELETE", "/api/v1/repos/:owner/:name/channels/:id", (ctx) => {
4629 const denied = requireScope(ctx, "admin");
4630 if (denied) return denied;
4631 const repo = loadRepo(ctx);
4632 if (!repo) return notFound();
4633 const removed = removeChannel(
4634 ctx.app,
4635 ctx.auth.user,
4636 repo,
4637 ctx.params.id ?? "",
4638 );
4639 if (!removed.ok) return respondAccess(removed.error, 422);
4640 return json({}, 200);
4641 });
4642
45644643 // Forge-level secrets: a sealed, write-only slot for the operator's own
45654644 // credentials. Admins only; the list is names and timestamps, never a
45664645 // value. `ref` names the owner: an org's name, or a repository's
src/http/mcp.ts +20
@@ -17,6 +17,7 @@
1717 * no page. `ro` tokens read; `rw` tokens act.
1818 */
1919
20 import { listChannels } from "../actions/channels.ts";
2021 import { voteVariant } from "../actions/variants.ts";
2122 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2223 import { listAccess } from "../actions/access_log.ts";
@@ -1417,6 +1418,25 @@ const TOOLS: readonly Tool[] = [
14171418 });
14181419 },
14191420 },
1421 {
1422 name: "posts",
1423 description:
1424 "What an app has said on X, for an admin: whether the X account is connected, whether drafts wait for review, and the log — each post's text, its state (held, posted, passed, failed), when, the link to the wave and X's id. Reading only; sending a held draft is POST /api/v1/repos/:o/:n/channels/:id/post.",
1425 inputSchema: {
1426 type: "object",
1427 properties: { app: APP_ARG },
1428 required: ["app"],
1429 },
1430 writes: false,
1431 async run(ctx, user, args) {
1432 const repo = planRepo(ctx, user, args);
1433 if (isAnswer(repo)) return repo;
1434 const listed = listChannels(ctx.app, user, repo);
1435 return listed.ok
1436 ? good({ channels: listed.value })
1437 : bad("not_found", "no such app, or you do not administer it");
1438 },
1439 },
14201440 {
14211441 name: "map",
14221442 description:
src/http/server.ts +21
@@ -322,6 +322,12 @@ import {
322322 promptSourceDelete,
323323 promptSourceRun,
324324 promptsSettingsPage,
325 channelsSettingsPage,
326 channelConnect,
327 channelUpdate,
328 channelDecide,
329 channelDelete,
330 channelCallback,
325331 repoDelete,
326332 settingsPage,
327333 settingsUpdate,
@@ -1169,6 +1175,21 @@ export function buildRouter(): Router<Handler> {
11691175 "/:owner/:name/settings/prompts/:id/delete",
11701176 promptSourceDelete,
11711177 );
1178 router.add("GET", "/:owner/:name/settings/channels", channelsSettingsPage);
1179 router.add("POST", "/:owner/:name/settings/channels", channelConnect);
1180 router.add("POST", "/:owner/:name/settings/channels/:id", channelUpdate);
1181 router.add(
1182 "POST",
1183 "/:owner/:name/settings/channels/:id/posts/:post/post",
1184 channelDecide("post"),
1185 );
1186 router.add(
1187 "POST",
1188 "/:owner/:name/settings/channels/:id/posts/:post/pass",
1189 channelDecide("pass"),
1190 );
1191 router.add("POST", "/:owner/:name/settings/channels/:id/delete", channelDelete);
1192 router.add("GET", "/oauth/x/callback", channelCallback);
11721193 router.add("GET", "/:owner/:name/settings/crew", crewSettingsPage);
11731194 router.add("POST", "/:owner/:name/settings/crew", crewAdd);
11741195 router.add(
src/main.ts +7
@@ -42,7 +42,9 @@ import { peopleOnCrews } from "./core/agents.ts";
4242 import { startNotifier } from "./crew/notify.ts";
4343 import { sweepStaleAsks } from "./crew/stale_asks.ts";
4444 import { recordAskLedger } from "./web/studio/asks.ts";
45 import { startChannelRoutine } from "./crew/channels.ts";
4546 import { startPromptRoutine } from "./crew/prompts.ts";
47 import { httpX } from "./crew/x.ts";
4648 import { pruneTokens } from "./core/tokens.ts";
4749 import { configProblem, dataDirOf, preflight } from "./kernel/preflight.ts";
4850 import { running } from "./kernel/version.ts";
@@ -361,6 +363,10 @@ const heartbeatTimer = startHeartbeat(app);
361363 // that connected an account, the top comment on its latest Reel is told to
362364 // the crew. A minute's clock; nothing leaves the box until a source exists.
363365 const prompts = startPromptRoutine(app, { client: graphInstagram() });
366 // A landed wave or watched milestone is drafted for X, and posted or held
367 // for its owner (#1084). A minute's clock; nothing leaves until a channel is
368 // connected.
369 const channels = startChannelRoutine(app, { client: httpX() });
364370 // What newly asks a person reaches the phone they chose (docs/APPS.md).
365371 const notifier = startNotifier(app, { forgeUrl });
366372
@@ -512,6 +518,7 @@ function shutdown(signal: NodeJS.Signals): void {
512518 Promise.all([
513519 linger,
514520 prompts.stop(),
521 channels.stop(),
515522 notifier.stop(),
516523 crew?.stop({ drain: true }),
517524 apps?.stop(),
src/story/post.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * The words of a distilled post: what changed and why it matters, in a
3 * person's terms, one link, under 240 characters (#1084). Drafted from a
4 * wave's note — its headline and the first highlight's why — never from
5 * pulls. Pure: plain data in, a string out, nothing posted here.
6 */
7
8 import type { Wave } from "./wave.ts";
9
10 export const POST_MAX = 240;
11
12 /** A line of the owner's markdown as plain words. */
13 const plain = (s: string): string =>
14 s
15 .replace(/`([^`]*)`/g, "$1")
16 .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
17 .replace(/[*_#>]+/g, "")
18 .replace(/\s+/g, " ")
19 .trim();
20
21 /** The first sentence of a line, with its full stop. */
22 export function firstSentence(s: string): string {
23 const text = plain(s);
24 const m = /^(.+?[.!?])(?:\s|$)/.exec(text);
25 return m ? m[1]! : text;
26 }
27
28 const stop = (s: string): string => (/[.!?…]$/.test(s) ? s : `${s}.`);
29
30 const clip = (s: string, n: number): string =>
31 s.length <= n ? s : `${s.slice(0, Math.max(0, n - 1)).trimEnd()}…`;
32
33 /** A placeholder the cut left for the owner is not a thing to say. */
34 const unwritten = (s: string): boolean => /\bTODO\b/i.test(s) || plain(s) === "";
35
36 /**
37 * `<headline> <why> <link> <hashtags>`, the body clipped so the whole is
38 * never over the limit. The link and the hashtags are never clipped.
39 */
40 export function composePost(o: {
41 headline: string;
42 why: string;
43 link: string;
44 hashtags?: string;
45 }): string {
46 const tail = [o.link, o.hashtags ?? ""].filter((p) => p !== "").join(" ");
47 const room = POST_MAX - tail.length - 1;
48 const head = stop(plain(o.headline));
49 const why = plain(o.why) === "" ? "" : stop(firstSentence(o.why));
50 const body = clip(why === "" ? head : `${head} ${why}`, room);
51 return `${body} ${tail}`;
52 }
53
54 /** The post for a wave, or nothing while its note is still a draft. */
55 export function postForWave(
56 wave: Wave,
57 link: string,
58 hashtags = "",
59 ): string | undefined {
60 const why = wave.highlights[0]?.why ?? "";
61 if (unwritten(wave.headline) || unwritten(why)) return undefined;
62 return composePost({ headline: wave.headline, why, link, hashtags });
63 }
64
65 /** The post for a milestone that landed, from its name and the issue's first words. */
66 export function postForMilestone(
67 m: { name: string; body: string },
68 link: string,
69 hashtags = "",
70 ): string | undefined {
71 if (unwritten(m.name)) return undefined;
72 return composePost({
73 headline: `Done: ${plain(m.name)}`,
74 why: m.body.split(/\n\s*\n/)[0] ?? "",
75 link,
76 hashtags,
77 });
78 }
src/web/pages/search.ts +18
@@ -489,6 +489,24 @@ const DESTRUCTIVE: {
489489 phrase: "",
490490 }),
491491 },
492 {
493 pattern: /^\/([^/]+)\/([^/]+)\/settings\/channels\/([^/]+)\/delete$/,
494 describe: (m) => ({
495 verb: "Disconnect",
496 title: "Disconnect X?",
497 detail: `Nothing more is posted for ${m[1]}/${m[2]}, and the tokens and the log are forgotten. What was already posted stays on X.`,
498 phrase: "",
499 }),
500 },
501 {
502 pattern: /^\/([^/]+)\/([^/]+)\/settings\/channels\/([^/]+)\/delete$/,
503 describe: (m) => ({
504 verb: "Disconnect",
505 title: "Disconnect X?",
506 detail: `Nothing more is posted for ${m[1]}/${m[2]}, and the tokens and the log are forgotten. What was already posted stays on X.`,
507 phrase: "",
508 }),
509 },
492510 {
493511 pattern: /^\/([^/]+)\/([^/]+)\/settings\/labels\/([^/]+)\/delete$/,
494512 describe: (m) => ({
src/web/pages/settings.ts +303
@@ -101,6 +101,16 @@ import {
101101 timeAgo,
102102 } from "../ui.ts";
103103 import { cutWaveFor } from "../../actions/cut_wave.ts";
104 import {
105 connectChannel,
106 decidePost,
107 finishConnect,
108 listChannels,
109 redirectUriFor,
110 removeChannel,
111 updateChannel,
112 type ChannelView,
113 } from "../../actions/channels.ts";
104114 import { secretsSection } from "./secrets.ts";
105115 import { saveGrants } from "./subscriptions.ts";
106116
@@ -108,6 +118,7 @@ type Section =
108118 | "general"
109119 | "app"
110120 | "prompts"
121 | "channels"
111122 | "labels"
112123 | "hooks"
113124 | "danger";
@@ -140,6 +151,12 @@ function sections(base: string, active: Section) {
140151 icon: "comment" as const,
141152 current: active === "prompts",
142153 },
154 {
155 label: "Channels",
156 href: `${base}/settings/channels`,
157 icon: "comment" as const,
158 current: active === "channels",
159 },
143160 {
144161 label: "Labels",
145162 href: `${base}/settings/labels`,
@@ -1286,6 +1303,292 @@ export async function promptSourceDelete(ctx: Ctx): Promise<Response> {
12861303 );
12871304 }
12881305
1306 // ---- channels ----
1307
1308 const CHANNEL_ERRORS: Record<string, string> = {
1309 invalid_client_id: "Paste the client id as X shows it: one line, no spaces.",
1310 invalid_client_secret:
1311 "Paste the client secret as X shows it: one line, no spaces.",
1312 invalid_hashtags: "Hashtags are up to three words that start with #.",
1313 no_credentials: "Paste the client id and the client secret from X.",
1314 no_such_channel: "No channel by that id.",
1315 no_such_post: "That post is not waiting.",
1316 not_connected: "X is not connected. Connect it again.",
1317 not_running: "The channel routine is not running on this forge.",
1318 };
1319
1320 /** The X card: the form when none is connected, the channel and its log otherwise. */
1321 function channelsView(
1322 base: string,
1323 channel: ChannelView | undefined,
1324 redirectUri: string,
1325 ): Html {
1326 const at = (id: string) => `${base}/settings/channels/${encodeURIComponent(id)}`;
1327 const credentials = (verb: string) => html`<form
1328 class="card-body"
1329 method="post"
1330 action="${base}/settings/channels"
1331 >
1332 ${formField({
1333 label: "Client id",
1334 name: "clientId",
1335 value: channel?.clientId ?? "",
1336 required: true,
1337 autocomplete: "off",
1338 mono: true,
1339 })}
1340 ${formField({
1341 label: "Client secret",
1342 name: "clientSecret",
1343 type: "password",
1344 hint: "The forge seals it, and never shows it again.",
1345 required: true,
1346 autocomplete: "off",
1347 mono: true,
1348 })}
1349 <div class="form-actions">
1350 ${btn(verb, { variant: "primary", icon: "plus" })}
1351 </div>
1352 </form>`;
1353 const settings = (c: ChannelView) => html`<form
1354 class="card-body"
1355 method="post"
1356 action="${at(c.id)}"
1357 >
1358 <div class="field">
1359 <label class="check">
1360 <input
1361 type="checkbox"
1362 name="review"
1363 ${c.reviewBeforePosting ? html`checked` : null}
1364 />
1365 <span
1366 ><b>Review before posting</b> — a draft waits in your feed for you to
1367 read and send. Off, it posts the moment a wave lands.</span
1368 >
1369 </label>
1370 </div>
1371 ${formField({
1372 label: "Hashtags",
1373 name: "hashtags",
1374 value: c.hashtags,
1375 hint: "Up to three, like #buildinpublic. Empty means none.",
1376 })}
1377 <div class="form-actions">${btn("Save", { size: "sm" })}</div>
1378 </form>`;
1379 const logRow = (c: ChannelView, p: ChannelView["posts"][number]) => html`<li>
1380 <div class="row">
1381 <span class="row-main">
1382 <span class="row-title">${p.text}</span>
1383 <span class="row-meta"
1384 >${badge(p.state)} ${time(p.postedAt ?? p.at)}
1385 ${p.said === "" ? null : html`· ${p.said}`}
1386 ${p.xId === null
1387 ? null
1388 : html`· <span class="mono">${p.xId}</span>`}
1389 · <a href="${p.link}">the wave</a></span
1390 >
1391 </span>
1392 ${p.state === "held" || p.state === "failed"
1393 ? html`<span class="row-trail">
1394 <form method="post" action="${at(c.id)}/posts/${encodeURIComponent(p.id)}/post">
1395 ${btn("Post", { size: "sm", variant: "primary" })}
1396 </form>
1397 <form method="post" action="${at(c.id)}/posts/${encodeURIComponent(p.id)}/pass">
1398 ${btn("Not this one", { size: "sm" })}
1399 </form>
1400 </span>`
1401 : null}
1402 </div>
1403 </li>`;
1404 const body =
1405 channel === undefined
1406 ? html`<div class="card-body">
1407 <p class="muted small">
1408 When a wave lands, or a milestone you watch, the forge writes one
1409 short post and puts it on X. Public repositories only.
1410 </p>
1411 </div>
1412 ${credentials("Connect")}`
1413 : html`<div class="card-body">
1414 <p>
1415 ${channel.connected
1416 ? html`${badge("connected")} Refreshed
1417 ${timeAgo(channel.refreshedAt ?? "")}.`
1418 : html`${badge("not connected")}
1419 ${channel.authorizeUrl === null
1420 ? html`Enter the client id and secret below to connect.`
1421 : html`<a class="btn primary" href="${channel.authorizeUrl}"
1422 >Authorize at X</a
1423 >`}`}
1424 ${channel.lastSaid === "" ? null : html`<br />${channel.lastSaid}`}
1425 </p>
1426 </div>
1427 ${settings(channel)}
1428 ${channel.connected ? null : credentials("Connect again")}
1429 <div class="card-body">
1430 ${confirmAction({
1431 action: `${at(channel.id)}/delete`,
1432 verb: "Disconnect",
1433 size: "sm",
1434 })}
1435 </div>`;
1436 return html`${card(body, {
1437 head: html`${icon("comment")}
1438 <h2>X</h2>`,
1439 pad: false,
1440 })}
1441 ${channel === undefined || channel.posts.length === 0
1442 ? null
1443 : card(
1444 html`<ul class="list">
1445 ${channel.posts.map((p) => logRow(channel, p))}
1446 </ul>`,
1447 { head: html`<h2>Posts</h2>`, pad: false },
1448 )}
1449 ${card(
1450 html`<p class="muted small">
1451 The one-time steps at X, because the forge cannot take them for anyone.
1452 </p>
1453 <ol class="steps">
1454 <li>At developers.x.com, make a project and an app.</li>
1455 <li>
1456 Turn on OAuth 2.0 with user authentication, type
1457 <b>Web App</b> (a confidential client), with read and write
1458 permissions.
1459 </li>
1460 <li>
1461 Set the callback URL to
1462 <span class="mono">${redirectUri}</span>
1463 exactly.
1464 </li>
1465 <li>Paste the client id and the client secret above.</li>
1466 <li>
1467 Press <b>Authorize at X</b>. The forge asks for
1468 <span class="mono">tweet.read tweet.write users.read offline.access</span>
1469 and refreshes the token itself.
1470 </li>
1471 </ol>`,
1472 { head: html`<h2>Getting a client</h2>` },
1473 )}`;
1474 }
1475
1476 // GET /:owner/:name/settings/channels
1477 export function channelsSettingsPage(ctx: Ctx): Response {
1478 const repo = loadAdminRepo(ctx);
1479 if (!repo) return repoNotFound(ctx);
1480 const listed = listChannels(ctx.app, ctx.auth.user, repo);
1481 return settingsPageResponse(
1482 ctx,
1483 repo,
1484 "channels",
1485 "Channels",
1486 channelsView(
1487 repoBase(repo),
1488 listed.ok ? listed.value[0] : undefined,
1489 redirectUriFor(ctx.app),
1490 ),
1491 );
1492 }
1493
1494 // POST /:owner/:name/settings/channels — seal the client and begin the authorization.
1495 export async function channelConnect(ctx: Ctx): Promise<Response> {
1496 const gate = await adminForm(ctx);
1497 if (gate instanceof Response) return gate;
1498 const { repo, form } = gate;
1499 const done = connectChannel(ctx.app, ctx.auth.user, repo, {
1500 kind: "x",
1501 clientId: field(form, "clientId"),
1502 clientSecret: field(form, "clientSecret"),
1503 });
1504 if (!done.ok && done.error === "not_found") return repoNotFound(ctx);
1505 return flashTo(
1506 ctx,
1507 `${repoBase(repo)}/settings/channels`,
1508 done.ok
1509 ? { message: "Saved. Press Authorize at X to finish connecting." }
1510 : { tone: "danger", message: CHANNEL_ERRORS[done.error] ?? "X could not be connected." },
1511 );
1512 }
1513
1514 // POST /:owner/:name/settings/channels/:id — review toggle and hashtags.
1515 export async function channelUpdate(ctx: Ctx): Promise<Response> {
1516 const gate = await adminForm(ctx);
1517 if (gate instanceof Response) return gate;
1518 const { repo, form } = gate;
1519 const done = updateChannel(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "", {
1520 review: form.get("review") !== null,
1521 hashtags: field(form, "hashtags"),
1522 });
1523 if (!done.ok && done.error === "not_found") return repoNotFound(ctx);
1524 return flashTo(
1525 ctx,
1526 `${repoBase(repo)}/settings/channels`,
1527 done.ok
1528 ? { message: "Saved." }
1529 : { tone: "danger", message: CHANNEL_ERRORS[done.error] ?? "Not saved." },
1530 );
1531 }
1532
1533 // POST /:owner/:name/settings/channels/:id/posts/:post/(post|pass)
1534 export function channelDecide(decision: "post" | "pass") {
1535 return async (ctx: Ctx): Promise<Response> => {
1536 const gate = await adminForm(ctx);
1537 if (gate instanceof Response) return gate;
1538 const { repo } = gate;
1539 const done = await decidePost(
1540 ctx.app,
1541 ctx.auth.user,
1542 repo,
1543 ctx.params.id ?? "",
1544 { post: ctx.params.post ?? "", decision },
1545 );
1546 if (!done.ok && done.error === "not_found") return repoNotFound(ctx);
1547 return flashTo(
1548 ctx,
1549 `${repoBase(repo)}/settings/channels`,
1550 done.ok
1551 ? { ...(done.value.ok ? {} : { tone: "danger" as const }), message: done.value.said }
1552 : { tone: "danger", message: CHANNEL_ERRORS[done.error] ?? "Not sent." },
1553 );
1554 };
1555 }
1556
1557 // POST /:owner/:name/settings/channels/:id/delete
1558 export async function channelDelete(ctx: Ctx): Promise<Response> {
1559 const gate = await adminForm(ctx);
1560 if (gate instanceof Response) return gate;
1561 const { repo } = gate;
1562 const removed = removeChannel(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
1563 if (!removed.ok && removed.error === "not_found") return repoNotFound(ctx);
1564 return flashTo(
1565 ctx,
1566 `${repoBase(repo)}/settings/channels`,
1567 removed.ok
1568 ? { message: "X is disconnected. The tokens are forgotten." }
1569 : { tone: "danger", message: "No channel by that id." },
1570 );
1571 }
1572
1573 // GET /oauth/x/callback — X sends the browser back with a code and the state.
1574 export async function channelCallback(ctx: Ctx): Promise<Response> {
1575 const q = ctx.url.searchParams;
1576 const done = await finishConnect(ctx.app, ctx.auth.user, {
1577 state: q.get("state") ?? "",
1578 code: q.get("code") ?? "",
1579 error: q.get("error") ?? "",
1580 });
1581 if (!done.ok)
1582 return flashTo(
1583 ctx,
1584 ctx.auth.user ? "/" : "/login",
1585 { tone: "danger", message: done.error },
1586 );
1587 return flashTo(ctx, `${repoBase(done.value)}/settings/channels`, {
1588 message: "X is connected.",
1589 });
1590 }
1591
12891592 // ---- crew ----
12901593
12911594 // GET /:owner/:name/settings/crew
test/channels.test.ts added +355
@@ -0,0 +1,355 @@
1 /**
2 * Distilled posts (#1084): a wave or a watched milestone that landed goes
3 * out as one short post on X, held for the owner or posted at once. X is a
4 * fake; the clock is the test's; nothing here touches the network.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import {
12 connectChannel,
13 decidePost,
14 finishConnect,
15 listChannels,
16 } from "../src/actions/channels.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { createApp, type App } from "../src/app.ts";
19 import { heldForRepos, listPosts } from "../src/core/channels.ts";
20 import { createIssue, setIssueState } from "../src/core/issues.ts";
21 import { addDependency } from "../src/core/dependencies.ts";
22 import { setWatch } from "../src/core/watches.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import { createUser, type User } from "../src/core/users.ts";
25 import { startChannelRoutine } from "../src/crew/channels.ts";
26 import {
27 authorizeUrl,
28 challengeOf,
29 httpX,
30 XError,
31 type XClient,
32 } from "../src/crew/x.ts";
33 import { serve, type Servers } from "../src/http/server.ts";
34 import { composePost, POST_MAX, postForWave } from "../src/story/post.ts";
35 import { writeWave, type Wave } from "../src/story/wave.ts";
36 import { quietLogs } from "./helpers/globals.ts";
37
38 quietLogs();
39
40 const SECRET = "client-secret-distinctive-QQ-91";
41 const ACCESS = "access-token-distinctive-QQ";
42
43 const wave = (version: string, over: Partial<Wave> = {}): Wave => ({
44 version,
45 date: "2026-10-15",
46 headline: "Posts you can read before they go",
47 highlights: [1, 2, 3].map((i) => ({
48 title: `Thing ${i}`,
49 why: i === 1 ? "Nothing reaches X without your say. And a second sentence." : "w",
50 })),
51 pulls: [],
52 ...over,
53 });
54 const waveFile = (w: Wave) => {
55 const text = writeWave(w);
56 if (!text.ok) throw text.error;
57 return { path: `waves/${w.version}.md`, content: text.value };
58 };
59
60 describe("the words of a post", () => {
61 test("headline, one sentence of why, a link; under the limit, however long the note", () => {
62 const text = postForWave(wave("0.1.0"), "https://f.test/o/r/blob/main/waves/0.1.0.md")!;
63 expect(text).toBe(
64 "Posts you can read before they go. Nothing reaches X without your say. https://f.test/o/r/blob/main/waves/0.1.0.md",
65 );
66 const long = composePost({
67 headline: "H".repeat(300),
68 why: "w ".repeat(200),
69 link: "https://f.test/x",
70 hashtags: "#a",
71 });
72 expect(long.length).toBeLessThanOrEqual(POST_MAX);
73 expect(long.endsWith("https://f.test/x #a")).toBe(true);
74 });
75 test("no hashtags unless the owner set them; a draft note says nothing", () => {
76 expect(postForWave(wave("0.1.0"), "https://f.test/x")).not.toContain("#");
77 expect(postForWave(wave("0.1.0", { headline: "TODO write this" }), "https://f.test/x")).toBeUndefined();
78 });
79 });
80
81 describe("the X client", () => {
82 test("PKCE S256 in the authorize address, Basic auth for the token, Bearer to post", async () => {
83 const asked: { url: string; init: RequestInit }[] = [];
84 const fetcher = ((url: string, init: RequestInit) => {
85 asked.push({ url, init });
86 return Promise.resolve(
87 new Response(
88 JSON.stringify(
89 url.endsWith("/tweets")
90 ? { data: { id: "99" } }
91 : { access_token: "a", refresh_token: "r", expires_in: 7200 },
92 ),
93 ),
94 );
95 }) as never;
96 const url = new URL(
97 authorizeUrl({ clientId: "cid", redirectUri: "https://f.test/oauth/x/callback", state: "st", verifier: "v".repeat(50) }),
98 );
99 expect(url.origin + url.pathname).toBe("https://x.com/i/oauth2/authorize");
100 expect(url.searchParams.get("code_challenge_method")).toBe("S256");
101 expect(url.searchParams.get("code_challenge")).toBe(challengeOf("v".repeat(50)));
102 expect(url.searchParams.get("scope")).toContain("offline.access");
103 const x = httpX(fetcher);
104 await x.exchange({ clientId: "cid", clientSecret: "sec", code: "c", verifier: "v", redirectUri: "r" });
105 expect((asked[0]!.init.headers as Record<string, string>).authorization).toBe(
106 `Basic ${Buffer.from("cid:sec").toString("base64")}`,
107 );
108 expect(String(asked[0]!.init.body)).toContain("code_verifier=v");
109 expect(await x.post({ access: "a", text: "hi" })).toEqual({ id: "99" });
110 expect((asked[1]!.init.headers as Record<string, string>).authorization).toBe("Bearer a");
111 });
112 test("a 401 is rejected, a 500 is a failure; neither carries the token", async () => {
113 const answer = (status: number) =>
114 httpX((() => Promise.resolve(new Response("{}", { status }))) as never);
115 const rejected = await answer(401).post({ access: ACCESS, text: "x" }).catch((e) => e);
116 expect(rejected).toBeInstanceOf(XError);
117 expect(rejected.kind).toBe("rejected");
118 const failed = await answer(500).post({ access: ACCESS, text: "x" }).catch((e) => e);
119 expect(failed.kind).toBe("failed");
120 expect(failed.message).not.toContain(ACCESS);
121 });
122 });
123
124 describe("channels on a forge", () => {
125 let dataDir: string;
126 let app: App;
127 let servers: Servers;
128 let alice: User;
129 let bob: User;
130 let repo: Repo;
131 let clock = new Date("2026-10-15T10:00:00Z");
132 const sent: string[] = [];
133 const refreshed: string[] = [];
134 let postError: XError | undefined;
135 let expiresInS = 7200;
136 const fake: XClient = {
137 exchange: async () => ({ access: ACCESS, refresh: "refresh-1", expiresInS }),
138 refresh: async ({ refresh }) => {
139 refreshed.push(refresh);
140 return { access: "access-2", refresh: "refresh-2", expiresInS: 7200 };
141 },
142 post: async ({ text }) => {
143 if (postError) throw postError;
144 sent.push(text);
145 return { id: `x${sent.length}` };
146 },
147 };
148 let routine: ReturnType<typeof startChannelRoutine>;
149
150 const stateOf = (url: string) => new URL(url).searchParams.get("state")!;
151 const connect = async (r: Repo, review = true) => {
152 const made = connectChannel(app, alice, r, { kind: "x", clientId: "cid", clientSecret: SECRET, review });
153 if (!made.ok) throw new Error(made.error);
154 const done = await finishConnect(app, alice, {
155 state: stateOf(made.value.channel.authorizeUrl!),
156 code: "code",
157 error: "",
158 });
159 if (!done.ok) throw new Error(done.error);
160 return made.value.channel.id;
161 };
162 const land = (r: Repo, version: string) =>
163 commitToBranch(app, alice, r, { message: `wave ${version}`, files: [waveFile(wave(version))] });
164 const newRepo = async (name: string, visibility: "public" | "private") => {
165 const made = await createRepo(app, alice, { name, visibility, description: "x" });
166 if (!made.ok) throw new Error(String(made.error));
167 await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "a.txt", content: "a\n" }] });
168 return made.value;
169 };
170
171 beforeAll(async () => {
172 dataDir = await mkdtemp(join(tmpdir(), "forge-channels-"));
173 app = createApp({ dataDir, port: 0 });
174 servers = await serve(app);
175 routine = startChannelRoutine(app, { client: fake, now: () => clock, everyMs: 3_600_000 });
176 const a = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
177 const b = await createUser(app.db, { trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
178 if (!a.ok || !b.ok) throw new Error("users");
179 alice = a.value;
180 bob = b.value;
181 repo = await newRepo("pub", "public");
182 await land(repo, "0.1.0");
183 });
184 afterAll(async () => {
185 await routine.stop();
186 servers.stop();
187 app.close();
188 await rm(dataDir, { recursive: true, force: true });
189 });
190
191 test("only an admin connects; the secret and tokens are sealed and never listed", async () => {
192 expect(connectChannel(app, bob, repo, { kind: "x", clientId: "c", clientSecret: "s" })).toEqual({ ok: false, error: "not_found" });
193 expect(connectChannel(app, alice, repo, { kind: "x", clientId: "c c", clientSecret: "s" }).ok).toBe(false);
194 expect(connectChannel(app, alice, repo, { kind: "x", clientId: "cid", clientSecret: SECRET, hashtags: "nope" })).toEqual({ ok: false, error: "invalid_hashtags" });
195 const id = await connect(repo);
196 const listed = listChannels(app, alice, repo);
197 expect(listed.ok && listed.value[0]!.connected).toBe(true);
198 const everything = JSON.stringify(listed) + JSON.stringify(app.db.query("SELECT * FROM channel").all());
199 expect(everything).not.toContain(SECRET);
200 expect(everything).not.toContain(ACCESS);
201 // One X channel per repository: connecting again is the same channel.
202 const again = connectChannel(app, alice, repo, { kind: "x", review: true });
203 expect(again.ok && again.value.channel.id).toBe(id);
204 // The state is single use.
205 const redo = connectChannel(app, alice, repo, { kind: "x", clientId: "cid", clientSecret: SECRET });
206 const st = stateOf(redo.ok ? redo.value.channel.authorizeUrl! : "");
207 expect((await finishConnect(app, bob, { state: st, code: "c", error: "" })).ok).toBe(false);
208 expect((await finishConnect(app, alice, { state: "bogus", code: "c", error: "" })).ok).toBe(false);
209 expect((await finishConnect(app, alice, { state: st, code: "c", error: "" })).ok).toBe(true);
210 expect((await finishConnect(app, alice, { state: st, code: "c", error: "" })).ok).toBe(false);
211 });
212
213 test("history is not posted; a new wave is held, read in the feed, and sent once on Post", async () => {
214 await routine.sweep();
215 const ch = listChannels(app, alice, repo);
216 const id = ch.ok ? ch.value[0]!.id : "";
217 // Connected before 0.1.0 landed? The first sweep seeds: nothing is held.
218 expect(sent).toEqual([]);
219 await land(repo, "0.1.1");
220 await routine.sweep();
221 await routine.sweep();
222 expect(sent).toEqual([]);
223 const held = heldForRepos(app.db, [repo.id]);
224 expect(held.length).toBe(1);
225 expect(held[0]!.subject).toBe("wave:0.1.1");
226 expect(held[0]!.text.length).toBeLessThanOrEqual(POST_MAX);
227 expect(held[0]!.link).toContain("/alice/pub/blob/main/waves/0.1.1.md");
228 const sentNow = await decidePost(app, alice, repo, id, { decision: "post" });
229 expect(sentNow.ok && sentNow.value.ok).toBe(true);
230 expect(sent).toEqual([held[0]!.text]);
231 expect(listPosts(app.db, id)[0]!.externalId).toBe("x1");
232 // Pressing Post again, or sweeping again, sends nothing more.
233 const twice = await decidePost(app, alice, repo, id, { post: held[0]!.id, decision: "post" });
234 expect(twice.ok && twice.value.ok).toBe(false);
235 await routine.sweep();
236 expect(sent.length).toBe(1);
237 expect((await decidePost(app, bob, repo, id, { decision: "post" })).ok).toBe(false);
238 });
239
240 test("Not this one passes; a failure is a sentence, and a rejected token says to connect again", async () => {
241 const ch = listChannels(app, alice, repo);
242 const id = ch.ok ? ch.value[0]!.id : "";
243 await land(repo, "0.1.2");
244 await routine.sweep();
245 const passed = await decidePost(app, alice, repo, id, { decision: "pass" });
246 expect(passed.ok && passed.value.post.state).toBe("passed");
247 await land(repo, "0.1.3");
248 await routine.sweep();
249 postError = new XError("failed", "X says to slow down; try again later.");
250 const failed = await decidePost(app, alice, repo, id, { decision: "post" });
251 expect(failed.ok && failed.value.said).toBe("X says to slow down; try again later.");
252 expect(sent.length).toBe(1);
253 postError = new XError("rejected", "x");
254 const rejected = await decidePost(app, alice, repo, id, { decision: "post" });
255 expect(rejected.ok && rejected.value.said).toContain("Connect again");
256 postError = undefined;
257 const now = listChannels(app, alice, repo);
258 expect(now.ok && now.value[0]!.connected).toBe(false);
259 expect(now.ok && now.value[0]!.lastSaid).toContain("Connect again");
260 // Not connected: nothing more is sent until it is.
261 expect((await decidePost(app, alice, repo, id, { decision: "post" })).ok).toBe(false);
262 });
263
264 test("review off posts at once, once; an expired token is refreshed first", async () => {
265 const r = await newRepo("auto", "public");
266 expiresInS = 30;
267 await connect(r, false);
268 expiresInS = 7200;
269 await routine.sweep();
270 sent.length = 0;
271 await land(r, "1.0.0");
272 await routine.sweep();
273 await routine.sweep();
274 expect(sent.length).toBe(1);
275 expect(refreshed).toEqual(["refresh-1"]);
276 expect(heldForRepos(app.db, [r.id])).toEqual([]);
277 });
278
279 test("a watched milestone that lands is drafted from its name", async () => {
280 const r = await newRepo("mile", "public");
281 const id = await connect(r);
282 await routine.sweep();
283 const mk = (title: string, body = "") => {
284 const i = createIssue(app.db, { repoId: r.id, authorId: alice.id, title, body });
285 if (!i.ok) throw new Error(i.error);
286 return i.value;
287 };
288 const top = mk("A faster feed", "Scrolling no longer waits on the network. Details follow.");
289 const leaf = mk("Cache it");
290 addDependency(app.db, top, leaf, alice.id);
291 setWatch(app.db, alice.id, top.id, true);
292 await routine.sweep();
293 expect(heldForRepos(app.db, [r.id])).toEqual([]);
294 setIssueState(app.db, leaf.id, "closed");
295 await routine.sweep();
296 const held = heldForRepos(app.db, [r.id]);
297 expect(held.map((h) => h.subject)).toEqual([`milestone:${top.id}`]);
298 expect(held[0]!.text).toContain("Done: A faster feed.");
299 expect(held[0]!.text).toContain("Scrolling no longer waits on the network.");
300 expect(held[0]!.text).toContain(`/alice/mile/milestones/${top.number}`);
301 expect(id).toBeTruthy();
302 });
303
304 test("nothing about a private repository is drafted or posted", async () => {
305 const r = await newRepo("secret", "private");
306 const id = await connect(r, false);
307 await routine.sweep();
308 sent.length = 0;
309 await land(r, "2.0.0");
310 await routine.sweep();
311 expect(sent).toEqual([]);
312 expect(app.db.query("SELECT COUNT(*) AS n FROM channel_post WHERE channel_id = ?1").get(id)).toEqual({ n: 0 });
313 // A repository that turns private with a draft held: sending refuses.
314 const p = await newRepo("flip", "public");
315 const flip = await connect(p);
316 await routine.sweep();
317 await land(p, "3.0.0");
318 await routine.sweep();
319 expect(heldForRepos(app.db, [p.id]).length).toBe(1);
320 app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(p.id);
321 const refused = await decidePost(app, alice, p, flip, { decision: "post" });
322 expect(refused.ok && refused.value.ok).toBe(false);
323 expect(sent).toEqual([]);
324 });
325
326 test("the settings page and the routes: admin only, same-origin, no secrets", async () => {
327 const login = async (u: string) => {
328 const res = await fetch(`${servers.url}/signin`, {
329 method: "POST",
330 body: new URLSearchParams({ username: u, password: "a-good-passphrase" }),
331 redirect: "manual",
332 });
333 return `${(res.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=dev`;
334 };
335 const a = await login("alice");
336 const b = await login("bob");
337 const page = await fetch(`${servers.url}/alice/pub/settings/channels`, { headers: { cookie: a } });
338 expect(page.status).toBe(200);
339 const text = await page.text();
340 expect(text).toContain("Review before posting");
341 expect(text).not.toContain(SECRET);
342 expect((await fetch(`${servers.url}/alice/pub/settings/channels`, { headers: { cookie: b } })).status).toBe(404);
343 const post = (cookie: string, headers: Record<string, string> = {}) =>
344 fetch(`${servers.url}/alice/pub/settings/channels`, {
345 method: "POST",
346 headers: { cookie, ...headers },
347 body: new URLSearchParams({ clientId: "c", clientSecret: "s" }),
348 redirect: "manual",
349 });
350 expect((await post(a, { origin: "http://evil.example" })).status).toBe(403);
351 expect((await post(b)).status).toBe(404);
352 const cb = await fetch(`${servers.url}/oauth/x/callback?state=nope&code=c`, { headers: { cookie: a }, redirect: "manual" });
353 expect(cb.status).toBe(303);
354 });
355 });
test/mcp.test.ts +1
@@ -192,6 +192,7 @@ describe("the forge over MCP", () => {
192192 "feed",
193193 "make_it_yours",
194194 "front_page",
195 "posts",
195196 "map",
196197 "milestones",
197198 "watch",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs