@in-the-loop-labs/pair-review 5.3.7 → 5.4.1
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.
- package/README.md +8 -0
- package/package.json +3 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
- package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
- package/public/css/pr.css +389 -13
- package/public/index.html +1 -0
- package/public/js/components/AIPanel.js +317 -99
- package/public/js/components/AdvancedConfigTab.js +18 -108
- package/public/js/components/ReviewHistoryModal.js +294 -0
- package/public/js/components/ReviewModal.js +96 -7
- package/public/js/components/SplitButton.js +14 -0
- package/public/js/components/VoiceCentricConfigTab.js +18 -108
- package/public/js/index.js +18 -5
- package/public/js/local.js +4 -8
- package/public/js/modules/comment-manager.js +2 -1
- package/public/js/modules/diff-renderer.js +7 -6
- package/public/js/modules/file-comment-manager.js +6 -2
- package/public/js/modules/pierre-bridge.js +35 -1
- package/public/js/modules/suggestion-manager.js +4 -1
- package/public/js/pr.js +174 -66
- package/public/js/utils/council-timeout.js +203 -0
- package/public/js/utils/posted-comment.js +259 -14
- package/public/js/vendor/pierre-diffs-worker.js +41 -13485
- package/public/js/vendor/pierre-diffs.js +131 -1364
- package/public/local.html +4 -0
- package/public/pr.html +5 -0
- package/src/ai/copilot-provider.js +21 -2
- package/src/ai/cursor-agent-provider.js +21 -2
- package/src/ai/opencode-provider.js +21 -2
- package/src/chat/api-reference.js +22 -2
- package/src/config.js +28 -4
- package/src/database.js +416 -114
- package/src/git/worktree-pool-lifecycle.js +152 -33
- package/src/git/worktree-pool-usage.js +20 -0
- package/src/git/worktree.js +14 -5
- package/src/github/client.js +70 -15
- package/src/github/impl/graphql/pending-review-comments.js +50 -11
- package/src/github/impl/graphql/pending-review.js +8 -2
- package/src/github/impl/graphql/review-comment-edit.js +89 -0
- package/src/github/impl/host/pending-review-comments.js +41 -10
- package/src/github/impl/host/review-comment-edit.js +36 -0
- package/src/github/impl/rest/pending-review.js +6 -2
- package/src/github/impl/rest/review-comment-edit.js +44 -0
- package/src/github/impl/review-comment-edit-utils.js +45 -0
- package/src/github/operations/pending-review.js +4 -3
- package/src/github/operations/review-comment-edit.js +35 -0
- package/src/github/record-submission.js +78 -0
- package/src/github/update-posted-comment.js +115 -0
- package/src/main.js +42 -50
- package/src/routes/mcp.js +1 -0
- package/src/routes/pr.js +158 -120
- package/src/routes/reviews.js +8 -30
- package/src/routes/setup.js +22 -9
- package/src/setup/pr-setup.js +12 -3
- package/src/utils/diff-file-content.js +62 -25
- package/src/utils/json-extractor.js +267 -13
- package/src/utils/pr-file-blob-cache.js +134 -0
- package/src/utils/process-liveness.js +64 -0
|
@@ -9,53 +9,79 @@
|
|
|
9
9
|
|
|
10
10
|
const { parseDiffGitPaths, parsePatchPaths } = require('./git-paths');
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Index the blob info of every file in a diff in a single pass.
|
|
14
|
+
*
|
|
15
|
+
* Each file is keyed by both its old and new path. When a path appears in
|
|
16
|
+
* more than one file block, the first block wins. A block whose first
|
|
17
|
+
* `index` line is malformed records `null` for its paths, and a block with
|
|
18
|
+
* no `index` line (e.g. a pure rename) records nothing, so a later block may
|
|
19
|
+
* still supply the path. This matches a per-file top-to-bottom scan.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} diffText - Unified diff text
|
|
22
|
+
* @returns {Map<string, Object|null>} path -> { oldPath, newPath, oldBlob, newBlob } or null
|
|
23
|
+
*/
|
|
24
|
+
function buildFileBlobIndex(diffText) {
|
|
25
|
+
const index = new Map();
|
|
26
|
+
if (!diffText) {
|
|
27
|
+
return index;
|
|
15
28
|
}
|
|
16
29
|
|
|
17
30
|
const lines = diffText.split('\n');
|
|
18
|
-
let
|
|
31
|
+
let blockPaths = null;
|
|
19
32
|
|
|
20
33
|
for (let i = 0; i < lines.length; i++) {
|
|
21
34
|
const line = lines[i];
|
|
22
35
|
if (line.startsWith('diff --git ')) {
|
|
23
|
-
|
|
24
|
-
matchedPaths = paths && (paths.oldPath === fileName || paths.newPath === fileName)
|
|
25
|
-
? paths
|
|
26
|
-
: null;
|
|
36
|
+
blockPaths = parsePatchPaths(lines, i);
|
|
27
37
|
continue;
|
|
28
38
|
}
|
|
29
39
|
|
|
30
|
-
if (!
|
|
40
|
+
if (!blockPaths || !line.startsWith('index ')) {
|
|
31
41
|
continue;
|
|
32
42
|
}
|
|
33
43
|
|
|
34
44
|
const match = line.match(/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: \d+)?$/i);
|
|
35
|
-
|
|
36
|
-
|
|
45
|
+
const blobInfo = match
|
|
46
|
+
? { ...blockPaths, oldBlob: match[1], newBlob: match[2] }
|
|
47
|
+
: null;
|
|
48
|
+
|
|
49
|
+
for (const filePath of [blockPaths.oldPath, blockPaths.newPath]) {
|
|
50
|
+
if (filePath && !index.has(filePath)) {
|
|
51
|
+
index.set(filePath, blobInfo);
|
|
52
|
+
}
|
|
37
53
|
}
|
|
38
54
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
55
|
+
// Only the first index line of a block describes it.
|
|
56
|
+
blockPaths = null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return index;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function findFileBlobInfoInDiff(diffText, fileName) {
|
|
63
|
+
if (!diffText || !fileName) {
|
|
64
|
+
return null;
|
|
44
65
|
}
|
|
45
66
|
|
|
46
|
-
return null;
|
|
67
|
+
return buildFileBlobIndex(diffText).get(fileName) ?? null;
|
|
47
68
|
}
|
|
48
69
|
|
|
49
70
|
function isZeroObjectId(objectId) {
|
|
50
71
|
return typeof objectId === 'string' && /^0+$/.test(objectId);
|
|
51
72
|
}
|
|
52
73
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
74
|
+
/**
|
|
75
|
+
* Build the ordered git specs for a file's original content: the exact diff
|
|
76
|
+
* blob first, then the file at base_sha. Callers fall back to the worktree
|
|
77
|
+
* when every spec fails or none apply.
|
|
78
|
+
*
|
|
79
|
+
* @param {Object|null} blobInfo - The file's entry from buildFileBlobIndex
|
|
80
|
+
* @param {string|null} baseSha - The PR's base commit
|
|
81
|
+
* @param {string} fileName - Path requested by the caller
|
|
82
|
+
* @returns {Array<{gitSpec: string, source: string}>}
|
|
83
|
+
*/
|
|
84
|
+
function buildOriginalFileContentSpecs(blobInfo, baseSha, fileName) {
|
|
59
85
|
const specs = [];
|
|
60
86
|
|
|
61
87
|
if (blobInfo?.oldBlob && !isZeroObjectId(blobInfo.oldBlob)) {
|
|
@@ -65,10 +91,10 @@ function resolveOriginalFileContentSpecs(prData, fileName) {
|
|
|
65
91
|
});
|
|
66
92
|
}
|
|
67
93
|
|
|
68
|
-
if (
|
|
94
|
+
if (baseSha) {
|
|
69
95
|
const originalPath = blobInfo?.oldPath || fileName;
|
|
70
96
|
specs.push({
|
|
71
|
-
gitSpec: `${
|
|
97
|
+
gitSpec: `${baseSha}:${originalPath}`,
|
|
72
98
|
source: 'base commit'
|
|
73
99
|
});
|
|
74
100
|
}
|
|
@@ -76,11 +102,22 @@ function resolveOriginalFileContentSpecs(prData, fileName) {
|
|
|
76
102
|
return specs;
|
|
77
103
|
}
|
|
78
104
|
|
|
105
|
+
function resolveOriginalFileContentSpecs(prData, fileName) {
|
|
106
|
+
if (!prData || typeof prData !== 'object') {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const blobInfo = findFileBlobInfoInDiff(prData.diff, fileName);
|
|
111
|
+
return buildOriginalFileContentSpecs(blobInfo, prData.base_sha, fileName);
|
|
112
|
+
}
|
|
113
|
+
|
|
79
114
|
function resolveOriginalFileContentSpec(prData, fileName) {
|
|
80
115
|
return resolveOriginalFileContentSpecs(prData, fileName)[0] || null;
|
|
81
116
|
}
|
|
82
117
|
|
|
83
118
|
module.exports = {
|
|
119
|
+
buildFileBlobIndex,
|
|
120
|
+
buildOriginalFileContentSpecs,
|
|
84
121
|
findFileBlobInfoInDiff,
|
|
85
122
|
parseDiffGitPaths,
|
|
86
123
|
resolveOriginalFileContentSpecs,
|
|
@@ -85,6 +85,251 @@ function sanitizeControlCharactersInStrings(text) {
|
|
|
85
85
|
return result;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
// Patterns that start our expected JSON response structures.
|
|
89
|
+
const JSON_ANCHORS = [
|
|
90
|
+
/\{"level"\s*:/,
|
|
91
|
+
/\{"suggestions"\s*:/,
|
|
92
|
+
/\{"fileLevelSuggestions"\s*:/,
|
|
93
|
+
/\{"summary"\s*:/,
|
|
94
|
+
/\{"overview"\s*:/,
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
// A key, in any spelling or half-quoted (`line:`, `'line':`, `line":`,
|
|
98
|
+
// `"line":`), followed by the start of a JSON value: a string, array or
|
|
99
|
+
// object, or a number or literal ending at a delimiter. Prose with a colon
|
|
100
|
+
// (`here: foo()`, `note: 5 items`) does not match.
|
|
101
|
+
const LOOKS_LIKE_FIELD =
|
|
102
|
+
/(?:[A-Za-z_$][\w$]*|["'`])["'`]?\s*:\s*(?:["'[{]|(?:-?\d[\d.eE+-]*|true|false|null)\s*[,}\]])/;
|
|
103
|
+
|
|
104
|
+
// Upper bound on error-directed repair attempts per response. Each attempt
|
|
105
|
+
// escapes one quote (or re-runs the control-character pass), so this caps
|
|
106
|
+
// the number of JSON.parse calls on input that is not JSON at all.
|
|
107
|
+
const MAX_QUOTE_REPAIR_ITERATIONS = 50;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Return true when the `"` at index q closes a string literal, judged by
|
|
111
|
+
* walking the same in-string/escaped state machine as the sanitizer from the
|
|
112
|
+
* start of text.
|
|
113
|
+
* @param {string} text - Candidate JSON text starting at its opening {
|
|
114
|
+
* @param {number} q - Index of a `"` character
|
|
115
|
+
* @returns {boolean}
|
|
116
|
+
*/
|
|
117
|
+
function isClosingQuote(text, q) {
|
|
118
|
+
let inString = false;
|
|
119
|
+
let escaped = false;
|
|
120
|
+
for (let i = 0; i < q; i++) {
|
|
121
|
+
const ch = text[i];
|
|
122
|
+
if (escaped) {
|
|
123
|
+
escaped = false;
|
|
124
|
+
} else if (ch === '\\' && inString) {
|
|
125
|
+
escaped = true;
|
|
126
|
+
} else if (ch === '"') {
|
|
127
|
+
inString = !inString;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return inString && !escaped;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Locate the unescaped `"` that ended a string literal too early, using a
|
|
135
|
+
* JSON.parse error.
|
|
136
|
+
*
|
|
137
|
+
* V8 does not report the bad quote itself: the string ends there, so the
|
|
138
|
+
* reported offset is the first non-whitespace character *after* it, where
|
|
139
|
+
* the parser expected structure but found prose. For
|
|
140
|
+
* `{"d":"say "hi" there"}` the error is "Expected ',' or '}' after property
|
|
141
|
+
* value ... at position 11", pointing at the `h`. So the heuristic is:
|
|
142
|
+
*
|
|
143
|
+
* - "Expected ',' or '}' after property value" / "Expected ',' or ']'
|
|
144
|
+
* after array element": the bad quote is the last non-whitespace
|
|
145
|
+
* character before the offset.
|
|
146
|
+
* - "Expected double-quoted property name": the early-closed string was
|
|
147
|
+
* followed by prose starting with a comma (`"called "foo", which"`), so
|
|
148
|
+
* the bad quote precedes that comma.
|
|
149
|
+
*
|
|
150
|
+
* The candidate is rejected when the character at the offset is `"`, `}` or
|
|
151
|
+
* `]`: that looks like a missing or trailing comma, not a quote in prose,
|
|
152
|
+
* and escaping would merge separate values. The quote must also be a closing
|
|
153
|
+
* quote according to the in-string state machine. Finally, it is rejected
|
|
154
|
+
* when the span escaping it would pull into the string (up to the next
|
|
155
|
+
* unescaped quote) looks like a malformed field (e.g. `, line":3,` or
|
|
156
|
+
* `, title:` followed by a string value's opening quote). A bare word and
|
|
157
|
+
* colon can also appear in prose; only reject it when the would-be string
|
|
158
|
+
* value's closing quote is followed by a JSON value delimiter.
|
|
159
|
+
*
|
|
160
|
+
* @param {string} text - Candidate JSON text
|
|
161
|
+
* @param {string} message - JSON.parse error message
|
|
162
|
+
* @returns {number} Index of the quote to escape, or -1 if this is not an
|
|
163
|
+
* unescaped-quote error
|
|
164
|
+
*/
|
|
165
|
+
function findPrematureStringEnd(text, message) {
|
|
166
|
+
const posMatch = /at position (\d+)/.exec(message);
|
|
167
|
+
if (!posMatch) return -1;
|
|
168
|
+
const pos = Number(posMatch[1]);
|
|
169
|
+
if (pos >= text.length || '"}]'.includes(text[pos])) return -1;
|
|
170
|
+
|
|
171
|
+
let q = pos - 1;
|
|
172
|
+
const skipWhitespace = () => { while (q >= 0 && /\s/.test(text[q])) q--; };
|
|
173
|
+
|
|
174
|
+
if (/Expected ',' or '[}\]]' after (property value|array element)/.test(message)) {
|
|
175
|
+
skipWhitespace();
|
|
176
|
+
} else if (/Expected double-quoted property name/.test(message)) {
|
|
177
|
+
skipWhitespace();
|
|
178
|
+
if (text[q] !== ',') return -1;
|
|
179
|
+
q--;
|
|
180
|
+
skipWhitespace();
|
|
181
|
+
} else {
|
|
182
|
+
return -1;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (q < 0 || text[q] !== '"' || !isClosingQuote(text, q)) return -1;
|
|
186
|
+
// Escaping q pulls everything up to the next unescaped quote into the
|
|
187
|
+
// string. If that span holds a field (`, line":3,`), the "prose" is really
|
|
188
|
+
// a malformed key: escaping would fold later fields into the string, so
|
|
189
|
+
// leave it to fail. A span ending in `":` is a key whose string value
|
|
190
|
+
// opens with the quote that ends the span (`, kind":"x"`).
|
|
191
|
+
const spanEnd = nextUnescapedQuote(text, q + 1);
|
|
192
|
+
const span = text.slice(q, spanEnd);
|
|
193
|
+
if (LOOKS_LIKE_FIELD.test(span) || /["'`]\s*:\s*$/.test(span)) return -1;
|
|
194
|
+
// A bare key's string value also opens at spanEnd (`, title:"next"`).
|
|
195
|
+
// Only reject it if the would-be value's closing quote precedes a JSON
|
|
196
|
+
// delimiter: `as follows:"` ends prose, and `mode: "strict" here` is prose
|
|
197
|
+
// too, despite having a word and colon before a quoted phrase.
|
|
198
|
+
if (/[A-Za-z_$][\w$]*\s*:\s*$/.test(span)) {
|
|
199
|
+
const valueEnd = nextUnescapedQuote(text, spanEnd + 1);
|
|
200
|
+
if (/^\s*[,}\]]/.test(text.slice(valueEnd + 1))) return -1;
|
|
201
|
+
}
|
|
202
|
+
return q;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* @param {string} text - Candidate JSON text
|
|
207
|
+
* @param {number} from - Index to start scanning at
|
|
208
|
+
* @returns {number} Index of the next `"` not preceded by a backslash
|
|
209
|
+
* escape, or text.length if there is none
|
|
210
|
+
*/
|
|
211
|
+
function nextUnescapedQuote(text, from) {
|
|
212
|
+
for (let i = from; i < text.length; i++) {
|
|
213
|
+
if (text[i] === '\\') i++;
|
|
214
|
+
else if (text[i] === '"') return i;
|
|
215
|
+
}
|
|
216
|
+
return text.length;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Escape raw control characters from index pos to the end of the string
|
|
221
|
+
* literal containing it (the next unescaped `"`).
|
|
222
|
+
*
|
|
223
|
+
* Unlike sanitizeControlCharactersInStrings this does not walk string state
|
|
224
|
+
* from the start of the text, so an unescaped quote earlier in the text
|
|
225
|
+
* cannot flip it and make it escape structural newlines between values.
|
|
226
|
+
* Like that sanitizer, a backslash directly before a raw control character
|
|
227
|
+
* (e.g. a shell line continuation) is doubled into a literal '\\'.
|
|
228
|
+
*
|
|
229
|
+
* @param {string} text - Candidate JSON text
|
|
230
|
+
* @param {number} pos - Offset JSON.parse reported for a bad control character
|
|
231
|
+
* @returns {string} Text with that string's control characters escaped
|
|
232
|
+
*/
|
|
233
|
+
function escapeControlCharactersFrom(text, pos) {
|
|
234
|
+
let span = '';
|
|
235
|
+
let escaped = false;
|
|
236
|
+
let end = pos;
|
|
237
|
+
for (; end < text.length; end++) {
|
|
238
|
+
const ch = text[end];
|
|
239
|
+
const isControl = ch.charCodeAt(0) < 0x20;
|
|
240
|
+
if (escaped) {
|
|
241
|
+
escaped = false;
|
|
242
|
+
span += isControl ? '\\' + escapeControlCharacter(ch) : ch;
|
|
243
|
+
} else if (ch === '\\') {
|
|
244
|
+
escaped = true;
|
|
245
|
+
span += ch;
|
|
246
|
+
} else if (ch === '"') {
|
|
247
|
+
break;
|
|
248
|
+
} else {
|
|
249
|
+
span += isControl ? escapeControlCharacter(ch) : ch;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return text.slice(0, pos) + span + text.slice(end);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Repair unescaped `"` characters inside JSON string literals (issue #561),
|
|
257
|
+
* guided by JSON.parse's own error offsets.
|
|
258
|
+
*
|
|
259
|
+
* LLMs writing prose into a string value sometimes quote a word without
|
|
260
|
+
* escaping it (`"description": "rename "foo" to bar"`). The string ends at
|
|
261
|
+
* the first inner quote and the parser fails on the prose that follows. Each
|
|
262
|
+
* attempt parses the text, asks findPrematureStringEnd for the offending
|
|
263
|
+
* quote, escapes it, and retries. Raw control characters are repaired the
|
|
264
|
+
* same way, one string literal per attempt at the reported offset: the
|
|
265
|
+
* whole-text sanitizer can't be trusted here because each unescaped quote
|
|
266
|
+
* flips its in-string state for the rest of the text. Gives up on any other
|
|
267
|
+
* error, when an attempt makes no progress, or after
|
|
268
|
+
* MAX_QUOTE_REPAIR_ITERATIONS attempts.
|
|
269
|
+
*
|
|
270
|
+
* Text that already parses is returned unchanged.
|
|
271
|
+
*
|
|
272
|
+
* @param {string} text - Candidate JSON text (should start at its opening {)
|
|
273
|
+
* @param {number} [maxIterations] - Bound on repair attempts
|
|
274
|
+
* @returns {{data: (Object|null), text: string, repairs: number}} data is the
|
|
275
|
+
* parsed object, or null if repair failed; text is the (possibly repaired)
|
|
276
|
+
* candidate; repairs counts the fixes applied
|
|
277
|
+
*/
|
|
278
|
+
function repairUnescapedQuotes(text, maxIterations = MAX_QUOTE_REPAIR_ITERATIONS) {
|
|
279
|
+
let current = text;
|
|
280
|
+
let repairs = 0;
|
|
281
|
+
let lastQuote = -1;
|
|
282
|
+
|
|
283
|
+
for (let attempt = 0; attempt <= maxIterations; attempt++) {
|
|
284
|
+
let message;
|
|
285
|
+
try {
|
|
286
|
+
const data = JSON.parse(current);
|
|
287
|
+
return { data: data && typeof data === 'object' ? data : null, text: current, repairs };
|
|
288
|
+
} catch (error) {
|
|
289
|
+
message = error.message;
|
|
290
|
+
}
|
|
291
|
+
if (attempt === maxIterations) break;
|
|
292
|
+
|
|
293
|
+
const controlMatch = /Bad control character in string literal in JSON at position (\d+)/.exec(message);
|
|
294
|
+
if (controlMatch) {
|
|
295
|
+
const repaired = escapeControlCharactersFrom(current, Number(controlMatch[1]));
|
|
296
|
+
if (repaired === current) break;
|
|
297
|
+
current = repaired;
|
|
298
|
+
repairs++;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const q = findPrematureStringEnd(current, message);
|
|
303
|
+
// Each escape moves the string end forward; a quote at or before the
|
|
304
|
+
// previous one means the heuristic is going in circles.
|
|
305
|
+
if (q === -1 || q <= lastQuote) break;
|
|
306
|
+
current = current.slice(0, q) + '\\' + current.slice(q);
|
|
307
|
+
lastQuote = q;
|
|
308
|
+
repairs++;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return { data: null, text: current, repairs };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Run repairUnescapedQuotes on the JSON region of a response: from the first
|
|
316
|
+
* known anchor (else the first {) to the last }.
|
|
317
|
+
* @param {string} text - Response text
|
|
318
|
+
* @returns {{data: (Object|null), text: string, repairs: number}|null} null
|
|
319
|
+
* when the text has no {...} region
|
|
320
|
+
*/
|
|
321
|
+
function repairCandidate(text) {
|
|
322
|
+
let start = -1;
|
|
323
|
+
for (const anchor of JSON_ANCHORS) {
|
|
324
|
+
const match = text.match(anchor);
|
|
325
|
+
if (match) { start = match.index; break; }
|
|
326
|
+
}
|
|
327
|
+
if (start === -1) start = text.indexOf('{');
|
|
328
|
+
const end = text.lastIndexOf('}');
|
|
329
|
+
if (start === -1 || end <= start) return null;
|
|
330
|
+
return repairUnescapedQuotes(text.substring(start, end + 1));
|
|
331
|
+
}
|
|
332
|
+
|
|
88
333
|
/**
|
|
89
334
|
* Run all extraction strategies against a candidate text.
|
|
90
335
|
*
|
|
@@ -144,16 +389,7 @@ function runExtractionStrategies(text) {
|
|
|
144
389
|
// (e.g. LLM discussing code: "the function handleEvent(event) { ... }")
|
|
145
390
|
// which would cause Strategy 3 to grab the wrong first brace.
|
|
146
391
|
() => {
|
|
147
|
-
|
|
148
|
-
const anchors = [
|
|
149
|
-
/\{"level"\s*:/,
|
|
150
|
-
/\{"suggestions"\s*:/,
|
|
151
|
-
/\{"fileLevelSuggestions"\s*:/,
|
|
152
|
-
/\{"summary"\s*:/,
|
|
153
|
-
/\{"overview"\s*:/,
|
|
154
|
-
];
|
|
155
|
-
|
|
156
|
-
for (const anchor of anchors) {
|
|
392
|
+
for (const anchor of JSON_ANCHORS) {
|
|
157
393
|
const match = text.match(anchor);
|
|
158
394
|
if (match) {
|
|
159
395
|
const startIdx = match.index;
|
|
@@ -267,7 +503,9 @@ function runExtractionStrategies(text) {
|
|
|
267
503
|
* The strategies (see runExtractionStrategies) run against the original
|
|
268
504
|
* response first. If all fail, a repair pass escapes raw control characters
|
|
269
505
|
* inside string literals (issue #560) and the strategies run once more against
|
|
270
|
-
* the sanitized text.
|
|
506
|
+
* the sanitized text. If that also fails, repairUnescapedQuotes escapes
|
|
507
|
+
* unescaped quotes inside string literals at the offsets JSON.parse reports
|
|
508
|
+
* (issue #561).
|
|
271
509
|
*
|
|
272
510
|
* @param {string} response - Raw response text (may include preamble/postamble prose)
|
|
273
511
|
* @param {string|number} level - Level identifier for logging (e.g., 1, 2, 3, 'orchestration', 'unknown')
|
|
@@ -305,10 +543,26 @@ function extractJSON(response, level = 'unknown', logPrefix) {
|
|
|
305
543
|
}
|
|
306
544
|
}
|
|
307
545
|
|
|
546
|
+
// Quote repair: escape unescaped quotes (and control characters) inside
|
|
547
|
+
// string literals at the offsets JSON.parse reports (issue #561). Works on
|
|
548
|
+
// the original response, not `sanitized`: an unescaped quote desyncs the
|
|
549
|
+
// sanitizer, which then escapes structural newlines in pretty-printed JSON.
|
|
550
|
+
// The region runs from the first known anchor (else the first {) to the
|
|
551
|
+
// last }, so offsets refer to the JSON rather than surrounding prose.
|
|
552
|
+
const quoteRepair = repairCandidate(response);
|
|
553
|
+
if (quoteRepair && quoteRepair.data) {
|
|
554
|
+
logger.info(`${levelPrefix} JSON extraction successful after repairing ${quoteRepair.repairs} unescaped quote/control-character error(s)`);
|
|
555
|
+
return { success: true, data: quoteRepair.data };
|
|
556
|
+
}
|
|
557
|
+
|
|
308
558
|
// All strategies failed — log the first pass's errors so `position N`
|
|
309
559
|
// offsets line up with the original-response preview below
|
|
560
|
+
const repairNotes = [
|
|
561
|
+
repairAttempted && 'control-character',
|
|
562
|
+
quoteRepair && quoteRepair.repairs > 0 && 'unescaped-quote',
|
|
563
|
+
].filter(Boolean);
|
|
310
564
|
logger.warn(`${levelPrefix} All JSON extraction strategies failed`);
|
|
311
|
-
logger.warn(`${levelPrefix} Strategy errors: ${firstPass.strategyErrors.join('; ')}${
|
|
565
|
+
logger.warn(`${levelPrefix} Strategy errors: ${firstPass.strategyErrors.join('; ')}${repairNotes.length ? ` (${repairNotes.join(' and ')} repair was also attempted and failed)` : ''}`);
|
|
312
566
|
logger.warn(`${levelPrefix} Response length: ${response.length} chars, preview: ${response.substring(0, 200)}...`);
|
|
313
567
|
|
|
314
568
|
return {
|
|
@@ -318,4 +572,4 @@ function extractJSON(response, level = 'unknown', logPrefix) {
|
|
|
318
572
|
};
|
|
319
573
|
}
|
|
320
574
|
|
|
321
|
-
module.exports = { extractJSON, sanitizeControlCharactersInStrings };
|
|
575
|
+
module.exports = { extractJSON, sanitizeControlCharactersInStrings, repairUnescapedQuotes };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Per-PR cache of the blob info the PR-mode file-content endpoints need.
|
|
4
|
+
*
|
|
5
|
+
* `pr_metadata.pr_data` holds the whole PR diff, and the file-content
|
|
6
|
+
* endpoints are hit on every lazy file body, gap expansion, context file and
|
|
7
|
+
* chat snippet. Parsing the row and scanning the diff on each request is
|
|
8
|
+
* wasteful on large PRs, so this module parses it once per PR into a
|
|
9
|
+
* path -> blob info index plus the base SHA, and serves lookups from that.
|
|
10
|
+
*
|
|
11
|
+
* Staleness guards (every one must hold for a cache hit):
|
|
12
|
+
* - Writers of `pr_data` on this connection call invalidatePRFileBlobCache().
|
|
13
|
+
* - The row's `(id, updated_at)` must match. These columns precede `pr_data`
|
|
14
|
+
* in the row, so reading them does not load the diff. A deleted row serves
|
|
15
|
+
* no specs; a recreated row has a new id.
|
|
16
|
+
* - `PRAGMA data_version` must be unchanged. SQLite bumps it whenever another
|
|
17
|
+
* connection (e.g. a `--headless --no-server` CLI run sharing the database
|
|
18
|
+
* file) commits, which an in-process invalidation cannot see and which a
|
|
19
|
+
* 1-second `updated_at` can miss.
|
|
20
|
+
*
|
|
21
|
+
* The lookup runs synchronously (better-sqlite3), so no write can interleave
|
|
22
|
+
* between reading the row and storing the index.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const logger = require('./logger');
|
|
26
|
+
const { safeParseJson } = require('./safe-parse-json');
|
|
27
|
+
const { buildFileBlobIndex, buildOriginalFileContentSpecs } = require('./diff-file-content');
|
|
28
|
+
|
|
29
|
+
// Upper bound on cached PRs per database, evicted least recently used.
|
|
30
|
+
const MAX_CACHED_PRS = 50;
|
|
31
|
+
|
|
32
|
+
// Keyed by database handle so separate databases (and tests) never share entries.
|
|
33
|
+
const cachesByDb = new WeakMap();
|
|
34
|
+
|
|
35
|
+
function cacheKey(repository, prNumber) {
|
|
36
|
+
return `${String(repository).toLowerCase()}#${Number(prNumber)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function getDbCache(db) {
|
|
40
|
+
let cache = cachesByDb.get(db);
|
|
41
|
+
if (!cache) {
|
|
42
|
+
cache = new Map();
|
|
43
|
+
cachesByDb.set(db, cache);
|
|
44
|
+
}
|
|
45
|
+
return cache;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function loadEntry(db, row, dataVersion) {
|
|
49
|
+
const record = db.prepare('SELECT pr_data FROM pr_metadata WHERE id = ?').get(row.id);
|
|
50
|
+
const prData = safeParseJson(record?.pr_data, null);
|
|
51
|
+
if (record?.pr_data && !prData) {
|
|
52
|
+
logger.warn('Could not parse pr_data for file-content route');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const isObject = prData && typeof prData === 'object';
|
|
56
|
+
return {
|
|
57
|
+
id: row.id,
|
|
58
|
+
updatedAt: row.updated_at,
|
|
59
|
+
dataVersion,
|
|
60
|
+
hasPrData: Boolean(isObject),
|
|
61
|
+
baseSha: isObject ? prData.base_sha || null : null,
|
|
62
|
+
blobIndex: isObject ? buildFileBlobIndex(prData.diff) : new Map()
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolve the ordered git specs for a file's original content in a PR:
|
|
68
|
+
* exact diff blob, then base_sha. An empty array means the caller should read
|
|
69
|
+
* the worktree (no stored PR data, or the file has neither source).
|
|
70
|
+
*
|
|
71
|
+
* @param {Database} db - better-sqlite3 database handle
|
|
72
|
+
* @param {string} repository - Repository in owner/repo form
|
|
73
|
+
* @param {number} prNumber - Pull request number
|
|
74
|
+
* @param {string} fileName - Path to resolve (old or new path in the diff)
|
|
75
|
+
* @returns {Array<{gitSpec: string, source: string}>}
|
|
76
|
+
*/
|
|
77
|
+
function getPRFileContentSpecs(db, repository, prNumber, fileName) {
|
|
78
|
+
const row = db.prepare(`
|
|
79
|
+
SELECT id, updated_at FROM pr_metadata
|
|
80
|
+
WHERE pr_number = ? AND repository = ? COLLATE NOCASE
|
|
81
|
+
`).get(prNumber, repository);
|
|
82
|
+
|
|
83
|
+
const cache = getDbCache(db);
|
|
84
|
+
const key = cacheKey(repository, prNumber);
|
|
85
|
+
|
|
86
|
+
if (!row) {
|
|
87
|
+
cache.delete(key);
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const dataVersion = db.pragma('data_version', { simple: true });
|
|
92
|
+
let entry = cache.get(key);
|
|
93
|
+
const fresh = entry
|
|
94
|
+
&& entry.id === row.id
|
|
95
|
+
&& entry.updatedAt === row.updated_at
|
|
96
|
+
&& entry.dataVersion === dataVersion;
|
|
97
|
+
|
|
98
|
+
if (fresh) {
|
|
99
|
+
// Re-insert to mark as most recently used.
|
|
100
|
+
cache.delete(key);
|
|
101
|
+
} else {
|
|
102
|
+
entry = loadEntry(db, row, dataVersion);
|
|
103
|
+
}
|
|
104
|
+
cache.set(key, entry);
|
|
105
|
+
|
|
106
|
+
if (cache.size > MAX_CACHED_PRS) {
|
|
107
|
+
cache.delete(cache.keys().next().value);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!entry.hasPrData) {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const blobInfo = entry.blobIndex.get(fileName) ?? null;
|
|
115
|
+
return buildOriginalFileContentSpecs(blobInfo, entry.baseSha, fileName);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Drop the cached blob info for a PR. Call after every write to its
|
|
120
|
+
* `pr_metadata.pr_data`.
|
|
121
|
+
*
|
|
122
|
+
* @param {Database} db - better-sqlite3 database handle the write used
|
|
123
|
+
* @param {string} repository - Repository in owner/repo form
|
|
124
|
+
* @param {number} prNumber - Pull request number
|
|
125
|
+
*/
|
|
126
|
+
function invalidatePRFileBlobCache(db, repository, prNumber) {
|
|
127
|
+
cachesByDb.get(db)?.delete(cacheKey(repository, prNumber));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = {
|
|
131
|
+
getPRFileContentSpecs,
|
|
132
|
+
invalidatePRFileBlobCache,
|
|
133
|
+
MAX_CACHED_PRS
|
|
134
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Process liveness helpers.
|
|
6
|
+
*
|
|
7
|
+
* Used to decide whether a pair-review process recorded as the holder of a
|
|
8
|
+
* shared resource (e.g. a worktree_pool row) is still running. Every
|
|
9
|
+
* uncertain answer errs toward "alive": wrongly treating a live holder as
|
|
10
|
+
* dead lets this process reclaim a worktree another process is using, which
|
|
11
|
+
* is far worse than leaving a dead holder's worktree parked until the next
|
|
12
|
+
* startup.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const os = require('os');
|
|
16
|
+
|
|
17
|
+
const defaults = {
|
|
18
|
+
kill: (pid, signal) => process.kill(pid, signal),
|
|
19
|
+
now: () => Date.now(),
|
|
20
|
+
uptime: () => os.uptime(),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Return whether a process with the given PID currently exists.
|
|
25
|
+
*
|
|
26
|
+
* Uses signal 0, which performs the existence/permission check without
|
|
27
|
+
* delivering a signal.
|
|
28
|
+
*
|
|
29
|
+
* @param {number} pid - Process ID to probe
|
|
30
|
+
* @param {Object} [_deps] - Dependency overrides for testing ({ kill })
|
|
31
|
+
* @returns {boolean} false for an invalid PID or ESRCH; true otherwise
|
|
32
|
+
* (success, EPERM — exists but owned by another user — and any other error,
|
|
33
|
+
* so an unexpected failure never causes a live holder to be treated as dead)
|
|
34
|
+
*/
|
|
35
|
+
function isProcessAlive(pid, _deps = {}) {
|
|
36
|
+
const deps = { ...defaults, ..._deps };
|
|
37
|
+
if (pid == null || !Number.isInteger(pid) || pid <= 0) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
deps.kill(pid, 0);
|
|
42
|
+
return true;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err && err.code === 'ESRCH') return false;
|
|
45
|
+
// EPERM: the process exists but we may not signal it.
|
|
46
|
+
// Anything else: unknown — fail safe and treat the holder as alive.
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Approximate wall-clock time (ms since epoch) at which the OS booted.
|
|
53
|
+
* A holder claim stamped before this moment cannot belong to a process that
|
|
54
|
+
* is running now, regardless of what PID it recorded.
|
|
55
|
+
*
|
|
56
|
+
* @param {Object} [_deps] - Dependency overrides for testing ({ now, uptime })
|
|
57
|
+
* @returns {number}
|
|
58
|
+
*/
|
|
59
|
+
function getBootTimeMs(_deps = {}) {
|
|
60
|
+
const deps = { ...defaults, ..._deps };
|
|
61
|
+
return deps.now() - deps.uptime() * 1000;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { isProcessAlive, getBootTimeMs };
|