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

The terminal's tell command sends one sentence as a tell and prints the post's address #13700

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13685-the-terminal-s-tell-command-sends-one-se → main 5 commits fork 2 threads · 2 unresolved

  • Merged. scout/13685-the-terminal-s-tell-command-sends-one-se was merged into main as 6ce223c.

Review

Sign in to review this change.
6 files changed +178 −9
docs/TOUR.md +1 −1
@@ -21,7 +21,7 @@ git clone ssh://localhost:2222/you/hello.git # git, same port
2121 ssh -p 2222 localhost tell make the header blue # tell the crew in one line
2222 ```
2323
24 `tell <words>` takes the rest of the command line as given (no shell expansion; control characters are refused) and tells the crew in the forge's own repository, as the account the key belongs to, through the same action as the web composer. It prints the told line and the full address of the issue, and exits 0; an unknown key, nothing said, too much, or an unverified email prints the reason on stderr, records nothing and exits 1. (Quote the words if your local shell would expand them.) When SSH is on, `/llms.txt` and `/api/v1/here` (the `ssh` field of the "tell the crew" action) name this exact command, so an agent finds it without being taught; with SSH off they say nothing about it.
24 `tell [owner/name] <words>` takes the rest of the command line as given (no shell expansion; control characters are refused) and tells the crew in the forge's own repository (or in `owner/name` when it leads the words and names a repository you can read), as the account the key belongs to, through the same action as the web composer. It prints the told line and the full address of the issue, and exits 0; an unknown key, nothing said, too much, or an unverified email prints the reason on stderr, records nothing and exits 1. (Quote the words if your local shell would expand them.) When SSH is on, `/llms.txt` and `/api/v1/here` (the `ssh` field of the "tell the crew" action) name this exact command, so an agent finds it without being taught; with SSH off they say nothing about it.
2525
2626 On an app's login, `ssh -p 2222 notes@localhost tell make the header blue` goes through the app terminal's gate (an app you may not enter answers `no app named notes`, and nothing is recorded) and tells the crew of the app's repository, with the app's production address as where it was said: the issue body and `/asked` show `Told from <address>`.
2727
docs/features/README.md +1
@@ -25,6 +25,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
2525 - [An app with no description says its README](readme-description.md)
2626 - [Arcade carts](arcade-carts.md)
2727 - [Changelog](changelog.md)
28 - [Tell the crew from any shell with ssh and tell](tell-from-ssh.md)
2829 - [/docs](docs-link.md)
2930 - [Engine shape](engine-shape.md)
3031 - [Feed fold](feed-fold.md)
docs/features/tell-from-ssh.md added +9
@@ -0,0 +1,9 @@
1 # Tell the crew from any shell (#13685)
2
3 `ssh <forge> tell <words>` tells the crew in one line and prints the issue's full address; `FORGE_APP_SSH` names the exact command.
4
5 - Where it goes: the forge's own repository, or the repository named by a leading `owner/name` when it exists, you can read it, and words follow (`tell alice/notes add a footer`).
6 - A first word that is not a repository you can read is just words for the forge's repository. The reply then starts with `no repository <word> you can read; told in <owner>/<name>`, so a typo is seen.
7 - Refusals are the composer's words: empty, too long, control characters, unverified email, may not direct the crew. Nothing is recorded when refused.
8 - A named repository skips the first-ask path that makes a new app on a claimed forge.
9 - Code: `src/tui/ssh-tell.ts` (`namedRepo`); tests in `test/ssh-tell.test.ts` and `test/ssh-tell-named-first-ask.test.ts`.
src/tui/ssh-tell.ts +35 −7
@@ -3,8 +3,8 @@
33 * exec of `tell` calls the same `tell()` the web composer
44 * and the terminal use, as the account the presented key belongs to, with
55 * `from` null (on an app's login: through the app terminal's gate, to the
6 * app's repository, `from` the app's production address), and prints the told line and the full address of the issue.
7 * The words are the rest of the command line as given: no shell, no
6 * app's repository, `from` the app's production address), and prints the told line and the full
7 * address of the issue. The words are the rest of the command line as given: no shell, no
88 * expansion, no `eval`; a control character is refused before anything runs.
99 */
1010
@@ -14,7 +14,7 @@ import { appGate, ttyRefusalText } from "../apps/tty.ts";
1414 import { appsRuntime } from "../apps/runtime.ts";
1515 import type { App } from "../app.ts";
1616 import type { AppRecord } from "../core/apps.ts";
17 import { getRepo, getRepoById } from "../core/repos.ts";
17 import { canRead, getRepo, getRepoById } from "../core/repos.ts";
1818 import type { Repo } from "../core/repos.ts";
1919 import type { User } from "../core/users.ts";
2020 import type { EnvName } from "../apps/data.ts";
@@ -82,20 +82,48 @@ async function told(
8282 if (said === "") return refuse(session, SAY_SOMETHING_WORDS);
8383 // A claimed forge's first ask makes a new app, as the page's does:
8484 // never an issue on the forge's own source.
85 if (appRepo === undefined && (await isFirstAsk(app, user))) return firstTold(app, session, user, said);
85 const named = namedRepo(app, user, said, appRepo);
outdated

Compute namedRepo once. This line is over-long and calls it again two lines below.

86 if (appRepo === undefined && named === undefined && (await isFirstAsk(app, user)))
87 return firstTold(app, session, user, said);
8688 const [owner = "", name = ""] = (app.config.forgeRepo ?? "").split("/");
87 const repo = appRepo ?? getRepo(app.db, owner, name);
89 const repo = named?.repo ?? appRepo ?? getRepo(app.db, owner, name);
8890 if (repo === undefined) return refuse(session, NO_CREW_WORDS);
89 const result = await tell(app, user, repo, said, 1, from, from !== null);
91 const sentence = named?.words ?? said;
92 const result = await tell(app, user, repo, sentence, 1, from, from !== null);
9093 const answer = tellAnswer(result);
9194 if (!result.ok) return refuse(session, answer.text);
9295 const base = app.config.url ?? `http://localhost:${app.config.port ?? 3000}`;
96 // A first word shaped like owner/name that named nothing readable went in
97 // as words: say where, so a typo is seen and not only posted.
98 const missed = named === undefined && appRepo === undefined && LOOKS_NAMED.test(said);
99 const landed = missed ? `no repository ${said.split(/\s/)[0]} you can read; told in ${repo.ownerName}/${repo.name}${CRLF}` : "";
93100 session.write(
94 `${answer.text}${CRLF}${base}/${repo.ownerName}/${repo.name}/issues/${result.value.issue.number}${CRLF}`,
101 `${landed}${answer.text}${CRLF}${base}/${repo.ownerName}/${repo.name}/issues/${result.value.issue.number}${CRLF}`,
95102 );
96103 session.exit(0);
97104 }
98105
106 /**
107 * `tell owner/name words`: a first word that names a repository the person
108 * can read, with words after it, aims the tell there. Anything else is all
109 * words for the forge's own repository, so a sentence is never lost.
110 */
111 const LOOKS_NAMED = /^[A-Za-z0-9][\w.-]*\/[\w.-]+[ \t]+\S/;
112
113 function namedRepo(
114 app: App,
115 user: User,
116 said: string,
117 appRepo: Repo | undefined,
118 ): { repo: Repo; words: string } | undefined {
119 if (appRepo !== undefined) return undefined;
120 const m = /^([A-Za-z0-9][\w.-]*)\/([\w.-]+)[ \t]+(\S[\s\S]*)$/.exec(said);
121 if (m === null) return undefined;
122 const repo = getRepo(app.db, m[1]!, m[2]!);
123 if (repo === undefined || !canRead(app.db, repo, user)) return undefined;
124 return { repo, words: m[3]! };
125 }
126
99127 /** Whether this is the person's first ask on a forge spawned for them: it makes an app. */
100128 function isFirstAsk(app: App, user: User): Promise<boolean> {
101129 return asksMakeANewApp(app, user);
test/ssh-tell-named-first-ask.test.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * `ssh <forge> tell owner/name words` on a forge whose first ask would make a
3 * new app (#13685): the named repository wins and no app is made.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createOrg } from "../src/core/orgs.ts";
12 import { addKey, fingerprint, parseAuthorizedKey } from "../src/core/keys.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { forgeSshSession } from "../src/tui/ssh.ts";
15 import type { SshSession } from "../src/ssh/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDo carol";
21
22 let dir = "";
23 let app: App;
24
25 const exec = async (command: string) => {
26 const parsed = parseAuthorizedKey(KEY);
27 if (!parsed.ok) throw new Error("key");
28 let out = "";
29 let err = "";
30 let code: number | undefined;
31 await new Promise<void>((resolve) => {
32 const session: SshSession = {
33 key: { algo: parsed.value.algo, blob: parsed.value.blob, fingerprint: fingerprint(parsed.value.blob), line: KEY },
34 username: "whoever",
35 remoteAddress: "203.0.113.9",
36 kind: "exec",
37 command,
38 term: undefined,
39 env: {},
40 cols: 0,
41 rows: 0,
42 widthPx: 0,
43 heightPx: 0,
44 ended: false,
45 pending: 0,
46 write: (d: Uint8Array | string) => void (out += typeof d === "string" ? d : Buffer.from(d).toString()),
47 writeStderr: (d: string) => void (err += d),
48 onData() {},
49 onResize() {},
50 onEof() {},
51 onClose() {},
52 exit(c: number) {
53 code ??= c;
54 resolve();
55 },
56 drain: async () => {},
57 };
58 forgeSshSession(app)(session);
59 });
60 return { out, err, code };
61 };
62
63 const issuesOn = (name: string) =>
64 app.db
65 .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue WHERE repo_id = (SELECT id FROM repo WHERE name = ?1)")
66 .get(name)!.n;
67
68 beforeAll(async () => {
69 dir = await mkdtemp(join(tmpdir(), "forge-ssh-named-"));
70 app = createApp({ dataDir: dir, port: 0, forgeRepo: "carol/forge", url: "https://forge.test" });
71 const u = await createUser(app.db, {
72 origin: "seed",
73 trusted: true,
74 username: "carol",
75 email: "[email protected]",
76 password: "a-good-passphrase",
77 adminIfFirst: true,
78 });
79 if (!u.ok) throw new Error(u.error);
80 const parsed = parseAuthorizedKey(KEY);
81 if (!parsed.ok) throw new Error("key");
82 addKey(app.db, u.value.id, "laptop", parsed.value);
83 const org = createOrg(app.db, "kin", u.value.id);
84 if (!org.ok) throw new Error(org.error);
85 await Bun.write(join(dir, "parent.json"), JSON.stringify({ org: "kin" }));
86 const made = await createRepo(app, u.value, { owner: "carol", name: "forge" });
87 if (!made.ok) throw new Error(made.error);
88 });
89
90 afterAll(async () => {
91 app.close();
92 await rm(dir, { recursive: true, force: true });
93 });
94
95 test("a named repository skips the first ask: it tells there and makes no app", async () => {
96 const named = await exec("tell carol/forge fix the footer");
97 expect(named.code).toBe(0);
98 expect(named.out).toContain("/carol/forge/issues/1");
99 expect(issuesOn("forge")).toBe(1);
100 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM repo").get()!.n).toBe(1);
101 });
test/ssh-tell.test.ts +31 −1
@@ -15,7 +15,7 @@ import { addKey, fingerprint, parseAuthorizedKey } from "../src/core/keys.ts";
1515 import { getRepo } from "../src/core/repos.ts";
1616 import { AppsRuntime } from "../src/apps/runtime.ts";
1717 import { appForLogin } from "../src/apps/tty.ts";
18 import { createUser } from "../src/core/users.ts";
18 import { createUser, getUserByName } from "../src/core/users.ts";
1919 import { forgeSshSession } from "../src/tui/ssh.ts";
2020 import { DIRECTION_NOTE } from "../src/crew/direct.ts";
2121 import { GUEST_RATE_WORDS } from "../src/tui/ssh-guest-rate.ts";
@@ -35,6 +35,10 @@ describe("ssh forge tell", () => {
3535 const issues = () =>
3636 app.db.query<{ title: string; body: string }, []>("SELECT title, body FROM issue ORDER BY number").all();
3737
38 const titlesIn = (repoId: string) =>
39 app.db.query<{ title: string }, [string]>("SELECT title FROM issue WHERE repo_id = ?1 ORDER BY number").all(repoId).map((r) => r.title);
40 const forgeId = () => getRepo(app.db, "alice", "forge")!.id;
41
3842 const exec = async (key: string, command: string, username = "whoever") => {
3943 const parsed = parseAuthorizedKey(key);
4044 if (!parsed.ok) throw new Error("key");
@@ -233,4 +237,30 @@ describe("ssh forge tell", () => {
233237 const known = await exec(KEY_A, "tell still allowed");
234238 expect(known.err).not.toContain(GUEST_RATE_WORDS);
235239 });
240
241 test("a leading owner/name aims the tell at that repository; an unknown one stays words and says where", async () => {
242 const made = await createRepo(app, getUserByName(app.db, "alice")!, { owner: "alice", name: "notes" });
243 if (!made.ok) throw new Error("repo");
244 const r = await exec(KEY_A, "tell alice/notes add a footer");
245 expect(r.code).toBe(0);
246 expect(r.out).toContain("https://forge.test/alice/notes/issues/1");
247 expect(titlesIn(made.value.id)).toEqual(["add a footer"]);
248 const odd = await exec(KEY_A, "tell nobody/nothing add a footer");
249 expect(odd.out).toContain("no repository nobody/nothing you can read; told in alice/forge");
250 expect(odd.out).toContain("/alice/forge/issues/");
251 expect(titlesIn(forgeId())).toContain("nobody/nothing add a footer");
252 });
253
254 test("a private repository the key cannot read is not told into: the words go to the forge repo whole", async () => {
255 const made = await createRepo(app, getUserByName(app.db, "alice")!, { owner: "alice", name: "private" });
256 if (!made.ok) throw new Error("repo");
257 app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(made.value.id);
258 const r = await exec(KEY_B, "tell alice/private add a footer");
259 expect(titlesIn(made.value.id)).toEqual([]);
260 expect(r.out).toContain("no repository alice/private you can read; told in alice/forge");
261 expect(titlesIn(forgeId())).toContain("alice/private add a footer");
262 // The owner can read it, so for them the same words go in.
263 await exec(KEY_A, "tell alice/private secret footer");
264 expect(titlesIn(made.value.id)).toEqual(["secret footer"]);
265 });
236266 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs