@in-the-loop-labs/pair-review 5.4.0 → 5.4.2

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 (35) hide show
  1. package/README.md +3 -3
  2. package/package.json +2 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/index.html +4 -0
  7. package/public/js/components/AdvancedConfigTab.js +18 -108
  8. package/public/js/components/VoiceCentricConfigTab.js +18 -108
  9. package/public/js/index.js +47 -5
  10. package/public/js/modules/diff-renderer.js +7 -6
  11. package/public/js/utils/council-timeout.js +203 -0
  12. package/public/local.html +4 -0
  13. package/public/pr.html +4 -0
  14. package/src/ai/antigravity-provider.js +76 -35
  15. package/src/ai/claude-provider.js +115 -39
  16. package/src/ai/codex-provider.js +19 -24
  17. package/src/ai/copilot-provider.js +59 -48
  18. package/src/ai/cursor-agent-provider.js +95 -133
  19. package/src/ai/opencode-provider.js +21 -2
  20. package/src/ai/provider.js +3 -3
  21. package/src/chat/session-manager.js +1 -1
  22. package/src/database.js +240 -59
  23. package/src/git/worktree-pool-lifecycle.js +152 -33
  24. package/src/git/worktree-pool-usage.js +20 -0
  25. package/src/git/worktree.js +14 -5
  26. package/src/main.js +25 -9
  27. package/src/routes/bulk-analysis-configs.js +1 -1
  28. package/src/routes/pr.js +11 -14
  29. package/src/routes/reviews.js +8 -30
  30. package/src/routes/setup.js +22 -9
  31. package/src/setup/pr-setup.js +12 -3
  32. package/src/utils/diff-file-content.js +62 -25
  33. package/src/utils/json-extractor.js +267 -13
  34. package/src/utils/pr-file-blob-cache.js +134 -0
  35. package/src/utils/process-liveness.js +64 -0
@@ -22,7 +22,7 @@ const { GitWorktreeManager } = require('../git/worktree');
22
22
  const { normalizeRepository } = require('../utils/paths');
23
23
  const { resolveFormat, formatAdoptedComment: formatComment } = require('../utils/comment-formatter');
24
24
  const { safeParseJson } = require('../utils/safe-parse-json');
25
- const { resolveOriginalFileContentSpecs } = require('../utils/diff-file-content');
25
+ const { getPRFileContentSpecs } = require('../utils/pr-file-blob-cache');
26
26
  const validateReviewId = require('./middleware/validate-review-id');
27
27
  const { reviewScope, scopeIncludes, includesBranch } = require('../local-scope');
28
28
  const { findMergeBase } = require('../local-review');
@@ -30,8 +30,8 @@ const { findMergeBase } = require('../local-review');
30
30
  const router = express.Router();
31
31
 
32
32
  /**
33
- * Resolve the worktree path and base_sha for a PR-mode review.
34
- * Returns { worktreePath, baseSha } or throws with { status, error } on failure.
33
+ * Resolve the worktree path and normalized repository for a PR-mode review.
34
+ * Returns { worktreePath, prNumber, repository } or throws with { statusCode } on failure.
35
35
  */
36
36
  async function resolveWorktreeForReview(review, db) {
37
37
  const prNumber = review.pr_number;
@@ -54,19 +54,7 @@ async function resolveWorktreeForReview(review, db) {
54
54
 
55
55
  const worktreePath = await worktreeManager.getWorktreePath({ owner, repo, number: prNumber });
56
56
 
57
- // Load cached PR metadata so callers can resolve exact diff blobs.
58
- const normalizedRepo = normalizeRepository(owner, repo);
59
- const prRecord = await queryOne(db, `
60
- SELECT pr_data FROM pr_metadata
61
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
62
- `, [prNumber, normalizedRepo]);
63
-
64
- const prData = safeParseJson(prRecord?.pr_data, null);
65
- if (prRecord?.pr_data && !prData) {
66
- logger.warn('Could not parse pr_data for review');
67
- }
68
-
69
- return { worktreePath, prData };
57
+ return { worktreePath, prNumber, repository: normalizeRepository(owner, repo) };
70
58
  }
71
59
 
72
60
  /**
@@ -1059,17 +1047,7 @@ router.get('/api/reviews/:reviewId/file-content/:fileName(*)', validateReviewId,
1059
1047
  // Prefer the exact blob from the cached diff snapshot. If that is unavailable,
1060
1048
  // fall back to repo-wide base_sha and finally the worktree filesystem.
1061
1049
  const normalizedRepo = normalizeRepository(owner, repo);
1062
- const prRecord = await queryOne(db, `
1063
- SELECT pr_data FROM pr_metadata
1064
- WHERE pr_number = ? AND repository = ? COLLATE NOCASE
1065
- `, [prNumber, normalizedRepo]);
1066
-
1067
- const prData = safeParseJson(prRecord?.pr_data, null);
1068
- if (prRecord?.pr_data && !prData) {
1069
- logger.warn('Could not parse pr_data for file-content route');
1070
- }
1071
-
1072
- const contentSpecs = resolveOriginalFileContentSpecs(prData, fileName);
1050
+ const contentSpecs = getPRFileContentSpecs(db, normalizedRepo, prNumber, fileName);
1073
1051
 
1074
1052
  if (contentSpecs.length > 0) {
1075
1053
  try {
@@ -1368,9 +1346,9 @@ router.get('/api/reviews/:reviewId/file-contents/:fileName(*)', validateReviewId
1368
1346
  }
1369
1347
 
1370
1348
  // --- PR mode ---
1371
- let worktreePath, prData;
1349
+ let worktreePath, prNumber, repository;
1372
1350
  try {
1373
- ({ worktreePath, prData } = await resolveWorktreeForReview(review, db));
1351
+ ({ worktreePath, prNumber, repository } = await resolveWorktreeForReview(review, db));
1374
1352
  } catch (resolveErr) {
1375
1353
  return res.status(resolveErr.statusCode || 500).json({ error: resolveErr.message });
1376
1354
  }
@@ -1378,7 +1356,7 @@ router.get('/api/reviews/:reviewId/file-contents/:fileName(*)', validateReviewId
1378
1356
  if (status !== 'added') {
1379
1357
  // Prefer the exact blob from the cached diff snapshot; fall back to base_sha.
1380
1358
  // Matches the /file-content endpoint so both stay consistent with stale PR metadata.
1381
- const contentSpecs = resolveOriginalFileContentSpecs(prData, oldFilePath);
1359
+ const contentSpecs = getPRFileContentSpecs(db, repository, prNumber, oldFilePath);
1382
1360
  for (const contentSpec of contentSpecs) {
1383
1361
  const content = await gitShow(worktreePath, contentSpec.gitSpec);
1384
1362
  if (content != null) {
@@ -167,7 +167,7 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
167
167
  const repository = normalizeRepository(owner, repo);
168
168
  const existingPR = await queryOne(
169
169
  db,
170
- 'SELECT id, pr_data FROM pr_metadata WHERE pr_number = ? AND repository = ? COLLATE NOCASE',
170
+ 'SELECT id, title, description, author, base_branch, head_branch, pr_data FROM pr_metadata WHERE pr_number = ? AND repository = ? COLLATE NOCASE',
171
171
  [prNumber, repository]
172
172
  );
173
173
  if (existingPR) {
@@ -186,15 +186,21 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
186
186
  const poolEntry = poolLifecycle ? await poolLifecycle.poolRepo.getPoolEntry(worktree.id) : null;
187
187
  if (poolEntry && poolEntry.status !== 'in_use') {
188
188
  if (poolEntry.status === 'available' && poolEntry.current_pr_number === prNumber) {
189
- // Still associated with this PR — reclaim without re-setup
189
+ // Still associated with this PR — reclaim without re-setup. The
190
+ // reclaim is atomic and conditional: another process sharing this
191
+ // database may have claimed the row since the read above.
190
192
  logger.info(`Reclaiming pool worktree ${worktree.id} for ${repository} #${prNumber} (was ${poolEntry.status})`);
191
- await poolLifecycle.poolRepo.markInUse(poolEntry.id, prNumber);
192
- const reviewRepo = new ReviewRepository(db);
193
- const { review } = await reviewRepo.getOrCreate({ prNumber, repository });
194
- await poolLifecycle.poolRepo.setCurrentReviewId(poolEntry.id, review.id);
195
- return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
193
+ const reclaimed = await poolLifecycle.reclaimForPR(poolEntry.id, prNumber);
194
+ if (reclaimed) {
195
+ const reviewRepo = new ReviewRepository(db);
196
+ const { review } = await reviewRepo.getOrCreate({ prNumber, repository });
197
+ await poolLifecycle.poolRepo.setCurrentReviewId(poolEntry.id, review.id);
198
+ return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
199
+ }
200
+ logger.info(`Pool worktree ${worktree.id} was claimed by another process before it could be reclaimed for ${repository} #${prNumber}, re-running setup to reacquire`);
201
+ } else {
202
+ logger.info(`Pool worktree ${worktree.id} for ${repository} #${prNumber} is ${poolEntry.status}, re-running setup to reacquire`);
196
203
  }
197
- logger.info(`Pool worktree ${worktree.id} for ${repository} #${prNumber} is ${poolEntry.status}, re-running setup to reacquire`);
198
204
  } else {
199
205
  return res.json({ existing: true, reviewUrl: `/pr/${owner}/${repo}/${prNumber}` });
200
206
  }
@@ -210,7 +216,14 @@ router.post('/api/setup/pr/:owner/:repo/:number', async (req, res) => {
210
216
  try {
211
217
  const parsed = JSON.parse(existingPR.pr_data);
212
218
  if (parsed.head_sha) {
213
- restoreMetadata = parsed;
219
+ restoreMetadata = {
220
+ ...parsed,
221
+ title: parsed.title ?? existingPR.title,
222
+ body: parsed.body ?? existingPR.description,
223
+ author: parsed.author ?? existingPR.author,
224
+ base_branch: parsed.base_branch ?? existingPR.base_branch,
225
+ head_branch: parsed.head_branch ?? existingPR.head_branch
226
+ };
214
227
  }
215
228
  } catch (e) {
216
229
  logger.warn(`Could not parse stored pr_data for ${repository} #${prNumber}`);
@@ -20,6 +20,7 @@ const { findMainGitRoot } = require('../local-review');
20
20
  const { getConfigDir, getRepoPath, resolveRepoOptions, resolvePoolConfig, getRepoResetScript, resolveHostBinding, resolveBindingRepositoryFromPR, getRepoConfig, getRepoCloneUrlForHost, DEFAULT_CHECKOUT_TIMEOUT_MS } = require('../config');
21
21
  const { storedHostToOption, isDualHostRepoConfig, resolveRecordedHost, bindingRepositoryForHost } = require('../utils/host-resolution');
22
22
  const logger = require('../utils/logger');
23
+ const { invalidatePRFileBlobCache } = require('../utils/pr-file-blob-cache');
23
24
  const { fireReviewStartedHook } = require('../hooks/payloads');
24
25
  const simpleGit = require('simple-git');
25
26
  const fs = require('fs').promises;
@@ -231,6 +232,10 @@ async function storePRData(db, prInfo, prData, diff, changedFiles, worktreePath,
231
232
  await run(db, 'ROLLBACK');
232
233
  logger.error('Error storing PR data:', error);
233
234
  throw new Error(`Failed to store PR data: ${error.message}`);
235
+ } finally {
236
+ // pr_data may have changed (or a lookup may have cached uncommitted rows
237
+ // mid-transaction), so drop the file-content blob cache once it settles.
238
+ invalidatePRFileBlobCache(db, repository, prInfo.number);
234
239
  }
235
240
  }
236
241
 
@@ -810,7 +815,7 @@ async function setupPRReview({ db, owner, repo, prNumber, githubToken, bindingRe
810
815
  await worktreeRepo.getOrCreate({
811
816
  prNumber,
812
817
  repository,
813
- branch: prData.head_branch || prData.head?.ref || '',
818
+ branch: worktreeManager.getPRHeadBranch(prData),
814
819
  path: worktreePath
815
820
  });
816
821
  }
@@ -948,8 +953,12 @@ async function setupPRReview({ db, owner, repo, prNumber, githubToken, bindingRe
948
953
  // mechanism can never fire to reclaim it.
949
954
  if (poolWorktreeId && poolLifecycle) {
950
955
  try {
951
- await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
952
- logger.info(`Released pool worktree ${poolWorktreeId} after setup failure`);
956
+ const released = await poolLifecycle.releaseAfterHeadless(poolWorktreeId);
957
+ if (released) {
958
+ logger.info(`Released pool worktree ${poolWorktreeId} after setup failure`);
959
+ } else {
960
+ logger.info(`Pool worktree ${poolWorktreeId} not released after setup failure: no longer held by this process`);
961
+ }
953
962
  } catch (releaseErr) {
954
963
  logger.error(`Failed to release pool worktree ${poolWorktreeId} after setup failure: ${releaseErr.message}`);
955
964
  }
@@ -9,53 +9,79 @@
9
9
 
10
10
  const { parseDiffGitPaths, parsePatchPaths } = require('./git-paths');
11
11
 
12
- function findFileBlobInfoInDiff(diffText, fileName) {
13
- if (!diffText || !fileName) {
14
- return null;
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 matchedPaths = null;
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
- const paths = parsePatchPaths(lines, i);
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 (!matchedPaths || !line.startsWith('index ')) {
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
- if (!match) {
36
- return null;
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
- return {
40
- ...matchedPaths,
41
- oldBlob: match[1],
42
- newBlob: match[2]
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
- function resolveOriginalFileContentSpecs(prData, fileName) {
54
- if (!prData || typeof prData !== 'object') {
55
- return [];
56
- }
57
-
58
- const blobInfo = findFileBlobInfoInDiff(prData.diff, fileName);
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 (prData.base_sha) {
94
+ if (baseSha) {
69
95
  const originalPath = blobInfo?.oldPath || fileName;
70
96
  specs.push({
71
- gitSpec: `${prData.base_sha}:${originalPath}`,
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
- // Look for patterns that start our expected JSON structures
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('; ')}${repairAttempted ? ' (a control-character repair pass was also attempted and failed)' : ''}`);
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 };