-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch-commit-tool.test.ts
More file actions
898 lines (775 loc) · 32.1 KB
/
batch-commit-tool.test.ts
File metadata and controls
898 lines (775 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
/**
* Tests for batch_commit_tool logic.
*
* The execute handler is not exported, so we test:
* 1. SHA extraction regex (unit) — mirrors the pattern inside the handler
* 2. Path escape detection (unit) — uses exported isStrictlyUnderGitTop + resolvePathForRepo
* 3. Integration: full stage-and-commit flow via spawnGitAsync against throwaway repos
*
* We test:
* 1. SHA extraction regex parses standard git commit output
* 2. SHA regex returns undefined for unrecognised output
* 3. path_escapes_repository: dotdot path rejected before staging
* 4. Single commit succeeds and SHA captured
* 5. Multiple sequential commits all succeed
* 6. Stops after first failure (nothing staged → commit_failed)
* 7. Valid path that is exactly the git root is accepted
*/
import { afterEach, describe, expect, test } from "bun:test";
import { rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { isStrictlyUnderGitTop, resolvePathForRepo } from "../repo-paths.js";
import { registerBatchCommitTool } from "./batch-commit-tool.js";
import { spawnGitAsync } from "./git.js";
import {
captureTool,
cleanupTmpPaths,
gitCmd,
makeRepo,
makeRepoWithUpstream,
mkTmpDir,
} from "./test-harness.js";
afterEach(cleanupTmpPaths);
// ---------------------------------------------------------------------------
// Mirrors the SHA extraction regex from batch-commit-tool.ts
// ---------------------------------------------------------------------------
function extractSha(commitOutput: string): string | undefined {
return /\[[\w/.-]+\s+([0-9a-f]+)\]/.exec(commitOutput)?.[1];
}
// ---------------------------------------------------------------------------
// Repo helpers (shared via test-harness.ts)
// ---------------------------------------------------------------------------
// gitCmd, makeRepo, makeRepoWithUpstream imported from test-harness
// ---------------------------------------------------------------------------
// Unit: SHA extraction regex
// ---------------------------------------------------------------------------
describe("extractSha", () => {
test("parses standard git commit output", () => {
const output = "[main abc1234] feat: add feature\n 1 file changed, 5 insertions(+)";
expect(extractSha(output)).toBe("abc1234");
});
test("parses branch with slash in name", () => {
const output = "[feature/my-branch d3adb33] fix: patch\n 1 file changed";
expect(extractSha(output)).toBe("d3adb33");
});
test("parses short SHA of varying length", () => {
const output = "[main 0a1b2c3d] chore: update\n";
expect(extractSha(output)).toBe("0a1b2c3d");
});
test("returns undefined for unrecognised output", () => {
expect(extractSha("nothing useful here")).toBeUndefined();
});
test("returns undefined for empty string", () => {
expect(extractSha("")).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// Unit: path escape detection (mirrors execute handler validation)
// ---------------------------------------------------------------------------
describe("path escape detection", () => {
test("dotdot path that escapes root is rejected", () => {
const gitTop = mkTmpDir("mcp-top-");
const rel = "../../etc/passwd";
const abs = resolvePathForRepo(rel, gitTop);
expect(isStrictlyUnderGitTop(abs, gitTop)).toBe(false);
});
test("normal nested path is accepted", () => {
const gitTop = mkTmpDir("mcp-top-");
const rel = "src/foo.ts";
const abs = resolvePathForRepo(rel, gitTop);
expect(isStrictlyUnderGitTop(abs, gitTop)).toBe(true);
});
test("absolute path outside root is rejected", () => {
const gitTop = mkTmpDir("mcp-top-");
const outside = mkTmpDir("mcp-other-");
expect(isStrictlyUnderGitTop(outside, gitTop)).toBe(false);
});
test("path equal to git root is accepted", () => {
const gitTop = mkTmpDir("mcp-top-");
expect(isStrictlyUnderGitTop(gitTop, gitTop)).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Integration: stage-and-commit flow
// ---------------------------------------------------------------------------
describe("batch_commit integration", () => {
test("single file commit succeeds and SHA is captured", async () => {
const dir = makeRepo();
// Create an initial commit so HEAD exists
writeFileSync(join(dir, "init.ts"), "const x = 0;\n");
gitCmd(dir, "add", "init.ts");
gitCmd(dir, "commit", "-m", "chore: init");
// Stage a new file
writeFileSync(join(dir, "feat.ts"), "export const y = 1;\n");
const addResult = await spawnGitAsync(dir, ["add", "--", "feat.ts"]);
expect(addResult.ok).toBe(true);
// Commit
const commitResult = await spawnGitAsync(dir, ["commit", "-m", "feat: add y"]);
expect(commitResult.ok).toBe(true);
const sha = extractSha(commitResult.stdout);
expect(sha).toBeDefined();
expect(sha).toMatch(/^[0-9a-f]+$/);
});
test("multiple sequential commits all succeed", async () => {
const dir = makeRepo();
// Establish HEAD so subsequent commits are non-root (root-commit output differs)
writeFileSync(join(dir, "base.ts"), "const base = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
const shas: string[] = [];
for (let i = 1; i <= 3; i++) {
const file = `file${i}.ts`;
writeFileSync(join(dir, file), `const v${i} = ${i};\n`);
const addR = await spawnGitAsync(dir, ["add", "--", file]);
expect(addR.ok).toBe(true);
const commitR = await spawnGitAsync(dir, ["commit", "-m", `chore: add file ${i}`]);
expect(commitR.ok).toBe(true);
const sha = extractSha(commitR.stdout);
expect(sha).toBeDefined();
if (sha) shas.push(sha);
}
// All 3 SHAs are distinct
expect(new Set(shas).size).toBe(3);
});
test("commit fails when nothing is staged", async () => {
const dir = makeRepo();
// Create initial commit so HEAD exists
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Attempt commit with empty index
const commitResult = await spawnGitAsync(dir, ["commit", "-m", "should fail"]);
expect(commitResult.ok).toBe(false);
});
test("stage fails for non-existent file", async () => {
const dir = makeRepo();
const addResult = await spawnGitAsync(dir, ["add", "--", "nonexistent.ts"]);
expect(addResult.ok).toBe(false);
});
test("git log reflects commits in order after sequential commits", async () => {
const dir = makeRepo();
const messages = ["feat: first", "feat: second", "feat: third"];
for (const msg of messages) {
const file = `f${++_seq}.ts`;
writeFileSync(join(dir, file), `// ${msg}\n`);
gitCmd(dir, "add", file);
gitCmd(dir, "commit", "-m", msg);
}
const logResult = await spawnGitAsync(dir, ["log", "--oneline", "-5"]);
expect(logResult.ok).toBe(true);
// Most recent first
expect(logResult.stdout).toContain("feat: third");
expect(logResult.stdout.indexOf("feat: third")).toBeLessThan(
logResult.stdout.indexOf("feat: second"),
);
});
});
// ---------------------------------------------------------------------------
// Execute handler: end-to-end via fake server harness
// ---------------------------------------------------------------------------
describe("batch_commit execute handler", () => {
test("happy path: single commit returns markdown with sha and success header", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "new.ts"), "export const x = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
expect(text).toContain("1/1 committed");
expect(text).toContain("feat: add new");
});
test("json format returns structured result with ok:true", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "a.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "feat: json", files: ["a.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number; total: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
expect(parsed.total).toBe(1);
});
test("path_escapes_repository: dotdot path → error in json response", async () => {
const dir = makeRepo();
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "bad", files: ["../../etc/passwd"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; results: Array<{ error: string }> };
expect(parsed.ok).toBe(false);
expect(parsed.results[0]?.error).toBe("path_escapes_repository");
});
test("non-git workspaceRoot → not_a_git_repository error", async () => {
const plain = mkTmpDir("mcp-plain-");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: plain,
format: "json",
commits: [{ message: "noop", files: ["x.ts"] }],
});
const parsed = JSON.parse(text) as { error: string };
expect(parsed.error).toBe("not_a_git_repository");
});
test("multiple commits: stops on first failure, reports partial progress", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "ok.ts"), "const ok = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [
{ message: "feat: ok", files: ["ok.ts"] },
{ message: "feat: bad", files: ["nonexistent.ts"] },
],
});
const parsed = JSON.parse(text) as {
ok: boolean;
committed: number;
results: Array<{ ok: boolean; error?: string }>;
};
expect(parsed.ok).toBe(false);
expect(parsed.committed).toBe(1);
expect(parsed.results[0]?.ok).toBe(true);
expect(parsed.results[1]?.ok).toBe(false);
});
});
// ---------------------------------------------------------------------------
// push: "after" behaviour
// ---------------------------------------------------------------------------
describe("batch_commit push: after", () => {
test("default (push omitted) does not touch the remote", async () => {
const { work, remote } = makeRepoWithUpstream();
writeFileSync(join(work, "a.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: work,
format: "json",
commits: [{ message: "feat: a", files: ["a.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; push?: unknown };
expect(parsed.ok).toBe(true);
expect(parsed.push).toBeUndefined();
// Remote is still at the seed commit only.
const remoteLog = gitCmd(remote, "log", "--oneline");
expect(remoteLog.split("\n").filter((l) => l.trim()).length).toBe(1);
});
test('push: "after" with a tracking branch pushes successfully', async () => {
const { work, remote } = makeRepoWithUpstream();
writeFileSync(join(work, "a.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: work,
format: "json",
push: "after",
commits: [{ message: "feat: a", files: ["a.ts"] }],
});
const parsed = JSON.parse(text) as {
ok: boolean;
push?: { ok: boolean; branch?: string; upstream?: string; error?: string };
};
expect(parsed.ok).toBe(true);
expect(parsed.push?.ok).toBe(true);
expect(parsed.push?.branch).toBe("main");
expect(parsed.push?.upstream).toBe("origin/main");
// Remote now has two commits (seed + new).
const remoteLog = gitCmd(remote, "log", "--oneline");
expect(remoteLog.split("\n").filter((l) => l.trim()).length).toBe(2);
});
test('push: "after" on a branch with no upstream returns push_no_upstream', async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "a.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
push: "after",
commits: [{ message: "feat: a", files: ["a.ts"] }],
});
const parsed = JSON.parse(text) as {
ok: boolean;
committed: number;
push?: { ok: boolean; error?: string };
};
// Commits succeed; only push fails — do NOT roll back.
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
expect(parsed.push?.ok).toBe(false);
expect(parsed.push?.error).toBe("push_no_upstream");
});
test('push: "after" is skipped when a commit fails', async () => {
const { work } = makeRepoWithUpstream();
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: work,
format: "json",
push: "after",
commits: [{ message: "feat: bad", files: ["nonexistent.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; push?: unknown };
expect(parsed.ok).toBe(false);
expect(parsed.push).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// dryRun mode tests
// ---------------------------------------------------------------------------
describe("batch_commit dryRun mode", () => {
test("dryRun: true stages files and returns preview without committing", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "new.ts"), "export const x = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: true,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
const parsed = JSON.parse(text) as {
dryRun: boolean;
ok: boolean;
results: Array<{ ok: boolean; staged?: string[] }>;
};
expect(parsed.dryRun).toBe(true);
expect(parsed.ok).toBe(true);
expect(parsed.results[0]?.staged).toEqual(["new.ts"]);
// Verify no commit was written (log unchanged)
const logResult = await spawnGitAsync(dir, ["log", "--oneline"]);
expect(logResult.stdout).toContain("chore: base");
expect(logResult.stdout).not.toContain("feat: add new");
});
test("dryRun: true unstages files after preview", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "new.ts"), "export const x = 1;\n");
const run = captureTool(registerBatchCommitTool);
await run({
workspaceRoot: dir,
dryRun: true,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
// Check that nothing is staged
const statusResult = await spawnGitAsync(dir, ["status", "--short"]);
expect(statusResult.stdout).toContain("?? new.ts"); // Untracked, not staged
});
test("dryRun: true includes diffStat in json response", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "file1.ts"), "export const a = 1;\n");
writeFileSync(join(dir, "file2.ts"), "export const b = 2;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: true,
commits: [{ message: "feat: multi", files: ["file1.ts", "file2.ts"] }],
});
const parsed = JSON.parse(text) as {
results: Array<{ diffStat?: string }>;
};
expect(parsed.results[0]?.diffStat).toBeDefined();
expect(parsed.results[0]?.diffStat).toContain("file1.ts");
expect(parsed.results[0]?.diffStat).toContain("file2.ts");
});
test("dryRun: true markdown header indicates DRY RUN mode", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "new.ts"), "export const x = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
dryRun: true,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
expect(text).toContain("DRY RUN");
expect(text).toContain("no commits written");
});
test("dryRun: true with multiple commits shows all previews", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "file1.ts"), "const a = 1;\n");
writeFileSync(join(dir, "file2.ts"), "const b = 2;\n");
writeFileSync(join(dir, "file3.ts"), "const c = 3;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: true,
commits: [
{ message: "feat: first", files: ["file1.ts"] },
{ message: "feat: second", files: ["file2.ts"] },
{ message: "feat: third", files: ["file3.ts"] },
],
});
const parsed = JSON.parse(text) as {
ok: boolean;
committed: number;
total: number;
results: Array<{ ok: boolean; staged?: string[] }>;
};
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(3);
expect(parsed.total).toBe(3);
expect(parsed.results[0]?.staged).toEqual(["file1.ts"]);
expect(parsed.results[1]?.staged).toEqual(["file2.ts"]);
expect(parsed.results[2]?.staged).toEqual(["file3.ts"]);
// Verify no commits were written
const logResult = await spawnGitAsync(dir, ["log", "--oneline"]);
expect(logResult.stdout).toContain("chore: base");
expect(logResult.stdout).not.toContain("feat: first");
expect(logResult.stdout).not.toContain("feat: second");
expect(logResult.stdout).not.toContain("feat: third");
});
test("dryRun: true does not perform push even with push: after", async () => {
const { work, remote } = makeRepoWithUpstream();
writeFileSync(join(work, "a.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: work,
format: "json",
dryRun: true,
push: "after",
commits: [{ message: "feat: a", files: ["a.ts"] }],
});
const parsed = JSON.parse(text) as { dryRun: boolean; push?: unknown };
expect(parsed.dryRun).toBe(true);
expect(parsed.push).toBeUndefined();
// Remote should still be at seed commit only
const remoteLog = gitCmd(remote, "log", "--oneline");
expect(remoteLog.split("\n").filter((l) => l.trim()).length).toBe(1);
});
test("dryRun: false (default) commits as normal", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "new.ts"), "export const x = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: false,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
const parsed = JSON.parse(text) as { dryRun?: boolean; ok: boolean };
expect(parsed.dryRun).toBeUndefined();
expect(parsed.ok).toBe(true);
// Verify commit was written
const logResult = await spawnGitAsync(dir, ["log", "--oneline"]);
expect(logResult.stdout).toContain("feat: add new");
});
test("dryRun: true with deleted file unstages cleanly after preview", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "keep.ts"), "const k = 0;\n");
writeFileSync(join(dir, "gone.ts"), "const g = 1;\n");
gitCmd(dir, "add", "keep.ts", "gone.ts");
gitCmd(dir, "commit", "-m", "chore: base");
rmSync(join(dir, "gone.ts"));
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: true,
commits: [{ message: "fix: remove gone", files: ["gone.ts"] }],
});
const parsed = JSON.parse(text) as {
dryRun: boolean;
ok: boolean;
results: Array<{ ok: boolean; staged?: string[] }>;
};
expect(parsed.dryRun).toBe(true);
expect(parsed.ok).toBe(true);
expect(parsed.results[0]?.staged).toEqual(["gone.ts"]);
// Cleanup must leave deletion unstaged (not staged, not committed)
const status = await spawnGitAsync(dir, ["status", "--short"]);
expect(status.stdout).not.toContain("D gone.ts"); // not staged
expect(status.stdout).toContain(" D gone.ts"); // unstaged deletion
const log = await spawnGitAsync(dir, ["log", "--oneline"]);
expect(log.stdout).not.toContain("fix: remove gone");
});
test("dryRun: true with mixed edits and deletions unstages all cleanly", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "edit.ts"), "const e = 0;\n");
writeFileSync(join(dir, "del.ts"), "const d = 1;\n");
gitCmd(dir, "add", "edit.ts", "del.ts");
gitCmd(dir, "commit", "-m", "chore: base");
writeFileSync(join(dir, "edit.ts"), "const e = 99;\n");
rmSync(join(dir, "del.ts"));
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
dryRun: true,
commits: [
{ message: "fix: edit", files: ["edit.ts"] },
{ message: "fix: delete", files: ["del.ts"] },
],
});
const parsed = JSON.parse(text) as {
ok: boolean;
results: Array<{ ok: boolean }>;
};
expect(parsed.ok).toBe(true);
expect(parsed.results).toHaveLength(2);
// Both files must be unstaged after cleanup
const status = await spawnGitAsync(dir, ["status", "--short"]);
expect(status.stdout).not.toContain("M edit.ts");
expect(status.stdout).not.toContain("D del.ts");
expect(status.stdout).toContain(" M edit.ts");
expect(status.stdout).toContain(" D del.ts");
});
test("dryRun: true leaves pre-staged file still staged after cleanup", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
writeFileSync(join(dir, "pre.ts"), "const p = 0;\n");
gitCmd(dir, "add", "base.ts", "pre.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify both files — stage only pre.ts before invoking dry run
writeFileSync(join(dir, "pre.ts"), "const p = 99;\n");
writeFileSync(join(dir, "new.ts"), "export const n = 1;\n");
gitCmd(dir, "add", "pre.ts"); // pre-existing staged change
const run = captureTool(registerBatchCommitTool);
await run({
workspaceRoot: dir,
dryRun: true,
commits: [{ message: "feat: add new", files: ["new.ts"] }],
});
// new.ts must be unstaged (dry-run file); pre.ts must remain staged
const statusResult = await spawnGitAsync(dir, ["diff", "--cached", "--name-only"]);
expect(statusResult.stdout).toContain("pre.ts"); // still staged — pre-existing
expect(statusResult.stdout).not.toContain("new.ts"); // cleaned up by dry-run
});
});
// ---------------------------------------------------------------------------
// Line-range staging (lines parameter)
// ---------------------------------------------------------------------------
describe("batch_commit line-range staging", () => {
test("stages only lines in range when lines parameter is provided", async () => {
const dir = makeRepo();
// Create base commit
writeFileSync(join(dir, "code.ts"), "const b = 0;\n");
gitCmd(dir, "add", "code.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify file with multiple sections
writeFileSync(
join(dir, "code.ts"),
"const a = 1;\nconst b = 2;\nconst c = 3;\nconst d = 4;\nconst e = 5;\n",
);
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [
{
message: "feat: stage lines 2-3",
files: [{ path: "code.ts", lines: { from: 2, to: 3 } }],
},
],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
// Verify commit was created
const logResult = await spawnGitAsync(dir, ["log", "--oneline"]);
expect(logResult.ok).toBe(true);
expect(logResult.stdout).toContain("feat: stage lines 2-3");
});
test("stages whole file when lines parameter is absent", async () => {
const dir = makeRepo();
// Create base commit
writeFileSync(join(dir, "code.ts"), "const b = 0;\n");
gitCmd(dir, "add", "code.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify file with multiple lines
writeFileSync(join(dir, "code.ts"), "const a = 1;\nconst b = 2;\nconst c = 3;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [
{
message: "feat: stage all",
files: ["code.ts"],
},
],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
// Verify whole file was committed
const logResult = await spawnGitAsync(dir, ["log", "-1", "--name-status"]);
expect(logResult.ok).toBe(true);
expect(logResult.stdout).toContain("code.ts");
});
test("supports mixed file entries (with and without lines)", async () => {
const dir = makeRepo();
// Create base commit
writeFileSync(join(dir, "file1.ts"), "const b = 0;\n");
writeFileSync(join(dir, "file2.ts"), "const x = 0;\n");
gitCmd(dir, "add", "file1.ts", "file2.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify both files
writeFileSync(join(dir, "file1.ts"), "const a = 1;\nconst b = 2;\nconst c = 3;\n");
writeFileSync(join(dir, "file2.ts"), "const x = 1;\nconst y = 2;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [
{
message: "feat: mixed staging",
files: [
{ path: "file1.ts", lines: { from: 2, to: 2 } }, // Only line 2
"file2.ts", // Whole file
],
},
],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
// Verify both files are in the commit
const logResult = await spawnGitAsync(dir, ["log", "-1", "--name-status"]);
expect(logResult.stdout).toContain("file1.ts");
expect(logResult.stdout).toContain("file2.ts");
});
test("returns error when line range has no matching hunks", async () => {
const dir = makeRepo();
// Create base commit
writeFileSync(join(dir, "code.ts"), "const b = 0;\n");
gitCmd(dir, "add", "code.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify only first line
writeFileSync(join(dir, "code.ts"), "const a = 1;\n");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [
{
message: "feat: invalid range",
files: [{ path: "code.ts", lines: { from: 100, to: 200 } }],
},
],
});
const parsed = JSON.parse(text) as { ok: boolean; results: Array<{ error?: string }> };
expect(parsed.ok).toBe(false);
expect(parsed.results[0]?.error).toBe("stage_failed");
});
});
// ---------------------------------------------------------------------------
// Deletion staging (deleted tracked files)
// ---------------------------------------------------------------------------
describe("batch_commit deletion staging", () => {
test("stages deleted tracked file via git rm --cached", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
writeFileSync(join(dir, "delete-me.ts"), "const gone = 1;\n");
gitCmd(dir, "add", "base.ts", "delete-me.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Delete the file from disk
const { unlinkSync } = await import("node:fs");
unlinkSync(join(dir, "delete-me.ts"));
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "fix: remove delete-me", files: ["delete-me.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
// Verify file is no longer tracked
const lsResult = await spawnGitAsync(dir, ["ls-files", "delete-me.ts"]);
expect(lsResult.stdout.trim()).toBe("");
});
test("commit mixing edits and deletions succeeds atomically", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "keep.ts"), "const k = 0;\n");
writeFileSync(join(dir, "gone.ts"), "const g = 1;\n");
gitCmd(dir, "add", "keep.ts", "gone.ts");
gitCmd(dir, "commit", "-m", "chore: base");
// Modify keep.ts, delete gone.ts
writeFileSync(join(dir, "keep.ts"), "const k = 99;\n");
const { unlinkSync } = await import("node:fs");
unlinkSync(join(dir, "gone.ts"));
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "fix: edit + delete", files: ["keep.ts", "gone.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; committed: number };
expect(parsed.ok).toBe(true);
expect(parsed.committed).toBe(1);
// gone.ts untracked, keep.ts updated
const lsGone = await spawnGitAsync(dir, ["ls-files", "gone.ts"]);
expect(lsGone.stdout.trim()).toBe("");
});
test("lines + deleted file returns stage_failed with descriptive error", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
writeFileSync(join(dir, "gone.ts"), "const g = 1;\n");
gitCmd(dir, "add", "base.ts", "gone.ts");
gitCmd(dir, "commit", "-m", "chore: base");
const { unlinkSync } = await import("node:fs");
unlinkSync(join(dir, "gone.ts"));
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "bad", files: [{ path: "gone.ts", lines: { from: 1, to: 5 } }] }],
});
const parsed = JSON.parse(text) as {
ok: boolean;
results: Array<{ error?: string; detail?: string }>;
};
expect(parsed.ok).toBe(false);
expect(parsed.results[0]?.error).toBe("stage_failed");
expect(parsed.results[0]?.detail).toContain("deleted");
});
test("untracked missing file still fails with pathspec error", async () => {
const dir = makeRepo();
writeFileSync(join(dir, "base.ts"), "const b = 0;\n");
gitCmd(dir, "add", "base.ts");
gitCmd(dir, "commit", "-m", "chore: base");
const run = captureTool(registerBatchCommitTool);
const text = await run({
workspaceRoot: dir,
format: "json",
commits: [{ message: "bad", files: ["never-existed.ts"] }],
});
const parsed = JSON.parse(text) as { ok: boolean; results: Array<{ error?: string }> };
expect(parsed.ok).toBe(false);
expect(parsed.results[0]?.error).toBe("stage_failed");
});
});
let _seq = 0;