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=23&format=json
639 linesFirst import 64% · pinch 23% · devops 5% · review 4% · infra-split 3%Last change pinch in version 23, 7 versions changed it

You're reading version 23. The newest is 318, and 15 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// 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).
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 { 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 };
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("#", ""));
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("; ")})` : ""}`;
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");
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"})`;
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());
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 !== "");
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;
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`;
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 ?? []).map(
164 (a) => `${indent}attached ${a.id}: ${q(a.name)}, ${sizeText(a.size)}${api ? `, ${api.attachmentUrl(a.id)}` : ""}`,
165 );
168/** An issue's page, as text. */
169export function issuePage(p: IssuePage, api?: Pick<Api, "attachmentUrl">): string[] {
170 const i = p.issue;
171 const facts = [
172 i.parent !== null ? `Under issue ${i.parent}.` : "",
173 `Opened by ${i.opened.by}, ${shortWhen(i.opened.at)}.`,
174 i.agent !== null ? `Agent: ${i.agent}.` : "",
175 i.agents.length > 0 ? `Working on it: ${i.agents.join(", ")}.` : "",
176 i.blockedBy.length > 0 ? `Blocked by: issue${i.blockedBy.length === 1 ? "" : "s"} ${i.blockedBy.join(", ")}.` : "",
177 (i.labels ?? []).length > 0 ? `Labels: ${i.labels.join(", ")}.` : "",
178 i.versions.length > 0 ? `Versions: ${i.versions.join(", ")}.` : "",
179 i.waitingOn.length > 0 ? `Waiting on: ${i.waitingOn.join(", ")}.` : "",
180 i.closed
181 ? `${i.closed.how === "done" ? "Done" : "Dropped"} by ${i.closed.by}${i.closed.version !== null ? ` in version ${i.closed.version}` : ""}, ${shortWhen(i.closed.at)}.`
182 : "",
183 ].filter((f) => f !== "");
184 return [
185 `Issue ${i.id}: ${q(i.title)} [${i.status}]`,
186 facts.join(" "),
187 ...(i.lines ? [`From ${i.lines.file} lines ${i.lines.from}-${i.lines.to} at version ${i.lines.version}.`] : []),
188 ...(i.description !== "" ? ["", ...i.description.split("\n").map((l) => ` ${l}`)] : []),
189 ...attachmentLines(api, i.attachments, " "),
190 ...(p.asks.length > 0 ? ["", "Asks:", ...p.asks.map(askLine)] : []),
191 ...(p.comments.length > 0
192 ? [
193 "",
194 "Comments:",
195 ...p.comments.flatMap((c) => [
196 ` ${c.by}${c.kind === "objection" ? " objects" : ""}, ${shortWhen(c.at)}: ${q(c.text)}`,
197 ...attachmentLines(api, c.attachments, " "),
198 ]),
199 ]
200 : []),
201 ...((p.edits ?? []).length > 0 ? ["", "Edits:", ...p.edits.map(editLine)] : []),
202 ...(p.children.length > 0 ? ["", "Sub-issues:", ...p.children.map(issueLine)] : []),
203 ...((i.watchers ?? []).length > 0 ? ["", `Watchers: ${i.watchers.join(", ")}.`] : []),
204 "",
205 `abso start "..." --issue ${i.id} starts on it; abso issue ${i.id} --comment "..." comments; abso ask <who> "..." --issue ${i.id} asks.`,
206 ];
209export async function runIssues(args: Parsed, env: Env): Promise<Output> {
210 if (args.positionals.length > 0)
211 throw new UsageError(
212 "issues takes no words: abso issues [--open] [--status <s>] [--agent <a>] [--parent <N>] [--label <l,l>] | abso issues --labels; abso issue <N> shows one",
213 );
214 const { api } = openIssues(env);
215 if (bool(args, "drafts")) {
216 const { drafts } = await api.drafts();
217 return {
218 text:
219 drafts.length === 0
220 ? 'No drafts. abso issue draft "<title>" saves one: only you see it, and nobody hears of it.'
221 : [
222 `${plural(drafts.length, "draft")}, newest first (only you see them):`,
223 ...drafts.map(draftLine),
224 "abso issue draft <D> --open opens one as an issue; --delete deletes it.",
225 ].join("\n"),
226 json: { drafts },
227 };
228 }
229 if (bool(args, "labels")) {
230 const { labels } = await api.issueLabels();
231 return {
232 text:
233 labels.length === 0
234 ? 'No labels yet. abso issue new "<title>" --label friction labels a new issue; abso issue <N> --label <l> labels one.'
235 : [
236 `${plural(labels.length, "label")} in use:`,
237 ...labels.map((l) => ` ${l.label}: ${l.open} open of ${l.total}`),
238 "abso issues --label <label> lists a label's issues.",
239 ].join("\n"),
240 json: { labels },
241 };
242 }
243 const parent = str(args, "parent");
244 const filter = {
245 ...(str(args, "status") ? { status: str(args, "status")! } : {}),
246 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
247 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
248 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
249 open: bool(args, "open"),
250 };
251 const { issues } = await api.issues(filter);
252 const scope = [
253 filter.open ? "open " : "",
254 filter.status ? `${filter.status} ` : "",
255 filter.labels ? `${filter.labels.join(", ")} ` : "",
256 ].join("");
257 return {
258 text:
259 issues.length === 0
260 ? `No ${scope}issues${filter.agent ? ` for ${filter.agent}` : ""}${parent !== undefined ? ` under ${parent}` : ""}. abso issue new "<title>" opens one.`
261 : [
262 `${plural(issues.length, `${scope}issue`)}, most recently updated first:`,
263 ...issues.map(issueLine),
264 "abso issue <N> shows one.",
265 ].join("\n"),
266 json: { issues },
267 };
270/** A new issue's fields from the command line, as open and drafts take them; `title` only when words were given. */
271function openFields(args: Parsed, title: string): DraftBody {
272 const lines = str(args, "lines");
273 const at = lines === undefined ? undefined : /^(.+):(\d+)(?:-(\d+))?@(\d+)$/.exec(lines);
274 if (lines !== undefined && !at)
275 throw new UsageError("--lines is <file>:<from>-<to>@<version>, like src/a.ts:10-14@140");
276 const parent = str(args, "parent");
277 return {
278 ...(title !== "" ? { title } : {}),
279 ...(str(args, "description") ? { description: str(args, "description")! } : {}),
280 ...(parent !== undefined ? { parent: issueNumber(parent, "--parent") } : {}),
281 ...(at ? { lines: { file: at[1]!, from: Number(at[2]), to: Number(at[3] ?? at[2]), version: Number(at[4]) } } : {}),
282 ...(str(args, "agent") ? { agent: str(args, "agent")! } : {}),
283 ...(str(args, "blocked-by") !== undefined
284 ? { blockedBy: listOf(str(args, "blocked-by")!).map((b) => issueNumber(b, "--blocked-by")) }
285 : {}),
286 ...(str(args, "notify") !== undefined ? { notify: listOf(str(args, "notify")!) } : {}),
287 ...(str(args, "label") !== undefined ? { labels: labelList(str(args, "label")!) } : {}),
288 };
291/** One draft as a line: its number, title, and what else it holds. */
292function draftLine(d: Draft): string {
293 const b = d.body;
294 const more = [
295 b.agent ? `for ${b.agent}` : "",
296 b.parent ? `under ${b.parent}` : "",
297 (b.labels ?? []).length > 0 ? `labels ${b.labels!.join(", ")}` : "",
298 b.description ? "a description" : "",
299 ].filter((m) => m !== "");
300 return ` draft ${d.id}: ${b.title ? q(b.title) : "(no title yet)"}${more.length > 0 ? ` (${more.join("; ")})` : ""}, saved ${shortWhen(d.saved)}`;
303/**
304 * Drafts (abso issue 3): an issue not opened yet, this agent's alone, with no
305 * number and no news. `abso issue draft "<title>" [fields]` saves a new one;
306 * `abso issue draft <D> [fields]` changes one; --open opens it as an issue;
307 * --delete deletes it. `abso issues --drafts` lists them.
308 */
309async function runDraft(api: Api, args: Parsed, words: string[]): Promise<Output> {
310 const [d, ...more] = words;
311 if (d !== undefined && /^\d+$/.test(d) && more.length === 0) {
312 const id = Number(d);
313 if (bool(args, "delete") && bool(args, "open")) throw new UsageError("--open or --delete, not both");
314 if (bool(args, "delete")) {
315 await api.deleteDraft(id);
316 return { text: `Deleted draft ${id}.`, json: { draft: id, deleted: true } };
317 }
318 if (bool(args, "open")) {
319 const r = await api.openDraft(id, openFields(args, ""));
320 return {
321 text: `Opened draft ${id} as issue ${r.id}. abso start "..." --issue ${r.id} starts on it.`,
322 json: { draft: id, id: r.id },
323 };
324 }
325 // Saving replaces the draft's body, so the fields given go over what it holds.
326 const found = (await api.drafts()).drafts.find((x) => x.id === id);
327 if (!found) throw new UsageError(`you have no draft ${id}; abso issues --drafts lists yours`);
328 await api.saveDraft({ ...found.body, ...openFields(args, ""), id });
329 return { text: `Saved draft ${id}.`, json: { draft: id } };
330 }
331 if (bool(args, "open") || bool(args, "delete"))
332 throw new UsageError("--open and --delete take a draft's number: abso issue draft <D> --open");
333 const r = await api.saveDraft(openFields(args, words.join(" ")));
334 return {
335 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.`,
336 json: { draft: r.id },
337 };
340/** The flags --copy-to goes with: anything else on the same command is refused, so a copy is never half an edit. */
341const COPY_FLAGS = new Set(["copy-to", "clean", "dry-run"]);
343/** abso issue <N> --copy-to <project>: the server reads the issue and writes the copy. */
344async function runCopy(api: Api, id: number, to: string, args: Parsed, env: Env): Promise<Output> {
345 const other = [...args.flags.keys()].filter((f) => !COPY_FLAGS.has(f) && f !== "json");
346 if (other.length > 0)
347 throw new UsageError(`--copy-to goes alone (with --clean and --dry-run), not with --${other[0]}`);
348 if (to === api.config.project)
349 throw new UsageError(`issue ${id} is already in ${to}; --copy-to names another project`);
350 const clean = str(args, "clean");
351 const texts = clean === undefined ? {} : readClean(resolve(env.cwd, clean), clean);
352 const dryRun = bool(args, "dry-run");
353 const from = api.config.project;
354 let answer: CopyAnswer;
355 try {
356 answer = await api.issueCopy(to, { ...texts, from, issue: id, ...(dryRun ? { dryRun: true } : {}) });
357 } catch (e) {
358 if (e instanceof ApiError && e.status === 403 && !dryRun)
359 throw new ApiError(`${e.message}. --dry-run still shows what would go.`, e.status);
360 throw e;
361 }
362 if ("dryRun" in answer) {
363 const p = answer.plan;
364 const edited = (list: { edited: boolean }[]) => list.filter((x) => x.edited).length;
365 const lines = [
366 `A dry run: nothing was written. Copying ${from} issue ${id} into ${to} would make:`,
367 ` ${q(p.title)}${p.closed ? `, ${p.closed.how}` : ""}${p.edited.length > 0 ? ` (${p.edited.join(" and ")} edited when copied)` : ""}`,
368 ` ${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(", ")}` : ""}`,
369 ...skippedLines(p.skipped),
370 `Run it again without --dry-run to copy it.`,
371 ];
372 return { text: lines.join("\n"), json: answer };
373 }
374 return {
375 text: [
376 `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.`,
377 ...skippedLines(answer.skipped),
378 ].join("\n"),
379 json: answer,
380 };
383function skippedLines(skipped: { comments: number[]; asks: number[] }): string[] {
384 const parts = [
385 ...(skipped.comments.length > 0 ? [`comments ${skipped.comments.join(", ")}`] : []),
386 ...(skipped.asks.length > 0 ? [`asks ${skipped.asks.join(", ")}`] : []),
387 ];
388 return parts.length > 0 ? [` not copied: ${parts.join("; ")} (open asks, and what --clean left out)`] : [];
391/** --clean's file: cleaned texts by source id. The server checks each id against the issue it reads. */
392function readClean(path: string, given: string): Omit<CopyBody, "from" | "issue"> {
393 let raw: unknown;
394 try {
395 raw = JSON.parse(readFileSync(path, "utf8"));
396 } catch (e) {
397 throw new UsageError(
398 `--clean ${given}: ${(e as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`,
399 );
400 }
401 if (typeof raw !== "object" || raw === null || Array.isArray(raw))
402 throw new UsageError(`--clean ${given}: a JSON object with title, description, comments or asks`);
403 const known = new Set(["title", "description", "comments", "asks"]);
404 const unknown = Object.keys(raw).filter((k) => !known.has(k));
405 if (unknown.length > 0)
406 throw new UsageError(`--clean ${given}: ${unknown[0]} isn't one of title, description, comments, asks`);
407 return raw as Omit<CopyBody, "from" | "issue">;
410export async function runIssue(args: Parsed, env: Env): Promise<Output> {
411 const [first, ...rest] = args.positionals;
412 const { api } = openIssues(env);
413 if (first === "draft") return runDraft(api, args, rest);
414 if (first === "new") {
415 if (rest.length === 0)
416 throw new UsageError(
417 'abso issue new "<title>" [--description "..."] [--parent <N>] [--lines <file>:<from>-<to>@<version>] [--agent <agent>] [--blocked-by <N,N>] [--notify <who,who>] [--label <l,l>]',
418 );
419 const fields = { ...openFields(args, rest.join(" ")), title: rest.join(" ") };
420 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
421 const r = await api.issueOpen({ ...fields, ...(attachments.length > 0 ? { attachments } : {}) });
422 return {
423 text: `Opened issue ${r.id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. abso start "..." --issue ${r.id} starts on it.`,
424 json: { id: r.id, ...(attachments.length > 0 ? { attachments } : {}) },
425 };
426 }
427 if (first === undefined || rest.length > 0)
428 throw new UsageError(
429 'abso issue <N> [--comment "..." | --object "..." | --drop | --reopen | --done [--done-by <version>] | an edit], or abso issue new "<title>"',
430 );
431 const id = issueNumber(first);
432 const copyTo = str(args, "copy-to");
433 if (copyTo !== undefined) return runCopy(api, id, copyTo, args, env);
434 if (str(args, "clean") !== undefined || bool(args, "dry-run"))
435 throw new UsageError("--clean and --dry-run go with --copy-to <project>");
436 const comment = str(args, "comment");
437 const object = str(args, "object");
438 const doneBy = str(args, "done-by");
439 const markingDone = bool(args, "done") || doneBy !== undefined;
440 const edits = ["title", "description", "parent", "agent", "blocked-by", "label", "unlabel"].filter(
441 (f) => str(args, f) !== undefined,
442 );
443 if (
444 [
445 comment !== undefined,
446 object !== undefined,
447 bool(args, "drop"),
448 bool(args, "reopen"),
449 markingDone,
450 edits.length > 0,
451 ].filter(Boolean).length > 1
452 )
453 throw new UsageError("one of --comment, --object, --drop, --reopen, --done or an edit at a time");
454 if (edits.length > 0) {
455 const parent = str(args, "parent");
456 const agent = str(args, "agent");
457 const blockedBy = str(args, "blocked-by");
458 const r = await api.issueEdit(id, {
459 ...(str(args, "title") !== undefined ? { title: str(args, "title")! } : {}),
460 ...(str(args, "description") !== undefined ? { description: str(args, "description")! } : {}),
461 ...(parent !== undefined ? { parent: parent === "none" ? null : issueNumber(parent, "--parent") } : {}),
462 ...(agent !== undefined ? { agent: agent === "none" ? null : agent } : {}),
463 ...(blockedBy !== undefined ? { blockedBy: listOf(blockedBy).map((b) => issueNumber(b, "--blocked-by")) } : {}),
464 ...(bool(args, "quiet") ? { notify: false } : {}),
465 ...(str(args, "notify") !== undefined ? { also: listOf(str(args, "notify")!) } : {}),
466 ...(str(args, "label") !== undefined ? { addLabels: labelList(str(args, "label")!) } : {}),
467 ...(str(args, "unlabel") !== undefined ? { removeLabels: labelList(str(args, "unlabel")!) } : {}),
468 // A labels-only edit tells nobody unless --notify names people.
469 ...(edits.every((f) => f === "label" || f === "unlabel") && str(args, "notify") !== undefined
470 ? { notify: true }
471 : {}),
472 });
473 return {
474 text: `Edited issue ${id}. ${r.notified.length > 0 ? `Told ${r.notified.join(", ")}.` : "Told nobody."}`,
475 json: { issue: id, edit: r.edit, notified: r.notified },
476 };
477 }
478 if (bool(args, "quiet") || str(args, "notify") !== undefined)
479 throw new UsageError(
480 "--quiet and --notify go with an edit (--title, --description, --parent, --agent, --blocked-by, --label or --unlabel)",
481 );
482 if (str(args, "attach") !== undefined && comment === undefined && object === undefined)
483 throw new UsageError("--attach goes with abso issue new or --comment (or --object)");
484 if (comment !== undefined || object !== undefined) {
485 const attachments = await uploadAttachments(api, env.cwd, str(args, "attach"));
486 const r = await api.issueComment(id, (comment ?? object)!, object !== undefined, attachments);
487 return {
488 text: `${object !== undefined ? "Objected" : "Commented"} on issue ${id}${attachments.length > 0 ? ` with ${plural(attachments.length, "attachment")} (${attachments.join(", ")})` : ""}. Its agents hear it.`,
489 json: { id: r.id, issue: id, ...(attachments.length > 0 ? { attachments } : {}) },
490 };
491 }
492 if (bool(args, "drop")) {
493 await api.issueDrop(id);
494 return { text: `Dropped issue ${id}.`, json: { issue: id, dropped: true } };
495 }
496 if (bool(args, "reopen")) {
497 await api.issueReopen(id);
498 return { text: `Reopened issue ${id}.`, json: { issue: id, reopened: true } };
499 }
500 if (markingDone) {
501 let version: number | null = null;
502 if (doneBy !== undefined) {
503 version = issueNumber(doneBy, "--done-by");
504 if (version < 1) throw new UsageError("--done-by is a published version, 1 or more");
505 try {
506 await api.show(version, { draft: null });
507 } catch {
508 throw new UsageError(`no version ${version}`);
509 }
510 }
511 await api.issueDone(id, version);
512 return {
513 text: version === null ? `Marked issue ${id} done.` : `Marked issue ${id} done in version ${version}.`,
514 json: { issue: id, done: true, ...(version !== null ? { version } : {}) },
515 };
516 }
517 const page = await api.issue(id);
518 return { text: issuePage(page, api).join("\n"), json: { ...page } };
521export async function runAsk(args: Parsed, env: Env): Promise<Output> {
522 const withdraw = str(args, "withdraw");
523 if (withdraw !== undefined) return withdrawAsk(args, env, withdraw);
524 if (str(args, "note") !== undefined)
525 throw new UsageError('--note goes with --withdraw: abso ask --withdraw <ask> --note "why"');
526 const [of, ...words] = args.positionals;
527 if (of === undefined || words.length === 0)
528 throw new UsageError(
529 '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>',
530 );
531 const { api } = openIssues(env);
532 if (bool(args, "review") && bool(args, "task")) throw new UsageError("an ask is a review or a task, not both");
533 const issue = str(args, "issue");
534 const blocks = str(args, "blocks");
535 const options = str(args, "options");
536 const r = await api.ask({
537 of,
538 question: words.join(" "),
539 ...(issue !== undefined ? { issue: issueNumber(issue, "--issue") } : {}),
540 ...(bool(args, "review") ? { review: true } : {}),
541 ...(bool(args, "task") ? { kind: "task" as const } : {}),
542 ...(str(args, "due") ? { due: str(args, "due")! } : {}),
543 ...(blocks !== undefined ? { blocks: blocks.split(",").map((b) => issueNumber(b.trim(), "--blocks")) } : {}),
544 ...(options !== undefined
545 ? {
546 options: options
547 .split("|")
548 .map((o) => o.trim())
549 .filter((o) => o !== ""),
550 }
551 : {}),
552 });
553 return { text: `Asked ${of} (ask ${r.id}). They hear it; abso waiting shows what's open.`, json: { id: r.id } };
556/** abso ask --withdraw <ask> [--note "why"]: the asker takes an ask back. It closes like an answer, and the one asked hears it. */
557async function withdrawAsk(args: Parsed, env: Env, word: string): Promise<Output> {
558 const others = ["issue", "due", "blocks", "options"].filter((f) => str(args, f) !== undefined);
559 if (args.positionals.length > 0 || others.length > 0 || bool(args, "review") || bool(args, "task"))
560 throw new UsageError('abso ask --withdraw <ask> [--note "why"] takes nothing else: it takes back an ask you made');
561 const id = issueNumber(word, "the ask number");
562 const { api } = openIssues(env);
563 const note = str(args, "note");
564 const r = await api.withdraw(id, note !== undefined ? { note } : {});
565 return { text: `Withdrew ask ${id}. ${r.ask.of} hears it, and it no longer waits on them.`, json: { ask: r.ask } };
568/** One search hit as two lines: the issue, then where it matched and the words around it. */
569export function searchLines(h: IssueSearchHit): string[] {
570 const where = h.meaning ? "by meaning" : h.where === "comment" ? `in comment ${h.comment}` : `in the ${h.where}`;
571 const words = h.snippet
572 .replace(/[\u0001\u0002]/g, "")
573 .replace(/\s+/g, " ")
574 .trim();
575 return [
576 ` ${String(h.issue.id).padStart(3)} ${h.issue.status.padEnd(11)} ${q(h.issue.title)}`,
577 ` ${where}${words && words !== h.issue.title ? `: ${q(words)}` : ""}`,
578 ];
581export async function runSearch(args: Parsed, env: Env): Promise<Output> {
582 const words = args.positionals.join(" ").trim();
583 if (words === "") throw new UsageError('search needs words: abso search "<words>" [--limit <N>]');
584 const limitWord = str(args, "limit");
585 const limit = limitWord === undefined ? undefined : Number(limitWord);
586 if (limit !== undefined && !(Number.isInteger(limit) && limit >= 1 && limit <= 50))
587 throw new UsageError("--limit is a number from 1 to 50");
588 const { api } = openIssues(env);
589 const { hits } = await api.issueSearch(words, limit);
590 return {
591 text:
592 hits.length === 0
593 ? `Nothing matches ${q(words)}.`
594 : [
595 `${plural(hits.length, "issue")} for ${q(words)}, best first:`,
596 ...hits.flatMap(searchLines),
597 "abso issue <N> shows one.",
598 ].join("\n"),
599 json: { hits },
600 };
603export async function runWaiting(args: Parsed, env: Env): Promise<Output> {
604 if (args.positionals.length > 0)
605 throw new UsageError("waiting takes no words: abso waiting [--of <agent or person:id>] [--mine]");
606 const { api, config } = openIssues(env);
607 const mine = bool(args, "mine") || str(args, "of") === config.agent;
608 const of = mine ? config.agent : str(args, "of");
609 const { asks } = mine ? await api.waitingMine() : await api.waiting(of);
610 return {
611 text:
612 asks.length === 0
613 ? `Nothing is waiting${of ? ` on ${of}` : ""}.`
614 : [
615 `${plural(asks.length, "open ask")}${of ? ` of ${of}` : ""}, soonest due first:`,
616 ...asks.map(askLine),
617 'abso answer <ask> "..." answers one asked of you.',
618 ].join("\n"),
619 json: { asks },
620 };
623export async function runAnswer(args: Parsed, env: Env): Promise<Output> {
624 const [first, ...words] = args.positionals;
625 const id = issueNumber(first, "the ask number");
626 const option = str(args, "option");
627 const done = bool(args, "done");
628 if (words.length === 0 && option === undefined && !done)
629 throw new UsageError('abso answer <ask> "<words>" | --option <N> [--note "..."] | --done [--note "..."]');
630 const { api } = openIssues(env);
631 const note = str(args, "note");
632 const r = await api.answer(id, {
633 ...(words.length > 0 ? { words: words.join(" ") } : {}),
634 ...(option !== undefined ? { option: /^\d+$/.test(option) ? Number(option) - 1 : option } : {}),
635 ...(done ? { done: true } : {}),
636 ...(note !== undefined ? { note } : {}),
637 });
638 return { text: `Answered ask ${id}. ${r.ask.by} hears it.`, json: { ask: r.ask } };