File size: 33,918 Bytes
06671aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// @ts-ignore vitest is not installed locally but provided by npx vitest at test time
import { describe, it, expect } from "vitest";
import {
    buildDocxEditSurface,
    renderDocxEditSurfaceForModel,
} from "./docxTrackedChanges";
import {
    TOOLS,
    makeCommentKey,
    verifyCommentBatchPostWrite,
    validateCommentPlanIntent,
    validatePlannedFinding,
    validateFindingTargetEvidence,
    buildWriterAnchorEligibilityFailures,
    buildCandidateContext,
    isPassItem,
    buildIgnoredPassReport,
    buildApplySummary,
    type CommentPlanIntent,
} from "./chatTools";

// Helper to build a minimal DOCX with a table using the docx package
async function buildTestDocx(): Promise<Buffer> {
    const { Document, Paragraph, Table, TableRow, TableCell, Packer } = await import("docx");
    const doc = new Document({
        sections: [{
            children: [
                new Paragraph({ text: "First body paragraph." }),
                new Table({
                    rows: [
                        new TableRow({
                            children: [
                                new TableCell({ children: [new Paragraph({ text: "Cell one text." })] }),
                                new TableCell({ children: [new Paragraph({ text: "Cell two text." })] }),
                            ],
                        }),
                    ],
                }),
                new Paragraph({ text: "Last body paragraph." }),
            ],
        }],
    });
    return Buffer.from(await Packer.toBuffer(doc));
}

// Helper to build a DOCX that differs in body text
async function buildModifiedDocx(): Promise<Buffer> {
    const { Document, Paragraph, Packer } = await import("docx");
    const doc = new Document({
        sections: [{
            children: [
                new Paragraph({ text: "Modified first body paragraph." }),
                new Paragraph({ text: "Last body paragraph." }),
            ],
        }],
    });
    return Buffer.from(await Packer.toBuffer(doc));
}

// Helper to inject a comments.xml into a docx buffer
async function injectCommentsXml(docxBytes: Buffer, commentCount: number): Promise<Buffer> {
    const JSZip = (await import("jszip")).default;
    const zip = await JSZip.loadAsync(docxBytes);
    const commentsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
${Array.from({ length: commentCount }, (_, i) =>
    `<w:comment w:id="${i}" w:author="Mike"><w:p><w:r><w:t>Comment ${i}</w:t></w:r></w:p></w:comment>`
).join("\n")}
</w:comments>`;
    zip.file("word/comments.xml", commentsXml);
    const [contentTypes] = await Promise.all([
        zip.file("[Content_Types].xml")?.async("string") ?? "",
    ]);
    let newContentTypes = contentTypes;
    if (!contentTypes.includes("comments.xml")) {
        newContentTypes = contentTypes.replace(
            "</Types>",
            '<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/></Types>'
        );
        zip.file("[Content_Types].xml", newContentTypes);
    }
    return Buffer.from(await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }));
}

// Build a synthetic anchor manifest from a surface for testing validateCommentPlanIntent
function buildTestManifest(surface: Awaited<ReturnType<typeof buildDocxEditSurface>>) {
    const anchorMap = new Map();
    for (const a of surface.anchors) anchorMap.set(a.block_id, a);
    return {
        docLabel: "doc-0",
        documentId: "doc-uuid",
        docRevisionId: surface.surfaceId,
        surfaceId: surface.surfaceId,
        readSerial: 1,
        anchors: anchorMap,
    };
}

function completeIntent(
    overrides: Partial<CommentPlanIntent> = {},
): CommentPlanIntent {
    return {
        block_id: "P_0001",
        comment:
            "[RISK] Issue: Delivery wording is unclear. | Zamil Impact: Delay exposure. | Recommended Action: Clarify the trigger.",
        comment_key: "delivery-trigger",
        status: "RISK",
        reasoning: {
            clause_section: "Section 6 – Delivery",
            violated_standard: "Delivery trigger must be objective.",
            zamil_exposure: "Delivery timing may become disputed.",
        },
        target_text: "First body paragraph.",
        type: "COMMENT",
        ...overrides,
    };
}

describe("Comment batch pipeline — best-of-both-worlds refactor", () => {
    describe("Phase 1-2: Document surface and table-cell support", () => {
        it("includes table-cell paragraphs in the edit surface", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);

            // Should have 4 paragraphs: first body + 2 table cells + last body
            expect(surface.blocks.length).toBe(4);
            expect(surface.anchors.length).toBe(4);
        });

        it("exposes container=table_cell in the model surface render", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const rendered = renderDocxEditSurfaceForModel(surface);

            expect(rendered).toContain("container=table_cell");
            const tableCellBlocks = surface.anchors.filter((a) => a.container === "table_cell");
            expect(tableCellBlocks.length).toBe(2);

            for (const anchor of tableCellBlocks) {
                expect(rendered).toContain(`[[${anchor.block_id} type=paragraph container=table_cell`);
            }
        });

        it("does not skip paragraphs inside tables", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const tableTexts = surface.blocks
                .filter((_, i) => surface.anchors[i]?.container === "table_cell")
                .map((b) => b.text);

            expect(tableTexts).toContain("Cell one text.");
            expect(tableTexts).toContain("Cell two text.");
        });
    });

    describe("Phase 3-6: Anchor validation and comment keys", () => {
        it("uses explicit comment_key when provided", () => {
            const key = makeCommentKey({
                doc_id: "doc-0",
                block_id: "P_0001",
                target_text: "",
                anchor_mode: "paragraph",
                comment: "Some issue",
                comment_key: "delivery-timeline-issue",
            });
            expect(key).toBe("doc-0:delivery-timeline-issue");
        });

        it("falls back to doc_id:block_id:comment digest when comment_key is missing", () => {
            const key = makeCommentKey({
                doc_id: "doc-0",
                block_id: "P_0001",
                target_text: "",
                anchor_mode: "paragraph",
                comment: "Some issue here",
            });
            expect(key).toBe("doc-0:P_0001:Some issue here");
        });
    });

    describe("Phase 3: validateCommentPlanIntent against manifest", () => {
        it("passes when block_id exists in manifest and hashes match", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const manifest = buildTestManifest(surface);

            const result = validateCommentPlanIntent({
                intent: { block_id: "P_0001", comment: "Test comment" },
                manifest: manifest as any,
                currentSurface: surface,
            });

            expect(result.ok).toBe(true);
            if (result.ok) {
                expect(result.anchor.block_id).toBe("P_0001");
            }
        });

        it("fails with anchor_not_found when block_id is not in manifest", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const manifest = buildTestManifest(surface);

            const result = validateCommentPlanIntent({
                intent: { block_id: "P_9999", comment: "Test comment" },
                manifest: manifest as any,
                currentSurface: surface,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("anchor_not_found");
            }
        });

        it("fails with anchor_revision_stale when manifest surfaceId mismatches currentSurface", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const manifest = buildTestManifest(surface);
            // Mutate manifest surfaceId to simulate stale read
            const staleManifest = { ...manifest, docRevisionId: "stale:surface", surfaceId: "stale:surface" };

            const result = validateCommentPlanIntent({
                intent: { block_id: "P_0001", comment: "Test comment" },
                manifest: staleManifest as any,
                currentSurface: surface,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("anchor_revision_stale");
            }
        });

        it("fails with anchor_stale_requires_document_refresh when currentSurface is missing the block", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const manifest = buildTestManifest(surface);

            // Create a currentSurface with the SAME surfaceId but missing the target anchor
            // (simulates a case where the manifest says the block exists but live doc doesn't)
            const tamperedSurface = {
                ...surface,
                anchors: surface.anchors.filter((a) => a.block_id !== "P_0001"),
            };

            const result = validateCommentPlanIntent({
                intent: { block_id: "P_0001", comment: "Test comment" },
                manifest: manifest as any,
                currentSurface: tamperedSurface as any,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("anchor_stale_requires_document_refresh");
            }
        });

        it("fails with anchor_identity_mismatch when native_para_id differs", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const manifest = buildTestManifest(surface);

            // Mutate the currentSurface anchor to have a different native_para_id
            const tamperedSurface = {
                ...surface,
                anchors: surface.anchors.map((a, i) =>
                    i === 0 ? { ...a, native_para_id: "FAKE1234" } : a
                ),
            };

            const result = validateCommentPlanIntent({
                intent: { block_id: "P_0001", comment: "Test comment" },
                manifest: manifest as any,
                currentSurface: tamperedSurface as any,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("anchor_identity_mismatch");
            }
        });

        it("fails with ANCHOR_NOT_ELIGIBLE for a navigation anchor", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const ineligibleSurface = {
                ...surface,
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            role: "navigation" as const,
                            anchor_eligible: false,
                            anchor_rejection_reason: "table_of_contents" as const,
                            navigation_score: 1,
                        }
                        : anchor,
                ),
                navigationRegions: [
                    {
                        startBlockId: "P_0001",
                        endBlockId: "P_0001",
                        startIndex: 0,
                        endIndex: 0,
                        reason: "table_of_contents" as const,
                    },
                ],
            };
            const manifest = buildTestManifest(ineligibleSurface);

            const result = validateCommentPlanIntent({
                intent: {
                    block_id: "P_0001",
                    comment: "Test comment",
                    target_text: "First body paragraph.",
                },
                manifest: manifest as any,
                currentSurface: ineligibleSurface,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("ANCHOR_NOT_ELIGIBLE");
                expect(result.excludedNavigationRegion).toMatchObject({
                    start_block_id: "P_0001",
                    end_block_id: "P_0001",
                });
                expect(result.candidates?.every((candidate) => candidate.block_id !== "P_0001")).toBe(true);
            }
        });

        it("rejects a tracked edit planned on a navigation block", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const ineligibleSurface = {
                ...surface,
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            role: "navigation" as const,
                            anchor_eligible: false,
                            anchor_rejection_reason: "table_of_contents" as const,
                            navigation_label: "First body paragraph",
                        }
                        : anchor,
                ),
                navigationRegions: [
                    {
                        startBlockId: "P_0001",
                        endBlockId: "P_0001",
                        startIndex: 0,
                        endIndex: 0,
                        reason: "table_of_contents" as const,
                    },
                ],
            };

            const result = validatePlannedFinding({
                intent: completeIntent({
                    target_text: undefined,
                    type: "REWRITE_PARAGRAPH",
                    new_text: "Replacement wording.",
                }),
                manifest: buildTestManifest(ineligibleSurface) as any,
                currentSurface: ineligibleSurface,
                allowCommentFallback: true,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("ANCHOR_NOT_ELIGIBLE");
            }
        });
    });

    describe("Phase 3: supporting evidence and deterministic redirect", () => {
        it("requires meaningful target_text for non-MISSING findings", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const result = validateFindingTargetEvidence({
                intent: completeIntent({ target_text: undefined }),
                surface,
                anchor: surface.anchors[0],
            });

            expect(result).toMatchObject({
                ok: false,
                failureCode: "schema_missing_target_text",
            });
        });

        it("rejects target_text that is not in the selected block", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const result = validateFindingTargetEvidence({
                intent: completeIntent({
                    target_text: "Supplier shall deliver within thirty days.",
                }),
                surface,
                anchor: surface.anchors[0],
            });

            expect(result).toMatchObject({
                ok: false,
                failureCode: "target_text_not_in_block",
            });
        });

        it("allows MISSING findings without target_text", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const result = validateFindingTargetEvidence({
                intent: completeIntent({
                    status: "MISSING",
                    target_text: undefined,
                }),
                surface,
                anchor: surface.anchors[0],
            });

            expect(result).toEqual({ ok: true });
        });

        it("rejects heading-only evidence when substantive text follows", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const headingSurface = {
                ...surface,
                blocks: surface.blocks.map((block, index) =>
                    index === 0
                        ? { ...block, text: "Section 6 – Delivery", length: 20 }
                        : index === 1
                            ? {
                                ...block,
                                text:
                                    "The Supplier shall deliver all materials within thirty days after receiving the approved purchase order and all required drawings.",
                                length: 124,
                            }
                            : block,
                ),
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            style_id: "Heading1",
                            style_name: "Heading 1",
                            text_preview: "Section 6 – Delivery",
                        }
                        : anchor,
                ),
            };
            const result = validateFindingTargetEvidence({
                intent: completeIntent({
                    target_text: "Section 6 – Delivery",
                }),
                surface: headingSurface,
                anchor: headingSurface.anchors[0],
            });

            expect(result).toMatchObject({
                ok: false,
                failureCode: "target_text_heading_only",
            });
        });

        it("auto-redirects only a unique eligible title and quote match", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const clauseText =
                "Section 6 Delivery Supplier shall deliver the materials within thirty days after receiving the approved purchase order.";
            const redirectSurface = {
                ...surface,
                blocks: surface.blocks.map((block, index) =>
                    index === 0
                        ? { ...block, text: "Section 6 Delivery 12" }
                        : index === 1
                            ? { ...block, text: clauseText }
                            : block,
                ),
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            role: "navigation" as const,
                            anchor_eligible: false,
                            anchor_rejection_reason: "manual_index" as const,
                            navigation_label: "Section 6 Delivery",
                            text_preview: "Section 6 Delivery 12",
                        }
                        : index === 1
                            ? { ...anchor, text_preview: clauseText }
                            : anchor,
                ),
                navigationRegions: [
                    {
                        startBlockId: "P_0001",
                        endBlockId: "P_0001",
                        startIndex: 0,
                        endIndex: 0,
                        reason: "manual_index" as const,
                    },
                ],
            };
            const result = validatePlannedFinding({
                intent: completeIntent({
                    block_id: "P_0001",
                    target_text:
                        "Supplier shall deliver the materials within thirty days",
                }),
                manifest: buildTestManifest(redirectSurface) as any,
                currentSurface: redirectSurface,
                allowCommentFallback: true,
            });

            expect(result.ok).toBe(true);
            if (result.ok) {
                expect(result.item.block_id).toBe("P_0002");
                expect(result.item.anchorRedirectedFrom).toBe("P_0001");
                expect(result.item.anchorRedirectedTo).toBe("P_0002");
            }
        });

        it("does not auto-redirect when two eligible blocks match", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const clauseText =
                "Section 6 Delivery Supplier shall deliver the materials within thirty days after receiving the approved purchase order.";
            const ambiguousSurface = {
                ...surface,
                blocks: surface.blocks.map((block, index) =>
                    index === 0
                        ? { ...block, text: "Section 6 Delivery 12" }
                        : index === 1 || index === 2
                            ? { ...block, text: clauseText }
                            : block,
                ),
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            role: "navigation" as const,
                            anchor_eligible: false,
                            anchor_rejection_reason: "manual_index" as const,
                            navigation_label: "Section 6 Delivery",
                            text_preview: "Section 6 Delivery 12",
                        }
                        : index === 1 || index === 2
                            ? { ...anchor, text_preview: clauseText }
                            : anchor,
                ),
                navigationRegions: [
                    {
                        startBlockId: "P_0001",
                        endBlockId: "P_0001",
                        startIndex: 0,
                        endIndex: 0,
                        reason: "manual_index" as const,
                    },
                ],
            };
            const result = validatePlannedFinding({
                intent: completeIntent({
                    block_id: "P_0001",
                    target_text:
                        "Supplier shall deliver the materials within thirty days",
                }),
                manifest: buildTestManifest(ambiguousSurface) as any,
                currentSurface: ambiguousSurface,
                allowCommentFallback: true,
            });

            expect(result.ok).toBe(false);
            if (!result.ok) {
                expect(result.failureCode).toBe("ANCHOR_NOT_ELIGIBLE");
            }
        });
    });

    describe("Phase 5: Candidate context for corrections", () => {
        it("returns nearby anchors around the target block_id", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);

            const candidates = buildCandidateContext({
                surface,
                targetBlockId: "P_0002",
                windowSize: 2,
            });

            // Should include P_0001, P_0002, P_0003 (window of 2 around index 1)
            expect(candidates.length).toBeGreaterThan(0);
            expect(candidates.some((c) => c.block_id === "P_0002")).toBe(true);
        });

        it("never returns navigation anchors as correction context", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const ineligibleSurface = {
                ...surface,
                anchors: surface.anchors.map((anchor, index) =>
                    index === 0
                        ? {
                            ...anchor,
                            role: "navigation" as const,
                            anchor_eligible: false,
                            anchor_rejection_reason: "table_of_contents" as const,
                        }
                        : anchor,
                ),
            };

            const candidates = buildCandidateContext({
                surface: ineligibleSurface,
                targetBlockId: "P_0001",
                windowSize: 3,
            });

            expect(candidates.some((candidate) => candidate.block_id === "P_0001")).toBe(false);
        });
    });

    describe("New tools exist in TOOLS array", () => {
        it("includes plan_comments_on_document", () => {
            const names = TOOLS.map((t: any) => t.function.name);
            expect(names).toContain("plan_comments_on_document");
        });

        it("includes correct_comment_anchors", () => {
            const names = TOOLS.map((t: any) => t.function.name);
            expect(names).toContain("correct_comment_anchors");
        });

        it("still includes comment_on_document for backward compatibility", () => {
            const names = TOOLS.map((t: any) => t.function.name);
            expect(names).toContain("comment_on_document");
        });
    });

    describe("Writer-boundary defense", () => {
        it("rejects ineligible anchors before the Python writer", async () => {
            const bytes = await buildTestDocx();
            const surface = await buildDocxEditSurface(bytes);
            const anchor = {
                ...surface.anchors[0],
                role: "navigation" as const,
                anchor_eligible: false,
                anchor_rejection_reason: "table_of_contents" as const,
            };

            const failures = buildWriterAnchorEligibilityFailures([
                {
                    id: "comment-1",
                    args: {
                        block_id: anchor.block_id,
                        comment_key: "delivery-trigger",
                        type: "COMMENT",
                    },
                    anchor,
                },
            ]);

            expect(failures).toHaveLength(1);
            expect(failures[0]).toMatchObject({
                failure_code: "ANCHOR_NOT_ELIGIBLE",
                model_block_id: "P_0001",
                anchor_rejection_reason: "table_of_contents",
            });
        });
    });

    describe("Phase 9-10: Post-write verification and manifest refresh", () => {
        it("passes verification when body text is unchanged and comments exist in xml", async () => {
            const original = await buildTestDocx();
            const commented = await injectCommentsXml(original, 2);

            const verification = await verifyCommentBatchPostWrite({
                originalBytes: original,
                commentedBytes: commented,
                expectedAppliedCount: 2,
                appliedReports: [
                    { status: "applied", model_block_id: "P_0001" },
                    { status: "applied", model_block_id: "P_0002" },
                ],
            });

            expect(verification.ok).toBe(true);
            expect(verification.body_text_unchanged).toBe(true);
            expect(verification.comments_in_xml).toBe(2);
            expect(verification.missing_from_xml).toBe(0);
            expect(verification.original_block_count).toBe(verification.commented_block_count);
        });

        it("fails verification when body text changed after write", async () => {
            const original = await buildTestDocx();
            const modified = await buildModifiedDocx();
            const commented = await injectCommentsXml(modified, 1);

            const verification = await verifyCommentBatchPostWrite({
                originalBytes: original,
                commentedBytes: commented,
                expectedAppliedCount: 1,
                appliedReports: [{ status: "applied", model_block_id: "P_0001" }],
            });

            expect(verification.ok).toBe(false);
            expect(verification.body_text_unchanged).toBe(false);
        });

        it("detects missing comments in comments.xml", async () => {
            const original = await buildTestDocx();
            // Inject fewer comments than expected
            const commented = await injectCommentsXml(original, 1);

            const verification = await verifyCommentBatchPostWrite({
                originalBytes: original,
                commentedBytes: commented,
                expectedAppliedCount: 3,
                appliedReports: [
                    { status: "applied", model_block_id: "P_0001" },
                    { status: "applied", model_block_id: "P_0002" },
                    { status: "applied", model_block_id: "P_0003" },
                ],
            });

            expect(verification.ok).toBe(false);
            expect(verification.missing_from_xml).toBeGreaterThan(0);
        });

        it("counts applied comments correctly in summary", async () => {
            const original = await buildTestDocx();
            const commented = await injectCommentsXml(original, 2);

            const verification = await verifyCommentBatchPostWrite({
                originalBytes: original,
                commentedBytes: commented,
                expectedAppliedCount: 2,
                appliedReports: [
                    { status: "applied", model_block_id: "P_0001" },
                    { status: "applied", model_block_id: "P_0002" },
                    { status: "not_applied", model_block_id: "P_0003", failure_code: "anchor_not_found" },
                ],
            });

            expect(verification.ok).toBe(true);
            expect(verification.expected_applied).toBe(2);
        });
    });

    describe("Acceptance criteria: surface stability", () => {
        it("preserves paragraph count after comment-only write", async () => {
            const original = await buildTestDocx();
            const commented = await injectCommentsXml(original, 1);

            const verification = await verifyCommentBatchPostWrite({
                originalBytes: original,
                commentedBytes: commented,
                expectedAppliedCount: 1,
                appliedReports: [{ status: "applied", model_block_id: "P_0001" }],
            });

            expect(verification.original_block_count).toBe(4);
            expect(verification.commented_block_count).toBe(4);
        });
    });

    describe("PASS filtering and reasoning", () => {
        it("detects PASS by status", () => {
            expect(
                isPassItem({ block_id: "P_0001", comment: "ok", status: "PASS" })
            ).toBe(true);
            expect(
                isPassItem({ block_id: "P_0001", comment: "ok", status: "pass" })
            ).toBe(true);
            expect(
                isPassItem({ block_id: "P_0001", comment: "ok", status: "FAIL" })
            ).toBe(false);
        });

        it("detects PASS by comment prefix when status is missing", () => {
            expect(
                isPassItem({ block_id: "P_0001", comment: "[PASS] Looks fine." })
            ).toBe(true);
            expect(
                isPassItem({ block_id: "P_0001", comment: "[pass] Looks fine." })
            ).toBe(true);
            expect(
                isPassItem({ block_id: "P_0001", comment: "[FAIL] Issue." })
            ).toBe(false);
        });

        it("builds ignored_pass report shape", () => {
            const report = buildIgnoredPassReport(
                { block_id: "P_0001", comment: "[PASS] ok", comment_key: "ok-1", reasoning: { clause_section: "c1", violated_standard: "v1", zamil_exposure: "z1" } },
                3
            );
            expect(report.status).toBe("ignored_pass");
            expect(report.ignored_reason).toBe("pass_status");
            expect(report.comment_key).toBe("ok-1");
            expect(report.reasoning).toEqual({ clause_section: "c1", violated_standard: "v1", zamil_exposure: "z1" });
            expect(report.failure_code).toBeNull();
        });

        it("excludes ignored_pass from apply summary failed count", () => {
            const summary = buildApplySummary([
                { status: "applied", id: "a" },
                { status: "ignored_pass", id: "b" },
                { status: "not_applied", id: "c", failure_code: "anchor_not_found" },
            ])!;
            expect(summary.total).toBe(2);
            expect(summary.applied).toBe(1);
            expect(summary.failed).toBe(1);
            expect(summary.failures.length).toBe(1);
            expect(summary.failures[0].id).toBe("c");
        });

        it("counts ignored_pass as zero actionable denominator impact", () => {
            const summary = buildApplySummary([
                { status: "ignored_pass", id: "b" },
                { status: "ignored_pass", id: "c" },
            ])!;
            expect(summary.total).toBe(0);
            expect(summary.applied).toBe(0);
            expect(summary.failed).toBe(0);
            expect(summary.failures.length).toBe(0);
        });
    });
});