The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,124 lines 37.7 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- Builds the zip Azure returns and stands in for az writing it.
2 import * as NodeFS from "node:fs";
3 import * as NodeZlib from "node:zlib";
4
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { afterEach, assert, expect, it, vi } from "@effect/vitest";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import { ChildProcessSpawner } from "effect/process";
10
11 import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
12 import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
13 import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
14
15 const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
16
17 const layer = it.layer(
18 AzureDevOpsPullRequestCli.layer.pipe(
19 Layer.provide(
20 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
21 execute: mockedExecute,
22 }),
23 ),
24 Layer.provide(NodeServices.layer),
25 ),
26 );
27
28 function output(stdout: string) {
29 return {
30 exitCode: ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35 };
36 }
37
38 const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
39
40 function outputWithin(maxOutputBytes: number | undefined, response: string) {
41 const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;
42 return ceiling >= Buffer.byteLength(response)
43 ? output(response)
44 : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };
45 }
46
47 const json = (value: Record<string, unknown>) => JSON.stringify(value);
48
49 const pullRequestRow = {
50 pullRequestId: 42,
51 title: "Add the page",
52 status: "active",
53 sourceRefName: "refs/heads/feat/page",
54 targetRefName: "refs/heads/main",
55 creationDate: "2026-07-01T00:00:00Z",
56 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
57 repository: { name: "web", project: { name: "platform" } },
58 };
59
60 const oneIteration = {
61 value: [
62 {
63 id: 1,
64 sourceRefCommit: { commitId: "a".repeat(40) },
65 commonRefCommit: { commitId: "b".repeat(40) },
66 },
67 ],
68 };
69
70 function pullRequestRows(
71 count: number,
72 firstNumber: number,
73 ): ReadonlyArray<Record<string, unknown>> {
74 return Array.from({ length: count }, (_, index) => ({
75 pullRequestId: firstNumber + index,
76 title: `Pull request ${firstNumber + index}`,
77 status: "active",
78 sourceRefName: "refs/heads/feat/page",
79 targetRefName: "refs/heads/main",
80 creationDate: "2026-07-01T00:00:00Z",
81 repository: { name: "web", project: { name: "platform" } },
82 url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
83 }));
84 }
85
86 function pullRequests(count: number, firstNumber: number): string {
87 return JSON.stringify(pullRequestRows(count, firstNumber));
88 }
89
90 /** Entries as Azure streams them: data descriptors, with sizes only in the central directory. */
91 function streamedZip(
92 entries: ReadonlyArray<{
93 readonly name: string;
94 readonly data: Uint8Array;
95 readonly stored?: true;
96 }>,
97 ): Buffer {
98 const parts: Buffer[] = [];
99 const directory: Buffer[] = [];
100 let offset = 0;
101 for (const entry of entries) {
102 const name = Buffer.from(entry.name);
103 const method = entry.stored ? 0 : 8;
104 const body = entry.stored ? Buffer.from(entry.data) : NodeZlib.deflateRawSync(entry.data);
105 const local = Buffer.alloc(30);
106 local.writeUInt32LE(0x04034b50, 0);
107 local.writeUInt16LE(0x0008, 6);
108 local.writeUInt16LE(method, 8);
109 local.writeUInt16LE(name.length, 26);
110 const descriptor = Buffer.alloc(16);
111 descriptor.writeUInt32LE(0x08074b50, 0);
112 descriptor.writeUInt32LE(body.length, 8);
113 descriptor.writeUInt32LE(entry.data.length, 12);
114 const central = Buffer.alloc(46);
115 central.writeUInt32LE(0x02014b50, 0);
116 central.writeUInt16LE(0x0008, 8);
117 central.writeUInt16LE(method, 10);
118 central.writeUInt32LE(body.length, 20);
119 central.writeUInt32LE(entry.data.length, 24);
120 central.writeUInt16LE(name.length, 28);
121 central.writeUInt32LE(offset, 42);
122 parts.push(local, name, body, descriptor);
123 directory.push(central, name);
124 offset += local.length + name.length + body.length + descriptor.length;
125 }
126 const centralDirectory = Buffer.concat(directory);
127 const end = Buffer.alloc(22);
128 end.writeUInt32LE(0x06054b50, 0);
129 end.writeUInt16LE(entries.length, 8);
130 end.writeUInt16LE(entries.length, 10);
131 end.writeUInt32LE(centralDirectory.length, 12);
132 end.writeUInt32LE(offset, 16);
133 return Buffer.concat([...parts, centralDirectory, end]);
134 }
135
136 function argsOfCall(index: number): ReadonlyArray<string> {
137 const call = mockedExecute.mock.calls[index];
138 assert.isDefined(call);
139 return call[0].args;
140 }
141
142 function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {
143 const commit = "c".repeat(40);
144 return Array.from({ length: count }, (_, index) => {
145 const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;
146 return {
147 changeType: "edit",
148 item: {
149 path,
150 objectId: "a".repeat(40),
151 originalObjectId: "b".repeat(40),
152 commitId: commit,
153 gitObjectType: "blob",
154 url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,
155 },
156 };
157 });
158 }
159
160 afterEach(() => {
161 mockedExecute.mockReset();
162 });
163
164 layer("AzureDevOpsPullRequestCli.layer", (it) => {
165 it.effect("reports the latest pushed source commit even while the trial merge is stale", () =>
166 Effect.gen(function* () {
167 const previousHead = "a".repeat(40);
168 const latestHead = "c".repeat(40);
169 mockedExecute
170 .mockReturnValueOnce(
171 Effect.succeed(
172 output(json({ ...pullRequestRow, lastMergeSourceCommit: { commitId: previousHead } })),
173 ),
174 )
175 .mockReturnValueOnce(
176 Effect.succeed(
177 output(
178 json({
179 value: [
180 {
181 id: 2,
182 sourceRefCommit: { commitId: latestHead },
183 commonRefCommit: { commitId: "b".repeat(40) },
184 },
185 ...oneIteration.value,
186 ],
187 }),
188 ),
189 ),
190 )
191 .mockReturnValueOnce(Effect.succeed(output(json({ changeEntries: [] }))))
192 .mockReturnValueOnce(Effect.succeed(output("[]")))
193 .mockReturnValueOnce(
194 Effect.succeed(output(json({ count: 1, value: [{ id: "4f1c", name: "release-1.0" }] }))),
195 );
196 const provider = yield* AzureDevOpsPullRequestProvider.make;
197 const detail = yield* provider.getChangeRequest({
198 cwd: "/w",
199 repository: "platform/web",
200 host: "dev.azure.com",
201 number: 42,
202 });
203
204 expect(detail.headSha).toBe(latestHead);
205 expect(argsOfCall(2)).toContain("iterationId=2");
206 expect(argsOfCall(4)).toContain("pullRequestLabels");
207 expect(detail.labels).toEqual([{ name: "release-1.0", color: null }]);
208 expect(mockedExecute).toHaveBeenCalledTimes(5);
209 }),
210 );
211
212 it.effect("reads an Azure pull request page larger than the VCS default output limit", () =>
213 Effect.gen(function* () {
214 const rows = pullRequestRows(100, 1).map((row) => ({
215 ...row,
216 description: "x".repeat(10_000),
217 }));
218 const response = JSON.stringify(rows);
219 expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);
220
221 mockedExecute.mockImplementationOnce((input) =>
222 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
223 );
224 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
225
226 const batch = yield* cli.listPullRequests({
227 cwd: "/w",
228 repository: "web",
229 state: "merged",
230 involvement: "all",
231 viewer: "bilal@acme.dev",
232 limit: 99,
233 });
234
235 assert.strictEqual(batch.items.length, 99);
236 assert.isTrue(batch.truncated);
237 }),
238 );
239
240 it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
241 Effect.gen(function* () {
242 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
243 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
244
245 yield* cli.listPullRequests({
246 cwd: "/w",
247 repository: "web",
248 state: "open",
249 involvement: "all",
250 viewer: "bilal@acme.dev",
251 limit: 10,
252 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
253 });
254
255 const args = argsOfCall(0);
256 expect(args).toContain("--skip");
257 assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
258 expect(args).not.toContain("2026-07-02T00:00:00Z");
259 }),
260 );
261
262 it.effect("asks Azure for the author's pull requests by creator", () =>
263 Effect.gen(function* () {
264 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
265 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
266
267 yield* cli.listPullRequests({
268 cwd: "/w",
269 repository: "web",
270 state: "open",
271 involvement: "reviewing",
272 viewer: "bilal@acme.dev",
273 limit: 10,
274 author: "ana@acme.dev",
275 });
276
277 const args = argsOfCall(0);
278 assert.strictEqual(args[args.indexOf("--creator") + 1], "ana@acme.dev");
279 assert.strictEqual(args[args.indexOf("--reviewer") + 1], "bilal@acme.dev");
280 }),
281 );
282
283 it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
284 Effect.gen(function* () {
285 mockedExecute
286 .mockReturnValueOnce(
287 Effect.succeed(
288 output(
289 JSON.stringify([
290 { pullRequestId: "malformed" },
291 pullRequestRows(1, 1)[0],
292 { pullRequestId: "also malformed" },
293 ]),
294 ),
295 ),
296 )
297 .mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
298 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
299
300 const batch = yield* cli.listPullRequests({
301 cwd: "/w",
302 repository: "web",
303 state: "open",
304 involvement: "all",
305 viewer: "bilal@acme.dev",
306 limit: 2,
307 });
308
309 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
310 assert.isTrue(batch.truncated);
311 assert.strictEqual(batch.cursorAdvance, 4);
312 const secondArgs = argsOfCall(1);
313 assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
314 assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
315 }),
316 );
317
318 it.effect("reads the signed-in account, which az reports as a bare value", () =>
319 Effect.gen(function* () {
320 mockedExecute.mockReturnValueOnce(
321 Effect.succeed(output(JSON.stringify({ name: "bilal@acme.dev", type: "user" }))),
322 );
323 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
324
325 const viewer = yield* cli.getViewer({ cwd: "/w" });
326
327 assert.strictEqual(viewer, "bilal@acme.dev");
328 expect(argsOfCall(0)).toEqual([
329 "account",
330 "show",
331 "--query",
332 "user",
333 "--only-show-errors",
334 "--output",
335 "json",
336 ]);
337 }),
338 );
339
340 it.effect("names a token sign-in by the viewer's own pull request", () =>
341 Effect.gen(function* () {
342 const notLoggedIn = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
343 operation: "execute",
344 command: "az",
345 cwd: "/w",
346 argumentCount: 7,
347 cause: new Error("Please run 'az login' to setup account."),
348 });
349 mockedExecute
350 .mockReturnValueOnce(Effect.fail(notLoggedIn))
351 .mockReturnValueOnce(
352 Effect.succeed(
353 output(
354 JSON.stringify([{ ...pullRequestRow, createdBy: { uniqueName: "bilal@acme.dev" } }]),
355 ),
356 ),
357 )
358 .mockReturnValueOnce(Effect.succeed(output("")))
359 .mockReturnValueOnce(Effect.succeed(output("[]")));
360 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
361
362 assert.strictEqual(yield* cli.getViewer({ cwd: "/w" }), "bilal@acme.dev");
363 expect(argsOfCall(1)).toEqual(expect.arrayContaining(["--creator", "me", "--top", "1"]));
364 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
365 assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
366 }),
367 );
368
369 it.effect("fails when no sign-in can read pull requests", () =>
370 Effect.gen(function* () {
371 const signedOut = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
372 operation: "execute",
373 command: "az",
374 cwd: "/w",
375 argumentCount: 7,
376 cause: new Error("signed out"),
377 });
378 mockedExecute.mockReturnValue(Effect.fail(signedOut));
379 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
380
381 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
382
383 assert.strictEqual(error._tag, "AzureDevOpsCliAuthenticationError");
384 }),
385 );
386
387 const policyRow = (name: string, status: string) => ({
388 status,
389 configuration: {
390 url: "https://dev.azure.com/acme/platform/_apis/policy/configurations/54",
391 isBlocking: true,
392 type: { id: "0609b952-1397-4640-95ec-e00a01b2c241" },
393 settings: { displayName: name },
394 },
395 });
396
397 it.effect("follows every page of policies and puts failures first", () =>
398 Effect.gen(function* () {
399 const fullPage = Array.from({ length: 100 }, () => policyRow("Lint", "approved"));
400 mockedExecute
401 .mockReturnValueOnce(Effect.succeed(output(JSON.stringify(fullPage))))
402 .mockReturnValueOnce(
403 Effect.succeed(output(JSON.stringify([policyRow("Tests", "rejected")]))),
404 );
405 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
406 const checks = yield* cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false });
407 assert.deepStrictEqual(argsOfCall(1).slice(0, 12), [
408 "repos",
409 "pr",
410 "policy",
411 "list",
412 "--detect",
413 "true",
414 "--id",
415 "42",
416 "--top",
417 "100",
418 "--skip",
419 "100",
420 ]);
421 assert.strictEqual(checks.length, 101);
422 assert.strictEqual(checks[0]?.name, "Tests");
423 }),
424 );
425
426 it.effect.each([
427 { name: "cut off", result: { ...output("[]"), stdoutTruncated: true } },
428 { name: "unreadable", result: output(JSON.stringify([{ status: 7 }])) },
429 ])("fails rather than report a $name policy page as complete", ({ result }) =>
430 Effect.gen(function* () {
431 mockedExecute.mockReturnValueOnce(Effect.succeed(result));
432 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
433 const error = yield* Effect.flip(
434 cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false }),
435 );
436 assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
437 }),
438 );
439
440 it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
441 Effect.gen(function* () {
442 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
443 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
444
445 yield* cli.updatePullRequest({
446 cwd: "/w",
447 number: 42,
448 body: "- rewrote the page\n- kept the rest",
449 });
450
451 expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
452 }),
453 );
454
455 it.effect(
456 "sends a title or description that looks like `@path` as text, not as a file for az to read",
457 () =>
458 Effect.gen(function* () {
459 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
460 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
461
462 yield* cli.updatePullRequest({
463 cwd: "/w",
464 number: 42,
465 title: "@notes.txt",
466 body: "@notes.txt",
467 });
468
469 // az replaces an argument that starts with `@`, or whose text after the first `=` does, with that file's contents.
470 const fileReads = argsOfCall(0).flatMap((arg) => {
471 const value = arg.startsWith("@") ? arg : arg.slice(arg.indexOf("=") + 1);
472 return (arg.startsWith("@") || arg.includes("=")) && value.startsWith("@")
473 ? [value.slice(1)]
474 : [];
475 });
476 expect(fileReads).not.toContain("notes.txt");
477 // Each `@` value goes over stdin, which reaches az wherever it runs; one per call.
478 expect(mockedExecute.mock.calls.map(([call]) => call.stdin)).toEqual([
479 "@notes.txt",
480 "@notes.txt",
481 ]);
482 }),
483 );
484
485 it.effect("names the head's blob as what a cleared file was cleared at", () =>
486 Effect.gen(function* () {
487 mockedExecute
488 .mockReturnValueOnce(
489 Effect.succeed(
490 output(
491 JSON.stringify({
492 pullRequestId: 42,
493 title: "Add the page",
494 status: "active",
495 sourceRefName: "refs/heads/feat/page",
496 targetRefName: "refs/heads/main",
497 creationDate: "2026-07-01T00:00:00Z",
498 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
499 repository: { name: "web", project: { name: "platform" } },
500 }),
501 ),
502 ),
503 )
504 .mockReturnValueOnce(
505 Effect.succeed(
506 output(
507 JSON.stringify({
508 value: [
509 {
510 id: 1,
511 sourceRefCommit: { commitId: "a".repeat(40) },
512 commonRefCommit: { commitId: "b".repeat(40) },
513 },
514 {
515 id: 2,
516 sourceRefCommit: { commitId: "c".repeat(40) },
517 commonRefCommit: { commitId: "b".repeat(40) },
518 },
519 ],
520 }),
521 ),
522 ),
523 )
524 .mockReturnValueOnce(
525 Effect.succeed(
526 output(
527 JSON.stringify({
528 changeEntries: [
529 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
530 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
531 ],
532 }),
533 ),
534 ),
535 );
536 const provider = yield* AzureDevOpsPullRequestProvider.make;
537
538 assert.strictEqual(provider.capabilities.viewedFiles, "environment");
539 assert.isDefined(provider.getFileRevisions);
540 const answer = yield* provider.getFileRevisions({
541 cwd: "/w",
542 repository: "web",
543 host: "dev.azure.com",
544 number: 42,
545 paths: ["README.md"],
546 });
547
548 expect(argsOfCall(2)).toContain("iterationId=2");
549 expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);
550 }),
551 );
552
553 it.effect(
554 "answers for a marked file the pull request no longer changes as the empty version",
555 () =>
556 Effect.gen(function* () {
557 mockedExecute
558 .mockReturnValueOnce(
559 Effect.succeed(
560 output(
561 json({
562 pullRequestId: 42,
563 title: "Add the page",
564 status: "active",
565 sourceRefName: "refs/heads/feat/page",
566 targetRefName: "refs/heads/main",
567 creationDate: "2026-07-01T00:00:00Z",
568 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
569 repository: { name: "web", project: { name: "platform" } },
570 }),
571 ),
572 ),
573 )
574 .mockReturnValueOnce(
575 Effect.succeed(
576 output(
577 json({
578 value: [
579 {
580 id: 1,
581 sourceRefCommit: { commitId: "a".repeat(40) },
582 commonRefCommit: { commitId: "b".repeat(40) },
583 },
584 ],
585 }),
586 ),
587 ),
588 )
589 .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));
590 const provider = yield* AzureDevOpsPullRequestProvider.make;
591 assert.isDefined(provider.getFileRevisions);
592
593 const answer = yield* provider.getFileRevisions({
594 cwd: "/w",
595 repository: "web",
596 host: "dev.azure.com",
597 number: 42,
598 paths: ["GONE.md"],
599 });
600
601 expect([...answer.revisions]).toEqual([["GONE.md", ""]]);
602 }),
603 );
604
605 it.effect("says nothing about the files past the end of a change it gave up following", () =>
606 Effect.gen(function* () {
607 const entries = (from: number, count: number) =>
608 Array.from({ length: count }, (_, index) => ({
609 changeType: "edit",
610 item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },
611 }));
612 mockedExecute
613 .mockReturnValueOnce(
614 Effect.succeed(
615 output(
616 json({
617 pullRequestId: 42,
618 title: "Add the page",
619 status: "active",
620 sourceRefName: "refs/heads/feat/page",
621 targetRefName: "refs/heads/main",
622 creationDate: "2026-07-01T00:00:00Z",
623 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
624 repository: { name: "web", project: { name: "platform" } },
625 }),
626 ),
627 ),
628 )
629 .mockReturnValueOnce(
630 Effect.succeed(
631 output(
632 json({
633 value: [
634 {
635 id: 1,
636 sourceRefCommit: { commitId: "a".repeat(40) },
637 commonRefCommit: { commitId: "b".repeat(40) },
638 },
639 ],
640 }),
641 ),
642 ),
643 )
644 .mockReturnValueOnce(
645 Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),
646 )
647 .mockReturnValueOnce(
648 Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),
649 );
650 const provider = yield* AzureDevOpsPullRequestProvider.make;
651 assert.isDefined(provider.getFileRevisions);
652
653 const answer = yield* provider.getFileRevisions({
654 cwd: "/w",
655 repository: "web",
656 host: "dev.azure.com",
657 number: 42,
658 paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],
659 });
660
661 expect(argsOfCall(3)).toContain("$skip=5000");
662 expect([...answer.revisions]).toEqual([
663 ["src/f1.ts", "blob-1"],
664 ["src/f5001.ts", "blob-5001"],
665 ]);
666 }),
667 );
668
669 it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>
670 Effect.gen(function* () {
671 mockedExecute
672 .mockReturnValueOnce(
673 Effect.succeed(
674 output(
675 json({
676 pullRequestId: 42,
677 title: "Add the page",
678 status: "active",
679 sourceRefName: "refs/heads/feat/page",
680 targetRefName: "refs/heads/main",
681 creationDate: "2026-07-01T00:00:00Z",
682 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
683 repository: { name: "web", project: { name: "platform" } },
684 }),
685 ),
686 ),
687 )
688 .mockReturnValueOnce(
689 Effect.succeed(
690 output(
691 json({
692 value: [
693 {
694 id: 1,
695 sourceRefCommit: { commitId: "a".repeat(40) },
696 commonRefCommit: { commitId: "b".repeat(40) },
697 },
698 ],
699 }),
700 ),
701 ),
702 )
703 .mockImplementation((command) => {
704 const skip = command.args.find((arg) => arg.startsWith("$skip="));
705 const from = Number(skip?.slice("$skip=".length) ?? 0);
706 return Effect.succeed(
707 output(
708 json({
709 changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],
710 nextSkip: from + 2_000,
711 }),
712 ),
713 );
714 });
715 const provider = yield* AzureDevOpsPullRequestProvider.make;
716 assert.isDefined(provider.getFileRevisions);
717
718 const answer = yield* provider.getFileRevisions({
719 cwd: "/w",
720 repository: "web",
721 host: "dev.azure.com",
722 number: 42,
723 paths: ["src/page.ts"],
724 });
725
726 assert.strictEqual(mockedExecute.mock.calls.length, 7);
727 assert.strictEqual(answer.revisions.size, 0);
728 }),
729 );
730
731 it.effect("leaves one file the host would not hand over listed without its hunks", () =>
732 Effect.gen(function* () {
733 mockedExecute
734 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
735 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
736 .mockReturnValueOnce(
737 Effect.succeed(
738 output(
739 json({
740 changeEntries: [
741 { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },
742 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
743 ],
744 }),
745 ),
746 ),
747 )
748 .mockReturnValueOnce(
749 Effect.fail(
750 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
751 operation: "execute",
752 command: "az",
753 cwd: "/w",
754 argumentCount: 1,
755 cause: "the blob is past what the route will carry",
756 }),
757 ),
758 )
759 .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));
760 const provider = yield* AzureDevOpsPullRequestProvider.make;
761
762 const slice = yield* provider.getDiff({
763 cwd: "/w",
764 repository: "web",
765 host: "dev.azure.com",
766 number: 42,
767 });
768
769 assert.isTrue(slice.truncated);
770 expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");
771 expect(slice.patch).toContain("+hello");
772 }),
773 );
774
775 it.effect("fails the whole read when it is the connection that would not answer", () =>
776 Effect.gen(function* () {
777 mockedExecute
778 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
779 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
780 .mockReturnValueOnce(
781 Effect.succeed(
782 output(
783 json({
784 changeEntries: [
785 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
786 ],
787 }),
788 ),
789 ),
790 )
791 .mockReturnValueOnce(
792 Effect.fail(
793 new AzureDevOpsCli.AzureDevOpsCliRateLimitError({
794 operation: "execute",
795 command: "az",
796 cwd: "/w",
797 argumentCount: 1,
798 cause: "429",
799 }),
800 ),
801 );
802 const provider = yield* AzureDevOpsPullRequestProvider.make;
803
804 const error = yield* Effect.flip(
805 provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),
806 );
807
808 assert.strictEqual(error.reason, "rate-limited");
809 }),
810 );
811
812 it.effect("takes Azure's own word on a file it will not spell out", () =>
813 Effect.gen(function* () {
814 mockedExecute
815 .mockReturnValueOnce(
816 Effect.succeed(
817 output(
818 json({
819 pullRequestId: 42,
820 title: "Add the page",
821 status: "active",
822 sourceRefName: "refs/heads/feat/page",
823 targetRefName: "refs/heads/main",
824 creationDate: "2026-07-01T00:00:00Z",
825 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
826 repository: { name: "web", project: { name: "platform" } },
827 }),
828 ),
829 ),
830 )
831 .mockReturnValueOnce(
832 Effect.succeed(
833 output(
834 json({
835 value: [
836 {
837 id: 1,
838 sourceRefCommit: { commitId: "a".repeat(40) },
839 commonRefCommit: { commitId: "b".repeat(40) },
840 },
841 ],
842 }),
843 ),
844 ),
845 )
846 .mockReturnValueOnce(
847 Effect.succeed(
848 output(
849 json({
850 changeEntries: [
851 { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },
852 ],
853 }),
854 ),
855 ),
856 )
857 .mockReturnValueOnce(
858 Effect.succeed(
859 output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),
860 ),
861 );
862 const provider = yield* AzureDevOpsPullRequestProvider.make;
863
864 const slice = yield* provider.getDiff({
865 cwd: "/w",
866 repository: "web",
867 host: "dev.azure.com",
868 number: 42,
869 });
870
871 expect(argsOfCall(3)).toContain("includeContentMetadata=true");
872 expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");
873 assert.isTrue(slice.truncated);
874 }),
875 );
876
877 it.effect("stops following pages when one of them does not move the cursor on", () =>
878 Effect.gen(function* () {
879 mockedExecute
880 .mockReturnValueOnce(
881 Effect.succeed(
882 output(
883 json({
884 pullRequestId: 42,
885 title: "Add the page",
886 status: "active",
887 sourceRefName: "refs/heads/feat/page",
888 targetRefName: "refs/heads/main",
889 creationDate: "2026-07-01T00:00:00Z",
890 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
891 repository: { name: "web", project: { name: "platform" } },
892 }),
893 ),
894 ),
895 )
896 .mockReturnValueOnce(
897 Effect.succeed(
898 output(
899 json({
900 value: [
901 {
902 id: 1,
903 sourceRefCommit: { commitId: "a".repeat(40) },
904 commonRefCommit: { commitId: "b".repeat(40) },
905 },
906 ],
907 }),
908 ),
909 ),
910 )
911 .mockReturnValueOnce(
912 Effect.succeed(
913 output(
914 json({
915 changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],
916 nextSkip: 2_000,
917 }),
918 ),
919 ),
920 )
921 .mockReturnValueOnce(
922 Effect.succeed(
923 output(
924 json({
925 changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],
926 nextSkip: 2_000,
927 }),
928 ),
929 ),
930 );
931 const provider = yield* AzureDevOpsPullRequestProvider.make;
932 assert.isDefined(provider.getFileRevisions);
933
934 const answer = yield* provider.getFileRevisions({
935 cwd: "/w",
936 repository: "web",
937 host: "dev.azure.com",
938 number: 42,
939 paths: ["a.ts", "b.ts", "unlisted.ts"],
940 });
941
942 assert.strictEqual(mockedExecute.mock.calls.length, 4);
943 expect([...answer.revisions]).toEqual([
944 ["a.ts", "8f80"],
945 ["b.ts", "0ca4"],
946 ]);
947 }),
948 );
949
950 it.effect("reads a full page of change entries, which is past the default output limit", () =>
951 Effect.gen(function* () {
952 const response = json({ changeEntries: changeEntries(2_000) });
953 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
954 mockedExecute.mockImplementationOnce((input) =>
955 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
956 );
957 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
958
959 const page = yield* cli.listIterationChanges({
960 cwd: "/w",
961 location: { project: "platform", repository: "web" },
962 number: 42,
963 iterationId: 1,
964 });
965
966 assert.strictEqual(page.changes.length, 2_000);
967 assert.isFalse(page.truncated);
968 }),
969 );
970
971 it.effect("reads a file whose JSON envelope is past the default output limit", () =>
972 Effect.gen(function* () {
973 const file = "const value = 1;\n".repeat(57_000);
974 const response = json({ content: file });
975 expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
976 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
977 mockedExecute.mockImplementationOnce((input) =>
978 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
979 );
980 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
981
982 const item = yield* cli.readItemContent({
983 cwd: "/w",
984 location: { project: "platform", repository: "web" },
985 path: "src/generated/schema.ts",
986 commit: "a".repeat(40),
987 });
988
989 assert.strictEqual(item.contents, file);
990 assert.isFalse(item.isBinary);
991 }),
992 );
993
994 it.effect(
995 "reads a batch of files from one blobs zip, keeping only what Azure's read would say",
996 () =>
997 Effect.gen(function* () {
998 const id = (digit: string) => digit.repeat(40);
999 const utf8 = (text: string) => new TextEncoder().encode(text);
1000 let sent = "";
1001 mockedExecute.mockImplementationOnce((input) =>
1002 Effect.sync(() => {
1003 const flag = (name: string) => input.args[input.args.indexOf(name) + 1] ?? "";
1004 sent = NodeFS.readFileSync(flag("--in-file"), "utf8");
1005 NodeFS.writeFileSync(
1006 flag("--out-file"),
1007 streamedZip([
1008 { name: id("a"), data: utf8("plain text\n") },
1009 { name: id("b"), data: utf8("\uFEFFcafé ✓\n") },
1010 { name: id("c"), data: Uint8Array.of(0x89, 0x50, 0x00, 0x01) },
1011 // Windows-1252 "café" and UTF-16: Azure decodes these itself.
1012 { name: id("d"), data: Uint8Array.of(0x63, 0x61, 0x66, 0xe9) },
1013 { name: id("e"), data: Uint8Array.of(0xff, 0xfe, 0x68, 0x00) },
1014 { name: id("f"), data: utf8("stored\n"), stored: true },
1015 { name: id("9"), data: utf8("never asked for\n") },
1016 ]),
1017 );
1018 return output("");
1019 }),
1020 );
1021 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1022
1023 const blobs = yield* cli.readBlobs({
1024 cwd: "/w",
1025 location: { project: "platform", repository: "web" },
1026 objectIds: [id("A"), id("b"), id("C"), id("d"), id("e"), id("f"), id("a"), "../etc"],
1027 });
1028
1029 expect(JSON.parse(sent)).toEqual([id("A"), id("b"), id("C"), id("d"), id("e"), id("f")]);
1030 expect(argsOfCall(0)).toEqual(
1031 expect.arrayContaining(["blobs", "POST", "application/zip", "project=platform"]),
1032 );
1033 expect(Object.fromEntries(blobs)).toEqual({
1034 [id("a")]: { contents: "plain text\n", isBinary: false },
1035 [id("b")]: { contents: "café ✓\n", isBinary: false },
1036 [id("c")]: { contents: "", isBinary: true },
1037 [id("f")]: { contents: "stored\n", isBinary: false },
1038 });
1039 }),
1040 );
1041
1042 it.effect("leaves blobs past the batch's total size to per-file reads", () =>
1043 Effect.gen(function* () {
1044 const ids = ["1", "2", "3", "4", "5", "6"].map((digit) => digit.repeat(40));
1045 // Compresses to a few KiB each, so only the inflated total can bound memory.
1046 const blob = new Uint8Array(3 * 1024 * 1024).fill(0x61);
1047 mockedExecute.mockImplementationOnce((input) =>
1048 Effect.sync(() => {
1049 NodeFS.writeFileSync(
1050 input.args[input.args.indexOf("--out-file") + 1] ?? "",
1051 streamedZip(ids.map((name) => ({ name, data: blob }))),
1052 );
1053 return output("");
1054 }),
1055 );
1056 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1057
1058 const blobs = yield* cli.readBlobs({
1059 cwd: "/w",
1060 location: { project: "platform", repository: "web" },
1061 objectIds: ids,
1062 });
1063
1064 expect([...blobs.keys()]).toEqual(ids.slice(0, 5));
1065 }),
1066 );
1067
1068 it.effect("escapes characters in a file path that would cut the query string", () =>
1069 Effect.gen(function* () {
1070 mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "x" }))));
1071 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1072
1073 yield* cli.readItemContent({
1074 cwd: "/w",
1075 location: { project: "platform", repository: "web" },
1076 path: "docs/C#/a&b.md",
1077 commit: "a".repeat(40),
1078 });
1079
1080 expect(mockedExecute.mock.calls.at(-1)?.[0].args).toContain("path=%2Fdocs%2FC%23%2Fa%26b.md");
1081 }),
1082 );
1083
1084 it.effect("reports a pull request it cannot place as its own outcome", () =>
1085 Effect.gen(function* () {
1086 mockedExecute.mockReturnValueOnce(
1087 Effect.succeed(
1088 output(
1089 JSON.stringify({
1090 pullRequestId: 42,
1091 title: "Add the page",
1092 sourceRefName: "refs/heads/feat/page",
1093 targetRefName: "refs/heads/main",
1094 creationDate: "2026-07-01T00:00:00Z",
1095 }),
1096 ),
1097 ),
1098 );
1099 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1100
1101 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1102
1103 assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
1104 }),
1105 );
1106
1107 it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
1108 Effect.gen(function* () {
1109 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1110
1111 const error = yield* Effect.flip(
1112 cli.setPullRequestReviewers({
1113 cwd: "/w",
1114 number: 42,
1115 reviewers: ["--query"],
1116 requested: true,
1117 }),
1118 );
1119
1120 assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
1121 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1122 }),
1123 );
1124 });