@in-the-loop-labs/pair-review 5.1.0 → 5.2.0

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 (39) hide show
  1. package/README.md +14 -4
  2. package/package.json +3 -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/plugin-pair-loop/skills/loop/SKILL.md +21 -6
  7. package/public/css/pr.css +2 -2
  8. package/public/index.html +5 -2
  9. package/public/js/index.js +106 -9
  10. package/src/ai/analyzer.js +191 -27
  11. package/src/ai/index.js +1 -0
  12. package/src/ai/omp/review-config.yml +13 -0
  13. package/src/ai/omp-provider.js +279 -0
  14. package/src/ai/pi-format.js +535 -0
  15. package/src/ai/pi-provider.js +38 -963
  16. package/src/ai/pi-style-provider.js +526 -0
  17. package/src/ai/provider.js +2 -0
  18. package/src/chat/chat-providers.js +34 -11
  19. package/src/chat/omp-bridge.js +111 -0
  20. package/src/chat/pi-bridge.js +42 -34
  21. package/src/chat/session-manager.js +30 -4
  22. package/src/config.js +32 -3
  23. package/src/links/host-names.js +200 -0
  24. package/src/local-review.js +7 -3
  25. package/src/main.js +21 -1
  26. package/src/review-config.js +81 -5
  27. package/src/routes/analyses.js +6 -2
  28. package/src/routes/config.js +16 -0
  29. package/src/routes/local.js +7 -6
  30. package/src/routes/mcp.js +5 -2
  31. package/src/routes/pr.js +8 -5
  32. package/src/routes/setup.js +1 -1
  33. package/src/routes/shared.js +27 -0
  34. package/src/routes/stack-analysis.js +4 -1
  35. package/src/settings/registry.js +1 -1
  36. package/src/setup/local-setup.js +5 -3
  37. package/src/single-port.js +1 -1
  38. package/src/utils/json-extractor.js +162 -41
  39. package/src/utils/local-path-input.js +64 -8
@@ -6,7 +6,7 @@ const { fireHooks, hasHooks } = require('../hooks/hook-runner');
6
6
  const { buildReviewStartedPayload, buildReviewLoadedPayload, getCachedUser } = require('../hooks/payloads');
7
7
  const { STOPS } = require('../local-scope');
8
8
  const logger = require('../utils/logger');
9
- const { LOCAL_REVIEW_PATH_URL_ERROR, rejectUrlLikeLocalReviewPath } = require('../utils/local-path-input');
9
+ const { isLocalPathUrlError, rejectUrlLikeLocalReviewPath } = require('../utils/local-path-input');
10
10
  const path = require('path');
11
11
  const fs = require('fs').promises;
12
12
 
@@ -35,12 +35,14 @@ async function setupLocalReview({ db, targetPath, onProgress, config, flags = {}
35
35
  let resolvedPath;
36
36
  try {
37
37
  progress({ step: 'validate', status: 'running', message: 'Validating target path...' });
38
- rejectUrlLikeLocalReviewPath(targetPath);
38
+ rejectUrlLikeLocalReviewPath(targetPath, config);
39
39
  resolvedPath = path.resolve(targetPath);
40
40
  await fs.access(resolvedPath);
41
41
  progress({ step: 'validate', status: 'completed', message: `Path resolved to ${resolvedPath}` });
42
42
  } catch (err) {
43
- const message = err.message === LOCAL_REVIEW_PATH_URL_ERROR
43
+ // Branch on the error CODE, never the message: the URL error names the
44
+ // configured hosts, so its text varies per installation.
45
+ const message = isLocalPathUrlError(err)
44
46
  ? err.message
45
47
  : `Path does not exist: ${path.resolve(targetPath)}`;
46
48
  progress({ step: 'validate', status: 'error', message });
@@ -327,7 +327,7 @@ async function attemptDelegation(config, flags, prArgs, _deps, options = {}) {
327
327
  // analyze=true (and analysisConfigId supersedes both when present).
328
328
  let url;
329
329
  if (flags.local) {
330
- rejectUrlLikeLocalReviewPath(flags.localPath);
330
+ rejectUrlLikeLocalReviewPath(flags.localPath, config);
331
331
  const targetPath = path.resolve(flags.localPath || process.cwd());
332
332
  const analysisConfigId = await handoffAnalysisConfigId(options.localRepository || null);
333
333
  url = buildDelegationUrl(port, 'local', {
@@ -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 };
@@ -1,23 +1,62 @@
1
1
  // Copyright 2026 Tim Perkins (tjwp) | SPDX-License-Identifier: Apache-2.0
2
2
 
3
- const LOCAL_REVIEW_PATH_URL_ERROR = 'Local reviews require a filesystem path, not a URL. Pass GitHub or Graphite URLs as PR review inputs instead.';
3
+ const { resolveHostListText, resolveUrlLikeHostnames } = require('../links/host-names');
4
+
5
+ /**
6
+ * Error code stamped on the "you passed a URL, not a path" error.
7
+ *
8
+ * Callers MUST branch on this rather than comparing the message text — the
9
+ * message names the configured hosts and therefore varies per installation.
10
+ */
11
+ const LOCAL_PATH_IS_URL_CODE = 'LOCAL_PATH_IS_URL';
12
+
13
+ /**
14
+ * Build the user-facing message for a local-review path that is really a URL.
15
+ *
16
+ * Without a config the message stays host-neutral. Falling back to the
17
+ * built-in list would name GitHub alone, which actively misinforms: on an
18
+ * install with `enable_graphite` or an alt host, those URLs ARE accepted as PR
19
+ * review inputs.
20
+ *
21
+ * @param {Object} [config] - Configuration object from loadConfig()
22
+ * @returns {string}
23
+ */
24
+ function localReviewPathUrlError(config) {
25
+ const hostClause = (config && typeof config === 'object')
26
+ ? `${resolveHostListText(config)} URLs`
27
+ : 'PR URLs';
28
+ return 'Local reviews require a filesystem path, not a URL. '
29
+ + `Pass ${hostClause} as PR review inputs instead.`;
30
+ }
4
31
 
5
32
  /**
6
33
  * Detect inputs that are URLs or remote-style Git URLs rather than filesystem paths.
7
34
  * This intentionally checks only unambiguous URL forms so normal absolute,
8
35
  * relative, tilde, and Windows paths continue to work.
9
36
  *
37
+ * Scheme-less PR URLs are recognised for github.com, Graphite, and every
38
+ * configured alt host (both its `api_host` and its `links.external`
39
+ * web host, which are frequently different domains).
40
+ *
10
41
  * @param {unknown} input
42
+ * @param {Object} [config] - Configuration object; without it only the
43
+ * built-in hosts are recognised scheme-less.
11
44
  * @returns {boolean}
12
45
  */
13
- function isUrlLikeLocalReviewPath(input) {
46
+ function isUrlLikeLocalReviewPath(input, config) {
14
47
  if (typeof input !== 'string') return false;
15
48
 
16
49
  const value = input.trim();
17
50
  if (!value) return false;
18
51
 
19
52
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return true;
20
- if (/^(?:github\.com|app\.graphite\.(?:dev|com))\//i.test(value)) return true;
53
+
54
+ const hostnames = resolveUrlLikeHostnames(config);
55
+ const lower = value.toLowerCase();
56
+ // Require a path separator so a bare hostname-shaped directory name is not
57
+ // mistaken for a URL, matching the previous built-in behaviour.
58
+ if (hostnames.some(hostname => lower.startsWith(`${hostname}/`))) return true;
59
+
21
60
  // Treat only a leading user@host:path token as SSH remote syntax; if a
22
61
  // directory prefix contains @ and : it should remain a filesystem path.
23
62
  if (/^[^@/\\\s]+@[^:/\\\s]+:[^\s]+$/.test(value)) return true;
@@ -28,17 +67,34 @@ function isUrlLikeLocalReviewPath(input) {
28
67
  /**
29
68
  * Throw a user-facing error when a local review path is actually a URL.
30
69
  *
70
+ * The thrown error carries `code === LOCAL_PATH_IS_URL_CODE`.
71
+ *
31
72
  * @param {unknown} input
73
+ * @param {Object} [config] - Configuration object from loadConfig()
32
74
  * @throws {Error}
33
75
  */
34
- function rejectUrlLikeLocalReviewPath(input) {
35
- if (isUrlLikeLocalReviewPath(input)) {
36
- throw new Error(LOCAL_REVIEW_PATH_URL_ERROR);
76
+ function rejectUrlLikeLocalReviewPath(input, config) {
77
+ if (isUrlLikeLocalReviewPath(input, config)) {
78
+ const error = new Error(localReviewPathUrlError(config));
79
+ error.code = LOCAL_PATH_IS_URL_CODE;
80
+ throw error;
37
81
  }
38
82
  }
39
83
 
84
+ /**
85
+ * True when an error came from rejectUrlLikeLocalReviewPath().
86
+ *
87
+ * @param {unknown} error
88
+ * @returns {boolean}
89
+ */
90
+ function isLocalPathUrlError(error) {
91
+ return Boolean(error) && error.code === LOCAL_PATH_IS_URL_CODE;
92
+ }
93
+
40
94
  module.exports = {
41
- LOCAL_REVIEW_PATH_URL_ERROR,
95
+ LOCAL_PATH_IS_URL_CODE,
96
+ localReviewPathUrlError,
42
97
  isUrlLikeLocalReviewPath,
43
- rejectUrlLikeLocalReviewPath
98
+ rejectUrlLikeLocalReviewPath,
99
+ isLocalPathUrlError
44
100
  };