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

A person puts a ready issue first: MCP `map` `first` and the map page reorder what the crew starts next #7739

Parked opened this
Closed without merging

mason/forge:mason/7657-a-person-puts-a-ready-issue-first-mcp-ma → main 3 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +435 −17
README.md +1 −1
@@ -57,7 +57,7 @@ A hold an agent placed does not stand forever: the tick releases one still stand
5757
5858 In the terminal, `T` on a shipped pull's screen takes it back, as the pull page's button does: a one-line confirm names the pull, Yes opens the pull that undoes it (`revertPull`, `src/actions/revert.ts`) and shows it, No changes nothing. The key appears only to a person who can write a local repository (never an agent, a reader, a guest or a mirror), and refusals read as the page's do (`takeBackWords`). `T` also opens an app preview's terminal on an open pull; a shipped pull has no live preview, so the two never meet.
5959
60 In the terminal, `m` on a local repository's issue list opens the plan screen (`src/tui/screens/plan.ts`): Working, Ready now, Waiting and Parked twice, each headed with its count. It reads what MCP `map` reads (`repoGraph` under the reader's sealed scope, `pillarView`, `mapHeldFor`, the runs in flight), so a sealed issue the reader may not see is left out. Enter opens the issue, `r` reads again, and the headings are skipped over. It is not offered on the pulls list or on a live browse of another forge.
60 In the terminal, `m` on a local repository's issue list opens the plan screen (`src/tui/screens/plan.ts`): Working, Ready now, Waiting and Parked twice, each headed with its count. It reads what MCP `map` reads (`repoGraph` under the reader's sealed scope, `pillarView`, `mapHeldFor`, the runs in flight), so a sealed issue the reader may not see is left out. Enter opens the issue, `r` reads again, and the headings are skipped over. `f` on a Ready now row puts it first (`putFirst`, writers only, the same words as the page): the crew starts it before the rest of what is ready, and never lifts the Later gate. On the map page a writer gets a First button on every Ready now row but the top; over MCP it is `map {app, first: <number>}`. It is not offered on the pulls list or on a live browse of another forge.
6161
6262 A hand-over card on `/asks` (an agent's pull the reviewer stopped on after three rounds) has "Give back to the crew": one press assigns the pull, and the open issue it closes if a person holds it, to the agent that opened it, writes "Given back to the crew by @who", and the card leaves; the next tick starts its run. It is for a writer of the repository, and a pull a person opened, or by an agent gone from the crew, gets no button. In the terminal, `b` on a handed-over row of the On you pane does the same (`src/actions/give_back.ts`). The repository's planner can do it by comment: one that starts "Planner, one more round" on a handed-over crew pull emits the assignment to its builder, which starts the run (the pull is already the builder's, so nothing changes hands). It is the planner's alone; a reader's, the reviewer's or any other agent's does nothing. It is an agent's word, not a director's, so it does not end the hand-over: the card stays on `/asks` and the pull still counts as handed over during the round.
6363
docs/MCP.md +1 −1
@@ -104,7 +104,7 @@ for a tunnel and a forge that sleeps.
104104 | `limb` | `{ app, issue, action, reason?, pillar?, operation?, dryRun? }`: defer, resume or close a whole limb as not doing, or undo an operation; plans unless `dryRun` is false, and applying takes an admin token | yes |
105105 | `limits` | `{ key?, value?, dryRun? }` (forge admin): every limit the forge's owner can hit, with its value, default and bounds; with `key` and `value` (`""` restores the default), planned first (`dryRun` is true unless `false`); a value out of bounds is refused, applying needs an admin-scope token | yes |
106106 | `make_it_yours` | `{ repo, name?, visibility?, dryRun? }`: a fork of an app you can see, as your own app, following the original; code and history copied, data and secrets not; private unless `visibility` is public (a public original only); at most 5 copies an account a day; plans unless `dryRun` is false | yes |
107 | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`, `done` to list closed issues too); draws the `ui://forge/map` card | |
107 | `map` | an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`, `done` to list closed issues too); `first: <number>` (a writer) puts a ready issue ahead of the rest; draws the `ui://forge/map` card | |
108108 | `merge` | `{ repo, number, strategy?, dryRun? }` (a person, never an agent: a person merges): land a pull as its page's Merge button does, `merge` (default) or `squash`; planned unless `dryRun` is false: the plan is the pull's `head`, `base`, `mergeable`, `conflicts` and `check` as `pull` reads them; landing is `mergePull`'s, with its refusals (conflict, review or check required, not a writer) in the page's words, and takes an rw token | yes |
109109 | `migrate` | `{ url, name?, crew? }` brings a public repository in by URL (history only; nothing reaches back) and answers `{ job, state, url }`; `{ job }` alone reads that job. Same validation, scope (`rw`) and private-address refusal as `POST /api/v1/migrate` | yes |
110110 | `milestones` | `{ app, issue? }`: how far each thing asked for is (and, with `issue`, whether you watch it: `watching`), from the dependency tree: the plan's limbs with their weights, or one milestone opened (who is building, what is blocked and on what, what merged in 7 days, an estimate, `closedPerDay` (14 days) and `paceDate`, and for an owner `spend`: dollars, changes landed ever, the costliest three issues) | |
src/actions/first.ts added +34
@@ -0,0 +1,34 @@
1 /**
2 * Put a ready issue first (#7657): the crew starts it before the rest of
3 * what is ready. The rank is an event with the actor (`core/first_rank.ts`).
4 * Only an issue `readyNow` lists can be ranked, so a closed, blocked or
5 * deferred one is invalid and the Later gate stays shut.
6 */
7
8 import type { App } from "../app.ts";
9 import { readyNow, repoGraph } from "../core/dependencies.ts";
10 import type { Issue } from "../core/issues.ts";
11 import { canWrite, type Repo } from "../core/repos.ts";
12 import { sealedScope } from "../core/sealed.ts";
13 import type { User } from "../core/users.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15
16 export type FirstError = "forbidden" | "invalid";
17
18 export const FIRST_SAY: Record<FirstError, string> = {
19 forbidden: "Only a person who writes here puts an issue first.",
20 invalid: "Only an issue that is ready now can go first: not closed, blocked or put off for later.",
21 };
22
23 export function putFirst(app: App, user: User, repo: Repo, issue: Issue): Result<Issue, FirstError> {
24 if (user.kind === "agent" || !canWrite(app.db, repo, user)) return err("forbidden");
25 const ready = readyNow(repoGraph(app.db, repo.id, { ...sealedScope(app.db, repo, user) }));
26 if (!ready.some((r) => r.issue.id === issue.id)) return err("invalid");
27 app.bus.append({
28 kind: "issue.ranked",
29 repoId: repo.id,
30 actorId: user.id,
31 payload: { number: issue.number, title: issue.title },
32 });
33 return ok(issue);
34 }
src/core/dependencies.ts +27 −4
@@ -16,6 +16,7 @@ import { getRepoById, type Repo } from "./repos.ts";
1616 import { unadoptedAmong } from "../crew/direct.ts";
1717 import { raisedAt, raisedInRepo } from "./thought_links.ts";
1818 import { limbRanks, limbTree, readPlaces } from "./limb_order.ts";
19 import { firstRanks } from "./first_rank.ts";
1920
2021 export type DependencyError = "self" | "cross_repo" | "cycle" | "not_an_issue";
2122
@@ -249,6 +250,11 @@ export interface Graph {
249250 * ready ahead of the rest, the latest raise first.
250251 */
251252 readonly raised?: ReadonlyMap<string, string>;
253 /**
254 * Issues a person put first (#7657), the place of the newest rank (higher
255 * is later). Ready ahead of everything else, the latest rank first.
256 */
257 readonly first?: ReadonlyMap<string, number>;
252258 }
253259
254260 /**
@@ -436,7 +442,18 @@ export function repoGraph(
436442 const set =
437443 repo === undefined ? undefined : (options.pillars ?? pillarsOf(db, repo));
438444 const places = readPlaces(db, repoId);
445 const ranked = firstRanks(db, repoId);
439446 return {
447 ...(ranked.size === 0
448 ? {}
449 : {
450 first: new Map(
451 issues.flatMap((i) => {
452 const at = ranked.get(i.number);
453 return at === undefined ? [] : [[i.id, at] as const];
454 }),
455 ),
456 }),
440457 ...(set === undefined || places.size === 0
441458 ? {}
442459 : {
@@ -655,10 +672,16 @@ export function readyNow(graph: Graph): Ranked[] {
655672 const of = (r: Ranked) => rank?.get(r.issue.id) ?? Number.MAX_SAFE_INTEGER;
656673 if (rank !== undefined) ready.sort((a, b) => of(a) - of(b));
657674 const raised = graph.raised;
658 if (raised === undefined || raised.size === 0) return ready;
659 // What the owner said again comes first (stable: the rest keep their order).
660 const at = (r: Ranked) => raised.get(r.issue.id) ?? "";
661 return ready.sort((a, b) => at(b).localeCompare(at(a)));
675 if (raised !== undefined && raised.size > 0) {
676 // What the owner said again comes first (stable: the rest keep their order).
677 const at = (r: Ranked) => raised.get(r.issue.id) ?? "";
678 ready.sort((a, b) => at(b).localeCompare(at(a)));
679 }
680 const first = graph.first;
681 if (first === undefined || first.size === 0) return ready;
682 // What a person put first comes before all of it, the latest rank first.
683 const place = (r: Ranked) => first.get(r.issue.id) ?? -1;
684 return ready.sort((a, b) => place(b) - place(a));
662685 }
663686
664687 /**
src/core/event_audience.ts +1
@@ -63,6 +63,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
6363 "issue.sealed",
6464 "issue.unsealed",
6565 "issue.assigned",
66 "issue.ranked",
6667 "pull.assigned",
6768 "pull.commented",
6869 "issue.reopened",
src/core/first_rank.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * "This first" (#7657): a person puts a ready issue ahead of the rest. The
3 * rank is an `issue.ranked` event with its actor; the newest rank of an issue
4 * is where it stands, and the latest ranked comes first. A rank only orders
5 * what is ready (`readyNow`): it never lifts the Later gate or a blocker.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 export const RANKED_EVENT = "issue.ranked";
11
12 /** Each ranked issue's number, with the place of its newest rank (higher is later). */
13 export function firstRanks(db: Database, repoId: string): Map<number, number> {
14 const out = new Map<number, number>();
15 for (const r of db
16 .query<{ n: number; at: number }, [string, string]>(

GROUP BY n over every issue.ranked event of the repo runs on each repoGraph call (the map and the dispatcher); events are never pruned and a rank never expires. Fine for now, but add a test covering the newest-rank-wins ordering.

17 `SELECT json_extract(payload, '$.number') AS n, MAX(seq) AS at
18 FROM event WHERE repo_id = ?1 AND kind = ?2 GROUP BY n`,
19 )
20 .all(repoId, RANKED_EVENT))
21 if (typeof r.n === "number") out.set(r.n, r.at);
22 return out;
23 }
src/http/mcp/tools/map.ts +17 −3
@@ -5,22 +5,36 @@ import { pillarView } from "../../../core/pillars.ts";
55 import { askToLiveFor } from "../../../web/ask_to_live.ts";
66 import { listActiveRuns } from "../../../core/runs.ts";
77 import { mapJson, marksFor, withoutDone } from "../../../web/pages/map.ts";
8 import { good, type Tool, APP_ARG, planRepo, isAnswer } from "../shared.ts";
8 import { putFirst, FIRST_SAY } from "../../../actions/first.ts";
9 import { scopeAllows } from "../../../core/tokens.ts";
10 import { good, bad, type Tool, APP_ARG, planRepo, isAnswer, issueArg } from "../shared.ts";
911
1012 export const tool: Tool = {
1113 name: "map",
12 doc: "an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`, `done` to list closed issues too); draws the `ui://forge/map` card",
14 doc: "an app's plan: ready now, waiting on what, the critical path, where the crew is, parked twice and why (`app`, `done` to list closed issues too); `first: <number>` (a writer) puts a ready issue ahead of the rest; draws the `ui://forge/map` card",
1315 description:
1416 "An app's plan: open issues ready or waiting, critical path, edges, crew, `parkedTwice`; `done: true` adds closed issues.",
1517 inputSchema: {
1618 type: "object",
17 properties: { app: APP_ARG, done: { type: "boolean" } },
19 properties: { app: APP_ARG, done: { type: "boolean" }, first: { type: "integer", minimum: 1 } },
1820 required: ["app"],
1921 },
22 // Stays `readOnlyHint` (a test pins it, and clients plan on it for the plan
23 // read): the one write, `first`, is refused below without an `rw` token, a
24 // writer's check in `putFirst`, and an agent never passes it.
2025 writes: false,
2126 async run(ctx, user, args) {
2227 const repo = planRepo(ctx, user, args);
2328 if (isAnswer(repo)) return repo;
29 if (args["first"] !== undefined) {
30 if (!scopeAllows(ctx.auth.scope ?? "ro", "rw"))
outdated

A write hidden inside a tool marked writes: false: any client policy or audit that trusts that flag treats map as read-only. Prefer making the rank its own write tool (writes: true) or at least document why; and putFirst is the only check of who, so add a test that a ro token and an agent are refused here.

31 return bad("forbidden", "this token may read, not act");
32 const issue = issueArg(ctx, repo, args, "first");
33 if ("ok" in issue) return issue;
34 const put = putFirst(ctx.app, user, repo, issue);
35 if (!put.ok) return bad(put.error, FIRST_SAY[put.error]);
36 return good({ says: `The crew starts #${issue.number} first.`, first: issue.number });
37 }
2438 const scope = sealedScope(ctx.app.db, repo, user);
2539 const graph = repoGraph(ctx.app.db, repo.id, { ...scope });
2640 const pillars = pillarView(ctx.app.db, repo);
src/http/server.ts +2
@@ -239,6 +239,7 @@ import { issuePicture } from "../web/studio/picture.ts";
239239 import { tellHerePage } from "../web/studio/tell_here.ts";
240240 import { globalMapPage } from "../web/pages/global-map.ts";
241241 import { mapPage } from "../web/pages/map.ts";
242 import { firstSubmit } from "../web/pages/map_first.ts";
242243 import {
243244 milestonePage,
244245 milestonesPage,
@@ -1181,6 +1182,7 @@ export function buildRouter(): Router<Handler> {
11811182 dependencySubmit,
11821183 );
11831184 router.add("GET", "/:owner/:name/map", mapPage);
1185 router.add("POST", "/:owner/:name/map/first", firstSubmit);
11841186 router.add("GET", "/:owner/:name/milestones", milestonesPage);
11851187 router.add("GET", "/:owner/:name/milestones/:number", milestonePage);
11861188 router.add("POST", "/:owner/:name/milestones/:number/watch", milestoneWatch);
src/tui/screens/plan.ts +16 −1
@@ -6,6 +6,8 @@
66 * is left out here as it is there.
77 */
88
9 import { FIRST_SAY, putFirst } from "../../actions/first.ts";
10 import { getIssue } from "../../core/issues.ts";
911 import { repoGraph, readyNow } from "../../core/dependencies.ts";
1012 import { pillarView } from "../../core/pillars.ts";
1113 import { listActiveRuns } from "../../core/runs.ts";
@@ -24,6 +26,8 @@ import { local } from "./where.ts";
2426 export interface PlanLine {
2527 readonly text: string;
2628 readonly number?: number;
29 /** A row of Ready now: `f` may put it first. */
30 readonly ready?: boolean;
2731 }
2832
2933 export function readPlan(f: Session, repo: Repo): PlanLine[] {
@@ -67,6 +71,7 @@ export function readPlan(f: Session, repo: Repo): PlanLine[] {
6771 lines.push({
6872 text: `#${i.number} ${i.title} — ${pillars?.of.get(i.id) ?? "no pillar"}${hold(i.number)}`,
6973 number: i.number,
74 ready: true,
7075 });
7176 lines.push({ text: `Waiting ${waiting.length}` });
7277 for (const i of waiting)
@@ -111,7 +116,7 @@ export function planScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
111116 };
112117 return {
113118 title: "Plan",
114 keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["r"], "refresh")],
119 keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["f"], "first"), binding(["r"], "refresh")],
115120 load(signal) {
116121 live(f, signal, { repoId: repo.id }, () => runAsync(ctx, async () => reload()));
117122 reload();
@@ -133,6 +138,16 @@ export function planScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
133138 openAt(state.index);
134139 return true;
135140 }
141 if (e.key === "f") {
142 const line = lines[state.index];
143 const issue = line?.ready === true ? getIssue(f.db, repo.id, line.number!) : undefined;
144 if (issue === undefined || f.user === undefined) return true;
145 const put = putFirst(f.app, f.user, repo, issue);
146 if (put.ok) ctx.toast(`The crew starts #${issue.number} first.`, "success");
147 else ctx.toast(FIRST_SAY[put.error], "danger");
148 reload();
149 return true;
150 }
136151 if (e.key === "r") {
137152 reload();
138153 return true;
src/web/pages/map.ts +23 −7
@@ -37,6 +37,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
3737 import { cachedLayout } from "../map_cache.ts";
3838 import { holdsFor } from "../../core/holds.ts";
3939 import {
40 canWrite,
4041 getRepoById,
4142 type Repo,
4243 } from "../../core/repos.ts";
@@ -955,6 +956,8 @@ export function countsLine(
955956
956957 function rankedList(
957958 repo: Repo,
959 /** Where a writer's First button posts; absent draws none. */
960 firstAction: string | undefined,
958961 title: string,
959962 items: Ranked[],
960963 say: (r: Ranked) => string,
@@ -968,13 +971,22 @@ function rankedList(
968971 ? html`<p class="muted small">${empty}</p>`
969972 : card(
970973 html`<ul class="list setting-list">
971 ${items.slice(0, 6).map((r) =>
972 row({
973 href: issueHref(base, r.issue.number),
974 title: r.issue.title,
975 titleAttr: r.issue.title,
976 meta: html`#${r.issue.number} · ${say(r)}`,
977 }),
974 ${items.slice(0, 6).map((r, at) =>
975 firstAction === undefined || at === 0
976 ? row({
977 href: issueHref(base, r.issue.number),
978 title: r.issue.title,
979 titleAttr: r.issue.title,
980 meta: html`#${r.issue.number} · ${say(r)}`,
981 })
982 : row({
983 title: html`<a href="${issueHref(base, r.issue.number)}">${r.issue.title}</a>`,

The top row is the only row without a First button, so a writer cannot tell the top is already ranked or just first by default; also rows now differ in markup (title link inside a div vs. a whole-row link). Acceptable per DESIGN, but add a test for it and confirm in the preview that the form's button does not sit inside an anchor on narrow screens.

984 meta: html`#${r.issue.number} · ${say(r)}`,
985 trail: html`<form method="post" action="${firstAction}">
986 <input type="hidden" name="number" value="${r.issue.number}" />
987 ${btn("First", { size: "sm", variant: "ghost" })}
988 </form>`,
989 }),
978990 )}
979991 </ul>`,
980992 { pad: false },
@@ -1401,6 +1413,8 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14011413 return { shown, graph, ready, blocked, critical, placed, marks, readySet, counts, pillars, ask };
14021414 });
14031415 const rendering = performance.now();
1416 const mayFirst =
1417 ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent" && canWrite(db, repo, ctx.auth.user);
14041418 const body = html`${repoHeader(ctx, repo, "map")}
14051419 <div class="page-head mt">
14061420 <h1>Map</h1>
@@ -1436,6 +1450,7 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14361450 ? null
14371451 : rankedList(
14381452 repo,
1453 mayFirst ? `${repoBase(repo)}/map/first` : undefined,
14391454 "Ready now",
14401455 ready,
14411456 (r) =>
@@ -1447,6 +1462,7 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14471462 )}
14481463 ${rankedList(
14491464 repo,
1465 undefined,
14501466 "Blocked on",
14511467 blocked,
14521468 (r) => `holds up ${r.holdsUp}`,
src/web/pages/map_first.ts added +25
@@ -0,0 +1,25 @@
1 /** POST /:owner/:name/map/first — put a ready issue first (#7657). Writers only. */
2 import { FIRST_SAY, putFirst } from "../../actions/first.ts";
3 import { getIssue } from "../../core/issues.ts";
4 import { mayView } from "../../core/sealed.ts";
5 import type { Ctx } from "../../http/context.ts";
6 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
7 import { readForm } from "../form.ts";
8 import { flashTo } from "../layout.ts";
9 import { parseNumber } from "./thread.ts";
10
11 export async function firstSubmit(ctx: Ctx): Promise<Response> {
12 const repo = loadRepo(ctx);
13 if (!repo) return notFoundPage(ctx);
14 if (!ctx.auth.user) return signInFirst(ctx);
15 const form = await readForm(ctx, "rw");
16 if (form instanceof Response) return form;
17 const dest = `${repoBase(repo)}/map`;
18 const number = parseNumber(String(form.get("number") ?? ""));
19 const issue = number === undefined ? undefined : getIssue(ctx.app.db, repo.id, number);
20 if (!issue || issue.kind !== "issue" || !mayView(ctx.app.db, repo, issue, ctx.auth.user))
21 return flashTo(ctx, dest, { tone: "danger", message: FIRST_SAY.invalid });
22 const put = putFirst(ctx.app, ctx.auth.user, repo, issue);
23 if (!put.ok) return flashTo(ctx, dest, { tone: "danger", message: FIRST_SAY[put.error] });
24 return flashTo(ctx, dest, { message: `The crew starts #${issue.number} first.` });
25 }
test/map-first-doors.test.ts added +149
@@ -0,0 +1,149 @@
1 /** Every door to "this first" (#7657): the map page, the POST route, MCP `map`, and the rank's own rules. */
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 { createAgent } from "../src/actions/crew.ts";
8 import { putFirst } from "../src/actions/first.ts";
9 import { openIssue } from "../src/actions/issues.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { readyNow, repoGraph } from "../src/core/dependencies.ts";
12 import type { Issue } from "../src/core/issues.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 let alice: User, bob: User, bot: User;
22 let repo: Repo;
23 let rw = "", ro = "", bobRw = "", botRw = "";
24 const issues: Issue[] = [];
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-first-doors-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 const make = async (username: string, admin = false) => {
31 const u = await createUser(app.db, {
32 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
33 password: "a-good-passphrase", ...(admin ? { adminIfFirst: true } : {}),
34 });
35 if (!u.ok) throw new Error(u.error);
36 return u.value;
37 };
38 alice = await make("alice", true);
39 bob = await make("bob");
40 const agent = await createAgent(app, alice, { username: "mason" });
41 if (!agent.ok) throw new Error(String(agent.error));
42 bot = agent.value.user ?? agent.value;
43 const made = await createRepo(app, alice, { name: "notes", visibility: "public" });
44 if (!made.ok) throw new Error(String(made.error));
45 repo = made.value;
46 for (const title of ["A", "B", "C"]) {
47 const r = openIssue(app, alice, repo, { title });
48 if (!r.ok) throw new Error(String(r.error));
49 issues.push(r.value);
50 }
51 rw = createToken(app.db, alice.id, "rw", "rw").token;
52 ro = createToken(app.db, alice.id, "ro", "ro").token;
53 bobRw = createToken(app.db, bob.id, "rw", "rw").token;
54 botRw = createToken(app.db, bot.id, "rw", "rw").token;
55 });
56
57 afterAll(async () => {
58 servers.stop();
59 app.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 const ranked = () =>
64 app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'issue.ranked'").get()!.n;
65 const order = () => readyNow(repoGraph(app.db, repo.id, { sealed: true })).map((r) => r.issue.title);
66
67 const post = (token: string, number: number, origin: string = servers.url) =>
68 fetch(`${servers.url}/alice/notes/map/first`, {
69 method: "POST",
70 redirect: "manual",
71 headers: { authorization: `Bearer ${token}`, origin },
72 body: new URLSearchParams({ number: String(number) }),
73 });
74
75 const mcp = async (token: string, args: Record<string, unknown>) => {
76 const res = await fetch(`${servers.url}/mcp`, {
77 method: "POST",
78 headers: {
79 "content-type": "application/json",
80 accept: "application/json, text/event-stream",
81 authorization: `Bearer ${token}`,
82 },
83 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "map", arguments: args } }),
84 });
85 const body: any = await res.json();
86 const text: string = body.result.content[0].text;
87 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
88 };
89
90 test("the newest rank wins: ranking another issue goes ahead of the first", () => {
91 expect(putFirst(app, alice, repo, issues[2]!).ok).toBe(true);
92 expect(order()[0]).toBe("C");
93 expect(putFirst(app, alice, repo, issues[1]!).ok).toBe(true);
94 expect(order().slice(0, 2)).toEqual(["B", "C"]);
95 expect(putFirst(app, alice, repo, issues[2]!).ok).toBe(true);
96 expect(order().slice(0, 2)).toEqual(["C", "B"]);
97 });
98
99 test("a reader and an agent cannot put an issue first, and no event is written", () => {
100 const before = ranked();
101 const reader = putFirst(app, bob, repo, issues[0]!);
102 expect(reader.ok ? "" : reader.error).toBe("forbidden");
103 const agent = putFirst(app, bot, repo, issues[0]!);
104 expect(agent.ok ? "" : agent.error).toBe("forbidden");
105 expect(ranked()).toBe(before);
106 });
107
108 test("the First button is a writer's, and not on the top row", async () => {
109 const page = async (token?: string) =>
110 (await fetch(`${servers.url}/alice/notes/map`, { headers: token ? { authorization: `Bearer ${token}` } : {} })).text();
111 const writer = await page(rw);
112 const buttons = writer.match(/<form method="post" action="\/alice\/notes\/map\/first"/g) ?? [];
113 expect(buttons.length).toBe(2);
114 expect(writer).not.toContain(`name="number" value="${issues[2]!.number}"`);
115 expect(writer).toContain(`name="number" value="${issues[0]!.number}"`);
116 expect(await page(bobRw)).not.toContain("/map/first");
117 expect(await page()).not.toContain("/map/first");
118 });
119
120 test("POST /map/first: a writer ranks and is sent back; a reader, a read token and a foreign origin are refused", async () => {
121 const before = ranked();
122 const refused = [await post(bobRw, issues[0]!.number), await post(ro, issues[0]!.number)];
123 expect(refused[1]!.status).toBe(403);
124 const cross = await post(rw, issues[0]!.number, "http://evil.example");
125 expect(cross.status).toBe(403);
126 expect(ranked()).toBe(before);
127 const ok = await post(rw, issues[0]!.number);
128 expect(ok.status).toBe(303);
129 expect(ok.headers.get("location")).toContain("/alice/notes/map");
130 expect(ranked()).toBe(before + 1);
131 expect(order()[0]).toBe("A");
132 const reader = refused[0]!;
133 expect(reader.status).toBe(303);
134 });
135
136 test("MCP map {first}: a writer ranks; a read token, an agent and a non-ready or missing issue are refused", async () => {
137 const before = ranked();
138 const denied = await mcp(ro, { app: "alice/notes", first: issues[1]!.number });
139 expect(denied.error).toContain("may read, not act");
140 expect((await mcp(botRw, { app: "alice/notes", first: issues[1]!.number })).error).toBeDefined();
141 expect((await mcp(rw, { app: "alice/notes", first: 9999 })).error).toContain("no issue");
142 expect(ranked()).toBe(before);
143 const done = await mcp(rw, { app: "alice/notes", first: issues[1]!.number });
144 expect(done.value.first).toBe(issues[1]!.number);
145 expect(order()[0]).toBe("B");
146 expect(ranked()).toBe(before + 1);
147 // A plain read still takes a read token.
148 expect((await mcp(ro, { app: "alice/notes" })).value).toBeDefined();
149 });
test/map-first.test.ts added +82
@@ -0,0 +1,82 @@
1 /** "This first" (#7657): a rank reorders the ready list the dispatcher reads, never lifts a gate. */
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
8 import { putFirst } from "../src/actions/first.ts";
9 import { openIssue, setIssueState } from "../src/actions/issues.ts";
10 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
11 import { addDependency, readyNow, repoGraph } from "../src/core/dependencies.ts";
12 import { getIssueById, type Issue } from "../src/core/issues.ts";
13 import { getRepoById, type Repo } from "../src/core/repos.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { driveRepo } from "../src/crew/autonomy.ts";
16
17 let dataDir: string;
18 let app: App;
19 let alice: User;
20 let repo: Repo;
21 const made: Record<string, Issue> = {};
22
23 const open = (key: string) => {
24 const r = openIssue(app, alice, getRepoById(app.db, repo.id)!, { title: key });
25 if (!r.ok) throw new Error(String(r.error));
26 made[key] = r.value;
27 };
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "forge-first-"));
31 app = createApp({ dataDir, port: 0 });
32 const a = await createUser(app.db, {
33 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
34 password: "a-good-passphrase", adminIfFirst: true,
35 });
36 if (!a.ok) throw new Error(a.error);
37 alice = a.value;
38 const r = await createRepo(app, alice, { name: "notes", visibility: "private" });
39 if (!r.ok) throw new Error(String(r.error));
40 repo = r.value;
41 const c = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# notes\n" }] });
42 if (!c.ok) throw new Error(JSON.stringify(c.error));
43 const agent = await createAgent(app, alice, { username: "mason" });
44 if (!agent.ok) throw new Error(String(agent.error));
45 expect(addToCrew(app, alice, repo, "mason").ok).toBe(true);
46 const on = await updateRepoSettings(app, alice, repo, {
47 autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.",
48 autonomyCeilingUsd: 10, autonomySlots: 1, autonomyBy: alice.id,
49 });
50 expect(on.ok).toBe(true);
51 for (const k of ["A", "B", "blocker", "waits", "gone"]) open(k);
52 expect(addDependency(app.db, made["waits"]!, made["blocker"]!, alice.id).ok).toBe(true);
53 });
54
55 afterAll(async () => {
56 app.close();
57 await rm(dataDir, { recursive: true, force: true });
58 });
59
60 const order = () =>
61 readyNow(repoGraph(app.db, repo.id, { sealed: true })).map((r) => r.issue.title);
62
63 test("ranking B over A puts B first and the dispatcher picks it", async () => {
64 expect(order().filter((t) => t === "A" || t === "B")).toEqual(["A", "B"]);
65 expect(putFirst(app, alice, repo, made["B"]!).ok).toBe(true);
66 expect(order().slice(0, 2)).toEqual(["B", "blocker"]);
67 const event = app.db
68 .query<{ actor_id: string }, []>("SELECT actor_id FROM event WHERE kind = 'issue.ranked'")
69 .get();
70 expect(event?.actor_id).toBe(alice.id);
71 expect(await driveRepo(app, getRepoById(app.db, repo.id)!)).toBe("picked");
72 expect(getIssueById(app.db, made["B"]!.id)!.assigneeId).not.toBeNull();
73 expect(getIssueById(app.db, made["A"]!.id)!.assigneeId).toBeNull();
74 });
75
76 test("a blocked or closed issue cannot be put first", () => {
77 const blocked = putFirst(app, alice, repo, made["waits"]!);
78 expect(blocked.ok ? "" : blocked.error).toBe("invalid");
79 expect(setIssueState(app, alice, repo, made["gone"]!, "closed").ok).toBe(true);
80 const closed = putFirst(app, alice, repo, getIssueById(app.db, made["gone"]!.id)!);
81 expect(closed.ok ? "" : closed.error).toBe("invalid");
82 });
test/tui-plan.test.ts +34
@@ -175,3 +175,37 @@ test("m is offered on the issues list and not on the pulls list", async () => {
175175 expect(pulls.text()).not.toContain("Parked twice");
176176 pulls.app.stop();
177177 });
178
179 test("f on a Ready now row puts it first; a reader's f changes nothing", async () => {
180 const r = await createRepo(forge, alice, { name: "firsts", visibility: "public" });
181 if (!r.ok) throw new Error("repo failed");
182 const where = r.value;
183 const add = (title: string): Issue => {
184 const made = createIssue(forge.db, { repoId: where.id, authorId: alice.id, title, body: "" });
185 if (!made.ok) throw new Error(String(made.error));
186 return made.value;
187 };
188 add("Older thing");
189 const newer = add("Newer thing");
190 const count = () =>
191 forge.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'issue.ranked'").get()!.n;
192 const h = await open(alice, where);
193 await h.press("m");
194 expect(h.text()).toContain("f first");
195 await h.press("j");
196 await h.press("f");
197 expect(count()).toBe(1);
198 expect(h.text()).toContain(`The crew starts #${newer.number} first.`);
199 h.app.stop();
200
201 const carol = await createUser(forge.db, {
202 origin: "seed", trusted: true, username: "dave", email: "[email protected]", password: "a-good-passphrase",
203 });
204 if (!carol.ok) throw new Error(String(carol.error));
205 const reader = await open(carol.value, where);
206 await reader.press("m");
207 await reader.press("f");
208 expect(count()).toBe(1);
209 expect(reader.text()).toContain("Only a person who writes here");
210 reader.app.stop();
211 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs