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 #7773
scout/forge:scout/7657-a-person-puts-a-ready-issue-first-mcp-ma → main 3 commits fork 5 threads · 5 unresolved
docs/MCP.md +1 −1
| @@ -104,7 +104,7 @@ for a tunnel and a forge that sleeps. | ||
| 104 | 104 | | `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 | |
| 105 | 105 | | `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 | |
| 106 | 106 | | `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` an issue number to start next: writers); draws the `ui://forge/map` card | yes | | |
| 108 | 108 | | `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 | |
| 109 | 109 | | `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 | |
| 110 | 110 | | `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) | | |
docs/design/areas/map.md +1
| @@ -25,3 +25,4 @@ is `data-state` on `.map-node`, not a class. | ||
| 25 | 25 | - `.map-edge-done` — an edge with a closed issue at either end, faded. |
| 26 | 26 | - `.map-toggle` — the link beside the counts that swaps between "Show done" (`?done=1`) and "Open only"; padded, 44px tall under `pointer: coarse`. It is a link, not a badge. |
| 27 | 27 | - `.map-ask` — a pillar row's lead-time figures in the side column, inline, with the hover title saying what they measure. |
| 28 | - The First button on a ready row (`rankedList`, writers only) is a `btn("First", { size: "sm" })` in a plain `<form method="post">` placed in the row's `children` slot, so it sits under the row's link rather than inside the anchor (a form in an `<a>` is invalid); it posts with JavaScript off and adds no class. |
docs/features/map-first.md added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | # Put an issue first | |
| 2 | ||
| 3 | A writer says "this first" on a ready issue: the **First** button on the map's *Ready now* list, or MCP `map` with `{ app, first: <issue number> }` (an `rw` token). | |
| 4 | ||
| 5 | - The rank is an `issue.ranked` event with the actor; the latest rank leads. | |
| 6 | - The crew starts ranked ready issues before the rest (before raised, roadmap and small work; ranked work is not held to the small share). | |
| 7 | - It reorders what is ready and never makes anything ready: a closed, blocked or Later-gated issue answers `invalid`. |
src/actions/first.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** | |
| 2 | * Putting a ready issue first. A writer's call, the same for the page and | |
| 3 | * the MCP: the issue must be open and ready now (not blocked, not behind | |
| 4 | * the Later gate), else it is `invalid`. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { RANKED } from "../core/first.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 type { User } from "../core/users.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | ||
| 15 | export type FirstError = "unauthorized" | "forbidden" | "not_found" | "invalid"; | |
| 16 | ||
| 17 | export const FIRST_WORDS: Record<FirstError, string> = { | |
| 18 | unauthorized: "sign in to put an issue first", | |
| 19 | forbidden: "putting an issue first is for a person who writes this repository", | |
| 20 | not_found: "no such issue", | |
| 21 | invalid: "only an open, ready issue can be put first: this one is closed, blocked or waiting", | |
| 22 | }; | |
| 23 | ||
| 24 | export function putFirst( | |
| 25 | app: App, | |
| 26 | actor: User | undefined, | |
| 27 | repo: Repo, | |
| 28 | issue: Issue, | |
| 29 | ): Result<void, FirstError> { | |
| 30 | if (!actor) return err("unauthorized"); | |
| 31 | if (issue.repoId !== repo.id || issue.kind !== "issue") return err("not_found"); | |
| 32 | if (!canWrite(app.db, repo, actor)) return err("forbidden"); | |
| 33 | if (issue.state !== "open") return err("invalid"); | |
| 34 | const ready = readyNow(repoGraph(app.db, repo.id, { sealed: true })); | |
| 35 | if (!ready.some((r) => r.issue.id === issue.id)) return err("invalid"); | |
| 36 | app.bus.append({ | |
| 37 | kind: RANKED, | |
| 38 | repoId: repo.id, | |
| 39 | actorId: actor.id, | |
| 40 | payload: { number: issue.number }, | |
| 41 | }); | |
| 42 | return ok(undefined); | |
| 43 | } |
src/core/dependencies.ts +13 −3
| @@ -14,6 +14,7 @@ import { getIssuesByIds, getIssuesOfRepo, type CloseReason, type Issue } from ". | ||
| 14 | 14 | import { pillarsOf, structuralIds, type Pillars } from "./pillars.ts"; |
| 15 | 15 | import { getRepoById, type Repo } from "./repos.ts"; |
| 16 | 16 | import { unadoptedAmong } from "../crew/direct.ts"; |
| 17 | import { rankedInRepo } from "./first.ts"; | |
| 17 | 18 | import { raisedAt, raisedInRepo } from "./thought_links.ts"; |
| 18 | 19 | import { limbRanks, limbTree, readPlaces } from "./limb_order.ts"; |
| 19 | 20 | |
| @@ -249,6 +250,8 @@ export interface Graph { | ||
| 249 | 250 | * ready ahead of the rest, the latest raise first. |
| 250 | 251 | */ |
| 251 | 252 | readonly raised?: ReadonlyMap<string, string>; |
| 253 | /** Issues a person put first (`first.ts`), by the sequence of the latest rank: the latest leads. */ | |
| 254 | readonly ranked?: ReadonlyMap<string, number>; | |
| 252 | 255 | } |
| 253 | 256 | |
| 254 | 257 | /** |
| @@ -445,6 +448,7 @@ export function repoGraph( | ||
| 445 | 448 | places, |
| 446 | 449 | ), |
| 447 | 450 | }), |
| 451 | ranked: rankedInRepo(db, repoId), | |
| 448 | 452 | raised: |
| 449 | 453 | whole === undefined |
| 450 | 454 | ? raisedAt(db, issues.map((i) => i.id)) |
| @@ -655,10 +659,16 @@ export function readyNow(graph: Graph): Ranked[] { | ||
| 655 | 659 | const of = (r: Ranked) => rank?.get(r.issue.id) ?? Number.MAX_SAFE_INTEGER; |
| 656 | 660 | if (rank !== undefined) ready.sort((a, b) => of(a) - of(b)); |
| 657 | 661 | const raised = graph.raised; |
| 658 | if (raised === undefined || raised.size === 0) return ready; | |
| 659 | 662 | // 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))); | |
| 663 | if (raised !== undefined && raised.size > 0) { | |
| 664 | const at = (r: Ranked) => raised.get(r.issue.id) ?? ""; | |
| 665 | ready.sort((a, b) => at(b).localeCompare(at(a))); | |
| 666 | } | |
| 667 | // What a person put first leads of all, the latest rank first. | |
| 668 | const ranked = graph.ranked; | |
| 669 | if (ranked === undefined || ranked.size === 0) return ready; | |
| 670 | const rankAt = (r: Ranked) => ranked.get(r.issue.id) ?? 0; | |
| 671 | return ready.sort((a, b) => rankAt(b) - rankAt(a)); | |
| 662 | 672 | } |
| 663 | 673 | |
| 664 | 674 | /** |
src/core/event_audience.ts +1
| @@ -41,6 +41,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([ | ||
| 41 | 41 | "usage.delta", |
| 42 | 42 | "issue.raised", |
| 43 | 43 | "issue.blocked", |
| 44 | "issue.ranked", | |
| 44 | 45 | "pull.pushed", |
| 45 | 46 | "forge.spawn.live", |
| 46 | 47 | "forge.spawn.failed", |
src/core/first.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | /** | |
| 2 | * "This first" (#7657): a person ranks a ready issue, and the crew starts | |
| 3 | * ranked ready issues before the rest, the latest rank first. The rank is | |
| 4 | * the `issue.ranked` event itself (with its actor), so there is no second | |
| 5 | * place to keep it. It reorders what is ready; it never makes anything ready. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | ||
| 10 | /** The event a rank is. */ | |
| 11 | export const RANKED = "issue.ranked"; | |
| 12 | ||
| 13 | /** | |
| 14 | * Each issue of a repository that was ranked, with the sequence of its latest rank (higher is later). | |
| 15 | * Cost: `event_repo_kind_number_at` (repo_id, kind, payload number) covers the | |
| 16 | * filter, so only this repository's `issue.ranked` events are read, not its whole log. | |
outdated
This runs on every repoGraph call, which includes every map render, and scans all events of the kind through json_extract with no index on the payload. Confirm there is an index covering (repo_id, kind), and add a test or note on cost. Also use the exported RANKED constant in src/actions/first.ts, which currently repeats the string "issue.ranked". |
||
| 17 | */ | |
| 18 | export function rankedInRepo(db: Database, repoId: string): Map<string, number> { | |
| 19 | const rows = db | |
| 20 | .query<{ id: string; at: number }, [string, string]>( | |
| 21 | `SELECT issue.id AS id, MAX(e.seq) AS at FROM event e | |
| 22 | JOIN issue ON issue.repo_id = e.repo_id AND issue.number = json_extract(e.payload, '$.number') | |
| 23 | WHERE e.repo_id = ?1 AND e.kind = ?2 AND issue.kind = 'issue' | |
| 24 | GROUP BY issue.id`, | |
| 25 | ) | |
| 26 | .all(repoId, RANKED); | |
| 27 | return new Map(rows.map((r) => [r.id, r.at])); | |
| 28 | } |
src/crew/autonomy.ts +3 −1
| @@ -107,6 +107,7 @@ import { handedOverPulls, SKIP_SUMMARY, skipsReplan } from "./guard.ts"; | ||
| 107 | 107 | import { atRunCap, type Held, heldBy, heldWords, replannable } from "./held.ts"; |
| 108 | 108 | import { holdHot, hotFiles, hotWords, learnPullFiles } from "./hot_files.ts"; |
| 109 | 109 | import { NO_PULL, shunnedBy, stallReason, unstickOwed } from "./stalls.ts"; |
| 110 | import { rankedInRepo } from "../core/first.ts"; | |
| 110 | 111 | import { alreadyDone, BY_CREW, DONE_LIKE } from "../core/done_on_main.ts"; |
| 111 | 112 | import { repoDir } from "../git/repos.ts"; |
| 112 | 113 | import { ALREADY_NOTE, alreadyDoneOids } from "./already.ts"; |
| @@ -376,10 +377,11 @@ function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], slotted: re | ||
| 376 | 377 | const small = smallIssues(app.db, issues); |
| 377 | 378 | const roadmap = roadmapIssues(app.db, repo, issues.map((i) => i.id)); |
| 378 | 379 | const raised = raisedAt(app.db, issues.map((i) => i.id)); |
| 380 | const ranked = rankedInRepo(app.db, repo.id); | |
| 379 | 381 | const running = smallOfIds(app.db, slotted.flatMap((r) => (r.issueId === null ? [] : [r.issueId]))); |
| 380 | 382 | return slotOrder( |
| 381 | 383 | ready, |
| 382 | (r) => ({ raised: raised.has(r.issue.id), roadmap: roadmap.has(r.issue.id), small: small.has(r.issue.id) }), | |
| 384 | (r) => ({ ranked: ranked.has(r.issue.id), raised: raised.has(r.issue.id), roadmap: roadmap.has(r.issue.id), small: small.has(r.issue.id) }), | |
| 383 | 385 | running, |
| 384 | 386 | smallCap(slots, smallShare(app.db)), |
| 385 | 387 | ); |
src/http/mcp/tools/map.ts +14 −5
| @@ -5,22 +5,31 @@ import { pillarView } from "../../../core/pillars.ts"; | ||
| 5 | 5 | import { askToLiveFor } from "../../../web/ask_to_live.ts"; |
| 6 | 6 | import { listActiveRuns } from "../../../core/runs.ts"; |
| 7 | 7 | import { mapJson, marksFor, withoutDone } from "../../../web/pages/map.ts"; |
| 8 | import { good, type Tool, APP_ARG, planRepo, isAnswer } from "../shared.ts"; | |
| 8 | import { FIRST_WORDS, putFirst } from "../../../actions/first.ts"; | |
| 9 | import { bad, good, issueArg, type Tool, APP_ARG, planRepo, isAnswer } from "../shared.ts"; | |
| 9 | 10 | |
| 10 | 11 | export const tool: Tool = { |
| 11 | 12 | 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", | |
| 13 | 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` an issue number to start next: writers); draws the `ui://forge/map` card", | |
| 13 | 14 | description: |
| 14 | "An app's plan: open issues ready or waiting, critical path, edges, crew, `parkedTwice`; `done: true` adds closed issues.", | |
| 15 | "An app's plan: ready, waiting, critical path, crew; `done` adds closed; `first` puts a ready issue first.", | |
| 15 | 16 | inputSchema: { |
| 16 | 17 | type: "object", |
| 17 | properties: { app: APP_ARG, done: { type: "boolean" } }, | |
| 18 | properties: { app: APP_ARG, done: { type: "boolean" }, first: { type: "number" } }, | |
| 18 | 19 | required: ["app"], |
| 19 | 20 | }, |
| 20 | writes: false, | |
| 21 | writes: true, | |
| 22 | readsWithout: "first", | |
| 21 | 23 | async run(ctx, user, args) { |
| 22 | 24 | const repo = planRepo(ctx, user, args); |
| 23 | 25 | if (isAnswer(repo)) return repo; |
| 26 | if (args["first"] !== undefined) { | |
| 27 | const issue = issueArg(ctx, repo, args, "first"); | |
| 28 | if (!("number" in issue)) return issue; | |
| 29 | const ranked = putFirst(ctx.app, user, repo, issue); | |
| 30 | if (!ranked.ok) return bad(ranked.error, FIRST_WORDS[ranked.error]); | |
| 31 | return good({ first: issue.number, says: `Done: #${issue.number} is first in line.` }); | |
| 32 | } | |
outdated
The ternary is redundant: |
||
| 24 | 33 | const scope = sealedScope(ctx.app.db, repo, user); |
| 25 | 34 | const graph = repoGraph(ctx.app.db, repo.id, { ...scope }); |
| 26 | 35 | const pillars = pillarView(ctx.app.db, repo); |
src/http/server.ts +2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { firstSubmit } from "../web/pages/map_first.ts"; | |
| 8 | 9 | import { followUpstreamCheck, followUpstreamUpdate } from "../web/pages/upstream-follow.ts"; |
| 9 | 10 | import { secureFor } from "./cookie_secure.ts"; |
| 10 | 11 | import { refusedByDatabase, shownRefusal } from "./refusal.ts"; |
| @@ -1172,6 +1173,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1172 | 1173 | router.add("POST", "/:owner/:name/issues/:number/assignee", (ctx) => |
| 1173 | 1174 | assigneeSubmit(ctx, "issue"), |
| 1174 | 1175 | ); |
| 1176 | router.add("POST", "/:owner/:name/issues/:number/first", firstSubmit); | |
| 1175 | 1177 | // The studio's verbs on an app: tell, ship, say, and — on a shipped |
| 1176 | 1178 | // change — take it back. |
| 1177 | 1179 | router.add("GET", "/:owner/:name/tell", tellHerePage); |
src/tui/screens/plan.ts +20 −1
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | * is left out here as it is there. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { FIRST_WORDS, putFirst } from "../../actions/first.ts"; | |
| 10 | import { getIssue } from "../../core/issues.ts"; | |
| 9 | 11 | import { repoGraph, readyNow } from "../../core/dependencies.ts"; |
| 10 | 12 | import { pillarView } from "../../core/pillars.ts"; |
| 11 | 13 | import { listActiveRuns } from "../../core/runs.ts"; |
| @@ -24,6 +26,8 @@ import { local } from "./where.ts"; | ||
| 24 | 26 | export interface PlanLine { |
| 25 | 27 | readonly text: string; |
| 26 | 28 | readonly number?: number; |
| 29 | /** Ready now, so a writer may put it first. */ | |
| 30 | readonly ready?: boolean; | |
| 27 | 31 | } |
| 28 | 32 | |
| 29 | 33 | export function readPlan(f: Session, repo: Repo): PlanLine[] { |
| @@ -67,6 +71,7 @@ export function readPlan(f: Session, repo: Repo): PlanLine[] { | ||
| 67 | 71 | lines.push({ |
| 68 | 72 | text: `#${i.number} ${i.title} — ${pillars?.of.get(i.id) ?? "no pillar"}${hold(i.number)}`, |
| 69 | 73 | number: i.number, |
| 74 | ready: true, | |
| 70 | 75 | }); |
| 71 | 76 | lines.push({ text: `Waiting ${waiting.length}` }); |
| 72 | 77 | for (const i of waiting) |
| @@ -111,7 +116,7 @@ export function planScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 111 | 116 | }; |
| 112 | 117 | return { |
| 113 | 118 | 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")], | |
| 115 | 120 | load(signal) { |
| 116 | 121 | live(f, signal, { repoId: repo.id }, () => runAsync(ctx, async () => reload())); |
| 117 | 122 | reload(); |
| @@ -133,6 +138,20 @@ export function planScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 133 | 138 | openAt(state.index); |
| 134 | 139 | return true; |
| 135 | 140 | } |
| 141 | if (e.key === "f") { | |
| 142 | const line = lines[state.index]; | |
| 143 | const issue = line?.number === undefined ? undefined : getIssue(f.db, repo.id, line.number); | |
| 144 | if (issue === undefined || line?.ready !== true) { | |
| 145 | ctx.toast(FIRST_WORDS.invalid, "danger"); | |
| 146 | return true; | |
| 147 | } | |
| 148 | const done = putFirst(f.app, f.user, repo, issue); | |
| 149 | if (done.ok) { | |
| 150 | ctx.toast(`#${issue.number} is first in line.`, "success"); | |
| 151 | reload(); | |
| 152 | } else ctx.toast(FIRST_WORDS[done.error], "danger"); | |
| 153 | return true; | |
| 154 | } | |
| 136 | 155 | if (e.key === "r") { |
| 137 | 156 | reload(); |
| 138 | 157 | return true; |
src/web/pages/map.ts +14
| @@ -37,6 +37,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t | ||
| 37 | 37 | import { cachedLayout } from "../map_cache.ts"; |
| 38 | 38 | import { holdsFor } from "../../core/holds.ts"; |
| 39 | 39 | import { |
| 40 | canWrite, | |
| 40 | 41 | getRepoById, |
| 41 | 42 | type Repo, |
| 42 | 43 | } from "../../core/repos.ts"; |
| @@ -960,6 +961,7 @@ function rankedList( | ||
| 960 | 961 | say: (r: Ranked) => string, |
| 961 | 962 | empty: string, |
| 962 | 963 | issueHref: (base: string, number: number) => string, |
| 964 | firstBy = false, | |
| 963 | 965 | ): Html { |
| 964 | 966 | const base = repoBase(repo); |
| 965 | 967 | return html`<section class="stack-tight"> |
| @@ -974,6 +976,17 @@ function rankedList( | ||
| 974 | 976 | title: r.issue.title, |
| 975 | 977 | titleAttr: r.issue.title, |
| 976 | 978 | meta: html`#${r.issue.number} · ${say(r)}`, |
| 979 | ...(firstBy && r.issue.state === "open" | |
| 980 | ? { | |
| 981 | children: [ | |
| 982 | html`<li> | |
| 983 | <form method="post" action="${base}/issues/${r.issue.number}/first"> | |
| 984 | ${btn("First", { size: "sm" })} | |
A hand-built |
||
| 985 | </form> | |
| 986 | </li>`, | |
| 987 | ], | |
| 988 | } | |
| 989 | : {}), | |
| 977 | 990 | }), |
| 978 | 991 | )} |
| 979 | 992 | </ul>`, |
| @@ -1444,6 +1457,7 @@ export async function mapPage(ctx: Ctx): Promise<Response> { | ||
| 1444 | 1457 | : `finishing it frees ${r.holdsUp}`, |
| 1445 | 1458 | "Nothing is ready: everything open waits for something.", |
| 1446 | 1459 | tellHref, |
| 1460 | canWrite(db, repo, ctx.auth.user), | |
| 1447 | 1461 | )} |
| 1448 | 1462 | ${rankedList( |
| 1449 | 1463 | repo, |
src/web/pages/map_first.ts added +29
| @@ -0,0 +1,29 @@ | ||
| 1 | /** POST /:owner/:name/issues/:number/first: the map's First button (#7657). */ | |
| 2 | ||
| 3 | import { FIRST_WORDS, putFirst } from "../../actions/first.ts"; | |
| 4 | import { getIssue } from "../../core/issues.ts"; | |
| 5 | import { mayView } from "../../core/sealed.ts"; | |
| 6 | import type { Ctx } from "../../http/context.ts"; | |
| 7 | import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts"; | |
| 8 | import { readForm } from "../form.ts"; | |
| 9 | import { flashTo } from "../layout.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 n = Number(ctx.params.number); | |
| 18 | const issue = Number.isInteger(n) && n > 0 ? getIssue(ctx.app.db, repo.id, n) : undefined; | |
| 19 | if (!issue || !mayView(ctx.app.db, repo, issue, ctx.auth.user)) return notFoundPage(ctx); | |
| 20 | const dest = `${repoBase(repo)}/map`; | |
| 21 | const done = putFirst(ctx.app, ctx.auth.user, repo, issue); | |
| 22 | return flashTo( | |
| 23 | ctx, | |
| 24 | dest, | |
| 25 | done.ok | |
| 26 | ? { message: `#${issue.number} is first in line.` } | |
| 27 | : { tone: "danger", message: FIRST_WORDS[done.error] }, | |
| 28 | ); | |
| 29 | } |
test/map-first.test.ts added +227
| @@ -0,0 +1,227 @@ | ||
| 1 | /** "This first" (#7657): ranking B over A makes the dispatcher pick B; closed or blocked cannot be ranked. */ | |
| 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 { 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 { setCrewRole } from "../src/core/agents.ts"; | |
| 12 | import { addDependency } from "../src/core/dependencies.ts"; | |
| 13 | import { getIssue } from "../src/core/issues.ts"; | |
| 14 | import { getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 15 | import { createUser } from "../src/core/users.ts"; | |
| 16 | import { readyNow, repoGraph } from "../src/core/dependencies.ts"; | |
| 17 | import { slotOrder } from "../src/crew/small_share.ts"; | |
| 18 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 19 | import { getUserByName } from "../src/core/users.ts"; | |
| 20 | import { driveRepo } from "../src/crew/autonomy.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 23 | ||
| 24 | let dataDir = ""; | |
| 25 | let app: App, servers: Servers, repo: Repo, bearer = ""; | |
| 26 | let alice: NonNullable<ReturnType<typeof getUserByName>>; | |
| 27 | const fresh = () => getRepoById(app.db, repo.id)!; | |
| 28 | const issue = (n: number) => getIssue(app.db, repo.id, n)!; | |
| 29 | ||
| 30 | beforeAll(async () => { | |
| 31 | dataDir = await mkdtemp(join(tmpdir(), "forge-mapfirst-")); | |
| 32 | app = createApp({ dataDir, port: 0 }); | |
| 33 | servers = await serve(app); | |
| 34 | const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 35 | if (!admin.ok) throw new Error(admin.error); | |
| 36 | alice = admin.value; | |
| 37 | const made = await createRepo(app, alice, { name: "engine", visibility: "private" }); | |
| 38 | if (!made.ok) throw new Error(String(made.error)); | |
| 39 | repo = made.value; | |
| 40 | const seeded = await commitToBranch(app, alice, repo, { | |
| 41 | message: "Start", | |
| 42 | files: [{ path: "README.md", content: "# engine\n" }], | |
| 43 | }); | |
| 44 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 45 | for (const name of ["scout", "atlas"]) { | |
| 46 | const agent = await createAgent(app, alice, { username: name }); | |
| 47 | if (!agent.ok) throw new Error(String(agent.error)); | |
| 48 | expect(addToCrew(app, alice, repo, name).ok).toBe(true); | |
| 49 | } | |
| 50 | setCrewRole(app.db, repo.id, getUserByName(app.db, "atlas")!.id, "planner"); | |
| 51 | // #1 holds #3 up, so it would go first; #2 is free; #3 is blocked; #4 is closed. | |
| 52 | for (const title of ["Renderer", "Input", "Scene graph", "Old"]) { | |
| 53 | const opened = openIssue(app, alice, repo, { title }); | |
| 54 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 55 | } | |
| 56 | expect(addDependency(app.db, issue(3), issue(1), alice.id).ok).toBe(true); | |
| 57 | setIssueState(app, alice, repo, issue(4), "closed"); | |
| 58 | const minted = await fetch(`${servers.url}/api/v1/tokens`, { | |
| 59 | method: "POST", | |
| 60 | headers: { "content-type": "application/json" }, | |
| 61 | body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }), | |
| 62 | }); | |
| 63 | bearer = ((await minted.json()) as { token: string }).token; | |
| 64 | }); | |
| 65 | ||
| 66 | afterAll(async () => { | |
| 67 | servers.stop?.(); | |
| 68 | app.close(); | |
| 69 | await rm(dataDir, { recursive: true, force: true }); | |
| 70 | }); | |
| 71 | ||
| 72 | const mcp = async (args: Record<string, unknown>) => { | |
| 73 | const res = await fetch(`${servers.url}/mcp`, { | |
| 74 | method: "POST", | |
| 75 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${bearer}` }, | |
| 76 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "map", arguments: { app: "alice/engine", ...args } } }), | |
| 77 | }); | |
| 78 | const body: any = await res.json(); | |
| 79 | return body.result as { isError?: boolean; content: { text: string }[] }; | |
| 80 | }; | |
| 81 | ||
| 82 | test("a closed or blocked issue cannot be put first", async () => { | |
| 83 | expect(putFirst(app, alice, repo, issue(4))).toEqual({ ok: false, error: "invalid" }); | |
| 84 | expect(putFirst(app, alice, repo, issue(3))).toEqual({ ok: false, error: "invalid" }); | |
| 85 | const refused = await mcp({ first: 3 }); | |
| 86 | expect(refused.isError).toBe(true); | |
| 87 | expect(refused.content[0]!.text).toContain("invalid"); | |
| 88 | expect(app.db.query("SELECT COUNT(*) AS n FROM event WHERE kind = 'issue.ranked'").get()).toEqual({ n: 0 }); | |
| 89 | }); | |
| 90 | ||
| 91 | test("a stranger cannot rank", () => { | |
| 92 | expect(putFirst(app, undefined, repo, issue(2))).toEqual({ ok: false, error: "unauthorized" }); | |
| 93 | }); | |
| 94 | ||
| 95 | test("ranking B over A puts B first on the map and the dispatcher picks it", async () => { | |
| 96 | const on = await updateRepoSettings(app, alice, repo, { | |
| 97 | autonomy: "autonomous", | |
| 98 | autonomyDirection: "Build the engine.", | |
| 99 | autonomyCeilingUsd: 10, | |
| 100 | autonomySlots: 1, | |
| 101 | autonomyBy: alice.id, | |
| 102 | }); | |
| 103 | expect(on.ok).toBe(true); | |
| 104 | const before = JSON.parse((await mcp({})).content[0]!.text) as { ready: { number: number }[] }; | |
| 105 | expect(before.ready.map((r) => r.number)).toEqual([1, 2]); | |
| 106 | ||
| 107 | const done = await mcp({ first: 2 }); | |
| 108 | expect(done.isError).not.toBe(true); | |
| 109 | const event = app.db | |
| 110 | .query<{ actor_id: string; payload: string }, []>("SELECT actor_id, payload FROM event WHERE kind = 'issue.ranked'") | |
| 111 | .get()!; | |
| 112 | expect(event.actor_id).toBe(alice.id); | |
| 113 | expect(JSON.parse(event.payload)).toEqual({ number: 2 }); | |
| 114 | ||
| 115 | const after = JSON.parse((await mcp({})).content[0]!.text) as { ready: { number: number }[] }; | |
| 116 | expect(after.ready.map((r) => r.number)).toEqual([2, 1]); | |
| 117 | ||
| 118 | expect(await driveRepo(app, fresh())).toBe("picked"); | |
| 119 | expect(issue(2).assigneeName).toBe("scout"); | |
outdated
The test name ends in a stray comma. It also covers only the writer case, so add the non-writer and guest cases. |
||
| 120 | expect(issue(1).assigneeName).toBeNull(); | |
| 121 | }); | |
| 122 | ||
| 123 | const rankedCount = () => | |
| 124 | app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'issue.ranked'").get()!.n; | |
| 125 | const post = (path: string, headers: Record<string, string> = {}) => | |
| 126 | fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers }); | |
| 127 | ||
| 128 | test("the latest rank leads when two issues are ranked", () => { | |
| 129 | expect(putFirst(app, alice, repo, issue(1)).ok).toBe(true); | |
| 130 | const order = (): number[] => readyNow(repoGraph(app.db, repo.id)).map((r) => r.issue.number).filter((n) => n <= 2); | |
| 131 | expect(order()).toEqual([1, 2]); | |
| 132 | expect(putFirst(app, alice, repo, issue(2)).ok).toBe(true); | |
| 133 | expect(order()).toEqual([2, 1]); | |
| 134 | }); | |
| 135 | ||
| 136 | test("a ranked small issue is not held to the small share; an unranked one is", () => { | |
| 137 | const c = (t: string) => ({ ranked: t === "s1", raised: false, roadmap: false, small: t.startsWith("s") }); | |
| 138 | expect(slotOrder(["r1", "s1", "s2"], c, 2, 2)).toEqual(["s1", "r1"]); | |
| 139 | expect(slotOrder(["r1", "s2"], c, 2, 2)).toEqual(["r1"]); | |
| 140 | }); | |
| 141 | ||
| 142 | describe("the map's First button and its route", () => { | |
| 143 | let openRepo: Repo, bobToken = "", aliceRw = "", aliceRo = ""; | |
| 144 | const base = "/alice/open"; | |
| 145 | beforeAll(async () => { | |
| 146 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 147 | if (!bob.ok) throw new Error(bob.error); | |
| 148 | const made = await createRepo(app, alice, { name: "open", visibility: "public" }); | |
| 149 | if (!made.ok) throw new Error(String(made.error)); | |
| 150 | openRepo = made.value; | |
| 151 | const seeded = await commitToBranch(app, alice, openRepo, { message: "Start", files: [{ path: "README.md", content: "# open\n" }] }); | |
| 152 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 153 | expect(openIssue(app, alice, openRepo, { title: "Paint" }).ok).toBe(true); | |
| 154 | bobToken = tokenFor(app, "bob", "rw"); | |
| 155 | aliceRw = tokenFor(app, "alice", "rw", "rw"); | |
| 156 | aliceRo = tokenFor(app, "alice", "ro", "ro"); | |
| 157 | }); | |
| 158 | const bearerOf = (t: string) => ({ authorization: `Bearer ${t}` }); | |
| 159 | ||
| 160 | test("a writer sees First as a POST form; a non-writer and a guest do not", async () => { | |
| 161 | const asWriter = await (await fetch(`${servers.url}${base}/map`, { headers: bearerOf(aliceRw) })).text(); | |
| 162 | expect(asWriter).toMatch(/<form method="post" action="\/alice\/open\/issues\/1\/first">/); | |
| 163 | for (const headers of [bearerOf(bobToken), {}]) { | |
| 164 | const page = await (await fetch(`${servers.url}${base}/map`, { headers })).text(); | |
| 165 | expect(page).not.toContain("/issues/1/first"); | |
| 166 | } | |
| 167 | }); | |
| 168 | ||
| 169 | test("a guest is sent to sign in and nothing is written", async () => { | |
| 170 | const before = rankedCount(); | |
| 171 | const res = await post(`${base}/issues/1/first`, { origin: servers.url }); | |
| 172 | expect(res.status).toBeGreaterThanOrEqual(300); | |
| 173 | expect(res.status).toBeLessThan(400); | |
| 174 | expect(res.headers.get("location")).toContain("/signin"); | |
| 175 | expect(rankedCount()).toBe(before); | |
| 176 | }); | |
| 177 | ||
| 178 | test("a cross-origin post and a read-only token are refused", async () => { | |
| 179 | const before = rankedCount(); | |
| 180 | expect((await post(`${base}/issues/1/first`, { ...bearerOf(aliceRw), origin: "https://evil.example" })).status).toBe(403); | |
| 181 | expect((await post(`${base}/issues/1/first`, { ...bearerOf(aliceRo), origin: servers.url })).status).toBe(403); | |
| 182 | expect(rankedCount()).toBe(before); | |
| 183 | }); | |
| 184 | ||
| 185 | test("a non-writer is told it is for writers, over the page and the MCP, and no event is written", async () => { | |
| 186 | const before = rankedCount(); | |
| 187 | const res = await post(`${base}/issues/1/first`, { ...bearerOf(bobToken), origin: servers.url }); | |
| 188 | expect(res.status).toBe(303); | |
| 189 | expect(res.headers.get("location")).toBe(`${base}/map`); | |
| 190 | expect(decodeURIComponent(res.headers.get("set-cookie") ?? "")).toContain("is for a person who writes this repository"); | |
| 191 | const over = await fetch(`${servers.url}/mcp`, { | |
| 192 | method: "POST", | |
| 193 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...bearerOf(bobToken) }, | |
| 194 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "map", arguments: { app: "alice/open", first: 1 } } }), | |
| 195 | }); | |
| 196 | const result = ((await over.json()) as any).result as { isError?: boolean; content: { text: string }[] }; | |
| 197 | expect(result.isError).toBe(true); | |
| 198 | expect(result.content[0]!.text).toContain("forbidden"); | |
| 199 | expect(rankedCount()).toBe(before); | |
| 200 | }); | |
| 201 | ||
| 202 | test("a writer's post writes the event and flashes", async () => { | |
| 203 | const before = rankedCount(); | |
| 204 | const res = await post(`${base}/issues/1/first`, { ...bearerOf(aliceRw), origin: servers.url }); | |
| 205 | expect(res.status).toBe(303); | |
| 206 | expect(res.headers.get("location")).toBe(`${base}/map`); | |
| 207 | expect(decodeURIComponent(res.headers.get("set-cookie") ?? "")).toContain("#1 is first in line."); | |
| 208 | expect(rankedCount()).toBe(before + 1); | |
| 209 | }); | |
| 210 | }); | |
| 211 | ||
| 212 | test("a read-only token cannot put an issue first over the MCP, but still reads the map", async () => { | |
| 213 | const ro = tokenFor(app, "alice", "ro", "ro2"); | |
| 214 | const call = async (args: Record<string, unknown>) => { | |
| 215 | const res = await fetch(`${servers.url}/mcp`, { | |
| 216 | method: "POST", | |
| 217 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${ro}` }, | |
| 218 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "map", arguments: { app: "alice/engine", ...args } } }), | |
| 219 | }); | |
| 220 | return ((await res.json()) as any).result as { isError?: boolean; content: { text: string }[] }; | |
| 221 | }; | |
| 222 | const before = rankedCount(); | |
| 223 | const refused = await call({ first: 1 }); | |
| 224 | expect(refused.isError).toBe(true); | |
| 225 | expect(rankedCount()).toBe(before); | |
| 226 | expect((await call({})).isError).not.toBe(true); | |
| 227 | }); |
test/mcp.test.ts +2 −1
| @@ -890,7 +890,8 @@ describe("the forge over MCP", () => { | ||
| 890 | 890 | t.annotations?.readOnlyHint ?? false, |
| 891 | 891 | ]), |
| 892 | 892 | ); |
| 893 | expect([hints.map, hints.wait_for]).toEqual([true, false]); | |
| 893 | // `map` also takes `first` (a writer ranks a ready issue), so it is no longer read-only by hint. | |
| 894 | expect([hints.map, hints.wait_for]).toEqual([false, false]); | |
| 894 | 895 | |
| 895 | 896 | expect( |
| 896 | 897 | (await tool(rw, "wait_for", { app: "alice/game", issue: b, blockedBy: a })) |
test/tui-plan-first.test.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | /** The terminal's plan screen puts a ready issue first with `f`, through the same putFirst the page and MCP use (#7657). */ | |
| 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 { openIssue } from "../src/actions/issues.ts"; | |
| 7 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 8 | import { createApp, type App } from "../src/app.ts"; | |
| 9 | import { type Repo } from "../src/core/repos.ts"; | |
| 10 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 12 | import { planScreen } from "../src/tui/screens/plan.ts"; | |
| 13 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 14 | import { quietLogs } from "./helpers/globals.ts"; | |
| 15 | import { settleApp } from "./helpers/tui.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | let dataDir = ""; | |
| 20 | let app: App, repo: Repo, alice: User, bob: User; | |
| 21 | const ranked = () => | |
| 22 | app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'issue.ranked' ORDER BY seq").all().map((r) => JSON.parse(r.payload).number); | |
| 23 | ||
| 24 | beforeAll(async () => { | |
| 25 | dataDir = await mkdtemp(join(tmpdir(), "forge-tui-planfirst-")); | |
| 26 | app = createApp({ dataDir, port: 0 }); | |
| 27 | const users: User[] = []; | |
| 28 | for (const username of ["alice", "bob"]) { | |
| 29 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: username === "alice" }); | |
| 30 | if (!made.ok) throw new Error(made.error); | |
| 31 | users.push(made.value); | |
| 32 | } | |
| 33 | [alice, bob] = users as [User, User]; | |
| 34 | const made = await createRepo(app, alice, { name: "garden", visibility: "public" }); | |
| 35 | if (!made.ok) throw new Error(String(made.error)); | |
| 36 | repo = made.value; | |
| 37 | const seeded = await commitToBranch(app, alice, repo, { message: "seed", files: [{ path: "README.md", content: "# garden\n" }] }); | |
| 38 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 39 | for (const title of ["Dig", "Sow"]) openIssue(app, alice, repo, { title }); | |
| 40 | }, 30_000); | |
| 41 | ||
| 42 | afterAll(async () => { | |
| 43 | app.close(); | |
| 44 | await rm(dataDir, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | ||
| 47 | const open = async (user: User) => { | |
| 48 | const terminal = headlessTerminal(140, 30); | |
| 49 | const { app: tui, session } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false }); | |
| 50 | tui.start(); | |
| 51 | await settleApp(tui); | |
| 52 | tui.push(planScreen(session, tui.ctx, repo)); | |
| 53 | await settleApp(tui); | |
| 54 | const press = async (key: string) => { | |
| 55 | tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 56 | await settleApp(tui); | |
| 57 | }; | |
| 58 | return { press, text: () => tui.screen.toText(), stop: () => tui.stop() }; | |
| 59 | }; | |
| 60 | ||
| 61 | test("f puts the issue under the cursor first; a non-writer is refused in the page's words", async () => { | |
| 62 | const w = await open(alice); | |
| 63 | try { | |
| 64 | await w.press("j"); | |
| 65 | await w.press("f"); | |
| 66 | expect(ranked()).toEqual([2]); | |
| 67 | expect(w.text()).toContain("#2 is first in line."); | |
| 68 | expect(w.text().indexOf("#2 Sow")).toBeLessThan(w.text().indexOf("#1 Dig")); | |
| 69 | } finally { | |
| 70 | w.stop(); | |
| 71 | } | |
| 72 | const r = await open(bob); | |
| 73 | try { | |
| 74 | await r.press("j"); | |
| 75 | await r.press("f"); | |
| 76 | expect(ranked()).toEqual([2]); | |
| 77 | expect(r.text()).toContain("is for a person who writes this repository"); | |
| 78 | } finally { | |
| 79 | r.stop(); | |
| 80 | } | |
| 81 | }); |
of2is a poor name, and this adds a second sort pass after the existing ones. Fold it into one comparator, or name itrankAt.