- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/issues.test.ts?version=84&format=json
462 linespinch 65% · First import 29% · devops 3% · infra-split 3% · review 1%Last change pinch in version 72, 8 versions changed it
You're reading version 84. The newest is 318, and 5 versions since then changed this file.
1// The Issues commands (#54) as far as the client alone decides them: which
2// Issues Worker a folder talks to, whether the token may go there, the MCP
3// tools, and the usage mistakes refused before any call. The Issues server
4// here is a stand-in that only counts calls; the commands against the real
5// store are issues/test/client-commands.test.ts, on the platform side (abso
6// issue 141).
8import assert from "node:assert/strict";
9import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
10import { createServer, type Server } from "node:http";
11import type { AddressInfo } from "node:net";
12import { tmpdir } from "node:os";
13import { join } from "node:path";
14import { after, before, describe, it } from "node:test";
15import { readConfig, readMachineServers } from "../src/config.ts";
16import { issuesServerFor, tokenGoesTo } from "../src/core.ts";
17import { issuePage, searchLines } from "../src/issues.ts";
18import type { IssuePage } from "../src/issues-wire.ts";
19import { main } from "../src/main.ts";
20import { argvFor, mcpTools } from "../src/mcp.ts";
21import { type Fake, startFake } from "./fake-server.ts";
23const TOKEN = "test-token-not-secret";
25let fake: Fake;
26let issues: Server;
27let issuesUrl: string;
28/** Every call the stand-in Issues server took. */
29const seen: string[] = [];
30/** The bodies of the copy requests it took. */
31const copies: Record<string, unknown>[] = [];
32/** The bodies of the replies it took. */
33const replies: { text: string; question?: boolean }[] = [];
34/** An open ask of fay's from desk with a thread: fay's ack, then a question back, so it waits on desk. */
35const threaded = {
36 id: 7,
37 issue: 3,
38 title: "Sync is slow",
39 by: "desk",
40 of: "fay",
41 kind: "question",
42 question: "Which way?",
43 review: false,
44 due: null,
45 recommendation: null,
46 options: [],
47 blocks: [],
48 at: 0,
49 answer: null,
50 seen: 0,
51 ack: { at: 0, note: "ok, let me check" },
52 replies: [
53 { id: 1, by: "fay", text: "ok, let me check", at: 0 },
54 { id: 2, by: "fay", text: "staging or live?\nlive is 906", at: 0, question: true },
55 ],
56 waitingOn: "desk",
57};
58const dirs: string[] = [];
60before(async () => {
61 fake = await startFake(0, TOKEN);
62 issues = createServer((req, res) => {
63 seen.push(`${req.method} ${req.url}`);
64 const send = (status: number, body: unknown) =>
65 res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
66 if (req.method === "POST" && /\/copy$/.test(req.url ?? "")) {
67 let raw = "";
68 req.on("data", (c: Buffer) => (raw += c.toString("utf8")));
69 req.on("end", () => {
70 const body = JSON.parse(raw) as Record<string, unknown>;
71 copies.push(body);
72 // Issue 403 stands for a live server refusing an agent's copy.
73 if (body.issue === 403 && body.dryRun !== true)
74 return send(403, { error: "copying an issue out of its project takes an owner of that project" });
75 const skipped = { comments: [4], asks: [2] };
76 if (body.dryRun === true)
77 return send(200, {
78 dryRun: true,
79 plan: {
80 from: { project: body.from, issue: body.issue },
81 title: "Sync is slow",
82 edited: ["description"],
83 labels: ["client"],
84 closed: { how: "done" },
85 comments: [{ edited: false }, { edited: true }],
86 asks: [{ edited: false }],
87 skipped,
88 },
89 });
90 send(200, { ok: true, id: 31, from: { project: body.from, issue: body.issue }, skipped });
91 });
92 return;
93 }
94 // An ack answers with the ask, acknowledged and still open.
95 const ack = /\/a\/([^/]+)\/ack\/(\d+)$/.exec(req.url ?? "");
96 if (req.method === "POST" && ack)
97 return send(200, {
98 ask: { id: Number(ack[2]), by: "desk", of: ack[1], answer: null, ack: { at: Date.now(), note: "" } },
99 });
100 // A reply answers with the ask; from the one asked, a question makes it wait on the asker.
101 const reply = /\/a\/([^/]+)\/reply\/(\d+)$/.exec(req.url ?? "");
102 if (req.method === "POST" && reply) {
103 let raw = "";
104 req.on("data", (c: Buffer) => (raw += c.toString("utf8")));
105 req.on("end", () => {
106 const body = JSON.parse(raw) as { text: string; question?: boolean };
107 replies.push(body);
108 send(200, {
109 ask: {
110 id: Number(reply[2]),
111 by: "desk",
112 of: reply[1],
113 answer: null,
114 waitingOn: body.question ? "desk" : reply[1],
115 },
116 });
117 });
118 return;
119 }
120 // One ask with its thread, and the asks an agent sent.
121 const one = /\/ask\/(\d+)$/.exec(req.url ?? "");
122 if (req.method === "GET" && one) return send(200, { ask: { ...threaded, id: Number(one[1]) } });
123 if (req.method === "GET" && /\/a\/[^/]+\/asked$/.test(req.url ?? ""))
124 return send(200, {
125 asks: [
126 threaded,
127 { ...threaded, id: 8, replies: [], answer: { by: "fay", words: "yes", at: 0 }, waitingOn: null },
128 ],
129 });
130 send(500, { error: "a stand-in" });
131 });
132 await new Promise<void>((ok) => issues.listen(0, "127.0.0.1", ok));
133 issuesUrl = `http://127.0.0.1:${(issues.address() as AddressInfo).port}`;
134});
135after(async () => {
136 await fake.close();
137 await new Promise((ok) => issues.close(ok));
138 for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
139});
141const ENV = (): Record<string, string> => ({
142 AVCS_TOKEN: TOKEN,
143 AVCS_HOOK_FORCE: "1",
144 AVCS_ISSUES_SERVER: issuesUrl,
145 AVCS_SERVERS_FILE: "no-servers.json",
146});
148async function avcs(
149 cwd: string,
150 argv: string[],
151 env: Record<string, string> = ENV(),
152): Promise<{ exit: number; out: string }> {
153 const r = await main([...argv, "--json"], { cwd, env, write: () => {} });
154 return { exit: r.exit, out: r.stdout + r.stderr };
155}
157let projects = 0;
158async function folder(agent: string): Promise<string> {
159 const dir = mkdtempSync(join(tmpdir(), "avcs-issues-"));
160 dirs.push(dir);
161 const r = await avcs(dir, ["init", "--server", fake.url, "--project", `issues${++projects}`, "--agent", agent]);
162 assert.equal(r.exit, 0, r.out);
163 return dir;
164}
166describe("issues commands, the client's part (#54)", () => {
167 it("sends the token only to an Issues Worker it trusts", async () => {
168 const dave = await folder("dave");
169 const before = seen.length;
170 const r = await avcs(dave, ["issues"], { ...ENV(), AVCS_ISSUES_SERVER: "https://issues.example.com" });
171 assert.equal(r.exit, 1, r.out);
172 assert.match(r.out, /sends your token only to its own servers and this machine/);
173 assert.equal(seen.length, before);
174 // A server with no Issues Worker beside it, and none named.
175 const { AVCS_ISSUES_SERVER: _, ...without } = ENV();
176 const none = await avcs(dave, ["waiting"], without);
177 assert.notEqual(none.exit, 0);
178 assert.match(
179 none.out,
180 /has no Issues Worker beside it that abso knows; ~\/\.abso\/servers\.json or ABSO_ISSUES_SERVER names one/,
181 );
182 });
184 it("finds a server's Issues Worker in this machine's servers.json, and may send it the token", async () => {
185 const dir = mkdtempSync(join(tmpdir(), "abso-servers-"));
186 dirs.push(dir);
187 const file = join(dir, "servers.json");
188 writeFileSync(file, JSON.stringify({ servers: { [fake.url]: { issues: issuesUrl } } }));
189 const erin = await folder("erin");
190 const before = seen.length;
191 const { AVCS_ISSUES_SERVER: _, ...without } = ENV();
192 await avcs(erin, ["waiting"], { ...without, AVCS_SERVERS_FILE: file });
193 assert.ok(seen.length > before, "the call went to the Issues Worker servers.json names");
194 const machine = readMachineServers({ AVCS_SERVERS_FILE: file });
195 assert.equal(issuesServerFor(fake.url, machine), issuesUrl);
196 assert.equal(issuesServerFor("https://abso.example", machine), undefined);
197 // abso's own server and its Issues Worker are built in.
198 assert.ok(tokenGoesTo("https://api.abso.dev"));
199 assert.ok(tokenGoesTo("https://issues.abso.dev"));
200 assert.equal(issuesServerFor("https://api.abso.dev/"), "https://issues.abso.dev");
201 });
203 it("are MCP tools", () => {
204 const names = mcpTools().map((t) => t.name);
205 for (const n of ["issues", "issue", "search", "ask", "waiting", "answer", "ack", "reply"])
206 assert.ok(names.includes(n), n);
207 assert.deepEqual(argvFor("ask", { args: ["alice", "Which login?"], issue: "3", review: true }), [
208 "ask",
209 "--issue=3",
210 "--review",
211 "--",
212 "alice",
213 "Which login?",
214 ]);
215 });
217 it("refuses usage mistakes before any call", async () => {
218 const erin = await folder("erin");
219 const before = seen.length;
220 for (const argv of [
221 ["issue"],
222 ["issue", "x"],
223 ["ask", "alice"],
224 ["ask", "a", "q", "--review", "--task"],
225 ["answer", "3"],
226 ["issue", "1", "--comment", "a", "--drop"],
227 ["issues", "extra"],
228 ["ask", "--withdraw", "x"],
229 ["ask", "--withdraw", "3", "alice", "q"],
230 ["ask", "--withdraw", "3", "--issue", "2"],
231 ["ask", "--withdraw", "3", "--task"],
232 ["ask", "alice", "q", "--note", "a note without --withdraw"],
233 ["search"],
234 ["search", "words", "--limit", "0"],
235 ["search", "words", "--limit", "51"],
236 ]) {
237 const r = await avcs(erin, argv);
238 assert.equal(r.exit, 1, `${argv.join(" ")}: ${r.out}`);
239 }
240 assert.equal(seen.length, before);
241 });
243 it("shows a search hit as the issue, then where it matched, without the match markers", () => {
244 const issue = { id: 12, title: "Sync is slow", status: "open" as const, updated: 0, labels: [] };
245 assert.deepEqual(
246 searchLines({ issue, where: "comment", comment: 40, snippet: "the \u0001network\u0002 drops mid-sync" }),
247 [' 12 open "Sync is slow"', ' in comment 40: "the network drops mid-sync"'],
248 );
249 assert.deepEqual(searchLines({ issue, where: "description", snippet: "Pages load late.", meaning: true }), [
250 ' 12 open "Sync is slow"',
251 ' by meaning: "Pages load late."',
252 ]);
253 assert.deepEqual(searchLines({ issue, where: "title", snippet: "Sync is slow" })[1], " in the title");
254 });
256 it("withdraw is one POST to the asker's own withdraw/<ask> route", async () => {
257 const erin = await folder("erin");
258 const before = seen.length;
259 await avcs(erin, ["ask", "--withdraw", "#3", "--note", "overtaken by later decisions"]);
260 const posts = seen.slice(before).filter((s) => s.startsWith("POST"));
261 assert.equal(posts.length, 1, posts.join("\n"));
262 assert.match(posts[0]!, /^POST \/p\/issues\d+\/a\/erin\/withdraw\/3$/);
263 });
265 it("ack is one POST to the one asked's ack/<ask> route, and says the ask stays open", async () => {
266 const fay = await folder("fay");
267 const before = seen.length;
268 const r = await main(["ack", "7", "on it after the deploy"], { cwd: fay, env: ENV(), write: () => {} });
269 assert.equal(r.exit, 0, r.stdout + r.stderr);
270 assert.equal(
271 r.stdout,
272 'Acknowledged ask 7. desk hears it; abso reply 7 "..." adds more as you go, and the ask stays open until abso answer 7 "...".\n',
273 );
274 const posts = seen.slice(before).filter((s) => s.startsWith("POST"));
275 assert.deepEqual(posts.length, 1, posts.join("\n"));
276 assert.match(posts[0]!, /^POST \/p\/issues\d+\/a\/fay\/ack\/7$/);
277 assert.equal((await main(["ack"], { cwd: fay, env: ENV(), write: () => {} })).exit, 1);
278 });
280 it("reply is one POST to reply/<ask> with the words, and says whose turn it is", async () => {
281 const fay = await folder("fay");
282 const before = seen.length;
283 const r = await main(["reply", "7", "staging or live?", "--question"], { cwd: fay, env: ENV(), write: () => {} });
284 assert.equal(r.exit, 0, r.stdout + r.stderr);
285 const posts = seen.slice(before).filter((s) => s.startsWith("POST"));
286 assert.equal(posts.length, 1, posts.join("\n"));
287 assert.match(posts[0]!, /^POST \/p\/issues\d+\/a\/fay\/reply\/7$/);
288 assert.deepEqual(replies.at(-1), { text: "staging or live?", question: true });
289 assert.equal(r.stdout, "Replied on ask 7. desk hears it. It waits on desk.\n");
290 assert.equal((await main(["reply", "7"], { cwd: fay, env: ENV(), write: () => {} })).exit, 1);
291 });
293 it("ask <N> reads one ask with its whole thread, oldest first, and whose turn it is", async () => {
294 const fay = await folder("fay");
295 const before = seen.length;
296 const r = await main(["ask", "7"], { cwd: fay, env: ENV(), write: () => {} });
297 assert.equal(r.exit, 0, r.stdout + r.stderr);
298 assert.match(seen.slice(before).join("\n"), /^GET \/p\/issues\d+\/ask\/7$/m);
299 assert.match(
300 r.stdout,
301 /^ {2}ask 7: desk, .* asks fay a question on issue 3 \("Sync is slow"\) \(2 replies; waiting on desk\): "Which way\?"$/m,
302 );
303 const ack = r.stdout.indexOf(' fay, Jan 1 1970 00:00 UTC: "ok, let me check"');
304 const back = r.stdout.indexOf(' fay, Jan 1 1970 00:00 UTC, a question: "staging or live?\\nlive is 906"');
305 assert.ok(ack > 0 && back > ack, r.stdout);
306 assert.match(
307 r.stdout,
308 /^It waits on desk\. abso reply 7 "\.\.\." adds to it; abso answer 7 "\.\.\." answers and closes it\.$/m,
309 );
310 // The asker reads it as their turn, and can't answer it.
311 const desk = await folder("desk");
312 const d = await main(["ask", "7"], { cwd: desk, env: ENV(), write: () => {} });
313 assert.match(d.stdout, /^It waits on you\. abso reply 7 "\.\.\." adds to it\.$/m);
314 });
316 it("waiting --asked lists the asks you sent, open first, then the latest answered", async () => {
317 const fay = await folder("fay");
318 const before = seen.length;
319 const r = await main(["waiting", "--asked"], { cwd: fay, env: ENV(), write: () => {} });
320 assert.equal(r.exit, 0, r.stdout + r.stderr);
321 assert.match(seen.slice(before).join("\n"), /^GET \/p\/issues\d+\/a\/fay\/asked$/m);
322 assert.match(r.stdout, /^1 open ask you sent:$/m);
323 assert.match(r.stdout, /^ {4}last: fay, .*, a question: "staging or live\? \.\.\."$/m);
324 assert.ok(r.stdout.indexOf("ask 7:") < r.stdout.indexOf("The latest answered:"), r.stdout);
325 assert.ok(r.stdout.indexOf("The latest answered:") < r.stdout.indexOf("ask 8:"), r.stdout);
326 assert.match(r.stdout, /^ {4}answer: "yes"$/m);
327 });
329 it("an acknowledged ask reads as acknowledged, not answered, with the note under it", () => {
330 const ask = {
331 id: 7,
332 issue: 3,
333 by: "desk",
334 of: "fay",
335 kind: "question",
336 question: "Which way?",
337 review: false,
338 due: null,
339 recommendation: null,
340 options: [],
341 blocks: [],
342 at: 0,
343 answer: null,
344 seen: 0,
345 ack: { at: 0, note: "on it after the deploy" },
346 };
347 const page = {
348 issue: {
349 id: 3,
350 title: "t",
351 status: "blocked",
352 parent: null,
353 opened: { by: "desk", at: 0 },
354 agent: null,
355 agents: [],
356 blockedBy: [],
357 labels: [],
358 versions: [],
359 waitingOn: ["fay"],
360 closed: null,
361 description: "",
362 lines: null,
363 watchers: [],
364 },
365 comments: [],
366 edits: [],
367 asks: [ask],
368 claims: [],
369 children: [],
370 } as unknown as IssuePage;
371 const text = issuePage(page).join("\n");
372 assert.match(
373 text,
374 /\n {2}ask 7: desk, [^\n]*asks fay a question on issue 3 \(acknowledged [^;)]+, not answered yet\): "Which way\?"\n {4}fay acknowledged: "on it after the deploy"/,
375 );
376 assert.doesNotMatch(text, /answer:/);
377 const answered = { ...ask, answer: { by: "fay", words: "This way", at: 0 } };
378 const later = issuePage({ ...page, asks: [answered] } as unknown as IssuePage).join("\n");
379 assert.doesNotMatch(later, /acknowledged/, "an answer replaces the ack");
380 });
381});
383describe("abso issue <N> --copy-to <project>", () => {
384 const text = async (cwd: string, argv: string[]) => {
385 const r = await main(argv, { cwd, env: ENV(), write: () => {} });
386 return { exit: r.exit, out: r.stdout + r.stderr };
387 };
389 it("a dry run asks the other project's copy route for the plan, and says nothing was written", async () => {
390 const gil = await folder("gil");
391 const before = seen.length;
392 const r = await text(gil, ["issue", "12", "--copy-to", "core", "--dry-run"]);
393 assert.equal(r.exit, 0, r.out);
394 assert.deepEqual(seen.slice(before), ["POST /p/core/a/gil/copy"]);
395 const from = (copies.at(-1) as { from: string }).from;
396 assert.match(from, /^issues\d+$/);
397 assert.deepEqual(copies.at(-1), { from, issue: 12, dryRun: true });
398 assert.equal(
399 r.out.trimEnd(),
400 [
401 `A dry run: nothing was written. Copying ${from} issue 12 into core would make:`,
402 ` "Sync is slow", done (description edited when copied)`,
403 " 2 comments (1 edited), 1 answered ask, labelled client",
404 " not copied: comments 4; asks 2 (open asks, and what --clean left out)",
405 "Run it again without --dry-run to copy it.",
406 ].join("\n"),
407 );
408 });
410 it("copies with the cleaned texts --clean gives, by source id", async () => {
411 const gil = await folder("gil");
412 writeFileSync(
413 join(gil, "clean.json"),
414 JSON.stringify({ description: "Cleaned.", comments: [{ id: 1 }, { id: 3, text: "Cleaned too." }] }),
415 );
416 const r = await text(gil, ["issue", "12", "--copy-to", "core", "--clean", "clean.json"]);
417 assert.equal(r.exit, 0, r.out);
418 const from = (copies.at(-1) as { from: string }).from;
419 assert.deepEqual(copies.at(-1), {
420 description: "Cleaned.",
421 comments: [{ id: 1 }, { id: 3, text: "Cleaned too." }],
422 from,
423 issue: 12,
424 });
425 assert.match(
426 r.out,
427 new RegExp(`^Copied ${from} issue 12 to core issue 31\\. Its comments and asks keep their authors`),
428 );
429 });
431 it("says a dry run still works when the server refuses the copy", async () => {
432 const gil = await folder("gil");
433 const r = await text(gil, ["issue", "403", "--copy-to", "core"]);
434 assert.equal(r.exit, 1, r.out);
435 assert.match(r.out, /takes an owner of that project\. --dry-run still shows what would go\./);
436 });
438 it("refuses mistakes before any call", async () => {
439 const gil = await folder("gil");
440 writeFileSync(join(gil, "bad.json"), JSON.stringify({ from: "elsewhere" }));
441 const before = seen.length;
442 for (const [argv, why] of [
443 [["issue", "12", "--copy-to", "core", "--comment", "x"], /--copy-to goes alone .* not with --comment/],
444 [["issue", "12", "--dry-run"], /--clean and --dry-run go with --copy-to <project>/],
445 [["issue", "12", "--copy-to", "core", "--clean", "nope.json"], /--clean nope\.json: no such file/],
446 [
447 ["issue", "12", "--copy-to", "core", "--clean", "bad.json"],
448 /from isn't one of title, description, comments, asks/,
449 ],
450 ] as const) {
451 const r = await text(gil, [...argv]);
452 assert.notEqual(r.exit, 0, argv.join(" "));
453 assert.match(r.out, why);
454 }
455 const { project } = readConfig(gil);
456 assert.match(
457 (await text(gil, ["issue", "12", "--copy-to", project])).out,
458 /issue 12 is already in issues\d+; --copy-to names another project/,
459 );
460 assert.equal(seen.length, before, "nothing reached the Issues server");
461 });
462});