@in-the-loop-labs/pair-review 5.1.0 → 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.
- package/README.md +2 -0
- package/package.json +1 -1
- 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/plugin-pair-loop/skills/loop/SKILL.md +21 -6
- package/public/css/pr.css +2 -2
- package/src/ai/analyzer.js +191 -27
- package/src/routes/analyses.js +6 -2
- package/src/routes/local.js +6 -5
- package/src/routes/mcp.js +5 -2
- package/src/routes/pr.js +6 -4
- package/src/routes/shared.js +27 -0
- package/src/routes/stack-analysis.js +4 -1
- package/src/utils/json-extractor.js +162 -41
package/README.md
CHANGED
|
@@ -988,6 +988,8 @@ An implement→review→fix loop with pair-review as the review oracle. The agen
|
|
|
988
988
|
|-------|-------------|
|
|
989
989
|
| `/pair-loop:loop` | Implement, review with pair-review councils, triage, fix, and repeat until clean |
|
|
990
990
|
|
|
991
|
+
**Run the loop in your agent's main session — do not delegate it to a subagent.** Each council round is a 15–40 minute external process owned by the session that started it, so a subagent's exit kills the round mid-flight and the work is discarded. Delegating the implementation or fix work *within* a round is fine; delegating the loop itself is not.
|
|
992
|
+
|
|
991
993
|
### code-critic — Standalone Analysis
|
|
992
994
|
|
|
993
995
|
AI-powered code review analysis that works without any server or MCP dependency. Install this plugin for three-level AI analysis directly in your coding agent.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pair-review",
|
|
3
|
-
"version": "5.1.
|
|
3
|
+
"version": "5.1.1",
|
|
4
4
|
"description": "pair-review app integration — Open PRs and local changes in the pair-review web UI, run server-side AI analysis, and address review feedback. Requires the pair-review MCP server.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "in-the-loop-labs",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pair-loop",
|
|
3
|
-
"version": "5.1.
|
|
3
|
+
"version": "5.1.1",
|
|
4
4
|
"description": "Agent-orchestrated review loop — implement, review with pair-review multi-model councils via the headless CLI, triage, fix, and repeat until a final review returns no blockers. MCP-independent.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "in-the-loop-labs",
|
|
@@ -49,11 +49,19 @@ These are not judgment calls:
|
|
|
49
49
|
3. **Sequence strictly: fix → write triage back → then run the next round.**
|
|
50
50
|
4. **One review at a time.** Never run two reviews concurrently for the same
|
|
51
51
|
repo.
|
|
52
|
-
5. **
|
|
52
|
+
5. **Drive the loop from the session that owns it — never delegate a review
|
|
53
|
+
round to a subagent.** A round is a 15–40 minute external process, and a
|
|
54
|
+
background process is killed when the session that spawned it ends. A
|
|
55
|
+
subagent's session ends the moment it returns, so a round launched inside
|
|
56
|
+
one dies mid-flight and the run is lost. If you are reading this from
|
|
57
|
+
inside a subagent, do not start a round — hand the loop back to the main
|
|
58
|
+
session. (Subagents are still fine for work that *finishes inside the
|
|
59
|
+
agent*: implementing the objective, applying a batch of fixes.)
|
|
60
|
+
6. **Do not commit or push.** Leave changes in the working tree. New
|
|
53
61
|
(untracked) files are included automatically whenever the review scope ends
|
|
54
62
|
at `untracked` — which the default scope (`unstaged..untracked`) does — so
|
|
55
63
|
no `git add -N` (intent-to-add) is needed.
|
|
56
|
-
|
|
64
|
+
7. **Report failures faithfully.** A failed run (`"ok": false`, non-zero
|
|
57
65
|
exit) is reported as what it is — never papered over as "no findings".
|
|
58
66
|
|
|
59
67
|
## Phase: Setup
|
|
@@ -69,8 +77,10 @@ These are not judgment calls:
|
|
|
69
77
|
call. An unknown handle → show the available names and ask the user.
|
|
70
78
|
4. If an objective was given and the working tree has no relevant changes
|
|
71
79
|
yet, implement the objective first (directly or via a Task agent — your
|
|
72
|
-
call based on size
|
|
73
|
-
before
|
|
80
|
+
call based on size; delegation is safe here because the agent's work
|
|
81
|
+
finishes before it returns, unlike a review round — hard rule 5). Verify
|
|
82
|
+
with `git status --short` that changes exist before the first review
|
|
83
|
+
round; if none, tell the user and stop.
|
|
74
84
|
|
|
75
85
|
## Running a review round
|
|
76
86
|
|
|
@@ -94,6 +104,10 @@ pair-review --local --headless --json --council <handle> [--scope <range>] --ins
|
|
|
94
104
|
Run the command in the background (or with a timeout of at least 45
|
|
95
105
|
minutes) and wait for it to exit. Do not abandon or kill it early; do not
|
|
96
106
|
start a second review while one is running (hard rule 4).
|
|
107
|
+
- **Launch it from the loop's own session, not from a subagent.** The
|
|
108
|
+
background process belongs to the session that spawned it, so a round
|
|
109
|
+
started inside a subagent is killed the moment that agent returns — the
|
|
110
|
+
council work is thrown away and the JSON never arrives (hard rule 5).
|
|
97
111
|
- stdout is exactly one JSON document (logs go to stderr):
|
|
98
112
|
- success: `{"ok": true, "mode": "local", "run": {...}, "suggestions":
|
|
99
113
|
[...], "count": N}` — exit code 0. **Zero suggestions is still
|
|
@@ -141,8 +155,9 @@ fresh.
|
|
|
141
155
|
## Fix
|
|
142
156
|
|
|
143
157
|
Apply the fixes (directly or via a Task agent for large batches — your
|
|
144
|
-
call
|
|
145
|
-
|
|
158
|
+
call; delegation is safe here for the same reason as in Setup — the agent's
|
|
159
|
+
edits and test runs complete before it returns). Run the project's relevant
|
|
160
|
+
tests for the changed code. A fix that breaks tests is not a fix.
|
|
146
161
|
|
|
147
162
|
## Write triage back (optional, needs the server)
|
|
148
163
|
|
package/public/css/pr.css
CHANGED
|
@@ -5225,8 +5225,8 @@ div.external-comment-row {
|
|
|
5225
5225
|
border: 1px solid #d1d9e0;
|
|
5226
5226
|
border-radius: 6px;
|
|
5227
5227
|
resize: vertical;
|
|
5228
|
-
min-height:
|
|
5229
|
-
max-height:
|
|
5228
|
+
min-height: 90px;
|
|
5229
|
+
max-height: 60vh;
|
|
5230
5230
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
|
5231
5231
|
}
|
|
5232
5232
|
|
package/src/ai/analyzer.js
CHANGED
|
@@ -385,6 +385,20 @@ A suggestion is a duplicate if it targets the same file and overlapping lines an
|
|
|
385
385
|
return sections.join('\n\n');
|
|
386
386
|
}
|
|
387
387
|
|
|
388
|
+
/**
|
|
389
|
+
* A response object is "ours" if it carries any key from our response schema.
|
|
390
|
+
* A string `summary` alone is a valid zero-finding result (e.g. "all findings
|
|
391
|
+
* duplicated existing comments"), so it counts. Shared by both acceptance
|
|
392
|
+
* branches in parseResponseWithMeta so they cannot drift (issue #560).
|
|
393
|
+
* @param {Object} obj - Candidate response object
|
|
394
|
+
* @returns {boolean} True if the object carries any schema key
|
|
395
|
+
*/
|
|
396
|
+
function hasSchemaKeys(obj) {
|
|
397
|
+
return Array.isArray(obj.suggestions) ||
|
|
398
|
+
Array.isArray(obj.fileLevelSuggestions) ||
|
|
399
|
+
typeof obj.summary === 'string';
|
|
400
|
+
}
|
|
401
|
+
|
|
388
402
|
class Analyzer {
|
|
389
403
|
/**
|
|
390
404
|
* @param {Object} database - Database instance
|
|
@@ -643,9 +657,15 @@ class Analyzer {
|
|
|
643
657
|
|
|
644
658
|
const orchestrationResult = await this.orchestrateWithAI(allSuggestions, prMetadata, mergedInstructions, worktreePath, { analysisId, tier, progressCallback, timeout: executionTimeout, logPrefix, reviewerNum, excludePrevious, dedupContext, githubClient });
|
|
645
659
|
|
|
646
|
-
//
|
|
660
|
+
// orchestrateWithAI degrades to the raw union of level suggestions when
|
|
661
|
+
// consolidation fails internally — report that honestly instead of 'success'
|
|
662
|
+
const consolidationOutcome = orchestrationResult.consolidationFailed ? 'failed' : 'success';
|
|
663
|
+
|
|
664
|
+
// Report orchestration step outcome
|
|
647
665
|
if (progressCallback) {
|
|
648
|
-
progressCallback(
|
|
666
|
+
progressCallback(orchestrationResult.consolidationFailed
|
|
667
|
+
? { level: 'orchestration', status: 'failed', progress: 'Cross-level consolidation failed' }
|
|
668
|
+
: { level: 'orchestration', status: 'completed', progress: 'Cross-level consolidation complete' });
|
|
649
669
|
}
|
|
650
670
|
|
|
651
671
|
// Validate and finalize suggestions
|
|
@@ -670,7 +690,7 @@ class Analyzer {
|
|
|
670
690
|
level1: levelResults.level1.status,
|
|
671
691
|
level2: levelResults.level2.status,
|
|
672
692
|
level3: levelResults.level3.status,
|
|
673
|
-
consolidation:
|
|
693
|
+
consolidation: consolidationOutcome
|
|
674
694
|
};
|
|
675
695
|
|
|
676
696
|
// Update analysis_run record with completion data
|
|
@@ -694,7 +714,8 @@ class Analyzer {
|
|
|
694
714
|
suggestions: finalSuggestions,
|
|
695
715
|
levelResults,
|
|
696
716
|
levelOutcomes,
|
|
697
|
-
summary: orchestrationResult.summary
|
|
717
|
+
summary: orchestrationResult.summary,
|
|
718
|
+
...(orchestrationResult.consolidationFailed ? { orchestrationFailed: true } : {})
|
|
698
719
|
};
|
|
699
720
|
|
|
700
721
|
} catch (orchestrationError) {
|
|
@@ -1192,6 +1213,8 @@ Or simply ignore any changes to files matching these patterns in your analysis.
|
|
|
1192
1213
|
});
|
|
1193
1214
|
|
|
1194
1215
|
// Parse and validate the response
|
|
1216
|
+
// A parse failure here still reports Level 1 success with zero suggestions;
|
|
1217
|
+
// honest per-level parse-failure reporting is a known follow-up to issue #560.
|
|
1195
1218
|
updateProgress('Processing AI results');
|
|
1196
1219
|
const parsedSuggestions = this.parseResponse(response, 1);
|
|
1197
1220
|
logger.success(`${lp}Parsed ${parsedSuggestions.length} valid Level 1 suggestions`);
|
|
@@ -1623,30 +1646,64 @@ If you are unsure, use "NEW" - it is correct for the vast majority of suggestion
|
|
|
1623
1646
|
* @param {Array} previousSuggestions - Previous suggestions to check for duplicates
|
|
1624
1647
|
*/
|
|
1625
1648
|
parseResponse(response, level, previousSuggestions = []) {
|
|
1649
|
+
return this.parseResponseWithMeta(response, level, previousSuggestions).suggestions;
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/**
|
|
1653
|
+
* Parse a response into suggestions, also reporting whether the response was
|
|
1654
|
+
* recognizable as our response schema. `parseFailed: true` means no parseable
|
|
1655
|
+
* suggestions were found — nothing in the response carried any of our schema
|
|
1656
|
+
* keys (suggestions / fileLevelSuggestions / summary). That is distinct from
|
|
1657
|
+
* a legitimately empty `suggestions: []` or a summary-only zero-finding
|
|
1658
|
+
* response — consolidation callers use the distinction to fall back instead
|
|
1659
|
+
* of silently reporting success with zero suggestions (issue #560).
|
|
1660
|
+
*
|
|
1661
|
+
* @param {Object} response - Provider response
|
|
1662
|
+
* @param {number|string} level - Analysis level (for logging)
|
|
1663
|
+
* @param {Array} previousSuggestions - Previous suggestions to check for duplicates
|
|
1664
|
+
* @returns {{ suggestions: Array, parseFailed: boolean }}
|
|
1665
|
+
*/
|
|
1666
|
+
parseResponseWithMeta(response, level, previousSuggestions = []) {
|
|
1626
1667
|
const levelPrefix = `[Level ${level}]`;
|
|
1627
1668
|
|
|
1628
1669
|
// Separate previous suggestions into line-level and file-level for deduplication
|
|
1629
1670
|
const previousLineSuggestions = previousSuggestions.filter(s => !s.is_file_level);
|
|
1630
1671
|
const previousFileLevelSuggestions = previousSuggestions.filter(s => s.is_file_level);
|
|
1631
1672
|
|
|
1632
|
-
//
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1673
|
+
// Already-parsed branch — the common path: providers resolve parsed schema
|
|
1674
|
+
// objects directly and only fall back to `{ raw, parsed: false }` (which
|
|
1675
|
+
// never carries a string summary) when their own parsing fails. Suggestion
|
|
1676
|
+
// arrays are authoritative regardless of any `raw` payload; a summary alone
|
|
1677
|
+
// is accepted here only when there is no `raw` payload to try first, so a
|
|
1678
|
+
// hypothetical `{ summary, raw }` shape with extractable suggestions in
|
|
1679
|
+
// `raw` does not lose them (final summary-only acceptance is below).
|
|
1680
|
+
// validateSuggestions requires real arrays, so default the missing ones —
|
|
1681
|
+
// a summary-only object has neither.
|
|
1682
|
+
if (Array.isArray(response.suggestions) || Array.isArray(response.fileLevelSuggestions) ||
|
|
1683
|
+
(hasSchemaKeys(response) && !response.raw)) {
|
|
1684
|
+
const lineSuggestions = this.validateSuggestions(response.suggestions || [], previousLineSuggestions);
|
|
1685
|
+
const fileLevelSuggestions = this.validateFileLevelSuggestions(
|
|
1686
|
+
response.fileLevelSuggestions || [], previousFileLevelSuggestions
|
|
1687
|
+
);
|
|
1688
|
+
return { suggestions: [...lineSuggestions, ...fileLevelSuggestions], parseFailed: false };
|
|
1639
1689
|
}
|
|
1640
1690
|
|
|
1641
|
-
// If response is raw text, try multiple extraction strategies
|
|
1691
|
+
// If response is raw text, try multiple extraction strategies. Extraction can
|
|
1692
|
+
// latch onto unrelated JSON fragments in prose, so only JSON carrying one of
|
|
1693
|
+
// our schema keys counts as parsed — a summary-only object is a legitimate
|
|
1694
|
+
// zero-finding response (e.g. "all findings duplicated existing comments").
|
|
1642
1695
|
if (response.raw) {
|
|
1643
1696
|
const extracted = extractJSON(response.raw, level);
|
|
1644
|
-
if (extracted.success &&
|
|
1645
|
-
const lineSuggestions = this.validateSuggestions(extracted.data.suggestions, previousLineSuggestions);
|
|
1697
|
+
if (extracted.success && hasSchemaKeys(extracted.data)) {
|
|
1698
|
+
const lineSuggestions = this.validateSuggestions(extracted.data.suggestions || [], previousLineSuggestions);
|
|
1646
1699
|
const fileLevelSuggestions = extracted.data.fileLevelSuggestions
|
|
1647
1700
|
? this.validateFileLevelSuggestions(extracted.data.fileLevelSuggestions, previousFileLevelSuggestions)
|
|
1648
1701
|
: [];
|
|
1649
|
-
return [...lineSuggestions, ...fileLevelSuggestions];
|
|
1702
|
+
return { suggestions: [...lineSuggestions, ...fileLevelSuggestions], parseFailed: false };
|
|
1703
|
+
} else if (extracted.success) {
|
|
1704
|
+
logger.warn(`${levelPrefix} Extracted JSON carried none of the expected schema keys (suggestions/fileLevelSuggestions/summary)`);
|
|
1705
|
+
logger.info(`${levelPrefix} Raw response length: ${response.raw.length} characters`);
|
|
1706
|
+
logger.info(`${levelPrefix} Raw response preview: ${response.raw.substring(0, 500)}...`);
|
|
1650
1707
|
} else {
|
|
1651
1708
|
logger.warn(`${levelPrefix} JSON extraction failed: ${extracted.error}`);
|
|
1652
1709
|
logger.info(`${levelPrefix} Raw response length: ${response.raw.length} characters`);
|
|
@@ -1654,9 +1711,17 @@ If you are unsure, use "NEW" - it is correct for the vast majority of suggestion
|
|
|
1654
1711
|
}
|
|
1655
1712
|
}
|
|
1656
1713
|
|
|
1714
|
+
// A string `summary` alone is a valid zero-finding result — reached only
|
|
1715
|
+
// for a `{ summary, raw }` response whose raw extraction yielded nothing
|
|
1716
|
+
// better (arrays would have been accepted above).
|
|
1717
|
+
if (hasSchemaKeys(response)) {
|
|
1718
|
+
logger.info(`${levelPrefix} Accepting summary-only response as a zero-finding result`);
|
|
1719
|
+
return { suggestions: [], parseFailed: false };
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1657
1722
|
// Fallback to empty array
|
|
1658
1723
|
logger.warn(`${levelPrefix} No valid suggestions found in response`);
|
|
1659
|
-
return [];
|
|
1724
|
+
return { suggestions: [], parseFailed: true };
|
|
1660
1725
|
}
|
|
1661
1726
|
|
|
1662
1727
|
/**
|
|
@@ -2161,6 +2226,8 @@ If you are unsure, use "NEW" - it is correct for the vast majority of suggestion
|
|
|
2161
2226
|
});
|
|
2162
2227
|
|
|
2163
2228
|
// Parse and validate the response
|
|
2229
|
+
// A parse failure here still reports Level 2 success with zero suggestions;
|
|
2230
|
+
// honest per-level parse-failure reporting is a known follow-up to issue #560.
|
|
2164
2231
|
updateProgress('Processing AI results');
|
|
2165
2232
|
let suggestions = this.parseResponse(response, 2);
|
|
2166
2233
|
logger.success(`${lp}Parsed ${suggestions.length} valid Level 2 suggestions`);
|
|
@@ -2275,6 +2342,8 @@ If you are unsure, use "NEW" - it is correct for the vast majority of suggestion
|
|
|
2275
2342
|
});
|
|
2276
2343
|
|
|
2277
2344
|
// Parse and validate the response
|
|
2345
|
+
// A parse failure here still reports Level 3 success with zero suggestions;
|
|
2346
|
+
// honest per-level parse-failure reporting is a known follow-up to issue #560.
|
|
2278
2347
|
updateProgress('Processing codebase context results');
|
|
2279
2348
|
let suggestions = this.parseResponse(response, 3);
|
|
2280
2349
|
logger.success(`${lp}Parsed ${suggestions.length} valid Level 3 suggestions`);
|
|
@@ -2782,7 +2851,9 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
2782
2851
|
* @param {Object} [options.excludePrevious] - { github: bool, feedback: bool } for dedup
|
|
2783
2852
|
* @param {Object} [options.dedupContext] - { owner, repo, pullNumber, reviewId, serverPort }
|
|
2784
2853
|
* @param {Object} [options.githubClient] - GitHubClient used to pre-fetch existing PR review comments for dedup
|
|
2785
|
-
* @returns {Promise<Array
|
|
2854
|
+
* @returns {Promise<{suggestions: Array, summary: string, consolidationFailed?: boolean}>}
|
|
2855
|
+
* Consolidation result. `consolidationFailed: true` means the suggestions
|
|
2856
|
+
* array is the raw union of all levels rather than a curated set.
|
|
2786
2857
|
*/
|
|
2787
2858
|
async orchestrateWithAI(allSuggestions, prMetadata, customInstructions = null, worktreePath = null, options = {}) {
|
|
2788
2859
|
const { analysisId, tier = 'balanced', progressCallback, providerOverride, modelOverride, timeout = 600000, logPrefix: lp = '', reviewerNum, excludePrevious, dedupContext, githubClient } = options;
|
|
@@ -2842,7 +2913,7 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
2842
2913
|
});
|
|
2843
2914
|
|
|
2844
2915
|
// Parse the orchestrated response
|
|
2845
|
-
const orchestratedSuggestions = this.
|
|
2916
|
+
const { suggestions: orchestratedSuggestions, parseFailed } = this.parseResponseWithMeta(response, 'orchestration');
|
|
2846
2917
|
|
|
2847
2918
|
// Debug: If consolidation returned 0 suggestions but there was input, log for investigation
|
|
2848
2919
|
const inputLevel1Count = allSuggestions.level1?.length || 0;
|
|
@@ -2866,6 +2937,17 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
2866
2937
|
}
|
|
2867
2938
|
}
|
|
2868
2939
|
|
|
2940
|
+
// A response with no parseable suggestions (nothing recognizable as our
|
|
2941
|
+
// response schema), when the levels produced suggestions, means every
|
|
2942
|
+
// input suggestion would be silently dropped. Route that through the
|
|
2943
|
+
// fallback below instead of reporting success with zero suggestions
|
|
2944
|
+
// (issue #560). A parseable-but-empty `suggestions: []` is left alone —
|
|
2945
|
+
// the consolidator may legitimately curate everything away (e.g. dedup
|
|
2946
|
+
// against previously posted comments).
|
|
2947
|
+
if (parseFailed && hadInputSuggestions) {
|
|
2948
|
+
throw new Error('Consolidation response could not be parsed; falling back to unconsolidated suggestions');
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2869
2951
|
// Extract summary from the orchestration response
|
|
2870
2952
|
let summary = `Analyzed PR with ${orchestratedSuggestions.length} curated suggestions`;
|
|
2871
2953
|
if (response.summary) {
|
|
@@ -2883,8 +2965,11 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
2883
2965
|
suggestions: orchestratedSuggestions,
|
|
2884
2966
|
summary: summary
|
|
2885
2967
|
};
|
|
2886
|
-
|
|
2968
|
+
|
|
2887
2969
|
} catch (error) {
|
|
2970
|
+
// Cancellation is not a consolidation failure — propagate so the run is
|
|
2971
|
+
// recorded as cancelled instead of consolidation 'failed'
|
|
2972
|
+
if (error.isCancellation) throw error;
|
|
2888
2973
|
logger.warn(`${lp}[Consolidation] Cross-level consolidation failed: ${error.message}`);
|
|
2889
2974
|
logger.warn(`${lp}[Consolidation] Falling back to storing all original suggestions`);
|
|
2890
2975
|
|
|
@@ -2911,7 +2996,8 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
2911
2996
|
|
|
2912
2997
|
return {
|
|
2913
2998
|
suggestions: fallbackSuggestions,
|
|
2914
|
-
summary: `Analysis complete (consolidation failed): ${fallbackSuggestions.length} suggestions from all analysis levels
|
|
2999
|
+
summary: `Analysis complete (consolidation failed): ${fallbackSuggestions.length} suggestions from all analysis levels`,
|
|
3000
|
+
consolidationFailed: true
|
|
2915
3001
|
};
|
|
2916
3002
|
}
|
|
2917
3003
|
}
|
|
@@ -3372,6 +3458,10 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3372
3458
|
logger.info('[ReviewerCouncil] Single reviewer result — skipping consolidation');
|
|
3373
3459
|
const singleResult = successfulVoices[0].result;
|
|
3374
3460
|
|
|
3461
|
+
// Preserve the surviving reviewer's own outcomes (e.g. a failed intra-run
|
|
3462
|
+
// consolidation) — only cross-voice consolidation was skipped here
|
|
3463
|
+
const singleLevelOutcomes = singleResult.levelOutcomes || { consolidation: 'skipped' };
|
|
3464
|
+
|
|
3375
3465
|
const finalSuggestions = this.validateAndFinalizeSuggestions(
|
|
3376
3466
|
singleResult.suggestions, fileLineCountMap, validFiles
|
|
3377
3467
|
);
|
|
@@ -3383,7 +3473,7 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3383
3473
|
summary: singleResult.summary,
|
|
3384
3474
|
totalSuggestions: finalSuggestions.length,
|
|
3385
3475
|
filesAnalyzed: validFiles.length,
|
|
3386
|
-
levelOutcomes:
|
|
3476
|
+
levelOutcomes: singleLevelOutcomes
|
|
3387
3477
|
});
|
|
3388
3478
|
} catch (err) {
|
|
3389
3479
|
logger.warn(`[ReviewerCouncil] Failed to update parent run: ${err.message}`);
|
|
@@ -3393,7 +3483,7 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3393
3483
|
runId: parentRunId,
|
|
3394
3484
|
suggestions: finalSuggestions,
|
|
3395
3485
|
summary: singleResult.summary || `Review council complete: ${finalSuggestions.length} suggestions`,
|
|
3396
|
-
levelOutcomes:
|
|
3486
|
+
levelOutcomes: singleLevelOutcomes
|
|
3397
3487
|
};
|
|
3398
3488
|
}
|
|
3399
3489
|
|
|
@@ -3471,6 +3561,17 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3471
3561
|
|
|
3472
3562
|
logger.success(`[ReviewerCouncil] Analysis complete: ${finalSuggestions.length} consolidated suggestions`);
|
|
3473
3563
|
|
|
3564
|
+
// Terminal orchestration event must be voiceId-less: events with a
|
|
3565
|
+
// voiceId only update levels[4].voices, never the aggregate status
|
|
3566
|
+
if (progressCallback) {
|
|
3567
|
+
progressCallback({
|
|
3568
|
+
status: 'completed',
|
|
3569
|
+
progress: 'Cross-reviewer consolidation complete',
|
|
3570
|
+
level: 'orchestration',
|
|
3571
|
+
voiceCentric: true
|
|
3572
|
+
});
|
|
3573
|
+
}
|
|
3574
|
+
|
|
3474
3575
|
return {
|
|
3475
3576
|
runId: parentRunId,
|
|
3476
3577
|
suggestions: finalSuggestions,
|
|
@@ -3478,8 +3579,23 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3478
3579
|
levelOutcomes: { consolidation: 'success' }
|
|
3479
3580
|
};
|
|
3480
3581
|
} catch (error) {
|
|
3582
|
+
// Cancellation is not a consolidation failure — propagate so the run is
|
|
3583
|
+
// recorded as cancelled instead of consolidation 'failed'
|
|
3584
|
+
if (error.isCancellation) throw error;
|
|
3481
3585
|
logger.error(`[ReviewerCouncil] Cross-reviewer consolidation failed: ${error.message}`);
|
|
3482
3586
|
|
|
3587
|
+
// Surface the failure live — without a terminal voiceId-less event,
|
|
3588
|
+
// levels[4] stays 'running' and the completion handler would show
|
|
3589
|
+
// consolidation as completed while the run records it as failed
|
|
3590
|
+
if (progressCallback) {
|
|
3591
|
+
progressCallback({
|
|
3592
|
+
status: 'failed',
|
|
3593
|
+
progress: 'Consolidation failed — showing unconsolidated results',
|
|
3594
|
+
level: 'orchestration',
|
|
3595
|
+
voiceCentric: true
|
|
3596
|
+
});
|
|
3597
|
+
}
|
|
3598
|
+
|
|
3483
3599
|
// Fallback: use all voice suggestions combined
|
|
3484
3600
|
const fallbackSuggestions = this.validateAndFinalizeSuggestions(
|
|
3485
3601
|
[...allVoiceSuggestions, ...allVoiceFileLevelSuggestions], fileLineCountMap, validFiles
|
|
@@ -3728,6 +3844,10 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3728
3844
|
}
|
|
3729
3845
|
|
|
3730
3846
|
// Pass 1: Intra-level consolidation (for levels with >1 reviewer)
|
|
3847
|
+
// Track Pass 1 fallbacks so the final outcome reports them as a failed
|
|
3848
|
+
// consolidation even when Pass 2 succeeds (the final set then contains
|
|
3849
|
+
// raw, unconsolidated suggestions for the affected level)
|
|
3850
|
+
let intraLevelConsolidationFailed = false;
|
|
3731
3851
|
const consolidatedPerLevel = {};
|
|
3732
3852
|
for (const [levelStr, suggestions] of Object.entries(levelSuggestions)) {
|
|
3733
3853
|
const level = parseInt(levelStr);
|
|
@@ -3764,7 +3884,11 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3764
3884
|
progressCallback({ level: `consolidation-L${level}`, status: 'completed', progress: `Level ${level} consolidation complete` });
|
|
3765
3885
|
}
|
|
3766
3886
|
} catch (error) {
|
|
3887
|
+
// Cancellation is not a consolidation failure — propagate so the run
|
|
3888
|
+
// is recorded as cancelled instead of consolidation 'failed'
|
|
3889
|
+
if (error.isCancellation) throw error;
|
|
3767
3890
|
logger.warn(`[Council] Intra-level consolidation failed for Level ${level}: ${error.message}`);
|
|
3891
|
+
intraLevelConsolidationFailed = true;
|
|
3768
3892
|
consolidatedPerLevel[level] = suggestions; // Fallback to raw
|
|
3769
3893
|
// Report intra-level consolidation step as failed
|
|
3770
3894
|
if (progressCallback) {
|
|
@@ -3791,9 +3915,18 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3791
3915
|
{ analysisId, tier: orchTier, progressCallback, providerOverride: orchProvider, modelOverride: orchModel, timeout: orchConfig.timeout || 600000, excludePrevious, dedupContext, githubClient }
|
|
3792
3916
|
);
|
|
3793
3917
|
|
|
3794
|
-
//
|
|
3918
|
+
// orchestrateWithAI degrades to the raw union of level suggestions when
|
|
3919
|
+
// consolidation fails internally, and a Pass 1 fallback means raw
|
|
3920
|
+
// suggestions leaked into the final set — report either honestly
|
|
3921
|
+
// instead of 'success'
|
|
3922
|
+
const consolidationOutcome = (intraLevelConsolidationFailed || orchestrationResult.consolidationFailed)
|
|
3923
|
+
? 'failed' : 'success';
|
|
3924
|
+
|
|
3925
|
+
// Report cross-level orchestration step outcome
|
|
3795
3926
|
if (progressCallback) {
|
|
3796
|
-
progressCallback(
|
|
3927
|
+
progressCallback(orchestrationResult.consolidationFailed
|
|
3928
|
+
? { level: 'orchestration', status: 'failed', progress: 'Cross-level consolidation failed' }
|
|
3929
|
+
: { level: 'orchestration', status: 'completed', progress: 'Cross-level consolidation complete' });
|
|
3797
3930
|
}
|
|
3798
3931
|
|
|
3799
3932
|
const finalSuggestions = this.validateAndFinalizeSuggestions(
|
|
@@ -3809,9 +3942,13 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3809
3942
|
runId,
|
|
3810
3943
|
suggestions: finalSuggestions,
|
|
3811
3944
|
summary: orchestrationResult.summary,
|
|
3812
|
-
|
|
3945
|
+
...(consolidationOutcome === 'failed' ? { orchestrationFailed: true } : {}),
|
|
3946
|
+
levelOutcomes: { consolidation: consolidationOutcome }
|
|
3813
3947
|
};
|
|
3814
3948
|
} catch (error) {
|
|
3949
|
+
// Cancellation is not a consolidation failure — propagate so the run is
|
|
3950
|
+
// recorded as cancelled instead of consolidation 'failed'
|
|
3951
|
+
if (error.isCancellation) throw error;
|
|
3815
3952
|
logger.error(`[Council] Cross-level consolidation failed: ${error.message}`);
|
|
3816
3953
|
|
|
3817
3954
|
// Report cross-level orchestration step as failed
|
|
@@ -3883,6 +4020,8 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3883
4020
|
});
|
|
3884
4021
|
|
|
3885
4022
|
// Parse response
|
|
4023
|
+
// A parse failure here still reports the voice as completed with zero
|
|
4024
|
+
// suggestions; honest per-voice reporting is a known follow-up to issue #560.
|
|
3886
4025
|
const suggestions = this.parseResponse(response, level);
|
|
3887
4026
|
logger.success(`[Council] ${displayLabel}: parsed ${suggestions.length} suggestions`);
|
|
3888
4027
|
|
|
@@ -3974,7 +4113,19 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
3974
4113
|
} : undefined
|
|
3975
4114
|
});
|
|
3976
4115
|
|
|
3977
|
-
|
|
4116
|
+
// Use the disambiguated identifier so parse logs don't read as the
|
|
4117
|
+
// Level N reviewer itself (matches the provider call's level above)
|
|
4118
|
+
const { suggestions: consolidated, parseFailed } = this.parseResponseWithMeta(response, `consolidation-L${level}`);
|
|
4119
|
+
|
|
4120
|
+
// A consolidation response with no parseable suggestions (nothing
|
|
4121
|
+
// recognizable as our response schema) would silently drop every reviewer
|
|
4122
|
+
// suggestion for this level (issue #560). Throw so the caller falls back
|
|
4123
|
+
// to the raw per-reviewer suggestions instead.
|
|
4124
|
+
if (parseFailed && suggestionCount > 0) {
|
|
4125
|
+
throw new Error(`Level ${level} consolidation response could not be parsed (${suggestionCount} reviewer suggestions at risk); falling back to raw suggestions`);
|
|
4126
|
+
}
|
|
4127
|
+
|
|
4128
|
+
return consolidated;
|
|
3978
4129
|
}
|
|
3979
4130
|
|
|
3980
4131
|
/**
|
|
@@ -4161,7 +4312,20 @@ File-level suggestions should NOT have a line number. They apply to the entire f
|
|
|
4161
4312
|
} : undefined
|
|
4162
4313
|
});
|
|
4163
4314
|
|
|
4164
|
-
const suggestions = this.
|
|
4315
|
+
const { suggestions, parseFailed } = this.parseResponseWithMeta(response, 'consolidation');
|
|
4316
|
+
|
|
4317
|
+
// If the consolidation response carried no parseable suggestions (nothing
|
|
4318
|
+
// recognizable as our response schema) while the voices produced
|
|
4319
|
+
// suggestions, every voice suggestion would be silently dropped and the
|
|
4320
|
+
// run would still report success (issue #560). Throw so
|
|
4321
|
+
// the caller's fallback path stores the raw voice suggestions and records
|
|
4322
|
+
// the consolidation outcome as 'failed'. A parseable-but-empty
|
|
4323
|
+
// `suggestions: []` is a legitimate outcome (e.g. dedup curated everything
|
|
4324
|
+
// away) and is not treated as a failure.
|
|
4325
|
+
const inputSuggestionCount = voiceReviews.reduce((sum, v) => sum + (v.suggestionCount || 0), 0);
|
|
4326
|
+
if (parseFailed && inputSuggestionCount > 0) {
|
|
4327
|
+
throw new Error(`Cross-voice consolidation response could not be parsed (${inputSuggestionCount} voice suggestions at risk); falling back to unconsolidated suggestions`);
|
|
4328
|
+
}
|
|
4165
4329
|
|
|
4166
4330
|
// Extract summary from response, falling back to raw JSON extraction (same pattern as orchestrateWithAI)
|
|
4167
4331
|
let summary;
|
package/src/routes/analyses.js
CHANGED
|
@@ -31,7 +31,8 @@ const {
|
|
|
31
31
|
localReviewDiffs,
|
|
32
32
|
broadcastProgress,
|
|
33
33
|
killProcesses,
|
|
34
|
-
createProgressCallback
|
|
34
|
+
createProgressCallback,
|
|
35
|
+
finalizeConsolidationLevel
|
|
35
36
|
} = require('./shared');
|
|
36
37
|
const { generateScopedDiff, computeScopedDigest, getCurrentBranch } = require('../local-review');
|
|
37
38
|
const { reviewScope } = require('../local-scope');
|
|
@@ -675,7 +676,10 @@ async function launchCouncilAnalysis(db, modeContext, councilConfig, councilId,
|
|
|
675
676
|
suggestionsCount: result.suggestions.length,
|
|
676
677
|
levels: {
|
|
677
678
|
...currentStatus.levels,
|
|
678
|
-
|
|
679
|
+
// Derive the terminal consolidation state from the authoritative
|
|
680
|
+
// result — the run finishing does not mean consolidation succeeded,
|
|
681
|
+
// and some council paths never emit a terminal orchestration event
|
|
682
|
+
4: finalizeConsolidationLevel(result, currentStatus.levels?.[4])
|
|
679
683
|
}
|
|
680
684
|
};
|
|
681
685
|
for (const levelKey of ['1', '2', '3', 'exec']) {
|
package/src/routes/local.js
CHANGED
|
@@ -54,6 +54,7 @@ const {
|
|
|
54
54
|
broadcastProgress,
|
|
55
55
|
CancellationError,
|
|
56
56
|
createProgressCallback,
|
|
57
|
+
finalizeConsolidationLevel,
|
|
57
58
|
parseEnabledLevels,
|
|
58
59
|
registerProcess: registerProcessForCancellation
|
|
59
60
|
} = require('./shared');
|
|
@@ -1657,11 +1658,11 @@ router.post('/api/local/:reviewId/analyses', async (req, res) => {
|
|
|
1657
1658
|
};
|
|
1658
1659
|
}
|
|
1659
1660
|
|
|
1660
|
-
//
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1661
|
+
// Derive the terminal consolidation (level 4) state from the
|
|
1662
|
+
// authoritative result — the run finishing does not mean the
|
|
1663
|
+
// consolidation step succeeded, and some council paths never emit a
|
|
1664
|
+
// terminal orchestration progress event
|
|
1665
|
+
currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
|
|
1665
1666
|
|
|
1666
1667
|
const completedStatus = {
|
|
1667
1668
|
...currentStatus,
|
package/src/routes/mcp.js
CHANGED
|
@@ -22,7 +22,8 @@ const {
|
|
|
22
22
|
localReviewDiffs,
|
|
23
23
|
determineCompletionInfo,
|
|
24
24
|
broadcastProgress,
|
|
25
|
-
createProgressCallback
|
|
25
|
+
createProgressCallback,
|
|
26
|
+
finalizeConsolidationLevel
|
|
26
27
|
} = require('./shared');
|
|
27
28
|
const { safeParseJson } = require('../utils/safe-parse-json');
|
|
28
29
|
const { resolveLoadSkills, resolveHostBinding } = require('../config');
|
|
@@ -56,7 +57,9 @@ async function handleAnalysisCompletion(analysisId, runId, result, savePersisten
|
|
|
56
57
|
currentStatus.levels[i] = { status: 'completed', progress: `Level ${i} complete` };
|
|
57
58
|
}
|
|
58
59
|
}
|
|
59
|
-
|
|
60
|
+
// Derive the terminal consolidation state from the authoritative result —
|
|
61
|
+
// the run finishing does not mean the consolidation step succeeded
|
|
62
|
+
currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
|
|
60
63
|
|
|
61
64
|
const completedStatus = {
|
|
62
65
|
...currentStatus,
|
package/src/routes/pr.js
CHANGED
|
@@ -47,6 +47,7 @@ const {
|
|
|
47
47
|
determineCompletionInfo,
|
|
48
48
|
broadcastProgress,
|
|
49
49
|
createProgressCallback,
|
|
50
|
+
finalizeConsolidationLevel,
|
|
50
51
|
parseEnabledLevels,
|
|
51
52
|
registerProcess: registerProcessForCancellation
|
|
52
53
|
} = require('./shared');
|
|
@@ -2481,10 +2482,11 @@ router.post('/api/pr/:owner/:repo/:number/analyses', async (req, res) => {
|
|
|
2481
2482
|
};
|
|
2482
2483
|
}
|
|
2483
2484
|
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2485
|
+
// Derive the terminal consolidation (level 4) state from the
|
|
2486
|
+
// authoritative result — the run finishing does not mean the
|
|
2487
|
+
// consolidation step succeeded, and some council paths never emit a
|
|
2488
|
+
// terminal orchestration progress event
|
|
2489
|
+
currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
|
|
2488
2490
|
|
|
2489
2491
|
const completedStatus = {
|
|
2490
2492
|
...currentStatus,
|
package/src/routes/shared.js
CHANGED
|
@@ -521,6 +521,32 @@ function createProgressCallback(analysisId) {
|
|
|
521
521
|
};
|
|
522
522
|
}
|
|
523
523
|
|
|
524
|
+
/**
|
|
525
|
+
* Build the terminal level-4 (consolidation) progress state for a completed
|
|
526
|
+
* analysis. The outcome is driven by the authoritative analyzer result rather
|
|
527
|
+
* than the transient progress state alone — some council paths never emit a
|
|
528
|
+
* terminal voiceId-less orchestration event, so levels[4] can still read
|
|
529
|
+
* 'running' even when consolidation failed (issue #560).
|
|
530
|
+
*
|
|
531
|
+
* @param {Object} result - Analyzer result (may carry levelOutcomes / orchestrationFailed)
|
|
532
|
+
* @param {Object} [level4] - Current levels[4] progress state, if any
|
|
533
|
+
* @returns {Object} Terminal level-4 state (preserves existing steps/voices maps)
|
|
534
|
+
*/
|
|
535
|
+
function finalizeConsolidationLevel(result, level4) {
|
|
536
|
+
const consolidationFailed =
|
|
537
|
+
result?.levelOutcomes?.consolidation === 'failed' ||
|
|
538
|
+
result?.orchestrationFailed === true ||
|
|
539
|
+
level4?.status === 'failed';
|
|
540
|
+
return {
|
|
541
|
+
// Spread keeps the `steps` / `voices` maps a plain
|
|
542
|
+
// `{ status, progress }` replacement would silently drop
|
|
543
|
+
...level4,
|
|
544
|
+
...(consolidationFailed
|
|
545
|
+
? { status: 'failed', progress: 'Consolidation failed — showing unconsolidated results' }
|
|
546
|
+
: { status: 'completed', progress: 'Results finalized' })
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
524
550
|
/**
|
|
525
551
|
* Parse enabledLevels from a request body into a normalized { 1: bool, 2: bool, 3: bool } object.
|
|
526
552
|
*
|
|
@@ -570,5 +596,6 @@ module.exports = {
|
|
|
570
596
|
killProcesses,
|
|
571
597
|
isAnalysisCancelled,
|
|
572
598
|
createProgressCallback,
|
|
599
|
+
finalizeConsolidationLevel,
|
|
573
600
|
parseEnabledLevels
|
|
574
601
|
};
|
|
@@ -43,6 +43,7 @@ const {
|
|
|
43
43
|
determineCompletionInfo,
|
|
44
44
|
broadcastProgress,
|
|
45
45
|
createProgressCallback,
|
|
46
|
+
finalizeConsolidationLevel,
|
|
46
47
|
parseEnabledLevels,
|
|
47
48
|
registerProcess: registerProcessForCancellation,
|
|
48
49
|
killProcesses
|
|
@@ -586,7 +587,9 @@ async function launchStackSingleAnalysis(deps, db, config, {
|
|
|
586
587
|
for (let lvl = 1; lvl <= completionInfo.completedLevel; lvl++) {
|
|
587
588
|
currentStatus.levels[lvl] = { status: 'completed', progress: `Level ${lvl} complete` };
|
|
588
589
|
}
|
|
589
|
-
|
|
590
|
+
// Derive the terminal consolidation state from the authoritative result —
|
|
591
|
+
// the run finishing does not mean the consolidation step succeeded
|
|
592
|
+
currentStatus.levels[4] = finalizeConsolidationLevel(result, currentStatus.levels?.[4]);
|
|
590
593
|
const completedStatus = {
|
|
591
594
|
...currentStatus,
|
|
592
595
|
status: 'completed',
|
|
@@ -2,40 +2,114 @@
|
|
|
2
2
|
const logger = require('./logger');
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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
|
|
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}
|
|
17
|
-
* @
|
|
18
|
-
*
|
|
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
|
|
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 =
|
|
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 =
|
|
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
|
|
125
|
+
// Strategy 2: Try the entire text as JSON (fast path for clean responses)
|
|
52
126
|
() => {
|
|
53
|
-
return JSON.parse(
|
|
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
|
|
131
|
+
// Works when the text is just JSON or has minimal wrapping
|
|
58
132
|
() => {
|
|
59
|
-
const firstBrace =
|
|
60
|
-
const lastBrace =
|
|
133
|
+
const firstBrace = text.indexOf('{');
|
|
134
|
+
const lastBrace = text.lastIndexOf('}');
|
|
61
135
|
if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
|
|
62
|
-
return JSON.parse(
|
|
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 =
|
|
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 =
|
|
161
|
+
const lastBrace = text.lastIndexOf('}');
|
|
88
162
|
if (lastBrace > startIdx) {
|
|
89
|
-
const candidate =
|
|
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 =
|
|
179
|
+
const lastBrace = text.lastIndexOf('}');
|
|
106
180
|
|
|
107
|
-
while (searchFrom <
|
|
108
|
-
const braceIdx =
|
|
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
|
|
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 =
|
|
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 =
|
|
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 <
|
|
144
|
-
const ch =
|
|
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(
|
|
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
|
-
|
|
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
|
|
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 };
|