docrev 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.gitattributes +1 -1
  2. package/CHANGELOG.md +207 -197
  3. package/PLAN-tables-and-postprocess.md +850 -850
  4. package/README.md +433 -433
  5. package/bin/rev.js +11 -11
  6. package/bin/rev.ts +145 -145
  7. package/completions/rev.bash +127 -127
  8. package/completions/rev.ps1 +210 -210
  9. package/completions/rev.zsh +207 -207
  10. package/dist/lib/annotations.d.ts.map +1 -1
  11. package/dist/lib/annotations.js +28 -0
  12. package/dist/lib/annotations.js.map +1 -1
  13. package/dist/lib/build.d.ts +28 -0
  14. package/dist/lib/build.d.ts.map +1 -1
  15. package/dist/lib/build.js +81 -4
  16. package/dist/lib/build.js.map +1 -1
  17. package/dist/lib/commands/comments.d.ts.map +1 -1
  18. package/dist/lib/commands/comments.js +58 -28
  19. package/dist/lib/commands/comments.js.map +1 -1
  20. package/dist/lib/commands/context.d.ts +1 -0
  21. package/dist/lib/commands/context.d.ts.map +1 -1
  22. package/dist/lib/commands/context.js +1 -0
  23. package/dist/lib/commands/context.js.map +1 -1
  24. package/dist/lib/commands/core.d.ts.map +1 -1
  25. package/dist/lib/commands/core.js +25 -8
  26. package/dist/lib/commands/core.js.map +1 -1
  27. package/dist/lib/commands/response.js +1 -1
  28. package/dist/lib/commands/response.js.map +1 -1
  29. package/dist/lib/commands/utilities.js +164 -164
  30. package/dist/lib/commands/word-tools.js +8 -8
  31. package/dist/lib/grammar.js +3 -3
  32. package/dist/lib/import.d.ts +14 -0
  33. package/dist/lib/import.d.ts.map +1 -1
  34. package/dist/lib/import.js +23 -0
  35. package/dist/lib/import.js.map +1 -1
  36. package/dist/lib/input.d.ts +67 -0
  37. package/dist/lib/input.d.ts.map +1 -0
  38. package/dist/lib/input.js +164 -0
  39. package/dist/lib/input.js.map +1 -0
  40. package/dist/lib/macro-filter.lua +201 -201
  41. package/dist/lib/pdf-comments.js +44 -44
  42. package/dist/lib/plugins.js +57 -57
  43. package/dist/lib/pptx-color-filter.lua +37 -37
  44. package/dist/lib/pptx-themes.js +115 -115
  45. package/dist/lib/response.d.ts +1 -1
  46. package/dist/lib/response.d.ts.map +1 -1
  47. package/dist/lib/response.js +5 -2
  48. package/dist/lib/response.js.map +1 -1
  49. package/dist/lib/schema.d.ts.map +1 -1
  50. package/dist/lib/schema.js +8 -2
  51. package/dist/lib/schema.js.map +1 -1
  52. package/dist/lib/spelling.js +2 -2
  53. package/dist/lib/templates.js +387 -387
  54. package/dist/lib/themes.js +51 -51
  55. package/eslint.config.js +27 -27
  56. package/lib/anchor-match.ts +307 -307
  57. package/lib/annotations.ts +695 -664
  58. package/lib/build.ts +2047 -1956
  59. package/lib/citations.ts +160 -160
  60. package/lib/commands/build.ts +885 -885
  61. package/lib/commands/citations.ts +515 -515
  62. package/lib/commands/comments.ts +1077 -1050
  63. package/lib/commands/context.ts +185 -176
  64. package/lib/commands/core.ts +328 -309
  65. package/lib/commands/doi.ts +451 -451
  66. package/lib/commands/file-ops.ts +372 -372
  67. package/lib/commands/history.ts +320 -320
  68. package/lib/commands/index.ts +87 -87
  69. package/lib/commands/init.ts +259 -259
  70. package/lib/commands/merge-resolve.ts +378 -378
  71. package/lib/commands/preview.ts +178 -178
  72. package/lib/commands/project-info.ts +244 -244
  73. package/lib/commands/quality.ts +517 -517
  74. package/lib/commands/response.ts +454 -454
  75. package/lib/commands/section-boundaries.ts +82 -82
  76. package/lib/commands/sections.ts +451 -451
  77. package/lib/commands/sync.ts +689 -689
  78. package/lib/commands/text-ops.ts +449 -449
  79. package/lib/commands/utilities.ts +448 -448
  80. package/lib/commands/verify-anchors.ts +272 -272
  81. package/lib/commands/word-tools.ts +340 -340
  82. package/lib/comment-realign.ts +99 -99
  83. package/lib/config.ts +84 -84
  84. package/lib/crossref.ts +781 -781
  85. package/lib/csl.ts +191 -191
  86. package/lib/dependencies.ts +132 -132
  87. package/lib/diff-engine.ts +465 -465
  88. package/lib/doi-cache.ts +115 -115
  89. package/lib/doi.ts +879 -879
  90. package/lib/equations.ts +506 -506
  91. package/lib/errors.ts +350 -350
  92. package/lib/format.ts +541 -541
  93. package/lib/git.ts +326 -326
  94. package/lib/grammar.ts +303 -303
  95. package/lib/image-registry.ts +180 -180
  96. package/lib/import.ts +932 -906
  97. package/lib/input.ts +174 -0
  98. package/lib/journals.ts +543 -543
  99. package/lib/macro-filter.lua +201 -201
  100. package/lib/macros.ts +273 -273
  101. package/lib/merge.ts +633 -633
  102. package/lib/ooxml.ts +768 -768
  103. package/lib/orcid.ts +144 -144
  104. package/lib/pdf-comments.ts +263 -263
  105. package/lib/pdf-import.ts +524 -524
  106. package/lib/plugins.ts +362 -362
  107. package/lib/postprocess.ts +188 -188
  108. package/lib/pptx-color-filter.lua +37 -37
  109. package/lib/pptx-template.ts +469 -469
  110. package/lib/pptx-themes.ts +483 -483
  111. package/lib/protect-restore.ts +520 -520
  112. package/lib/rate-limiter.ts +127 -127
  113. package/lib/response.ts +200 -197
  114. package/lib/restore-references.ts +240 -240
  115. package/lib/review.ts +327 -327
  116. package/lib/schema.ts +494 -488
  117. package/lib/scientific-words.ts +73 -73
  118. package/lib/sections.ts +428 -428
  119. package/lib/slides.ts +756 -756
  120. package/lib/spelling.ts +334 -334
  121. package/lib/templates.ts +526 -526
  122. package/lib/themes.ts +742 -742
  123. package/lib/trackchanges.ts +166 -166
  124. package/lib/tui.ts +450 -450
  125. package/lib/types.ts +546 -546
  126. package/lib/undo.ts +250 -250
  127. package/lib/utils.ts +69 -69
  128. package/lib/variables.ts +179 -179
  129. package/lib/word-extraction.ts +525 -525
  130. package/lib/word.ts +526 -526
  131. package/lib/wordcomments.ts +789 -789
  132. package/package.json +1 -1
  133. package/scripts/postbuild.js +47 -47
  134. package/skill/REFERENCE.md +550 -550
  135. package/skill/SKILL.md +302 -302
  136. package/tsconfig.json +26 -26
  137. package/types/index.d.ts +531 -531
  138. package/issues.md +0 -180
  139. package/site/assets/extra.css +0 -208
  140. package/site/commands.html +0 -926
  141. package/site/configuration.html +0 -469
  142. package/site/index.html +0 -288
  143. package/site/troubleshooting.html +0 -461
  144. package/site/workflow.html +0 -518
@@ -1,307 +1,307 @@
1
- /**
2
- * Anchor matching primitives shared between sync (insertion) and
3
- * verify-anchors (drift reporting). The functions are pure: given an
4
- * anchor string and surrounding context, locate candidate positions in
5
- * a target text using progressively looser strategies.
6
- */
7
-
8
- import { stripAnnotations } from './annotations.js';
9
-
10
- export type AnchorStrategy =
11
- | 'direct'
12
- | 'normalized'
13
- | 'stripped'
14
- | 'partial-start'
15
- | 'partial-start-stripped'
16
- | 'partial-window'
17
- | 'partial-window-stripped'
18
- | 'context-both'
19
- | 'context-before'
20
- | 'context-after'
21
- | 'split-match'
22
- | 'empty-anchor'
23
- | 'failed';
24
-
25
- export interface AnchorSearchResult {
26
- occurrences: number[];
27
- matchedAnchor: string | null;
28
- strategy: AnchorStrategy;
29
- stripped?: boolean;
30
- }
31
-
32
- /**
33
- * Strip CriticMarkup so the matcher sees plain prose instead of
34
- * `{++inserted++}`/`{--deleted--}`/etc. Used when an anchor lives
35
- * underneath previously imported track changes. Delegates to the single
36
- * annotation stripper so the matcher and the build path resolve markup the
37
- * same way — a payload containing `+`, `-`, or `~` is handled correctly.
38
- */
39
- export function stripCriticMarkup(text: string): string {
40
- return stripAnnotations(text);
41
- }
42
-
43
- /**
44
- * Return every starting index where `needle` occurs in `haystack`.
45
- * Empty needles return no occurrences (empty matches are not useful
46
- * for anchor placement).
47
- */
48
- /**
49
- * Score how well the docx-side `before` / `after` context matches the
50
- * surroundings of a candidate position in the target text. Used by
51
- * `verify-anchors` to tell apart "multiple hits but context picks one
52
- * cleanly" (sync will place it correctly) from "multiple hits, context
53
- * doesn't help" (truly ambiguous, needs human placement).
54
- *
55
- * Returns 0 if no context was provided.
56
- */
57
- export function scoreContextAt(
58
- pos: number,
59
- text: string,
60
- before: string,
61
- after: string,
62
- anchorLen: number,
63
- ): number {
64
- let score = 0;
65
- if (before) {
66
- const contextBefore = text.slice(Math.max(0, pos - before.length - 20), pos).toLowerCase();
67
- const beforeLower = before.toLowerCase();
68
- const beforeWords = beforeLower.split(/\s+/).filter(w => w.length > 3);
69
- for (const word of beforeWords) {
70
- if (contextBefore.includes(word)) score += 2;
71
- }
72
- if (contextBefore.includes(beforeLower.slice(-30))) score += 5;
73
- }
74
- if (after) {
75
- const contextAfter = text.slice(pos + anchorLen, pos + anchorLen + after.length + 20).toLowerCase();
76
- const afterLower = after.toLowerCase();
77
- const afterWords = afterLower.split(/\s+/).filter(w => w.length > 3);
78
- for (const word of afterWords) {
79
- if (contextAfter.includes(word)) score += 2;
80
- }
81
- if (contextAfter.includes(afterLower.slice(0, 30))) score += 5;
82
- }
83
- return score;
84
- }
85
-
86
- export function findAllOccurrences(haystack: string, needle: string): number[] {
87
- if (!needle || needle.length === 0) return [];
88
- const occurrences: number[] = [];
89
- let idx = 0;
90
- while ((idx = haystack.indexOf(needle, idx)) !== -1) {
91
- occurrences.push(idx);
92
- idx += 1;
93
- }
94
- return occurrences;
95
- }
96
-
97
- /**
98
- * Find candidate positions for `anchor` in `text`, falling back through
99
- * progressively looser strategies (whitespace normalization, stripped
100
- * CriticMarkup, partial-prefix, surrounding context, word splitting).
101
- *
102
- * The returned `strategy` lets callers distinguish a clean direct hit
103
- * from a fuzzy approximation — useful for drift reporting.
104
- */
105
- export function findAnchorInText(
106
- anchor: string,
107
- text: string,
108
- before: string = '',
109
- after: string = ''
110
- ): AnchorSearchResult {
111
- // Empty anchor: skip directly to context-based matching
112
- if (!anchor || anchor.trim().length === 0) {
113
- if (before || after) {
114
- const beforeLower = (before || '').toLowerCase();
115
- const afterLower = (after || '').toLowerCase();
116
- const textLower = text.toLowerCase();
117
-
118
- if (before && after) {
119
- const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
120
- if (beforeIdx !== -1) {
121
- const searchStart = beforeIdx + beforeLower.slice(-50).length;
122
- const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
123
- if (afterIdx !== -1 && afterIdx - searchStart < 500) {
124
- return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
125
- }
126
- }
127
- }
128
-
129
- if (before) {
130
- const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
131
- if (beforeIdx !== -1) {
132
- return {
133
- occurrences: [beforeIdx + beforeLower.slice(-30).length],
134
- matchedAnchor: null,
135
- strategy: 'context-before',
136
- };
137
- }
138
- }
139
-
140
- if (after) {
141
- const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
142
- if (afterIdx !== -1) {
143
- return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
144
- }
145
- }
146
- }
147
- return { occurrences: [], matchedAnchor: null, strategy: 'empty-anchor' };
148
- }
149
-
150
- const anchorLower = anchor.toLowerCase();
151
- const textLower = text.toLowerCase();
152
-
153
- // Strategy 1: direct match
154
- let occurrences = findAllOccurrences(textLower, anchorLower);
155
- if (occurrences.length > 0) {
156
- return { occurrences, matchedAnchor: anchor, strategy: 'direct' };
157
- }
158
-
159
- // Strategy 2: normalized whitespace
160
- const normalizedAnchor = anchor.replace(/\s+/g, ' ').toLowerCase();
161
- const normalizedText = text.replace(/\s+/g, ' ').toLowerCase();
162
- const idx = normalizedText.indexOf(normalizedAnchor);
163
- if (idx !== -1) {
164
- return { occurrences: [idx], matchedAnchor: anchor, strategy: 'normalized' };
165
- }
166
-
167
- // Strategy 3: match in stripped CriticMarkup version
168
- const strippedText = stripCriticMarkup(text);
169
- const strippedLower = strippedText.toLowerCase();
170
- occurrences = findAllOccurrences(strippedLower, anchorLower);
171
- if (occurrences.length > 0) {
172
- return { occurrences, matchedAnchor: anchor, strategy: 'stripped', stripped: true };
173
- }
174
-
175
- // Strategy 4: word window from anchor (prefix or interior).
176
- // Sliding the window across the anchor catches the case where the
177
- // anchor's prefix has been edited but a chunk in the middle/end
178
- // survived intact (e.g. "Sensitivity analyses were performed by
179
- // perturbing the prior variance" → drifted "Sensitivity analyses
180
- // perturbed the prior variance" still contains "the prior variance").
181
- const words = anchor.split(/\s+/);
182
- if (words.length > 3) {
183
- for (let n = Math.min(6, words.length); n >= 3; n--) {
184
- for (let start = 0; start + n <= words.length; start++) {
185
- const window = words.slice(start, start + n).join(' ');
186
- const windowLower = window.toLowerCase();
187
- if (windowLower.length < 15) continue;
188
-
189
- let occ = findAllOccurrences(textLower, windowLower);
190
- if (occ.length > 0) {
191
- const strategy: AnchorStrategy = start === 0 ? 'partial-start' : 'partial-window';
192
- return { occurrences: occ, matchedAnchor: window, strategy };
193
- }
194
- occ = findAllOccurrences(strippedLower, windowLower);
195
- if (occ.length > 0) {
196
- const strategy: AnchorStrategy = start === 0 ? 'partial-start-stripped' : 'partial-window-stripped';
197
- return { occurrences: occ, matchedAnchor: window, strategy, stripped: true };
198
- }
199
- }
200
- }
201
- }
202
-
203
- // Strategy 5: context (before/after) only.
204
- //
205
- // For a non-empty anchor that already failed every text-based strategy
206
- // above, we treat context as a degraded placement: classify it
207
- // 'context-only' so callers can warn the user. We also reject
208
- // implausible brackets — if both contexts match but the gap between
209
- // them is far too small to contain the anchor (e.g. the anchored
210
- // sentence was deleted), do not silently land the comment between
211
- // the surviving sentences. Return 'failed' so the user is told to
212
- // place it manually.
213
- if (before || after) {
214
- const beforeLower = before.toLowerCase();
215
- const afterLower = after.toLowerCase();
216
- const anchorLen = anchor.length;
217
-
218
- if (before && after) {
219
- const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
220
- if (beforeIdx !== -1) {
221
- const searchStart = beforeIdx + beforeLower.slice(-50).length;
222
- const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
223
- if (afterIdx !== -1) {
224
- const gap = afterIdx - searchStart;
225
- // Require the bracket to plausibly contain a remnant of the anchor.
226
- // Below 30% of anchor length: anchor was deleted — refuse to place.
227
- // Above 2× anchor length + slack: brackets are too far apart, the
228
- // matcher has latched onto unrelated repeats of common context.
229
- const minGap = Math.floor(anchorLen * 0.3);
230
- const maxGap = Math.min(500, anchorLen * 2 + 50);
231
- if (gap >= minGap && gap <= maxGap) {
232
- return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
233
- }
234
- // Both brackets found but gap implausible: anchor likely deleted.
235
- // Don't fall back to single-side context — that would silently
236
- // place the comment in the wrong location.
237
- return { occurrences: [], matchedAnchor: null, strategy: 'failed' };
238
- }
239
- }
240
- }
241
-
242
- if (before) {
243
- const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
244
- if (beforeIdx !== -1) {
245
- return {
246
- occurrences: [beforeIdx + beforeLower.slice(-30).length],
247
- matchedAnchor: null,
248
- strategy: 'context-before',
249
- };
250
- }
251
- }
252
-
253
- if (after) {
254
- const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
255
- if (afterIdx !== -1) {
256
- return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
257
- }
258
- }
259
- }
260
-
261
- // Strategy 6: split anchor on transition characters
262
- const splitPatterns = [' ', ', ', '. ', ' - ', ' – '];
263
- for (const sep of splitPatterns) {
264
- if (anchor.includes(sep)) {
265
- const parts = anchor.split(sep).filter(p => p.length >= 4);
266
- for (const part of parts) {
267
- const partLower = part.toLowerCase();
268
- occurrences = findAllOccurrences(textLower, partLower);
269
- if (occurrences.length > 0 && occurrences.length < 5) {
270
- return { occurrences, matchedAnchor: part, strategy: 'split-match' };
271
- }
272
- }
273
- }
274
- }
275
-
276
- return { occurrences: [], matchedAnchor: null, strategy: 'failed' };
277
- }
278
-
279
- /**
280
- * Classify a strategy as a clean hit, a fuzzy/drifted hit, or no hit.
281
- * Used by `verify-anchors` to summarize per-comment match quality.
282
- */
283
- export type AnchorMatchQuality = 'clean' | 'drift' | 'context-only' | 'unmatched';
284
-
285
- export function classifyStrategy(strategy: AnchorStrategy, occurrences: number): AnchorMatchQuality {
286
- if (occurrences === 0) return 'unmatched';
287
- switch (strategy) {
288
- case 'direct':
289
- case 'normalized':
290
- return 'clean';
291
- case 'stripped':
292
- case 'partial-start':
293
- case 'partial-start-stripped':
294
- case 'partial-window':
295
- case 'partial-window-stripped':
296
- case 'split-match':
297
- return 'drift';
298
- case 'context-both':
299
- case 'context-before':
300
- case 'context-after':
301
- return 'context-only';
302
- case 'empty-anchor':
303
- case 'failed':
304
- default:
305
- return 'unmatched';
306
- }
307
- }
1
+ /**
2
+ * Anchor matching primitives shared between sync (insertion) and
3
+ * verify-anchors (drift reporting). The functions are pure: given an
4
+ * anchor string and surrounding context, locate candidate positions in
5
+ * a target text using progressively looser strategies.
6
+ */
7
+
8
+ import { stripAnnotations } from './annotations.js';
9
+
10
+ export type AnchorStrategy =
11
+ | 'direct'
12
+ | 'normalized'
13
+ | 'stripped'
14
+ | 'partial-start'
15
+ | 'partial-start-stripped'
16
+ | 'partial-window'
17
+ | 'partial-window-stripped'
18
+ | 'context-both'
19
+ | 'context-before'
20
+ | 'context-after'
21
+ | 'split-match'
22
+ | 'empty-anchor'
23
+ | 'failed';
24
+
25
+ export interface AnchorSearchResult {
26
+ occurrences: number[];
27
+ matchedAnchor: string | null;
28
+ strategy: AnchorStrategy;
29
+ stripped?: boolean;
30
+ }
31
+
32
+ /**
33
+ * Strip CriticMarkup so the matcher sees plain prose instead of
34
+ * `{++inserted++}`/`{--deleted--}`/etc. Used when an anchor lives
35
+ * underneath previously imported track changes. Delegates to the single
36
+ * annotation stripper so the matcher and the build path resolve markup the
37
+ * same way — a payload containing `+`, `-`, or `~` is handled correctly.
38
+ */
39
+ export function stripCriticMarkup(text: string): string {
40
+ return stripAnnotations(text);
41
+ }
42
+
43
+ /**
44
+ * Return every starting index where `needle` occurs in `haystack`.
45
+ * Empty needles return no occurrences (empty matches are not useful
46
+ * for anchor placement).
47
+ */
48
+ /**
49
+ * Score how well the docx-side `before` / `after` context matches the
50
+ * surroundings of a candidate position in the target text. Used by
51
+ * `verify-anchors` to tell apart "multiple hits but context picks one
52
+ * cleanly" (sync will place it correctly) from "multiple hits, context
53
+ * doesn't help" (truly ambiguous, needs human placement).
54
+ *
55
+ * Returns 0 if no context was provided.
56
+ */
57
+ export function scoreContextAt(
58
+ pos: number,
59
+ text: string,
60
+ before: string,
61
+ after: string,
62
+ anchorLen: number,
63
+ ): number {
64
+ let score = 0;
65
+ if (before) {
66
+ const contextBefore = text.slice(Math.max(0, pos - before.length - 20), pos).toLowerCase();
67
+ const beforeLower = before.toLowerCase();
68
+ const beforeWords = beforeLower.split(/\s+/).filter(w => w.length > 3);
69
+ for (const word of beforeWords) {
70
+ if (contextBefore.includes(word)) score += 2;
71
+ }
72
+ if (contextBefore.includes(beforeLower.slice(-30))) score += 5;
73
+ }
74
+ if (after) {
75
+ const contextAfter = text.slice(pos + anchorLen, pos + anchorLen + after.length + 20).toLowerCase();
76
+ const afterLower = after.toLowerCase();
77
+ const afterWords = afterLower.split(/\s+/).filter(w => w.length > 3);
78
+ for (const word of afterWords) {
79
+ if (contextAfter.includes(word)) score += 2;
80
+ }
81
+ if (contextAfter.includes(afterLower.slice(0, 30))) score += 5;
82
+ }
83
+ return score;
84
+ }
85
+
86
+ export function findAllOccurrences(haystack: string, needle: string): number[] {
87
+ if (!needle || needle.length === 0) return [];
88
+ const occurrences: number[] = [];
89
+ let idx = 0;
90
+ while ((idx = haystack.indexOf(needle, idx)) !== -1) {
91
+ occurrences.push(idx);
92
+ idx += 1;
93
+ }
94
+ return occurrences;
95
+ }
96
+
97
+ /**
98
+ * Find candidate positions for `anchor` in `text`, falling back through
99
+ * progressively looser strategies (whitespace normalization, stripped
100
+ * CriticMarkup, partial-prefix, surrounding context, word splitting).
101
+ *
102
+ * The returned `strategy` lets callers distinguish a clean direct hit
103
+ * from a fuzzy approximation — useful for drift reporting.
104
+ */
105
+ export function findAnchorInText(
106
+ anchor: string,
107
+ text: string,
108
+ before: string = '',
109
+ after: string = ''
110
+ ): AnchorSearchResult {
111
+ // Empty anchor: skip directly to context-based matching
112
+ if (!anchor || anchor.trim().length === 0) {
113
+ if (before || after) {
114
+ const beforeLower = (before || '').toLowerCase();
115
+ const afterLower = (after || '').toLowerCase();
116
+ const textLower = text.toLowerCase();
117
+
118
+ if (before && after) {
119
+ const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
120
+ if (beforeIdx !== -1) {
121
+ const searchStart = beforeIdx + beforeLower.slice(-50).length;
122
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
123
+ if (afterIdx !== -1 && afterIdx - searchStart < 500) {
124
+ return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
125
+ }
126
+ }
127
+ }
128
+
129
+ if (before) {
130
+ const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
131
+ if (beforeIdx !== -1) {
132
+ return {
133
+ occurrences: [beforeIdx + beforeLower.slice(-30).length],
134
+ matchedAnchor: null,
135
+ strategy: 'context-before',
136
+ };
137
+ }
138
+ }
139
+
140
+ if (after) {
141
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
142
+ if (afterIdx !== -1) {
143
+ return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
144
+ }
145
+ }
146
+ }
147
+ return { occurrences: [], matchedAnchor: null, strategy: 'empty-anchor' };
148
+ }
149
+
150
+ const anchorLower = anchor.toLowerCase();
151
+ const textLower = text.toLowerCase();
152
+
153
+ // Strategy 1: direct match
154
+ let occurrences = findAllOccurrences(textLower, anchorLower);
155
+ if (occurrences.length > 0) {
156
+ return { occurrences, matchedAnchor: anchor, strategy: 'direct' };
157
+ }
158
+
159
+ // Strategy 2: normalized whitespace
160
+ const normalizedAnchor = anchor.replace(/\s+/g, ' ').toLowerCase();
161
+ const normalizedText = text.replace(/\s+/g, ' ').toLowerCase();
162
+ const idx = normalizedText.indexOf(normalizedAnchor);
163
+ if (idx !== -1) {
164
+ return { occurrences: [idx], matchedAnchor: anchor, strategy: 'normalized' };
165
+ }
166
+
167
+ // Strategy 3: match in stripped CriticMarkup version
168
+ const strippedText = stripCriticMarkup(text);
169
+ const strippedLower = strippedText.toLowerCase();
170
+ occurrences = findAllOccurrences(strippedLower, anchorLower);
171
+ if (occurrences.length > 0) {
172
+ return { occurrences, matchedAnchor: anchor, strategy: 'stripped', stripped: true };
173
+ }
174
+
175
+ // Strategy 4: word window from anchor (prefix or interior).
176
+ // Sliding the window across the anchor catches the case where the
177
+ // anchor's prefix has been edited but a chunk in the middle/end
178
+ // survived intact (e.g. "Sensitivity analyses were performed by
179
+ // perturbing the prior variance" → drifted "Sensitivity analyses
180
+ // perturbed the prior variance" still contains "the prior variance").
181
+ const words = anchor.split(/\s+/);
182
+ if (words.length > 3) {
183
+ for (let n = Math.min(6, words.length); n >= 3; n--) {
184
+ for (let start = 0; start + n <= words.length; start++) {
185
+ const window = words.slice(start, start + n).join(' ');
186
+ const windowLower = window.toLowerCase();
187
+ if (windowLower.length < 15) continue;
188
+
189
+ let occ = findAllOccurrences(textLower, windowLower);
190
+ if (occ.length > 0) {
191
+ const strategy: AnchorStrategy = start === 0 ? 'partial-start' : 'partial-window';
192
+ return { occurrences: occ, matchedAnchor: window, strategy };
193
+ }
194
+ occ = findAllOccurrences(strippedLower, windowLower);
195
+ if (occ.length > 0) {
196
+ const strategy: AnchorStrategy = start === 0 ? 'partial-start-stripped' : 'partial-window-stripped';
197
+ return { occurrences: occ, matchedAnchor: window, strategy, stripped: true };
198
+ }
199
+ }
200
+ }
201
+ }
202
+
203
+ // Strategy 5: context (before/after) only.
204
+ //
205
+ // For a non-empty anchor that already failed every text-based strategy
206
+ // above, we treat context as a degraded placement: classify it
207
+ // 'context-only' so callers can warn the user. We also reject
208
+ // implausible brackets — if both contexts match but the gap between
209
+ // them is far too small to contain the anchor (e.g. the anchored
210
+ // sentence was deleted), do not silently land the comment between
211
+ // the surviving sentences. Return 'failed' so the user is told to
212
+ // place it manually.
213
+ if (before || after) {
214
+ const beforeLower = before.toLowerCase();
215
+ const afterLower = after.toLowerCase();
216
+ const anchorLen = anchor.length;
217
+
218
+ if (before && after) {
219
+ const beforeIdx = textLower.indexOf(beforeLower.slice(-50));
220
+ if (beforeIdx !== -1) {
221
+ const searchStart = beforeIdx + beforeLower.slice(-50).length;
222
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 50), searchStart);
223
+ if (afterIdx !== -1) {
224
+ const gap = afterIdx - searchStart;
225
+ // Require the bracket to plausibly contain a remnant of the anchor.
226
+ // Below 30% of anchor length: anchor was deleted — refuse to place.
227
+ // Above 2× anchor length + slack: brackets are too far apart, the
228
+ // matcher has latched onto unrelated repeats of common context.
229
+ const minGap = Math.floor(anchorLen * 0.3);
230
+ const maxGap = Math.min(500, anchorLen * 2 + 50);
231
+ if (gap >= minGap && gap <= maxGap) {
232
+ return { occurrences: [searchStart], matchedAnchor: null, strategy: 'context-both' };
233
+ }
234
+ // Both brackets found but gap implausible: anchor likely deleted.
235
+ // Don't fall back to single-side context — that would silently
236
+ // place the comment in the wrong location.
237
+ return { occurrences: [], matchedAnchor: null, strategy: 'failed' };
238
+ }
239
+ }
240
+ }
241
+
242
+ if (before) {
243
+ const beforeIdx = textLower.lastIndexOf(beforeLower.slice(-30));
244
+ if (beforeIdx !== -1) {
245
+ return {
246
+ occurrences: [beforeIdx + beforeLower.slice(-30).length],
247
+ matchedAnchor: null,
248
+ strategy: 'context-before',
249
+ };
250
+ }
251
+ }
252
+
253
+ if (after) {
254
+ const afterIdx = textLower.indexOf(afterLower.slice(0, 30));
255
+ if (afterIdx !== -1) {
256
+ return { occurrences: [afterIdx], matchedAnchor: null, strategy: 'context-after' };
257
+ }
258
+ }
259
+ }
260
+
261
+ // Strategy 6: split anchor on transition characters
262
+ const splitPatterns = [' ', ', ', '. ', ' - ', ' – '];
263
+ for (const sep of splitPatterns) {
264
+ if (anchor.includes(sep)) {
265
+ const parts = anchor.split(sep).filter(p => p.length >= 4);
266
+ for (const part of parts) {
267
+ const partLower = part.toLowerCase();
268
+ occurrences = findAllOccurrences(textLower, partLower);
269
+ if (occurrences.length > 0 && occurrences.length < 5) {
270
+ return { occurrences, matchedAnchor: part, strategy: 'split-match' };
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ return { occurrences: [], matchedAnchor: null, strategy: 'failed' };
277
+ }
278
+
279
+ /**
280
+ * Classify a strategy as a clean hit, a fuzzy/drifted hit, or no hit.
281
+ * Used by `verify-anchors` to summarize per-comment match quality.
282
+ */
283
+ export type AnchorMatchQuality = 'clean' | 'drift' | 'context-only' | 'unmatched';
284
+
285
+ export function classifyStrategy(strategy: AnchorStrategy, occurrences: number): AnchorMatchQuality {
286
+ if (occurrences === 0) return 'unmatched';
287
+ switch (strategy) {
288
+ case 'direct':
289
+ case 'normalized':
290
+ return 'clean';
291
+ case 'stripped':
292
+ case 'partial-start':
293
+ case 'partial-start-stripped':
294
+ case 'partial-window':
295
+ case 'partial-window-stripped':
296
+ case 'split-match':
297
+ return 'drift';
298
+ case 'context-both':
299
+ case 'context-before':
300
+ case 'context-after':
301
+ return 'context-only';
302
+ case 'empty-anchor':
303
+ case 'failed':
304
+ default:
305
+ return 'unmatched';
306
+ }
307
+ }