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

The owner moves an issue up or down inside the open chapter, on the page and as an action on the chapters MCP tool #15781

Merged opened this

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

Merged

scout/forge:scout/15761-the-owner-moves-an-issue-up-or-down-insi → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/15761-the-owner-moves-an-issue-up-or-down-insi was merged into main as 2d4455a.

Review

Sign in to review this change.
11 files changed +403 −26
docs/features/chapters.md +3 −1
@@ -13,7 +13,9 @@ A chapter is a named list of a repository's issues that is finished, tagged and
1313 - **Closed is forever.** A closed chapter stays readable at its own address and cannot be reopened or changed. A fix for something it shipped goes in a patch chapter (`v1.0.1`), opened with one click from the closed chapter's page.
1414 - **No chapter, no change.** A repository that never drafted one flows continuously, as before.
1515
16 Doors: the page (`/chapters`, linked from `/queue`), the terminal (`src/tui/screens/chapters.ts`, the palette's "Chapters" while an app is open: `n` drafts, `o` opens, `s` ships, `c` closes (nothing moves; refused with the page's sentence naming what is in the way), `u` undoes a close within 60 seconds, `p` patches, `enter` shows the list where `a` adds an issue and `x` takes one out) and the API (`GET`/`POST /api/v1/repos/:owner/:name/chapters`, `POST …/chapters/:chapter/:verb` with `open`, `add`, `remove`, `ship`, `patch`). Only a person who administers the repository acts; an agent is refused.
16 - **Order (#15761).** The list is in the order the owner set, not by issue number: a new item goes last. On the page the owner sees **Up** on every row but the first and **Down** on every row but the last; in the terminal `u` and `d` move the row under the cursor (the cursor follows it); on the MCP, `action: "move"` with `chapter`, `number` and `direction: "up"|"down"` (a preview without `confirm: true`). One move swaps neighbours, so the opposite move undoes it; the first cannot go up nor the last down (`at_edge`); a closed chapter holds its order. Each move is a `chapter.item_moved` event, and only a person who administers the repository moves.
17
18 Doors: the page (`/chapters`, linked from `/queue`), the terminal (`src/tui/screens/chapters.ts`, the palette's "Chapters" while an app is open: `n` drafts, `o` opens, `s` ships, `c` closes (nothing moves; refused with the page's sentence naming what is in the way), `u` undoes a close within 60 seconds, `p` patches, `enter` shows the list where `a` adds an issue, `u`/`d` move one up or down and `x` takes one out) and the API (`GET`/`POST /api/v1/repos/:owner/:name/chapters`, `POST …/chapters/:chapter/:verb` with `open`, `add`, `remove`, `ship`, `patch`). Only a person who administers the repository acts; an agent is refused.
1719
1820 The MCP answers too: the `repo` tool with `view: "chapters"` lists a repository's chapters (name, what done means, state); adding `chapter: "v1"` names that chapter's items (`done`, `building` or `left`), its `progress` (the same sentence the page and the terminal print, from `progressSentence`) and `finishesOn`. `chapter` without `view` is `invalid`; a repository the caller cannot read is refused as the page refuses it.
1921
src/actions/chapters.ts +41 −1
@@ -12,6 +12,8 @@ import {
1212 getChapter,
1313 itemsOf,
1414 EVERY_ITEM,
15 moveItem,
16 type Way,
1517 type ItemView,
1618 nextChapterOf,
1719 nextName,
@@ -41,7 +43,7 @@ import { repoDir } from "../git/repos.ts";
4143 import { err, ok, type Result } from "../kernel/result.ts";
4244 import { writeChapterWave } from "./chapter_wave.ts";
4345
44 export type ChapterActError = ChapterError | "forbidden" | "no_issue" | "unfinished" | "no_branch" | "tag_exists" | "git" | "too_late" | "moved" | "another_open" | "unproven";
46 export type ChapterActError = ChapterError | "forbidden" | "no_issue" | "unfinished" | "no_branch" | "tag_exists" | "git" | "too_late" | "moved" | "another_open" | "unproven" | "at_edge";
4547
4648 /** How long after closing a chapter its owner may take the close back. */
4749 export const CLOSE_UNDO_MS = 60_000;
@@ -171,6 +173,43 @@ export function fill(app: App, actor: User | undefined, repo: Repo, name: string
171173 return done;
172174 }
173175
176 /** The checks `move` makes before it writes, shared with `previewMove`. */
177 function movePlan(app: App, actor: User | undefined, repo: Repo, name: string, number: number, way: Way): Result<{ actor: User; chapter: Chapter; issue: Issue; at: number; of: number }, ChapterActError> {
178 if (!owner(app, actor, repo)) return err("forbidden");
179 const chapter = getChapter(app.db, repo.id, name);
180 if (chapter === undefined) return err("not_found");
181 if (chapter.state === "closed") return err("closed");
182 const issue = getIssue(app.db, repo.id, number);
183 if (issue === undefined || issue.kind !== "issue") return err("no_issue");
184 const items = itemsOf(app.db, chapter, EVERY_ITEM);
185 const at = items.findIndex((i) => i.number === number);
186 if (at < 0) return err("not_found");
187 if (way === "up" ? at === 0 : at === items.length - 1) return err("at_edge");
188 return ok({ actor, chapter, issue, at, of: items.length });
189 }
190
191 const placeWords = (n: number, way: Way, at: number): string => `#${n} from place ${at + 1} to ${at + (way === "up" ? 0 : 2)}`;
192
193 /** What a move would do, changing nothing. */
194 export function previewMove(app: App, actor: User | undefined, repo: Repo, name: string, number: number, way: Way): Result<{ says: string }, ChapterActError> {
195 const planned = movePlan(app, actor, repo, name, number, way);
196 return planned.ok ? ok({ says: `Would move ${placeWords(number, way, planned.value.at)} in ${name}.` }) : planned;
197 }
198
199 /**
200 * Move an issue one place up or down its chapter's list: the owner's act, recorded; the opposite
201 * move undoes it.
202 */
203 export function move(app: App, actor: User | undefined, repo: Repo, name: string, number: number, way: Way): Result<{ says: string }, ChapterActError> {
204 const planned = movePlan(app, actor, repo, name, number, way);
205 if (!planned.ok) return planned;
206 const { chapter, issue, at } = planned.value;
207 const done = moveItem(app.db, chapter, issue.id, way);
208 if (!done.ok) return err(done.error === "edge" ? "at_edge" : done.error);
209 app.bus.append({ kind: "chapter.item_moved", repoId: repo.id, actorId: planned.value.actor.id, payload: { name, number, way } });
210 return ok({ says: `Moved ${placeWords(number, way, at)} in ${name}.` });
211 }
212
174213 /** What closing would do, found by the checks `close` makes before it writes anything. */
175214 interface ClosePlan {
176215 readonly actor: User;
@@ -391,6 +430,7 @@ export const CHAPTER_WORDS: Readonly<Record<ChapterActError, string>> = {
391430 too_late: "The minute to take the close back has passed.",
392431 moved: "That close moved items to the next chapter, so it cannot be taken back.",
393432 unproven: "v1.0.0 closes only when the proof passes on production, every probe.",
433 at_edge: "It is already at that end of the list.",
394434 another_open: "Another chapter has been opened since, so this close cannot be taken back.",
395435 };
396436
src/core/chapters.ts +36 −5
@@ -193,8 +193,9 @@ export function putIssue(db: Database, chapter: Chapter, issueId: string, byId:
193193 const from = chapterOfIssue(db, issueId);
194194 if (from?.state === "closed") return err("closed");
195195 db.query(
196 `INSERT INTO chapter_item (issue_id, chapter_id, by_id) VALUES (?1, ?2, ?3)
197 ON CONFLICT(issue_id) DO UPDATE SET chapter_id = ?2, by_id = ?3, at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
196 `INSERT INTO chapter_item (issue_id, chapter_id, by_id, place)
197 VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(place), 0) + 1 FROM chapter_item WHERE chapter_id = ?2))
198 ON CONFLICT(issue_id) DO UPDATE SET chapter_id = ?2, by_id = ?3, place = excluded.place, at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
198199 ).run(issueId, chapter.id, byId ?? null);
199200 return ok(undefined);
200201 }
@@ -204,6 +205,37 @@ export function takeIssueOut(db: Database, chapter: Chapter, issueId: string): b
204205 return db.query("DELETE FROM chapter_item WHERE issue_id = ?1 AND chapter_id = ?2").run(issueId, chapter.id).changes > 0;
205206 }
206207
208 export type Way = "up" | "down";
209
210 /** A chapter's items as ids, in the order the owner set (the place, then the issue number). */
211 function orderOf(db: Database, chapterId: string): string[] {
212 return db
213 .query<{ issue_id: string }, [string]>("SELECT c.issue_id FROM chapter_item c JOIN issue i ON i.id = c.issue_id WHERE c.chapter_id = ?1 ORDER BY c.place, i.number")
214 .all(chapterId)
215 .map((r) => r.issue_id);
216 }
217
218 /**
219 * Move an item one place up or down its chapter's list: the places are rewritten 1..n so a list
220 * that never moved (all zero, so by number) takes its first order from what it showed. The first
221 * cannot go up nor the last down (`edge`). A closed chapter holds its list.
222 */
223 export function moveItem(db: Database, chapter: Chapter, issueId: string, way: Way): Result<void, "closed" | "not_found" | "edge"> {
224 if (chapter.state === "closed") return err("closed");
225 const order = orderOf(db, chapter.id);
226 const at = order.indexOf(issueId);
227 if (at < 0) return err("not_found");
228 const to = way === "up" ? at - 1 : at + 1;
229 if (to < 0 || to >= order.length) return err("edge");
230 [order[at], order[to]] = [order[to]!, order[at]!];
231 db.transaction(() => {
232 const set = db.query("UPDATE chapter_item SET place = ?1 WHERE issue_id = ?2");
233 order.forEach((id, k) => set.run(k + 1, id));
234 })();
235 forgetFrozenItems();
236 return ok(undefined);
237 }
238
207239 export type ItemStatus = "done" | "building" | "left";
208240
209241 export interface Item {
@@ -352,12 +384,11 @@ export function itemsOf(db: Database, chapter: Chapter, view: ItemView): Item[]
352384 const rows = db
353385 .query<Omit<ItemRow, "sealed"> & { sealed: number }, [string]>(
354386 `SELECT i.id, i.number, i.title, i.state, i.sealed, i.author_id AS authorId FROM chapter_item c
355 JOIN issue i ON i.id = c.issue_id WHERE c.chapter_id = ?1`,
387 JOIN issue i ON i.id = c.issue_id WHERE c.chapter_id = ?1 ORDER BY c.place, i.number`,
356388 )
357389 .all(chapter.id)
358390 .map((r): ItemRow => ({ ...r, sealed: r.sealed === 1 }))
359 .filter((r) => shows(view, r))
360 .sort((a, b) => a.number - b.number);
391 .filter((r) => shows(view, r));
361392 const out: Item[] = [];
362393 if (rows.length > 0) {
363394 const facts = pullFacts(db, chapter.repoId, view);
src/core/event_audience.ts +1
@@ -221,6 +221,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
221221 "chapter.opened",
222222 "chapter.item_added",
223223 "chapter.item_removed",
224 "chapter.item_moved",
224225 "chapter.closed",
225226 "chapter.reopened",
226227 ]);
src/core/migration-pins/20261123090000-chapter-item-place.pin added +1
@@ -0,0 +1,1 @@
1 6b4ae503b102925a497465909608a91beb329a84d49d2277d63f105d18b71da5
src/core/migrations/20261123090000-chapter-item-place.ts added +5
@@ -0,0 +1,5 @@
1 // The owner's order inside a chapter (#15761): a place beside each item. Zero means never moved,
2 // and such items keep their issue-number order; a move rewrites the chapter's places 1..n.
3 export default `
4 ALTER TABLE chapter_item ADD COLUMN place INTEGER NOT NULL DEFAULT 0;
5 `;
src/http/mcp/tools/repo.ts +15 −6
@@ -5,7 +5,7 @@ import { repoFor } from "../../../core/repo_fields.ts";
55 import { upstreamCounts } from "../../../actions/upstream_counts.ts";
66 import { upstreamFacts } from "../../../actions/upstream_follow.ts";
77 import { creditFacts } from "../../../actions/credit_facts.ts";
8 import { type ChapterActError, close, closeSummary, fill, open, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
8 import { type ChapterActError, close, closeSummary, fill, move, open, previewMove, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
99 import { summaryWords } from "../../../core/chapter_notes.ts";
1010 import { costSentence, EVERY_ITEM, flowOf, flowSentence, getChapter, itemsOf, spentOf, listChapters, progressOf, progressSentence } from "../../../core/chapters.ts";
1111 import { err } from "../../../kernel/result.ts";
@@ -14,12 +14,12 @@ import { good, str, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../share
1414
1515 export const tool: Tool = {
1616 name: "repo",
17 doc: "`{ repo }`: one repository's description, visibility, autonomy (to a writer), `audience { level, who, sentence, appLine }` and `provenance` (where a migrated one came from, `null` when hidden), `credit` (a mirror's upstream, licence, authors; `null` otherwise), the same as `GET /api/v1/repos/:owner/:name`; `action` (`open|add|remove|close` with `chapter`, `number` for add/remove; a person who administers it, `rw` token) says what it would do, and with `confirm: true` does it, as the page; `view: \"chapters\"` lists its chapters with state, and with `chapter` names one's items (`done|building|left`) and `progress` (the page's sentence)",
17 doc: "`{ repo }`: one repository's description, visibility, autonomy (to a writer), `audience { level, who, sentence, appLine }` and `provenance` (where a migrated one came from, `null` when hidden), `credit` (a mirror's upstream, licence, authors; `null` otherwise), the same as `GET /api/v1/repos/:owner/:name`; `action` (`open|add|remove|move|close` with `chapter`, `number` for add/remove/move, `direction: up|down` for move; a person who administers it, `rw` token) says what it would do, and with `confirm: true` does it, as the page; `view: \"chapters\"` lists its chapters with state, and with `chapter` names one's items (`done|building|left`) and `progress` (the page's sentence)",
1818 description:
1919 "One repository you can read, as GET /api/v1/repos/:owner/:name.",
2020 inputSchema: {
2121 type: "object",
22 properties: { repo: REPO_ARG, view: { type: "string", enum: ["chapters"] }, chapter: { type: "string" }, action: { type: "string", enum: ["open", "add", "remove", "close"] }, number: { type: "integer" }, confirm: { type: "boolean" } },
22 properties: { repo: REPO_ARG, view: { type: "string", enum: ["chapters"] }, chapter: { type: "string" }, action: { type: "string", enum: ["open", "add", "remove", "move", "close"] }, direction: { type: "string", enum: ["up", "down"] }, number: { type: "integer" }, confirm: { type: "boolean" } },
2323 required: ["repo"],
2424 },
2525 writes: true,
@@ -30,14 +30,23 @@ export const tool: Tool = {
3030 if (isAnswer(repo)) return repo;
3131 if (args["action"] !== undefined) {
3232 const verb = args["action"];
33 if (verb !== "open" && verb !== "add" && verb !== "remove" && verb !== "close") return bad("invalid", "`action` is open, add, remove or close");
33 if (verb !== "open" && verb !== "add" && verb !== "remove" && verb !== "move" && verb !== "close") return bad("invalid", "`action` is open, add, remove, move or close");
3434 const name = str(args["chapter"]);
3535 if (name === "") return bad("invalid", "`action` needs `chapter`");
3636 const number = args["number"];
37 if ((verb === "add" || verb === "remove") && (typeof number !== "number" || !Number.isInteger(number) || number < 1))
38 return bad("invalid", "`add` and `remove` need an issue `number`");
37 if ((verb === "add" || verb === "remove" || verb === "move") && (typeof number !== "number" || !Number.isInteger(number) || number < 1))
38 return bad("invalid", "`add`, `remove` and `move` need an issue `number`");
39 const way = args["direction"];
3940 const n = typeof number === "number" ? number : undefined;
4041 const refused = (r: Refused) => bad(r.error, refusalWords(ctx.app, getChapter(ctx.app.db, repo.id, name), r));
42 if (verb === "move") {
43 if (n === undefined) return bad("invalid", "`move` needs an issue `number`");
44 if (way !== "up" && way !== "down") return bad("invalid", "`move` needs `direction`: up or down");
45 const doing = args["confirm"] === true;
46 const m = doing ? move(ctx.app, user, repo, name, n, way) : previewMove(ctx.app, user, repo, name, n, way);
47 if (!m.ok) return refused(m);
48 return doing ? good({ done: true, chapter: name, action: verb, number: n, direction: way, says: m.value.says }) : good({ ...m.value, done: false, says: `${m.value.says} Send confirm: true to do it.` });
49 }
4150 if (args["confirm"] !== true) {
4251 const seen = await preview(ctx.app, user, repo, verb, name, n);
4352 return seen.ok ? good({ ...seen.value, done: false, says: `${seen.value.says} Send confirm: true to do it.` }) : refused(seen);
src/tui/screens/chapters.ts +15 −4
@@ -5,12 +5,13 @@
55 * patches. `n` drafts, `c` closes the one under the cursor when nothing is in its way and `u` takes
66 * a close back within a minute (#12288), `o` opens the one under the cursor, `s` ships it, `p`
77 * opens a patch chapter for a closed one, `enter` shows its list, where `a` adds an issue by number
8 * and `x` takes the one under the cursor out. Each act is an event on the bus, so an open web page
9 * sees it, and this screen follows a change made there.
8 * `u` and `d` move the one under the cursor up or down the list (the page's Up and Down), and `x`
9 * takes it out. Each act is an event on the bus, so an open web page sees it, and this screen
10 * follows a change made there.
1011 */
1112
1213 import { summaryWords } from "../../core/chapter_notes.ts";
13 import { CHAPTER_WORDS, close, closeSummary, draft, fill, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
14 import { CHAPTER_WORDS, close, closeSummary, draft, fill, move, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
1415 import { barCount, barNext, barOf, costSentence, getChapter, nextChapterOf, nextWords, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1516 import { canAdmin, type Repo } from "../../core/repos.ts";
1617 import { sealedScope } from "../../core/sealed.ts";
@@ -75,7 +76,7 @@ export function chapterScreen(f: Session, ctx: Ctx, repo: Repo, name: string): S
7576 };
7677 const screen: Screen = {
7778 title: `${repo.ownerName}/${repo.name} — ${name}`,
78 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "add an issue"), binding(["x"], "take it out"), binding(["o"], "open"), binding(["s"], "ship")],
79 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "add an issue"), binding(["u", "d"], "move it up, down"), binding(["x"], "take it out"), binding(["o"], "open"), binding(["s"], "ship")],
7980 async load(signal) {
8081 refresh();
8182 live(f, signal, { repoId: repo.id, where: (e) => isChapterEvent(e.kind) }, () => {
@@ -125,6 +126,16 @@ export function chapterScreen(f: Session, ctx: Ctx, repo: Repo, name: string): S
125126 );
126127 return true;
127128 }
129 if (e.key === "u" || e.key === "d") {
130 const at = all[state.index];
131 if (at === undefined) return true;
132 const way = e.key === "u" ? "up" : "down";
133 const done = move(f.app, f.user, repo, name, at.number, way);
134 if (done.ok) state.index += way === "up" ? -1 : 1;
135 ctx.toast(done.ok ? done.value.says : refusalWords(f.app, getChapter(f.app.db, repo.id, name), done), done.ok ? undefined : "danger");
136 ctx.invalidate();
137 return true;
138 }
128139 if (e.key === "x") {
129140 const at = all[state.index];
130141 if (at === undefined) return true;
src/web/pages/chapters.ts +17 −9
@@ -6,7 +6,7 @@
66 * change is a same-origin POST by a person who administers the repository.
77 */
88
9 import { CHAPTER_WORDS, close, closeSummary, draft, fill, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
9 import { CHAPTER_WORDS, close, closeSummary, draft, fill, move, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
1010 import { nextLead } from "../../core/chapter_notes.ts";
1111 import { costSentence, flowOf, flowSentence, nextParts, openChapterOf, getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1212 import { canAdmin, type Repo } from "../../core/repos.ts";
@@ -29,7 +29,7 @@ const hrefOf = (repo: Repo, c: Chapter): string => `${repoBase(repo)}/chapters/$
2929
3030 const STATE_WORDS = { open: "open", draft: "waiting its turn", closed: "closed" } as const;
3131
32 function itemRow(repo: Repo, i: Item, may: boolean, chapter: Chapter): Html {
32 function itemRow(repo: Repo, i: Item, may: boolean, chapter: Chapter, at: number, of: number): Html {
3333 const title = html`<a href="${repoBase(repo)}/issues/${i.number}">#${i.number}</a> ${i.status === "done" ? html`<s>${i.title}</s>` : i.title}`;
3434 const trail =
3535 i.status === "done"
@@ -41,7 +41,13 @@ function itemRow(repo: Repo, i: Item, may: boolean, chapter: Chapter): Html {
4141 may && chapter.state !== "closed"
4242 ? html`<form method="post" action="${hrefOf(repo, chapter)}/remove"><input type="hidden" name="number" value="${String(i.number)}">${btn("Take out", { variant: "ghost" })}</form>`
4343 : null;
44 return html`<li data-item="${String(i.number)}" data-status="${i.status}">${row({ title, trail })}${out}</li>`;
44 const hidden = html`<input type="hidden" name="number" value="${String(i.number)}">`;
45 const editing = may && chapter.state !== "closed";
46 const way = (verb: "up" | "down", label: string): Html =>
47 html`<form method="post" action="${hrefOf(repo, chapter)}/${verb}">${hidden}${btn(label, { variant: "ghost" })}</form>`;
outdated

Principles 3 and 6: Up and Down are shown on every row, including the first (no Up) and the last (no Down). Drop the buttons that cannot act. Also add a test that posts these forms as the owner.

48 const up = editing && at > 0 ? way("up", "Up") : null;
49 const down = editing && at < of - 1 ? way("down", "Down") : null;
50 return html`<li data-item="${String(i.number)}" data-status="${i.status}">${row({ title, trail })}${up}${down}${out}</li>`;
4551 }
4652
4753 // GET /:owner/:name/chapters
@@ -131,14 +137,11 @@ export function chapterPage(ctx: Ctx): Response {
131137 let main: Html;
132138 if (c.state === "closed") main = finished(ctx, repo, c, items, may, nextChapterOf(ctx.app.db, repo.id));
133139 else {
134 const building = items.filter((i) => i.status === "building");
135 const left = items.filter((i) => i.status === "left");
136 const done = items.filter((i) => i.status === "done");
137140 main = html`<p>${c.means}</p>
138141 <p data-progress>${progressSentence(p)}${c.state === "open" ? html` <span data-chapter-flow>${flowSentence(flowOf(ctx.app.db, c, items, new Date()))}.</span>` : null}</p>
139142 <p data-cost>${costSentence(items)}</p>
140 ${items.length === 0 ? html`<p>No issues in this chapter yet.</p>` : null}
141 <ul class="list setting-list">${[...done, ...building, ...left].map((i) => itemRow(repo, i, may, c))}</ul>
143 ${items.length === 0 ? html`<p>No issues in this chapter yet.</p>` : html`<p data-order>In the owner's order, first to last${may ? "; Up and Down change it" : ""}.</p>`}
144 <ul class="list setting-list">${items.map((i, at) => itemRow(repo, i, may, c, at, items.length))}</ul>
142145 ${may
143146 ? html`<form method="post" action="${here}/add" class="bar">
144147 <input class="input" name="number" inputmode="numeric" pattern="[0-9]+" placeholder="Issue number" aria-label="Issue number" required>
@@ -179,6 +182,11 @@ export async function chapterAct(ctx: Ctx): Promise<Response> {
179182 const at = backTo(form, `${list}/${encodeURIComponent(name)}`);
180183 const verb = ctx.params.verb ?? "";
181184 const number = Number(field(form, "number"));
185 if (verb === "up" || verb === "down") {
186 const moved = move(app, user, repo, name, number, verb);
187 if (!moved.ok) return flashTo(ctx, at, { tone: "danger", message: refusalWords(app, getChapter(app.db, repo.id, name), moved) });
188 return flashTo(ctx, at, { message: moved.value.says });
189 }
182190 const result =
183191 verb === "open" ? open(app, user, repo, name)
184192 : verb === "add" || verb === "remove" ? fill(app, user, repo, name, number, verb === "add")
@@ -193,7 +201,7 @@ export async function chapterAct(ctx: Ctx): Promise<Response> {
193201 const why = refusalWords(app, chapter, result);
194202 return flashTo(ctx, at, { tone: "danger", message: why });
195203 }
196 const landed = verb === "patch" && result.value !== undefined ? `${list}/${encodeURIComponent(result.value.name)}` : at;
204 const landed = verb === "patch" && result.value !== undefined && "name" in result.value ? `${list}/${encodeURIComponent(result.value.name)}` : at;
197205 const said = verb === "ship" ? `${name} is shipped.` : verb === "close" ? `${name} is closed and tagged.` : verb === "undo" ? `${name} is open again.` : "Done.";
198206 return flashTo(ctx, landed, { message: said });
199207 }
test/chapters-order.test.ts added +186
@@ -0,0 +1,186 @@
1 /** The owner moves an issue up or down inside a chapter (#15761): core, action, page and MCP. */
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 { createRepo } from "../src/actions/repos.ts";
7 import { draft, fill, move, open, previewMove } from "../src/actions/chapters.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { EVERY_ITEM, getChapter, itemsOf } from "../src/core/chapters.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15
16 let dataDir: string;
17 let app: App;
18 let servers: Servers;
19 let alice: any;
20 let bob: any;
21 let token: string;
22 let nums: number[] = [];
23 let n = 1;
24 const repo = () => getRepo(app.db, "alice", "pub")!;
25 const order = () => itemsOf(app.db, getChapter(app.db, repo().id, "v1")!, EVERY_ITEM).map((i) => i.number);
26
27 const call = async (args: unknown) => {
28 const res = await fetch(`${servers.url}/mcp`, {
29 method: "POST",
30 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
31 body: JSON.stringify({ jsonrpc: "2.0", id: n++, method: "tools/call", params: { name: "repo", arguments: args } }),
32 });
33 const body: any = await res.json();
34 const text: string = body.result.content[0].text;
35 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
36 };
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-order-"));
40 app = createApp({ dataDir, port: 0 });
41 servers = await serve(app);
42 const mk = async (username: string, first = false) => {
43 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
44 if (!u.ok) throw new Error(u.error);
45 return u.value;
46 };
47 alice = await mk("alice", true);
48 bob = await mk("bob");
49 token = createToken(app.db, alice.id, "a", "admin").token;
50 const made = await createRepo(app, alice, { name: "pub", visibility: "public" });
51 if (!made.ok) throw new Error(String(made.error));
52 for (const t of ["one", "two", "three"]) {
53 const i = createIssue(app.db, { repoId: repo().id, authorId: alice.id, title: t, body: "" });
54 if (!i.ok) throw new Error("issue");
55 nums.push(i.value.number);
56 }
57 expect(draft(app, alice, repo(), { name: "v1" }).ok).toBe(true);
58 for (const k of [2, 0, 1]) expect(fill(app, alice, repo(), "v1", nums[k]!, true).ok).toBe(true);
59 expect(open(app, alice, repo(), "v1").ok).toBe(true);
60 }, 30_000);
61
62 afterAll(async () => {
63 servers.stop();
64 app.close();
65 await rm(dataDir, { recursive: true, force: true });
66 });
67
68 test("items keep the order they were added in; a move changes it and the opposite move undoes it", () => {
69 const [a, b, c] = nums as [number, number, number];
70 expect(order()).toEqual([c, a, b]);
71 expect(move(app, alice, repo(), "v1", b, "up").ok).toBe(true);
72 expect(order()).toEqual([c, b, a]);
73 expect(move(app, alice, repo(), "v1", b, "down").ok).toBe(true);
74 expect(order()).toEqual([c, a, b]);
75 });
76
77 test("the first cannot go up, the last cannot go down", () => {
78 const first = order()[0]!;
79 const last = order()[2]!;
80 const before = order();
81 const up = move(app, alice, repo(), "v1", first, "up");
82 expect(up.ok ? "" : up.error).toBe("at_edge");
83 const down = move(app, alice, repo(), "v1", last, "down");
84 expect(down.ok ? "" : down.error).toBe("at_edge");
85 expect(order()).toEqual(before);
86 });
87
88 test("a person who does not administer the repository is refused, and nothing moves", () => {
89 const before = order();
90 const r = move(app, bob, repo(), "v1", before[1]!, "up");
91 expect(r.ok ? "" : r.error).toBe("forbidden");
92 expect(order()).toEqual(before);
93 });
94
95 test("a preview changes nothing", () => {
96 const before = order();
97 const p = previewMove(app, alice, repo(), "v1", before[1]!, "up");
98 expect(p.ok && p.value.says).toContain("Would move");
99 expect(order()).toEqual(before);
100 });
101
102 test("the MCP chapters tool moves with the same words, previewed unless confirmed", async () => {
103 const before = order();
104 const seen = await call({ repo: "alice/pub", action: "move", chapter: "v1", number: before[1], direction: "up" });
105 expect(seen.value.done).toBe(false);
106 expect(order()).toEqual(before);
107 const done = await call({ repo: "alice/pub", action: "move", chapter: "v1", number: before[1], direction: "up", confirm: true });
108 expect(done.value.done).toBe(true);
109 expect(order()).toEqual([before[1]!, before[0]!, before[2]!]);
110 const bad = await call({ repo: "alice/pub", action: "move", chapter: "v1", number: before[1], direction: "sideways" });
111 expect(bad.error).toContain("direction");
112 const edge = await call({ repo: "alice/pub", action: "move", chapter: "v1", number: before[1], direction: "up", confirm: true });
113 expect(edge.error).toContain("already at that end");
114 });
115
116 const form = (path: string, number: number, opts: { origin?: string; as?: string | null } = {}) =>
117 fetch(`${servers.url}${path}`, {
118 method: "POST",
119 redirect: "manual",
120 headers: {
121 "content-type": "application/x-www-form-urlencoded",
122 origin: opts.origin ?? servers.url,
123 ...(opts.as === null ? {} : { authorization: `Bearer ${opts.as ?? token}` }),
124 },
125 body: `number=${number}&back=%2Falice%2Fpub%2Fchapters%2Fv1`,
126 });
127 const flashOf = (res: Response) => decodeURIComponent(res.headers.getSetCookie().join(";")).replace(/\+/g, " ");
128
129 test("the page lists in that order; the owner sees Up except on the first and Down except on the last", async () => {
130 const res = await fetch(`${servers.url}/alice/pub/chapters/v1`, { headers: { authorization: `Bearer ${token}` } });
131 const text = await res.text();
132 const o = order();
133 const at = o.map((x) => text.indexOf(`data-item="${x}"`));
134 expect(at.every((x) => x > 0)).toBe(true);
135 expect([...at].sort((p, q) => p - q)).toEqual(at);
136 expect(text).toContain("data-order");
137 const li = (x: number) => {
138 const from = text.indexOf(`data-item="${x}"`);
139 const next = text.indexOf("data-item=", from + 1);
140 return text.slice(from, next < 0 ? undefined : next);
141 };
142 expect(li(o[0]!)).not.toContain("/chapters/v1/up");
143 expect(li(o[0]!)).toContain("/chapters/v1/down");
144 expect(li(o[1]!)).toContain("/chapters/v1/up");
145 expect(li(o[1]!)).toContain("/chapters/v1/down");
146 expect(li(o[2]!)).toContain("/chapters/v1/up");
147 expect(li(o[2]!)).not.toContain("/chapters/v1/down");
148 });
149
150 test("an anonymous visitor sees no move forms", async () => {
151 const text = await (await fetch(`${servers.url}/alice/pub/chapters/v1`)).text();
152 expect(text).not.toContain("/chapters/v1/up");
153 expect(text).not.toContain("/chapters/v1/down");
154 });
155
156 test("the owner posts Up and Down from the same origin: the order changes, with the words and the redirect", async () => {
157 const before = order();
158 const up = await form("/alice/pub/chapters/v1/up", before[1]!);
159 expect(up.status).toBe(303);
160 expect(up.headers.get("location")).toBe("/alice/pub/chapters/v1");
161 expect(flashOf(up)).toContain(`Moved #${before[1]} from place 2 to 1 in v1.`);
162 expect(order()).toEqual([before[1]!, before[0]!, before[2]!]);
163 const down = await form("/alice/pub/chapters/v1/down", before[1]!);
164 expect(flashOf(down)).toContain(`Moved #${before[1]} from place 1 to 2 in v1.`);
165 expect(order()).toEqual(before);
166 });
167
168 test("the page refuses an edge move with words and moves nothing", async () => {
169 const before = order();
170 const res = await form("/alice/pub/chapters/v1/up", before[0]!);
171 expect(res.status).toBe(303);
172 expect(flashOf(res)).toContain("already at that end");
173 expect(order()).toEqual(before);
174 });
175
176 test("a cross-origin post, an anonymous one and a non-owner's move nothing", async () => {
177 const before = order();
178 const cross = await form("/alice/pub/chapters/v1/up", before[1]!, { origin: "https://evil.example" });
179 expect(cross.status).toBe(403);
180 const anon = await form("/alice/pub/chapters/v1/up", before[1]!, { as: null });
181 expect(anon.status).not.toBe(200);
182 const other = createToken(app.db, bob.id, "b", "rw").token;
183 const notOwner = await form("/alice/pub/chapters/v1/up", before[1]!, { as: other });
184 expect(flashOf(notOwner)).not.toContain("Moved");
185 expect(order()).toEqual(before);
186 });
test/tui-chapter-move.test.ts added +83
@@ -0,0 +1,83 @@
1 /** The terminal moves an issue up or down a chapter with `u` and `d`, as the page does (#15761). */
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 { createRepo } from "../src/actions/repos.ts";
7 import { draft, fill, open } from "../src/actions/chapters.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { EVERY_ITEM, getChapter, itemsOf } from "../src/core/chapters.ts";
11 import { getRepo, type Repo } from "../src/core/repos.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import type { Ctx } from "../src/tui/app/app.ts";
14 import { chapterScreen } from "../src/tui/screens/chapters.ts";
15 import type { Session } from "../src/tui/session.ts";
16 import { theme } from "../src/tui/ui/theme.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dir: string;
22 let app: App;
23 let alice: User;
24 let bob: User;
25 let repo: Repo;
26 const nums: number[] = [];
27 const order = () => itemsOf(app.db, getChapter(app.db, repo.id, "v1")!, EVERY_ITEM).map((i) => i.number);
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-tui-move-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 const mk = async (username: string, first = false) => {
33 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.dev`, password: "a-good-passphrase", adminIfFirst: first });
34 if (!u.ok) throw new Error(u.error);
35 return u.value;
36 };
37 alice = await mk("alice", true);
38 bob = await mk("bob");
39 const made = await createRepo(app, alice, { name: "pub", visibility: "public" });
40 if (!made.ok) throw new Error("repo");
41 repo = getRepo(app.db, "alice", "pub")!;
42 for (const t of ["one", "two", "three"]) {
43 const i = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: t, body: "" });
44 if (!i.ok) throw new Error("issue");
45 nums.push(i.value.number);
46 }
47 draft(app, alice, repo, { name: "v1" });
48 for (const n of nums) fill(app, alice, repo, "v1", n, true);
49 open(app, alice, repo, "v1");
50 }, 30_000);
51
52 afterAll(async () => {
53 app.close();
54 await rm(dir, { recursive: true, force: true });
55 });
56
57 function screenFor(user: User) {
58 const toasts: string[] = [];
59 const ctx = { theme: theme("dark"), invalidate() {}, toast: (t: string) => toasts.push(t), push() {}, pop() {}, copy() {}, hit() {}, setCursor() {} } as unknown as Ctx;
60 const screen = chapterScreen({ app, db: app.db, user } as unknown as Session, ctx, repo, "v1");
61 return { toasts, press: (k: string) => screen.key!({ type: "key", key: k, ctrl: false, alt: false, shift: false }), keys: screen.keys };
62 }
63
64 test("d moves the row under the cursor down, the cursor follows, u brings it back", () => {
65 const [a, b, c] = nums as [number, number, number];
66 const t = screenFor(alice);
67 expect(t.keys.some((k) => k.keys.includes("u") && k.keys.includes("d"))).toBe(true);
68 t.press("d");
69 expect(order()).toEqual([b, a, c]);
70 expect(t.toasts.at(-1)).toContain("Moved");
71 t.press("u");
72 expect(order()).toEqual([a, b, c]);
73 });
74
75 test("the first cannot go up, and a person who does not administer the repository moves nothing", () => {
76 const t = screenFor(alice);
77 t.press("u");
78 expect(t.toasts.at(-1)).toContain("already at that end");
79 const other = screenFor(bob);
80 other.press("d");
81 expect(other.toasts.at(-1)).not.toContain("Moved");
82 expect(order()).toEqual(nums);
83 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs