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

Remove "asks": what needs a person is an issue or a pull request assigned to… #17023

opened this in answer to

Merged 29h 25m ago, live in production

torque/forge:torque/16229-remove-asks-what-needs-a-person-is-an-is → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/16229-remove-asks-what-needs-a-person-is-an-is was merged into main as 8fc1791.

Review

Sign in to review this change.
70 files changed +299 −3866
docs/MCP.md −1
@@ -442,7 +442,6 @@ answers
442442 | `ui://forge/pull` | `pull` | One pull: state, check, conflicts, head → base, preview link. |
443443 | `ui://forge/pulls` | `pulls` | Pulls, at most 20: `#N title`, state, check and review word, each linked. |
444444 | `ui://forge/runs` | `runs` | Recent runs, newest first, linked to their logs. |
445 | `ui://forge/asked` | `asked` | What people asked the crew for and where each ask stands. |
446445 | `ui://forge/explore` | `explore` | Apps, people and forges ranked, at most 20: name, kind, the numbers (and likes or ship time when sorted by them), linked; only what you may see. With `kind: tree`: upstream, this and fork rows, each with how it follows and linked to its repository. |
447446 | `ui://forge/issue` | `issue` | One issue: title, state, assignee, labels, what it waits for. |
448447 | `ui://forge/flow` | `flow` | The pipeline: per stage counts, oldest waiting, the bottleneck. `{ kind: "lanes" }` (a forge admin who is a person): each home lane's now and typical seconds and the slowest lane. |
docs/REFERENCE.md −1
@@ -576,7 +576,6 @@ This page is the front door. Everything else is a file of its own under
576576 - Under each queued repository's merge-queue line, the terminal Flow dialog lists its last five gates, newest first: the pulls carried, `green`, `red` or `cut off`, how long ago, and for a red gate the first failing test with its file, `flaky` when two gates sharing no pull failed it (`src/checks/gate_result.ts`, as MCP `queue_gates` reads them); a repository with none kept says `no gates yet`, and an agent reader sees public repositories only.
577577 - The flow panel on `/boards` has a Last gates card: the newest ten merge-queue gates, each with its pulls linked, green, red or cut off, and the first failing test with its first error line (or the reason a gate was cut off). A gate carrying a sealed pull shows `a sealed pull` and the verdict alone; a non-admin reader sees public repositories only (`src/web/pages/boards-gates.ts`, the same `recentGates` read as MCP `queue_gates`).
578578 - The flow panel on `/boards` and the terminal Flow dialog say how the open crew pulls sort into piles (red, conflicted, changes asked, approved and waiting, awaiting review), each pull counted once in the first pile it fits (`src/flow/pile.ts`).
579 - On the terminal's Asked screen, Enter on a thought opens a card of what became of it, as MCP `thought` answers: the issue it placed (Enter opens it), "kept as a note" or "not placed yet", and the thoughts it repeats or takes back and the later ones that did the same to it. A repository you cannot read is named as nothing, and a thought that is not yours or is gone says "No such thought". The card is a snapshot; `r` re-reads it (`src/tui/screens/asked.ts`).
580579 - The off-box snapshot mirror is set from three doors with one set of rules (`src/actions/mirror.ts`): Settings → Backups, MCP `mirror_set` (`set` or `forget`), and the terminal's Resilience screen (a forge admin who is a person; an admin agent only reads). The screen shows `Mirror: <place>` or `Mirror: none.`, `m` seals it with five prompts (endpoint, bucket, region, access key, secret key; the keys are masked as typed) where a blank keeps what was sealed, and `f` forgets it after a confirm. `t` tests where snapshots go, as MCP `backups_test` and the Backups page's Test button do: the sealed destination, otherwise the environment's, said as `Reached …: N objects listed.` or `Could not list …: <reason>` in the page's words; with none set it says so and calls nobody. A key is never read back or drawn.
581580 - [`docs/PLANNING.md`](PLANNING.md) — how issues depend on issues: the edge, the map, and what "ready now" means to a person and to the crew.
582581 - [`docs/FLEET.md`](FLEET.md) — one change across many repositories, runs or issues: a query, a dry-run plan of every row before → after, a receipt, and undo.
docs/STUDIO.md +2 −25
@@ -348,32 +348,9 @@ so the numbers agree. Each card's words, forms and buttons are drawn in
348348 `src/web/studio/decisions.ts`. It is server-rendered and every button is a form post,
349349 so it works without JavaScript.
350350
351 ## What you asked for
351 ## What you opened
352352
353 `/asked` (`askedPage`, `src/web/studio/asked_page.ts`) is the other
354 direction: not what waits on you, but what you and your people asked of the
355 crew, and whether it happened. One row per issue a person opened (an
356 agent's issue is not an ask; neither is the direction issue) in every
357 repository the viewer can write — by default only what has nothing merged
358 yet, oldest first, because the path is "open the oldest unmet ask": who
359 asked and when, the pull that answers it, when the crew last ran or spoke on
360 it, and one word — _Waiting_, _Building_ (a pull is open or the crew
361 is running), _Shipped_ (a pull that closes it merged), _Closed_ (closed with
362 nothing merged). An ask still waiting after three days carries _Nothing
363 built_, in red: no pull for it is open or merged and nobody is on it. One
364 whose pull is still open after three days says _Pull open_ and how long the
365 pull has been open. `?show=flagged|all` changes the view, `?order=newest` flips it,
366 `?repo=owner/name` keeps it to one repository. The rows are derived on read
367 in `src/core/asked.ts`, and `/api/v1/asked` and the MCP `asked` tool answer
368 the same rows. Above the asks, the same page
369 shows the viewer's own thoughts, newest first and verbatim (`src/core/thought_stream.ts`):
370 time, source, the issues the planner placed each on, and one word — _Heard_
371 (not yet placed), _Placed_, _Building_, _Shipped_ (a placed issue's pull
372 merged) or _Superseded_ (a later thought marked what it placed superseded,
373 and the row says which). A thought with something placed and nothing merged
374 more than N days after placement (the `thoughtFlagDays` user setting, 3 by
375 default) is _Nothing built_; the one primary button opens the oldest such
376 thought's placed issue. `/api/v1/asked` and the MCP `asked` tool return them as `thoughts`. A placement in a repository the viewer cannot read shows no title, state or name. It is reached from the feed's header, the board, the asks page and the palette.
353 `/asked` redirects to `/feed?show=mine` (#16229): an issue or a pull request is what a person opened, and the feed narrowed to theirs lists it. The page, `/api/v1/asked`, the MCP `asked` tool and the terminal's Asked screen are gone. A thought's placements and state stay on `/notes` and in MCP `thought` (`src/core/thought_stream.ts`).
377354
378355 ## The home
379356
docs/TOUR.md +5 −15
@@ -26,7 +26,7 @@ ssh -p 2222 localhost tell make the header blue # tell the crew in one line
2626
2727 `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.
2828
29 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>`.
29 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 your feed's mine view (`/feed?show=mine`) show `Told from <address>`.
3030
3131 An app's open pulls, newest five first, one line each (`#n title · green|red|running|none`), need no tty: run `pulls` on the app's login — `ssh <app>@<forge> pulls`, with the app's page printing the exact command as `FORGE_APP_SSH` (the terminal is off when that is unset). A private app answers only a key its gate admits; sealed pulls show to their author, writers and the crew (`src/apps/door_pulls.ts`).
3232
@@ -128,18 +128,9 @@ copy. Both read `live` on the row from `clientAppRows`, which is set only while
128128 production runs; an app that is not running offers neither and says nothing
129129 about why.
130130
131 ## Asked, review, a client's forge and the family
131 ## Review, a client's forge and the family
132132
133 What you asked for: `Ctrl+K`, then **Asked**, is `/asked` in the terminal — your
134 thoughts, then the issues you can write to that are not shipped, oldest first,
135 as MCP `asked` defaults to. `s` cycles not shipped → flagged → all and `o` flips
136 oldest/newest first, the title saying which; each row says the ask's state
137 (waiting, building, shipped, closed) and stale or flagged in MCP's words. The
138 rows keep MCP's order in every view, so the terminal and an agent read the same
139 list; the web page `/asked` groups what needs you first instead
140 (`j`/`k` move, `enter` gives the issue's web address, `r` refreshes). It is read
141 only, shows a guest nothing, and names nothing of a placement in a repository
142 you cannot read.
133 What you opened: `/asked` is the feed narrowed to your own (`/feed?show=mine`). What needs you is an issue or a pull request assigned to you, or one whose review is asked of you (#16229).
143134
144135 Review: `/review` lists the asks waiting on you, one row each (title, repository,
145136 age, why, and the crew's advice or that it has not advised yet), newest first. A pull's row also carries the check verdict for its head (the pull page's badge: passed, failed, running, cancelled, or none) in the row's trail, and, when its repository is an app, an "Open the preview" link under it (shown for any app, even before a preview is deployed); and, when the pull has a look the viewer may fetch, its preview thumbnail beside production's under that (sized, lazy, never inside the row's link; the pull's is the only link, named for a screen reader, and production's is a named picture; a viewer who may not fetch it sees none); all of it comes from the database, never git. The row's trail also says the pull's size (`3 files changed, +40 −7`), kept per base and head commit (`src/web/studio/review_evidence.ts`); a request never waits on git: until the stat is kept the row says "Diff loading — reload for the size" while the app computes it in the background (at most 4 at once, stopped by closing the app), and a failed stat says "Diff size unavailable" and is not asked again for a minute, so a bad pull cannot spawn git on every visit. Visits while a stat is running share it. Each row also carries its actions under it, as plain form POSTs to `/review/act` (same-origin checked, `rw` scope): on a pull **Merge** (through the same landing gate as anywhere, so a red or unreviewed head is refused with the gate's sentence), **Close**, **Request changes** (with a text box) and **Reply** (with a text box); on an issue **Close** and **Reply**. After an action the page answers 303 to `/review#<the next ask>` (the first that followed it and still waits, else the first left, else `/review`), and the acted ask is gone; a refusal comes back to the same row with its reason. Keys: `j`/`k` move between rows, and on the focused row `m` merges, `c` closes and `r` jumps to the Request-changes box; keys are ignored while a text box has focus, and `?` lists them. `/asks` links to it, and signed out it sends you to sign-in. The terminal has no page of its
@@ -424,9 +415,8 @@ to the front of the ready order, unless that issue is deferred or closed, which
424415 the reply says. A close restatement counts only when the planner reads it as
425416 plain work and nothing in it negates or flips the earlier one; "don't make X"
426417 after "make X" is a reversal, never a repeat. A reversal links the thoughts it
427 takes back (`supersedes`). `/asked` shows "said again, first on …", "takes back
428 …" and "superseded by …" under each thought, and the MCP `thought` tool returns
429 `repeats`, `supersedes`, `repeatedBy` and `supersededBy` thought ids.
418 takes back (`supersedes`). Only the MCP `thought` tool shows these links: it returns
outdated

Principle 1 (say one true thing). This now says the notes page shows "said again, first on …", "takes back …" and "superseded by …". src/web/pages/notes.ts and src/tui/screens/thoughtnotes.ts render none of those words: they were drawn only by the deleted /asked page and the deleted thoughtNotes helper. Either say they are only in the MCP thought fields (repeats, supersedes, repeatedBy, supersededBy), or draw them on /notes. Do not leave a claim the product does not meet.

419 `repeats`, `supersedes`, `repeatedBy` and `supersededBy` thought ids. The notes page does not draw them.
430420
431421 ## Link-preview cards
432422
docs/design/audit.md −1
@@ -67,7 +67,6 @@ Machine routes are not pages and have no entry: `/audit.csv`,
6767 - `/asks` — `studio/asks_page.ts` · what the crew is waiting on me for · `/` "needs me" list · colours 2.
6868 - `/data` — `pages/data.ts` · the SQLite files I may see, their tables and rows, secrets masked · `/system` · none seen.
6969 - `/dataset` — `pages/dataset.ts` · what the forge's dataset holds and what it already answers, admin only · Settings, Dataset · none seen.
70 - `/asked` — `studio/asked_page.ts` · what I answered, as a record · `/asks` · none seen.
7170 - `/review` — `studio/review_page.ts` · every ask waiting on me, one row each, newest first · `/asks` (same asks, with buttons) · none seen.
7271 - `/flow` — `pages/flow.ts` · the pipeline from ready issue to live deploy, and the bottleneck · `/system`, `/board`, `/` · none seen. A topbar button points here.
7372 - `/talk` — `pages/talk.ts` · the person's one conversation with the forge: history, composer, Do it and Not now; replies stream in over `/talk/stream` · `/settings/confirms` (the same yes, as a list), the home tell box (one line to an app's crew) · none seen; styles in `docs/design/areas/talk.md`.
docs/features/home-frame.md +1 −1
@@ -5,7 +5,7 @@ row: Home paints its frame first
55 # Home paints its frame first (#7660)
66
77 Signed in, `/` answers from memory. Its slow regions — `kpis` (figures, vitals,
8 clog, alarms), `waiting`, `panels`, `asked` (the tab's count) and `feed` — are
8 clog, alarms), `waiting`, `panels` and `feed` — are
99 kept per viewer as last drawn (`src/core/region_memory.ts`, driven by
1010 `src/web/studio/home_last.ts`).
1111
plugins/claude-code/.claude-plugin/plugin.json +1 −1
@@ -1,7 +1,7 @@
11 {
22 "name": "forge",
33 "version": "0.2.0",
4 "description": "Your forge inside Claude Code: its MCP server and a /forge command (new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, asked, waves, held, forks).",
4 "description": "Your forge inside Claude Code: its MCP server and a /forge command (new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, waves, held, forks).",
55 "mcpServers": {
66 "forge": {
77 "type": "http",
plugins/claude-code/README.md +1 −7
@@ -8,7 +8,7 @@ claude plugin marketplace add $FORGE_URL/plugins/claude-code/marketplace.json &&
88
99 The forge serves that marketplace manifest (name `forge`, one plugin `forge`, fetched by Claude Code as the `plugins/claude-code` subdirectory of the forge's public source repository). Inside Claude Code, the same from the repository: `/plugin marketplace add $FORGE_URL/trevato/forge.git` then `/plugin install forge@forge`. Then set `FORGE_URL` (the forge's address, no trailing slash) in your environment. From a clone, `claude --plugin-dir plugins/claude-code` loads it locally instead. It registers the forge's MCP
1010 server and a `/forge` command: `new`, `tell`, `status`, `decide`, `archive`, `undo`, `plan`, `preview`,
11 `pulls`, `runs`, `log`, `asked`, `waves`, `held`, `forks`.
11 `pulls`, `runs`, `log`, `waves`, `held`, `forks`.
1212
1313 **Sign in (nothing to copy).** The `forge` server sends no Authorization header, so Claude Code takes the forge's OAuth sign-in: open `/mcp` in Claude Code, choose `forge`, and approve in the browser.
1414
@@ -31,12 +31,6 @@ and the last three finished, one line each (kind, issue or pull, state, how
3131 long), through MCP `runs`. `/forge log <app> <run>` relays that run's last 40
3232 lines verbatim, through MCP `run_log`.
3333
34 `/forge asked [app]` says what you asked the crew for and what became of
35 each, shipped ones included: one line per ask (what, waiting/building/shipped/closed,
36 the pull that closes it, and the outcome sentence: landed, who is building,
37 parked and why, failed), flagged ones first, through MCP `asked` with
38 `show: "all"`; with an app, only that app's asks.
39
4034 `/forge waves <app>` relays the app's newest three waves (version, date, headline), through MCP `waves`. `/forge held` says how many themes the Later gate holds and which are done, through MCP `held`; it only reads. `/forge forks <app>` says in two lines what the app follows upstream and who follows it downstream, through MCP `forks` with `kind: "chain"`. None of them lands or closes anything.
4135
4236 `test/plugins.test.ts` fails when this plugin names an MCP tool the forge does not list, so a rename in `src/http/mcp.ts` cannot leave it behind.
plugins/claude-code/commands/forge.md +2 −3
@@ -1,6 +1,6 @@
11 ---
2 description: Talk to your forge: new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, asked, waves, held, forks
3 argument-hint: new <name> <words> | tell <app> <words> | status | decide <approve|redirect|decline> [words] | decide all <dismiss|ship|close> [kind] | archive <app> | undo <operation> | plan [approve|redirect <words>|later] | preview <url> | pulls <app> | runs <app> | log <app> <run> | asked [app] | waves <app> | held | forks <app>
2 description: Talk to your forge: new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, waves, held, forks
3 argument-hint: new <name> <words> | tell <app> <words> | status | decide <approve|redirect|decline> [words] | decide all <dismiss|ship|close> [kind] | archive <app> | undo <operation> | plan [approve|redirect <words>|later] | preview <url> | pulls <app> | runs <app> | log <app> <run> | waves <app> | held | forks <app>
44 ---
55
66 Use the `forge` MCP server's tools for `$ARGUMENTS`.
@@ -17,7 +17,6 @@ Use the `forge` MCP server's tools for `$ARGUMENTS`.
1717 - `pulls <app>`: call `pulls` with `repo` = the app (owner/name); list the open pulls, one line each with its check.
1818 - `runs <app>`: call `runs` with `repo` = the app (owner/name); say, one line each, the running runs and the last three finished ones: kind, issue or pull number, state, and how long (from `startedAt` to `endedAt`, or to now while running).
1919 - `log <app> <run>`: call `run_log` with `repo` = the app, `run` = the run id and `tail` = 40; relay the lines verbatim, in a code block.
20 - `asked [app]`: call `asked` with `show` = `all`, and `repo` = the app (owner/name) when one is given; say, one line each, flagged ones first, what was asked (its title and number), its state (waiting, building, shipped or closed), the pull that closes it (none yet: say so) and the `outcomeText` sentence, so a parked or failed ask says why.
2120 - `waves <app>`: call `waves` with `repo` = the app (owner/name); relay the newest three waves, one line each: version, date, headline. Read-only: it lands nothing.
2221 - `held`: call `held` with `app` = the app the conversation names (owner/name); when none is named, ask which app before calling, since `held` needs one (never `apply`); say in two sentences how many themes the Later gate holds and which are done (the issues in `approve`, found done on main). Read-only: never close or land anything; closing is the person's, on the page.
2322 - `forks <app>`: call `forks` with `repo` = the app (owner/name) and `kind: "chain"`; say in two lines what it follows upstream (its parent and grandparent, or that it follows none) and who follows it downstream (its children, or none), noting a severed link. Read-only.
plugins/opencode/README.md +1 −7
@@ -4,7 +4,7 @@ Fetch `forge.ts` into `.opencode/plugin/` (or list this package under `plugin`
44 in `opencode.json`), and set `FORGE_URL` and `FORGE_TOKEN` (make the token at `/settings/tokens` on the forge, which shows the line with its own address filled in):
55 `mkdir -p .opencode/plugin && curl -fsSo .opencode/plugin/forge.ts <forge>/plugins/opencode/forge.ts && FORGE_URL=<forge> FORGE_TOKEN=<token> opencode`, where `<forge>` is the forge's own origin (it serves this file). It registers the
66 forge's MCP server and the `forge` command: `new`, `tell`, `status`, `decide`, `archive`, `undo`, `plan`,
7 `preview`, `pulls`, `runs`, `log`, `asked`, `waves`, `held`, `forks`.
7 `preview`, `pulls`, `runs`, `log`, `waves`, `held`, `forks`.
88 `/forge archive <app>` plans archiving the app, then archives it after you say yes (put away, not deleted; the receipt says how to wake it). `/forge decide all <dismiss|ship|close> [kind]` plans the same action over every waiting ask (of that kind), says how many and which, applies after a yes and prints the `operation` id; `/forge undo <operation>` reverses it.
99
1010 `/forge plan` shows the planner's next wave (the first wave-proposal row of `asks`);
@@ -22,12 +22,6 @@ and the last three finished, one line each (kind, issue or pull, state, how
2222 long), through MCP `runs`. `/forge log <app> <run>` relays that run's last 40
2323 lines verbatim, through MCP `run_log`.
2424
25 `/forge asked [app]` says what you asked the crew for and what became of
26 each, shipped ones included: one line per ask (what, waiting/building/shipped/closed,
27 the pull that closes it, and the outcome sentence: landed, who is building,
28 parked and why, failed), flagged ones first, through MCP `asked` with
29 `show: "all"`; with an app, only that app's asks.
30
3125 Two ways to connect. With only `FORGE_URL` set, the plugin registers the MCP
3226 server with no Authorization header and `oauth: {}`, so OpenCode signs in
3327 through the forge's OAuth (run `opencode mcp auth forge`). With `FORGE_TOKEN`
plugins/opencode/forge.ts +2 −3
@@ -1,6 +1,6 @@
11 /**
22 * forge for OpenCode: registers the forge's MCP server and a `forge`
3 * command (new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, asked, waves, held, forks). Set FORGE_URL, and FORGE_TOKEN too
3 * command (new, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, waves, held, forks). Set FORGE_URL, and FORGE_TOKEN too
44 * to skip the OAuth sign-in.
55 * No logic lives here: the tools are the forge's own (`docs/MCP.md`).
66 */
@@ -20,7 +20,6 @@ const COMMAND = `Use the forge MCP tools for: $ARGUMENTS
2020 - pulls <app>: call \`pulls\` with repo; list the open pulls, one line each with its check.
2121 - runs <app>: call \`runs\` with repo; say, one line each, the running runs and the last three finished: kind, issue or pull number, state, how long (startedAt to endedAt, or to now).
2222 - log <app> <run>: call \`run_log\` with repo, run (the run id) and \`tail\` 40; relay the lines verbatim.
23 - asked [app]: call \`asked\` with \`show\` \`all\`, and repo when an app is given; say, one line each, flagged ones first, what was asked (title and number), its state (waiting, building, shipped or closed), the pull that closes it and the \`outcomeText\` sentence, so a parked or failed ask says why.
2423 - waves <app>: call \`waves\` with repo; relay the newest three waves, one line each: version, date, headline. Read-only: it lands nothing.
2524 - held: call \`held\` with app = the app the conversation names; when none is named, ask which app before calling, since \`held\` needs one (never \`apply\`); say in two sentences how many themes the Later gate holds and which are done (the issues in \`approve\`). Read-only: never close or land anything.
2625 - forks <app>: call \`forks\` with repo and kind "chain"; say in two lines what it follows upstream (parent, grandparent, or none) and who follows it downstream (children, or none), noting a severed link. Read-only.
@@ -144,7 +143,7 @@ export const forgePlugin = (load?: () => Promise<any>): Plugin => async () => ({
144143 };
145144 config["command"] = {
146145 ...config["command"],
147 forge: { description: "New, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, asked, waves, held or forks on your forge", template: COMMAND },
146 forge: { description: "New, tell, status, decide, archive, undo, plan, preview, pulls, runs, log, waves, held or forks on your forge", template: COMMAND },
148147 };
149148 },
150149 });
src/actions/ask_state_words.ts −82
@@ -4,15 +4,6 @@
44 * terminal. Plain strings: each caller escapes them as its surface does.
55 */
66
7 /** An ask the planner has not yet put on any issue, and nobody has replied to. */
8 export const NOT_PLACED_YET = "the planner has not placed it yet";
9
10 /** A thought the planner has not placed yet, as its row on /asked ends. */
11 export const NOT_PLACED = "not placed yet";
12
13 /** A thought the planner placed on no issue: a vision, a decision, a note. */
14 export const KEPT_AS_NOTE = "kept as a note";
15
167 /** An ask whose issue has a run going and no answer yet. */
178 export const CREW_WORKING = "The crew is working on it.";
189
@@ -23,76 +14,3 @@ export const cut = (raw: string, n: number): string => {
2314 const space = text.lastIndexOf(" ", n - 1);
2415 return `${text.slice(0, space > 0 ? space : n - 1)}…`;
2516 };
26
27 /** One piece of where a thought went: `lead` plain, `text` linked to `href` where the surface links. */
28 export interface WherePart {
29 readonly lead: string;
30 readonly text: string;
31 readonly href?: string;
32 }
33
34 /** What `whereItWent` reads of a thought, so the words need nothing but plain data. */
35 export interface ThoughtWhere {
36 readonly reply: string | null;
37 readonly asked: boolean;
38 readonly placedAt: string | null;
39 readonly placed: readonly {
40 readonly action: string;
41 readonly repo: string;
42 readonly number: number;
43 readonly pull?: number;
44 readonly readable: boolean;
45 readonly title: string | null;
46 }[];
47 }
48
49 const ACTED = new Set(["opened", "linked"]);
50
51 /**
52 * Where a thought went, as MCP `thought` answers it (#7509), in the same words
53 * on /asked and in the terminal: `→` each issue it placed; the planner's
54 * question when it answered with one; `kept as a note` when it placed it on
55 * none; `not placed yet` until it has.
56 */
57 export function whereItWent(t: ThoughtWhere): WherePart[] {
58 if (t.placed.length === 0) {
59 if (t.placedAt === null) return [{ lead: NOT_PLACED, text: "" }];
60 if (t.asked && t.reply) return [{ lead: t.reply, text: "" }];
61 return [{ lead: KEPT_AS_NOTE, text: "" }];
62 }
63 return t.placed.map((x) => {
64 const act = ACTED.has(x.action) ? "" : `${x.action} `;
65 if (!x.readable) return { lead: `→ ${act}in a repository you cannot read`, text: "" };
66 if (x.title === null) return { lead: `→ ${act}${x.repo}#${x.number}`, text: "" };
67 return {
68 lead: `→ ${act}`,
69 text: `${x.repo}#${x.number} ${cut(x.title, 60)}`,
70 href: `/${x.repo}/${x.pull === x.number ? "pulls" : "issues"}/${x.number}`,
71 };
72 });
73 }
74
75 /** What a thought repeats, takes back, or was taken back by: the words, and the other thought's time. */
76 export interface ThoughtNote {
77 readonly text: string;
78 readonly at: string;
79 }
80
81 interface Ref {
82 readonly text: string;
83 readonly receivedAt: string;
84 }
85
86 export function thoughtNotes(t: {
87 readonly supersededBy: Ref | null;
88 readonly repeats: Ref | null;
89 readonly supersedes: readonly Ref[];
90 }): ThoughtNote[] {
91 const notes: ThoughtNote[] = [];
92 if (t.supersededBy)
93 notes.push({ text: `superseded by “${cut(t.supersededBy.text, 60)}”`, at: t.supersededBy.receivedAt });
94 if (t.repeats) notes.push({ text: `repeats “${cut(t.repeats.text, 60)}”`, at: t.repeats.receivedAt });
95 const back = t.supersedes[0];
96 if (back) notes.push({ text: `takes back “${cut(back.text, 60)}”`, at: back.receivedAt });
97 return notes;
98 }
src/contract/openapi/routes/getApiV1Asked.ts deleted −14
@@ -1,14 +0,0 @@
1 import type { Route } from "../shared.ts";
2 import { ORDER_WORDS } from "../../../core/arg_words.ts";
3
4 export const route: Route = {
5 method: "get",
6 path: "/api/v1/asked",
7 summary: "What people asked, and the caller's thought stream",
8 detail: "What people asked, and the caller's thought stream; answers { asked, thoughts } (ro scope)",
9 auth: true,
10 role: "member",
11 query: { show: "string", order: "string", repo: "string" },
12 refusals: { invalid_show: "show is all, unshipped or flagged", invalid_order: ORDER_WORDS },
13 refuses: [401],
14 };
src/contract/openapi/routes/index.ts −1
@@ -72,7 +72,6 @@ export { route as getApiV1AgentsUsername } from "./getApiV1AgentsUsername.ts";
7272 export { route as getApiV1AppTemplates } from "./getApiV1AppTemplates.ts";
7373 export { route as getApiV1Apps } from "./getApiV1Apps.ts";
7474 export { route as getApiV1AppsSlugConfig } from "./getApiV1AppsSlugConfig.ts";
75 export { route as getApiV1Asked } from "./getApiV1Asked.ts";
7675 export { route as getApiV1Asks } from "./getApiV1Asks.ts";
7776 export { route as getApiV1AsksAdmin } from "./getApiV1AsksAdmin.ts";
7877 export { route as getApiV1Boards } from "./getApiV1Boards.ts";
src/core/arg_words.ts −3
@@ -16,9 +16,6 @@ export const HIDDEN_WORDS = "hidden is true or false";
1616 /** A board pin's `op`: `pin`, `unpin` or `move`. */
1717 export const PIN_OP_WORDS = "op must be pin, unpin or move";
1818
19 /** A listing's `order`: `oldest` or `newest`. */
20 export const ORDER_WORDS = "order is oldest or newest";
21
2219 /** The forge's `signup` setting: `open`, `invite` or `closed`. */
2320 export const SIGNUP_WORDS = "signup is open, request, invite or closed";
2421
src/core/asked.ts deleted −595
@@ -1,595 +0,0 @@
1 /**
2 * What people asked for, and what became of it.
3 *
4 * An ask is an issue a person opened — never one an agent filed, never one
5 * imported from an origin under someone else's name. Each comes back with
6 * its age, the pulls that say they close it, and one state word read from
7 * those facts: `shipped` once one of them merged, `building` while one is
8 * open or the crew is running on it, `closed` when it closed with nothing
9 * merged, `waiting` otherwise. An ask that is not shipped or closed and is
10 * older than the stale window is `stale`. A stale ask that is still
11 * `waiting` is `flagged`: nothing was built for it. One with a pull open,
12 * or the crew on it, is stale and not flagged: something exists, and each
13 * pull says when it was opened so a row can say how long it has been open.
14 *
15 * Every row is derived on read from the issue, pull and run tables, so
16 * nothing here can drift from the map. `source` names where the ask came
17 * from, so the thought stream can join this list as a second source with
18 * the same row shape.
19 */
20
21 import type { Database } from "bun:sqlite";
22 import { marksByName, type Mark } from "./marks.ts";
23 import { alreadyDone, BY_CREW, PARK_LEAD, PARK_LIKE } from "./done_on_main.ts";
24 import { getIssuesByIds, type Issue } from "./issues.ts";
25 import { closesFromBody } from "./pulls.ts";
26 import { getRepo, listReposWritableTo, type Repo } from "./repos.ts";
27 import { listActiveRuns } from "./runs.ts";
28 import type { User } from "./users.ts";
29
30 /** Every state an ask can be in, in the order it moves through them. */
31 export const ASKED_STATES = ["waiting", "building", "shipped", "closed"] as const;
32 export type AskedState = (typeof ASKED_STATES)[number];
33
34 export interface AskedPull {
35 /** The pull's issue id, for reads; not part of the JSON. */
36 readonly id: string;
37 readonly number: number;
38 readonly title: string;
39 readonly state: "open" | "merged" | "closed";
40 /** When the pull was opened. */
41 readonly openedAt: string;
42 /** When it merged; null otherwise. */
43 readonly mergedAt: string | null;
44 /** Closed by the crew because it could not finish it, not by a person. */
45 readonly parked: boolean;
46 /** Who opened it. */
47 readonly author: string;
48 }
49
50 /**
51 * What became of an ask, read from its issue, pulls and runs alone:
52 * `parked` and `failed` need the owner; `building` and `unplaced` are in
53 * progress; `landed` is merged; `closed` is closed with nothing merged.
54 */
55 export type AskedOutcome =
56 | { readonly kind: "landed"; readonly pull: number; readonly at: string }
57 | { readonly kind: "building"; readonly by: string; readonly byMark?: Mark; readonly pull: number | null }
58 | { readonly kind: "parked"; readonly pull: number; readonly note: string }
59 | { readonly kind: "failed"; readonly by: string; readonly byMark?: Mark; readonly at: string }
60 | { readonly kind: "unplaced" }
61 | { readonly kind: "closed" };
62
63 export interface Asked {
64 readonly source: "issue";
65 readonly repo: Repo;
66 readonly issue: Issue;
67 /** Who asked: the issue's author. */
68 readonly askedBy: string;
69 readonly askedAt: string;
70 readonly pulls: readonly AskedPull[];
71 readonly state: AskedState;
72 /** Not shipped or closed, and older than the stale window. */
73 readonly stale: boolean;
74 /** Stale, and still waiting: no pull open or merged, and nobody on it. */
75 readonly flagged: boolean;
76 /** The crew's last word on it: its newest agent run or agent comment, on
77 * the ask or a pull that closes it. Null when the crew never touched it. */
78 readonly lastCrewAt: string | null;
79 /** The commits the crew found it done by on the base, while it waits for the asker to close it; empty otherwise. */
80 readonly doneBy: readonly string[];
81 readonly outcome: AskedOutcome;
82 }
83
84 export type AskedShow = "all" | "unshipped" | "flagged";
85
86 export const isAskedShow = (value: unknown): value is AskedShow =>
87 value === "all" || value === "unshipped" || value === "flagged";
88
89 /** Oldest first is the default: the path is "open the oldest unmet ask". */
90 export type AskedOrder = "oldest" | "newest";
91
92 export const isAskedOrder = (value: unknown): value is AskedOrder =>
93 value === "oldest" || value === "newest";
94
95 /** How long an ask may wait with nothing built before it is flagged. */
96 export const STALE_DAYS = 3;
97
98 /** The most rows one read returns. */
99 export const ASKED_LIMIT = 200;
100
101 const DAY = 24 * 60 * 60 * 1000;
102
103 /** Asks read per step of the scan. */
104 const SCAN_STEP = 500;
105
106 /** An ask with everything but the crew's last activity, which is read per page. */
107 type Scanned = Omit<Asked, "lastCrewAt" | "doneBy" | "outcome">;
108
109 const shown = (a: Scanned, show: AskedShow): boolean =>
110 show === "all" ||
111 (show === "flagged"
112 ? a.flagged
113 : a.state === "waiting" || a.state === "building");
114
115 interface AskRow {
116 id: string;
117 }
118
119 interface PullRow {
120 id: string;
121 number: number;
122 title: string;
123 body: string;
124 state: "open" | "closed";
125 created_at: string;
126 merged_at: string | null;
127 parked: number;
128 author: string;
129 }
130
131 const placeholders = (n: number, from = 1): string =>
132 Array.from({ length: n }, (_, i) => `?${i + from}`).join(",");
133
134 /**
135 * The repositories a viewer may read asks about: those they can write,
136 * narrowed to one when `repoSpec` (`owner/name`) names one of them. Any
137 * other name narrows to nothing, so a repository the viewer cannot write is
138 * indistinguishable from one that does not exist.
139 */
140 export function askedRepos(
141 db: Database,
142 viewer: User | undefined,
143 repoSpec: string | null | undefined,
144 ): readonly Repo[] {
145 const writable = listReposWritableTo(db, viewer, {
146 limit: 200,
147 withoutArchived: true,
148 });
149 if (repoSpec === null || repoSpec === undefined || repoSpec === "")
150 return writable;
151 const [owner, name, ...rest] = repoSpec.split("/");
152 const one =
153 owner && name && rest.length === 0 ? getRepo(db, owner, name) : undefined;
154 return one !== undefined && writable.some((r) => r.id === one.id)
155 ? [one]
156 : [];
157 }
158
159 /**
160 * The pulls that say they close each ask, keyed `repoId#number`: every pull
161 * in these repositories, read once — the one join `scan` and `askedCounts`
162 * share, so a count can never disagree with the list.
163 */
164 export function pullsByAsk(
165 db: Database,
166 repoIds: readonly string[],
167 ): Map<string, AskedPull[]> {
168 const pulls = new Map<string, AskedPull[]>();
169 const rows = db
170 .query<PullRow & { repo_id: string }, string[]>(
171 `SELECT issue.id, issue.repo_id, issue.number, issue.title, issue.body, issue.state,
172 issue.created_at, issue.parked, pull.merged_at,
173 user.username AS author
174 FROM issue JOIN pull ON pull.issue_id = issue.id JOIN user ON user.id = issue.author_id
175 WHERE issue.repo_id IN (${placeholders(repoIds.length)}) AND issue.kind = 'pull'
176 AND issue.body LIKE '%#%'
177 AND (issue.body LIKE '%close%' OR issue.body LIKE '%fix%' OR issue.body LIKE '%resolve%')
178 ORDER BY issue.number`,
179 )
180 .all(...repoIds);
181 for (const row of rows)
182 for (const n of closesFromBody(row.body)) {
183 const key = `${row.repo_id}#${n}`;
184 const list = pulls.get(key) ?? [];
185 list.push({
186 id: row.id,
187 number: row.number,
188 title: row.title,
189 state:
190 row.merged_at !== null
191 ? "merged"
192 : row.state === "open"
193 ? "open"
194 : "closed",
195 openedAt: row.created_at,
196 mergedAt: row.merged_at,
197 parked: row.parked === 1,
198 author: row.author,
199 });
200 pulls.set(key, list);
201 }
202 return pulls;
203 }
204
205 /** A person's issues — not an agent's, not one imported under another name: what counts as an ask. */
206 const ASK_WHERE = (n: number) => `issue.repo_id IN (${placeholders(n)})
207 AND issue.kind = 'issue' AND user.is_agent = 0
208 AND issue.origin_author IS NULL`;
209
210 /**
211 * Every ask in these repositories, in `order`, with its state. It reads a
212 * step at a time and in the order asked for, so a caller that stops when
213 * its page is full reads no further, and one that reads on misses nothing:
214 * however many asks there are, the oldest are the first out.
215 */
216 function* scan(
217 db: Database,
218 repos: readonly Repo[],
219 order: AskedOrder,
220 now: number,
221 ): Generator<Scanned> {
222 if (repos.length === 0) return;
223 const byId = new Map(repos.map((r) => [r.id, r]));
224 const repoIds = [...byId.keys()];
225 const direction = new Set(
226 repos.flatMap((r) =>
227 r.directionIssueId === null ? [] : [r.directionIssueId],
228 ),
229 );
230
231 const pulls = pullsByAsk(db, repoIds);
232
233 const running = new Set(
234 listActiveRuns(db, repoIds).flatMap((r) =>
235 r.issueId === null ? [] : [r.issueId],
236 ),
237 );
238
239 // A person's issues: the author is not an agent and the row is native.
240 const way = order === "oldest" ? "ASC" : "DESC";
241 const step = db.query<AskRow, (string | number)[]>(
242 `SELECT issue.id FROM issue JOIN user ON user.id = issue.author_id
243 WHERE ${ASK_WHERE(repoIds.length)}
244 ORDER BY issue.created_at ${way}, issue.number ${way}, issue.id ${way}
245 LIMIT ?${repoIds.length + 1} OFFSET ?${repoIds.length + 2}`,
246 );
247 for (let offset = 0; ; offset += SCAN_STEP) {
248 const ids = step.all(...repoIds, SCAN_STEP, offset).map((r) => r.id);
249 const issues = getIssuesByIds(db, ids);
250 for (const id of ids) {
251 const issue = issues.get(id);
252 const repo = issue === undefined ? undefined : byId.get(issue.repoId);
253 if (issue === undefined || repo === undefined || direction.has(id))
254 continue;
255 const its = pulls.get(`${issue.repoId}#${issue.number}`) ?? [];
256 const state: AskedState = its.some((p) => p.state === "merged")
257 ? "shipped"
258 : its.some((p) => p.state === "open") || running.has(issue.id)
259 ? "building"
260 : issue.state === "closed"
261 ? "closed"
262 : "waiting";
263 const stale =
264 (state === "waiting" || state === "building") &&
265 now - Date.parse(issue.createdAt) > STALE_DAYS * DAY;
266 yield {
267 source: "issue",
268 repo,
269 issue,
270 askedBy: issue.authorName,
271 askedAt: issue.createdAt,
272 pulls: its,
273 state,
274 stale,
275 flagged: stale && state === "waiting",
276 };
277 }
278 if (ids.length < SCAN_STEP) return;
279 }
280 }
281
282 /**
283 * The asks in these repositories, oldest first unless `order` says newest:
284 * the first `limit` that `show` lets through. The caller decides which
285 * repositories the viewer may read this about (writers of each).
286 */
287 export function askedIn(
288 db: Database,
289 repos: readonly Repo[],
290 options: {
291 show?: AskedShow;
292 order?: AskedOrder;
293 now?: Date;
294 limit?: number;
295 } = {},
296 ): Asked[] {
297 const show = options.show ?? "unshipped";
298 const limit = Math.min(
299 Math.max(options.limit ?? ASKED_LIMIT, 1),
300 ASKED_LIMIT,
301 );
302 const page: Scanned[] = [];
303 for (const ask of scan(
304 db,
305 repos,
306 options.order ?? "oldest",
307 (options.now ?? new Date()).getTime(),
308 )) {
309 if (!shown(ask, show)) continue;
310 page.push(ask);
311 if (page.length === limit) break;
312 }
313 const last = lastCrewActivity(
314 db,
315 page.flatMap((a) => [a.issue.id, ...a.pulls.map((p) => p.id)]),
316 );
317 const done = alreadyDone(
318 db,
319 page.filter((a) => a.issue.state === "open").map((a) => a.issue.id),
320 );
321 const outcomes = outcomesOf(db, page);
322 return page.map((a) => {
323 let at: string | null = last.get(a.issue.id) ?? null;
324 for (const p of a.pulls) {
325 const t = last.get(p.id);
326 if (t !== undefined && (at === null || t > at)) at = t;
327 }
328 return {
329 ...a,
330 lastCrewAt: at,
331 doneBy: done.get(a.issue.id) ?? [],
332 outcome: outcomes.get(a.issue.id)!,
333 };
334 });
335 }
336
337 /** The first sentence of a parking note, without the crew's fixed lead-in. */
338 export function firstSentence(text: string): string {
339 const lead = text.startsWith(PARK_LEAD) ? text.slice(PARK_LEAD.length).replace(/^:\s*/, "") : text;
340 const plain = lead.replace(/\s+/g, " ").trim();
341 const end = plain.search(/[.!?](\s|$)/);
342 return end === -1 ? plain : plain.slice(0, end + 1);
343 }
344
345 type Run = { state: string; by: string; at: string };
346
347 /** The newest agent run of each issue or pull in `ids`, in grouped reads. */
348 function lastRuns(db: Database, ids: readonly string[]): Map<string, Run> {
349 const out = new Map<string, Run>();
350 for (let i = 0; i < ids.length; i += 400) {
351 const batch = ids.slice(i, i + 400);
352 for (const r of db
353 .query<{ issue_id: string; state: string; by: string | null; at: string }, string[]>(
354 `SELECT run.issue_id, run.state, user.username AS by, run.created_at AS at
355 FROM run LEFT JOIN user ON user.id = run.actor_id
356 WHERE run.kind = 'agent' AND run.issue_id IN (${placeholders(batch.length)})
357 ORDER BY run.created_at, run.id`,
358 )
359 .all(...batch))
360 out.set(r.issue_id, { state: r.state, by: r.by ?? "the crew", at: r.at });
361 }
362 return out;
363 }
364
365 /** The newest parking note on each of the pulls `ids`, in grouped reads. */
366 function parkingNotes(db: Database, ids: readonly string[]): Map<string, string> {
367 const out = new Map<string, string>();
368 for (let i = 0; i < ids.length; i += 400) {
369 const batch = ids.slice(i, i + 400);
370 for (const c of db
371 .query<{ issue_id: string; body: string }, string[]>(
372 `SELECT n.issue_id, n.body FROM comment n
373 WHERE n.body LIKE '${PARK_LIKE}' AND ${BY_CREW} AND n.issue_id IN (${placeholders(batch.length)})
374 ORDER BY n.created_at, n.id`,
375 )
376 .all(...batch))
377 out.set(c.issue_id, c.body);
378 }
379 return out;
380 }
381
382 const newest = <T>(items: readonly T[], keep: (item: T) => boolean): T | undefined => {
383 for (let i = items.length - 1; i >= 0; i--) if (keep(items[i]!)) return items[i];
384 return undefined;
385 };
386
387 /** The outcome of each ask: its pulls first, then the issue, then the newest agent run. */
388 function outcomesOf(db: Database, page: readonly Scanned[]): Map<string, AskedOutcome> {
389 const runs = lastRuns(db, page.flatMap((a) => [a.issue.id, ...a.pulls.map((p) => p.id)]));
390 const notes = parkingNotes(db, page.flatMap((a) => a.pulls.filter((p) => p.parked).map((p) => p.id)));
391 const out = new Map<string, AskedOutcome>();
392 for (const a of page) {
393 const merged = newest(a.pulls, (p) => p.state === "merged");
394 const open = newest(a.pulls, (p) => p.state === "open");
395 const parked = newest(a.pulls, (p) => p.parked);
396 let run: Run | undefined;
397 for (const id of [a.issue.id, ...a.pulls.map((p) => p.id)]) {
398 const r = runs.get(id);
399 if (r !== undefined && (run === undefined || r.at > run.at)) run = r;
400 }
401 let outcome: AskedOutcome;
402 if (merged !== undefined)
403 outcome = { kind: "landed", pull: merged.number, at: merged.mergedAt ?? merged.openedAt };
404 else if (open !== undefined) outcome = { kind: "building", by: open.author, pull: open.number };
405 else if (a.state === "building") outcome = { kind: "building", by: run?.by ?? "the crew", pull: null };
406 else if (a.state === "closed") outcome = { kind: "closed" };
407 else if (parked !== undefined)
408 outcome = { kind: "parked", pull: parked.number, note: firstSentence(notes.get(parked.id) ?? "") };
409 else if (run?.state === "failed") outcome = { kind: "failed", by: run.by, at: run.at };
410 else outcome = { kind: "unplaced" };
411 out.set(a.issue.id, outcome);
412 }
413 // A name says who it is: the mark comes from the account, never from the name.
414 const marks = marksByName(db, [...out.values()].flatMap((o) => ("by" in o ? [o.by] : [])));
415 for (const [id, o] of out) {
416 const byMark = "by" in o ? marks.get(o.by) : undefined;
417 if (byMark !== undefined && "by" in o) out.set(id, { ...o, byMark });
418 }
419 return out;
420 }
421
422 /** 0 needs the owner, 1 is in progress, 2 landed, 3 closed with nothing merged. */
423 export function askedTier(a: Asked): 0 | 1 | 2 | 3 {
424 if (a.doneBy.length > 0 && a.outcome.kind !== "closed") return 0;
425 switch (a.outcome.kind) {
426 case "parked":
427 case "failed":
428 return 0;
429 case "building":
430 case "unplaced":
431 return 1;
432 case "landed":
433 return 2;
434 case "closed":
435 return 3;
436 }
437 }
438
439 /** A name with its mark word, as the terminal and the API print it. */
440 const named = (by: string, mark: Mark | undefined): string => (mark === undefined ? by : `${by} (${mark})`);
441
442 /** What became of the ask as plain words, for the terminal; the page links the same words. */
443 export function outcomeText(a: Asked): string {
444 if (a.doneBy.length > 0)
445 return `on main in ${a.doneBy.map((o) => o.slice(0, 7)).join(", ")}, waiting for you to close it`;
446 const o = a.outcome;
447 switch (o.kind) {
448 case "landed":
449 return `landed in #${o.pull}`;
450 case "building":
451 return o.pull === null ? `${named(o.by, o.byMark)} building` : `${named(o.by, o.byMark)} building in #${o.pull}`;
452 case "parked":
453 return `parked: ${o.note === "" ? "no note left" : o.note}`;
454 case "failed":
455 return `${named(o.by, o.byMark)} failed`;
456 case "unplaced":
457 return "not placed yet";
458 case "closed":
459 return "closed, nothing merged";
460 }
461 }
462
463 export interface AskedCounts {
464 /** Every ask. */
465 readonly asked: number;
466 readonly shipped: number;
467 /** Waiting or building: what `show=unshipped` lists. */
468 readonly unshipped: number;
469 /** What `show=flagged` lists. */
470 readonly flagged: number;
471 }
472
473 /**
474 * How many asks there are of each kind, over all of them, not one page —
475 * counted in SQL, never by reading every ask: the pulls that close asks are
476 * read once (`pullsByAsk`) and handed to one grouped query as key sets, so
477 * the cost follows the pulls, not the tens of thousands of issues a busy
478 * repository can carry. The states are `scan`'s, word for word.
479 */
480 export function askedCounts(
481 db: Database,
482 repos: readonly Repo[],
483 now: Date = new Date(),
484 ): AskedCounts {
485 if (repos.length === 0) return { asked: 0, shipped: 0, unshipped: 0, flagged: 0 };
486 const repoIds = repos.map((r) => r.id);
487 const shipped: string[] = [];
488 const open: string[] = [];
489 for (const [key, list] of pullsByAsk(db, repoIds)) {
490 if (list.some((p) => p.state === "merged")) shipped.push(key);
491 else if (list.some((p) => p.state === "open")) open.push(key);
492 }
493 const running = listActiveRuns(db, repoIds).flatMap((r) =>
494 r.issueId === null ? [] : [r.issueId],
495 );
496 const direction = repos.flatMap((r) =>
497 r.directionIssueId === null ? [] : [r.directionIssueId],
498 );
499 const n = repoIds.length;
500 const set = (k: number) => `(SELECT value FROM json_each(?${n + k}))`;
501 const row = db
502 .query<
503 { asked: number; shipped: number; building: number; waiting: number; flagged: number },
504 string[]
505 >(
506 `SELECT COUNT(*) AS asked,
507 COALESCE(SUM(shipped), 0) AS shipped,
508 COALESCE(SUM(building), 0) AS building,
509 COALESCE(SUM(waiting), 0) AS waiting,
510 COALESCE(SUM(waiting AND created_at < ?${n + 5}), 0) AS flagged
511 FROM (
512 SELECT shipped,
513 NOT shipped AND (k IN ${set(2)} OR id IN ${set(3)}) AS building,
514 NOT shipped AND NOT (k IN ${set(2)} OR id IN ${set(3)}) AND state = 'open' AS waiting,
515 created_at
516 FROM (
517 SELECT issue.id AS id, issue.state AS state, issue.created_at AS created_at,
518 issue.repo_id || '#' || issue.number AS k,
519 (issue.repo_id || '#' || issue.number) IN ${set(1)} AS shipped
520 FROM issue JOIN user ON user.id = issue.author_id
521 WHERE ${ASK_WHERE(n)} AND issue.id NOT IN ${set(4)}
522 )
523 )`,
524 )
525 .get(
526 ...repoIds,
527 JSON.stringify(shipped),
528 JSON.stringify(open),
529 JSON.stringify(running),
530 JSON.stringify(direction),
531 new Date(now.getTime() - STALE_DAYS * DAY).toISOString(),
532 )!;
533 return {
534 asked: row.asked,
535 shipped: row.shipped,
536 unshipped: row.building + row.waiting,
537 flagged: row.flagged,
538 };
539 }
540
541 /** The newest agent run or agent comment per issue, in two grouped reads. */
542 function lastCrewActivity(
543 db: Database,
544 issueIds: readonly string[],
545 ): Map<string, string> {
546 const out = new Map<string, string>();
547 const unique = [...new Set(issueIds)];
548 const CHUNK = 400;
549 for (let i = 0; i < unique.length; i += CHUNK) {
550 const batch = unique.slice(i, i + CHUNK);
551 const marks = placeholders(batch.length);
552 const rows = db
553 .query<{ issue_id: string; at: string }, string[]>(
554 `SELECT issue_id, MAX(created_at) AS at FROM run
555 WHERE kind = 'agent' AND issue_id IN (${marks}) GROUP BY issue_id
556 UNION ALL
557 SELECT comment.issue_id, MAX(comment.created_at) AS at
558 FROM comment JOIN user ON user.id = comment.author_id
559 WHERE user.is_agent = 1 AND comment.issue_id IN (${marks})
560 GROUP BY comment.issue_id`,
561 )
562 .all(...batch);
563 for (const r of rows) {
564 const seen = out.get(r.issue_id);
565 if (seen === undefined || r.at > seen) out.set(r.issue_id, r.at);
566 }
567 }
568 return out;
569 }
570
571 /** The row as JSON, for the API and the MCP. */
572 export function askedJson(a: Asked) {
573 return {
574 source: a.source,
575 repo: `${a.repo.ownerName}/${a.repo.name}`,
576 number: a.issue.number,
577 title: a.issue.title,
578 askedBy: a.askedBy,
579 askedAt: a.askedAt,
580 issueState: a.issue.state,
581 state: a.state,
582 stale: a.stale,
583 flagged: a.flagged,
584 lastCrewAt: a.lastCrewAt,
585 doneBy: a.doneBy,
586 outcome: a.outcome,
587 outcomeText: outcomeText(a),
588 pulls: a.pulls.map((p) => ({
589 number: p.number,
590 title: p.title,
591 state: p.state,
592 openedAt: p.openedAt,
593 })),
594 };
595 }
src/core/thought_stream.ts +35 −24
@@ -16,8 +16,8 @@
1616 */
1717
1818 import type { Database } from "bun:sqlite";
19 import { pullsByAsk } from "./asked.ts";
2019 import { getIssue } from "./issues.ts";
20 import { closesFromBody } from "./pulls.ts";
2121 import { placementsOf, type Kind, type Placed } from "./placements.ts";
2222 import { canRead, getRepo, type Repo } from "./repos.ts";
2323 import { listActiveRuns } from "./runs.ts";
@@ -26,6 +26,40 @@ import { linksFrom, linksTo } from "./thought_links.ts";
2626 import { recentThoughts, thoughtOf } from "./thoughts.ts";
2727 import type { User } from "./users.ts";
2828
29 /** One pull that says it closes an issue: its number and where it stands. */
30 export interface ClosingPull {
31 readonly number: number;
32 readonly state: "open" | "merged" | "closed";
33 }
34
35 /**
36 * The pulls that say they close each issue, keyed `repoId#number`: every pull in these
37 * repositories whose body can name one, read once.
38 */
39 export function pullsByAsk(db: Database, repoIds: readonly string[]): Map<string, ClosingPull[]> {
40 const pulls = new Map<string, ClosingPull[]>();
41 if (repoIds.length === 0) return pulls;
42 const marks = repoIds.map((_, i) => `?${i + 1}`).join(",");
43 const rows = db
44 .query<{ repo_id: string; number: number; body: string; state: string; merged_at: string | null }, string[]>(
45 `SELECT issue.repo_id, issue.number, issue.body, issue.state, pull.merged_at
46 FROM issue JOIN pull ON pull.issue_id = issue.id
47 WHERE issue.repo_id IN (${marks}) AND issue.kind = 'pull'
48 AND issue.body LIKE '%#%'
49 AND (issue.body LIKE '%close%' OR issue.body LIKE '%fix%' OR issue.body LIKE '%resolve%')
50 ORDER BY issue.number`,
51 )
52 .all(...repoIds);
53 for (const row of rows)
54 for (const n of closesFromBody(row.body)) {
55 const key = `${row.repo_id}#${n}`;
56 const list = pulls.get(key) ?? [];
57 list.push({ number: row.number, state: row.merged_at !== null ? "merged" : row.state === "open" ? "open" : "closed" });
58 pulls.set(key, list);
59 }
60 return pulls;
61 }
62
2963 export type ThoughtState = "unplaced" | "placed" | "building" | "shipped" | "superseded";
3064
3165 export const FLAG_DAYS = 3;
@@ -205,26 +239,3 @@ export function thoughtStream(
205239 };
206240 });
207241 }
208
209 /** The row as JSON, for the MCP: the text verbatim. */
210 export function streamJson(t: StreamThought) {
211 return {
212 id: t.id,
213 text: t.text,
214 source: t.source,
215 receivedAt: t.receivedAt,
216 kind: t.kind,
217 reply: t.reply,
218 placedAt: t.placedAt,
219 placed: t.placed.map((x) =>
220 x.readable
221 ? { action: x.action, repo: x.repo, number: x.number, title: x.title, ...(x.pull === undefined ? {} : { pull: x.pull }) }
222 : { action: x.action, repo: null, number: null, title: null },
223 ),
224 state: t.state,
225 flagged: t.flagged,
226 supersededBy: t.supersededBy,
227 repeats: t.repeats,
228 supersedes: t.supersedes,
229 };
230 }
src/generated/marks.ts +190 −192
@@ -8,197 +8,196 @@ import k3 from "../http/marks/api-v1-admin.json";
88 import k4 from "../http/marks/api-v1-agents.json";
99 import k5 from "../http/marks/api-v1-app-templates.json";
1010 import k6 from "../http/marks/api-v1-apps.json";
11 import k7 from "../http/marks/api-v1-asked.json";
12 import k8 from "../http/marks/api-v1-asks.json";
13 import k9 from "../http/marks/api-v1-boards.json";
14 import k10 from "../http/marks/api-v1-broker.json";
15 import k11 from "../http/marks/api-v1-builds.json";
16 import k12 from "../http/marks/api-v1-cache.json";
17 import k13 from "../http/marks/api-v1-changelog.json";
18 import k14 from "../http/marks/api-v1-cloud.json";
19 import k15 from "../http/marks/api-v1-codes.json";
20 import k16 from "../http/marks/api-v1-config.json";
21 import k17 from "../http/marks/api-v1-contribute.json";
22 import k18 from "../http/marks/api-v1-conversation-confirms.json";
23 import k19 from "../http/marks/api-v1-conversation-tokens.json";
24 import k20 from "../http/marks/api-v1-conversation.json";
25 import k21 from "../http/marks/api-v1-conversations.json";
26 import k22 from "../http/marks/api-v1-credit.json";
27 import k23 from "../http/marks/api-v1-crew.json";
28 import k24 from "../http/marks/api-v1-devices.json";
29 import k25 from "../http/marks/api-v1-drills.json";
30 import k26 from "../http/marks/api-v1-explore.json";
31 import k27 from "../http/marks/api-v1-family.json";
32 import k28 from "../http/marks/api-v1-features.json";
33 import k29 from "../http/marks/api-v1-feed.json";
34 import k30 from "../http/marks/api-v1-first-admin.json";
35 import k31 from "../http/marks/api-v1-flags.json";
36 import k32 from "../http/marks/api-v1-fleet.json";
37 import k33 from "../http/marks/api-v1-flow.json";
38 import k34 from "../http/marks/api-v1-forge-templates.json";
39 import k35 from "../http/marks/api-v1-forge.json";
40 import k36 from "../http/marks/api-v1-forges.json";
41 import k37 from "../http/marks/api-v1-front.json";
42 import k38 from "../http/marks/api-v1-games.json";
43 import k39 from "../http/marks/api-v1-health.json";
44 import k40 from "../http/marks/api-v1-heartbeat.json";
45 import k41 from "../http/marks/api-v1-here.json";
46 import k42 from "../http/marks/api-v1-keeper.json";
47 import k43 from "../http/marks/api-v1-maintenance.json";
48 import k44 from "../http/marks/api-v1-map.json";
49 import k45 from "../http/marks/api-v1-migrate.json";
50 import k46 from "../http/marks/api-v1-offers.json";
51 import k47 from "../http/marks/api-v1-openapi.json.json";
52 import k48 from "../http/marks/api-v1-orgs.json";
53 import k49 from "../http/marks/api-v1-packs.json";
54 import k50 from "../http/marks/api-v1-passport.json";
55 import k51 from "../http/marks/api-v1-places.json";
56 import k52 from "../http/marks/api-v1-plans.json";
57 import k53 from "../http/marks/api-v1-proof.json";
58 import k54 from "../http/marks/api-v1-reach.json";
59 import k55 from "../http/marks/api-v1-release.json";
60 import k56 from "../http/marks/api-v1-releases.json";
61 import k57 from "../http/marks/api-v1-repos.json";
62 import k58 from "../http/marks/api-v1-returns.json";
63 import k59 from "../http/marks/api-v1-runner.json";
64 import k60 from "../http/marks/api-v1-search.json";
65 import k61 from "../http/marks/api-v1-secrets.json";
66 import k62 from "../http/marks/api-v1-sessions.json";
67 import k63 from "../http/marks/api-v1-share.json";
68 import k64 from "../http/marks/api-v1-slash.json";
69 import k65 from "../http/marks/api-v1-start.json";
70 import k66 from "../http/marks/api-v1-status.json";
71 import k67 from "../http/marks/api-v1-telemetry.json";
72 import k68 from "../http/marks/api-v1-templates.json";
73 import k69 from "../http/marks/api-v1-thoughts.json";
74 import k70 from "../http/marks/api-v1-timers.json";
75 import k71 from "../http/marks/api-v1-tokens.json";
76 import k72 from "../http/marks/api-v1-usage.json";
77 import k73 from "../http/marks/api-v1-user.json";
78 import k74 from "../http/marks/api-v1-users.json";
79 import k75 from "../http/marks/api-v1-version.json";
80 import k76 from "../http/marks/api-v1.json";
81 import k77 from "../http/marks/api.json";
82 import k78 from "../http/marks/apple-touch-icon-precomposed.png.json";
83 import k79 from "../http/marks/apple-touch-icon.png.json";
84 import k80 from "../http/marks/apps.json";
85 import k81 from "../http/marks/asked.json";
86 import k82 from "../http/marks/asks.json";
87 import k83 from "../http/marks/assets.json";
88 import k84 from "../http/marks/audit.csv.json";
89 import k85 from "../http/marks/audit.json";
90 import k86 from "../http/marks/big.json";
91 import k87 from "../http/marks/board.json";
92 import k88 from "../http/marks/boards.json";
93 import k89 from "../http/marks/bring.json";
94 import k90 from "../http/marks/broker.json";
95 import k91 from "../http/marks/changelog.atom.json";
96 import k92 from "../http/marks/changelog.json";
97 import k93 from "../http/marks/claim.json";
98 import k94 from "../http/marks/cloud.json";
99 import k95 from "../http/marks/contract.json";
100 import k96 from "../http/marks/contribute.json";
101 import k97 from "../http/marks/csp-report.json";
102 import k98 from "../http/marks/dash.json";
103 import k99 from "../http/marks/data.json";
104 import k100 from "../http/marks/dataset.json";
105 import k101 from "../http/marks/deploy-to.json";
106 import k102 from "../http/marks/design.json";
107 import k103 from "../http/marks/desk.json";
108 import k104 from "../http/marks/displays.json";
109 import k105 from "../http/marks/docs.json";
110 import k106 from "../http/marks/edge.json";
111 import k107 from "../http/marks/edition.json";
112 import k108 from "../http/marks/events.json";
113 import k109 from "../http/marks/explore.atom.json";
114 import k110 from "../http/marks/explore.json";
115 import k111 from "../http/marks/explore.json.json";
116 import k112 from "../http/marks/family.json";
117 import k113 from "../http/marks/favicon.ico.json";
118 import k114 from "../http/marks/feed.json";
119 import k115 from "../http/marks/feed.json.json";
120 import k116 from "../http/marks/first-admin.json";
121 import k117 from "../http/marks/fleet.json";
122 import k118 from "../http/marks/flow.json";
123 import k119 from "../http/marks/forge.json";
124 import k120 from "../http/marks/forges.json";
125 import k121 from "../http/marks/front.json";
126 import k122 from "../http/marks/funnel.json";
127 import k123 from "../http/marks/games.json";
128 import k124 from "../http/marks/go.json";
129 import k125 from "../http/marks/health.json";
130 import k126 from "../http/marks/home.json";
131 import k127 from "../http/marks/hooks.json";
132 import k128 from "../http/marks/icons.json";
133 import k129 from "../http/marks/infra.json";
134 import k130 from "../http/marks/join.json";
135 import k131 from "../http/marks/live.json";
136 import k132 from "../http/marks/llms-full.txt.json";
137 import k133 from "../http/marks/llms.txt.json";
138 import k134 from "../http/marks/login.json";
139 import k135 from "../http/marks/logout.json";
140 import k136 from "../http/marks/maintenance-json.json";
141 import k137 from "../http/marks/maintenance.json";
142 import k138 from "../http/marks/manifest.webmanifest.json";
143 import k139 from "../http/marks/map.json";
144 import k140 from "../http/marks/mcp.json";
145 import k141 from "../http/marks/measure.json";
146 import k142 from "../http/marks/metrics.json";
147 import k143 from "../http/marks/migrate.json";
148 import k144 from "../http/marks/new.json";
149 import k145 from "../http/marks/next.json";
150 import k146 from "../http/marks/notes.json";
151 import k147 from "../http/marks/now.json";
152 import k148 from "../http/marks/oauth.json";
153 import k149 from "../http/marks/oembed.json";
154 import k150 from "../http/marks/offers.json";
155 import k151 from "../http/marks/offline.json";
156 import k152 from "../http/marks/og.json";
157 import k153 from "../http/marks/openapi.json.json";
158 import k154 from "../http/marks/opensearch.xml.json";
159 import k155 from "../http/marks/organizations.json";
160 import k156 from "../http/marks/origins.json";
161 import k157 from "../http/marks/owner.atom.json";
162 import k158 from "../http/marks/owner.json";
163 import k159 from "../http/marks/packs.json";
164 import k160 from "../http/marks/peek.json";
165 import k161 from "../http/marks/pinned.json";
166 import k162 from "../http/marks/pipeline.json";
167 import k163 from "../http/marks/plugins.json";
168 import k164 from "../http/marks/pricing.json";
169 import k165 from "../http/marks/privacy.json";
170 import k166 from "../http/marks/r.json";
171 import k167 from "../http/marks/recover.json";
172 import k168 from "../http/marks/releases.json";
173 import k169 from "../http/marks/releases.json.json";
174 import k170 from "../http/marks/repos.json";
175 import k171 from "../http/marks/resilience.json";
176 import k172 from "../http/marks/review.json";
177 import k173 from "../http/marks/robots.txt.json";
178 import k174 from "../http/marks/root.json";
179 import k175 from "../http/marks/runs.json";
180 import k176 from "../http/marks/script-error.json";
181 import k177 from "../http/marks/search.json";
182 import k178 from "../http/marks/security.json";
183 import k179 from "../http/marks/settings.json";
184 import k180 from "../http/marks/sign-in.json";
185 import k181 from "../http/marks/signin.json";
186 import k182 from "../http/marks/signup.json";
187 import k183 from "../http/marks/sitemap.xml.json";
188 import k184 from "../http/marks/status.json";
189 import k185 from "../http/marks/sw.js.json";
190 import k186 from "../http/marks/system.json";
191 import k187 from "../http/marks/talk.json";
192 import k188 from "../http/marks/tell.json";
193 import k189 from "../http/marks/templates.json";
194 import k190 from "../http/marks/templates.json.json";
195 import k191 from "../http/marks/terms.json";
196 import k192 from "../http/marks/theme.json";
197 import k193 from "../http/marks/toolbar-lab.js.json";
198 import k194 from "../http/marks/toolbar-lab.json";
199 import k195 from "../http/marks/verify.json";
200 import k196 from "../http/marks/welcome.json";
201 import k197 from "../http/marks/well-known.json";
11 import k7 from "../http/marks/api-v1-asks.json";
12 import k8 from "../http/marks/api-v1-boards.json";
13 import k9 from "../http/marks/api-v1-broker.json";
14 import k10 from "../http/marks/api-v1-builds.json";
15 import k11 from "../http/marks/api-v1-cache.json";
16 import k12 from "../http/marks/api-v1-changelog.json";
17 import k13 from "../http/marks/api-v1-cloud.json";
18 import k14 from "../http/marks/api-v1-codes.json";
19 import k15 from "../http/marks/api-v1-config.json";
20 import k16 from "../http/marks/api-v1-contribute.json";
21 import k17 from "../http/marks/api-v1-conversation-confirms.json";
22 import k18 from "../http/marks/api-v1-conversation-tokens.json";
23 import k19 from "../http/marks/api-v1-conversation.json";
24 import k20 from "../http/marks/api-v1-conversations.json";
25 import k21 from "../http/marks/api-v1-credit.json";
26 import k22 from "../http/marks/api-v1-crew.json";
27 import k23 from "../http/marks/api-v1-devices.json";
28 import k24 from "../http/marks/api-v1-drills.json";
29 import k25 from "../http/marks/api-v1-explore.json";
30 import k26 from "../http/marks/api-v1-family.json";
31 import k27 from "../http/marks/api-v1-features.json";
32 import k28 from "../http/marks/api-v1-feed.json";
33 import k29 from "../http/marks/api-v1-first-admin.json";
34 import k30 from "../http/marks/api-v1-flags.json";
35 import k31 from "../http/marks/api-v1-fleet.json";
36 import k32 from "../http/marks/api-v1-flow.json";
37 import k33 from "../http/marks/api-v1-forge-templates.json";
38 import k34 from "../http/marks/api-v1-forge.json";
39 import k35 from "../http/marks/api-v1-forges.json";
40 import k36 from "../http/marks/api-v1-front.json";
41 import k37 from "../http/marks/api-v1-games.json";
42 import k38 from "../http/marks/api-v1-health.json";
43 import k39 from "../http/marks/api-v1-heartbeat.json";
44 import k40 from "../http/marks/api-v1-here.json";
45 import k41 from "../http/marks/api-v1-keeper.json";
46 import k42 from "../http/marks/api-v1-maintenance.json";
47 import k43 from "../http/marks/api-v1-map.json";
48 import k44 from "../http/marks/api-v1-migrate.json";
49 import k45 from "../http/marks/api-v1-offers.json";
50 import k46 from "../http/marks/api-v1-openapi.json.json";
51 import k47 from "../http/marks/api-v1-orgs.json";
52 import k48 from "../http/marks/api-v1-packs.json";
53 import k49 from "../http/marks/api-v1-passport.json";
54 import k50 from "../http/marks/api-v1-places.json";
55 import k51 from "../http/marks/api-v1-plans.json";
56 import k52 from "../http/marks/api-v1-proof.json";
57 import k53 from "../http/marks/api-v1-reach.json";
58 import k54 from "../http/marks/api-v1-release.json";
59 import k55 from "../http/marks/api-v1-releases.json";
60 import k56 from "../http/marks/api-v1-repos.json";
61 import k57 from "../http/marks/api-v1-returns.json";
62 import k58 from "../http/marks/api-v1-runner.json";
63 import k59 from "../http/marks/api-v1-search.json";
64 import k60 from "../http/marks/api-v1-secrets.json";
65 import k61 from "../http/marks/api-v1-sessions.json";
66 import k62 from "../http/marks/api-v1-share.json";
67 import k63 from "../http/marks/api-v1-slash.json";
68 import k64 from "../http/marks/api-v1-start.json";
69 import k65 from "../http/marks/api-v1-status.json";
70 import k66 from "../http/marks/api-v1-telemetry.json";
71 import k67 from "../http/marks/api-v1-templates.json";
72 import k68 from "../http/marks/api-v1-thoughts.json";
73 import k69 from "../http/marks/api-v1-timers.json";
74 import k70 from "../http/marks/api-v1-tokens.json";
75 import k71 from "../http/marks/api-v1-usage.json";
76 import k72 from "../http/marks/api-v1-user.json";
77 import k73 from "../http/marks/api-v1-users.json";
78 import k74 from "../http/marks/api-v1-version.json";
79 import k75 from "../http/marks/api-v1.json";
80 import k76 from "../http/marks/api.json";
81 import k77 from "../http/marks/apple-touch-icon-precomposed.png.json";
82 import k78 from "../http/marks/apple-touch-icon.png.json";
83 import k79 from "../http/marks/apps.json";
84 import k80 from "../http/marks/asked.json";
85 import k81 from "../http/marks/asks.json";
86 import k82 from "../http/marks/assets.json";
87 import k83 from "../http/marks/audit.csv.json";
88 import k84 from "../http/marks/audit.json";
89 import k85 from "../http/marks/big.json";
90 import k86 from "../http/marks/board.json";
91 import k87 from "../http/marks/boards.json";
92 import k88 from "../http/marks/bring.json";
93 import k89 from "../http/marks/broker.json";
94 import k90 from "../http/marks/changelog.atom.json";
95 import k91 from "../http/marks/changelog.json";
96 import k92 from "../http/marks/claim.json";
97 import k93 from "../http/marks/cloud.json";
98 import k94 from "../http/marks/contract.json";
99 import k95 from "../http/marks/contribute.json";
100 import k96 from "../http/marks/csp-report.json";
101 import k97 from "../http/marks/dash.json";
102 import k98 from "../http/marks/data.json";
103 import k99 from "../http/marks/dataset.json";
104 import k100 from "../http/marks/deploy-to.json";
105 import k101 from "../http/marks/design.json";
106 import k102 from "../http/marks/desk.json";
107 import k103 from "../http/marks/displays.json";
108 import k104 from "../http/marks/docs.json";
109 import k105 from "../http/marks/edge.json";
110 import k106 from "../http/marks/edition.json";
111 import k107 from "../http/marks/events.json";
112 import k108 from "../http/marks/explore.atom.json";
113 import k109 from "../http/marks/explore.json";
114 import k110 from "../http/marks/explore.json.json";
115 import k111 from "../http/marks/family.json";
116 import k112 from "../http/marks/favicon.ico.json";
117 import k113 from "../http/marks/feed.json";
118 import k114 from "../http/marks/feed.json.json";
119 import k115 from "../http/marks/first-admin.json";
120 import k116 from "../http/marks/fleet.json";
121 import k117 from "../http/marks/flow.json";
122 import k118 from "../http/marks/forge.json";
123 import k119 from "../http/marks/forges.json";
124 import k120 from "../http/marks/front.json";
125 import k121 from "../http/marks/funnel.json";
126 import k122 from "../http/marks/games.json";
127 import k123 from "../http/marks/go.json";
128 import k124 from "../http/marks/health.json";
129 import k125 from "../http/marks/home.json";
130 import k126 from "../http/marks/hooks.json";
131 import k127 from "../http/marks/icons.json";
132 import k128 from "../http/marks/infra.json";
133 import k129 from "../http/marks/join.json";
134 import k130 from "../http/marks/live.json";
135 import k131 from "../http/marks/llms-full.txt.json";
136 import k132 from "../http/marks/llms.txt.json";
137 import k133 from "../http/marks/login.json";
138 import k134 from "../http/marks/logout.json";
139 import k135 from "../http/marks/maintenance-json.json";
140 import k136 from "../http/marks/maintenance.json";
141 import k137 from "../http/marks/manifest.webmanifest.json";
142 import k138 from "../http/marks/map.json";
143 import k139 from "../http/marks/mcp.json";
144 import k140 from "../http/marks/measure.json";
145 import k141 from "../http/marks/metrics.json";
146 import k142 from "../http/marks/migrate.json";
147 import k143 from "../http/marks/new.json";
148 import k144 from "../http/marks/next.json";
149 import k145 from "../http/marks/notes.json";
150 import k146 from "../http/marks/now.json";
151 import k147 from "../http/marks/oauth.json";
152 import k148 from "../http/marks/oembed.json";
153 import k149 from "../http/marks/offers.json";
154 import k150 from "../http/marks/offline.json";
155 import k151 from "../http/marks/og.json";
156 import k152 from "../http/marks/openapi.json.json";
157 import k153 from "../http/marks/opensearch.xml.json";
158 import k154 from "../http/marks/organizations.json";
159 import k155 from "../http/marks/origins.json";
160 import k156 from "../http/marks/owner.atom.json";
161 import k157 from "../http/marks/owner.json";
162 import k158 from "../http/marks/packs.json";
163 import k159 from "../http/marks/peek.json";
164 import k160 from "../http/marks/pinned.json";
165 import k161 from "../http/marks/pipeline.json";
166 import k162 from "../http/marks/plugins.json";
167 import k163 from "../http/marks/pricing.json";
168 import k164 from "../http/marks/privacy.json";
169 import k165 from "../http/marks/r.json";
170 import k166 from "../http/marks/recover.json";
171 import k167 from "../http/marks/releases.json";
172 import k168 from "../http/marks/releases.json.json";
173 import k169 from "../http/marks/repos.json";
174 import k170 from "../http/marks/resilience.json";
175 import k171 from "../http/marks/review.json";
176 import k172 from "../http/marks/robots.txt.json";
177 import k173 from "../http/marks/root.json";
178 import k174 from "../http/marks/runs.json";
179 import k175 from "../http/marks/script-error.json";
180 import k176 from "../http/marks/search.json";
181 import k177 from "../http/marks/security.json";
182 import k178 from "../http/marks/settings.json";
183 import k179 from "../http/marks/sign-in.json";
184 import k180 from "../http/marks/signin.json";
185 import k181 from "../http/marks/signup.json";
186 import k182 from "../http/marks/sitemap.xml.json";
187 import k183 from "../http/marks/status.json";
188 import k184 from "../http/marks/sw.js.json";
189 import k185 from "../http/marks/system.json";
190 import k186 from "../http/marks/talk.json";
191 import k187 from "../http/marks/tell.json";
192 import k188 from "../http/marks/templates.json";
193 import k189 from "../http/marks/templates.json.json";
194 import k190 from "../http/marks/terms.json";
195 import k191 from "../http/marks/theme.json";
196 import k192 from "../http/marks/toolbar-lab.js.json";
197 import k193 from "../http/marks/toolbar-lab.json";
198 import k194 from "../http/marks/verify.json";
199 import k195 from "../http/marks/welcome.json";
200 import k196 from "../http/marks/well-known.json";
202201
203202 /** Each file of `http/marks/`, parsed, in name order. */
204203 export const MARK_FILES: readonly unknown[] = [
@@ -399,5 +398,4 @@ export const MARK_FILES: readonly unknown[] = [
399398 k194,
400399 k195,
401400 k196,
402 k197,
403401 ];
src/http/api.ts +1 −36
@@ -54,14 +54,6 @@ import {
5454 } from "../actions/signins.ts";
5555 import { STRANGER_MAX } from "./limits.ts";
5656 import { VIA_FORM, WORDS_MAX } from "../core/fence.ts";
57 import {
58 askedIn,
59 askedJson,
60 askedRepos,
61 isAskedOrder,
62 isAskedShow,
63 } from "../core/asked.ts";
64 import { streamJson, thoughtStream } from "../core/thought_stream.ts";
6557 import { PROVE_FIRST } from "../actions/verify_words.ts";
6658 import { REPORT_LINK_TITLE } from "../actions/report_words.ts";
6759 import { editMessage } from "../actions/edit_words.ts";
@@ -399,7 +391,7 @@ import { egressMetrics } from "../apps/egress_metrics.ts";
399391 import { forgeMetrics, processSources } from "../metrics/forge.ts";
400392 import { appSources } from "../metrics/app_sources.ts";
401393 import { ADMIN_WORDS } from "../actions/admin_words.ts";
402 import { ORDER_WORDS, VISIBILITY_WORDS } from "../core/arg_words.ts";
394 import { VISIBILITY_WORDS } from "../core/arg_words.ts";
403395 import { censusReport } from "../perf/heap_census.ts";
404396
405397 /** Take the parent's updates for `repo` and answer as the API does, for every route that asks. */
@@ -2601,33 +2593,6 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
26012593 },
26022594 });
26032595 });
2604 // What people asked of the crew in the repositories the caller can write —
2605 // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts,
2606 // the /asked page).
2607 router.add("GET", "/api/v1/asked", (ctx) => {
2608 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2609 const denied = requireScope(ctx, "ro");
2610 if (denied) return denied;
2611 const raw = ctx.url.searchParams.get("show");
2612 if (raw !== null && !isAskedShow(raw))
2613 return apiError("invalid_show", 422, "show is all, unshipped or flagged");
2614 const order = ctx.url.searchParams.get("order");
2615 if (order !== null && !isAskedOrder(order))
2616 return apiError("invalid_order", 422, ORDER_WORDS);
2617 const read = timePhase(ctx.request, "asked", () => {
2618 const repos = askedRepos(ctx.app.db, ctx.auth.user, ctx.url.searchParams.get("repo"));
2619 return {
2620 asked: askedIn(ctx.app.db, repos, {
2621 show: raw ?? "unshipped",
2622 order: order ?? "oldest",
2623 }),
2624 thoughts: ctx.auth.user ? thoughtStream(ctx.app.db, ctx.auth.user) : [],
2625 };
2626 });
2627 return timePhase(ctx.request, "render", () =>
2628 json({ asked: read.asked.map(askedJson), thoughts: read.thoughts.map(streamJson) }),
2629 );
2630 });
26312596 // Every repository the caller can see, one entry each: the global map.
26322597 router.add("GET", "/api/v1/map", (ctx) => {
26332598 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
src/http/marks/api-v1-asked.json deleted −4
@@ -1,4 +0,0 @@
1 {
2 "head": "/api/v1/asked",
3 "mark": "open"
4 }
src/http/marks/live.json −1
@@ -15,7 +15,6 @@
1515 "/live/figures": "admin",
1616 "/live/home/waiting": "open",
1717 "/live/home/panels": "admin",
18 "/live/home/asked": "open",
1918 "/live/home/feed": "open",
2019 "/live/talk-work": "open",
2120 "/live/talk-plan": "open",
src/http/mcp/catalog.ts +1 −1
@@ -37,7 +37,7 @@ export const DEFAULT_TOOLS: readonly string[] = [
3737 * boards, raw data), which an admin does on its own page; `find_tool` still names them. Also left
3838 * out, so the list stays well inside one page of `tools/list` (about 17 KB of `TOOLS_PAGE_BYTES`'
3939 * 20,000): `explore`, `forge_view` and `feed` (`apps`, `person`, `now` and `health` answer
40 * the same), `asked` (`issues`), `agents` (`now`), `asks`, `asks_act` and the asks filters (a
40 * the same), `agents` (`now`), `asks`, `asks_act` and the asks filters (a
4141 * question about what waits on the person is answered by the forge itself from the same rows,
4242 * `actions/talk_decisions.ts`, each item a link to the page where it is decided; the inbox they
4343 * belong to is going, #16229), and the planning knobs a page sets (`milestones`, `wait_for`,
src/http/mcp/tools/asked.ts deleted −36
@@ -1,36 +0,0 @@
1 import { askedIn, askedJson, askedRepos, isAskedOrder, isAskedShow } from "../../../core/asked.ts";
2 import { streamJson, thoughtStream } from "../../../core/thought_stream.ts";
3 import { good, bad, type Tool, str, REPO_ARG } from "../shared.ts";
4 import { ORDER_WORDS } from "../../../core/arg_words.ts";
5
6 export const tool: Tool = {
7 name: "asked",
8 doc: "`{ repo?, show?, order? }`: what people asked the crew for, by default nothing merged yet and oldest first: who and when, the pulls that close it, the crew's last activity, waiting/building/shipped/closed, the outcome (landed in a pull, who is building, parked and why, failed) and its sentence, stale when not shipped in three days and flagged when stale with nothing built; repositories you can write; draws the `ui://forge/asked` card: flagged asks first, then each ask's words, its state and a link to the merged or open pull that closes it, else the issue; at most 20 rows",
9 description:
10 "What people asked the crew for: unmerged by default, oldest first.",
11 inputSchema: {
12 type: "object",
13 properties: {
14 repo: REPO_ARG,
15 show: { type: "string", enum: ["unshipped", "flagged", "all"] },
16 order: { type: "string", enum: ["oldest", "newest"] },
17 },
18 },
19 writes: false,
20 run(ctx, user, args) {
21 const show = args["show"] ?? "unshipped";
22 if (!isAskedShow(show))
23 return bad("invalid_show", "show is unshipped, flagged or all");
24 const order = args["order"] ?? "oldest";
25 if (!isAskedOrder(order))
26 return bad("invalid_order", ORDER_WORDS);
27 const spec = args["repo"] === undefined ? null : str(args["repo"]);
28 const repos = askedRepos(ctx.app.db, user, spec);
29 if (spec !== null && repos.length === 0)
30 return bad("not_found", "no such app or repository you can write (owner/name)");
31 return good({
32 asked: askedIn(ctx.app.db, repos, { show, order }).map(askedJson),
33 thoughts: thoughtStream(ctx.app.db, user).map(streamJson),
34 });
35 },
36 };
src/http/mcp/tools/index.ts −1
@@ -19,7 +19,6 @@ export { tool as app_members } from "./app_members.ts";
1919 export { tool as app_notes } from "./app_notes.ts";
2020 export { tool as apps } from "./apps.ts";
2121 export { tool as archive } from "./archive.ts";
22 export { tool as asked } from "./asked.ts";
2322 export { tool as asks } from "./asks.ts";
2423 export { tool as asks_act } from "./asks_act.ts";
2524 export { tool as asks_decide } from "./asks_decide.ts";
src/http/server.ts +3 −3
@@ -353,7 +353,6 @@ import { forgeItSubmit } from "../web/pages/forge-it.ts";
353353 import { funnelSubmit } from "./funnel.ts";
354354 import { redirect } from "../web/layout.ts";
355355 import { inventoryPage } from "../web/pages/inventory.ts";
356 import { askedPage } from "../web/studio/asked_page.ts";
357356 import { notesOverrule, notesSave, notesView } from "../web/pages/notes.ts";
358357 import { reviewPage } from "../web/studio/review_page.ts";
359358 import { reviewAnswersPage, reviewAnswersSend, reviewStepOpen } from "../web/studio/review_guide.ts";
@@ -1090,8 +1089,9 @@ export function buildRouter(): Router<Handler> {
10901089 router.add("POST", "/asks/admin/later", askAdminLater);
10911090 router.add("POST", "/asks/give-back", asksGiveBack);
10921091 router.add("POST", "/asks/decide/:id/undo", asksDecideUndo);
1093 // What people asked of the crew, and what became of it (core/asked.ts).
1094 router.add("GET", "/asked", askedPage);
1092 // What a person opened is an issue or a pull request: /asked is the feed narrowed to theirs
1093 // (#16229).
1094 router.add("GET", "/asked", () => redirect("/feed?show=mine"));
10951095 router.add("GET", "/notes", notesView);
10961096 router.add("POST", "/notes", notesSave);
10971097 router.add("POST", "/notes/:id/overrule", notesOverrule);
src/tui/forge.ts −9
@@ -61,7 +61,6 @@ import {
6161 } from "./screens/common.ts";
6262 import { chainScreen } from "./screens/chain.ts";
6363 import { canSeeMemory } from "../boards/memory.ts";
64 import { askedScreen } from "./screens/asked.ts";
6564 import { notesScreen } from "./screens/thoughtnotes.ts";
6665 import { deciderScreen } from "./screens/decider.ts";
6766 import { familyScreen, withForkCount } from "./screens/family.ts";
@@ -437,14 +436,6 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
437436 hint: "spawn a client's forge and get its claim link",
438437 run: () => ctx.push(newForgeScreen(session, ctx)),
439438 });
440 // What you asked for and what became of it, as /asked says it: a signed-in person's.
441 if (session.signedIn)
442 commands.push({
443 id: "asked",
444 title: "Asked",
445 hint: "your thoughts and what became of them",
446 run: () => ctx.push(askedScreen(session, ctx)),
447 });
448439 // One box to write an idea in, each note with its live state; /notes' own door (#8696).
449440 if (session.signedIn)
450441 commands.push({
src/tui/screens/asked.ts deleted −293
@@ -1,293 +0,0 @@
1 /**
2 * `/asked` in the terminal (#1755): the owner's thoughts, then what they
3 * asked for in issues, from the same `thoughtStream` and `askedIn` reads the
4 * page makes — so the gate is core's and not this screen's. A guest has
5 * neither, a viewer sees only their own thoughts, and a placement in a
6 * repository the viewer cannot read says so and names nothing of it.
7 * The palette offers the door only when signed in, so the screen has no
8 * signed-out face; `askedLines` still returns nothing for a guest. Read-only;
9 * `enter` on an ask hands over its web address, on a thought opens its card
10 * (#7473): where it went and what it repeats or takes back, as MCP `thought`
11 * answers. The card is re-read on `r`.
12 * `s` cycles unshipped → flagged → all and `o` flips oldest/newest, with MCP
13 * `asked`'s defaults, words and order (#7303) — not the page's grouping.
14 */
15
16 import type { Database } from "bun:sqlite";
17 import { NOT_PLACED_YET, thoughtNotes, whereItWent } from "../../actions/ask_state_words.ts";
18 import { askedIn, askedRepos, outcomeText, type Asked, type AskedOrder, type AskedShow } from "../../core/asked.ts";
19 import { getIssue } from "../../core/issues.ts";
20 import { mayView } from "../../core/sealed.ts";
21 import { placementOf } from "../../core/placements.ts";
22 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
23 import { linksFrom, linksTo } from "../../core/thought_links.ts";
24 import { thoughtStream, type StreamThought } from "../../core/thought_stream.ts";
25 import { thoughtOf } from "../../core/thoughts.ts";
26 import type { User } from "../../core/users.ts";
27 import type { Ctx, Screen } from "../app/app.ts";
28 import { binding } from "../app/keys.ts";
29 import type { Session } from "../session.ts";
30 import { split, fill, len } from "../ui/layout.ts";
31 import { emptyState, type Tone } from "../ui/widgets.ts";
32 import { EMPTY_WORDS } from "../../core/empty_words.ts";
33 import { style } from "../term/style.ts";
34 import { truncate } from "../term/width.ts";
35 import { ListState, drawList, hitList, metaOf, openOnWeb, relTime, type ListRow } from "./common.ts";
36 import { issueScreen } from "./issue.ts";
37 import { local } from "./where.ts";
38
39 /**
40 * One line of plain text: a typed thought may carry newlines or escapes the terminal must not obey.
41 */
42 const plain = (text: string): string =>
43 // eslint-disable-next-line no-control-regex
44 text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim();
45
46 export interface AskedLine extends ListRow {
47 /** The web path `enter` opens; absent for a thought. */
48 readonly path?: string;
49 /** The thought `enter` opens a card for. */
50 readonly thoughtId?: string;
51 /** The issue `enter` opens, on a card line: only ever a repository the viewer can read. */
52 readonly issue?: { readonly repo: Repo; readonly number: number };
53 }
54
55 const THOUGHT_WORD = {
56 unplaced: "heard",
57 placed: "placed",
58 building: "building",
59 shipped: "shipped",
60 superseded: "superseded",
61 } as const;
62
63 /** Red is for nothing built, green for shipped, amber for under way. */
64 function toneOf(flagged: boolean, state: string): { tone?: Tone } {
65 if (flagged) return { tone: "danger" };
66 if (state === "shipped") return { tone: "success" };
67 return state === "building" ? { tone: "attn" } : {};
68 }
69
70 /**
71 * Where it went and what it repeats or takes back, in /asked's words (`whereItWent`,
72 * `thoughtNotes`).
73 */
74 function thoughtLine(t: StreamThought): AskedLine {
75 const where = whereItWent(t).map((x) => `${x.lead}${x.text}`);
76 const notes = thoughtNotes(t).map((n) => `${n.text} ${relTime(n.at)}`);
77 return {
78 thoughtId: t.id,
79 title: plain(t.text),
80 ...toneOf(t.flagged, t.state),
81 hollow: t.state === "unplaced" || t.state === "superseded",
82 secondary: plain([...where, ...notes].join(" · ")),
83 meta: metaOf(t.flagged ? "nothing built" : THOUGHT_WORD[t.state], relTime(t.receivedAt)),
84 };
85 }
86
87 /** The state, then stale or flagged, in MCP `asked`'s words; the outcome is the secondary line. */
88 function askLine(a: Asked): AskedLine {
89 return {
90 title: plain(a.issue.title),
91 ...toneOf(a.flagged, a.state),
92 secondary: `${plain(outcomeText(a))} · ${a.repo.ownerName}/${a.repo.name} #${a.issue.number}`,
93 meta: metaOf(a.state, a.flagged ? "flagged" : a.stale ? "stale" : "", relTime(a.askedAt)),
94 path: `/${a.repo.ownerName}/${a.repo.name}/issues/${a.issue.number}`,
95 };
96 }
97
98 /** The repository `owner/name` when the viewer may read it: the one place a card decides that. */
99 function readableRepo(db: Database, viewer: User, slug: string): Repo | undefined {
100 const [owner, name, ...rest] = slug.split("/");
101 const r = owner && name && rest.length === 0 ? getRepo(db, owner, name) : undefined;
102 return r && canRead(db, r, viewer) ? r : undefined;
103 }
104
105 const quoted = (text: string): string => `\u201c${plain(text)}\u201d`;
106
107 /**
108 * What became of one thought, as MCP `thought` answers: one sentence a line.
109 * Not the viewer's, or not there, is `undefined` alike.
110 */
111 export function thoughtCard(db: Database, viewer: User | undefined, id: string): AskedLine[] | undefined {
112 if (viewer === undefined) return undefined;
113 const t = thoughtOf(db, viewer.id, id);
114 if (t === undefined) return undefined;
115 const out: AskedLine[] = [{ title: quoted(t.text), hollow: true }];
116 const p = placementOf(db, id);
117 if (p === undefined) out.push({ title: `Not placed yet: ${NOT_PLACED_YET}.` });
118 else if (p.placed.length === 0) out.push({ title: "Kept as a note." });
119 for (const x of p?.placed ?? []) {
120 const repo = readableRepo(db, viewer, x.repo);
121 const issue = repo === undefined ? undefined : getIssue(db, repo.id, x.number);
122 // A sealed issue in a readable repository is no more there than an unreadable repository.
123 if (repo === undefined || issue === undefined || !mayView(db, repo, issue, viewer)) {
124 out.push({ title: `It ${x.action} something in a repository you cannot read.` });
125 continue;
126 }
127 out.push({
128 title: `It ${x.action} ${x.repo} #${x.number}: ${plain(issue.title)}.`,
129 issue: { repo, number: x.number },
130 });
131 }
132 const refs = (ids: readonly string[], verb: string): void => {
133 for (const other of ids) {
134 const o = thoughtOf(db, viewer.id, other);
135 out.push({ title: o ? `${verb} ${quoted(o.text)}.` : `${verb} a thought that is gone.` });
136 }
137 };
138 const from = linksFrom(db, id);
139 const to = linksTo(db, id);
140 refs(from.repeats, "It repeats");
141 refs(from.supersedes, "It takes back");
142 refs(to.repeatedBy, "Repeated later by");
143 refs(to.supersededBy === null ? [] : [to.supersededBy], "Taken back later by");
144 return out;
145 }
146
147 function cardScreen(f: Session, ctx: Ctx, id: string, first: AskedLine[]): Screen {
148 const state = new ListState();
149 let rows = first;
150 const open = (index: number): void => {
151 const x = rows[index]?.issue;
152 if (x !== undefined) ctx.push(issueScreen(f, ctx, local(f, x.repo), x.number));
153 };
154 return {
155 title: "Thought",
156 keys: [binding(["j", "k"], "move"), binding(["enter"], "open issue (on a line that has one)"), binding(["r"], "refresh")],
157 render(area, s) {
158 drawList(s, area, ctx.theme.c, state, rows);
159 hitList(ctx, area, state, rows.length, { open });
160 },
161 key(e) {
162 if (state.key(e, rows.length)) return true;
163 if (e.key === "enter") {
164 open(state.index);
165 return true;
166 }
167 if (e.key === "r") {
168 const again = thoughtCard(f.db, f.user, id);
169 if (again === undefined) {
170 // Gone since it was drawn: stale rows must not pass for current ones.
171 ctx.toast("No such thought", "attn");
172 ctx.pop();
173 return true;
174 }
175 rows = again;
176 state.clamp(rows.length);
177 ctx.invalidate();
178 return true;
179 }
180 return false;
181 },
182 };
183 }
184
185 /** What MCP `asked` takes, and its defaults. */
186 export interface AskedView {
187 readonly show: AskedShow;
188 readonly order: AskedOrder;
189 }
190
191 export const DEFAULT_VIEW: AskedView = { show: "unshipped", order: "oldest" };
192
193 const SHOW_CYCLE: readonly AskedShow[] = ["unshipped", "flagged", "all"];
194
195 const SHOW_WORDS: Record<AskedShow, string> = { unshipped: "not shipped", flagged: "flagged", all: "all" };
196
197 /** The choice in words, for the title: "not shipped, oldest first". */
198 export const viewWords = (v: AskedView): string => `${SHOW_WORDS[v.show]}, ${v.order} first`;
199
200 export const nextShow = (show: AskedShow): AskedShow =>
201 SHOW_CYCLE[(SHOW_CYCLE.indexOf(show) + 1) % SHOW_CYCLE.length]!;
202
203 /** The thoughts, then the asks, as rows. A guest has none of either. */
204 export function askedLines(
205 db: Database,
206 viewer: User | undefined,
207 view: AskedView = DEFAULT_VIEW,
208 ): { thoughts: AskedLine[]; asks: AskedLine[] } {
209 if (viewer === undefined) return { thoughts: [], asks: [] };
210 const repos = askedRepos(db, viewer, null);
211 return {
212 thoughts: thoughtStream(db, viewer, { limit: 50 }).map(thoughtLine),
213 // MCP's order, not /asked's needs-the-owner grouping: the title names the order, so the rows
214 // keep it.
215 asks: askedIn(db, repos, view).map(askLine),
216 };
217 }
218
219 export function askedScreen(f: Session, ctx: Ctx): Screen {
220 const state = new ListState();
221 let lines: AskedLine[] = [];
222 let thoughtCount = 0;
223 let view = DEFAULT_VIEW;
224 const open = (index: number): void => {
225 const line = lines[index];
226 if (line?.thoughtId !== undefined) {
227 // Not the viewer's, or gone: nothing exists, as MCP answers.
228 const card = thoughtCard(f.db, f.user, line.thoughtId);
229 if (card === undefined) ctx.toast("No such thought", "attn");
230 else ctx.push(cardScreen(f, ctx, line.thoughtId, card));
231 return;
232 }
233 if (line?.path !== undefined) openOnWeb(f, ctx, line.path, "That ask");
234 };
235 const read = (): void => {
236 const got = askedLines(f.db, f.user, view);
237 lines = [...got.thoughts, ...got.asks];
238 thoughtCount = got.thoughts.length;
239 state.clamp(lines.length);
240 };
241 return {
242 get title() {
243 return `Asked · ${viewWords(view)}`;
244 },
245 keys: [
246 binding(["j", "k"], "move"),
247 binding(["enter"], "open"),
248 binding(["s"], "show"),
249 binding(["o"], "order"),
250 binding(["r"], "refresh"),
251 ],
252 load: async () => read(),
253 render(area, s) {
254 const c = ctx.theme.c;
255 const [head, body] = split(area, "v", [len(1), fill(1)]);
256 // The title names the choice; the head line only counts.
257 const sentence = `${thoughtCount} thoughts · ${lines.length - thoughtCount} asks`;
258 s.text(head!.x, head!.y, truncate(sentence, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
259 if (lines.length === 0) {
260 emptyState(s, body!, c, {
261 title: EMPTY_WORDS.inbox.sentence,
262 body: "What you tell the crew shows up here, with what became of it.",
263 });
264 return;
265 }
266 drawList(s, body!, c, state, lines);
267 hitList(ctx, body!, state, lines.length, { open });
268 },
269 key(e) {
270 if (state.key(e, lines.length)) return true;
271 if (e.key === "enter") {
272 open(state.index);
273 return true;
274 }
275 if (e.key === "s" || e.key === "o") {
276 view = e.key === "s"
277 ? { ...view, show: nextShow(view.show) }
278 : { ...view, order: view.order === "oldest" ? "newest" : "oldest" };
279 state.index = 0;
280 state.offset = 0;
281 read();
282 ctx.invalidate();
283 return true;
284 }
285 if (e.key === "r") {
286 read();
287 ctx.invalidate();
288 return true;
289 }
290 return false;
291 },
292 };
293 }
src/web/go_pages.ts −1
@@ -29,7 +29,6 @@ export const GO_PAGES: readonly GoPage[] = [
2929 { name: "Boards", href: "/boards", who: "admin", palette: "Boards" },
3030 { name: "Flow", href: "/flow", who: "admin", key: "f" },
3131 { name: "Waiting", href: "/?waits=me", who: "user" },
32 { name: "Asked", href: "/asked", who: "user", palette: "What you asked for" },
3332 { name: "Notes", href: "/notes", who: "user", palette: "Notes" },
3433 { name: "Talk", href: "/talk", who: "user", key: "t", palette: "Talk to the forge" },
3534 { name: "Map", href: "/map", who: "user", palette: "Map" },
src/web/pages/apps.ts +2 −2
@@ -85,7 +85,7 @@ import { noAgentsBlocked } from "../../actions/blocked_words.ts";
8585 import { flashTo, page, redirect } from "../layout.ts";
8686 import { writableAppsOf } from "../studio/asks.ts";
8787 import { costLine } from "../studio/cost_line.ts";
88 import { homeTabs, unshippedAsks } from "../studio/home_tabs.ts";
88 import { homeTabs } from "../studio/home_tabs.ts";
8989 import { shelfRows } from "../studio/shelf.ts";
9090 import {
9191 badge,
@@ -257,7 +257,7 @@ export async function appsList(ctx: Ctx): Promise<Response> {
257257 const hasData =
258258 ctx.auth.user !== undefined &&
259259 (ctx.auth.user.isAdmin || writableAppsOf(ctx, ctx.auth.user).repos.length > 0);
260 const body = html`<div data-apps-page>${when(ctx.auth.user, (user) => homeTabs("apps", unshippedAsks(ctx.app.db, user)))}
260 const body = html`<div data-apps-page>${when(ctx.auth.user, () => homeTabs("apps"))}
261261 ${pageHead("Apps", {
262262 actions: hasData ? html`${btn("Data", { href: "/data", size: "sm" })}${create}` : create,
263263 sub: APPS_PURPOSE,
src/web/pages/board.ts −1
@@ -292,7 +292,6 @@ export async function boardPage(ctx: Ctx): Promise<Response> {
292292 : `${repos.length} app${repos.length === 1 ? "" : "s"}`
293293 }</span
294294 >
295 <a class="muted small" href="/asked">What you asked for</a>
296295 <span class="spacer"></span>
297296 ${
298297 wall
src/web/studio/asked_page.ts deleted −236
@@ -1,236 +0,0 @@
1 /**
2 * `/asked`: everything a person asked for, oldest unmet first, and what
3 * became of it (`core/asked.ts`). The path: the owner wonders whether something
4 * they asked for was heard, opens this from the asks page or the board, and
5 * opens the ask. One row per ask, one sentence per row: what was asked, then
6 * what became of it, each linked to its evidence. `?show=` and `?order=`
7 * choose the asks; within them, those that need the owner come first, then
8 * those in progress, then what landed, then what was closed with nothing
9 * merged. `?repo=owner/name` keeps it to one repository.
10 */
11
12 import {
13 askedCounts,
14 askedIn,
15 askedRepos,
16 askedTier,
17 isAskedOrder,
18 isAskedShow,
19 outcomeText,
20 type Asked,
21 type AskedOrder,
22 type AskedShow,
23 } from "../../core/asked.ts";
24 import {
25 flagDays,
26 thoughtStream,
27 type StreamThought,
28 type ThoughtState,
29 } from "../../core/thought_stream.ts";
30 import { cut, thoughtNotes, whereItWent } from "../../actions/ask_state_words.ts";
31 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
32 import type { Ctx } from "../../http/context.ts";
33 import { repoBase, signInFirst } from "../chrome.ts";
34 import { html, type Html } from "../html.ts";
35 import { page } from "../layout.ts";
36 import {
37 badge,
38 empty,
39 listCard,
40 row,
41 seg,
42 time,
43 userTag,
44 type Tone,
45 } from "../ui.ts";
46 import { homeTabs } from "./home_tabs.ts";
47
48 const THOUGHT_WORD: Record<ThoughtState, { text: string; tone: Tone }> = {
49 unplaced: { text: "Heard", tone: "default" },
50 placed: { text: "Placed", tone: "default" },
51 building: { text: "Building", tone: "attn" },
52 shipped: { text: "Shipped", tone: "success" },
53 superseded: { text: "Superseded", tone: "default" },
54 };
55
56 /** Where a thought went (`whereItWent`), each issue linked when the viewer may read it. */
57 function placedLinks(t: StreamThought): Html {
58 const parts = whereItWent(t).map((x) =>
59 x.href === undefined ? html`${x.lead}${x.text}` : html`${x.lead}<a href="${x.href}">${x.text}</a>`,
60 );
61 return html`${parts.map((l, i) => html`${i > 0 ? " · " : ""}${l}`)}`;
62 }
63
64 export function thoughtRow(t: StreamThought, days: number): Html {
65 const word = t.flagged
66 ? { text: "Nothing built", tone: "danger" as Tone }
67 : THOUGHT_WORD[t.state];
68 return row({
69 title: t.text,
70 titleAttr: t.flagged
71 ? t.placedAt === null
72 ? `Not placed ${days} days after it was sent`
73 : `Nothing merged ${days} days after it was placed`
74 : t.text,
75 meta: html`${time(t.receivedAt)} · ${t.source} · ${placedLinks(t)}${thoughtNotes(t).map(
76 (n) => html` · ${n.text} ${time(n.at)}`,
77 )}`,
78 trail: badge(word.text, { tone: word.tone }),
79 });
80 }
81
82 /** The first placed issue of the oldest flagged thought: the one next action. */
83 function oldestFlaggedHref(stream: readonly StreamThought[]): string | null {
84 for (let i = stream.length - 1; i >= 0; i--) {
85 const t = stream[i]!;
86 if (!t.flagged) continue;
87 const to = t.placed.find((x) => x.title !== null);
88 if (to) return `/${to.repo}/issues/${to.number}`;
89 }
90 return null;
91 }
92
93 /** The ask, its first 80 characters. */
94 const asking = (a: Asked): string => cut(a.issue.title, 80);
95
96 /**
97 * What became of the ask, as the end of its sentence, linked to the pull or
98 * issue that says so. Only an ask with nothing built wears red; the rest are
99 * green for landed, amber for under way, and plain otherwise.
100 */
101 function outcomeOf(a: Asked): { text: Html; badge: { text: string; tone: Tone } } {
102 const base = repoBase(a.repo);
103 const issue = `${base}/issues/${a.issue.number}`;
104 const pull = (n: number) => html`<a href="${base}/pulls/${n}">#${n}</a>`;
105 const flagged: Tone = a.flagged ? "danger" : "default";
106 if (a.doneBy.length > 0)
107 return {
108 text: html`<a href="${issue}">${outcomeText(a)}</a>`,
109 badge: { text: "Done on main", tone: "success" },
110 };
111 const o = a.outcome;
112 switch (o.kind) {
113 case "landed":
114 return { text: html`landed in ${pull(o.pull)} ${time(o.at)}`, badge: { text: "Landed", tone: "success" } };
115 case "building":
116 return {
117 text: o.pull === null
118 ? html`${userTag(o.by, { avatar: false, mark: o.byMark })} <a href="${issue}">building</a>`
119 : html`${userTag(o.by, { avatar: false, mark: o.byMark })} building in ${pull(o.pull)}`,
120 badge: { text: "Building", tone: "attn" },
121 };
122 case "parked":
123 return {
124 text: html`<a href="${base}/pulls/${o.pull}">${outcomeText(a)}</a>`,
125 badge: { text: a.flagged ? "Nothing built" : "Parked", tone: flagged },
126 };
127 case "failed":
128 return {
129 text: html`${userTag(o.by, { avatar: false, mark: o.byMark })} <a href="${issue}">failed</a> ${time(o.at)}`,
130 badge: { text: a.flagged ? "Nothing built" : "Failed", tone: flagged },
131 };
132 case "closed":
133 return { text: html`<a href="${issue}">${outcomeText(a)}</a>`, badge: { text: "Closed", tone: "default" } };
134 default:
135 return {
136 text: html`<a href="${issue}">${outcomeText(a)}</a>`,
137 badge: { text: a.flagged ? "Nothing built" : "Waiting", tone: flagged },
138 };
139 }
140 }
141
142 function askedRow(a: Asked): Html {
143 const out = outcomeOf(a);
144 return row({
145 title: html`<a href="${repoBase(a.repo)}/issues/${a.issue.number}">${asking(a)}</a>`,
146 titleAttr: a.issue.title,
147 meta: html`${out.text} · ${a.repo.ownerName}/${a.repo.name} #${a.issue.number}`,
148 trail: badge(out.badge.text, { tone: out.badge.tone }),
149 });
150 }
151
152 /**
153 * GET /asked — `?show=unshipped` (the default: nothing merged yet),
154 * `flagged` or `all`; oldest first unless `?order=newest`; `?repo=` for one.
155 * Within the order, asks that need the owner come before those in progress,
156 * and those before what landed.
157 */
158 export function askedPage(ctx: Ctx): Response {
159 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
160 if (!ctx.auth.user) return signInFirst(ctx);
161 const user = ctx.auth.user;
162 const q = ctx.url.searchParams;
163 const rawShow = q.get("show");
164 const show: AskedShow = isAskedShow(rawShow) ? rawShow : "unshipped";
165 const rawOrder = q.get("order");
166 const order: AskedOrder = isAskedOrder(rawOrder) ? rawOrder : "oldest";
167 const repoSpec = q.get("repo");
168 const repos = timePhase(ctx.request, "repos", () => askedRepos(ctx.app.db, user, repoSpec));
169 const counts = timePhase(ctx.request, "counts", () => askedCounts(ctx.app.db, repos));
170 const listed = timePhase(ctx.request, "asks", () => askedIn(ctx.app.db, repos, { show, order }));
171 const href = (s: AskedShow, o: AskedOrder = order) => {
172 const parts = [
173 s === "unshipped" ? "" : `show=${s}`,
174 o === "oldest" ? "" : "order=newest",
175 repoSpec ? `repo=${encodeURIComponent(repoSpec)}` : "",
176 ].filter(Boolean);
177 return `/asked${parts.length > 0 ? `?${parts.join("&")}` : ""}`;
178 };
179 const stream = timePhase(ctx.request, "thoughts", () => thoughtStream(ctx.app.db, user, { limit: 50 }));
180 const days = timePhase(ctx.request, "flags", () => flagDays(ctx.app.db, user.id));
181 const rendering = performance.now();
182 // The sort is stable, so each group keeps the order asked for.
183 const rows = [...listed].sort((x, y) => askedTier(x) - askedTier(y));
184 const next = oldestFlaggedHref(stream);
185 const flaggedThoughts = stream.filter((t) => t.flagged).length;
186 const thoughts =
187 stream.length === 0
188 ? null
189 : html`<section id="thoughts" aria-labelledby="thoughts-h">
190 <div class="bar mb">
191 <h2 id="thoughts-h">Your thoughts</h2>
192 <span class="spacer"></span>
193 ${next === null
194 ? null
195 : html`<a class="btn" data-variant="primary" href="${next}"
196 >Open the oldest of ${flaggedThoughts} with nothing built</a
197 >`}
198 </div>
199 ${listCard(stream.map((t) => thoughtRow(t, days)))}
200 </section>
201 <h2 class="mt">Asked in issues</h2>`;
202 const { asked, shipped, unshipped, flagged } = counts;
203 const sentence =
204 asked === 0
205 ? "Nothing asked yet"
206 : `${asked} asked · ${shipped} landed${flagged > 0 ? ` · ${flagged} with nothing built` : ""}`;
207
208 const body = html`${homeTabs("asked", unshipped)}
209 <h1 id="asked-sentence">What you asked for</h1>
210 <p class="muted">${sentence}</p>
211 ${thoughts}
212 <div class="bar mb mt">
213 ${seg([
214 { label: "Not shipped", href: href("unshipped"), current: show === "unshipped", count: unshipped },
215 { label: "Nothing built", href: href("flagged"), current: show === "flagged", count: flagged },
216 { label: "All", href: href("all"), current: show === "all", count: asked },
217 ])}
218 <span class="spacer"></span>
219 <a class="small muted" href="${href(show, order === "oldest" ? "newest" : "oldest")}"
220 >${order === "oldest" ? "Show newest first" : "Show oldest first"}</a
221 >
222 </div>
223 ${rows.length === 0
224 ? empty({
225 icon: "issue",
226 title: asked === 0 ? "Nothing asked yet" : "Nothing here",
227 note:
228 asked === 0
229 ? "What a person tells the crew shows up here, with what became of it."
230 : "Every ask in this view has something built for it.",
231 })
232 : listCard(rows.map(askedRow))}`;
233 const response = page({ ctx, title: "What you asked for", body });
234 notePhase(ctx.request, "render", performance.now() - rendering);
235 return response;
236 }
src/web/studio/cards.ts +2 −32
@@ -14,7 +14,7 @@ import { HIDDEN_FORK_WORD } from "../../actions/follow_words.ts";
1414 import { VERB_WORDS } from "../../actions/asks_words.ts";
1515 import { span, stageSays, STAGE_LABEL, verdict, type PipelineKey, type PipelineStage } from "../../flow/pipeline.ts";
1616
17 export type CardKind = "app" | "run" | "asks" | "wave" | "map" | "feed" | "pull" | "pulls" | "runs" | "asked" | "explore" | "issue" | "flow" | "scorecard" | "crew" | "board" | "forks" | "milestones" | "release" | "releases" | "search" | "issues" | "forges" | "held" | "drill" | "reports" | "usage" | "health" | "capacity" | "forge";
17 export type CardKind = "app" | "run" | "asks" | "wave" | "map" | "feed" | "pull" | "pulls" | "runs" | "explore" | "issue" | "flow" | "scorecard" | "crew" | "board" | "forks" | "milestones" | "release" | "releases" | "search" | "issues" | "forges" | "held" | "drill" | "reports" | "usage" | "health" | "capacity" | "forge";
1818
1919 export interface CardRow {
2020 readonly label: string;
@@ -52,7 +52,7 @@ export const CARD_MIME = "text/html;profile=mcp-app";
5252 */
5353 export const CARD_RESOURCE_META = { ui: { prefersBorder: false, csp: { connectDomains: [], resourceDomains: [] } } } as const;
5454 export const CARD_URI = (kind: CardKind): string => `ui://forge/${kind}`;
55 export const CARD_KINDS: readonly CardKind[] = ["app", "run", "asks", "wave", "map", "feed", "pull", "pulls", "runs", "asked", "explore", "issue", "flow", "scorecard", "crew", "board", "forks", "milestones", "release", "releases", "search", "issues", "held", "forges", "drill", "reports", "usage", "health", "capacity", "forge"];
55 export const CARD_KINDS: readonly CardKind[] = ["app", "run", "asks", "wave", "map", "feed", "pull", "pulls", "runs", "explore", "issue", "flow", "scorecard", "crew", "board", "forks", "milestones", "release", "releases", "search", "issues", "held", "forges", "drill", "reports", "usage", "health", "capacity", "forge"];
5656
5757 /** The tool whose answer each card draws. */
5858 export const CARD_OF_TOOL: Readonly<Record<string, CardKind>> = {
@@ -72,7 +72,6 @@ export const CARD_OF_TOOL: Readonly<Record<string, CardKind>> = {
7272 archive: "app",
7373 pull: "pull",
7474 pulls: "pulls",
75 asked: "asked",
7675 issue: "issue",
7776 flow: "flow",
7877 scorecard: "scorecard",
@@ -102,7 +101,6 @@ const CARD_TITLE: Readonly<Record<CardKind, string>> = {
102101 pull: "Pull",
103102 pulls: "Pulls",
104103 runs: "Runs",
105 asked: "Asked",
106104 issue: "Issue",
107105 flow: "Flow",
108106 scorecard: "Crew",
@@ -160,8 +158,6 @@ export const ISSUES_ROWS = 20;
160158 const HELD_ROWS = 40;
161159 const REPORT_ROWS = 30;
162160 const USAGE_ROWS = 20;
163 const ASKED_WORDS = 80;
164 const ASKED_LIMIT = 20;
165161 const RELEASE_ROWS = 10;
166162 /** A waiting row's words are cut to this many characters. */
167163 const SAYS_WORDS = 160;
@@ -866,32 +862,6 @@ export function cardFor(
866862 }
867863 return { kind, title: CARD_TITLE[kind], status, rows, actions };
868864 }
869 if (kind === "asked") {
870 // `asked` answers `{ asked: [{ repo, number, title, state, flagged, pulls }] }`.
871 const asks = list(obj(value)["asked"]).map(obj);
872 const flagged = asks.filter((a) => a["flagged"] === true);
873 const waiting = asks.filter((a) => a["state"] === "waiting").length;
874 status = `${waiting} waiting · ${flagged.length} flagged`;
875 for (const a of [...flagged, ...asks.filter((a) => a["flagged"] !== true)].slice(0, ASKED_LIMIT)) {
876 const repo = text(a["repo"]);
877 const number = text(a["number"]);
878 // The pull that closes it: a landed one, else an open one, else the issue.
879 const pulls = list(a["pulls"]).map(obj);
880 const closing = pulls.find((p) => p["state"] === "merged") ?? pulls.find((p) => p["state"] === "open");
881 const pullNumber = closing === undefined ? "" : text(closing["number"]);
882 const path =
883 /^[1-9]\d*$/.test(pullNumber) ? `/${repo}/pulls/${pullNumber}` : `/${repo}/issues/${number}`;
884 const title = text(a["title"]);
885 rows.push({
886 label: title.length > ASKED_WORDS ? `${title.slice(0, ASKED_WORDS - 1)}…` : title,
887 value: text(a["state"]),
888 ...(web(origin) && slugOf(repo) && /^[1-9]\d*$/.test(number) && here(origin, path)
889 ? { link: origin + path }
890 : {}),
891 });
892 }
893 return { kind, title: CARD_TITLE[kind], status, rows, actions };
894 }
895865 if (kind === "issue") {
896866 const v = obj(value);
897867 const number = text(v["number"]);
src/web/studio/home.ts +3 −4
@@ -87,7 +87,7 @@ import { pinnedPanels } from "./pinned.ts";
8787 import { isNavigation, lastVisit, noteVisit } from "../../core/home_visit.ts";
8888 import { sinceYouWere } from "./since.ts";
8989 import { newLine, newSince } from "../../feed/last_seen.ts";
90 import { homeTabs, unshippedAsks } from "./home_tabs.ts";
90 import { homeTabs } from "./home_tabs.ts";
9191 import { homeFlowPage } from "../pages/home_flow.ts";
9292 import { crewKeyCard } from "./crew_key.ts";
9393 import { everydayLine, firstAskJs, nextStepsCard, nextStepsOf } from "../pages/next-steps.ts";
@@ -270,7 +270,6 @@ export function homeDraws(ctx: Ctx, user: User): Record<HomeRegion, () => Html |
270270 return {
271271 waiting: () => timePhase(request, "waiting", () => waitingLine(db, user), () => waitingCache(db)),
272272 panels: async () => (await timePhaseAsync(request, "panels", () => pinnedPanels(ctx.app, user), () => panelCache(db))) ?? html``,
273 asked: () => homeTabs("feed", timePhase(request, "asked", () => unshippedAsks(db, user))),
274273 feed: () => timePhase(request, "feed", () => feedRegion(user, ctx), () => feedCandidateCache(db)),
275274 };
276275 }
@@ -404,7 +403,7 @@ export async function feedPage(ctx: Ctx): Promise<Response> {
404403 ${user.isAdmin ? await regionOf("panels") : null}
405404 ${since}
406405 ${quiet ? quietLine() : null}
407 ${await regionOf("asked")}
406 ${homeTabs("feed")}
408407 <div class="split" data-rail="wide">
409408 <div class="stack">
410409 ${composer(ctx, user)}
@@ -425,7 +424,7 @@ export async function feedPage(ctx: Ctx): Promise<Response> {
425424 body,
426425 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${feedJs}\n${refreshJs}`,
427426 });
428 notePhaseRest(ctx.request, "render", rendering, ["waiting", "feed", "asked", "visit", "since", "new", "access", "repos"]);
427 notePhaseRest(ctx.request, "render", rendering, ["waiting", "feed", "visit", "since", "new", "access", "repos"]);
429428 return res;
430429 }
431430
src/web/studio/home_last.ts +1 −1
@@ -24,7 +24,7 @@ import { escapeHtml, raw, type Html } from "../html.ts";
2424 import { HOME_MAX_AGE_MS } from "./home_cache.ts";
2525
2626 /** The regions home draws late, by name; each has a fragment at `/live/home/<name>`. */
27 export const HOME_REGIONS = ["waiting", "panels", "asked", "feed"] as const;
27 export const HOME_REGIONS = ["waiting", "panels", "feed"] as const;
2828 export type HomeRegion = (typeof HOME_REGIONS)[number];
2929
3030 /**
src/web/studio/home_tabs.ts +9 −24
@@ -1,34 +1,19 @@
11 /**
2 * The home's three tabs on a phone — Feed, Your apps, Asked — drawn on each
3 * of the three pages, so each is a tap from the others and never only the
4 * logo away (#599, #851). Drawn with §5's tabs.
2 * The home's tabs — Feed, Your apps, Design — drawn on each of the pages, so each is a tap from
3 * the others and never only the logo away (#599, #851). Drawn with §5's tabs. What was once an
4 * "Asked" tab is gone (#16229): what a person made is an issue or a pull request, found in the
5 * feed's `?show=mine`.
56 */
67
7 import type { Database } from "bun:sqlite";
8 import { askedCounts, askedRepos } from "../../core/asked.ts";
9 import type { User } from "../../core/users.ts";
108 import { html, type Html } from "../html.ts";
119 import { tabs } from "../ui.ts";
1210
13 export type HomeTab = "feed" | "apps" | "asked" | "design";
11 export type HomeTab = "feed" | "apps" | "design";
1412
15 /** The asks not yet shipped across the viewer's repositories: `/asked`'s own number. */
16 export function unshippedAsks(db: Database, viewer: User): number {
17 return askedCounts(db, askedRepos(db, viewer, null)).unshipped;
18 }
19
20 /** §5's `tabs()` in a `.mb` block: link tabs, so `aria-current`; Asked wears the unshipped count. */
21 export function homeTabs(current: HomeTab, unshipped = 0): Html {
22 const item = (id: HomeTab, href: string, label: string, count?: number) => ({
23 label,
24 ...(count === undefined ? {} : { count }),
25 href,
26 current: current === id,
27 });
13 /** §5's `tabs()` in a `.mb` block: link tabs, so `aria-current`. */
14 export function homeTabs(current: HomeTab): Html {
15 const item = (id: HomeTab, href: string, label: string) => ({ label, href, current: current === id });
2816 return html`<div class="mb">
29 ${tabs(
30 [item("feed", "/feed", "Feed"), item("apps", "/apps", "Your apps"), item("asked", "/asked", "Asked", unshipped), item("design", "/design", "Design")],
31 "Home",
32 )}
17 ${tabs([item("feed", "/feed", "Feed"), item("apps", "/apps", "Your apps"), item("design", "/design", "Design")], "Home")}
3318 </div>`;
3419 }
test/api-asked-timing.test.ts deleted −62
@@ -1,62 +0,0 @@
1 /** The API asked list names its Server-Timing phases (#4948). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createSession } from "../src/core/sessions.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12 import { requestTiming } from "./helpers/request-timing.ts";
13
14 quietLogs();
15
16 let dataDir: string;
17 let app: App;
18 let servers: Servers;
19 let cookie = "";
20
21 const cells = process.env["FORGE_CELLS"];
22
23 beforeAll(async () => {
24 process.env["FORGE_CELLS"] = "off";
25 dataDir = await mkdtemp(join(tmpdir(), "forge-api-asked-timing-"));
26 app = createApp({ dataDir, port: 0 });
27 servers = await serve(app);
28 const made = await createUser(app.db, {
29 origin: "seed",
30 trusted: true,
31 username: "alice",
32 email: "[email protected]",
33 password: "a-good-passphrase",
34 adminIfFirst: true,
35 });
36 if (!made.ok) throw new Error(String(made.error));
37 const alice = made.value;
38 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
39 const repo = await createRepo(app, alice, { name: "r", visibility: "public" });
40 if (!repo.ok) throw new Error(String(repo.error));
41 });
42 afterAll(async () => {
43 await servers.stop();
44 app.close();
45 if (cells === undefined) delete process.env["FORGE_CELLS"];
46 else process.env["FORGE_CELLS"] = cells;
47 await rm(dataDir, { recursive: true, force: true });
48 });
49
50 async function phases(path: string): Promise<{ status: number; names: string[]; body: string }> {
51 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
52 const body = await res.text();
53 const names = requestTiming(res).split(", ").map((p) => p.split(";")[0]!);
54 return { status: res.status, names: names.slice(names.indexOf("app") + 1), body };
55 }
56
57 test("the asked list names session, asked, render in order", async () => {
58 const got = await phases("/api/v1/asked");
59 expect(got.status).toBe(200);
60 expect(got.names).toEqual(["session", "asked", "render"]);
61 expect(Array.isArray(JSON.parse(got.body).asked)).toBe(true);
62 });
test/arg-words.test.ts −3
@@ -17,7 +17,6 @@ const DOORS: Record<string, string> = {
1717 "src/http/api.ts": "../core/arg_words.ts",
1818 "src/http/api/upstream.ts": "../../core/arg_words.ts",
1919 "src/http/feed.ts": "../core/arg_words.ts",
20 "src/http/mcp/tools/asked.ts": DEEP,
2120 "src/http/mcp/tools/board_pins.ts": DEEP,
2221 "src/http/mcp/tools/feed_chips.ts": DEEP,
2322 "src/http/mcp/tools/make_it_yours.ts": DEEP,
@@ -25,7 +24,6 @@ const DOORS: Record<string, string> = {
2524 "src/http/mcp/tools/signup.ts": DEEP,
2625 "src/http/mcp/tools/upstream.ts": DEEP,
2726 "src/http/mcp/tools/variant.ts": DEEP,
28 "src/contract/openapi/routes/getApiV1Asked.ts": DEEP,
2927 "src/contract/openapi/routes/postApiV1ReposOwnerNameMakeItYours.ts": DEEP,
3028 "src/contract/openapi/routes/putApiV1ReposOwnerNameUpstream.ts": DEEP,
3129 };
@@ -37,7 +35,6 @@ describe("an argument's allowed-values refusals", () => {
3735 "enabled is true or false",
3836 "hidden is true or false",
3937 "op must be pin, unpin or move",
40 "order is oldest or newest",
4138 "signup is open, request, invite or closed",
4239 "visibility is public or private",
4340 ]);
test/ask-state-words.test.ts +2 −5
@@ -7,18 +7,15 @@
77 import { expect, test } from "bun:test";
88 import { readFileSync } from "node:fs";
99 import { join } from "node:path";
10 import { CREW_WORKING, NOT_PLACED_YET } from "../src/actions/ask_state_words.ts";
10 import { CREW_WORKING } from "../src/actions/ask_state_words.ts";
1111
1212 const root = join(import.meta.dir, "..");
1313 const views = [
14 "src/web/studio/asked_page.ts",
15 "src/tui/screens/asked.ts",
1614 "src/web/studio/answers.ts",
1715 "src/tui/screens/answers.ts",
1816 ];
1917
2018 test("the sentences read as they always have", () => {
21 expect(NOT_PLACED_YET).toBe("the planner has not placed it yet");
2219 expect(CREW_WORKING).toBe("The crew is working on it.");
2320 });
2421
@@ -26,6 +23,6 @@ for (const file of views) {
2623 test(`${file} imports the ask's state words and types none of them`, () => {
2724 const text = readFileSync(join(root, file), "utf8");
2825 expect(text).toContain("actions/ask_state_words.ts");
29 for (const sentence of [NOT_PLACED_YET, CREW_WORKING]) expect(text).not.toContain(sentence);
26 for (const sentence of [CREW_WORKING]) expect(text).not.toContain(sentence);
3027 });
3128 }
test/asked-outcomes.test.ts deleted −218
@@ -1,218 +0,0 @@
1 /** `/asked` reads as one sentence per ask: what was asked, then what became of it, linked to its evidence, needing-the-owner first (#5802). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtempSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createAgent } from "../src/actions/crew.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { firstSentence } from "../src/core/asked.ts";
10 import { createIssue, addComment } from "../src/core/issues.ts";
11 import { createRun } from "../src/core/runs.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { askedLines } from "../src/tui/screens/asked.ts";
14 import { createUser, getUserByName, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { proveAll } from "./helpers/verified.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const DAY = 24 * 60 * 60 * 1000;
22 let root = "";
23 let app: App;
24 let servers: Servers;
25 let cookie = "";
26 let alice: User;
27 let bot: User;
28 let repoId = "";
29 const numbers: Record<string, number> = {};
30
31 const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString();
32
33 const ask = (key: string, title: string) => {
34 const made = createIssue(app.db, { repoId, authorId: alice.id, title });
35 if (!made.ok) throw new Error(made.error);
36 numbers[key] = made.value.number;
37 return made.value;
38 };
39
40 /** A pull by `author` whose body closes `issue`. */
41 const pullFor = (key: string, issue: { number: number }, author: User, extra: string) => {
42 const made = createIssue(app.db, {
43 repoId,
44 authorId: author.id,
45 title: `Answers ${issue.number}`,
46 body: `Closes #${issue.number}`,
47 kind: "pull",
48 });
49 if (!made.ok) throw new Error(made.error);
50 numbers[key] = made.value.number;
51 app.db
52 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
53 VALUES (?1, 'main', ?2, 'a', 'b', ?3)`)
54 .run(made.value.id, key, extra === "" ? null : extra);
55 return made.value;
56 };
57
58 beforeAll(async () => {
59 root = mkdtempSync(join(tmpdir(), "forge-asked-outcomes-"));
60 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
61 const u = await createUser(app.db, {
62 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
63 password: "a-good-passphrase", adminIfFirst: true,
64 });
65 if (!u.ok) throw new Error(u.error);
66 alice = u.value;
67 const b = await createAgent(app, alice, { username: "bot" });
68 if (!b.ok) throw new Error(String(b.error));
69 bot = getUserByName(app.db, "bot")!;
70 proveAll(app);
71 const made = await createRepo(app, alice, { name: "garden" });
72 if (!made.ok) throw new Error(String(made.error));
73 repoId = made.value.id;
74
75 app.db.query("INSERT INTO repo_crew (repo_id, user_id) VALUES (?1, ?2)").run(repoId, bot.id);
76 const landed = ask("landed", "Prune the roses");
77 const merged = pullFor("landedPull", landed, bot, ago(1));
78 app.db.query("UPDATE issue SET state = 'closed' WHERE id IN (?1, ?2)").run(landed.id, merged.id);
79 const old = ask("old", "Paint the shed");
80 const oldPull = pullFor("oldPull", old, bot, ago(20));
81 app.db.query("UPDATE issue SET state = 'closed' WHERE id IN (?1, ?2)").run(old.id, oldPull.id);
82
83 const building = ask("building", "A watering schedule");
84 pullFor("buildingPull", building, bot, "");
85
86 const parked = ask("parked", "Plant tomatoes in the north bed");
87 const parkedPull = pullFor("parkedPull", parked, bot, "");
88 app.db.query("UPDATE issue SET state = 'closed', parked = 1 WHERE id = ?1").run(parkedPull.id);
89 addComment(app.db, {
90 issueId: parkedPull.id,
91 authorId: bot.id,
92 body: "Parked by the crew: the check failed twice on the same test. Run it again by hand.",
93 });
94 addComment(app.db, { issueId: parkedPull.id, authorId: alice.id, body: "Parked by the crew: spoofed" });
95
96 const failed = ask("failed", "Fix the gate");
97 const run = createRun(app.db, { repoId, kind: "agent", issueId: failed.id, actorId: bot.id });
98 app.db.query("UPDATE run SET state = 'failed' WHERE id = ?1").run(run.id);
99
100 ask("unplaced", "x".repeat(100));
101 ask("spaced", `${"word ".repeat(15)}tails and more tail`);
102
103 const dropped = ask("dropped", "Dropped idea");
104 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(dropped.id);
105
106 servers = await serve(app);
107 const signin = await fetch(`${servers.url}/signin`, {
108 method: "POST",
109 headers: { origin: servers.url },
110 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
111 redirect: "manual",
112 });
113 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
114 }, 30_000);
115
116 afterAll(() => {
117 servers.stop();
118 app.close();
119 rmSync(root, { recursive: true, force: true });
120 });
121
122 const read = async () => {
123 const res = await fetch(`${servers.url}/asked?show=all`, { headers: { cookie } });
124 expect(res.status).toBe(200);
125 return (await res.text()).replace(/\s+/g, " ");
126 };
127 /** The row holding this ask's title, as text and as hrefs. */
128 const rowOf = (page: string, title: string) => {
129 const at = page.indexOf(`>${title}</a>`);
130 expect(at).toBeGreaterThan(-1);
131 const start = page.lastIndexOf("<li", at);
132 const end = page.indexOf("</li>", at);
133 const li = page.slice(start, end);
134 return {
135 text: li.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim(),
136 hrefs: [...li.matchAll(/href="([^"]+)"/g)].map((m) => m[1]!),
137 };
138 };
139
140 test("each state reads as one sentence with a link to its evidence", async () => {
141 const page = await read();
142 const n = numbers;
143 const landed = rowOf(page, "Prune the roses");
144 expect(landed.text).toContain(`landed in #${n.landedPull}`);
145 expect(landed.hrefs).toContain(`/alice/garden/pulls/${n.landedPull}`);
146 expect(landed.hrefs).toContain(`/alice/garden/issues/${n.landed}`);
147
148 const building = rowOf(page, "A watering schedule");
149 expect(building.text).toContain(`botcrew building in #${n.buildingPull}`);
150 expect(building.hrefs).toContain(`/alice/garden/pulls/${n.buildingPull}`);
151
152 const parked = rowOf(page, "Plant tomatoes in the north bed");
153 expect(parked.text).toContain("parked: the check failed twice on the same test.");
154 expect(parked.text).not.toContain("Run it again");
155 expect(parked.hrefs).toContain(`/alice/garden/pulls/${n.parkedPull}`);
156
157 const failed = rowOf(page, "Fix the gate");
158 expect(failed.text).toContain("botcrew failed");
159 expect(failed.hrefs).toContain(`/alice/garden/issues/${n.failed}`);
160
161 const unplaced = rowOf(page, `${"x".repeat(79)}…`);
162 expect(unplaced.text).toContain("not placed yet");
163 expect(unplaced.hrefs).toContain(`/alice/garden/issues/${n.unplaced}`);
164 });
165
166 test("what needs the owner comes first, then progress, then what landed", async () => {
167 const page = await read();
168 const at = (t: string) => page.indexOf(`>${t}</a>`);
169 const order = ["Plant tomatoes in the north bed", "Fix the gate", "A watering schedule", "Prune the roses"].map(at);
170 expect(order.every((i) => i > -1)).toBe(true);
171 expect(order[0]!).toBeLessThan(order[2]!);
172 expect(order[1]!).toBeLessThan(order[2]!);
173 expect(order[2]!).toBeLessThan(order[3]!);
174 expect(page.indexOf(`>${"x".repeat(79)}…</a>`)).toBeLessThan(order[3]!);
175 expect(at("Paint the shed")).toBeGreaterThan(order[2]!);
176 });
177
178 test("the API, the MCP and the terminal carry the same outcome and sentence", async () => {
179 const res = await fetch(`${servers.url}/api/v1/asked?show=all`, { headers: { authorization: `Bearer ${createToken(app.db, alice.id, "ro", "ro").token}` } });
180 const rows = ((await res.json()) as any).asked as any[];
181 const by = (t: string) => rows.find((r) => r.title === t);
182 expect(by("Prune the roses").outcome.kind).toBe("landed");
183 expect(by("Prune the roses").outcomeText).toBe(`landed in #${numbers.landedPull}`);
184 expect(by("Plant tomatoes in the north bed").outcomeText).toBe("parked: the check failed twice on the same test.");
185 expect(by("Fix the gate").outcome).toMatchObject({ kind: "failed", by: "bot" });
186 const lines = askedLines(app.db, getUserByName(app.db, "alice")!).asks;
187 // Found by title: the terminal keeps MCP's order, not the page's grouping (#7303).
188 expect(lines.find((l) => l.title === "Plant tomatoes in the north bed")?.secondary).toStartWith("parked: the check failed twice");
189 });
190
191 test("All lists every ask it counts, closed ones last", async () => {
192 const page = await read();
193 const counted = Number(page.match(/>All<span class="pill" >(\d+)</)?.[1]);
194 expect(counted).toBeGreaterThan(0);
195 expect(page.split('<div class="row"').length - 1).toBe(counted);
196 const dropped = rowOf(page, "Dropped idea");
197 expect(dropped.text).toContain("closed, nothing merged");
198 expect(page.indexOf(">Dropped idea</a>")).toBeGreaterThan(page.indexOf(">Prune the roses</a>"));
199 });
200
201 test("a name in the sentence wears its mark, outside the link", async () => {
202 const page = await read();
203 const li = page.slice(page.lastIndexOf("<li", page.indexOf(">A watering schedule</a>")), page.indexOf("</li>", page.indexOf(">A watering schedule</a>")));
204 expect(li).toContain('data-mark="crew"');
205 expect(li).not.toMatch(/<a [^>]*>[^<]*bot/);
206 const lines = askedLines(app.db, alice).asks.map((l) => l.secondary);
207 expect(lines.some((t) => t?.startsWith("bot (crew) building in #"))).toBe(true);
208 });
209
210 test("a parking note is cut at its first sentence", () => {
211 expect(firstSentence("the check failed. Then more.")).toBe("the check failed.");
212 expect(firstSentence("no full stop")).toBe("no full stop");
213 });
214
215 test("a long ask is cut at the last space before 80 characters", async () => {
216 const page = await read();
217 expect(page).toContain(`>${"word ".repeat(15).trim()}…</a>`);
218 });
test/asked-placement.test.ts deleted −130
@@ -1,130 +0,0 @@
1 /** On /asked each thought says where it went (#7509): the issue, a note, or not yet, and what it repeats. */
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 { createApp, type App } from "../src/app.ts";
8 import { openIssue } from "../src/actions/issues.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { placementsOf, savePlacement, type Placed } from "../src/core/placements.ts";
12 import { linkThoughts } from "../src/core/thought_links.ts";
13 import { serve } from "../src/http/server.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { promote } from "./helpers/members.ts";
17
18 quietLogs();
19
20 let dir = "";
21 let app: App;
22 let alice: User;
23 let bob: User;
24
25 beforeAll(async () => {
26 dir = await mkdtemp(join(tmpdir(), "asked-placement-"));
27 app = createApp({ dataDir: dir, port: 0 });
28 const mk = async (username: string, first = false) => {
29 const u = await createUser(app.db, {
30 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
31 password: "a-good-passphrase", adminIfFirst: first,
32 });
33 if (!u.ok) throw new Error(u.error);
34 promote(app.db, u.value);
35 return u.value;
36 };
37 bob = await mk("bob", true); // the forge's admin, first
38 alice = await mk("alice");
39 });
40 afterAll(async () => {
41 app.db.close();
42 await rm(dir, { recursive: true, force: true });
43 });
44
45 const think = (id: string, who: User, text: string, minutesAgo: number) =>
46 app.db
47 .query("INSERT INTO thought (id, author, text, source, received_at) VALUES (?1, ?2, ?3, 'composer', ?4)")
48 .run(id, who.id, text, new Date(Date.now() - minutesAgo * 60_000).toISOString());
49 const place = (thoughtId: string, placed: Placed[], reply = { text: "ok", asked: false }) =>
50 savePlacement(app.db, {
51 thoughtId, kind: placed.length > 0 ? "work" : "decision", placed, reply: reply.text, asked: reply.asked,
52 decidedBy: "rule", placedAt: new Date().toISOString(),
53 });
54
55 async function askedAs(user: string): Promise<string> {
56 const servers = await serve(app);
57 try {
58 const signin = await fetch(`${servers.url}/signin`, {
59 method: "POST",
60 body: new URLSearchParams({ username: user, password: "a-good-passphrase" }),
61 redirect: "manual",
62 });
63 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
64 const res = await fetch(`${servers.url}/asked`, { headers: { cookie } });
65 expect(res.status).toBe(200);
66 return (await res.text()).replace(/\s+/g, " ");
67 } finally {
68 servers.stop();
69 }
70 }
71
72 test("a placed thought links its issue, a repeat says what it repeats, a note and a waiting one say so", async () => {
73 const made = await createRepo(app, alice, { name: "gauges" });
74 if (!made.ok) throw new Error(String(made.error));
75 const issue = openIssue(app, alice, made.value, { title: "Queue <depth> gauge" });
76 if (!issue.ok) throw new Error(String(issue.error));
77 const n = issue.value.number;
78
79 think("t-first", alice, "build a gauge for queue depth on the board please", 30);
80 think("t-again", alice, "a queue depth gauge, again", 20);
81 think("t-note", alice, "we prefer plain words", 10);
82 think("t-wait", alice, "and a dark theme", 5);
83 place("t-first", [{ action: "opened", repo: "alice/gauges", number: n }]);
84 place("t-again", []);
85 linkThoughts(app.db, "t-again", "t-first", "repeats");
86 place("t-note", []);
87
88 const page = await askedAs("alice");
89 expect(page).toContain(`→ <a href="/alice/gauges/issues/${n}">alice/gauges#${n} Queue &lt;depth&gt; gauge</a>`);
90 expect(page).toContain("repeats “build a gauge for queue depth on the board please”");
91 expect(page).toContain("kept as a note");
92 expect(page).toContain("not placed yet");
93
94 // Only the author's own thoughts carry this.
95 const other = await askedAs("bob");
96 expect(other).not.toContain("alice/gauges#");
97 expect(other).not.toContain("kept as a note");
98 });
99
100 test("a question back stays visible, a proposed pull links to /pulls, an unreadable repository names nothing", async () => {
101 const vault = await createRepo(app, bob, { name: "vault", visibility: "private" });
102 if (!vault.ok) throw new Error(String(vault.error));
103 const sealed = openIssue(app, bob, vault.value, { title: "Bob's sealed plan" });
104 if (!sealed.ok) throw new Error(String(sealed.error));
105 const repo = await createRepo(app, alice, { name: "visions" });
106 if (!repo.ok) throw new Error(String(repo.error));
107 const pull = createIssue(app.db, { repoId: repo.value.id, authorId: alice.id, kind: "pull", title: "A vision for gauges" });
108 if (!pull.ok) throw new Error(String(pull.error));
109 const p = pull.value.number;
110
111 think("t-question", alice, "the thing from before", 4);
112 think("t-vision", alice, "gauges everywhere", 3);
113 think("t-hidden", alice, "the vault, too", 2);
114 place("t-question", [], { text: "Which thing do you mean — the gauge or the theme?", asked: true });
115 place("t-vision", [{ action: "proposed", repo: "alice/visions", number: p, pull: p }]);
116 place("t-hidden", [{ action: "opened", repo: "bob/vault", number: sealed.value.number }]);
117
118 const page = await askedAs("alice");
119 expect(page).toContain("Which thing do you mean — the gauge or the theme?");
120 expect(page).toContain(`→ proposed <a href="/alice/visions/pulls/${p}">alice/visions#${p} A vision for gauges</a>`);
121 expect(page).toContain("→ in a repository you cannot read");
122 expect(page).not.toContain("bob/vault");
123 expect(page).not.toContain("sealed plan");
124 });
125
126 test("the page's placements are read in one batch", () => {
127 const got = placementsOf(app.db, ["t-first", "t-note", "t-wait", "t-first"]);
128 expect([...got.keys()].sort()).toEqual(["t-first", "t-note"]);
129 expect(got.get("t-first")!.placed[0]!.repo).toBe("alice/gauges");
130 });
test/asked-tab-count.test.ts deleted −88
@@ -1,88 +0,0 @@
1 /** The Asked tab wears the number of unshipped asks, on `/`, `/apps` and `/asked`; none reads plain `Asked` (#6745). */
2 import { forgetHome } from "../src/web/studio/home_last.ts";
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtempSync, rmSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { homeTabs } from "../src/web/studio/home_tabs.ts";
13 import { proveAll } from "./helpers/verified.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 let root = "";
19 let app: App;
20 let servers: Servers;
21 let cookie = "";
22 let repoId = "";
23 let userId = "";
24
25 beforeAll(async () => {
26 root = mkdtempSync(join(tmpdir(), "forge-asked-tab-"));
27 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
28 const u = await createUser(app.db, {
29 origin: "seed",
30 trusted: true,
31 username: "alice",
32 email: "[email protected]",
33 password: "a-good-passphrase",
34 adminIfFirst: true,
35 });
36 if (!u.ok) throw new Error(u.error);
37 proveAll(app);
38 const made = await createRepo(app, { id: u.value.id, username: "alice" } as never, { name: "r" });
39 if (!made.ok) throw new Error(made.error);
40 repoId = made.value.id;
41 userId = u.value.id;
42 servers = await serve(app);
43 const signin = await fetch(`${servers.url}/signin`, {
44 method: "POST",
45 headers: { origin: servers.url },
46 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
47 redirect: "manual",
48 });
49 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
50 });
51 afterAll(() => {
52 servers.stop();
53 app.close();
54 rmSync(root, { recursive: true, force: true });
55 });
56
57 /** The Asked tab's inner text, tags stripped. */
58 async function askedTab(path: string): Promise<string> {
59 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
60 const page = await res.text();
61 const nav = page.match(/<nav class="tabs" aria-label="Home"[\s\S]*?<\/nav>/)?.[0] ?? "";
62 const m = nav.match(/<a[^>]*href="\/asked"[^>]*>([\s\S]*?)<\/a\s*>/);
63 if (!m) throw new Error(`no Asked tab on ${path}`);
64 return m[1]!.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
65 }
66
67 test("homeTabs reads plain Asked at 0 or when not given, and the count otherwise", () => {
68 expect(String(homeTabs("feed"))).not.toContain("pill");
69 expect(String(homeTabs("feed", 0))).not.toContain("pill");
70 expect(String(homeTabs("feed", 3))).toContain("pill");
71 });
72
73 test("with no asks the Asked tab is plain on all three pages", async () => {
74 forgetHome(app.db);
75 for (const path of ["/feed?all=1", "/apps", "/asked"]) expect(await askedTab(path)).toBe("Asked");
76 });
77
78 test("three unshipped asks read Asked 3 on `/`, `/apps` and `/asked`", async () => {
79 for (let i = 0; i < 3; i++) {
80 const ask = createIssue(app.db, { repoId, authorId: userId, title: `Ask ${i}` });
81 if (!ask.ok) throw new Error(ask.error);
82 }
83 forgetHome(app.db);
84 for (const path of ["/feed?all=1", "/apps", "/asked"]) expect(await askedTab(path)).toBe("Asked 3");
85 const res = await fetch(`${servers.url}/feed?all=1`, { headers: { cookie } });
86 await res.arrayBuffer();
87 expect(res.headers.get("server-timing") ?? "").toContain("asked;");
88 });
test/asked-timing.test.ts deleted −89
@@ -1,89 +0,0 @@
1 /** `/asked` names session, each read and render in Server-Timing, and costs a bounded number of statements for a person with 500 asks (#3358). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { expectWork, requestStatements } from "./helpers/work.ts";
4 import { mkdtempSync, rmSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { proveAll } from "./helpers/verified.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 let root = "";
18 let app: App;
19 let servers: Servers;
20 let cookie = "";
21
22 beforeAll(async () => {
23 root = mkdtempSync(join(tmpdir(), "forge-asked-timing-"));
24 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
25 const u = await createUser(app.db, {
26 origin: "seed",
27 trusted: true,
28 username: "alice",
29 email: "[email protected]",
30 password: "a-good-passphrase",
31 adminIfFirst: true,
32 });
33 if (!u.ok) throw new Error(u.error);
34 proveAll(app);
35 const owner = { id: u.value.id, username: "alice" } as never;
36 // 500 asks over 5 repositories; every other ask is closed by a merged pull.
37 for (let r = 0; r < 5; r++) {
38 const made = await createRepo(app, owner, { name: `r${r}` });
39 if (!made.ok) throw new Error(made.error);
40 for (let i = 0; i < 100; i++) {
41 const ask = createIssue(app.db, { repoId: made.value.id, authorId: u.value.id, title: `Ask ${r}.${i}` });
42 if (!ask.ok) throw new Error(ask.error);
43 if (i % 2 === 1) continue;
44 const pull = createIssue(app.db, {
45 repoId: made.value.id,
46 authorId: u.value.id,
47 title: `Answers ${ask.value.number}`,
48 body: `Closes #${ask.value.number}`,
49 kind: "pull",
50 });
51 if (!pull.ok) throw new Error(pull.error);
52 app.db
53 .query(
54 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
55 VALUES (?1, 'main', ?2, 'a', 'b', ?3)`,
56 )
57 .run(pull.value.id, `b${i}`, new Date().toISOString());
58 }
59 }
60 servers = await serve(app);
61 const signin = await fetch(`${servers.url}/signin`, {
62 method: "POST",
63 headers: { origin: servers.url },
64 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
65 redirect: "manual",
66 });
67 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
68 });
69 afterAll(() => {
70 servers.stop();
71 app.close();
72 rmSync(root, { recursive: true, force: true });
73 });
74
75 test("GET /asked names its phases and costs a bounded number of statements with 500 asks", async () => {
76 const get = () => fetch(`${servers.url}/asked?show=all`, { headers: { cookie } });
77 await (await get()).text();
78 // The best of three: a shared runner's stall hits one request, not the page's cost.
79 for (let i = 0; i < 3; i++) {
80 const res = await get();
81 const body = await res.text();
82 expect(res.status).toBe(200);
83 expect(body).toContain("500 asked · 250 landed");
84 const parts = (res.headers.get("server-timing") ?? "").split(", ");
85 for (const name of ["app", "session", "repos", "counts", "asks", "thoughts", "flags", "render"])
86 expect(parts.find((p) => p.startsWith(`${name};`))).toMatch(/^[a-z]+;dur=\d+\.\d$/);
87 }
88 expectWork(await requestStatements(app.db, `${servers.url}/asked?show=all`, { headers: { cookie } }), { max: 35 });
89 });
test/asked.test.ts deleted −669
@@ -1,669 +0,0 @@
1 /**
2 * `/asked`: what people asked of the crew, oldest unmet first, with one state
3 * word each and a flag when nothing was built — the same rows on the page,
4 * the API and the MCP, and only for repositories the viewer can write.
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 { createApp, type App } from "../src/app.ts";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { openIssue } from "../src/actions/issues.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import {
17 ASKED_LIMIT,
18 askedCounts,
19 askedIn,
20 askedRepos,
21 STALE_DAYS,
22 } from "../src/core/asked.ts";
23 import { addComment, createIssue, type Issue } from "../src/core/issues.ts";
24 import type { Repo } from "../src/core/repos.ts";
25 import { createRun } from "../src/core/runs.ts";
26 import { createToken } from "../src/core/tokens.ts";
27 import { createUser, getUserByName, type User } from "../src/core/users.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30
31 quietLogs();
32
33 const DAY = 24 * 60 * 60 * 1000;
34
35 describe("what you asked for", () => {
36 let dataDir = "";
37 let app: App;
38 let servers: Servers;
39 let alice: User;
40 let bob: User;
41 let repo: Repo;
42 let aliceRo = "";
43 let bobRo = "";
44 const asks: Record<string, Issue> = {};
45 let nextId = 1;
46 let crewAt = "";
47
48 const ask = (who: User, title: string): Issue => {
49 const made = openIssue(app, who, repo, { title });
50 if (!made.ok) throw new Error(String(made.error));
51 return made.value;
52 };
53
54 /** A pull from `branch` whose description closes `issue`. */
55 const pullFor = async (issue: Issue, branch: string) => {
56 const committed = await commitToBranch(app, alice, repo, {
57 branch,
58 base: "main",
59 message: branch,
60 files: [{ path: `${branch.replace(/\//g, "-")}.md`, content: "x\n" }],
61 });
62 if (!committed.ok) throw new Error(String(committed.error));
63 const opened = await openPull(app, alice, repo, {
64 title: `Answers #${issue.number}`,
65 body: `Closes #${issue.number}`,
66 baseBranch: "main",
67 headBranch: branch,
68 });
69 if (!opened.ok) throw new Error(String(opened.error));
70 return opened.value;
71 };
72
73 const backdate = (issue: Issue, days: number) =>
74 app.db
75 .query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
76 .run(new Date(Date.now() - days * DAY).toISOString(), issue.id);
77
78 const api = async (token: string | null, path: string) => {
79 const res = await fetch(`${servers.url}${path}`, {
80 headers: token === null ? {} : { authorization: `Bearer ${token}` },
81 redirect: "manual",
82 });
83 return {
84 status: res.status,
85 body: res.status === 200 ? ((await res.json()) as any) : null,
86 };
87 };
88
89 const mcp = async (token: string, args: unknown) => {
90 const res = await fetch(`${servers.url}/mcp`, {
91 method: "POST",
92 headers: {
93 "content-type": "application/json",
94 accept: "application/json, text/event-stream",
95 authorization: `Bearer ${token}`,
96 },
97 body: JSON.stringify({
98 jsonrpc: "2.0",
99 id: nextId++,
100 method: "tools/call",
101 params: { name: "asked", arguments: args },
102 }),
103 });
104 const body = (await res.json()) as any;
105 const text: string = body.result.content[0].text;
106 return body.result.isError === true
107 ? { error: text }
108 : { value: JSON.parse(text) };
109 };
110
111 beforeAll(async () => {
112 dataDir = await mkdtemp(join(tmpdir(), "forge-asked-"));
113 app = createApp({ dataDir, port: 0 });
114 servers = await serve(app);
115 const a = await createUser(app.db, { origin: "seed", trusted: true,
116 username: "alice",
117 email: "[email protected]",
118 password: "a-good-passphrase",
119 adminIfFirst: true,
120 });
121 if (!a.ok) throw new Error(a.error);
122 alice = a.value;
123 const b = await createUser(app.db, { origin: "seed", trusted: true,
124 username: "bob",
125 email: "[email protected]",
126 password: "a-good-passphrase",
127 });
128 if (!b.ok) throw new Error(b.error);
129 bob = b.value;
130 aliceRo = createToken(app.db, alice.id, "ro", "ro").token;
131 bobRo = createToken(app.db, bob.id, "ro", "ro").token;
132 const made = await createRepo(app, alice, {
133 name: "garden",
134 visibility: "public",
135 });
136 if (!made.ok) throw new Error(String(made.error));
137 repo = made.value;
138 await commitToBranch(app, alice, repo, {
139 message: "seed",
140 files: [{ path: "README.md", content: "# garden\n" }],
141 });
142 const bot = await createAgent(app, alice, { username: "bot" });
143 if (!bot.ok) throw new Error(String(bot.error));
144
145 asks["waiting"] = ask(alice, "Plant tomatoes");
146 asks["stale"] = ask(alice, "Fix the gate");
147 backdate(asks["stale"], STALE_DAYS + 1);
148 asks["building"] = ask(alice, "A watering schedule");
149 const building = await pullFor(asks["building"], "work/building");
150 // The crew worked the pull an hour ago: that is the row's last activity.
151 const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: building.id });
152 crewAt = new Date(Date.now() - 3_600_000).toISOString();
153 app.db.query("UPDATE run SET created_at = ?1 WHERE id = ?2").run(crewAt, run.id);
154 asks["shipped"] = ask(alice, "Prune the roses");
155 const merged = await pullFor(asks["shipped"], "work/shipped");
156 // A merge, as the row records it: the pull and the issue close.
157 app.db
158 .query("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2")
159 .run(new Date().toISOString(), merged.id);
160 app.db
161 .query("UPDATE issue SET state = 'closed' WHERE id IN (?1, ?2)")
162 .run(merged.id, asks["shipped"].id);
163 asks["closed"] = ask(alice, "Paint the shed");
164 app.db
165 .query("UPDATE issue SET state = 'closed' WHERE id = ?1")
166 .run(asks["closed"].id);
167 // An agent's issue is not an ask.
168 asks["agent"] = ask(
169 getUserByName(app.db, "bot")!,
170 "Refactor the watering module",
171 );
172 }, 30_000);
173
174 afterAll(async () => {
175 servers.stop();
176 app.close();
177 await rm(dataDir, { recursive: true, force: true });
178 });
179
180 const states = () =>
181 Object.fromEntries(
182 askedIn(app.db, [repo], { show: "all" }).map((a) => [a.issue.title, a.state]),
183 );
184
185 test("each ask gets one state word from its pulls and its issue", () => {
186 expect(states()).toEqual({
187 "Plant tomatoes": "waiting",
188 "Fix the gate": "waiting",
189 "A watering schedule": "building",
190 "Prune the roses": "shipped",
191 "Paint the shed": "closed",
192 });
193 });
194
195 test("an agent's issue is not an ask", () => {
196 expect(states()["Refactor the watering module"]).toBeUndefined();
197 });
198
199 test("the counts, made in SQL, agree with the list kind by kind", () => {
200 const all = askedIn(app.db, [repo], { show: "all", limit: ASKED_LIMIT });
201 expect(askedCounts(app.db, [repo])).toEqual({
202 asked: all.length,
203 shipped: all.filter((a) => a.state === "shipped").length,
204 unshipped: all.filter((a) => a.state === "waiting" || a.state === "building").length,
205 flagged: all.filter((a) => a.flagged).length,
206 });
207 expect(askedCounts(app.db, [])).toEqual({ asked: 0, shipped: 0, unshipped: 0, flagged: 0 });
208 // The fixture holds every state, so the agreement is not a run of zeros.
209 expect(new Set(all.map((a) => a.state))).toEqual(
210 new Set(["waiting", "building", "shipped", "closed"]),
211 );
212 });
213
214 test("by default: nothing merged yet, oldest first; newest first on request", () => {
215 const rows = askedIn(app.db, [repo]);
216 expect(rows.map((a) => a.issue.title)).toEqual([
217 "Fix the gate",
218 "Plant tomatoes",
219 "A watering schedule",
220 ]);
221 expect(
222 askedIn(app.db, [repo], { order: "newest" }).map((a) => a.issue.title),
223 ).toEqual(["A watering schedule", "Plant tomatoes", "Fix the gate"]);
224 });
225
226 test("an ask with nothing built past the window is flagged", () => {
227 expect(
228 askedIn(app.db, [repo], { show: "all" })
229 .filter((a) => a.flagged)
230 .map((a) => a.issue.title),
231 ).toEqual(["Fix the gate"]);
232 expect(
233 askedIn(app.db, [repo], { show: "flagged" }).map((a) => a.issue.title),
234 ).toEqual(["Fix the gate"]);
235 });
236
237 test("each row carries the crew's last activity, from the ask or its pulls", () => {
238 const rows = new Map(askedIn(app.db, [repo]).map((a) => [a.issue.title, a]));
239 expect(rows.get("A watering schedule")!.lastCrewAt).toBe(crewAt);
240 expect(rows.get("Plant tomatoes")!.lastCrewAt).toBeNull();
241 });
242
243 test("a person who cannot write the repository reads nothing about it", () => {
244 expect(askedRepos(app.db, bob, null)).toEqual([]);
245 expect(askedRepos(app.db, bob, "alice/garden")).toEqual([]);
246 expect(
247 askedRepos(app.db, alice, "alice/garden").map((r) => r.name),
248 ).toEqual(["garden"]);
249 });
250
251 test("the page lists the asks with their words; a signed-out reader is sent to sign in", async () => {
252 const out = await fetch(`${servers.url}/asked`, { redirect: "manual" });
253 expect(out.status).toBe(303);
254 expect(out.headers.get("location")).toContain("/signin");
255
256 const signin = await fetch(`${servers.url}/signin`, {
257 method: "POST",
258 body: new URLSearchParams({
259 username: "alice",
260 password: "a-good-passphrase",
261 }),
262 redirect: "manual",
263 });
264 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
265 const res = await fetch(`${servers.url}/asked`, { headers: { cookie } });
266 expect(res.status).toBe(200);
267 const page = (await res.text()).replace(/\s+/g, " ");
268 expect(page).toContain("What you asked for");
269 expect(page).toContain("Plant tomatoes");
270 // The filter bar is §5's bar: the retired .filters is gone, the words stay.
271 expect(page).not.toMatch(/class="[^"]*\bfilters\b/);
272 expect(page).toContain("Not shipped");
273 expect(page).toContain("Nothing built");
274 expect(page).toContain("Show newest first");
275 expect(page).not.toContain("Refactor the watering module");
276 // The default view is what has nothing merged yet: the shipped ask waits behind "All".
277 expect(page).not.toContain("Prune the roses");
278 expect(page).toContain("not placed yet");
279 expect(page.indexOf("Fix the gate")).toBeLessThan(page.indexOf("Plant tomatoes"));
280 // Reached from the board and the feed's header, not only the asks page.
281 expect(await (await fetch(`${servers.url}/board`, { headers: { cookie } })).text()).toContain('href="/asked"');
282 expect(await (await fetch(`${servers.url}/feed`, { headers: { cookie } })).text()).toContain('href="/asked"');
283 const flagged = (
284 await (
285 await fetch(`${servers.url}/asked?show=flagged`, {
286 headers: { cookie },
287 })
288 ).text()
289 ).replace(/\s+/g, " ");
290 expect(flagged).toContain("Fix the gate");
291 expect(flagged).not.toContain("Plant tomatoes");
292 });
293
294 test("the API answers the same rows, only to a token, and nothing to a stranger", async () => {
295 expect((await api(null, "/api/v1/asked")).status).toBe(401);
296 const mine = await api(aliceRo, "/api/v1/asked");
297 expect(mine.status).toBe(200);
298 expect(mine.body.asked.map((a: any) => a.title).sort()).toEqual([
299 "A watering schedule",
300 "Fix the gate",
301 "Plant tomatoes",
302 ]);
303 const building = mine.body.asked.find(
304 (a: any) => a.title === "A watering schedule",
305 );
306 expect(building.pulls[0].state).toBe("open");
307 expect((await api(bobRo, "/api/v1/asked")).body.asked).toEqual([]);
308 expect((await api(aliceRo, "/api/v1/asked?show=nope")).status).toBe(422);
309 expect((await api(aliceRo, "/api/v1/asked?order=nope")).status).toBe(422);
310 expect(building.lastCrewAt).toBe(crewAt);
311 expect(Object.keys(building.pulls[0]).sort()).toEqual([
312 "number",
313 "openedAt",
314 "state",
315 "title",
316 ]);
317 });
318
319 test("the MCP `asked` tool reads the same rows, with an ro token", async () => {
320 const all = await mcp(aliceRo, { repo: "alice/garden", show: "flagged" });
321 expect(all.value.asked.map((a: any) => a.title)).toEqual(["Fix the gate"]);
322 expect((await mcp(bobRo, { repo: "alice/garden" })).error).toContain(
323 "not_found",
324 );
325 expect((await mcp(bobRo, {})).value.asked).toEqual([]);
326 });
327
328 test("the page leads each row with what became of it, so a narrow screen cuts where and who, not that", async () => {
329 const signin = await fetch(`${servers.url}/signin`, {
330 method: "POST",
331 body: new URLSearchParams({
332 username: "alice",
333 password: "a-good-passphrase",
334 }),
335 redirect: "manual",
336 });
337 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
338 const page = await (
339 await fetch(`${servers.url}/asked`, { headers: { cookie } })
340 ).text();
341 const meta = (title: string) =>
342 (
343 page.match(
344 new RegExp(
345 `${title}</a></span\\s*>\\s*<span class="row-meta">([\\s\\S]*?)</span>`,
346 ),
347 )?.[1] ?? ""
348 )
349 .replace(/<[^>]+>/g, "")
350 .replace(/\s+/g, " ")
351 .trim();
352 expect(meta("Plant tomatoes")).toStartWith(
353 "not placed yet · alice/garden #",
354 );
355 expect(meta("A watering schedule")).toMatch(
356 /^aliceowner building in #\d+ · alice\/garden #\d+$/,
357 );
358 });
359
360 // Last, because it moves the crew's last activity the tests above read.
361 test("an agent's comment is the crew's last activity too; a person's comment is not", () => {
362 const bot = getUserByName(app.db, "bot")!;
363 const at = (minutesAgo: number) =>
364 new Date(Date.now() - minutesAgo * 60_000).toISOString();
365 const say = (who: User, issueId: string, when: string) => {
366 const said = addComment(app.db, {
367 issueId,
368 authorId: who.id,
369 body: "A word on this.",
370 });
371 if (!said.ok) throw new Error(said.error);
372 app.db
373 .query("UPDATE comment SET created_at = ?1 WHERE id = ?2")
374 .run(when, said.value.id);
375 };
376 const lastOf = (title: string) =>
377 askedIn(app.db, [repo]).find((a) => a.issue.title === title)!;
378
379 // Nothing ran on this ask: the agent's comment alone is the activity,
380 // and the person's later one does not move it.
381 const botAt = at(120);
382 say(bot, asks["waiting"]!.id, botAt);
383 say(alice, asks["waiting"]!.id, at(5));
384 expect(lastOf("Plant tomatoes").lastCrewAt).toBe(botAt);
385
386 // On a pull that closes the ask, newer than the run: the comment wins.
387 const building = lastOf("A watering schedule");
388 const onPull = at(10);
389 say(bot, building.pulls[0]!.id, onPull);
390 expect(lastOf("A watering schedule").lastCrewAt).toBe(onPull);
391 // And an older comment does not move it back.
392 say(bot, building.issue.id, at(600));
393 expect(lastOf("A watering schedule").lastCrewAt).toBe(onPull);
394 });
395 });
396
397 describe("an old ask says what exists for it", () => {
398 let dataDir = "";
399 let app: App;
400 let servers: Servers;
401 let alice: User;
402 let repo: Repo;
403 let ro = "";
404
405 const old = (title: string, days: number): Issue => {
406 const made = openIssue(app, alice, repo, { title });
407 if (!made.ok) throw new Error(String(made.error));
408 app.db
409 .query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
410 .run(new Date(Date.now() - days * DAY).toISOString(), made.value.id);
411 return made.value;
412 };
413 /** A pull that closes `issue`, opened `days` ago. */
414 const pullFor = async (issue: Issue, branch: string, days: number) => {
415 const committed = await commitToBranch(app, alice, repo, {
416 branch,
417 base: "main",
418 message: branch,
419 files: [{ path: `${branch}.md`, content: "x\n" }],
420 });
421 if (!committed.ok) throw new Error(String(committed.error));
422 const opened = await openPull(app, alice, repo, {
423 title: `Answers #${issue.number}`,
424 body: `Closes #${issue.number}`,
425 baseBranch: "main",
426 headBranch: branch,
427 });
428 if (!opened.ok) throw new Error(String(opened.error));
429 app.db
430 .query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
431 .run(new Date(Date.now() - days * DAY).toISOString(), opened.value.id);
432 return opened.value;
433 };
434
435 beforeAll(async () => {
436 dataDir = await mkdtemp(join(tmpdir(), "forge-asked-old-"));
437 app = createApp({ dataDir, port: 0 });
438 servers = await serve(app);
439 const a = await createUser(app.db, { origin: "seed", trusted: true,
440 username: "alice",
441 email: "[email protected]",
442 password: "a-good-passphrase",
443 adminIfFirst: true,
444 });
445 if (!a.ok) throw new Error(a.error);
446 alice = a.value;
447 ro = createToken(app.db, alice.id, "ro", "ro").token;
448 const made = await createRepo(app, alice, {
449 name: "garden",
450 visibility: "private",
451 });
452 if (!made.ok) throw new Error(String(made.error));
453 repo = made.value;
454 await commitToBranch(app, alice, repo, {
455 message: "seed",
456 files: [{ path: "README.md", content: "# garden\n" }],
457 });
458 // All four were asked five days ago, past the three-day window.
459 old("Nothing at all", 5);
460 await pullFor(old("A pull is open", 5), "open", 2);
461 const dropped = await pullFor(old("Its only pull closed", 5), "dropped", 4);
462 app.db
463 .query("UPDATE issue SET state = 'closed' WHERE id = ?1")
464 .run(dropped.id);
465 const onIt = old("The crew is on it", 5);
466 createRun(app.db, { repoId: repo.id, kind: "agent", issueId: onIt.id });
467 // And one asked today, with a pull opened today.
468 await pullFor(old("Asked today", 0), "today", 0);
469 }, 30_000);
470
471 afterAll(async () => {
472 servers.stop();
473 app.close();
474 await rm(dataDir, { recursive: true, force: true });
475 });
476
477 const rows = () =>
478 new Map(
479 askedIn(app.db, [repo], { show: "all" }).map((a) => [a.issue.title, a]),
480 );
481
482 test("nothing built is for an old ask with no pull open or merged and nobody on it", () => {
483 const all = rows();
484 const facts = (title: string) => {
485 const a = all.get(title)!;
486 return [a.state, a.stale, a.flagged];
487 };
488 expect(facts("Nothing at all")).toEqual(["waiting", true, true]);
489 expect(facts("Its only pull closed")).toEqual(["waiting", true, true]);
490 expect(facts("A pull is open")).toEqual(["building", true, false]);
491 expect(facts("The crew is on it")).toEqual(["building", true, false]);
492 expect(facts("Asked today")).toEqual(["building", false, false]);
493 expect(
494 askedIn(app.db, [repo], { show: "flagged" }).map((a) => a.issue.title),
495 ).toEqual(["Nothing at all", "Its only pull closed"]);
496 expect(askedCounts(app.db, [repo])).toEqual({
497 asked: 5,
498 shipped: 0,
499 unshipped: 5,
500 flagged: 2,
501 });
502 });
503
504 test("the page says a pull is open and for how long; red only where nothing exists", async () => {
505 const signin = await fetch(`${servers.url}/signin`, {
506 method: "POST",
507 body: new URLSearchParams({
508 username: "alice",
509 password: "a-good-passphrase",
510 }),
511 redirect: "manual",
512 });
513 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
514 const page = await (
515 await fetch(`${servers.url}/asked`, { headers: { cookie } })
516 ).text();
517 /** The badge of the row with this title: its tone and its words. */
518 const badgeOf = (title: string): string => {
519 const row =
520 page.match(
521 new RegExp(
522 `${title}</a></span[\\s\\S]*?<span class="row-trail">([\\s\\S]*?)</li>`,
523 ),
524 )?.[1] ?? "";
525 const tone = row.match(/data-variant="(\w+)"/)?.[1] ?? "default";
526 return `${tone}: ${row
527 .replace(/<[^>]+>/g, "")
528 .replace(/\s+/g, " ")
529 .trim()}`;
530 };
531 expect(badgeOf("Nothing at all")).toBe("danger: Nothing built");
532 expect(badgeOf("Its only pull closed")).toBe("danger: Nothing built");
533 expect(badgeOf("A pull is open")).toBe("attn: Building");
534 expect(badgeOf("The crew is on it")).toBe("attn: Building");
535 expect(badgeOf("Asked today")).toBe("attn: Building");
536 expect(page).toContain("5 asked · 0 landed · 2 with nothing built");
537 });
538
539 test("the API and the MCP say stale and flagged apart, and when each pull was opened", async () => {
540 const res = await fetch(`${servers.url}/api/v1/asked?show=all`, {
541 headers: { authorization: `Bearer ${ro}` },
542 });
543 const asked = ((await res.json()) as any).asked as any[];
544 const open = asked.find((a) => a.title === "A pull is open");
545 expect([open.stale, open.flagged]).toEqual([true, false]);
546 expect(Date.now() - Date.parse(open.pulls[0].openedAt)).toBeGreaterThan(
547 2 * DAY - 60_000,
548 );
549 const none = asked.find((a) => a.title === "Nothing at all");
550 expect([none.stale, none.flagged]).toEqual([true, true]);
551 const mcp = await fetch(`${servers.url}/mcp`, {
552 method: "POST",
553 headers: {
554 "content-type": "application/json",
555 accept: "application/json, text/event-stream",
556 authorization: `Bearer ${ro}`,
557 },
558 body: JSON.stringify({
559 jsonrpc: "2.0",
560 id: 1,
561 method: "tools/call",
562 params: { name: "asked", arguments: { show: "flagged" } },
563 }),
564 });
565 const told = JSON.parse(((await mcp.json()) as any).result.content[0].text)
566 .asked as any[];
567 expect(told.map((a) => a.title)).toEqual([
568 "Nothing at all",
569 "Its only pull closed",
570 ]);
571 });
572 });
573
574 describe("a repository with more asks than one read", () => {
575 /** More than the 2,000 the scan once stopped at. */
576 const MANY = 2_100;
577 let dataDir = "";
578 let app: App;
579 let repo: Repo;
580 let alice: User;
581
582 beforeAll(async () => {
583 dataDir = await mkdtemp(join(tmpdir(), "forge-asked-many-"));
584 app = createApp({ dataDir, port: 0 });
585 const a = await createUser(app.db, { origin: "seed", trusted: true,
586 username: "alice",
587 email: "[email protected]",
588 password: "a-good-passphrase",
589 adminIfFirst: true,
590 });
591 if (!a.ok) throw new Error(a.error);
592 alice = a.value;
593 const made = await createRepo(app, alice, {
594 name: "orchard",
595 visibility: "private",
596 });
597 if (!made.ok) throw new Error(String(made.error));
598 repo = made.value;
599 // One ask from long ago that nothing was built for, then many since.
600 app.db.exec("BEGIN");
601 for (let i = 0; i <= MANY; i++) {
602 const opened = createIssue(app.db, {
603 repoId: repo.id,
604 authorId: alice.id,
605 title: i === 0 ? "The oldest wish" : `Ask ${i}`,
606 });
607 if (!opened.ok) throw new Error(opened.error);
608 }
609 app.db.exec("COMMIT");
610 // Asked a minute apart, oldest first, the first one a month ago.
611 app.db
612 .query(
613 `UPDATE issue SET created_at =
614 strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01T00:00:00Z', '+' || number || ' minutes')
615 WHERE repo_id = ?1`,
616 )
617 .run(repo.id);
618 }, 60_000);
619
620 afterAll(async () => {
621 app.close();
622 await rm(dataDir, { recursive: true, force: true });
623 });
624
625 const now = new Date("2026-02-01T00:00:00Z");
626
627 test("the oldest unmet ask is first, however many came after", () => {
628 const rows = askedIn(app.db, [repo], { now });
629 expect(rows).toHaveLength(ASKED_LIMIT);
630 expect(rows[0]!.issue.title).toBe("The oldest wish");
631 expect(rows[1]!.issue.title).toBe("Ask 1");
632 expect(rows.every((a) => a.flagged)).toBe(true);
633 const newest = askedIn(app.db, [repo], { now, order: "newest" });
634 expect(newest[0]!.issue.title).toBe(`Ask ${MANY}`);
635 expect(newest.at(-1)!.issue.title).toBe(`Ask ${MANY - ASKED_LIMIT + 1}`);
636 });
637
638 test("the counts are of every ask, not of one page", () => {
639 expect(askedCounts(app.db, [repo], now)).toEqual({
640 asked: MANY + 1,
641 shipped: 0,
642 unshipped: MANY + 1,
643 flagged: MANY + 1,
644 });
645 });
646
647 test("asks that are closed are read past: the page still fills with what is unmet, oldest first", () => {
648 // Everything but the oldest wish and the newest fifty is closed.
649 app.db
650 .query(
651 "UPDATE issue SET state = 'closed' WHERE repo_id = ?1 AND number > 1 AND number <= ?2",
652 )
653 .run(repo.id, MANY + 1 - 50);
654 const rows = askedIn(app.db, [repo], { now });
655 expect(rows.map((a) => a.issue.title)).toEqual([
656 "The oldest wish",
657 ...Array.from({ length: 50 }, (_, i) => `Ask ${MANY - 49 + i}`),
658 ]);
659 expect(askedCounts(app.db, [repo], now)).toEqual({
660 asked: MANY + 1,
661 shipped: 0,
662 unshipped: 51,
663 flagged: 51,
664 });
665 expect(askedIn(app.db, [repo], { now, show: "all" })).toHaveLength(
666 ASKED_LIMIT,
667 );
668 });
669 });
test/cache-private.test.ts −1
@@ -62,7 +62,6 @@ describe("cache headers", () => {
6262 "/",
6363 "/ada/secret",
6464 "/ada/secret/issues/1",
65 "/asked",
6665 "/forges",
6766 "/api/v1/feed",
6867 "/api/v1/repos/ada/secret/issues/1",
test/cold-home-queries.test.ts +1 −1
@@ -5,7 +5,7 @@
55 */
66 import { afterAll, beforeAll, expect, test } from "bun:test";
77 import { breakerParked, WAITING_NOTES } from "../src/crew/breaker.ts";
8 import { pullsByAsk } from "../src/core/asked.ts";
8 import { pullsByAsk } from "../src/core/thought_stream.ts";
99 import { readPipeline } from "../src/flow/pipeline.ts";
1010 import { readVitals } from "../src/flow/vitals.ts";
1111 import { id } from "../src/kernel/id.ts";
test/crew-parks-done.test.ts +1 −25
@@ -23,7 +23,6 @@ import {
2323 } from "../src/crew/already.ts";
2424 import { repoDir } from "../src/git/repos.ts";
2525 import { alreadyDone } from "../src/core/done_on_main.ts";
26 import { askedIn, askedJson } from "../src/core/asked.ts";
2726 import { answerCancelled, cancelRun, createRun } from "../src/core/runs.ts";
2827 import { parkedTwice, struckOut } from "../src/crew/parks.ts";
2928 import { engine, tick, type Engine } from "./helpers/parks-engine.ts";
@@ -115,13 +114,9 @@ describe("an issue found already done is the asker's to close, not a park", () =
115114 ).toBe(true);
116115 });
117116
118 test("the asked JSON carries the commits; closing through any door writes the note", async () => {
117 test("closing through any door writes the note", async () => {
119118 const work = e.issue("Asked and already built");
120119 expect(settle(work, "ok", alreadyDoneSummary([oid]))).toBe(true);
121 const row = askedIn(e.app.db, [e.fresh()], { show: "all" }).find(
122 (a) => a.issue.id === work.id,
123 )!;
124 expect(askedJson(row).doneBy).toEqual([oid]);
125120 // Not the web form: the same close the terminal makes.
126121 expect(setIssueState(e.app, e.alice, e.fresh(), work, "closed").ok).toBe(true);
127122 const comments = listComments(e.app.db, work.id).filter((c) =>
@@ -137,25 +132,6 @@ describe("an issue found already done is the asker's to close, not a park", () =
137132 ).toBe(false);
138133 });
139134
140 test("the asked page says done on main, with the commits", async () => {
141 const work = e.issue("Asked page");
142 expect(settle(work, "ok", alreadyDoneSummary([oid]))).toBe(true);
143 const signin = await fetch(`${e.servers.url}/signin`, {
144 method: "POST",
145 body: new URLSearchParams({
146 username: "alice",
147 password: "a-good-passphrase",
148 }),
149 redirect: "manual",
150 });
151 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
152 const page = await (
153 await fetch(`${e.servers.url}/asked`, { headers: { cookie } })
154 ).text();
155 expect(page).toContain("Done on main");
156 expect(page).toContain(`on main in ${oid.slice(0, 7)}, waiting for you to close it`);
157 });
158
159135 test("an issue parked twice and then found done leaves the planner's list", () => {
160136 const work = e.issue("Parked, then built");
161137 e.ended(work, "no changes pushed: DECLINED: out of scope");
test/design-audit.test.ts +1 −1
@@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1717
1818 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1919 const NOT_PAGES =
20 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|boards\/stream$|system\/stream$|talk\/stream$|peek$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
20 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|asked$|events$|boards\/stream$|system\/stream$|talk\/stream$|peek$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2121
2222 const getRoutes = [
2323 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/forge-looks.test.ts +1 −1
@@ -40,7 +40,6 @@ const NOT_A_PAGE: Record<string, string> = {
4040 "/infra": "no picture: app.looks is at its 32 paths; an admin's view of their own cloud, screenshotted at 390 and 1280 in #16706 and covered by test/infra-page.test.ts",
4141 "/games": "no picture: not in app.looks; a game box's network, seen only with a grant on a box, covered by test/games.test.ts",
4242 "/data": "no picture: not in app.looks; a guest sees the not-found page and the page is covered by its own tests",
43 "/asked": "no picture: its slot went to /notes, the page that now leads with a person's thoughts; /asked is covered by test/asked.test.ts",
4443 "/forges": "no picture: its slot went to the preview's /waves and /milestones; the page is covered by its own tests",
4544 "/family": "no picture: its slot went to the preview's /waves and /milestones; the page is covered by its own tests",
4645 "/llms.txt": "plain markdown for machines, not a page to picture",
@@ -54,6 +53,7 @@ const NOT_A_PAGE: Record<string, string> = {
5453 "/toolbar-lab": "the toolbar's lab, pictured at 360 and 1280 by PREVIEW_TOOLBAR_LAB_PAGES in preview-looks.ts; covered by test/toolbar-lab.test.ts",
5554 "/toolbar-lab.js": "the toolbar lab's script; covered by test/toolbar-lab.test.ts",
5655 "/openapi.json": "a redirect to the contract document",
56 "/asked": "a redirect to /feed?show=mine (#16229); covered by test/home-feed.test.ts",
5757 "/favicon.ico": "the tab icon, an image",
5858 "/releases.json": "JSON feed of /releases",
5959 "/maintenance.json": "JSON rendering of the findings on /maintenance, which is pictured; covered by test/maintenance-json.test.ts",
test/home-feed.test.ts +7 −7
@@ -169,10 +169,9 @@ describe("home is the feed", () => {
169169 // missing key sits beside the timeline (after it on a phone), and
170170 // "What you asked for" is the Asked tab, the one door to /asked.
171171 expect(text).not.toContain("feed-head");
172 expect(text).not.toContain('href="/asked">What you asked for');
172 expect(text).not.toContain('href="/asked"');
173173 const note = text.indexOf('id="crew-key-note"');
174174 if (note !== -1) expect(note).toBeGreaterThan(feed);
175 expect(text).toMatch(/class="tabs"[\s\S]*?href="\/asked"/);
176175 // The old home's shelf rows and cost line are /apps's now.
177176 expect(text).not.toContain("spent today across");
178177 const apps = await (await get("/apps", aliceCookie)).text();
@@ -180,13 +179,14 @@ describe("home is the feed", () => {
180179 // Each of the three pages carries the three tabs, so a phone has a way
181180 // back that is not only the logo.
182181 expect(apps).toMatch(/class="tabs"[\s\S]*?href="\/apps"\s+aria-current="page"/);
183 const asked = await (await get("/asked", aliceCookie)).text();
184 expect(asked).toMatch(/class="tabs"[\s\S]*?href="\/asked"\s+aria-current="page"/);
185 expect(asked).toContain('href="/"');
182 // /asked is the feed narrowed to what the person opened (#16229).
183 const moved = await get("/asked", aliceCookie);
184 expect(moved.status).toBe(303);
185 expect(moved.headers.get("location")).toBe("/feed?show=mine");
186186 expect(text).toMatch(/class="tabs"[\s\S]*?href="\/feed"\s+aria-current="page"/);
187 for (const page of [apps, asked]) {
187 for (const page of [apps]) {
188188 expect(page).not.toContain("home-tabs");
189 for (const w of ["Feed", "Your apps", "Asked"]) expect(page).toContain(w);
189 for (const w of ["Feed", "Your apps"]) expect(page).toContain(w);
190190 }
191191 });
192192
test/home-frame.test.ts +2 −2
@@ -71,7 +71,7 @@ test("after a write, signed-in home is answered from memory within the budget an
7171 expect(warm).toBeLessThanOrEqual(STATEMENT_BUDGET);
7272 // A look from memory is cheaper than a cold draw of the same page, so the budget means something.
7373 expect(warm).toBeLessThan(medianCount(colds));
74 for (const name of ["waiting", "panels", "asked", "feed"]) {
74 for (const name of ["waiting", "panels", "feed"]) {
7575 expect(marked).toContain(`id="home-${name}"`);
7676 }
7777 expect(marked).toContain('data-refresh="/live/home/feed"');
@@ -83,7 +83,7 @@ test("the first response stays under its byte limit", async () => {
8383 });
8484
8585 test("each late region answers alone, to its own viewer, and to no one else", async () => {
86 for (const name of ["waiting", "panels", "asked", "feed"]) {
86 for (const name of ["waiting", "panels", "feed"]) {
8787 const res = await fetch(`${f.base}/live/home/${name}`, { headers: { cookie: f.ownerCookie } });
8888 expect(res.status).toBe(200);
8989 expect((await res.text()).length).toBeGreaterThan(0);
test/mcp-asked-args.test.ts deleted −127
@@ -1,127 +0,0 @@
1 /** The `asked` tool takes only the known `show` and `order` words, and lists nothing in a repository the caller cannot write. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { askedIn, askedRepos, askedJson } from "../src/core/asked.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { createToken } from "../src/core/tokens.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13
14 const DAY = 24 * 60 * 60 * 1000;
15
16 describe("MCP asked arguments", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let alice: User;
21 let aliceTok: string;
22 let bobTok: string;
23 let id = 1;
24
25 const call = async (token: string, args: unknown = {}) => {
26 const res = await fetch(`${servers.url}/mcp`, {
27 method: "POST",
28 headers: {
29 "content-type": "application/json",
30 accept: "application/json, text/event-stream",
31 authorization: `Bearer ${token}`,
32 },
33 body: JSON.stringify({
34 jsonrpc: "2.0",
35 id: id++,
36 method: "tools/call",
37 params: { name: "asked", arguments: args },
38 }),
39 });
40 const body: any = await res.json();
41 const text: string = body.result.content[0].text;
42 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
43 };
44
45 /** What the /asked page reads for these choices. */
46 const page = (show: "all" | "unshipped" | "flagged", order: "oldest" | "newest") =>
47 askedIn(app.db, askedRepos(app.db, alice, null), { show, order }).map(askedJson);
48
49 beforeAll(async () => {
50 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-asked-args-"));
51 app = createApp({ dataDir, port: 0 });
52 servers = await serve(app);
53 const mk = async (username: string, first = false) => {
54 const u = await createUser(app.db, {
55 origin: "seed",
56 trusted: true,
57 username,
58 email: `${username}@forge.local`,
59 password: "a-good-passphrase",
60 adminIfFirst: first,
61 });
62 if (!u.ok) throw new Error(u.error);
63 return u.value;
64 };
65 alice = await mk("alice", true);
66 const bob = await mk("bob");
67 aliceTok = createToken(app.db, alice.id, "ro", "ro").token;
68 bobTok = createToken(app.db, bob.id, "ro", "ro").token;
69 for (const [name, visibility] of [["open", "public"], ["secret", "private"]] as const) {
70 const made = await createRepo(app, alice, { name, visibility });
71 if (!made.ok) throw new Error(String(made.error));
72 for (const [n, days] of [["first", 9], ["second", 5], ["third", 1]] as const) {
73 const issue = createIssue(app.db, { repoId: made.value.id, authorId: alice.id, title: `${n} in ${name}` });
74 if (!issue.ok) throw new Error(issue.error);
75 app.db
76 .query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
77 .run(new Date(Date.now() - days * DAY).toISOString(), issue.value.id);
78 }
79 }
80 // One ask is done with, so "all" has more than "unshipped".
81 app.db.query("UPDATE issue SET state = 'closed' WHERE title = 'second in open'").run();
82 }, 30_000);
83
84 afterAll(async () => {
85 servers.stop();
86 app.close();
87 await rm(dataDir, { recursive: true, force: true });
88 });
89
90 test("no arguments lists unshipped asks, oldest first", async () => {
91 const got = await call(aliceTok);
92 const titles = got.value.asked.map((a: any) => a.title);
93 expect(titles.length).toBeGreaterThan(0);
94 expect(got.value.asked).toEqual(page("unshipped", "oldest"));
95 const times: string[] = got.value.asked.map((a: any) => a.askedAt);
96 expect(times).toEqual([...times].sort());
97 expect(titles).not.toContain("second in open");
98 });
99
100 test("each known show and order returns what the page shows", async () => {
101 for (const show of ["unshipped", "flagged", "all"] as const)
102 for (const order of ["oldest", "newest"] as const)
103 expect((await call(aliceTok, { show, order })).value.asked).toEqual(page(show, order));
104 const all = (await call(aliceTok, { show: "all" })).value.asked;
105 expect(all.map((a: any) => a.title)).toContain("second in open");
106 const newest = (await call(aliceTok, { order: "newest" })).value.asked;
107 expect(newest.map((a: any) => a.title)).toEqual(
108 [...(await call(aliceTok)).value.asked].reverse().map((a: any) => a.title),
109 );
110 });
111
112 test("an unknown show or order is refused", async () => {
113 expect((await call(aliceTok, { show: "everything" })).error).toContain('argument "show"');
114 expect((await call(aliceTok, { order: "random" })).error).toContain('argument "order"');
115 expect((await call(aliceTok, { show: "all", order: "random" })).error).toContain('argument "order"');
116 });
117
118 test("a repository the caller cannot read lists nothing about it", async () => {
119 const mine = await call(aliceTok, { repo: "alice/secret" });
120 expect(mine.value.asked.length).toBe(3);
121 const theirs = await call(bobTok, { repo: "alice/secret" });
122 expect(theirs.error).toContain("not_found");
123 expect(JSON.stringify(theirs)).not.toContain("in secret");
124 const none = await call(bobTok);
125 expect(none.value.asked).toEqual([]);
126 });
127 });
test/mcp-asked-card.test.ts deleted −93
@@ -1,93 +0,0 @@
1 /** MCP `asked` draws the `ui://forge/asked` card: flagged first, a state per ask, linked to the closing pull or the issue. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createIssue } from "../src/core/issues.ts";
9 import { createToken } from "../src/core/tokens.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { cardFor } from "../src/web/studio/cards.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 const DAY = 24 * 60 * 60 * 1000;
18
19 describe("MCP asked card", () => {
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let token = "";
24 const numbers: Record<string, number> = {};
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-asked-card-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 const a = await createUser(app.db, { origin: "seed", trusted: true,
31 username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
32 if (!a.ok) throw new Error("users");
33 token = createToken(app.db, a.value.id, "ro", "ro").token;
34 const made = await createRepo(app, a.value, { name: "game", visibility: "private" });
35 if (!made.ok) throw new Error(String(made.error));
36 // The older ask is stale with nothing built, so it is flagged and oldest-first leads with it.
37 for (const [title, days] of [["stale and unbuilt", 9], ["fresh", 1]] as const) {
38 const i = createIssue(app.db, { repoId: made.value.id, authorId: a.value.id, title });
39 if (!i.ok) throw new Error(i.error);
40 app.db.query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
41 .run(new Date(Date.now() - days * DAY).toISOString(), i.value.id);
42 numbers[title] = i.value.number;
43 }
44 }, 30_000);
45
46 afterAll(async () => {
47 servers.stop();
48 app.close();
49 await rm(dataDir, { recursive: true, force: true });
50 });
51
52 test("tools/call asked carries the card, flagged first, beside an unchanged text answer", async () => {
53 const res = await fetch(`${servers.url}/mcp`, {
54 method: "POST",
55 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
56 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "asked", arguments: {} } }),
57 });
58 const body: any = await res.json();
59 const text = JSON.parse(body.result.content[0].text);
60 expect(text.asked.map((x: any) => x.title)).toEqual(["stale and unbuilt", "fresh"]);
61 expect(text.asked[0].flagged).toBe(true);
62 const card = body.result.structuredContent.card;
63 expect(card.kind).toBe("asked");
64 expect(card.status).toBe("2 waiting · 1 flagged");
65 // Put "fresh" first in the answer's order: the card still leads with the flagged ask.
66 const flipped = cardFor("asked", { asked: [...text.asked].reverse() }, servers.url)!;
67 expect(flipped.rows.map((r) => r.label)).toEqual(["stale and unbuilt", "fresh"]);
68 expect(card.rows).toEqual([
69 { label: "stale and unbuilt", value: "waiting", link: `${servers.url}/alice/game/issues/${numbers["stale and unbuilt"]}` },
70 { label: "fresh", value: "waiting", link: `${servers.url}/alice/game/issues/${numbers["fresh"]}` },
71 ]);
72 });
73
74 test("the closing pull, the 80-character cut, the 20-row ceiling, links only on this forge", () => {
75 const ask = (over: Record<string, unknown>) => ({ repo: "alice/game", number: 1, title: "t", state: "waiting", flagged: false, pulls: [], ...over });
76 const card = cardFor("asked", { asked: [
77 ask({ number: 1, title: "x".repeat(200), state: "shipped", pulls: [{ number: 7, state: "closed" }, { number: 9, state: "merged" }] }),
78 ask({ number: 2, state: "building", pulls: [{ number: 8, state: "open" }] }),
79 ask({ number: 3, state: "closed" }),
80 ] }, "https://forge.test")!;
81 expect(card.status).toBe("0 waiting · 0 flagged");
82 expect(card.rows[0]!.label.length).toBe(80);
83 expect(card.rows.map((r) => r.link)).toEqual([
84 "https://forge.test/alice/game/pulls/9",
85 "https://forge.test/alice/game/pulls/8",
86 "https://forge.test/alice/game/issues/3",
87 ]);
88 const many = Array.from({ length: 30 }, (_, i) => ask({ number: i + 1 }));
89 expect(cardFor("asked", { asked: many }, "https://forge.test")!.rows.length).toBe(20);
90 expect(cardFor("asked", { asked: many }, "")!.rows[0]!.link).toBeUndefined();
91 expect(cardFor("asked", { asked: [ask({ repo: "/evil.example/x" })] }, "https://forge.test")!.rows[0]!.link).toBeUndefined();
92 });
93 });
test/mcp-forge-cards.test.ts −2
@@ -37,7 +37,6 @@ describe("the forge over MCP: cards", () => {
3737 const uris = list.body.result.resources.map((r: any) => r.uri).sort();
3838 expect(uris).toEqual([
3939 "ui://forge/app",
40 "ui://forge/asked",
4140 "ui://forge/asks",
4241 "ui://forge/board",
4342 "ui://forge/capacity",
@@ -90,7 +89,6 @@ describe("the forge over MCP: cards", () => {
9089 expect(meta("pull")).toBe("ui://forge/pull");
9190 expect(meta("pulls")).toBe("ui://forge/pulls");
9291 expect(meta("runs")).toBe("ui://forge/runs");
93 expect(meta("asked")).toBe("ui://forge/asked");
9492 expect(meta("flow")).toBe("ui://forge/flow");
9593 expect(meta("scorecard")).toBe("ui://forge/scorecard");
9694 });
test/mcp-forge-protocol.test.ts −1
@@ -226,7 +226,6 @@ describe("the forge over MCP: protocol", () => {
226226 "next_steps",
227227 "notify",
228228 "thought",
229 "asked",
230229 "assigned",
231230 "assign",
232231 "app_members",
test/oauth-refresh.test.ts +1 −1
@@ -78,7 +78,7 @@ describe("oauth refresh", () => {
7878 const refresh = (token: unknown, extra: Record<string, string> = {}) =>
7979 post("/oauth/token", { grant_type: "refresh_token", refresh_token: String(token), client_id: client.id, ...extra });
8080 const api = (token: unknown) =>
81 fetch(`${base}/api/v1/asked`, { headers: { authorization: `Bearer ${String(token)}` } }).then((r) => r.status);
81 fetch(`${base}/api/v1/returns`, { headers: { authorization: `Bearer ${String(token)}` } }).then((r) => r.status);
8282
8383 test("a code with a lifetime returns a refresh token, stored hashed; one without does not", async () => {
8484 const lived = await exchange("rw", 86_400);
test/oauth-revoke.test.ts +1 −1
@@ -76,7 +76,7 @@ describe("oauth revoke", () => {
7676 body: new URLSearchParams({ token }),
7777 });
7878 const callApi = (token: string) =>
79 fetch(`${base}/api/v1/asked`, { headers: { authorization: `Bearer ${token}` } });
79 fetch(`${base}/api/v1/returns`, { headers: { authorization: `Bearer ${token}` } });
8080 const mcp = (token: string) =>
8181 fetch(`${base}/mcp`, {
8282 method: "POST",
test/openapi-oa-agents.test.ts −1
@@ -19,7 +19,6 @@ const want: readonly (readonly [string, string])[] = [
1919 ["post", `${REPO}/contribute`],
2020 ["post", `${REPO}/edits`],
2121 ["post", "/api/v1/thoughts"],
22 ["get", "/api/v1/asked"],
2322 ["get", "/api/v1/returns"],
2423 ["get", "/api/v1/here"],
2524 ["get", "/api/v1/crew/scorecard"],
test/page-text.test.ts +2 −2
@@ -60,7 +60,7 @@ test("the real home reads as text: heading and waiting count, no CSS, script or
6060 expect(raw).toContain("<script");
6161 expect(raw).toContain("<style");
6262 const text = pageText(raw);
63 expect(text).toContain("Feed Your apps Asked");
63 expect(text).toContain("Feed Your apps Design");
6464 // The oldest is said in the largest sensible unit: 50 hours is 2 days.
6565 expect(text).toMatch(/3 waiting on you, oldest 2 days/);
6666 expect(text).not.toMatch(/<\/?[a-z]/i);
@@ -96,7 +96,7 @@ test("scripts/home-read.ts prints the text and the stats line, sends FORGE_COOKI
9696 const r = await run([`${servers.url}/feed`], { FORGE_COOKIE: cookie });
9797 expect(r.code).toBe(0);
9898 expect(r.out.trimEnd().split("\n").pop()).toMatch(/^chars \d+ · words \d+ · fetched in \d+ ms$/);
99 expect(r.out).toContain("Feed Your apps Asked");
99 expect(r.out).toContain("Feed Your apps Design");
100100 const token = cookie.match(/forge_session=([^;]+)/)![1]!;
101101 expect(r.out).not.toContain(token);
102102 expect(r.err).not.toContain(token);
test/palette-repos.test.ts +1 −1
@@ -119,7 +119,7 @@ test("a visitor's palette holds places to go and Sign in; a signed-in one holds
119119 expect(out.map((i) => i.t)).toEqual(["Home", "Apps", "Explore", "Forge packs", "Front page", "Search", "Sign in"]);
120120 expect(out.find((i) => i.t === "Sign in")!.h).toBe("/signin?next=%2Fexplore%3Fq%3Da%2526b");
121121 const inn = (await rows({ cookie }, "/explore")).map((i) => i.t);
122 for (const t of ["New app", "New repository", "Migrate a repository", "New organization", "What you asked for", "Account settings", "Access codes", "Computer keys", "Connected accounts", "Map"]) expect(inn).toContain(t);
122 for (const t of ["New app", "New repository", "Migrate a repository", "New organization", "Account settings", "Access codes", "Computer keys", "Connected accounts", "Map"]) expect(inn).toContain(t);
123123 expect(inn).not.toContain("Sign in");
124124 });
125125
test/palette-roster.test.ts −3
@@ -102,7 +102,6 @@ test("a site-admin person is offered the whole roster", () => {
102102 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
103103 ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"],
104104 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
105 ["asked", "Asked", "your thoughts and what became of them"],
106105 ["thought-notes", "Notes", "write an idea and watch it become shipped work"],
107106 ["decider", "Decider", "what it closed, deferred and asked you about today"],
108107 ["shells", "Your shells", "the machine shells you hold, live then ended"],
@@ -302,7 +301,6 @@ test("a site-admin agent is offered the roster without the person-only entries",
302301 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
303302 ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"],
304303 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
305 ["asked", "Asked", "your thoughts and what became of them"],
306304 ["thought-notes", "Notes", "write an idea and watch it become shipped work"],
307305 ["decider", "Decider", "what it closed, deferred and asked you about today"],
308306 ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"],
@@ -424,7 +422,6 @@ test("a member person is offered the signed-in roster without the admin entries"
424422 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
425423 ["inventory", "What is left to bring over", "every repository on your connected accounts, what it holds, where its move stands"],
426424 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
427 ["asked", "Asked", "your thoughts and what became of them"],
428425 ["thought-notes", "Notes", "write an idea and watch it become shipped work"],
429426 ["decider", "Decider", "what it closed, deferred and asked you about today"],
430427 ["shells", "Your shells", "the machine shells you hold, live then ended"],
test/plugin-claude-oauth.test.ts +1 −1
@@ -17,7 +17,7 @@ test("the description names every verb the command handles", async () => {
1717 const md = await Bun.file(`${dir}/commands/forge.md`).text();
1818 const list = md.match(/^description: Talk to your forge: (.*)$/m)![1] as string;
1919 const verbs = list.split(",").map((v) => v.trim());
20 expect(verbs.length).toBe(15);
20 expect(verbs.length).toBe(14);
2121 for (const v of verbs) expect(plugin.description).toContain(v);
2222 });
2323
test/plugins.test.ts +1 −55
@@ -3,8 +3,6 @@ import { describe, expect, test } from "bun:test";
33 import { readFileSync } from "node:fs";
44 import { toolNames } from "../src/http/mcp.ts";
55 import { tool as heldTool } from "../src/http/mcp/tools/held.ts";
6 import { tool as askedTool } from "../src/http/mcp/tools/asked.ts";
7 import { ASKED_STATES, askedJson, type Asked } from "../src/core/asked.ts";
86
97 const read = (path: string): string => readFileSync(new URL(`../${path}`, import.meta.url), "utf8");
108
@@ -69,58 +67,6 @@ describe("what the crew is doing on an app", () => {
6967 });
7068 });
7169
72 describe("what you asked the crew for", () => {
73 for (const [label, text] of [
74 ["Claude Code", claudeText],
75 ["OpenCode", opencodeText],
76 ] as const) {
77 test(`${label} names asked, which the forge lists`, () => {
78 expect(toolsNamed(text())).toContain("asked");
79 expect(tools.has("asked")).toBe(true);
80 expect(text()).toMatch(/asked \[app\]/);
81 expect(text()).toContain("flagged ones first");
82 expect(text()).toContain("`outcomeText`");
83 });
84
85 test(`${label} passes only arguments asked takes, and lists exactly the states it returns`, () => {
86 const line = text().split("\n").find((l) => /^- `?asked \[app\]/.test(l))!;
87 const props = askedTool.inputSchema["properties"] as Record<string, { enum?: string[] }>;
88 expect(Object.keys(props)).toContain("repo");
89 expect(line).toMatch(/`show`\s*(=\s*)?`all`/);
90 expect(props["show"]!.enum).toContain("all");
91 const listed = /its state \(([^)]*)\)/.exec(line)![1]!.split(/,\s*|\s+or\s+/);
92 expect(listed).toEqual([...ASKED_STATES]);
93 });
94 }
95
96 test("the outcome sentence the texts name is a field asked returns, and says why a parked ask waits", () => {
97 const parked = {
98 source: "issue",
99 repo: { ownerName: "ada", name: "notes" },
100 issue: { number: 7, title: "Export to CSV", state: "open" },
101 askedBy: "ada",
102 askedAt: "2026-10-01T00:00:00Z",
103 pulls: [],
104 state: "waiting",
105 stale: true,
106 flagged: true,
107 lastCrewAt: null,
108 doneBy: [],
109 outcome: { kind: "parked", note: "needs a schema decision" },
110 } as unknown as Asked;
111 expect(askedJson(parked).outcomeText).toBe("parked: needs a schema decision");
112 });
113
114 test("a command that drops asked is caught", () => {
115 expect(toolsNamed("- asked [app]: call `asks` with `repo`")).not.toContain("asked");
116 });
117
118 test("both READMEs and the argument hint list it", () => {
119 expect(read("plugins/claude-code/commands/forge.md")).toMatch(/argument-hint:.*\| asked \[app\]/);
120 for (const p of ["plugins/claude-code/README.md", "plugins/opencode/README.md"]) expect(read(p)).toContain("`/forge asked [app]`");
121 });
122 });
123
12470 test("a renamed tool is caught", () => {
12571 expect(toolsNamed("call `tell_renamed` with `repo`").filter((n) => !tools.has(n))).toEqual(["tell_renamed"]);
12672 expect(backticked("`a_b` and `C`")).toEqual(["a_b"]);
@@ -208,7 +154,7 @@ const verbDiff = (a: string, b: string): { onlyA: string[]; onlyB: string[] } =>
208154
209155 describe("the two plugin commands offer the same verbs", () => {
210156 test("Claude Code and OpenCode have the same set", () => {
211 expect(verbsOf(claudeText())).toEqual(["archive", "asked", "decide", "forks", "held", "log", "new", "plan", "preview", "pulls", "runs", "status", "tell", "undo", "waves"]);
157 expect(verbsOf(claudeText())).toEqual(["archive", "decide", "forks", "held", "log", "new", "plan", "preview", "pulls", "runs", "status", "tell", "undo", "waves"]);
212158 expect(verbDiff(claudeText(), opencodeText())).toEqual({ onlyA: [], onlyB: [] });
213159 });
214160
test/server-timing-sweep.test.ts +1
@@ -43,6 +43,7 @@ const NOT_PAGES = new Set([
4343 * by redirecting.
4444 */
4545 const REDIRECTS = new Set([
46 "/asked",
4647 "/asks",
4748 "/.well-known/change-password",
4849 "/alice/forge/changes",
test/thought-stream.test.ts +10 −39
@@ -1,4 +1,4 @@
1 /** The thought stream on /asked (#653): states derive, flag after N days, superseded shown. */
1 /** The thought stream (#653): states derive, flag after N days, superseded shown. */
22
33 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
44 import { mkdtemp, rm } from "node:fs/promises";
@@ -11,9 +11,7 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1111 import { savePlacement, type Placed } from "../src/core/placements.ts";
1212 import type { Repo } from "../src/core/repos.ts";
1313 import { setUserSetting } from "../src/core/settings.ts";
14 import { flagDays, streamJson, thoughtStream } from "../src/core/thought_stream.ts";
15 import { serve } from "../src/http/server.ts";
16 import { createToken } from "../src/core/tokens.ts";
14 import { flagDays, thoughtStream } from "../src/core/thought_stream.ts";
1715 import { createUser, type User } from "../src/core/users.ts";
1816 import { quietLogs } from "./helpers/globals.ts";
1917 import { promote } from "./helpers/members.ts";
@@ -152,45 +150,18 @@ describe("thought stream", () => {
152150 const mine = find(id);
153151 expect(mine.state).toBe("placed");
154152 expect(mine.placed[0]).toMatchObject({ readable: false, title: null });
155 expect(JSON.stringify(streamJson(mine))).not.toContain("secret");
153 expect(JSON.stringify({ ...mine.placed[0], repo: undefined })).not.toContain("secret");
156154 // A later thought superseding it changes nothing for someone who cannot read it.
157155 place(thought("never mind", 0.05), [{ action: "superseded", repo: "bob/secret", number: hidden.value.number }], 0.05);
158156 expect(find(id).state).toBe("placed");
159157 });
160158
161 test("/asked and the asked tool show the stream, with the one next action", async () => {
162 const servers = await serve(app);
163 try {
164 const i = issue();
165 const id = thought("<b>stale</b> thought", 60);
166 place(id, [{ action: "opened", repo: slug, number: i.number }], 60);
167 const signin = await fetch(`${servers.url}/signin`, {
168 method: "POST",
169 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
170 redirect: "manual",
171 });
172 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
173 const page = (await (await fetch(`${servers.url}/asked`, { headers: { cookie } })).text()).replace(/\s+/g, " ");
174 expect(page).toContain("Your thoughts");
175 expect(page).toContain("&lt;b&gt;stale&lt;/b&gt; thought");
176 expect(page).not.toContain("<b>stale</b>");
177 expect(page).toContain("Nothing built");
178 expect(page).not.toContain("secret");
179 expect(page).toContain("in a repository you cannot read");
180 // The one button goes to the oldest flagged thought's issue.
181 expect(page).toContain(`data-variant="primary" href="/${slug}/issues/${i.number}"`);
182 expect(page).toMatch(/Open the oldest of \d+ with nothing built/);
183 const token = createToken(app.db, alice.id, "ro", "ro").token;
184 const res = await fetch(`${servers.url}/mcp`, {
185 method: "POST",
186 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
187 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "asked", arguments: {} } }),
188 });
189 const got = JSON.parse(((await res.json()) as any).result.content[0].text);
190 const mine = got.thoughts.find((t: any) => t.id === id);
191 expect(mine).toMatchObject({ text: "<b>stale</b> thought", state: "placed", flagged: true });
192 } finally {
193 servers.stop();
194 }
159 test("a stale thought is flagged, its text kept as written, and a repository you cannot read is not named", () => {
160 const i = issue();
161 const id = thought("<b>stale</b> thought", 60);
162 place(id, [{ action: "opened", repo: slug, number: i.number }], 60);
163 const mine = JSON.parse(JSON.stringify(thoughtStream(app.db, alice))).find((t: any) => t.id === id);
164 expect(mine).toMatchObject({ text: "<b>stale</b> thought", state: "placed", flagged: true });
165 expect(JSON.stringify(mine)).not.toContain("secret");
195166 });
196167 });
test/triage.test.ts +3 −8
@@ -21,7 +21,6 @@ import { createUser, type User } from "../src/core/users.ts";
2121 import { BATCH_MS, placeThought, ruleKind, triageTick } from "../src/crew/triage.ts";
2222 import type { Decider } from "../src/crew/decide.ts";
2323 import { replyUnder } from "../src/web/studio/feed.ts";
24 import { thoughtRow } from "../src/web/studio/asked_page.ts";
2524
2625 /** Answers by the first word of the thought: `kind:p:#target:pillar`. */
2726 const stub = (script: Record<string, [string, number, string?, string?]>): Decider => ({
@@ -331,13 +330,9 @@ describe("triage", () => {
331330 const late = think(`scrap #${num}, no <i>gauge</i>`);
332331 await placeThought(app, fresh(), alice, late);
333332 const rows = thoughtStream(app.db, alice);
334 const repeatRow = String(thoughtRow(rows.find((t) => t.id === again.id)!, 7));
335 expect(repeatRow).toContain("repeats “build a &lt;b&gt;bold&lt;/b&gt; gauge for queue depth”");
336 const reverseRow = String(thoughtRow(rows.find((t) => t.id === late.id)!, 7));
337 expect(reverseRow).toContain("takes back");
338 expect(reverseRow).toContain("&lt;b&gt;bold&lt;/b&gt;");
339 expect(reverseRow).not.toContain("<b>bold</b>");
340 expect(String(thoughtRow(rows.find((t) => t.id === early.id)!, 7))).toContain("superseded by");
333 expect(rows.find((t) => t.id === again.id)!.repeats?.text).toBe("build a <b>bold</b> gauge for queue depth");
334 expect(rows.find((t) => t.id === late.id)!.supersedes[0]?.text).toContain("<b>bold</b>");
335 expect(rows.find((t) => t.id === early.id)!.supersededBy?.text).toContain("scrap");
341336 });
342337
343338 test("a reply links its issue numbers and escapes everything else", () => {
test/tui-asked-view.test.ts deleted −144
@@ -1,144 +0,0 @@
1 /**
2 * The asked screen narrows as MCP `asked` does (#7303): `s` cycles
3 * unshipped → flagged → all, `o` flips oldest/newest, the title says the
4 * choice, and each row says its state and stale or flagged in MCP's words.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createIssue } from "../src/core/issues.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { tool } from "../src/http/mcp/tools/asked.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { askedLines, askedScreen, type AskedView } from "../src/tui/screens/asked.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { settleApp } from "./helpers/tui.ts";
20 import { promote } from "./helpers/members.ts";
21
22 quietLogs();
23
24 const DAY = 86_400_000;
25 let dir: string;
26 let app: App;
27 let alice: User;
28
29 const ask = (repoId: string, title: string, daysAgo: number, kind: "issue" | "pull" = "issue", body = "") => {
30 const r = createIssue(app.db, { repoId, authorId: alice.id, title, body, kind });
31 if (!r.ok) throw new Error(r.error);
32 app.db.query("UPDATE issue SET created_at = ?1 WHERE id = ?2").run(new Date(Date.now() - daysAgo * DAY).toISOString(), r.value.id);
33 return r.value;
34 };
35
36 beforeAll(async () => {
37 dir = await mkdtemp(join(tmpdir(), "forge-tui-asked-view-"));
38 app = createApp({ dataDir: dir, port: 0 });
39 const u = await createUser(app.db, {
40 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
41 password: "a-good-passphrase", adminIfFirst: true,
42 });
43 if (!u.ok) throw new Error(u.error);
44 alice = u.value;
45 promote(app.db, alice);
46 const repo = await createRepo(app, alice, { name: "garden", visibility: "public" });
47 if (!repo.ok) throw new Error(String(repo.error));
48 const id = repo.value.id;
49 ask(id, "Flagged ask", 5);
50 const shipped = ask(id, "Shipped ask", 4);
51 const pull = ask(id, "Answers it", 4, "pull", `Closes #${shipped.number}`);
52 app.db
53 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
54 VALUES (?1, 'main', 'answer', 'a', 'b', ?2)`)
55 .run(pull.id, new Date().toISOString());
56 app.db.query("UPDATE issue SET state = 'closed' WHERE id IN (?1, ?2)").run(shipped.id, pull.id);
57 ask(id, "Fresh ask", 1);
58 // Stale and not flagged: older than the stale window, with an open pull on it.
59 const building = ask(id, "Building ask", 6);
60 const draft = ask(id, "Works on it", 1, "pull", `Closes #${building.number}`);
61 app.db
62 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid)
63 VALUES (?1, 'main', 'work', 'a', 'b')`)
64 .run(draft.id);
65 });
66 afterAll(async () => {
67 app.db.close();
68 await rm(dir, { recursive: true, force: true });
69 });
70
71 const titles = (view?: AskedView) => askedLines(app.db, alice, view).asks.map((a) => a.title);
72
73 /** What MCP `asked` answers for the same choice. */
74 const mcp = async (args: Record<string, string>) => {
75 const answer = await tool.run({ app } as never, alice, args);
76 if (!answer.ok) throw new Error(answer.message);
77 return (answer.value as { asked: { title: string }[] }).asked.map((a) => a.title);
78 };
79
80 test("the defaults are MCP's: unshipped, oldest first, in the same order", async () => {
81 expect(titles()).toEqual(["Building ask", "Flagged ask", "Fresh ask"]);
82 expect(titles()).toEqual(await mcp({}));
83 });
84
85 test("each choice of show lists what MCP lists", async () => {
86 expect(titles({ show: "flagged", order: "oldest" })).toEqual(["Flagged ask"]);
87 expect(titles({ show: "flagged", order: "oldest" })).toEqual(await mcp({ show: "flagged" }));
88 // Exactly MCP's order: /asked's grouping would put the shipped ask after the fresh one.
89 expect(titles({ show: "all", order: "oldest" })).toEqual(["Building ask", "Flagged ask", "Shipped ask", "Fresh ask"]);
90 expect(titles({ show: "all", order: "oldest" })).toEqual(await mcp({ show: "all" }));
91 expect(titles({ show: "all", order: "newest" })).toEqual(["Fresh ask", "Shipped ask", "Flagged ask", "Building ask"]);
92 expect(titles({ show: "all", order: "newest" })).toEqual(await mcp({ show: "all", order: "newest" }));
93 });
94
95 test("newest first reverses them, as MCP does", async () => {
96 expect(titles({ show: "unshipped", order: "newest" })).toEqual(["Fresh ask", "Flagged ask", "Building ask"]);
97 expect(titles({ show: "unshipped", order: "newest" })).toEqual(await mcp({ order: "newest" }));
98 });
99
100 test("a row says its state and marks it flagged, in MCP's words", () => {
101 const rows = askedLines(app.db, alice, { show: "all", order: "oldest" }).asks;
102 const meta = (t: string) => rows.find((r) => r.title === t)!.meta ?? "";
103 expect(meta("Flagged ask")).toStartWith("waiting flagged");
104 expect(meta("Fresh ask")).toStartWith("waiting");
105 expect(meta("Fresh ask")).not.toContain("flagged");
106 expect(meta("Fresh ask")).not.toContain("stale");
107 expect(meta("Shipped ask")).toStartWith("shipped");
108 expect(meta("Building ask")).toStartWith("building stale");
109 expect(meta("Building ask")).not.toContain("flagged");
110 });
111
112 test("s cycles unshipped, flagged, all and o flips the order, the title saying which", async () => {
113 const terminal = headlessTerminal(120, 30);
114 const { app: tui, session } = createForgeApp(
115 app,
116 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
117 { terminal, exitHooks: false },
118 );
119 tui.start();
120 tui.ctx.push(askedScreen(session, tui.ctx));
121 await settleApp(tui);
122 const screen = () => tui.screen.toText();
123 const press = async (key: string) => {
124 terminal.feed(key);
125 await settleApp(tui);
126 };
127 expect(screen()).toContain("Asked · not shipped, oldest first");
128 expect(screen()).toContain("· 3 asks");
129 expect(screen()).not.toContain("asks not shipped");
130 expect(screen()).not.toContain("Shipped ask");
131 expect(screen().indexOf("Flagged ask")).toBeLessThan(screen().indexOf("Fresh ask"));
132 await press("s");
133 expect(screen()).toContain("flagged, oldest first");
134 expect(screen()).toContain("Flagged ask");
135 expect(screen()).not.toContain("Fresh ask");
136 await press("s");
137 expect(screen()).toContain("all, oldest first");
138 expect(screen()).toContain("Shipped ask");
139 await press("s");
140 await press("o");
141 expect(screen()).toContain("not shipped, newest first");
142 expect(screen().indexOf("Fresh ask")).toBeLessThan(screen().indexOf("Flagged ask"));
143 tui.stop?.();
144 });
test/tui-asked.test.ts deleted −208
@@ -1,208 +0,0 @@
1 /**
2 * /asked in the terminal (#1755): the screen reads the page's own rows, so a
3 * guest sees nothing, a viewer sees only their own thoughts, and a placement
4 * in a repository they cannot read names nothing.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createIssue, setIssueState } from "../src/core/issues.ts";
13 import { savePlacement } from "../src/core/placements.ts";
14 import { linkThoughts } from "../src/core/thought_links.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
17 import { askedLines, askedScreen } from "../src/tui/screens/asked.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21 import { promote } from "./helpers/members.ts";
22
23 quietLogs();
24
25 let dir: string;
26 let app: App;
27 let alice: User;
28 let bob: User;
29 let carol: User;
30
31 const identity = (user?: User) => ({
32 sshUsername: user?.username ?? "git",
33 remoteAddress: "127.0.0.1",
34 fingerprint: "SHA256:test",
35 user,
36 });
37
38 const thought = (who: User, id: string, text: string) =>
39 app.db
40 .query("INSERT INTO thought (id, author, text, source, received_at) VALUES (?1, ?2, ?3, 'composer', ?4)")
41 .run(id, who.id, text, new Date().toISOString());
42
43 async function screenText(user?: User, keys = ""): Promise<string> {
44 const terminal = headlessTerminal(120, 30);
45 const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
46 tui.start();
47 tui.ctx.push(askedScreen(session, tui.ctx));
48 await settleApp(tui);
49 if (keys !== "") {
50 terminal.feed(keys);
51 await settleApp(tui);
52 }
53 const text = tui.screen.toText();
54 tui.stop?.();
55 return text;
56 }
57
58 const ask = (repoId: string, who: User, title: string, at: string) => {
59 const r = createIssue(app.db, { repoId, authorId: who.id, title });
60 if (!r.ok) throw new Error(r.error);
61 app.db.query("UPDATE issue SET created_at = ?1 WHERE id = ?2").run(at, r.value.id);
62 return r.value;
63 };
64
65 beforeAll(async () => {
66 dir = await mkdtemp(join(tmpdir(), "forge-tui-asked-"));
67 app = createApp({ dataDir: dir, port: 0 });
68 const mk = async (username: string, first = false) => {
69 const r = await createUser(app.db, {
70 origin: "seed",
71 trusted: true, username, email: `${username}@forge.local`,
72 password: "a-good-passphrase", adminIfFirst: first,
73 });
74 if (!r.ok) throw new Error(r.error);
75 promote(app.db, r.value);
76 return r.value;
77 };
78 carol = await mk("carol", true);
79 alice = await mk("alice");
80 bob = await mk("bob");
81 const lobby = await createRepo(app, alice, { name: "lobby", visibility: "public" });
82 if (!lobby.ok) throw new Error(String(lobby.error));
83 const secret = await createRepo(app, bob, { name: "vault", visibility: "private" });
84 if (!secret.ok) throw new Error(String(secret.error));
85 const now = Date.now();
86 const iso = (daysAgo: number) => new Date(now - daysAgo * 86_400_000).toISOString();
87 ask(lobby.value.id, alice, "Newer ask for the lobby", iso(1));
88 ask(lobby.value.id, alice, "Older ask for the lobby", iso(2));
89 setIssueState(app.db, ask(lobby.value.id, alice, "Already shipped ask", iso(3)).id, "closed");
90 ask(secret.value.id, bob, "Secret ask in the vault", iso(1));
91 thought(alice, "t1", "make the lobby louder");
92 thought(alice, "t2", "hide the vault door");
93 thought(bob, "t3", "bob's private idea");
94 savePlacement(app.db, {
95 thoughtId: "t2", kind: "work", asked: false, decidedBy: "rule", reply: "ok",
96 placed: [{ action: "opened", repo: "bob/vault", number: 1 }],
97 placedAt: new Date().toISOString(),
98 });
99 });
100 afterAll(async () => {
101 app.db.close();
102 await rm(dir, { recursive: true, force: true });
103 });
104
105 describe("the asked screen", () => {
106 test("a signed-in user sees their own thoughts and no one else's", async () => {
107 const text = await screenText(alice);
108 expect(text).toContain("make the lobby louder");
109 expect(text).toContain("hide the vault door");
110 expect(text).not.toContain("bob's private idea");
111 });
112
113 test("a placement in an unreadable repository shows no slug or state", async () => {
114 const text = await screenText(alice);
115 expect(text).toContain("→ in a repository you cannot read");
116 expect(text).not.toContain("bob/vault");
117 });
118
119 test("a guest sees nothing", async () => {
120 const text = await screenText();
121 expect(text).toContain("Nothing is waiting on you.");
122 expect(text).not.toContain("make the lobby louder");
123 expect(text).not.toContain("bob's private idea");
124 });
125
126 test("asks are unshipped, oldest first, with their address, and an unreadable repository's is absent", () => {
127 // Only the asks this file filed up front: other tests file their own.
128 const filed = new Set(["Newer ask for the lobby", "Older ask for the lobby", "Already shipped ask", "Secret ask in the vault"]);
129 const asks = askedLines(app.db, alice).asks.filter((a) => filed.has(a.title));
130 expect(asks.map((a) => a.title)).toEqual(["Older ask for the lobby", "Newer ask for the lobby"]);
131 expect(asks[0]!.secondary).toContain("alice/lobby #");
132 expect(asks[0]!.secondary).toContain("alice");
133 expect(asks[0]!.path).toMatch(/^\/alice\/lobby\/issues\/\d+$/);
134 expect(JSON.stringify(askedLines(app.db, alice))).not.toContain("Secret ask");
135 });
136
137 test("the screen shows the ask and its address, never the unreadable one", async () => {
138 const text = await screenText(alice);
139 expect(text).toContain("Older ask for the lobby");
140 expect(text).toContain("alice/lobby #");
141 expect(text).not.toContain("Already shipped ask");
142 expect(text).not.toContain("Secret ask");
143 });
144
145 test("an admin sees every ask, a guest none", () => {
146 const titles = askedLines(app.db, carol).asks.map((a) => a.title);
147 expect(titles).toContain("Secret ask in the vault");
148 expect(titles).toContain("Older ask for the lobby");
149 expect(askedLines(app.db, undefined)).toEqual({ thoughts: [], asks: [] });
150 });
151
152 test("enter on an ask hands over its web address", async () => {
153 const { asks, thoughts } = askedLines(app.db, alice);
154 const down = "j".repeat(thoughts.length);
155 const text = await screenText(alice, `${down}\r`);
156 expect(text).toContain(asks[0]!.path!);
157 });
158
159 test("r reads again, so a new ask appears", async () => {
160 const terminal = headlessTerminal(120, 30);
161 const { app: tui, session } = createForgeApp(app, identity(alice), { terminal, exitHooks: false });
162 tui.start();
163 tui.ctx.push(askedScreen(session, tui.ctx));
164 await settleApp(tui);
165 const lobby = app.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name = 'lobby'").get()!;
166 ask(lobby.id, alice, "Asked while watching", new Date().toISOString());
167 expect(tui.screen.toText()).not.toContain("Asked while watching");
168 terminal.feed("r");
169 await settleApp(tui);
170 expect(tui.screen.toText()).toContain("Asked while watching");
171 tui.stop?.();
172 });
173
174 test("the palette offers the door to the signed in only", () => {
175 const ctx = {} as never;
176 const ids = (u?: User) => forgeCommands(new Session(app, identity(u)))(ctx).map((c) => c.id);
177 expect(ids(alice)).toContain("asked");
178 expect(ids()).not.toContain("asked");
179 });
180 test("a thought says where it went in /asked's words: the issue, the question back, a note, or not yet (#7509)", () => {
181 const lobby = app.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name = 'lobby'").get()!;
182 const issue = createIssue(app.db, { repoId: lobby.id, authorId: alice.id, title: "Louder lobby" });
183 if (!issue.ok) throw new Error(issue.error);
184 const n = issue.value.number;
185 const placed = (thoughtId: string, reply: string, asked: boolean, number?: number) =>
186 savePlacement(app.db, {
187 thoughtId, kind: number === undefined ? "decision" : "work", asked, decidedBy: "rule", reply,
188 placed: number === undefined ? [] : [{ action: "opened", repo: "alice/lobby", number }],
189 placedAt: new Date().toISOString(),
190 });
191 thought(alice, "t4", "a louder lobby, again");
192 thought(alice, "t5", "which one was it");
193 thought(alice, "t6", "we like plain words");
194 placed("t1", "ok", false, n);
195 placed("t4", "ok", false, n);
196 linkThoughts(app.db, "t4", "t1", "repeats");
197 placed("t5", "Do you mean the lobby or the vault?", true);
198 placed("t6", "ok", false);
199 thought(alice, "t7", "and a dark theme");
200
201 const by = new Map(askedLines(app.db, alice).thoughts.map((t) => [t.title, t.secondary]));
202 expect(by.get("make the lobby louder")).toBe(`→ alice/lobby#${n} Louder lobby`);
203 expect(by.get("a louder lobby, again")).toStartWith(`→ alice/lobby#${n} Louder lobby · repeats “make the lobby louder”`);
204 expect(by.get("which one was it")).toBe("Do you mean the lobby or the vault?");
205 expect(by.get("we like plain words")).toBe("kept as a note");
206 expect(by.get("and a dark theme")).toBe("not placed yet");
207 });
208 });
test/tui-thought-where.test.ts deleted −210
@@ -1,210 +0,0 @@
1 /** Enter on a thought in the terminal's asked screen says where it went (#7473). */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { createIssue } from "../src/core/issues.ts";
9 import { savePlacement } from "../src/core/placements.ts";
10 import { linkThoughts } from "../src/core/thought_links.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { askedLines, askedScreen, thoughtCard } from "../src/tui/screens/asked.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { promote } from "./helpers/members.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { settleApp } from "./helpers/tui.ts";
18
19 quietLogs();
20
21 let dir: string;
22 let app: App;
23 let alice: User;
24 let bob: User;
25
26 const thought = (who: User, id: string, text: string, at: string) =>
27 app.db
28 .query("INSERT INTO thought (id, author, text, source, received_at) VALUES (?1, ?2, ?3, 'composer', ?4)")
29 .run(id, who.id, text, at);
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-tui-thought-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 const mk = async (username: string, first = false) => {
35 const r = await createUser(app.db, {
36 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
37 password: "a-good-passphrase", adminIfFirst: first,
38 });
39 if (!r.ok) throw new Error(r.error);
40 promote(app.db, r.value);
41 return r.value;
42 };
43 await mk("carol", true);
44 alice = await mk("alice");
45 bob = await mk("bob");
46 const lobby = await createRepo(app, alice, { name: "lobby", visibility: "public" });
47 if (!lobby.ok) throw new Error(String(lobby.error));
48 const i = createIssue(app.db, { repoId: lobby.value.id, authorId: alice.id, title: "Louder lobby" });
49 if (!i.ok) throw new Error(i.error);
50 thought(alice, "t1", "make the lobby louder", "2026-01-01T00:00:00.000Z");
51 thought(alice, "t2", "louder lobby please", "2026-01-02T00:00:00.000Z");
52 thought(bob, "t3", "bob's idea", "2026-01-03T00:00:00.000Z");
53 const vault = await createRepo(app, bob, { name: "vault", visibility: "private" });
54 if (!vault.ok) throw new Error(String(vault.error));
55 const secret = createIssue(app.db, { repoId: vault.value.id, authorId: bob.id, title: "Hidden vault door" });
56 if (!secret.ok) throw new Error(secret.error);
57 thought(alice, "t5", "hide the vault door", "2026-01-05T00:00:00.000Z");
58 savePlacement(app.db, {
59 thoughtId: "t5", kind: "work", asked: false, decidedBy: "rule", reply: "ok",
60 placed: [{ action: "opened", repo: "bob/vault", number: secret.value.number }],
61 placedAt: "2026-01-05T00:01:00.000Z",
62 });
63 thought(alice, "t6", "and again", "2026-01-06T00:00:00.000Z");
64 linkThoughts(app.db, "t6", "t3", "repeats");
65 linkThoughts(app.db, "t6", "t3", "supersedes");
66 savePlacement(app.db, {
67 thoughtId: "t1", kind: "work", asked: false, decidedBy: "rule", reply: "ok",
68 placed: [{ action: "opened", repo: "alice/lobby", number: i.value.number }],
69 placedAt: "2026-01-01T00:01:00.000Z",
70 });
71 linkThoughts(app.db, "t2", "t1", "repeats");
72 });
73 afterAll(async () => {
74 app.db.close();
75 await rm(dir, { recursive: true, force: true });
76 });
77
78 const titles = (id: string, who: User) => thoughtCard(app.db, who, id)?.map((l) => l.title);
79
80 describe("a thought's card", () => {
81 test("the placed one names its issue and the thought that repeated it", () => {
82 const lines = titles("t1", alice)!.join("\n");
83 expect(lines).toContain("It opened alice/lobby #1: Louder lobby.");
84 expect(lines).toContain("Repeated later by \u201clouder lobby please\u201d.");
85 expect(thoughtCard(app.db, alice, "t1")!.some((l) => l.issue?.repo.name === "lobby")).toBe(true);
86 });
87
88 test("the repeating one says what it repeats and that it is not placed yet", () => {
89 const lines = titles("t2", alice)!.join("\n");
90 expect(lines).toContain("Not placed yet");
91 expect(lines).toContain("It repeats \u201cmake the lobby louder\u201d.");
92 });
93
94 test("a placement with nothing on the map is kept as a note", () => {
95 thought(alice, "t4", "we value small things", "2026-01-04T00:00:00.000Z");
96 savePlacement(app.db, {
97 thoughtId: "t4", kind: "vision", asked: false, decidedBy: "rule", reply: "noted", placed: [],
98 placedAt: "2026-01-04T00:01:00.000Z",
99 });
100 expect(titles("t4", alice)).toContain("Kept as a note.");
101 });
102
103 test("a placement in a repository the viewer cannot read names nothing and opens nothing", () => {
104 const card = thoughtCard(app.db, alice, "t5")!;
105 expect(card.map((l) => l.title)).toContain("It opened something in a repository you cannot read.");
106 const all = JSON.stringify(card);
107 for (const leak of ["bob/vault", "Hidden", "#1"]) expect(all).not.toContain(leak);
108 expect(card.some((l) => l.issue !== undefined)).toBe(false);
109 });
110
111 test("a sealed issue in a readable repository names nothing and opens nothing", async () => {
112 // A public repository of bob's: alice reads it but does not write it.
113 const open = await createRepo(app, bob, { name: "open", visibility: "public" });
114 if (!open.ok) throw new Error(String(open.error));
115 const sealed = createIssue(app.db, { repoId: open.value.id, authorId: bob.id, title: "Sealed zero-day", sealed: true });
116 if (!sealed.ok) throw new Error(sealed.error);
117 thought(alice, "t8", "what about the zero-day", "2025-12-31T00:00:00.000Z");
118 savePlacement(app.db, {
119 thoughtId: "t8", kind: "work", asked: false, decidedBy: "rule", reply: "ok",
120 placed: [{ action: "opened", repo: "bob/open", number: sealed.value.number }],
121 placedAt: "2026-01-08T00:01:00.000Z",
122 });
123 const card = thoughtCard(app.db, alice, "t8")!;
124 expect(card.map((l) => l.title)).toContain("It opened something in a repository you cannot read.");
125 const all = JSON.stringify(card);
126 expect(all).not.toContain("Sealed zero-day");
127 expect(all).not.toContain(`#${sealed.value.number}`);
128 expect(card.some((l) => l.issue !== undefined)).toBe(false);
129 });
130
131 test("a link to another person's thought reads as gone and quotes nothing of it", () => {
132 const card = thoughtCard(app.db, alice, "t6")!;
133 const titles = card.map((l) => l.title);
134 expect(titles).toContain("It repeats a thought that is gone.");
135 expect(titles).toContain("It takes back a thought that is gone.");
136 expect(JSON.stringify(card)).not.toContain("bob's idea");
137 });
138
139 test("someone else's thought and a missing one are alike nothing", () => {
140 expect(thoughtCard(app.db, alice, "t3")).toBeUndefined();
141 expect(thoughtCard(app.db, alice, "nope")).toBeUndefined();
142 expect(thoughtCard(app.db, undefined, "t1")).toBeUndefined();
143 });
144
145 // A thought is never deleted, so a test that needs it gone lifts the guard for one statement.
146 const vanish = (id: string) => {
147 app.db.run("DROP TRIGGER thought_no_delete");
148 app.db.query("DELETE FROM thought WHERE id = ?1").run(id);
149 app.db.run("CREATE TRIGGER thought_no_delete BEFORE DELETE ON thought BEGIN SELECT RAISE(ABORT, 'a thought is never deleted'); END");
150 };
151
152 const open = async (text: string) => {
153 const terminal = headlessTerminal(120, 30);
154 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
155 tui.start();
156 tui.ctx.push(askedScreen(session, tui.ctx));
157 await settleApp(tui);
158 // Select the row by its text, not by its place in the list.
159 const at = askedLines(app.db, alice).thoughts.findIndex((t) => t.title === text);
160 if (at < 0) throw new Error(`no thought ${text}`);
161 terminal.feed("j".repeat(at));
162 await settleApp(tui);
163 return { tui, terminal };
164 };
165
166 test("enter on a thought in the screen opens its card", async () => {
167 const { tui, terminal } = await open("make the lobby louder");
168 terminal.feed("\r");
169 await settleApp(tui);
170 const text = tui.screen.toText();
171 tui.stop?.();
172 expect(text).toContain("It opened alice/lobby #1");
173 });
174
175 test("enter on a thought that has gone toasts and opens no card", async () => {
176 thought(alice, "t9", "soon gone", "2026-01-09T00:00:00.000Z");
177 const { tui, terminal } = await open("soon gone");
178 vanish("t9");
179 terminal.feed("\r");
180 await settleApp(tui);
181 const text = tui.screen.toText();
182 tui.stop?.();
183 expect(text).toContain("No such thought");
184 expect(text).toContain("Asked");
185 expect(text).not.toContain("Not placed yet");
186 });
187
188 test("r on a card reads again, and a card whose thought has gone toasts and pops", async () => {
189 thought(alice, "t10", "to be placed", "2026-01-10T00:00:00.000Z");
190 const { tui, terminal } = await open("to be placed");
191 terminal.feed("\r");
192 await settleApp(tui);
193 expect(tui.screen.toText()).toContain("Not placed yet");
194 savePlacement(app.db, {
195 thoughtId: "t10", kind: "vision", asked: false, decidedBy: "rule", reply: "noted", placed: [],
196 placedAt: "2026-01-10T00:01:00.000Z",
197 });
198 terminal.feed("r");
199 await settleApp(tui);
200 expect(tui.screen.toText()).toContain("Kept as a note.");
201 vanish("t10");
202 terminal.feed("r");
203 await settleApp(tui);
204 const text = tui.screen.toText();
205 tui.stop?.();
206 expect(text).toContain("No such thought");
207 expect(text).not.toContain("Kept as a note.");
208 expect(text).toContain("Asked");
209 });
210 });
test/vision-pull.test.ts +1 −5
@@ -14,7 +14,6 @@ import { keepThought } from "../src/actions/thought.ts";
1414 import { getRepoById, type Repo } from "../src/core/repos.ts";
1515 import { getIssue } from "../src/core/issues.ts";
1616 import { placementJson, placementOf } from "../src/core/placements.ts";
17 import { thoughtStream } from "../src/core/thought_stream.ts";
1817 import { createUser, type User } from "../src/core/users.ts";
1918 import { placeThought } from "../src/crew/triage.ts";
2019 import { directionLine, withDirection } from "../src/crew/vision.ts";
@@ -22,7 +21,6 @@ import type { Decider } from "../src/crew/decide.ts";
2221 import { listTree, readerFor } from "../src/git/read.ts";
2322 import { repoDir } from "../src/git/repos.ts";
2423 import { replyUnder } from "../src/web/studio/feed.ts";
25 import { thoughtRow } from "../src/web/studio/asked_page.ts";
2624
2725 const visionDecider: Decider = {
2826 name: "stub",
@@ -124,11 +122,9 @@ describe("a vision thought", () => {
124122 expect(edited).toContain("## Changes of direction\n- ");
125123 expect(edited).toContain(t.id);
126124
127 // Under the thought, on /asked, and in MCP `thought`.
125 // Under the thought, and in MCP `thought`.
128126 const href = `/${slug}/pulls/${proposed.number}`;
129127 expect(String(replyUnder(t.p))).toContain(href);
130 const row = thoughtStream(app.db, alice).find((x) => x.id === t.id)!;
131 expect(String(thoughtRow(row, 3))).toContain(href);
132128 const mcp = placementJson(placementOf(app.db, t.id)) as { placed: { action: string; pull?: number }[] };
133129 expect(mcp.placed.find((x) => x.action === "proposed")?.pull).toBe(proposed.number);
134130 });
test/xss-everywhere.test.ts −1
@@ -144,7 +144,6 @@ describe("one hostile string, every surface", () => {
144144 ["the issue list", () => "/alice/game/issues"],
145145 ["search", () => "/search?q=img"],
146146 ["explore", () => "/explore"],
147 ["asked", () => "/asked"],
148147 ["the repository home", () => "/alice/game"],
149148 ["the activity feed", () => "/alice/game/activity.atom"],
150149 ["the waves feed", () => "/alice/game/waves.atom"],

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

Keyboard shortcuts

Docs