- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/issues.ts?version=26&format=json
645 linesFirst import 64% · pinch 24% · devops 5% · review 4% · infra-split 3%Last change pinch in version 24, 8 versions changed it
You're reading version 26. The newest is 318, and 14 versions since then changed this file.
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// AVCS_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 { readFileSync, statSync } from "node:fs";
9import { basename, 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 { seenText, shortWhen } from "./times.ts";
29const q = (s: string): string => JSON.stringify(s);
31/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */
32function openIssues(env: Env): { config: Config; api: Api } {
33 const { config, api } = open(env);
34 const server = env.env.AVCS_ISSUES_SERVER || issuesServerFor(config.server, readMachineServers(env.env));
35 if (server === undefined)
36 throw new UsageError(
37 `${config.server} has no Issues Worker beside it that abso knows; ~/.abso/servers.json or AVCS_ISSUES_SERVER names one`,
38 );
39 if (config.token !== undefined && !tokenGoesTo(server, trustedServers(env.env))) {
40 throw new UsageError(
41 `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 AVCS_TRUSTED_SERVERS.`,
42 );
43 }
44 api.issuesServer = server;
45 return { config, api };
46}
48function issueNumber(word: string | undefined, what = "an issue number"): number {
49 if (word === undefined || !/^#?\d+$/.test(word)) throw new UsageError(`${what} is a number, like 12`);
50 return Number(word.replace("#", ""));
51}
53/** One issue as a line. */
54export function issueLine(i: IssueRow): string {
55 const detail = [
56 i.agent !== null && !i.agents.includes(i.agent) ? `for ${i.agent}` : "",
57 i.agents.length > 0 ? i.agents.join(", ") : "",
58 i.blockedBy.length > 0 ? `blocked by ${i.blockedBy.join(", ")}` : "",
59 (i.labels ?? []).length > 0 ? `labels ${i.labels.join(", ")}` : "",
60 i.versions.length > 0 ? `${i.versions.length === 1 ? "version" : "versions"} ${i.versions.join(", ")}` : "",
61 i.waitingOn.length > 0 ? `waiting on ${i.waitingOn.join(", ")}` : "",
62 i.parent !== null ? `under ${i.parent}` : "",
63 i.children > 0 ? plural(i.children, "sub-issue") : "",
64 `updated ${shortWhen(i.updated)}`,
65 ].filter((d) => d !== "");
66 return ` ${String(i.id).padStart(3)} ${i.status.padEnd(11)} ${q(i.title)}${detail.length > 0 ? ` (${detail.join("; ")})` : ""}`;
67}
69function askLine(a: Ask & { title?: string | null }): string {
70 const what = a.review ? "a review" : a.kind === "task" ? "a task" : "a question";
71 const where = a.issue === null ? "" : ` on issue ${a.issue}${a.title ? ` (${q(a.title)})` : ""}`;
72 const extra = [
73 // Who answered, and when, on the ask's own line, so a handled ask can't pass for an open one.
74 a.answer
75 ? `${a.outcome === "withdrawn" ? "withdrawn" : "answered"} by ${a.answer.by}, ${shortWhen(a.answer.at)}`
76 : "",
77 !a.answer && a.seen !== undefined ? seenText(a.seen) : "",
78 a.due ? `due ${a.due}` : "",
79 a.blocks.length > 0 ? `blocks ${a.blocks.join(", ")}` : "",
80 ].filter((x) => x !== "");
81 const head = ` ask ${a.id}: ${a.by}, ${shortWhen(a.at)}, asks ${a.of} ${what}${where}${extra.length > 0 ? ` (${extra.join("; ")})` : ""}: ${q(a.question)}`;
82 const lines = [head];
83 if (a.options.length > 0) lines.push(` options: ${a.options.map((o, i) => `${i + 1}. ${q(o)}`).join(", ")}`);
84 if (a.recommendation) lines.push(` ${a.recommendation.by} recommends: ${q(a.recommendation.text)}`);
85 if (a.answer && a.outcome === "withdrawn") {
86 if (a.answer.words !== "") lines.push(` why: ${q(a.answer.words)}`);
87 } else if (a.answer) lines.push(` answer: ${q(a.answer.words)}`);
88 return lines.join("\n");
89}
91/** One edit in an issue's activity: what changed, and who was told. */
92function editLine(e: IssuePage["edits"][number]): string {
93 const c = e.changes;
94 const said = [
95 c.title ? `title ${q(String(c.title.from))} to ${q(String(c.title.to))}` : "",
96 c.description ? "the description" : "",
97 c.parent ? (c.parent.to === null ? "no parent" : `parent issue ${String(c.parent.to)}`) : "",
98 c.agent ? (c.agent.to === null ? "no Agent" : `Agent ${String(c.agent.to)}`) : "",
99 c.blockedBy
100 ? (c.blockedBy.to as number[]).length === 0
101 ? "blocked by nothing"
102 : `blocked by ${(c.blockedBy.to as number[]).join(", ")}`
103 : "",
104 c.labels
105 ? (c.labels.to as string[]).length === 0
106 ? "no labels"
107 : `labels ${(c.labels.to as string[]).join(", ")}`
108 : "",
109 ].filter((x) => x !== "");
110 return ` ${e.by}, ${shortWhen(e.at)}: ${said.join("; ")} (${e.notified.length > 0 ? `told ${e.notified.join(", ")}` : "told nobody"})`;
111}
113/** Labels as typed, lower-cased, since the Worker refuses upper case (Security): --label Friction means friction. */
114function labelList(value: string): string[] {
115 return listOf(value).map((l) => l.toLowerCase());
116}
118/** A comma-separated list of names or issue numbers; "none" is the empty list. */
119function listOf(value: string): string[] {
120 return value.trim() === "none"
121 ? []
122 : value
123 .split(",")
124 .map((v) => v.trim())
125 .filter((v) => v !== "");
126}
128/** The most one attachment may be: the Issues Worker's cap, checked here before sending (abso issue 171). */
129const ATTACH_MAX = 10 * 1024 * 1024;
131/** Uploads each file --attach names (comma-separated), in order, and answers their ids. Nothing is sent if a file is missing or too big. */
132async function uploadAttachments(api: Api, cwd: string, value: string | undefined): Promise<string[]> {
133 if (value === undefined) return [];
134 const paths = listOf(value);
135 if (paths.length === 0) throw new UsageError("--attach names files, comma-separated: --attach shot.png,after.png");
136 const files = paths.map((p) => {
137 const full = resolve(cwd, p);
138 let size: number;
139 try {
140 size = statSync(full).size;
141 } catch {
142 throw new UsageError(`--attach ${p}: no such file`);
143 }
144 if (size > ATTACH_MAX)
145 throw new UsageError(`--attach ${p} is ${sizeText(size)}; one attachment is at most ${sizeText(ATTACH_MAX)}`);
146 return { full, name: basename(full) };
147 });
148 const ids: string[] = [];
149 for (const f of files) ids.push((await api.attachmentUpload(readFileSync(f.full), f.name)).id);
150 return ids;
151}
153function sizeText(n: number): string {
154 return n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`;
155}
157/** Attachments as lines under what carries them: name, size and where it's served. */
158function attachmentLines(
159 api: Pick<Api, "attachmentUrl"> | undefined,
160 files: readonly Attachment[] | undefined,
161 indent: string,
162): string[] {
163 return (files ?? []).flatMap((a) => [
164 `${indent}attached ${a.id}: ${q(a.name)}, ${sizeText(a.size)}${api ? `, ${api.attachmentUrl(a.id)}` : ""}`,
165 // An SVG is shown as the PNG drawn from it; its own file is a download beside it.
166 ...(a.source
167 ? [
168 `${indent} drawn from ${q(a.source.name)}, ${sizeText(a.source.size)}${api ? `, ${api.attachmentUrl(a.id)}/source` : ""}`,
169 ]
170 : []),
171 ]);
172}
174/** An issue's page, as text. */
175export function issuePage(p: IssuePage, api?: Pick<Api, "attachmentUrl">): string[] {
176 const i = p.issue;
177 const facts = [
178 i.parent !== null ? `Under issue ${i.parent}.` : "",
179 `Opened by ${i.opened.by}, ${shortWhen(i.opened.at)}.`,
180 i.agent !== null ? `Agent: ${i.agent}.` : "",
181 i.agents.length > 0 ? `Working on it: ${i.agents.join(", ")}.` : "",
182 i.blockedBy.length > 0 ? `Blocked by: issue${i.blockedBy.length === 1 ? "" : "s"} ${i.blockedBy.join(", ")}.` : "",
183 (i.labels ?? []).length > 0 ? `Labels: ${i.labels.join(", ")}.` : "",
184 i.versions.length > 0 ? `Versions: ${i.versions.join(", ")}.` : "",
185 i.waitingOn.length > 0 ? `Waiting on: ${i.waitingOn.join(", ")}.` : "",
186 i.closed
187 ? `${i.closed.how === "done" ? "Done" : "Dropped"} by ${i.closed.by}${i.closed.version !== null ? ` in version ${i.closed.version}` : ""}, ${shortWhen(i.closed.at)}.`
188 : "",
189 ].filter((f) => f !== "");
190 return [
191 `Issue ${i.id}: ${q(i.title)} [${i.status}]`,
192 facts.join(" "),
193 ...(i.lines ? [`From ${i.lines.file} lines ${i.lines.from}-${i.lines.to} at version ${i.lines.version}.`] : []),
194 ...(i.description !== "" ? ["", ...i.description.split("\n").map((l) => ` ${l}`)] : []),
195 ...attachmentLines(api, i.attachments, " "),
196 ...(p.asks.length > 0 ? ["", "Asks:", ...p.asks.map(askLine)] : []),
197 ...(p.comments.length > 0
198 ? [
199 "",
200 "Comments:",
201 ...p.comments.flatMap((c) => [
202 ` ${c.by}${c.kind === "objection" ? " objects" : ""}, ${shortWhen(c.at)}: ${q(c.text)}`,
203 ...attachmentLines(api, c.attachments, " "),
204 ]),
205 ]
206 : []),
207 ...((p.edits ?? []).length > 0 ? ["", "Edits:", ...p.edits.map(editLine)] : []),
208 ...(p.children.length > 0 ? ["", "Sub-issues:", ...p.children.map(issueLine)] : []),
209 ...((i.watchers ?? []).length > 0 ? ["", `Watchers: ${i.watchers.join(", ")}.`] : []),
210 "",
211 `abso start "..." --issue ${i.id} starts on it; abso issue ${i.id} --comment "..." comments; abso ask <who> "..." --issue ${i.id} asks.`,
212 ];
213}
215export async function runIssues(args: Parsed, env: Env): Promise<Output> {
216 if (args.positionals.length > 0)
217 throw new UsageError(
218 "issues takes no words: abso issues [--open] [--status <s>] [--agent <a>] [--parent <N>] [--label <l,l>] | abso issues --labels; abso issue <N> shows one",
219 );
220 const { api } = openIssues(env);
221 if (bool(args, "drafts")) {
222 const { drafts } = await api.drafts();
223 return {
224 text:
225 drafts.length === 0
226 ? 'No drafts. abso issue draft "<title>" saves one: only you see it, and nobody hears of it.'
227 : [
228 `${plural(drafts.length, "draft")}, newest first (only you see them):`,
229 ...drafts.map(draftLine),
230 "abso issue draft <D> --open opens one as an issue; --delete deletes it.",
231 ].join("\n"),
232 json: { drafts },
233 };
234 }
235 if (bool(args, "labels")) {
236 const { labels } = await api.issueLabels();
237 return {
238 text:
239 labels.length === 0
240 ? 'No labels yet. abso issue new "<title>" --label friction labels a new issue; abso issue <N> --label <l> labels one.'
241 : [
242 `${plural(labels.length, "label")} in use:`,
243 ...labels.map((l) => ` ${l.label}: ${l.open} open of ${l.total}`),
244 "abso issues --label <label> lists a label's issues.",
245 ].join("\n"),
246 json: { labels },
247 };
248 }
249 const parent = str(args, "parent");
250 const filter = {
251 ...(str(args, "status") ? { status: str(args, "status")! } : {}),
252 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
253 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
254 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
255 open: bool(args, "open"),
256 };
257 const { issues } = await api.issues(filter);
258 const scope = [
259 filter.open ? "open " : "",
260 filter.status ? `${filter.status} ` : "",
261 filter.labels ? `${filter.labels.join(", ")} ` : "",
262 ].join("");
263 return {
264 text:
265 issues.length === 0
266 ? `No ${scope}issues${filter.agent ? ` for ${filter.agent}` : ""}${parent !== undefined ? ` under ${parent}` : ""}. abso issue new "<title>" opens one.`
267 : [
268 `${plural(issues.length, `${scope}issue`)}, most recently updated first:`,
269 ...issues.map(issueLine),
270 "abso issue <N> shows one.",
271 ].join("\n"),
272 json: { issues },
273 };
274}
276/** A new issue's fields from the command line, as open and drafts take them; `title` only when words were given. */
277function openFields(args: Parsed, title: string): DraftBody {
278 const lines = str(args, "lines");
279 const at = lines === undefined ? undefined : /^(.+):(\d+)(?:-(\d+))?@(\d+)$/.exec(lines);
280 if (lines !== undefined && !at)
281 throw new UsageError("--lines is <file>:<from>-<to>@<version>, like src/a.ts:10-14@140");
282 const parent = str(args, "parent");
283 return {
284 ...(title !== "" ? { title } : {}),
285 ...(str(args, "description") ? { description: str(args, "description")! } : {}),
286 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
287 ...(at ? { lines: { file: at[1]!, from: Number(at[2]), to: Number(at[3] ?? at[2]), version: Number(at[4]) } } : {}),
288 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
289 ...(str(args, "blocked-by") !== undefined
290 ? { blockedBy: listOf(str(args, "blocked-by")!).map((b) => issueNumber(b, "--blocked-by")) }
291 : {}),
292 ...(str(args, "notify") !== undefined ? { notify: listOf(str(args, "notify")!) } : {}),
293 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
294 };
295}
297/** One draft as a line: its number, title, and what else it holds. */
298function draftLine(d: Draft): string {
299 const b = d.body;
300 const more = [
301 b.agent ? `for ${b.agent}` : "",
302 b.parent ? `under ${b.parent}` : "",
303 (b.labels ?? []).length > 0 ? `labels ${b.labels!.join(", ")}` : "",
304 b.description ? "a description" : "",
305 ].filter((m) => m !== "");
306 return ` draft ${d.id}: ${b.title ? q(b.title) : "(no title yet)"}${more.length > 0 ? ` (${more.join("; ")})` : ""}, saved ${shortWhen(d.saved)}`;
307}
309/**
310 * Drafts (abso issue 3): an issue not opened yet, this agent's alone, with no
311 * number and no news. `abso issue draft "<title>" [fields]` saves a new one;
312 * `abso issue draft <D> [fields]` changes one; --open opens it as an issue;
313 * --delete deletes it. `abso issues --drafts` lists them.
314 */
315async function runDraft(api: Api, args: Parsed, words: string[]): Promise<Output> {
316 const [d, ...more] = words;
317 if (d !== undefined && /^\d+$/.test(d) && more.length === 0) {
318 const id = Number(d);
319 if (bool(args, "delete") && bool(args, "open")) throw new UsageError("--open or --delete, not both");
320 if (bool(args, "delete")) {
321 await api.deleteDraft(id);
322 return { text: `Deleted draft ${id}.`, json: { draft: id, deleted: true } };
323 }
324 if (bool(args, "open")) {
325 const r = await api.openDraft(id, openFields(args, ""));
326 return {
327 text: `Opened draft ${id} as issue ${r.id}. abso start "..." --issue ${r.id} starts on it.`,
328 json: { draft: id, id: r.id },
329 };
330 }
331 // Saving replaces the draft's body, so the fields given go over what it holds.
332 const found = (await api.drafts()).drafts.find((x) => x.id === id);
333 if (!found) throw new UsageError(`you have no draft ${id}; abso issues --drafts lists yours`);
334 await api.saveDraft({ ...found.body, ...openFields(args, ""), id });
335 return { text: `Saved draft ${id}.`, json: { draft: id } };
336 }
337 if (bool(args, "open") || bool(args, "delete"))
338 throw new UsageError("--open and --delete take a draft's number: abso issue draft <D> --open");
339 const r = await api.saveDraft(openFields(args, words.join(" ")));
340 return {
341 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.`,
342 json: { draft: r.id },
343 };
344}
346/** The flags --copy-to goes with: anything else on the same command is refused, so a copy is never half an edit. */
347const COPY_FLAGS = new Set(["copy-to", "clean", "dry-run"]);
349/** abso issue <N> --copy-to <project>: the server reads the issue and writes the copy. */
350async function runCopy(api: Api, id: number, to: string, args: Parsed, env: Env): Promise<Output> {
351 const other = [...args.flags.keys()].filter((f) => !COPY_FLAGS.has(f) && f !== "json");
352 if (other.length > 0)
353 throw new UsageError(`--copy-to goes alone (with --clean and --dry-run), not with --${other[0]}`);
354 if (to === api.config.project)
355 throw new UsageError(`issue ${id} is already in ${to}; --copy-to names another project`);
356 const clean = str(args, "clean");
357 const texts = clean === undefined ? {} : readClean(resolve(env.cwd, clean), clean);
358 const dryRun = bool(args, "dry-run");
359 const from = api.config.project;
360 let answer: CopyAnswer;
361 try {
362 answer = await api.issueCopy(to, { ...texts, from, issue: id, ...(dryRun ? { dryRun: true } : {}) });
363 } catch (e) {
364 if (e instanceof ApiError && e.status === 403 && !dryRun)
365 throw new ApiError(`${e.message}. --dry-run still shows what would go.`, e.status);
366 throw e;
367 }
368 if ("dryRun" in answer) {
369 const p = answer.plan;
370 const edited = (list: { edited: boolean }[]) => list.filter((x) => x.edited).length;
371 const lines = [
372 `A dry run: nothing was written. Copying ${from} issue ${id} into ${to} would make:`,
373 ` ${q(p.title)}${p.closed ? `, ${p.closed.how}` : ""}${p.edited.length > 0 ? ` (${p.edited.join(" and ")} edited when copied)` : ""}`,
374 ` ${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(", ")}` : ""}`,
375 ...skippedLines(p.skipped),
376 `Run it again without --dry-run to copy it.`,
377 ];
378 return { text: lines.join("\n"), json: answer };
379 }
380 return {
381 text: [
382 `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.`,
383 ...skippedLines(answer.skipped),
384 ].join("\n"),
385 json: answer,
386 };
387}
389function skippedLines(skipped: { comments: number[]; asks: number[] }): string[] {
390 const parts = [
391 ...(skipped.comments.length > 0 ? [`comments ${skipped.comments.join(", ")}`] : []),
392 ...(skipped.asks.length > 0 ? [`asks ${skipped.asks.join(", ")}`] : []),
393 ];
394 return parts.length > 0 ? [` not copied: ${parts.join("; ")} (open asks, and what --clean left out)`] : [];
395}
397/** --clean's file: cleaned texts by source id. The server checks each id against the issue it reads. */
398function readClean(path: string, given: string): Omit<CopyBody, "from" | "issue"> {
399 let raw: unknown;
400 try {
401 raw = JSON.parse(readFileSync(path, "utf8"));
402 } catch (e) {
403 throw new UsageError(
404 `--clean ${given}: ${(e as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`,
405 );
406 }
407 if (typeof raw !== "object" || raw === null || Array.isArray(raw))
408 throw new UsageError(`--clean ${given}: a JSON object with title, description, comments or asks`);
409 const known = new Set(["title", "description", "comments", "asks"]);
410 const unknown = Object.keys(raw).filter((k) => !known.has(k));
411 if (unknown.length > 0)
412 throw new UsageError(`--clean ${given}: ${unknown[0]} isn't one of title, description, comments, asks`);
413 return raw as Omit<CopyBody, "from" | "issue">;
414}
416export async function runIssue(args: Parsed, env: Env): Promise<Output> {
417 const [first, ...rest] = args.positionals;
418 const { api } = openIssues(env);
419 if (first === "draft") return runDraft(api, args, rest);
420 if (first === "new") {
421 if (rest.length === 0)
422 throw new UsageError(
423 'abso issue new "<title>" [--description "..."] [--parent <N>] [--lines <file>:<from>-<to>@<version>] [--agent <agent>] [--blocked-by <N,N>] [--notify <who,who>] [--label <l,l>]',
424 );
425 const fields = { ...openFields(args, rest.join(" ")), title: rest.join(" ") };
426 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
427 const r = await api.issueOpen({ ...fields, ...(attachments.length > 0 ? { attachments } : {}) });
428 return {
429 text: `Opened issue ${r.id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. abso start "..." --issue ${r.id} starts on it.`,
430 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}) },
431 };
432 }
433 if (first === undefined || rest.length > 0)
434 throw new UsageError(
435 'abso issue <N> [--comment "..." | --object "..." | --drop | --reopen | --done [--done-by <version>] | an edit], or abso issue new "<title>"',
436 );
437 const id = issueNumber(first);
438 const copyTo = str(args, "copy-to");
439 if (copyTo !== undefined) return runCopy(api, id, copyTo, args, env);
440 if (str(args, "clean") !== undefined || bool(args, "dry-run"))
441 throw new UsageError("--clean and --dry-run go with --copy-to <project>");
442 const comment = str(args, "comment");
443 const object = str(args, "object");
444 const doneBy = str(args, "done-by");
445 const markingDone = bool(args, "done") || doneBy !== undefined;
446 const edits = ["title", "description", "parent", "agent", "blocked-by", "label", "unlabel"].filter(
447 (f) => str(args, f) !== undefined,
448 );
449 if (
450 [
451 comment !== undefined,
452 object !== undefined,
453 bool(args, "drop"),
454 bool(args, "reopen"),
455 markingDone,
456 edits.length > 0,
457 ].filter(Boolean).length > 1
458 )
459 throw new UsageError("one of --comment, --object, --drop, --reopen, --done or an edit at a time");
460 if (edits.length > 0) {
461 const parent = str(args, "parent");
462 const agent = str(args, "agent");
463 const blockedBy = str(args, "blocked-by");
464 const r = await api.issueEdit(id, {
465 ...(str(args, "title") !== undefined ? { title: str(args, "title")! } : {}),
466 ...(str(args, "description") !== undefined ? { description: str(args, "description")! } : {}),
467 ...(parent !== undefined ? { parent: parent === "none" ? null : issueNumber(parent, "--parent") } : {}),
468 ...(agent !== undefined ? { agent: agent === "none" ? null : agent } : {}),
469 ...(blockedBy !== undefined ? { blockedBy: listOf(blockedBy).map((b) => issueNumber(b, "--blocked-by")) } : {}),
470 ...(bool(args, "quiet") ? { notify: false } : {}),
471 ...(str(args, "notify") !== undefined ? { also: listOf(str(args, "notify")!) } : {}),
472 ...(str(args, "label") !== undefined ? { addLabels: labelList(str(args, "label")!) } : {}),
473 ...(str(args, "unlabel") !== undefined ? { removeLabels: labelList(str(args, "unlabel")!) } : {}),
474 // A labels-only edit tells nobody unless --notify names people.
475 ...(edits.every((f) => f === "label" || f === "unlabel") && str(args, "notify") !== undefined
476 ? { notify: true }
477 : {}),
478 });
479 return {
480 text: `Edited issue ${id}. ${r.notified.length > 0 ? `Told ${r.notified.join(", ")}.` : "Told nobody."}`,
481 json: { issue: id, edit: r.edit, notified: r.notified },
482 };
483 }
484 if (bool(args, "quiet") || str(args, "notify") !== undefined)
485 throw new UsageError(
486 "--quiet and --notify go with an edit (--title, --description, --parent, --agent, --blocked-by, --label or --unlabel)",
487 );
488 if (str(args, "attach") !== undefined && comment === undefined && object === undefined)
489 throw new UsageError("--attach goes with abso issue new or --comment (or --object)");
490 if (comment !== undefined || object !== undefined) {
491 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
492 const r = await api.issueComment(id, (comment ?? object)!, object !== undefined, attachments);
493 return {
494 text: `${object !== undefined ? "Objected" : "Commented"} on issue ${id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. Its agents hear it.`,
495 json: { id: r.id, issue: id, ...(attachments.length > 0 ? { attachments } : {}) },
496 };
497 }
498 if (bool(args, "drop")) {
499 await api.issueDrop(id);
500 return { text: `Dropped issue ${id}.`, json: { issue: id, dropped: true } };
501 }
502 if (bool(args, "reopen")) {
503 await api.issueReopen(id);
504 return { text: `Reopened issue ${id}.`, json: { issue: id, reopened: true } };
505 }
506 if (markingDone) {
507 let version: number | null = null;
508 if (doneBy !== undefined) {
509 version = issueNumber(doneBy, "--done-by");
510 if (version < 1) throw new UsageError("--done-by is a published version, 1 or more");
511 try {
512 await api.show(version, { draft: null });
513 } catch {
514 throw new UsageError(`no version ${version}`);
515 }
516 }
517 await api.issueDone(id, version);
518 return {
519 text: version === null ? `Marked issue ${id} done.` : `Marked issue ${id} done in version ${version}.`,
520 json: { issue: id, done: true, ...(version !== null ? { version } : {}) },
521 };
522 }
523 const page = await api.issue(id);
524 return { text: issuePage(page, api).join("\n"), json: { ...page } };
525}
527export async function runAsk(args: Parsed, env: Env): Promise<Output> {
528 const withdraw = str(args, "withdraw");
529 if (withdraw !== undefined) return withdrawAsk(args, env, withdraw);
530 if (str(args, "note") !== undefined)
531 throw new UsageError('--note goes with --withdraw: abso ask --withdraw <ask> --note "why"');
532 const [of, ...words] = args.positionals;
533 if (of === undefined || words.length === 0)
534 throw new UsageError(
535 '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>',
536 );
537 const { api } = openIssues(env);
538 if (bool(args, "review") && bool(args, "task")) throw new UsageError("an ask is a review or a task, not both");
539 const issue = str(args, "issue");
540 const blocks = str(args, "blocks");
541 const options = str(args, "options");
542 const r = await api.ask({
543 of,
544 question: words.join(" "),
545 ...(issue !== undefined ? { issue: issueNumber(issue, "--issue") } : {}),
546 ...(bool(args, "review") ? { review: true } : {}),
547 ...(bool(args, "task") ? { kind: "task" as const } : {}),
548 ...(str(args, "due") ? { due: str(args, "due")! } : {}),
549 ...(blocks !== undefined ? { blocks: blocks.split(",").map((b) => issueNumber(b.trim(), "--blocks")) } : {}),
550 ...(options !== undefined
551 ? {
552 options: options
553 .split("|")
554 .map((o) => o.trim())
555 .filter((o) => o !== ""),
556 }
557 : {}),
558 });
559 return { text: `Asked ${of} (ask ${r.id}). They hear it; abso waiting shows what's open.`, json: { id: r.id } };
560}
562/** abso ask --withdraw <ask> [--note "why"]: the asker takes an ask back. It closes like an answer, and the one asked hears it. */
563async function withdrawAsk(args: Parsed, env: Env, word: string): Promise<Output> {
564 const others = ["issue", "due", "blocks", "options"].filter((f) => str(args, f) !== undefined);
565 if (args.positionals.length > 0 || others.length > 0 || bool(args, "review") || bool(args, "task"))
566 throw new UsageError('abso ask --withdraw <ask> [--note "why"] takes nothing else: it takes back an ask you made');
567 const id = issueNumber(word, "the ask number");
568 const { api } = openIssues(env);
569 const note = str(args, "note");
570 const r = await api.withdraw(id, note !== undefined ? { note } : {});
571 return { text: `Withdrew ask ${id}. ${r.ask.of} hears it, and it no longer waits on them.`, json: { ask: r.ask } };
572}
574/** One search hit as two lines: the issue, then where it matched and the words around it. */
575export function searchLines(h: IssueSearchHit): string[] {
576 const where = h.meaning ? "by meaning" : h.where === "comment" ? `in comment ${h.comment}` : `in the ${h.where}`;
577 const words = h.snippet
578 .replace(/[\u0001\u0002]/g, "")
579 .replace(/\s+/g, " ")
580 .trim();
581 return [
582 ` ${String(h.issue.id).padStart(3)} ${h.issue.status.padEnd(11)} ${q(h.issue.title)}`,
583 ` ${where}${words && words !== h.issue.title ? `: ${q(words)}` : ""}`,
584 ];
585}
587export async function runSearch(args: Parsed, env: Env): Promise<Output> {
588 const words = args.positionals.join(" ").trim();
589 if (words === "") throw new UsageError('search needs words: abso search "<words>" [--limit <N>]');
590 const limitWord = str(args, "limit");
591 const limit = limitWord === undefined ? undefined : Number(limitWord);
592 if (limit !== undefined && !(Number.isInteger(limit) && limit >= 1 && limit <= 50))
593 throw new UsageError("--limit is a number from 1 to 50");
594 const { api } = openIssues(env);
595 const { hits } = await api.issueSearch(words, limit);
596 return {
597 text:
598 hits.length === 0
599 ? `Nothing matches ${q(words)}.`
600 : [
601 `${plural(hits.length, "issue")} for ${q(words)}, best first:`,
602 ...hits.flatMap(searchLines),
603 "abso issue <N> shows one.",
604 ].join("\n"),
605 json: { hits },
606 };
607}
609export async function runWaiting(args: Parsed, env: Env): Promise<Output> {
610 if (args.positionals.length > 0)
611 throw new UsageError("waiting takes no words: abso waiting [--of <agent or person:id>] [--mine]");
612 const { api, config } = openIssues(env);
613 const mine = bool(args, "mine") || str(args, "of") === config.agent;
614 const of = mine ? config.agent : str(args, "of");
615 const { asks } = mine ? await api.waitingMine() : await api.waiting(of);
616 return {
617 text:
618 asks.length === 0
619 ? `Nothing is waiting${of ? ` on ${of}` : ""}.`
620 : [
621 `${plural(asks.length, "open ask")}${of ? ` of ${of}` : ""}, soonest due first:`,
622 ...asks.map(askLine),
623 'abso answer <ask> "..." answers one asked of you.',
624 ].join("\n"),
625 json: { asks },
626 };
627}
629export async function runAnswer(args: Parsed, env: Env): Promise<Output> {
630 const [first, ...words] = args.positionals;
631 const id = issueNumber(first, "the ask number");
632 const option = str(args, "option");
633 const done = bool(args, "done");
634 if (words.length === 0 && option === undefined && !done)
635 throw new UsageError('abso answer <ask> "<words>" | --option <N> [--note "..."] | --done [--note "..."]');
636 const { api } = openIssues(env);
637 const note = str(args, "note");
638 const r = await api.answer(id, {
639 ...(words.length > 0 ? { words: words.join(" ") } : {}),
640 ...(option !== undefined ? { option: /^\d+$/.test(option) ? Number(option) - 1 : option } : {}),
641 ...(done ? { done: true } : {}),
642 ...(note !== undefined ? { note } : {}),
643 });
644 return { text: `Answered ask ${id}. ${r.ask.by} hears it.`, json: { ask: r.ask } };
645}