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

`forge tell "words"` tells the crew from your shell, about the repository of the folder you are in #7460

Parked opened this
Closed without merging

scout/forge:scout/7352-forge-tell-words-tells-the-crew-from-you → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +350 −24
README.md +1
@@ -321,6 +321,7 @@ forge ship 12 # land pull #12 after a y/N, as Merge does
321321 forge pulls # open pulls of this clone, newest first
322322 forge asks # what waits on you, most important first
323323 forge asks --repo owner/name # only that repository's; --json for the API's answer
324 forge tell "make the header smaller" # tell the crew, about the repo of this folder's origin; --repo owner/name overrides; --variants 1-4 and --from /path as the API takes them; `forge tell -- "--fast"` for words that start with a dash. The MCP `tell` tool takes `from` but not `variants`; the terminal (tty) takes neither
324325 forge asks --ship 1 3 # decide by the line numbers just printed: planned, then Apply? [y/N]
325326 forge asks --close 2 --reason "words" # also --dismiss 4; --yes skips the question (needed without a TTY)
326327 forge asks --undo <id> # take back a decision by the receipt id it printed
docs/CLI.md +17
@@ -288,6 +288,23 @@ look alice/shop Pull #3 is green — look and merge https://forge.example.
288288 parked alice/notes Issue #9 waits on a decision https://forge.example.com/alice/notes/issues/9
289289 ```
290290
291 ## forge tell
292
293 Tell the crew something about a repository; it becomes an issue. The
294 repository is that of this folder's `origin` when it points at the workbench,
295 or `--repo`. Words are 1 to 2000 characters; start them with a dash after `--`.
296
297 Flags:
298
299 - `--repo owner/name` — the repository, instead of this folder's origin.
300 - `--variants 1-4` — how many attempts the crew makes.
301 - `--from /path` — the workbench page you were looking at.
302
303 ```console
304 $ forge tell "make the header smaller"
305 told alice/shop: issue #12 https://forge.example.com/alice/shop/issues/12
306 ```
307
291308 ## forge ship
292309
293310 Lands a pull, as its Merge button does: prints the pull with its check and
src/actions/tell.ts +2 −23
@@ -17,7 +17,8 @@ import { routeIssue, type Routed } from "../crew/route.ts";
1717 import { err, ok, type Result } from "../kernel/result.ts";
1818 import { requireParticipant } from "./access.ts";
1919 import { assignIssue, openIssue, type MirrorError } from "./issues.ts";
20 import { scrubQuery } from "./tell_context.ts";
20 export { FROM_MAX, parseFrom } from "./tell_from.ts";
21 import { parseFrom } from "./tell_from.ts";
2122 import { requireVerified } from "./verify.ts";
2223 import { VERIFY_FIRST } from "./verify_words.ts";
2324
@@ -45,28 +46,6 @@ export function parseVariants(raw: unknown): number | undefined {
4546 return raw >= 1 && raw <= VARIANTS_MAX ? raw : undefined;
4647 }
4748
48 /** The longest `from` a tell may carry. */
49 export const FROM_MAX = 512;
50
51 /**
52 * `from` as the doors take it: absent is none; otherwise a same-forge path
53 * (leading single `/`, no scheme, no backslash, no control or space) of at
54 * most 512 characters. Undefined for no. A query parameter that carries a
55 * secret (`scrubQuery`) is dropped; the rest of the path is kept as given.
56 */
57 export function parseFrom(raw: unknown): string | null | undefined {
58 if (raw === undefined || raw === null) return null;
59 if (typeof raw !== "string" || raw.length === 0 || raw.length > FROM_MAX)
60 return undefined;
61 if (!raw.startsWith("/") || raw.startsWith("//")) return undefined;
62 if (/[\\\s\x00-\x1f\x7f<>()\[\]`"'*]/.test(raw)) return undefined;
63 const q = raw.indexOf("?");
64 const h = raw.indexOf("#");
65 if (q === -1 || (h !== -1 && h < q)) return raw;
66 const end = h === -1 ? raw.length : h;
67 return `${raw.slice(0, q)}${scrubQuery(raw.slice(q, end))}${raw.slice(end)}`;
68 }
69
7049 /**
7150 * An app's own address as a place a tell was said: scheme and host (and
7251 * port) only. Only the app terminal's door builds one and says `fromApp`; every other
src/actions/tell_from.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Where a tell was said: the one rule for `from`, pure, so the CLI refuses
3 * what the server would before it spends a round trip.
4 */
5
6 import { scrubQuery } from "./tell_context.ts";
7
8 /** The longest `from` a tell may carry. */
9 export const FROM_MAX = 512;
10
11 /**
12 * `from` as the doors take it: absent is none; otherwise a same-forge path
13 * (leading single `/`, no scheme, no backslash, no control or space) of at
14 * most 512 characters. Undefined for no. A query parameter that carries a
15 * secret (`scrubQuery`) is dropped; the rest of the path is kept as given.
16 */
17 export function parseFrom(raw: unknown): string | null | undefined {
18 if (raw === undefined || raw === null) return null;
19 if (typeof raw !== "string" || raw.length === 0 || raw.length > FROM_MAX)
20 return undefined;
21 if (!raw.startsWith("/") || raw.startsWith("//")) return undefined;
22 if (/[\\\s\x00-\x1f\x7f<>()\[\]`"'*]/.test(raw)) return undefined;
23 const q = raw.indexOf("?");
24 const h = raw.indexOf("#");
25 if (q === -1 || (h !== -1 && h < q)) return raw;
26 const end = h === -1 ? raw.length : h;
27 return `${raw.slice(0, q)}${scrubQuery(raw.slice(q, end))}${raw.slice(end)}`;
28 }
src/cli/api.ts +30
@@ -356,6 +356,36 @@ export class ForgeApi {
356356 return ok({ raw: out.value, asks });
357357 }
358358
359 /**
360 * Tell the crew something about `owner/name` (`POST /api/v1/feed/tells`).
361 * Answers the issue it became, with its address on the workbench.
362 */
363 async tell(
364 owner: string,
365 name: string,
366 text: string,
367 more: { variants?: number | undefined; from?: string | undefined } = {},
368 ): Promise<ApiResult<{ issue: number; url: string }>> {
369 const out = await this.call<{ issue?: unknown }>("/api/v1/feed/tells", {
370 method: "POST",
371 body: JSON.stringify({
372 app: `${owner}/${name}`,
373 text,
374 ...(more.variants === undefined ? {} : { variants: more.variants }),
375 ...(more.from === undefined ? {} : { from: more.from }),
376 }),
377 });
378 if (!out.ok) return out;
379 const issue = out.value.issue;
380 if (typeof issue !== "number")
381 return err({
382 code: "bad_response",
383 message: "the forge did not say which issue the tell became",
384 status: 0,
385 });
386 return ok({ issue, url: `${this.webUrl(owner, name)}/issues/${issue}` });
387 }
388
359389 /**
360390 * One action on many asks (`POST /api/v1/asks/bulk`): the plan while
361391 * `preview` is true, the deed and its receipt when false.
src/cli/main.ts +107 −1
@@ -7,6 +7,7 @@
77 * forge sync clone what is missing, fetch the rest, report
88 * forge status the same report without touching the network
99 * forge asks what waits on you, most important first
10 * forge tell "words" tell the crew about this folder's repository
1011 * forge asks --ship 1 3 decide asks by their numbers: planned, then a y/N
1112 * forge asks --undo <id> take back what that decided
1213 * forge ship <number> land a pull after a y/N, as its Merge button does
@@ -19,6 +20,7 @@
1920
2021 import { parseArgs, parseDuration, parseRepoRef, type Args } from "./args.ts";
2122 import { ForgeApi, type ApiError, type Ask, type Bulk } from "./api.ts";
23 import { parseFrom } from "../actions/tell_from.ts";
2224 import { parseWish, pickAsks, type Wish } from "./decide.ts";
2325 import {
2426 clearConfig,
@@ -31,6 +33,7 @@ import {
3133 saveConfig,
3234 type Config,
3335 } from "./config.ts";
36 import * as git from "../git/local.ts";
3437 import { folderRepo } from "./folder-repo.ts";
3538 import { systemNotifier } from "./notify.ts";
3639 import { resolveRepo } from "./here.ts";
@@ -63,7 +66,7 @@ export const EXIT = {
6366 refused: 5,
6467 } as const;
6568
66 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "repo", "reason"];
69 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "repo", "variants", "from", "reason"];
6770
6871 /** What the CLI needs from the person at the keyboard; a test fakes it. */
6972 export interface Io {
@@ -120,6 +123,8 @@ export async function main(
120123 return openRepo(out, args);
121124 case "asks":
122125 return asks(out, args, argv.slice(1));
126 case "tell":
127 return tell(out, args);
123128 case "ship":
124129 return ship(out, args, io);
125130 case "ui":
@@ -154,6 +159,10 @@ function usage(out: Out): void {
154159 out.line(
155160 b(" forge asks") + " [--repo owner/name] [--json]",
156161 );
162 out.line(
163 b(" forge tell <words…>") +
164 " [--repo owner/name] [--variants 1-4] [--from /path] [--]",
165 );
157166 out.line(
158167 b(" forge asks --ship|--close|--dismiss <n…>") +
159168 " [--reason words] [--yes]",
@@ -663,6 +672,103 @@ function printBulk(out: Out, bulk: Bulk, action: string, done: boolean): void {
663672 out.line(` skipped ${inert(s.item)} (${inert(s.reason)})`);
664673 }
665674
675 /**
676 * `owner/name` from a git remote that points at the workbench at `base`
677 * (http or https, same host, same path prefix), or undefined for any other.
678 */
679 export function repoFromRemote(
680 remote: string,
681 base: string,
682 ): { owner: string; name: string } | undefined {
683 let r: URL;
684 let b: URL;
685 try {
686 r = new URL(remote);
687 b = new URL(base);
688 } catch {
689 return undefined;
690 }
691 if (!/^https?:$/.test(r.protocol) || r.host !== b.host) return undefined;
692 const prefix = b.pathname.replace(/\/+$/, "");
693 if (!r.pathname.startsWith(`${prefix}/`)) return undefined;
694 const rest = r.pathname
695 .slice(prefix.length + 1)
696 .replace(/\/+$/, "")
697 .replace(/\.git$/, "");
698 try {
699 return parseRepoRef(decodeURIComponent(rest));
700 } catch {
701 return undefined;
702 }
703 }
704
705 async function tell(out: Out, args: Args): Promise<number> {
706 const text = args.positional.join(" ").trim();
707 if (text === "") {
708 out.err(
709 "forge tell: say something — " +
710 'forge tell "words" [--repo owner/name] [--variants 1-4] [--from /path]',
711 );
712 return EXIT.usage;
713 }
714 if (text.length > 2000) {
715 out.err("forge tell: the words are 1 to 2000 characters");
716 return EXIT.usage;
717 }
718 const only = args.value("repo");
719 let ref = only === undefined ? undefined : parseRepoRef(only);
720 if (only !== undefined && ref === undefined) {
721 out.err("forge tell: --repo expects owner/name");
722 return EXIT.usage;
723 }
724 const rawVariants = args.value("variants");
725 const variants = rawVariants === undefined ? undefined : Number(rawVariants);
726 if (
727 variants !== undefined &&
728 !(Number.isInteger(variants) && variants >= 1 && variants <= 4)
729 ) {
730 out.err("forge tell: --variants is a whole number from 1 to 4");
731 return EXIT.usage;
732 }
733 const from = args.value("from");
734 if (
735 from !== undefined &&
736 parseFrom(from) === undefined
737 ) {
738 out.err(
739 "forge tell: --from is a path on the workbench, like /alice/notes/pulls/3",
740 );
741 return EXIT.usage;
742 }
743 const loaded = await requireConfig(out);
744 if (typeof loaded === "number") return loaded;
745 if (ref === undefined) {
746 const remote = await git.remoteUrl(process.cwd());
747 ref = remote === null ? undefined : repoFromRemote(remote, loaded.url);
748 if (ref === undefined) {
749 out.err(
750 "forge tell: this folder's origin is not on the workbench — " +
751 "use --repo owner/name",
752 );
753 return EXIT.usage;
754 }
755 }
756 const told = await new ForgeApi(loaded.url, loaded.token).tell(
757 ref.owner,
758 ref.name,
759 text,
760 { variants, from },
761 );
762 if (!told.ok) {
763 out.err(`forge tell: ${inert(told.error.message)}`);
764 return told.error.status === 401 ? EXIT.notConfigured : EXIT.failed;
765 }
766 out.line(
767 `told ${ref.owner}/${ref.name}: issue #${told.value.issue} ${told.value.url}`,
768 );
769 return EXIT.ok;
770 }
771
666772 /**
667773 * The asks as lines no wider than `width - 1`, so none wraps on its own:
668774 * kind and repository padded to their widest, the address whole, and the
test/cli-tell.test.ts added +165
@@ -0,0 +1,165 @@
1 /** `forge tell` against a fake `POST /api/v1/feed/tells`, run as a shell runs it. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { EXIT, repoFromRemote } from "../src/cli/main.ts";
8
9 const CLI = new URL("../src/cli/main.ts", import.meta.url).pathname;
10
11 let server: ReturnType<typeof Bun.serve>;
12 let base = "";
13 let dir = "";
14 let reply: () => Response = () => Response.json({ issue: 12 }, { status: 201 });
15 const seen: { auth: string | null; body: unknown }[] = [];
16
17 beforeAll(async () => {
18 dir = await mkdtemp(join(tmpdir(), "forge-tell-"));
19 server = Bun.serve({
20 port: 0,
21 async fetch(req) {
22 const url = new URL(req.url);
23 if (url.pathname !== "/api/v1/feed/tells" || req.method !== "POST")
24 return Response.json({ error: "not_found", message: "no" }, { status: 404 });
25 seen.push({ auth: req.headers.get("authorization"), body: await req.json() });
26 return reply();
27 },
28 });
29 base = `http://127.0.0.1:${server.port}`;
30 for (const [name, remote] of [
31 ["clone", `${base}/alice/shop.git`],
32 ["other", "https://example.com/a/b.git"],
33 ] as const) {
34 Bun.spawnSync(["git", "init", "-q", join(dir, name)]);
35 Bun.spawnSync(["git", "remote", "add", "origin", remote], { cwd: join(dir, name) });
36 }
37 });
38
39 afterAll(async () => {
40 server.stop(true);
41 await rm(dir, { recursive: true, force: true });
42 });
43
44 async function forge(args: string[], cwd = join(dir, "clone")) {
45 const proc = Bun.spawn(["bun", CLI, ...args], {
46 cwd,
47 env: {
48 PATH: process.env["PATH"] ?? "",
49 HOME: process.env["HOME"] ?? "",
50 FORGE_URL: base,
51 FORGE_TOKEN: "tok",
52 FORGE_CONFIG_DIR: dir,
53 FORGE_KEYCHAIN: "0",
54 NO_COLOR: "1",
55 },
56 stdout: "pipe",
57 stderr: "pipe",
58 });
59 const [out, err, code] = await Promise.all([
60 new Response(proc.stdout).text(),
61 new Response(proc.stderr).text(),
62 proc.exited,
63 ]);
64 return { code, out, err };
65 }
66
67 test("posts the words about the folder's repository and prints the issue address", async () => {
68 const run = await forge(["tell", "make", "the", "header", "smaller"]);
69 expect(run.code).toBe(EXIT.ok);
70 expect(seen.at(-1)).toEqual({
71 auth: "Bearer tok",
72 body: { app: "alice/shop", text: "make the header smaller" },
73 });
74 expect(run.out).toContain(`issue #12 ${base}/alice/shop/issues/12`);
75 });
76
77 test("`--` ends the options, so words may start with a dash", async () => {
78 const run = await forge(["tell", "--", "--fast", "please"]);
79 expect(run.code).toBe(EXIT.ok);
80 expect((seen.at(-1)!.body as { text: string }).text).toBe("--fast please");
81 });
82
83 test("--variants and --from go to the API as given", async () => {
84 const run = await forge([
85 "tell", "try", "it", "--variants", "3", "--from", "/alice/shop/pulls/3",
86 ]);
87 expect(run.code).toBe(EXIT.ok);
88 expect(seen.at(-1)!.body).toEqual({
89 app: "alice/shop",
90 text: "try it",
91 variants: 3,
92 from: "/alice/shop/pulls/3",
93 });
94 });
95
96 test("a bad --variants or --from exits 2 without a request", async () => {
97 const before = seen.length;
98 const bads = [
99 ["--variants", "9"],
100 ["--variants", "x"],
101 ["--from", "https://evil.example/"],
102 ["--from", "/a b"],
103 ["--from", "/a\"b"],
104 ["--from", "//evil"],
105 ];
106 for (const bad of bads) {
107 expect((await forge(["tell", "hi", ...bad])).code).toBe(EXIT.usage);
108 }
109 expect(seen.length).toBe(before);
110 });
111
112 test("--repo overrides the folder, even one that is not a clone", async () => {
113 const run = await forge(["tell", "hi", "--repo", "bob/lab"], dir);
114 expect(run.code).toBe(EXIT.ok);
115 expect((seen.at(-1)!.body as { app: string }).app).toBe("bob/lab");
116 });
117
118 test("empty words print usage and exit 2 without a request", async () => {
119 const before = seen.length;
120 const run = await forge(["tell", " "]);
121 expect(run.code).toBe(EXIT.usage);
122 expect(run.err).toContain("forge tell");
123 expect(seen.length).toBe(before);
124 });
125
126 test("an origin elsewhere asks for --repo and exits 2", async () => {
127 const run = await forge(["tell", "hi"], join(dir, "other"));
128 expect(run.code).toBe(EXIT.usage);
129 expect(run.err).toContain("--repo");
130 });
131
132 test("a refusal prints the API's words and exits 1; a 401 exits 3", async () => {
133 reply = () =>
134 Response.json({ error: "not_found", message: "no such repository" }, { status: 404 });
135 const gone = await forge(["tell", "hi"]);
136 expect(gone.code).toBe(EXIT.failed);
137 expect(gone.err).toContain("no such repository");
138 reply = () => Response.json({ error: "unauthorized", message: "bad token" }, { status: 401 });
139 expect((await forge(["tell", "hi"])).code).toBe(EXIT.notConfigured);
140 reply = () => Response.json({ issue: 12 }, { status: 201 });
141 });
142
143 test("not logged in exits 3", async () => {
144 const proc = Bun.spawn(["bun", CLI, "tell", "hi"], {
145 cwd: join(dir, "clone"),
146 env: { PATH: process.env["PATH"] ?? "", HOME: dir, FORGE_CONFIG_DIR: join(dir, "empty"), FORGE_KEYCHAIN: "0" },
147 stdout: "pipe",
148 stderr: "pipe",
149 });
150 expect(await proc.exited).toBe(EXIT.notConfigured);
151 });
152
153 test("help lists the command", async () => {
154 expect((await forge(["help"])).out).toContain("forge tell");
155 });
156
157 test("repoFromRemote reads http(s) remotes of the workbench only", () => {
158 const w = "https://forge.example";
159 expect(repoFromRemote("https://forge.example/a/b.git", w)).toEqual({ owner: "a", name: "b" });
160 expect(repoFromRemote("https://u:[email protected]/a/b", w)).toEqual({ owner: "a", name: "b" });
161 expect(repoFromRemote("https://other.example/a/b", w)).toBeUndefined();
162 expect(repoFromRemote("[email protected]:a/b.git", w)).toBeUndefined();
163 expect(repoFromRemote("https://forge.example/a/b/c", w)).toBeUndefined();
164 expect(repoFromRemote("https://forge.example/x/a/b", "https://forge.example/x/")).toEqual({ owner: "a", name: "b" });
165 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs