@in-the-loop-labs/pair-review 5.0.3 → 5.1.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.
Files changed (37) hide show
  1. package/README.md +26 -3
  2. package/package.json +4 -3
  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/plugin-pair-loop/skills/loop/SKILL.md +21 -6
  7. package/public/css/pr.css +2 -2
  8. package/public/js/vendor/pierre-diffs-worker.js +3446 -5992
  9. package/public/js/vendor/pierre-diffs.js +731 -1047
  10. package/src/ai/abort-signal-wiring.js +91 -46
  11. package/src/ai/analyzer.js +191 -27
  12. package/src/ai/antigravity-provider.js +31 -5
  13. package/src/ai/claude-cli.js +8 -2
  14. package/src/ai/claude-provider.js +34 -5
  15. package/src/ai/codex-provider.js +31 -5
  16. package/src/ai/copilot-provider.js +28 -4
  17. package/src/ai/cursor-agent-provider.js +32 -5
  18. package/src/ai/executable-provider.js +8 -2
  19. package/src/ai/index.js +1 -0
  20. package/src/ai/muse-provider.js +1224 -0
  21. package/src/ai/opencode-provider.js +31 -5
  22. package/src/ai/pi-provider.js +29 -4
  23. package/src/ai/provider.js +111 -28
  24. package/src/ai/stream-parser.js +71 -0
  25. package/src/config.js +35 -2
  26. package/src/database.js +96 -16
  27. package/src/git/fetch-helpers.js +48 -0
  28. package/src/git/pack-cleanup.js +120 -0
  29. package/src/git/worktree.js +65 -43
  30. package/src/main.js +176 -27
  31. package/src/routes/analyses.js +6 -2
  32. package/src/routes/local.js +6 -5
  33. package/src/routes/mcp.js +5 -2
  34. package/src/routes/pr.js +8 -7
  35. package/src/routes/shared.js +27 -0
  36. package/src/routes/stack-analysis.js +4 -1
  37. package/src/utils/json-extractor.js +162 -41
@@ -2,40 +2,114 @@
2
2
  const logger = require('./logger');
3
3
 
4
4
  /**
5
- * Extract JSON from text responses using multiple strategies.
6
- * This is a shared utility to ensure consistent JSON extraction across the application.
5
+ * Escape a single control character (U+0000 - U+001F) to its JSON string form.
6
+ * @param {string} ch - Single control character
7
+ * @returns {string} Escaped form (e.g. '\\n', '\\u0001')
8
+ */
9
+ function escapeControlCharacter(ch) {
10
+ switch (ch) {
11
+ case '\n': return '\\n';
12
+ case '\r': return '\\r';
13
+ case '\t': return '\\t';
14
+ case '\b': return '\\b';
15
+ case '\f': return '\\f';
16
+ default: return '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0');
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Escape raw (unescaped) control characters found inside JSON string literals.
22
+ *
23
+ * LLM responses that embed code snippets in string values sometimes contain
24
+ * literal newlines/tabs instead of the \n / \t escapes JSON requires. A single
25
+ * such character makes JSON.parse reject the entire response ("Bad control
26
+ * character in string literal"), which can silently discard every suggestion
27
+ * in a large consolidation response (issue #560).
28
+ *
29
+ * Walks the text tracking string/escape state (the same state machine used by
30
+ * the bracket-matching strategy) and rewrites control characters (U+0000 -
31
+ * U+001F) that appear inside string literals to their escaped forms. Text
32
+ * outside string literals is left untouched — control characters there are
33
+ * legal JSON whitespace or would be a structural error sanitization cannot fix.
34
+ *
35
+ * @param {string} text - Candidate JSON text
36
+ * @returns {string} Text with in-string control characters escaped
37
+ */
38
+ function sanitizeControlCharactersInStrings(text) {
39
+ let result = '';
40
+ let inString = false;
41
+ let escaped = false;
42
+
43
+ for (let i = 0; i < text.length; i++) {
44
+ const ch = text[i];
45
+
46
+ if (!inString) {
47
+ if (ch === '"') inString = true;
48
+ result += ch;
49
+ continue;
50
+ }
51
+
52
+ if (escaped) {
53
+ escaped = false;
54
+ if (ch.charCodeAt(0) < 0x20) {
55
+ // A raw control character cannot follow a backslash in valid JSON.
56
+ // Double the dangling backslash into a literal '\\' and escape the
57
+ // control character itself.
58
+ result += '\\' + escapeControlCharacter(ch);
59
+ } else {
60
+ result += ch;
61
+ }
62
+ continue;
63
+ }
64
+
65
+ if (ch === '\\') {
66
+ escaped = true;
67
+ result += ch;
68
+ continue;
69
+ }
70
+
71
+ if (ch === '"') {
72
+ inString = false;
73
+ result += ch;
74
+ continue;
75
+ }
76
+
77
+ if (ch.charCodeAt(0) < 0x20) {
78
+ result += escapeControlCharacter(ch);
79
+ continue;
80
+ }
81
+
82
+ result += ch;
83
+ }
84
+
85
+ return result;
86
+ }
87
+
88
+ /**
89
+ * Run all extraction strategies against a candidate text.
7
90
  *
8
91
  * Strategies are tried in order:
9
92
  * 1. Markdown code blocks (```json ... ```)
10
- * 2. Direct JSON.parse of the trimmed response
93
+ * 2. Direct JSON.parse of the trimmed text
11
94
  * 3. First { to last } substring
12
95
  * 4. Known JSON key anchors (e.g. {"level", {"suggestions")
13
96
  * 5. Forward scan: try JSON.parse from every top-level { in the text
14
97
  * 6. Bracket-matched substring from the first {
15
98
  *
16
- * @param {string} response - Raw response text (may include preamble/postamble prose)
17
- * @param {string|number} level - Level identifier for logging (e.g., 1, 2, 3, 'orchestration', 'unknown')
18
- * @param {string} [logPrefix] - Custom log prefix to use instead of `[Level <level>]`.
19
- * Used by callers (e.g., summary generation, council mode) that have a more
20
- * meaningful identifier than a numeric analysis level.
21
- * @returns {Object} Extraction result with success flag and data/error
99
+ * @param {string} text - Candidate text (may include preamble/postamble prose)
100
+ * @returns {{data: (Object|null), strategy: number|undefined, strategyErrors: Array<string>}}
101
+ * data is null when every strategy failed; strategyErrors collects per-strategy failures
22
102
  */
23
- function extractJSON(response, level = 'unknown', logPrefix) {
24
- const levelPrefix = logPrefix || `[Level ${level}]`;
25
-
26
- if (!response || !response.trim()) {
27
- return { success: false, error: 'Empty response' };
28
- }
29
-
103
+ function runExtractionStrategies(text) {
30
104
  const strategies = [
31
105
  // Strategy 1: Look for markdown code blocks with 'json' label
32
106
  () => {
33
107
  // First, try to find ```json specifically (more precise)
34
- let codeBlockMatch = response.match(/```json\s*\n([\s\S]*?)\n```/);
108
+ let codeBlockMatch = text.match(/```json\s*\n([\s\S]*?)\n```/);
35
109
 
36
110
  // If not found, try generic ``` blocks
37
111
  if (!codeBlockMatch) {
38
- codeBlockMatch = response.match(/```\s*\n([\s\S]*?)\n```/);
112
+ codeBlockMatch = text.match(/```\s*\n([\s\S]*?)\n```/);
39
113
  }
40
114
 
41
115
  if (codeBlockMatch && codeBlockMatch[1]) {
@@ -48,18 +122,18 @@ function extractJSON(response, level = 'unknown', logPrefix) {
48
122
  throw new Error('No JSON code block found');
49
123
  },
50
124
 
51
- // Strategy 2: Try the entire response as JSON (fast path for clean responses)
125
+ // Strategy 2: Try the entire text as JSON (fast path for clean responses)
52
126
  () => {
53
- return JSON.parse(response.trim());
127
+ return JSON.parse(text.trim());
54
128
  },
55
129
 
56
130
  // Strategy 3: Look for JSON between first { and last }
57
- // Works when the response is just JSON or has minimal wrapping
131
+ // Works when the text is just JSON or has minimal wrapping
58
132
  () => {
59
- const firstBrace = response.indexOf('{');
60
- const lastBrace = response.lastIndexOf('}');
133
+ const firstBrace = text.indexOf('{');
134
+ const lastBrace = text.lastIndexOf('}');
61
135
  if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
62
- return JSON.parse(response.substring(firstBrace, lastBrace + 1));
136
+ return JSON.parse(text.substring(firstBrace, lastBrace + 1));
63
137
  }
64
138
  throw new Error('No valid JSON braces found');
65
139
  },
@@ -80,13 +154,13 @@ function extractJSON(response, level = 'unknown', logPrefix) {
80
154
  ];
81
155
 
82
156
  for (const anchor of anchors) {
83
- const match = response.match(anchor);
157
+ const match = text.match(anchor);
84
158
  if (match) {
85
159
  const startIdx = match.index;
86
160
  // Find the matching closing brace from the end
87
- const lastBrace = response.lastIndexOf('}');
161
+ const lastBrace = text.lastIndexOf('}');
88
162
  if (lastBrace > startIdx) {
89
- const candidate = response.substring(startIdx, lastBrace + 1);
163
+ const candidate = text.substring(startIdx, lastBrace + 1);
90
164
  return JSON.parse(candidate);
91
165
  }
92
166
  }
@@ -102,19 +176,19 @@ function extractJSON(response, level = 'unknown', logPrefix) {
102
176
  // Limit attempts to avoid excessive parsing on very large non-JSON text
103
177
  const maxAttempts = 20;
104
178
  let attempts = 0;
105
- const lastBrace = response.lastIndexOf('}');
179
+ const lastBrace = text.lastIndexOf('}');
106
180
 
107
- while (searchFrom < response.length && attempts < maxAttempts) {
108
- const braceIdx = response.indexOf('{', searchFrom);
181
+ while (searchFrom < text.length && attempts < maxAttempts) {
182
+ const braceIdx = text.indexOf('{', searchFrom);
109
183
  if (braceIdx === -1) break;
110
184
 
111
185
  attempts++;
112
186
  try {
113
- // Try parsing from this brace to the end of the response.
187
+ // Try parsing from this brace to the end of the text.
114
188
  // JSON.parse is lenient about trailing content only if we trim to the
115
189
  // right boundary, so use lastIndexOf('}') from the end.
116
190
  if (lastBrace > braceIdx) {
117
- const candidate = response.substring(braceIdx, lastBrace + 1);
191
+ const candidate = text.substring(braceIdx, lastBrace + 1);
118
192
  const parsed = JSON.parse(candidate);
119
193
  if (parsed && typeof parsed === 'object') {
120
194
  return parsed;
@@ -133,15 +207,15 @@ function extractJSON(response, level = 'unknown', logPrefix) {
133
207
  // the end of the first top-level object. No iteration cap — the loop
134
208
  // runs for the full length of the matched region.
135
209
  () => {
136
- const firstBrace = response.indexOf('{');
210
+ const firstBrace = text.indexOf('{');
137
211
  if (firstBrace === -1) throw new Error('No opening brace found');
138
212
 
139
213
  let braceCount = 0;
140
214
  let inString = false;
141
215
  let escaped = false;
142
216
 
143
- for (let i = firstBrace; i < response.length; i++) {
144
- const ch = response[i];
217
+ for (let i = firstBrace; i < text.length; i++) {
218
+ const ch = text[i];
145
219
 
146
220
  if (escaped) {
147
221
  escaped = false;
@@ -164,7 +238,7 @@ function extractJSON(response, level = 'unknown', logPrefix) {
164
238
  else if (ch === '}') {
165
239
  braceCount--;
166
240
  if (braceCount === 0) {
167
- return JSON.parse(response.substring(firstBrace, i + 1));
241
+ return JSON.parse(text.substring(firstBrace, i + 1));
168
242
  }
169
243
  }
170
244
  }
@@ -177,17 +251,64 @@ function extractJSON(response, level = 'unknown', logPrefix) {
177
251
  try {
178
252
  const data = strategies[i]();
179
253
  if (data && typeof data === 'object') {
180
- logger.info(`${levelPrefix} JSON extraction successful using strategy ${i + 1}`);
181
- return { success: true, data };
254
+ return { data, strategy: i + 1, strategyErrors };
182
255
  }
183
256
  } catch (error) {
184
257
  strategyErrors.push(`S${i + 1}: ${error.message}`);
185
258
  }
186
259
  }
260
+ return { data: null, strategy: undefined, strategyErrors };
261
+ }
262
+
263
+ /**
264
+ * Extract JSON from text responses using multiple strategies.
265
+ * This is a shared utility to ensure consistent JSON extraction across the application.
266
+ *
267
+ * The strategies (see runExtractionStrategies) run against the original
268
+ * response first. If all fail, a repair pass escapes raw control characters
269
+ * inside string literals (issue #560) and the strategies run once more against
270
+ * the sanitized text.
271
+ *
272
+ * @param {string} response - Raw response text (may include preamble/postamble prose)
273
+ * @param {string|number} level - Level identifier for logging (e.g., 1, 2, 3, 'orchestration', 'unknown')
274
+ * @param {string} [logPrefix] - Custom log prefix to use instead of `[Level <level>]`.
275
+ * Used by callers (e.g., summary generation, council mode) that have a more
276
+ * meaningful identifier than a numeric analysis level.
277
+ * @returns {Object} Extraction result with success flag and data/error
278
+ */
279
+ function extractJSON(response, level = 'unknown', logPrefix) {
280
+ const levelPrefix = logPrefix || `[Level ${level}]`;
281
+
282
+ if (!response || !response.trim()) {
283
+ return { success: false, error: 'Empty response' };
284
+ }
285
+
286
+ const firstPass = runExtractionStrategies(response);
287
+ if (firstPass.data) {
288
+ logger.info(`${levelPrefix} JSON extraction successful using strategy ${firstPass.strategy}`);
289
+ return { success: true, data: firstPass.data };
290
+ }
291
+
292
+ // Repair pass: escape raw control characters inside string literals and
293
+ // retry. Sanitize only from the first { onward so quotes in surrounding
294
+ // prose don't desync the in-string state machine.
295
+ const braceIdx = response.indexOf('{');
296
+ const sanitized = braceIdx === -1
297
+ ? response
298
+ : response.slice(0, braceIdx) + sanitizeControlCharactersInStrings(response.slice(braceIdx));
299
+ const repairAttempted = sanitized !== response;
300
+ if (repairAttempted) {
301
+ const repairPass = runExtractionStrategies(sanitized);
302
+ if (repairPass.data) {
303
+ logger.info(`${levelPrefix} JSON extraction successful using strategy ${repairPass.strategy} after control-character repair`);
304
+ return { success: true, data: repairPass.data };
305
+ }
306
+ }
187
307
 
188
- // All strategies failed — log details for debugging
308
+ // All strategies failed — log the first pass's errors so `position N`
309
+ // offsets line up with the original-response preview below
189
310
  logger.warn(`${levelPrefix} All JSON extraction strategies failed`);
190
- logger.warn(`${levelPrefix} Strategy errors: ${strategyErrors.join('; ')}`);
311
+ logger.warn(`${levelPrefix} Strategy errors: ${firstPass.strategyErrors.join('; ')}${repairAttempted ? ' (a control-character repair pass was also attempted and failed)' : ''}`);
191
312
  logger.warn(`${levelPrefix} Response length: ${response.length} chars, preview: ${response.substring(0, 200)}...`);
192
313
 
193
314
  return {
@@ -197,4 +318,4 @@ function extractJSON(response, level = 'unknown', logPrefix) {
197
318
  };
198
319
  }
199
320
 
200
- module.exports = { extractJSON };
321
+ module.exports = { extractJSON, sanitizeControlCharactersInStrings };