- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/issues.ts?draft=login-timeout&format=json
782 linesFirst import 50% · pinch 39% · devops 4% · review 4% · infra-split 2%0 versions changed it
1// Issues (#54): abso issues, abso issue, abso ask, abso waiting and avcs
2// answer. The Issues Worker keeps them (avcs-issues beside avcs, or
3// ABSO_ISSUES_SERVER), and takes the same token. Statuses come from the work: a start note naming
4// an issue (abso start --issue N) puts it In progress, an open ask Blocked or
5// In review, and publish --done closes it. Other agents' and people's words
6// are quoted as JSON, so none can print as another line (#30).
8import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
9import { basename, join, resolve } from "node:path";
10import {
11 type Api,
12 ApiError,
13 type Ask,
14 type Attachment,
15 type CopyAnswer,
16 type CopyBody,
17 type Draft,
18 type DraftBody,
19 type IssuePage,
20 type IssueRow,
21 type IssueSearchHit,
22} from "./api.ts";
23import { bool, type Parsed, str, UsageError } from "./args.ts";
24import { type Env, type Output, open, plural } from "./commands.ts";
25import { type Config, readMachineServers, trustedServers } from "./config.ts";
26import { issuesServerFor, tokenGoesTo } from "./core.ts";
27import { fromEnv } from "./env-names.ts";
28import { ignoredHere } from "./fetch.ts";
29import { loadIgnore, relativeTo } from "./folder.ts";
30import { queuedLines, standing } from "./queue.ts";
31import { seenText, shortWhen } from "./times.ts";
33const q = (s: string): string => JSON.stringify(s);
35/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */
36function openIssues(env: Env): { root: string; config: Config; api: Api } {
37 const { root, config, api } = open(env);
38 const server = fromEnv(env.env, "ISSUES_SERVER") || issuesServerFor(config.server, readMachineServers(env.env));
39 if (server === undefined)
40 throw new UsageError(
41 `${config.server} has no Issues Worker beside it that abso knows; ~/.abso/servers.json or ABSO_ISSUES_SERVER names one`,
42 );
43 if (config.token !== undefined && !tokenGoesTo(server, trustedServers(env.env))) {
44 throw new UsageError(
45 `the Issues Worker is ${server}, and abso sends your token only to its own servers and this machine. If ${server} is yours, name it in ~/.abso/servers.json or ABSO_TRUSTED_SERVERS.`,
46 );
47 }
48 api.issuesServer = server;
49 return { root, config, api };
50}
52function issueNumber(word: string | undefined, what = "an issue number"): number {
53 if (word === undefined || !/^#?\d+$/.test(word)) throw new UsageError(`${what} is a number, like 12`);
54 return Number(word.replace("#", ""));
55}
57/** One issue as a line. */
58export function issueLine(i: IssueRow): string {
59 const detail = [
60 i.agent !== null && !i.agents.includes(i.agent) ? `for ${i.agent}` : "",
61 i.agents.length > 0 ? i.agents.join(", ") : "",
62 i.blockedBy.length > 0 ? `blocked by ${i.blockedBy.join(", ")}` : "",
63 (i.labels ?? []).length > 0 ? `labels ${i.labels.join(", ")}` : "",
64 i.versions.length > 0 ? `${i.versions.length === 1 ? "version" : "versions"} ${i.versions.join(", ")}` : "",
65 i.waitingOn.length > 0 ? `waiting on ${i.waitingOn.join(", ")}` : "",
66 i.parent !== null ? `under ${i.parent}` : "",
67 i.children > 0 ? plural(i.children, "sub-issue") : "",
68 `updated ${shortWhen(i.updated)}`,
69 ].filter((d) => d !== "");
70 return ` ${String(i.id).padStart(3)} ${i.status.padEnd(11)} ${q(i.title)}${detail.length > 0 ? ` (${detail.join("; ")})` : ""}`;
71}
73function askLine(a: Ask & { title?: string | null }, api?: Pick<Api, "attachmentUrl">): string {
74 const what = a.review ? "a review" : a.kind === "task" ? "a task" : "a question";
75 const where = a.issue === null ? "" : ` on issue ${a.issue}${a.title ? ` (${q(a.title)})` : ""}`;
76 const extra = [
77 // Who answered, and when, on the ask's own line, so a handled ask can't pass for an open one.
78 a.answer
79 ? `${a.outcome === "withdrawn" ? "withdrawn" : "answered"} by ${a.answer.by}, ${shortWhen(a.answer.at)}`
80 : "",
81 !a.answer && a.ack ? `acknowledged ${shortWhen(a.ack.at)}, not answered yet` : "",
82 !a.answer && !a.ack && a.seen !== undefined ? seenText(a.seen) : "",
83 a.due ? `due ${a.due}` : "",
84 a.blocks.length > 0 ? `blocks ${a.blocks.join(", ")}` : "",
85 ].filter((x) => x !== "");
86 const head = ` ask ${a.id}: ${a.by}, ${shortWhen(a.at)}, asks ${a.of} ${what}${where}${extra.length > 0 ? ` (${extra.join("; ")})` : ""}: ${q(a.question)}`;
87 const lines = [head, ...attachmentLines(api, a.attachments, " ")];
88 if (a.options.length > 0) lines.push(` options: ${a.options.map((o, i) => `${i + 1}. ${q(o)}`).join(", ")}`);
89 if (a.recommendation) lines.push(` ${a.recommendation.by} recommends: ${q(a.recommendation.text)}`);
90 if (!a.answer && a.ack && a.ack.note !== "") lines.push(` ${a.of} acknowledged: ${q(a.ack.note)}`);
91 if (a.answer && a.outcome === "withdrawn") {
92 if (a.answer.words !== "") lines.push(` why: ${q(a.answer.words)}`);
93 } else if (a.answer)
94 lines.push(` answer: ${q(a.answer.words)}`, ...attachmentLines(api, a.answer.attachments, " "));
95 return lines.join("\n");
96}
98/** One edit in an issue's activity: what changed, and who was told. */
99function editLine(e: IssuePage["edits"][number]): string {
100 const c = e.changes;
101 const said = [
102 c.title ? `title ${q(String(c.title.from))} to ${q(String(c.title.to))}` : "",
103 c.description ? "the description" : "",
104 c.parent ? (c.parent.to === null ? "no parent" : `parent issue ${String(c.parent.to)}`) : "",
105 c.agent ? (c.agent.to === null ? "no Agent" : `Agent ${String(c.agent.to)}`) : "",
106 c.blockedBy
107 ? (c.blockedBy.to as number[]).length === 0
108 ? "blocked by nothing"
109 : `blocked by ${(c.blockedBy.to as number[]).join(", ")}`
110 : "",
111 c.labels
112 ? (c.labels.to as string[]).length === 0
113 ? "no labels"
114 : `labels ${(c.labels.to as string[]).join(", ")}`
115 : "",
116 ].filter((x) => x !== "");
117 return ` ${e.by}, ${shortWhen(e.at)}: ${said.join("; ")} (${e.notified.length > 0 ? `told ${e.notified.join(", ")}` : "told nobody"})`;
118}
120/** Labels as typed, lower-cased, since the Worker refuses upper case: --label Friction means friction. */
121function labelList(value: string): string[] {
122 return listOf(value).map((l) => l.toLowerCase());
123}
125/** A comma-separated list of names or issue numbers; "none" is the empty list. */
126function listOf(value: string): string[] {
127 return value.trim() === "none"
128 ? []
129 : value
130 .split(",")
131 .map((v) => v.trim())
132 .filter((v) => v !== "");
133}
135/** " with 2 attachments (a…, a…)" after a write that carried some; nothing otherwise. */
136function withFiles(ids: readonly string[]): string {
137 return ids.length > 0 ? ` with ${plural(ids.length, "attachment")} (${ids.join(", ")})` : "";
138}
140/**
141 * What to say when a write sent files the server didn't keep: an Issues server from before asks carried
142 * attachments takes the words and leaves the files out. Nothing to say when it kept them, or none were sent.
143 */
144function notKept(sent: readonly string[], kept: readonly string[] | undefined, what: string): string | undefined {
145 if (sent.length === 0 || (kept !== undefined && sent.every((id) => kept.includes(id)))) return undefined;
146 return `The Issues server didn't keep the ${sent.length === 1 ? "file" : "files"} on ${what}: it is older than this client. The words went; the ${sent.length === 1 ? "file goes" : "files go"} on a comment instead (abso issue <N> --comment "..." --attach ...).`;
147}
149/** The most one attachment may be: the Issues Worker's cap, checked here before sending (abso issue 171). */
150const ATTACH_MAX = 10 * 1024 * 1024;
152/** Uploads each file --attach names (comma-separated), in order, and answers their ids. Nothing is sent if a file is missing or too big. */
153async function uploadAttachments(api: Api, cwd: string, value: string | undefined): Promise<string[]> {
154 if (value === undefined) return [];
155 const paths = listOf(value);
156 if (paths.length === 0) throw new UsageError("--attach names files, comma-separated: --attach shot.png,after.png");
157 const files = paths.map((p) => {
158 const full = resolve(cwd, p);
159 let size: number;
160 try {
161 size = statSync(full).size;
162 } catch {
163 throw new UsageError(`--attach ${p}: no such file`);
164 }
165 if (size > ATTACH_MAX)
166 throw new UsageError(`--attach ${p} is ${sizeText(size)}; one attachment is at most ${sizeText(ATTACH_MAX)}`);
167 return { full, name: basename(full) };
168 });
169 const ids: string[] = [];
170 for (const f of files) ids.push((await api.attachmentUpload(readFileSync(f.full), f.name)).id);
171 return ids;
172}
174function sizeText(n: number): string {
175 return n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`;
176}
178/** Attachments as lines under what carries them: name, size and where it's served. */
179function attachmentLines(
180 api: Pick<Api, "attachmentUrl"> | undefined,
181 files: readonly Attachment[] | undefined,
182 indent: string,
183): string[] {
184 return (files ?? []).flatMap((a) => [
185 `${indent}attached ${a.id}: ${q(a.name)}, ${sizeText(a.size)}${api ? `, ${api.attachmentUrl(a.id)}` : ""}`,
186 // An SVG is shown as the PNG drawn from it; its own file is a download beside it.
187 ...(a.source
188 ? [
189 `${indent} drawn from ${q(a.source.name)}, ${sizeText(a.source.size)}${api ? `, ${api.attachmentUrl(a.id)}/source` : ""}`,
190 ]
191 : []),
192 ]);
193}
195/** A saved attachment's file name: its id, then its own name with anything but letters, digits, . - _ made _. */
196export function savedName(id: string, name: string): string {
197 const own = (name.split(/[\\/]/).pop() ?? "")
198 .replace(/[^A-Za-z0-9._-]/g, "_")
199 .replace(/^\.+/, "_")
200 .slice(0, 100);
201 return `${id}-${own || "file"}`;
202}
204/**
205 * abso issue N --save-attachments <folder>: every attachment on the issue, its
206 * comments and its asks and answers, written to that folder as <id>-<name>; an svg's own file
207 * beside the png drawn from it. Not into the abso folder unless abso leaves
208 * that place out, or the images would be recorded as edits.
209 */
210async function saveAttachments(api: Api, root: string, cwd: string, dir: string, page: IssuePage): Promise<Output> {
211 const target = resolve(cwd, dir);
212 const inside = target === resolve(root) ? "" : relativeTo(root, target);
213 if (inside !== undefined && (inside === "" || !ignoredHere(loadIgnore(root), inside, true)))
214 throw new UsageError(
215 `${dir} is inside this abso folder, so abso would record the images as your edits. Save them outside the folder, or into a folder .absoignore leaves out`,
216 );
217 const seen = new Set<string>();
218 const all = [
219 ...(page.issue.attachments ?? []),
220 ...page.comments.flatMap((c) => c.attachments ?? []),
221 ...page.asks.flatMap((a) => [...(a.attachments ?? []), ...(a.answer?.attachments ?? [])]),
222 ].filter((a) => !seen.has(a.id) && seen.add(a.id));
223 if (all.length === 0)
224 return {
225 text: `Issue ${page.issue.id} has no attachments.`,
226 json: { issue: page.issue.id, folder: target, files: [] },
227 };
228 mkdirSync(target, { recursive: true });
229 const files: { id: string; path: string; size: number }[] = [];
230 for (const a of all) {
231 const wanted = [{ name: a.name, source: false }, ...(a.source ? [{ name: a.source.name, source: true }] : [])];
232 for (const w of wanted) {
233 const bytes = await api.attachmentBytes(a.id, w.source, ATTACH_MAX);
234 const path = join(target, savedName(a.id, w.name));
235 writeFileSync(path, bytes);
236 files.push({ id: a.id, path, size: bytes.length });
237 }
238 }
239 return {
240 text: [
241 `Saved ${plural(files.length, "file")} from issue ${page.issue.id} to ${target}:`,
242 ...files.map((f) => ` ${basename(f.path)}, ${sizeText(f.size)}`),
243 ].join("\n"),
244 json: { issue: page.issue.id, folder: target, files },
245 };
246}
248/** An issue's page, as text. */
249export function issuePage(p: IssuePage, api?: Pick<Api, "attachmentUrl">): string[] {
250 const i = p.issue;
251 const facts = [
252 i.parent !== null ? `Under issue ${i.parent}.` : "",
253 `Opened by ${i.opened.by}, ${shortWhen(i.opened.at)}.`,
254 i.agent !== null ? `Agent: ${i.agent}.` : "",
255 i.agents.length > 0 ? `Working on it: ${i.agents.join(", ")}.` : "",
256 i.blockedBy.length > 0 ? `Blocked by: issue${i.blockedBy.length === 1 ? "" : "s"} ${i.blockedBy.join(", ")}.` : "",
257 (i.labels ?? []).length > 0 ? `Labels: ${i.labels.join(", ")}.` : "",
258 i.versions.length > 0 ? `Versions: ${i.versions.join(", ")}.` : "",
259 i.waitingOn.length > 0 ? `Waiting on: ${i.waitingOn.join(", ")}.` : "",
260 i.closed
261 ? `${i.closed.how === "done" ? "Done" : "Dropped"} by ${i.closed.by}${i.closed.version !== null ? ` in version ${i.closed.version}` : ""}, ${shortWhen(i.closed.at)}.`
262 : "",
263 ].filter((f) => f !== "");
264 // The links below open for people signed in on the website; an agent's fetch of one is refused. Say the way in
265 // before the first link, so an agent reads the files instead of hunting for them.
266 const files =
267 (i.attachments ?? []).length +
268 p.comments.reduce((n, c) => n + (c.attachments ?? []).length, 0) +
269 p.asks.reduce((n, a) => n + (a.attachments ?? []).length + (a.answer?.attachments ?? []).length, 0);
270 return [
271 `Issue ${i.id}: ${q(i.title)} [${i.status}]`,
272 facts.join(" "),
273 ...(files > 0
274 ? [
275 `${files === 1 ? "1 file is" : `${files} files are`} attached below. To read ${files === 1 ? "it" : "them"}: abso issue ${i.id} --save-attachments <folder> saves ${files === 1 ? "it" : "every one"} there, then open the files. The links are for people signed in on the website.`,
276 ]
277 : []),
278 ...(i.lines ? [`From ${i.lines.file} lines ${i.lines.from}-${i.lines.to} at version ${i.lines.version}.`] : []),
279 ...(i.description !== "" ? ["", ...i.description.split("\n").map((l) => ` ${l}`)] : []),
280 ...attachmentLines(api, i.attachments, " "),
281 ...(p.asks.length > 0 ? ["", "Asks:", ...p.asks.map((a) => askLine(a, api))] : []),
282 ...(p.comments.length > 0
283 ? [
284 "",
285 "Comments:",
286 ...p.comments.flatMap((c) => [
287 ` ${c.by}${c.kind === "objection" ? " objects" : ""}, ${shortWhen(c.at)}: ${q(c.text)}`,
288 ...attachmentLines(api, c.attachments, " "),
289 ]),
290 ]
291 : []),
292 ...((p.edits ?? []).length > 0 ? ["", "Edits:", ...p.edits.map(editLine)] : []),
293 ...(p.children.length > 0 ? ["", "Sub-issues:", ...p.children.map(issueLine)] : []),
294 ...((i.watchers ?? []).length > 0 ? ["", `Watchers: ${i.watchers.join(", ")}.`] : []),
295 "",
296 `abso start "..." --issue ${i.id} starts on it; abso issue ${i.id} --comment "..." comments; abso ask <who> "..." --issue ${i.id} asks.`,
297 ];
298}
300export async function runIssues(args: Parsed, env: Env): Promise<Output> {
301 if (args.positionals.length > 0)
302 throw new UsageError(
303 "issues takes no words: abso issues [--open] [--status <s>] [--agent <a>] [--parent <N>] [--label <l,l>] | abso issues --labels; abso issue <N> shows one",
304 );
305 const { api } = openIssues(env);
306 if (bool(args, "drafts")) {
307 const { drafts } = await api.drafts();
308 return {
309 text:
310 drafts.length === 0
311 ? 'No drafts. abso issue draft "<title>" saves one: only you see it, and nobody hears of it.'
312 : [
313 `${plural(drafts.length, "draft")}, newest first (only you see them):`,
314 ...drafts.map(draftLine),
315 "abso issue draft <D> --open opens one as an issue; --delete deletes it.",
316 ].join("\n"),
317 json: { drafts },
318 };
319 }
320 if (bool(args, "labels")) {
321 const { labels } = await api.issueLabels();
322 return {
323 text:
324 labels.length === 0
325 ? 'No labels yet. abso issue new "<title>" --label friction labels a new issue; abso issue <N> --label <l> labels one.'
326 : [
327 `${plural(labels.length, "label")} in use:`,
328 ...labels.map((l) => ` ${l.label}: ${l.open} open of ${l.total}`),
329 "abso issues --label <label> lists a label's issues.",
330 ].join("\n"),
331 json: { labels },
332 };
333 }
334 const parent = str(args, "parent");
335 const filter = {
336 ...(str(args, "status") ? { status: str(args, "status")! } : {}),
337 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
338 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
339 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
340 open: bool(args, "open"),
341 };
342 const { issues } = await api.issues(filter);
343 const scope = [
344 filter.open ? "open " : "",
345 filter.status ? `${filter.status} ` : "",
346 filter.labels ? `${filter.labels.join(", ")} ` : "",
347 ].join("");
348 return {
349 text:
350 issues.length === 0
351 ? `No ${scope}issues${filter.agent ? ` for ${filter.agent}` : ""}${parent !== undefined ? ` under ${parent}` : ""}. abso issue new "<title>" opens one.`
352 : [
353 `${plural(issues.length, `${scope}issue`)}, most recently updated first:`,
354 ...issues.map(issueLine),
355 "abso issue <N> shows one.",
356 ].join("\n"),
357 json: { issues },
358 };
359}
361/** A new issue's fields from the command line, as open and drafts take them; `title` only when words were given. */
362function openFields(args: Parsed, title: string): DraftBody {
363 const lines = str(args, "lines");
364 const at = lines === undefined ? undefined : /^(.+):(\d+)(?:-(\d+))?@(\d+)$/.exec(lines);
365 if (lines !== undefined && !at)
366 throw new UsageError("--lines is <file>:<from>-<to>@<version>, like src/a.ts:10-14@140");
367 const parent = str(args, "parent");
368 return {
369 ...(title !== "" ? { title } : {}),
370 ...(str(args, "description") ? { description: str(args, "description")! } : {}),
371 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
372 ...(at ? { lines: { file: at[1]!, from: Number(at[2]), to: Number(at[3] ?? at[2]), version: Number(at[4]) } } : {}),
373 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
374 ...(str(args, "blocked-by") !== undefined
375 ? { blockedBy: listOf(str(args, "blocked-by")!).map((b) => issueNumber(b, "--blocked-by")) }
376 : {}),
377 ...(str(args, "notify") !== undefined ? { notify: listOf(str(args, "notify")!) } : {}),
378 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
379 };
380}
382/** One draft as a line: its number, title, and what else it holds. */
383function draftLine(d: Draft): string {
384 const b = d.body;
385 const more = [
386 b.agent ? `for ${b.agent}` : "",
387 b.parent ? `under ${b.parent}` : "",
388 (b.labels ?? []).length > 0 ? `labels ${b.labels!.join(", ")}` : "",
389 b.description ? "a description" : "",
390 ].filter((m) => m !== "");
391 return ` draft ${d.id}: ${b.title ? q(b.title) : "(no title yet)"}${more.length > 0 ? ` (${more.join("; ")})` : ""}, saved ${shortWhen(d.saved)}`;
392}
394/**
395 * Drafts (abso issue 3): an issue not opened yet, this agent's alone, with no
396 * number and no news. `abso issue draft "<title>" [fields]` saves a new one;
397 * `abso issue draft <D> [fields]` changes one; --open opens it as an issue;
398 * --delete deletes it. `abso issues --drafts` lists them.
399 */
400async function runDraft(api: Api, args: Parsed, words: string[]): Promise<Output> {
401 const [d, ...more] = words;
402 if (d !== undefined && /^\d+$/.test(d) && more.length === 0) {
403 const id = Number(d);
404 if (bool(args, "delete") && bool(args, "open")) throw new UsageError("--open or --delete, not both");
405 if (bool(args, "delete")) {
406 await api.deleteDraft(id);
407 return { text: `Deleted draft ${id}.`, json: { draft: id, deleted: true } };
408 }
409 if (bool(args, "open")) {
410 const r = await api.openDraft(id, openFields(args, ""));
411 return {
412 text: `Opened draft ${id} as issue ${r.id}. abso start "..." --issue ${r.id} starts on it.`,
413 json: { draft: id, id: r.id },
414 };
415 }
416 // Saving replaces the draft's body, so the fields given go over what it holds.
417 const found = (await api.drafts()).drafts.find((x) => x.id === id);
418 if (!found) throw new UsageError(`you have no draft ${id}; abso issues --drafts lists yours`);
419 await api.saveDraft({ ...found.body, ...openFields(args, ""), id });
420 return { text: `Saved draft ${id}.`, json: { draft: id } };
421 }
422 if (bool(args, "open") || bool(args, "delete"))
423 throw new UsageError("--open and --delete take a draft's number: abso issue draft <D> --open");
424 const r = await api.saveDraft(openFields(args, words.join(" ")));
425 return {
426 text: `Saved draft ${r.id}. Only you see it, and nobody hears of it. abso issue draft ${r.id} --open opens it as an issue.`,
427 json: { draft: r.id },
428 };
429}
431/** The flags --copy-to goes with: anything else on the same command is refused, so a copy is never half an edit. */
432const COPY_FLAGS = new Set(["copy-to", "clean", "dry-run"]);
434/** abso issue <N> --copy-to <project>: the server reads the issue and writes the copy. */
435async function runCopy(api: Api, id: number, to: string, args: Parsed, env: Env): Promise<Output> {
436 const other = [...args.flags.keys()].filter((f) => !COPY_FLAGS.has(f) && f !== "json");
437 if (other.length > 0)
438 throw new UsageError(`--copy-to goes alone (with --clean and --dry-run), not with --${other[0]}`);
439 if (to === api.config.project)
440 throw new UsageError(`issue ${id} is already in ${to}; --copy-to names another project`);
441 const clean = str(args, "clean");
442 const texts = clean === undefined ? {} : readClean(resolve(env.cwd, clean), clean);
443 const dryRun = bool(args, "dry-run");
444 const from = api.config.project;
445 let answer: CopyAnswer;
446 try {
447 answer = await api.issueCopy(to, { ...texts, from, issue: id, ...(dryRun ? { dryRun: true } : {}) });
448 } catch (e) {
449 if (e instanceof ApiError && e.status === 403 && !dryRun)
450 throw new ApiError(`${e.message}. --dry-run still shows what would go.`, e.status);
451 throw e;
452 }
453 if ("dryRun" in answer) {
454 const p = answer.plan;
455 const edited = (list: { edited: boolean }[]) => list.filter((x) => x.edited).length;
456 const lines = [
457 `A dry run: nothing was written. Copying ${from} issue ${id} into ${to} would make:`,
458 ` ${q(p.title)}${p.closed ? `, ${p.closed.how}` : ""}${p.edited.length > 0 ? ` (${p.edited.join(" and ")} edited when copied)` : ""}`,
459 ` ${plural(p.comments.length, "comment")}${edited(p.comments) > 0 ? ` (${edited(p.comments)} edited)` : ""}, ${plural(p.asks.length, "answered ask")}${edited(p.asks) > 0 ? ` (${edited(p.asks)} edited)` : ""}${p.labels.length > 0 ? `, labelled ${p.labels.join(", ")}` : ""}`,
460 ...skippedLines(p.skipped),
461 `Run it again without --dry-run to copy it.`,
462 ];
463 return { text: lines.join("\n"), json: answer };
464 }
465 return {
466 text: [
467 `Copied ${from} issue ${id} to ${to} issue ${answer.id}. Its comments and asks keep their authors and times, and issue ${id} has a comment saying where it went.`,
468 ...skippedLines(answer.skipped),
469 ].join("\n"),
470 json: answer,
471 };
472}
474function skippedLines(skipped: { comments: number[]; asks: number[] }): string[] {
475 const parts = [
476 ...(skipped.comments.length > 0 ? [`comments ${skipped.comments.join(", ")}`] : []),
477 ...(skipped.asks.length > 0 ? [`asks ${skipped.asks.join(", ")}`] : []),
478 ];
479 return parts.length > 0 ? [` not copied: ${parts.join("; ")} (open asks, and what --clean left out)`] : [];
480}
482/** --clean's file: cleaned texts by source id. The server checks each id against the issue it reads. */
483function readClean(path: string, given: string): Omit<CopyBody, "from" | "issue"> {
484 let raw: unknown;
485 try {
486 raw = JSON.parse(readFileSync(path, "utf8"));
487 } catch (e) {
488 throw new UsageError(
489 `--clean ${given}: ${(e as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`,
490 );
491 }
492 if (typeof raw !== "object" || raw === null || Array.isArray(raw))
493 throw new UsageError(`--clean ${given}: a JSON object with title, description, comments or asks`);
494 const known = new Set(["title", "description", "comments", "asks"]);
495 const unknown = Object.keys(raw).filter((k) => !known.has(k));
496 if (unknown.length > 0)
497 throw new UsageError(`--clean ${given}: ${unknown[0]} isn't one of title, description, comments, asks`);
498 return raw as Omit<CopyBody, "from" | "issue">;
499}
501export async function runIssue(args: Parsed, env: Env): Promise<Output> {
502 const [first, ...rest] = args.positionals;
503 const { root, api } = openIssues(env);
504 const saveTo = str(args, "save-attachments");
505 if (saveTo !== undefined) {
506 const other = [...args.flags.keys()].filter((f) => f !== "save-attachments" && f !== "json");
507 if (other.length > 0 || first === "new" || first === "draft")
508 throw new UsageError(
509 `--save-attachments goes alone with an issue number: abso issue <N> --save-attachments <folder>${other.length > 0 ? `, not with --${other[0]}` : ""}`,
510 );
511 }
512 if (first === "draft") return runDraft(api, args, rest);
513 if (first === "new") {
514 if (rest.length === 0)
515 throw new UsageError(
516 'abso issue new "<title>" [--description "..."] [--parent <N>] [--lines <file>:<from>-<to>@<version>] [--agent <agent>] [--blocked-by <N,N>] [--notify <who,who>] [--label <l,l>]',
517 );
518 const fields = { ...openFields(args, rest.join(" ")), title: rest.join(" ") };
519 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
520 const r = await api.issueOpen({ ...fields, ...(attachments.length > 0 ? { attachments } : {}) });
521 return {
522 text: `Opened issue ${r.id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. abso start "..." --issue ${r.id} starts on it.`,
523 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}) },
524 };
525 }
526 if (first === undefined || rest.length > 0)
527 throw new UsageError(
528 'abso issue <N> [--comment "..." | --object "..." | --drop | --reopen | --done [--done-by <version>] | an edit], or abso issue new "<title>"',
529 );
530 const id = issueNumber(first);
531 const copyTo = str(args, "copy-to");
532 if (copyTo !== undefined) return runCopy(api, id, copyTo, args, env);
533 if (str(args, "clean") !== undefined || bool(args, "dry-run"))
534 throw new UsageError("--clean and --dry-run go with --copy-to <project>");
535 const comment = str(args, "comment");
536 const object = str(args, "object");
537 const doneBy = str(args, "done-by");
538 const markingDone = bool(args, "done") || doneBy !== undefined;
539 const edits = ["title", "description", "parent", "agent", "blocked-by", "label", "unlabel"].filter(
540 (f) => str(args, f) !== undefined,
541 );
542 if (
543 [
544 comment !== undefined,
545 object !== undefined,
546 bool(args, "drop"),
547 bool(args, "reopen"),
548 markingDone,
549 edits.length > 0,
550 ].filter(Boolean).length > 1
551 )
552 throw new UsageError("one of --comment, --object, --drop, --reopen, --done or an edit at a time");
553 if (edits.length > 0) {
554 const parent = str(args, "parent");
555 const agent = str(args, "agent");
556 const blockedBy = str(args, "blocked-by");
557 const r = await api.issueEdit(id, {
558 ...(str(args, "title") !== undefined ? { title: str(args, "title")! } : {}),
559 ...(str(args, "description") !== undefined ? { description: str(args, "description")! } : {}),
560 ...(parent !== undefined ? { parent: parent === "none" ? null : issueNumber(parent, "--parent") } : {}),
561 ...(agent !== undefined ? { agent: agent === "none" ? null : agent } : {}),
562 ...(blockedBy !== undefined ? { blockedBy: listOf(blockedBy).map((b) => issueNumber(b, "--blocked-by")) } : {}),
563 ...(bool(args, "quiet") ? { notify: false } : {}),
564 ...(str(args, "notify") !== undefined ? { also: listOf(str(args, "notify")!) } : {}),
565 ...(str(args, "label") !== undefined ? { addLabels: labelList(str(args, "label")!) } : {}),
566 ...(str(args, "unlabel") !== undefined ? { removeLabels: labelList(str(args, "unlabel")!) } : {}),
567 // A labels-only edit tells nobody unless --notify names people.
568 ...(edits.every((f) => f === "label" || f === "unlabel") && str(args, "notify") !== undefined
569 ? { notify: true }
570 : {}),
571 });
572 return {
573 text: `Edited issue ${id}. ${r.notified.length > 0 ? `Told ${r.notified.join(", ")}.` : "Told nobody."}`,
574 json: { issue: id, edit: r.edit, notified: r.notified },
575 };
576 }
577 if (bool(args, "quiet") || str(args, "notify") !== undefined)
578 throw new UsageError(
579 "--quiet and --notify go with an edit (--title, --description, --parent, --agent, --blocked-by, --label or --unlabel)",
580 );
581 if (str(args, "attach") !== undefined && comment === undefined && object === undefined)
582 throw new UsageError("--attach goes with abso issue new or --comment (or --object)");
583 if (comment !== undefined || object !== undefined) {
584 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
585 const r = await api.issueComment(id, (comment ?? object)!, object !== undefined, attachments);
586 return {
587 text: `${object !== undefined ? "Objected" : "Commented"} on issue ${id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. Its agents hear it.`,
588 json: { id: r.id, issue: id, ...(attachments.length > 0 ? { attachments } : {}) },
589 };
590 }
591 if (bool(args, "drop")) {
592 await api.issueDrop(id);
593 return { text: `Dropped issue ${id}.`, json: { issue: id, dropped: true } };
594 }
595 if (bool(args, "reopen")) {
596 await api.issueReopen(id);
597 return { text: `Reopened issue ${id}.`, json: { issue: id, reopened: true } };
598 }
599 if (markingDone) {
600 let version: number | null = null;
601 if (doneBy !== undefined) {
602 version = issueNumber(doneBy, "--done-by");
603 if (version < 1) throw new UsageError("--done-by is a published version, 1 or more");
604 try {
605 await api.show(version, { draft: null });
606 } catch {
607 throw new UsageError(`no version ${version}`);
608 }
609 }
610 await api.issueDone(id, version);
611 return {
612 text: version === null ? `Marked issue ${id} done.` : `Marked issue ${id} done in version ${version}.`,
613 json: { issue: id, done: true, ...(version !== null ? { version } : {}) },
614 };
615 }
616 const page = await api.issue(id);
617 if (saveTo !== undefined) return saveAttachments(api, root, env.cwd, saveTo, page);
618 return { text: issuePage(page, api).join("\n"), json: { ...page } };
619}
621export async function runAsk(args: Parsed, env: Env): Promise<Output> {
622 const withdraw = str(args, "withdraw");
623 if (withdraw !== undefined) return withdrawAsk(args, env, withdraw);
624 if (str(args, "note") !== undefined)
625 throw new UsageError('--note goes with --withdraw: abso ask --withdraw <ask> --note "why"');
626 const [of, ...words] = args.positionals;
627 if (of === undefined || words.length === 0)
628 throw new UsageError(
629 'abso ask <who> "<question>" [--issue <N>] [--review | --task] [--due <YYYY-MM-DD>] [--blocks <N,N>] [--options "A|B|C"]; who is an agent, or person:<id>',
630 );
631 const { api } = openIssues(env);
632 if (bool(args, "review") && bool(args, "task")) throw new UsageError("an ask is a review or a task, not both");
633 const issue = str(args, "issue");
634 const blocks = str(args, "blocks");
635 const options = str(args, "options");
636 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
637 const r = await api.ask({
638 of,
639 question: words.join(" "),
640 ...(issue !== undefined ? { issue: issueNumber(issue, "--issue") } : {}),
641 ...(bool(args, "review") ? { review: true } : {}),
642 ...(bool(args, "task") ? { kind: "task" as const } : {}),
643 ...(str(args, "due") ? { due: str(args, "due")! } : {}),
644 ...(blocks !== undefined ? { blocks: blocks.split(",").map((b) => issueNumber(b.trim(), "--blocks")) } : {}),
645 ...(options !== undefined
646 ? {
647 options: options
648 .split("|")
649 .map((o) => o.trim())
650 .filter((o) => o !== ""),
651 }
652 : {}),
653 ...(attachments.length > 0 ? { attachments } : {}),
654 });
655 const lost = notKept(attachments, r.attachments, `ask ${r.id}`);
656 return {
657 text: `Asked ${of} (ask ${r.id})${withFiles(attachments)}. They hear it; abso waiting shows what's open.${lost ? ` ${lost}` : ""}`,
658 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}), ...(lost ? { notKept: lost } : {}) },
659 };
660}
662/** abso ask --withdraw <ask> [--note "why"]: the asker takes an ask back. It closes like an answer, and the one asked hears it. */
663async function withdrawAsk(args: Parsed, env: Env, word: string): Promise<Output> {
664 const others = ["issue", "due", "blocks", "options", "attach"].filter((f) => str(args, f) !== undefined);
665 if (args.positionals.length > 0 || others.length > 0 || bool(args, "review") || bool(args, "task"))
666 throw new UsageError('abso ask --withdraw <ask> [--note "why"] takes nothing else: it takes back an ask you made');
667 const id = issueNumber(word, "the ask number");
668 const { api } = openIssues(env);
669 const note = str(args, "note");
670 const r = await api.withdraw(id, note !== undefined ? { note } : {});
671 return { text: `Withdrew ask ${id}. ${r.ask.of} hears it, and it no longer waits on them.`, json: { ask: r.ask } };
672}
674/** One search hit as two lines: the issue, then where it matched and the words around it. */
675export function searchLines(h: IssueSearchHit): string[] {
676 const where = h.meaning ? "by meaning" : h.where === "comment" ? `in comment ${h.comment}` : `in the ${h.where}`;
677 const words = h.snippet
678 .replace(/[\u0001\u0002]/g, "")
679 .replace(/\s+/g, " ")
680 .trim();
681 return [
682 ` ${String(h.issue.id).padStart(3)} ${h.issue.status.padEnd(11)} ${q(h.issue.title)}`,
683 ` ${where}${words && words !== h.issue.title ? `: ${q(words)}` : ""}`,
684 ];
685}
687export async function runSearch(args: Parsed, env: Env): Promise<Output> {
688 const words = args.positionals.join(" ").trim();
689 if (words === "") throw new UsageError('search needs words: abso search "<words>" [--limit <N>]');
690 const limitWord = str(args, "limit");
691 const limit = limitWord === undefined ? undefined : Number(limitWord);
692 if (limit !== undefined && !(Number.isInteger(limit) && limit >= 1 && limit <= 50))
693 throw new UsageError("--limit is a number from 1 to 50");
694 const { api } = openIssues(env);
695 const { hits } = await api.issueSearch(words, limit);
696 return {
697 text:
698 hits.length === 0
699 ? `Nothing matches ${q(words)}.`
700 : [
701 `${plural(hits.length, "issue")} for ${q(words)}, best first:`,
702 ...hits.flatMap(searchLines),
703 "abso issue <N> shows one.",
704 ].join("\n"),
705 json: { hits },
706 };
707}
709export async function runWaiting(args: Parsed, env: Env): Promise<Output> {
710 if (args.positionals.length > 0)
711 throw new UsageError("waiting takes no words: abso waiting [--of <agent or person:id>] [--mine]");
712 const { api, config } = openIssues(env);
713 const mine = bool(args, "mine") || str(args, "of") === config.agent;
714 const of = mine ? config.agent : str(args, "of");
715 // With --mine, your own publishes still in the merge queue are open work too. A server without a queue,
716 // or one that can't be read now, leaves them out rather than failing the asks.
717 const [{ asks }, queue] = await Promise.all([
718 mine ? api.waitingMine() : api.waiting(of),
719 mine ? api.queueState().catch(() => undefined) : undefined,
720 ]);
721 const queued = queuedLines(queue, config.agent);
722 const yours = (queue?.items ?? []).filter((q) => q.agent === config.agent);
723 return {
724 text: [
725 ...queued,
726 ...(asks.length === 0
727 ? [queued.length > 0 ? `No open asks of ${of}.` : `Nothing is waiting${of ? ` on ${of}` : ""}.`]
728 : [
729 `${plural(asks.length, "open ask")}${of ? ` of ${of}` : ""}, soonest due first:`,
730 ...asks.map((a) => askLine(a, api)),
731 'abso answer <ask> "..." answers one asked of you.',
732 ]),
733 ].join("\n"),
734 json: {
735 asks,
736 ...(yours.length > 0
737 ? { queued: yours.map((q) => ({ id: q.id, message: q.message, standing: standing(queue!.items, q.id) })) }
738 : {}),
739 },
740 };
741}
743/** abso ack <ask> ["note"]: tell the asker you have it, and answer later. The ask stays open until abso answer. */
744export async function runAck(args: Parsed, env: Env): Promise<Output> {
745 const [first, ...words] = args.positionals;
746 const id = issueNumber(first, "the ask number");
747 const { api } = openIssues(env);
748 const note = words.join(" ");
749 const r = await api.ack(id, note !== "" ? { note } : {});
750 return {
751 text: `Acknowledged ask ${id}. ${r.ask.by} hears it; the ask stays open until abso answer ${id} "...".`,
752 json: { ask: r.ask },
753 };
754}
756export async function runAnswer(args: Parsed, env: Env): Promise<Output> {
757 const [first, ...words] = args.positionals;
758 const id = issueNumber(first, "the ask number");
759 const option = str(args, "option");
760 const done = bool(args, "done");
761 if (words.length === 0 && option === undefined && !done)
762 throw new UsageError('abso answer <ask> "<words>" | --option <N> [--note "..."] | --done [--note "..."]');
763 const { api } = openIssues(env);
764 const note = str(args, "note");
765 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
766 const r = await api.answer(id, {
767 ...(words.length > 0 ? { words: words.join(" ") } : {}),
768 ...(option !== undefined ? { option: /^\d+$/.test(option) ? Number(option) - 1 : option } : {}),
769 ...(done ? { done: true } : {}),
770 ...(note !== undefined ? { note } : {}),
771 ...(attachments.length > 0 ? { attachments } : {}),
772 });
773 const lost = notKept(
774 attachments,
775 r.ask.answer?.attachments?.map((a) => a.id),
776 `your answer to ask ${id}`,
777 );
778 return {
779 text: `Answered ask ${id}${withFiles(attachments)}. ${r.ask.by} hears it.${lost ? ` ${lost}` : ""}`,
780 json: { ask: r.ask, ...(lost ? { notKept: lost } : {}) },
781 };
782}