Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=28&format=json
646 linesFirst import 63% · pinch 24% · devops 5% · review 5% · infra-split 3%Last change review in version 27, 9 versions changed it

You're reading version 28. The newest is 318, and 13 versions since then changed this file. Go to the newestCompare with 318

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