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=35&format=json
741 linesFirst import 54% · pinch 35% · devops 5% · review 4% · infra-split 2%Last change pinch in version 35, 11 versions changed it

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