peaks-loop 4.1.10 → 4.1.11

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 (30) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +43 -0
  3. package/dist/cli/commands/code-review-commands.d.ts +1 -1
  4. package/dist/cli/commands/code-review-commands.js +23 -37
  5. package/dist/cli/commands/code-review-ocr-delegate-record.d.ts +3 -0
  6. package/dist/cli/commands/code-review-ocr-delegate-record.js +73 -0
  7. package/dist/cli/commands/code-review-ocr-delegate.d.ts +12 -0
  8. package/dist/cli/commands/code-review-ocr-delegate.js +140 -0
  9. package/dist/cli/commands/code-review-run-ocr-18.d.ts +11 -0
  10. package/dist/cli/commands/code-review-run-ocr-18.js +127 -0
  11. package/dist/services/lint/detect-ocr-18.js +1 -1
  12. package/dist/services/lint/ocr-18-acquire.d.ts +1 -1
  13. package/dist/services/lint/ocr-18-acquire.js +2 -2
  14. package/dist/services/lint/ocr-18-allowlist.d.ts +30 -0
  15. package/dist/services/lint/ocr-18-allowlist.js +165 -0
  16. package/dist/services/lint/ocr-18-delegate-packet.d.ts +84 -0
  17. package/dist/services/lint/ocr-18-delegate-packet.js +175 -0
  18. package/dist/services/lint/ocr-18-delegate-payload.d.ts +67 -0
  19. package/dist/services/lint/ocr-18-delegate-payload.js +208 -0
  20. package/dist/services/lint/ocr-18-delegate-record.d.ts +42 -0
  21. package/dist/services/lint/ocr-18-delegate-record.js +223 -0
  22. package/dist/services/lint/ocr-18-language-routing.d.ts +96 -0
  23. package/dist/services/lint/ocr-18-language-routing.js +148 -0
  24. package/dist/services/lint/ocr-18-multi.d.ts +54 -0
  25. package/dist/services/lint/ocr-18-multi.js +184 -0
  26. package/dist/services/lint/ocr-multilang-adapter.d.ts +45 -7
  27. package/dist/services/lint/ocr-multilang-adapter.js +133 -94
  28. package/package.json +10 -10
  29. package/skills/bee/peaks-rd/SKILL.md +32 -0
  30. package/skills/bee/peaks-rd/references/ocr-multilang-1.8.md +314 -111
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Vendored snapshot of the extension allowlist compiled into the PINNED OCR
3
+ * runtime, plus the explicit list of allowlisted formats this project does not
4
+ * route to a language.
5
+ *
6
+ * Source: `alibaba/open-code-review`, `internal/config/allowlist/supported_file_types.json`
7
+ * at tag `v1.13.1` (the version `OCR_18_PACKAGE` pins) — 115 entries. This is a
8
+ * SNAPSHOT, not a live binding: the binary embeds its own copy at build time, so
9
+ * a pin bump must update this file together with `OCR_18_PACKAGE`. The partition
10
+ * test in `tests/unit/services/lint/ocr-multilang-adapter.test.ts` reddens when
11
+ * the routing table and `OCR_18_EXCLUDED_EXTENSIONS` stop covering it exactly,
12
+ * which is how an upstream addition surfaces instead of being silently ignored.
13
+ *
14
+ * Empirical control (2026-10-20, ocr 1.13.1 on win32-x64): a scratch repository
15
+ * holding one file per extension was run through `ocr review --preview`. Every
16
+ * extension below was listed under "Will review"; `.mts`, `.cts` and `.glsl`
17
+ * were listed under "Excluded from review (unsupported_ext)". `.glsl` is in the
18
+ * HEAD allowlist but not in v1.13.1, which is why the tag — not HEAD — is the
19
+ * source here.
20
+ */
21
+ export const OCR_18_ALLOWLIST_V1_13_1 = [
22
+ '.java',
23
+ '.kt',
24
+ '.kts',
25
+ '.scala',
26
+ '.groovy',
27
+ '.py',
28
+ '.pyi',
29
+ '.js',
30
+ '.jsx',
31
+ '.ts',
32
+ '.tsx',
33
+ '.mjs',
34
+ '.cjs',
35
+ '.c',
36
+ '.h',
37
+ '.cpp',
38
+ '.cc',
39
+ '.cxx',
40
+ '.hpp',
41
+ '.hxx',
42
+ '.cs',
43
+ '.vb',
44
+ '.fs',
45
+ '.fsi',
46
+ '.fsx',
47
+ '.go',
48
+ '.rs',
49
+ '.rb',
50
+ '.rake',
51
+ '.gemspec',
52
+ '.php',
53
+ '.phtml',
54
+ '.swift',
55
+ '.m',
56
+ '.mm',
57
+ '.sh',
58
+ '.bash',
59
+ '.zsh',
60
+ '.fish',
61
+ '.ps1',
62
+ '.sql',
63
+ '.css',
64
+ '.scss',
65
+ '.sass',
66
+ '.less',
67
+ '.html',
68
+ '.htm',
69
+ '.ftl',
70
+ '.ftlh',
71
+ '.ftlx',
72
+ '.hbs',
73
+ '.mustache',
74
+ '.jinja2',
75
+ '.j2',
76
+ '.pug',
77
+ '.astro',
78
+ '.vue',
79
+ '.ipynb',
80
+ '.svelte',
81
+ '.xml',
82
+ '.yaml',
83
+ '.yml',
84
+ '.json',
85
+ '.toml',
86
+ '.ini',
87
+ '.env',
88
+ '.gradle',
89
+ '.cmake',
90
+ '.r',
91
+ '.lua',
92
+ '.pl',
93
+ '.pm',
94
+ '.ex',
95
+ '.exs',
96
+ '.erl',
97
+ '.hrl',
98
+ '.ets',
99
+ '.json5',
100
+ '.dart',
101
+ '.tf',
102
+ '.graphql',
103
+ '.gql',
104
+ '.prisma',
105
+ '.jl',
106
+ '.hcl',
107
+ '.tfvars',
108
+ '.bicep',
109
+ '.proto',
110
+ '.nix',
111
+ '.hs',
112
+ '.lhs',
113
+ '.nim',
114
+ '.nims',
115
+ '.nimble',
116
+ '.elm',
117
+ '.properties',
118
+ '.po',
119
+ '.pot',
120
+ '.jsonnet',
121
+ '.libsonnet',
122
+ '.zig',
123
+ '.thrift',
124
+ '.capnp',
125
+ '.ml',
126
+ '.mli',
127
+ '.re',
128
+ '.rei',
129
+ '.v',
130
+ '.sv',
131
+ '.vh',
132
+ '.vhd',
133
+ '.vhdl',
134
+ '.sol',
135
+ '.vy',
136
+ '.rego'
137
+ ];
138
+ /**
139
+ * Allowlisted formats this project deliberately does NOT route to a language.
140
+ *
141
+ * The PRD routes source languages only: markup, stylesheets, data/config and
142
+ * notebook containers carry no source semantics to review per language. They
143
+ * are still reviewed by the CLI — they are simply not attributed to a language,
144
+ * so they never appear as a routed language with a misleading zero.
145
+ */
146
+ export const OCR_18_EXCLUDED_EXTENSIONS = {
147
+ '.css': 'stylesheet, not source',
148
+ '.scss': 'stylesheet, not source',
149
+ '.sass': 'stylesheet, not source',
150
+ '.less': 'stylesheet, not source',
151
+ '.html': 'markup, not source',
152
+ '.htm': 'markup, not source',
153
+ '.xml': 'markup/data, not source',
154
+ '.yaml': 'data/config, not source',
155
+ '.yml': 'data/config, not source',
156
+ '.json': 'data/config, not source',
157
+ '.json5': 'data/config, not source',
158
+ '.toml': 'data/config, not source',
159
+ '.ini': 'data/config, not source',
160
+ '.env': 'data/config, not source',
161
+ '.properties': 'data/config, not source',
162
+ '.po': 'translation catalogue, not source',
163
+ '.pot': 'translation catalogue, not source',
164
+ '.ipynb': 'notebook container, not source'
165
+ };
@@ -0,0 +1,84 @@
1
+ import { type Ocr18Language } from './ocr-18-language-routing.js';
2
+ import { type Ocr18Detection } from './ocr-18-multi.js';
3
+ import { type DelegateFile, type DelegatePreview, type DelegateRuleGroup, type RulesResult } from './ocr-18-delegate-payload.js';
4
+ import { type Ocr18Range, type Ocr18State } from './ocr-multilang-adapter.js';
5
+ export type DelegateSelectedFile = {
6
+ readonly path: string;
7
+ readonly status: string;
8
+ readonly insertions: number;
9
+ readonly deletions: number;
10
+ readonly language: Ocr18Language | null;
11
+ /** The glob that selected this file, or `null` when no rule group claimed it. */
12
+ readonly pattern: string | null;
13
+ };
14
+ export type DelegatePacketState = 'no-routed-language' | 'unsupported-files-only' | 'ocr-unavailable' | 'awaiting-envelope';
15
+ export type DelegatePacket = {
16
+ readonly schema_version: '1';
17
+ readonly mode: 'delegate';
18
+ readonly state: DelegatePacketState;
19
+ readonly findings: null;
20
+ readonly rid: string;
21
+ readonly session: string;
22
+ readonly git: {
23
+ readonly from: string | null;
24
+ readonly to: string | null;
25
+ readonly commit: string | null;
26
+ };
27
+ readonly detection: {
28
+ readonly languages: readonly Ocr18Language[];
29
+ readonly changed_file_count: number;
30
+ readonly unsupported_files: readonly string[];
31
+ };
32
+ readonly cost: {
33
+ readonly total_files: number;
34
+ readonly reviewable_count: number;
35
+ readonly excluded_count: number;
36
+ readonly total_insertions: number;
37
+ readonly total_deletions: number;
38
+ } | null;
39
+ readonly selected_files: readonly DelegateSelectedFile[];
40
+ readonly excluded_files: readonly DelegateFile[];
41
+ readonly rules: readonly DelegateRuleGroup[];
42
+ readonly warnings: readonly string[];
43
+ readonly raw_output: string | null;
44
+ };
45
+ export type DelegatePacketInput = {
46
+ readonly rid: string;
47
+ readonly session: string;
48
+ readonly range: Ocr18Range;
49
+ readonly detection: Ocr18Detection;
50
+ readonly preview: DelegatePreview | null;
51
+ readonly rules: readonly DelegateRuleGroup[];
52
+ readonly unavailable: string | null;
53
+ };
54
+ export declare function buildDelegatePacket(input: DelegatePacketInput): DelegatePacket;
55
+ /** Rule resolution in batches, merged by `source|pattern` — the key the rule text is resolved on. */
56
+ export declare function collectDelegateRules(cwd: string, paths: readonly string[], range: Ocr18Range, timeoutMs?: number): RulesResult;
57
+ /**
58
+ * A rid is ONE path segment: it names the packet file under the session's
59
+ * `rd/ocr-delegate/` directory, so a separator or a traversal value would move
60
+ * the write somewhere the caller did not name.
61
+ */
62
+ export declare function isDelegateRid(value: string): boolean;
63
+ export type CollectDelegateOptions = {
64
+ readonly cwd: string;
65
+ readonly rid: string;
66
+ readonly session: string;
67
+ readonly range: Ocr18Range;
68
+ readonly timeoutMs?: number;
69
+ };
70
+ export type DelegatePacketResult = {
71
+ readonly packet: DelegatePacket;
72
+ readonly failure: {
73
+ readonly state: Ocr18State;
74
+ readonly rawOutput: string;
75
+ } | null;
76
+ };
77
+ /**
78
+ * Phase 1. Writes nothing; the caller owns the path and the durable write.
79
+ *
80
+ * No routed language skips BOTH invocations, exactly like the API path: spawning
81
+ * OCR to discover there is nothing to review is the cost that guard exists for.
82
+ */
83
+ export declare function collectDelegatePacket(options: CollectDelegateOptions): DelegatePacketResult;
84
+ export declare function writeDelegatePacket(packetPath: string, packet: DelegatePacket): void;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * OCR 1.x delegation — phase 1: the review packet.
3
+ *
4
+ * The packet is the durable artifact the host agent reviews from: which files
5
+ * OCR selected and by which pattern, which it excluded, the resolved rule text
6
+ * per group, the git range, and the cost surface. Building it never calls an
7
+ * LLM and never reads a key.
8
+ *
9
+ * It keeps the pinned CLI's snake_case field names because it is a boundary
10
+ * document. `findings` is always `null` here: a recorded review carries `[]`
11
+ * when it was clean, so "the agent never ran" cannot be read as zero findings.
12
+ */
13
+ import { mkdirSync, writeFileSync } from 'node:fs';
14
+ import { dirname } from 'node:path';
15
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
16
+ import { normalizePath } from '../../shared/path-utils.js';
17
+ import { languageForPath } from './ocr-18-language-routing.js';
18
+ import { detectLanguages } from './ocr-18-multi.js';
19
+ import { buildDelegateRuleArgs, parseDelegateRules, runDelegatePreview } from './ocr-18-delegate-payload.js';
20
+ import { invokeOcr } from './ocr-multilang-adapter.js';
21
+ /** `delegate rule` takes paths as argv; this keeps each invocation under the Windows limit. */
22
+ const RULE_BATCH = 50;
23
+ function patternFor(path, rules) {
24
+ const target = normalizePath(path);
25
+ for (const group of rules) {
26
+ if (group.files.some((file) => normalizePath(file) === target))
27
+ return group.pattern;
28
+ }
29
+ return null;
30
+ }
31
+ function selectFiles(preview, rules) {
32
+ if (preview === null)
33
+ return { files: [], warnings: [] };
34
+ const warnings = [];
35
+ const files = preview.reviewable_files.map((file) => {
36
+ const pattern = patternFor(file.path, rules);
37
+ if (pattern === null)
38
+ warnings.push(`no rule group matched ${file.path}`);
39
+ return {
40
+ path: file.path,
41
+ status: file.status,
42
+ insertions: file.insertions,
43
+ deletions: file.deletions,
44
+ language: languageForPath(file.path),
45
+ pattern
46
+ };
47
+ });
48
+ return { files, warnings };
49
+ }
50
+ function packetState(input) {
51
+ if (input.unavailable !== null)
52
+ return 'ocr-unavailable';
53
+ if (input.preview !== null)
54
+ return 'awaiting-envelope';
55
+ // Zero changed files and "files changed, none reviewable" are different facts.
56
+ return input.detection.changedFileCount === 0 ? 'no-routed-language' : 'unsupported-files-only';
57
+ }
58
+ export function buildDelegatePacket(input) {
59
+ const selected = selectFiles(input.preview, input.rules);
60
+ return {
61
+ schema_version: '1',
62
+ mode: 'delegate',
63
+ state: packetState(input),
64
+ findings: null,
65
+ rid: input.rid,
66
+ session: input.session,
67
+ git: {
68
+ from: input.range.from ?? null,
69
+ to: input.range.to ?? null,
70
+ commit: input.range.commit ?? null
71
+ },
72
+ detection: {
73
+ languages: input.detection.languages,
74
+ changed_file_count: input.detection.changedFileCount,
75
+ unsupported_files: input.detection.unsupportedFiles
76
+ },
77
+ cost: input.preview === null
78
+ ? null
79
+ : {
80
+ total_files: input.preview.total_files,
81
+ reviewable_count: input.preview.reviewable_count,
82
+ excluded_count: input.preview.excluded_count,
83
+ total_insertions: input.preview.total_insertions,
84
+ total_deletions: input.preview.total_deletions
85
+ },
86
+ selected_files: selected.files,
87
+ excluded_files: input.preview?.excluded_files ?? [],
88
+ rules: input.rules,
89
+ warnings: selected.warnings,
90
+ raw_output: input.unavailable
91
+ };
92
+ }
93
+ function mergeGroups(merged, groups) {
94
+ for (const group of groups) {
95
+ const key = `${group.source}|${group.pattern}`;
96
+ const existing = merged.get(key);
97
+ if (existing === undefined) {
98
+ merged.set(key, { ...group, files: [...group.files] });
99
+ continue;
100
+ }
101
+ const files = [...existing.files];
102
+ for (const file of group.files)
103
+ if (!files.includes(file))
104
+ files.push(file);
105
+ merged.set(key, { ...existing, files });
106
+ }
107
+ }
108
+ /** Rule resolution in batches, merged by `source|pattern` — the key the rule text is resolved on. */
109
+ export function collectDelegateRules(cwd, paths, range, timeoutMs) {
110
+ const merged = new Map();
111
+ for (let start = 0; start < paths.length; start += RULE_BATCH) {
112
+ const batch = paths.slice(start, start + RULE_BATCH);
113
+ const invoked = invokeOcr(buildDelegateRuleArgs(batch, range), cwd, timeoutMs);
114
+ if (!invoked.ok)
115
+ return { ok: false, state: invoked.state, rawOutput: invoked.rawOutput };
116
+ const parsed = parseDelegateRules(invoked.stdout);
117
+ if (!parsed.ok)
118
+ return parsed;
119
+ mergeGroups(merged, parsed.groups);
120
+ }
121
+ return { ok: true, groups: [...merged.values()] };
122
+ }
123
+ /**
124
+ * A rid is ONE path segment: it names the packet file under the session's
125
+ * `rd/ocr-delegate/` directory, so a separator or a traversal value would move
126
+ * the write somewhere the caller did not name.
127
+ */
128
+ export function isDelegateRid(value) {
129
+ return (value.length > 0 && !isUnsafePathInput(value) && !value.includes('/') && !value.includes('\\'));
130
+ }
131
+ function assertRid(value) {
132
+ if (!isDelegateRid(value))
133
+ throw new Error(`invalid rid: ${value}`);
134
+ }
135
+ /**
136
+ * Phase 1. Writes nothing; the caller owns the path and the durable write.
137
+ *
138
+ * No routed language skips BOTH invocations, exactly like the API path: spawning
139
+ * OCR to discover there is nothing to review is the cost that guard exists for.
140
+ */
141
+ export function collectDelegatePacket(options) {
142
+ assertRid(options.rid);
143
+ const detection = detectLanguages(options.cwd, options.range);
144
+ const base = { rid: options.rid, session: options.session, range: options.range, detection };
145
+ const unavailable = (state, rawOutput) => ({
146
+ packet: buildDelegatePacket({ ...base, preview: null, rules: [], unavailable: rawOutput }),
147
+ failure: { state, rawOutput }
148
+ });
149
+ if (detection.languages.length === 0) {
150
+ return {
151
+ packet: buildDelegatePacket({ ...base, preview: null, rules: [], unavailable: null }),
152
+ failure: null
153
+ };
154
+ }
155
+ const preview = runDelegatePreview(options.cwd, options.range, options.timeoutMs);
156
+ if (!preview.ok)
157
+ return unavailable(preview.state, preview.rawOutput);
158
+ const paths = preview.preview.reviewable_files.map((file) => file.path);
159
+ const rules = collectDelegateRules(options.cwd, paths, options.range, options.timeoutMs);
160
+ if (!rules.ok)
161
+ return unavailable(rules.state, rules.rawOutput);
162
+ return {
163
+ packet: buildDelegatePacket({
164
+ ...base,
165
+ preview: preview.preview,
166
+ rules: rules.groups,
167
+ unavailable: null
168
+ }),
169
+ failure: null
170
+ };
171
+ }
172
+ export function writeDelegatePacket(packetPath, packet) {
173
+ mkdirSync(dirname(packetPath), { recursive: true });
174
+ writeFileSync(packetPath, `${JSON.stringify(packet, null, 2)}\n`, 'utf8');
175
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * OCR 1.x delegation — the pinned CLI's payloads, parsed at their boundary.
3
+ *
4
+ * `ocr delegate preview` returns the file selection; `ocr delegate rule` returns
5
+ * the resolved rule text per pattern. Neither calls an LLM and neither reads a
6
+ * key. These parsers are strict on purpose: a `comments[]` review payload is NOT
7
+ * a delegation spec, and reading one as the other is the defect this slice fixes.
8
+ */
9
+ import { type Ocr18Range, type Ocr18State } from './ocr-multilang-adapter.js';
10
+ export type DelegateFile = {
11
+ readonly path: string;
12
+ readonly status: string;
13
+ readonly insertions: number;
14
+ readonly deletions: number;
15
+ readonly exclude_reason?: string;
16
+ };
17
+ export type DelegatePreview = {
18
+ readonly schema_version: string;
19
+ readonly mode: string;
20
+ readonly repository: string;
21
+ readonly from?: string;
22
+ readonly to?: string;
23
+ readonly merge_base?: string;
24
+ readonly total_files: number;
25
+ readonly reviewable_count: number;
26
+ readonly excluded_count: number;
27
+ readonly total_insertions: number;
28
+ readonly total_deletions: number;
29
+ readonly reviewable_files: readonly DelegateFile[];
30
+ readonly excluded_files: readonly DelegateFile[];
31
+ };
32
+ export type DelegateRuleGroup = {
33
+ readonly group_id: number;
34
+ readonly source: string;
35
+ readonly pattern: string;
36
+ readonly files: readonly string[];
37
+ readonly rule: string;
38
+ };
39
+ export declare function buildDelegatePreviewArgs(range: Ocr18Range): string[];
40
+ export declare function buildDelegateRuleArgs(paths: readonly string[], range: Ocr18Range): string[];
41
+ export type PreviewResult = {
42
+ readonly ok: true;
43
+ readonly preview: DelegatePreview;
44
+ } | {
45
+ readonly ok: false;
46
+ readonly reason: string;
47
+ };
48
+ export declare function parseDelegatePreview(stdout: string): PreviewResult;
49
+ export type RulesResult = {
50
+ readonly ok: true;
51
+ readonly groups: readonly DelegateRuleGroup[];
52
+ } | {
53
+ readonly ok: false;
54
+ readonly state: Ocr18State;
55
+ readonly rawOutput: string;
56
+ };
57
+ export declare function parseDelegateRules(stdout: string): RulesResult;
58
+ export type DelegatePreviewResult = {
59
+ readonly ok: true;
60
+ readonly preview: DelegatePreview;
61
+ } | {
62
+ readonly ok: false;
63
+ readonly state: Ocr18State;
64
+ readonly rawOutput: string;
65
+ };
66
+ /** One `delegate preview` invocation — the selection only. No review runs. */
67
+ export declare function runDelegatePreview(cwd: string, range?: Ocr18Range, timeoutMs?: number): DelegatePreviewResult;
@@ -0,0 +1,208 @@
1
+ /**
2
+ * OCR 1.x delegation — the pinned CLI's payloads, parsed at their boundary.
3
+ *
4
+ * `ocr delegate preview` returns the file selection; `ocr delegate rule` returns
5
+ * the resolved rule text per pattern. Neither calls an LLM and neither reads a
6
+ * key. These parsers are strict on purpose: a `comments[]` review payload is NOT
7
+ * a delegation spec, and reading one as the other is the defect this slice fixes.
8
+ */
9
+ import { invokeOcr, OCR_18_PACKAGE, rangeArgs } from './ocr-multilang-adapter.js';
10
+ export function buildDelegatePreviewArgs(range) {
11
+ return [
12
+ '--package',
13
+ OCR_18_PACKAGE,
14
+ '--',
15
+ 'ocr',
16
+ 'delegate',
17
+ 'preview',
18
+ ...rangeArgs(range),
19
+ '--format',
20
+ 'json'
21
+ ];
22
+ }
23
+ export function buildDelegateRuleArgs(paths, range) {
24
+ return [
25
+ '--package',
26
+ OCR_18_PACKAGE,
27
+ '--',
28
+ 'ocr',
29
+ 'delegate',
30
+ 'rule',
31
+ ...paths,
32
+ ...rangeArgs(range),
33
+ '--format',
34
+ 'json'
35
+ ];
36
+ }
37
+ function asRecord(value) {
38
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
39
+ ? value
40
+ : null;
41
+ }
42
+ function asText(value) {
43
+ return typeof value === 'string' && value.length > 0 ? value : null;
44
+ }
45
+ function asCount(value) {
46
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : null;
47
+ }
48
+ function parseFile(value) {
49
+ const record = asRecord(value);
50
+ if (record === null)
51
+ return null;
52
+ const path = asText(record['path']);
53
+ const status = asText(record['status']);
54
+ const insertions = asCount(record['insertions']);
55
+ const deletions = asCount(record['deletions']);
56
+ if (path === null || status === null || insertions === null || deletions === null)
57
+ return null;
58
+ const reason = asText(record['exclude_reason']);
59
+ return {
60
+ path,
61
+ status,
62
+ insertions,
63
+ deletions,
64
+ ...(reason !== null ? { exclude_reason: reason } : {})
65
+ };
66
+ }
67
+ function parseFiles(value, field) {
68
+ if (!Array.isArray(value))
69
+ return `${field} is not an array`;
70
+ const files = [];
71
+ for (const [index, entry] of value.entries()) {
72
+ const file = parseFile(entry);
73
+ if (file === null)
74
+ return `${field}[${String(index)}] is not a file entry`;
75
+ files.push(file);
76
+ }
77
+ return files;
78
+ }
79
+ function optionalText(record, key) {
80
+ const value = record[key];
81
+ return typeof value === 'string' ? value : undefined;
82
+ }
83
+ function previewCost(record) {
84
+ const totalFiles = asCount(record['total_files']);
85
+ const reviewableCount = asCount(record['reviewable_count']);
86
+ const excludedCount = asCount(record['excluded_count']);
87
+ const insertions = asCount(record['total_insertions']);
88
+ const deletions = asCount(record['total_deletions']);
89
+ if (totalFiles === null ||
90
+ reviewableCount === null ||
91
+ excludedCount === null ||
92
+ insertions === null ||
93
+ deletions === null) {
94
+ return null;
95
+ }
96
+ return {
97
+ total_files: totalFiles,
98
+ reviewable_count: reviewableCount,
99
+ excluded_count: excludedCount,
100
+ total_insertions: insertions,
101
+ total_deletions: deletions
102
+ };
103
+ }
104
+ /** The parsed preview, or the reason a file list is malformed. */
105
+ function previewFrom(record, cost) {
106
+ const reviewable = parseFiles(record['reviewable_files'], 'reviewable_files');
107
+ if (typeof reviewable === 'string')
108
+ return reviewable;
109
+ const excluded = parseFiles(record['excluded_files'], 'excluded_files');
110
+ if (typeof excluded === 'string')
111
+ return excluded;
112
+ const from = optionalText(record, 'from');
113
+ const to = optionalText(record, 'to');
114
+ const mergeBase = optionalText(record, 'merge_base');
115
+ return {
116
+ schema_version: optionalText(record, 'schema_version') ?? '1',
117
+ mode: optionalText(record, 'mode') ?? 'range',
118
+ repository: optionalText(record, 'repository') ?? '',
119
+ ...(from !== undefined ? { from } : {}),
120
+ ...(to !== undefined ? { to } : {}),
121
+ ...(mergeBase !== undefined ? { merge_base: mergeBase } : {}),
122
+ ...cost,
123
+ reviewable_files: reviewable,
124
+ excluded_files: excluded
125
+ };
126
+ }
127
+ export function parseDelegatePreview(stdout) {
128
+ let raw;
129
+ try {
130
+ raw = JSON.parse(stdout);
131
+ }
132
+ catch {
133
+ return { ok: false, reason: 'stdout is not JSON' };
134
+ }
135
+ const record = asRecord(raw);
136
+ if (record === null)
137
+ return { ok: false, reason: 'stdout is not a JSON object' };
138
+ if (!Array.isArray(record['reviewable_files'])) {
139
+ return {
140
+ ok: false,
141
+ reason: 'no reviewable_files[] — a review payload is not a delegate preview'
142
+ };
143
+ }
144
+ const cost = previewCost(record);
145
+ if (cost === null)
146
+ return { ok: false, reason: 'preview cost fields are missing' };
147
+ const preview = previewFrom(record, cost);
148
+ if (typeof preview === 'string')
149
+ return { ok: false, reason: preview };
150
+ return { ok: true, preview };
151
+ }
152
+ function parseRuleGroup(value) {
153
+ const record = asRecord(value);
154
+ if (record === null)
155
+ return null;
156
+ const groupId = asCount(record['group_id']);
157
+ const source = asText(record['source']);
158
+ const pattern = asText(record['pattern']);
159
+ const rule = typeof record['rule'] === 'string' ? record['rule'] : null;
160
+ if (groupId === null || source === null || pattern === null || rule === null)
161
+ return null;
162
+ if (!Array.isArray(record['files']))
163
+ return null;
164
+ const files = record['files'].map(asText);
165
+ if (files.some((file) => file === null))
166
+ return null;
167
+ return { group_id: groupId, source, pattern, files: files, rule };
168
+ }
169
+ export function parseDelegateRules(stdout) {
170
+ let raw;
171
+ try {
172
+ raw = JSON.parse(stdout);
173
+ }
174
+ catch {
175
+ return { ok: false, state: 'execution-failed', rawOutput: 'delegate rule output is not JSON' };
176
+ }
177
+ const record = asRecord(raw);
178
+ if (record === null || !Array.isArray(record['groups'])) {
179
+ return {
180
+ ok: false,
181
+ state: 'execution-failed',
182
+ rawOutput: 'delegate rule output has no groups[]'
183
+ };
184
+ }
185
+ const groups = [];
186
+ for (const [index, entry] of record['groups'].entries()) {
187
+ const group = parseRuleGroup(entry);
188
+ if (group === null) {
189
+ return {
190
+ ok: false,
191
+ state: 'execution-failed',
192
+ rawOutput: `groups[${String(index)}] is not a rule group`
193
+ };
194
+ }
195
+ groups.push(group);
196
+ }
197
+ return { ok: true, groups };
198
+ }
199
+ /** One `delegate preview` invocation — the selection only. No review runs. */
200
+ export function runDelegatePreview(cwd, range = {}, timeoutMs) {
201
+ const invoked = invokeOcr(buildDelegatePreviewArgs(range), cwd, timeoutMs);
202
+ if (!invoked.ok)
203
+ return { ok: false, state: invoked.state, rawOutput: invoked.rawOutput };
204
+ const parsed = parseDelegatePreview(invoked.stdout);
205
+ if (!parsed.ok)
206
+ return { ok: false, state: 'execution-failed', rawOutput: parsed.reason };
207
+ return { ok: true, preview: parsed.preview };
208
+ }