peaks-loop 4.1.9 → 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 (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +72 -0
  3. package/dist/cli/commands/_register.js +2 -0
  4. package/dist/cli/commands/code-review-commands.d.ts +1 -1
  5. package/dist/cli/commands/code-review-commands.js +23 -37
  6. package/dist/cli/commands/code-review-ocr-delegate-record.d.ts +3 -0
  7. package/dist/cli/commands/code-review-ocr-delegate-record.js +73 -0
  8. package/dist/cli/commands/code-review-ocr-delegate.d.ts +12 -0
  9. package/dist/cli/commands/code-review-ocr-delegate.js +140 -0
  10. package/dist/cli/commands/code-review-run-ocr-18.d.ts +11 -0
  11. package/dist/cli/commands/code-review-run-ocr-18.js +127 -0
  12. package/dist/cli/commands/strat-tact-command-helpers.d.ts +16 -0
  13. package/dist/cli/commands/strat-tact-command-helpers.js +162 -0
  14. package/dist/cli/commands/strat-tact-commands.d.ts +3 -0
  15. package/dist/cli/commands/strat-tact-commands.js +176 -0
  16. package/dist/services/lint/detect-ocr-18.js +1 -1
  17. package/dist/services/lint/ocr-18-acquire.d.ts +1 -1
  18. package/dist/services/lint/ocr-18-acquire.js +2 -2
  19. package/dist/services/lint/ocr-18-allowlist.d.ts +30 -0
  20. package/dist/services/lint/ocr-18-allowlist.js +165 -0
  21. package/dist/services/lint/ocr-18-delegate-packet.d.ts +84 -0
  22. package/dist/services/lint/ocr-18-delegate-packet.js +175 -0
  23. package/dist/services/lint/ocr-18-delegate-payload.d.ts +67 -0
  24. package/dist/services/lint/ocr-18-delegate-payload.js +208 -0
  25. package/dist/services/lint/ocr-18-delegate-record.d.ts +42 -0
  26. package/dist/services/lint/ocr-18-delegate-record.js +223 -0
  27. package/dist/services/lint/ocr-18-language-routing.d.ts +96 -0
  28. package/dist/services/lint/ocr-18-language-routing.js +148 -0
  29. package/dist/services/lint/ocr-18-multi.d.ts +54 -0
  30. package/dist/services/lint/ocr-18-multi.js +184 -0
  31. package/dist/services/lint/ocr-multilang-adapter.d.ts +45 -7
  32. package/dist/services/lint/ocr-multilang-adapter.js +133 -94
  33. package/dist/services/rd/ast-gate.d.ts +19 -12
  34. package/dist/services/rd/ast-gate.js +10 -0
  35. package/dist/services/rd/canonical-hash.d.ts +1 -0
  36. package/dist/services/rd/canonical-hash.js +38 -0
  37. package/dist/services/rd/impl.js +2 -8
  38. package/dist/services/rd/strategy.js +2 -8
  39. package/dist/services/rd/types.d.ts +10 -10
  40. package/dist/services/rd/types.js +21 -10
  41. package/package.json +10 -10
  42. package/skills/bee/peaks-rd/SKILL.md +57 -3
  43. package/skills/bee/peaks-rd/references/ocr-multilang-1.8.md +314 -111
@@ -0,0 +1,184 @@
1
+ /**
2
+ * OCR 1.x multi-language review: detect which routed languages a git range
3
+ * touches, run `ocr review` ONCE for the whole change set, and group the
4
+ * returned comments by language.
5
+ *
6
+ * A Python+Go change costs one review, not two. A range with no routed language
7
+ * skips the invocation entirely — spawning OCR to discover there is nothing to
8
+ * review is exactly the cost this guard exists to avoid.
9
+ */
10
+ import { spawnSync } from 'node:child_process';
11
+ import { buildReviewArgs, emptyByLanguage, invokeOcr, parseComments, summarize } from './ocr-multilang-adapter.js';
12
+ import { languageForPath } from './ocr-18-language-routing.js';
13
+ /** 16 MiB — the largest `git diff --name-only` list this repo reviews. */
14
+ const GIT_MAX_BUFFER = 16_777_216;
15
+ /**
16
+ * A ref is handed to git as its own argv entry. No valid revision starts with
17
+ * `-`, but an option-shaped value would let a caller inject a git flag
18
+ * (`--output=…`), so it is refused at the boundary rather than passed through.
19
+ */
20
+ function checkedRef(value, flag) {
21
+ if (value.startsWith('-'))
22
+ throw new Error(`invalid ${flag} value: ${value}`);
23
+ return value;
24
+ }
25
+ function changedFiles(cwd, range) {
26
+ const git = (args) => {
27
+ // `windowsHide` on every spawn (repo convention) — the child is a console app.
28
+ const result = spawnSync('git', [...args], {
29
+ cwd,
30
+ encoding: 'utf8',
31
+ windowsHide: true,
32
+ maxBuffer: GIT_MAX_BUFFER
33
+ });
34
+ if (result.error !== undefined && result.error !== null) {
35
+ throw new Error(`git ${args.join(' ')} failed: ${result.error.message}`);
36
+ }
37
+ if (result.status !== 0) {
38
+ const stderr = typeof result.stderr === 'string' ? result.stderr.trim() : '';
39
+ throw new Error(`git ${args.join(' ')} failed: ${stderr || `exit ${String(result.status)}`}`);
40
+ }
41
+ const stdout = typeof result.stdout === 'string' ? result.stdout : '';
42
+ return stdout
43
+ .split('\n')
44
+ .map((line) => line.trim())
45
+ .filter((line) => line.length > 0);
46
+ };
47
+ if (range.commit !== undefined) {
48
+ // `--commit` reviews one commit against its parent; `git show` is that diff
49
+ // and also works for a root commit.
50
+ return git([
51
+ 'show',
52
+ '--pretty=format:',
53
+ '--name-only',
54
+ '--diff-filter=ACMR',
55
+ checkedRef(range.commit, '--commit')
56
+ ]);
57
+ }
58
+ if (range.from !== undefined || range.to !== undefined) {
59
+ const refs = [];
60
+ if (range.from !== undefined)
61
+ refs.push(checkedRef(range.from, '--from'));
62
+ if (range.to !== undefined)
63
+ refs.push(checkedRef(range.to, '--to'));
64
+ return git(['diff', '--name-only', '--diff-filter=ACMR', ...refs, '--']);
65
+ }
66
+ // The workspace, as `ocr review` defaults to it: staged + unstaged tracked
67
+ // changes vs HEAD, plus untracked files. Missing the untracked half would let
68
+ // a brand-new source file skip the review it is about to be part of.
69
+ return [
70
+ ...git(['diff', '--name-only', '--diff-filter=ACMR', 'HEAD', '--']),
71
+ ...git(['ls-files', '--others', '--exclude-standard'])
72
+ ];
73
+ }
74
+ /**
75
+ * Which routed languages (and which unrouted files) the requested range touches.
76
+ *
77
+ * @throws when git cannot answer — "could not detect" must not read as "nothing
78
+ * to review", so the caller is given the choice of what to say.
79
+ */
80
+ export function detectLanguages(cwd, range = {}) {
81
+ const files = [...new Set(changedFiles(cwd, range))];
82
+ const languages = new Set();
83
+ const unsupportedFiles = [];
84
+ for (const file of files) {
85
+ const language = languageForPath(file);
86
+ if (language === null)
87
+ unsupportedFiles.push(file);
88
+ else
89
+ languages.add(language);
90
+ }
91
+ return {
92
+ languages: [...languages].sort(),
93
+ changedFileCount: files.length,
94
+ unsupportedFiles
95
+ };
96
+ }
97
+ function groupByLanguage(findings) {
98
+ const byLanguage = new Map();
99
+ const routed = [];
100
+ const unrouted = [];
101
+ for (const finding of findings) {
102
+ const language = languageForPath(finding.filePath);
103
+ if (language === null) {
104
+ unrouted.push(finding);
105
+ continue;
106
+ }
107
+ routed.push(finding);
108
+ const bucket = byLanguage.get(language) ?? [];
109
+ bucket.push(finding);
110
+ byLanguage.set(language, bucket);
111
+ }
112
+ return { byLanguage, routed, unrouted };
113
+ }
114
+ /**
115
+ * Every requested/detected language gets an entry, so a clean language is a
116
+ * visible zero; a language that only appears in the findings is kept as well
117
+ * rather than dropped for not having been detected.
118
+ */
119
+ function reportsFor(grouped, requested) {
120
+ const order = [...new Set([...requested, ...grouped.byLanguage.keys()])];
121
+ return order.map((language) => {
122
+ const bucket = grouped.byLanguage.get(language) ?? [];
123
+ return { language, findings: bucket, count: bucket.length };
124
+ });
125
+ }
126
+ function countsFor(grouped) {
127
+ const counts = { ...emptyByLanguage() };
128
+ for (const [language, bucket] of grouped.byLanguage)
129
+ counts[language] = bucket.length;
130
+ return counts;
131
+ }
132
+ /** A result for an outcome that has no per-language reports — and so no zero. */
133
+ function stopped(base, state, start, rawOutput) {
134
+ return {
135
+ ...base,
136
+ state,
137
+ languages: [],
138
+ unroutedFindings: [],
139
+ summary: null,
140
+ durationMs: Date.now() - start,
141
+ rawOutput
142
+ };
143
+ }
144
+ /**
145
+ * One review for the whole change set, findings grouped by language.
146
+ *
147
+ * The four outcomes a caller must be able to tell apart:
148
+ * 1. a language reported with findings (`count` > 0);
149
+ * 2. a language reported with count 0 while the state is `ok` — it ran and was clean;
150
+ * 3. `unsupportedFiles` — the file is in the diff but the CLI does not review it
151
+ * as a routed language (with state `no-routed-language` when that is ALL
152
+ * the range holds);
153
+ * 4. a state of `ocr18-missing` / `execution-failed` with `languages: []` — it
154
+ * never ran, so there is no zero to mistake for a clean result.
155
+ */
156
+ export function runOcr18Multi(options) {
157
+ const start = Date.now();
158
+ const detection = detectLanguages(options.cwd, options);
159
+ const base = {
160
+ detected: detection.languages,
161
+ changedFileCount: detection.changedFileCount,
162
+ unsupportedFiles: detection.unsupportedFiles
163
+ };
164
+ // No routed language ⇒ no review. Spawning OCR to discover there is nothing
165
+ // to review is exactly the cost this guard exists to avoid.
166
+ if (detection.languages.length === 0)
167
+ return stopped(base, 'no-routed-language', start, '');
168
+ const invoked = invokeOcr(buildReviewArgs(options), options.cwd, options.timeoutMs);
169
+ if (!invoked.ok)
170
+ return stopped(base, invoked.state, start, invoked.rawOutput);
171
+ const parsed = invoked.stdout.trim().length === 0 ? { ok: true, findings: [] } : parseComments(invoked.stdout);
172
+ if (!parsed.ok)
173
+ return stopped(base, 'execution-failed', start, invoked.stderr || invoked.stdout);
174
+ const grouped = groupByLanguage(parsed.findings);
175
+ return {
176
+ ...base,
177
+ state: 'ok',
178
+ languages: reportsFor(grouped, options.languages ?? detection.languages),
179
+ unroutedFindings: grouped.unrouted,
180
+ summary: summarize(grouped.routed, countsFor(grouped)),
181
+ durationMs: Date.now() - start,
182
+ rawOutput: invoked.stdout
183
+ };
184
+ }
@@ -1,7 +1,6 @@
1
- export declare const OCR_18_PACKAGE = "@alibaba-group/open-code-review@1.8.9";
2
- export declare const OCR_18_LANGUAGES: readonly ["python", "go", "java", "rust", "cpp", "csharp", "ruby", "php"];
3
- export type Ocr18Language = (typeof OCR_18_LANGUAGES)[number];
4
- export type Ocr18State = 'ok' | 'ocr18-missing' | 'binary-missing' | 'llm-config-missing' | 'execution-failed' | 'language-unsupported';
1
+ import { type Ocr18Language } from './ocr-18-language-routing.js';
2
+ export declare const OCR_18_PACKAGE = "@alibaba-group/open-code-review@1.13.1";
3
+ export type Ocr18State = 'ok' | 'no-routed-language' | 'ocr18-missing' | 'binary-missing' | 'llm-config-missing' | 'execution-failed' | 'language-unsupported';
5
4
  export type Ocr18Finding = {
6
5
  readonly filePath: string;
7
6
  readonly line: number;
@@ -21,14 +20,53 @@ export type Ocr18RunResult = {
21
20
  readonly durationMs: number;
22
21
  readonly rawOutput: string;
23
22
  };
24
- export type Ocr18RunOptions = {
25
- readonly cwd: string;
26
- readonly language: string;
23
+ /** The git range a review covers; empty means "the workspace" (what `ocr review` defaults to). */
24
+ export type Ocr18Range = {
27
25
  readonly from?: string;
28
26
  readonly to?: string;
29
27
  readonly commit?: string;
28
+ };
29
+ export type Ocr18RunOptions = Ocr18Range & {
30
+ readonly cwd: string;
31
+ /** Required for a review; ignored by delegation mode, which is not language-scoped. */
32
+ readonly language?: string;
30
33
  readonly delegate?: boolean;
31
34
  readonly timeoutMs?: number;
32
35
  };
36
+ /**
37
+ * The one severity map: OCR comments (`parseComments`) and the delegated
38
+ * envelope (`ocr-18-delegate-record`) both map through it, so the two cannot
39
+ * disagree about what `high` means.
40
+ */
41
+ export declare function severityFor(value: unknown): 'error' | 'warn' | 'info';
42
+ export declare function emptyByLanguage(): Readonly<Record<Ocr18Language, number>>;
43
+ export declare function rangeArgs(range: Ocr18Range): string[];
44
+ /** The review argv — no language flag exists, and none is emitted. */
45
+ export declare function buildReviewArgs(range: Ocr18Range): string[];
33
46
  export declare function buildOcr18Args(options: Ocr18RunOptions): string[];
47
+ export type Ocr18Invocation = {
48
+ readonly ok: true;
49
+ readonly stdout: string;
50
+ readonly stderr: string;
51
+ } | {
52
+ readonly ok: false;
53
+ readonly state: Ocr18State;
54
+ readonly rawOutput: string;
55
+ };
56
+ export declare function invokeOcr(args: readonly string[], cwd: string, timeoutMs?: number): Ocr18Invocation;
57
+ export type ParsedComments = {
58
+ readonly ok: true;
59
+ readonly findings: readonly Ocr18Finding[];
60
+ } | {
61
+ readonly ok: false;
62
+ };
63
+ /**
64
+ * `comments[]` from the real 1.13.1 envelope, mapped onto `Ocr18Finding`.
65
+ *
66
+ * A discriminated result rather than `null`: `{ ok: false }` is the execution
67
+ * failure the caller must report, and it cannot be mistaken for an empty review
68
+ * (which is `{ ok: true, findings: [] }`).
69
+ */
70
+ export declare function parseComments(stdout: string): ParsedComments;
71
+ export declare function summarize(findings: readonly Ocr18Finding[], counts: Readonly<Record<Ocr18Language, number>>): Ocr18Summary;
34
72
  export declare function runOcr18(options: Ocr18RunOptions): Ocr18RunResult;
@@ -1,152 +1,191 @@
1
1
  /**
2
- * OCR 1.8.x multi-language reviewer adapter. Routes one of the
3
- * 8 supported languages to the corresponding `ocr review` filter.
2
+ * OCR 1.x reviewer adapter: builds the argv, spawns the pinned runtime, and maps
3
+ * its real `comments[]` envelope onto `Ocr18Finding`.
4
+ *
5
+ * The pinned CLI has NO language flag — `--filter-language` is not a flag of the
6
+ * real binary (`Error: unknown flag`) — so this module never emits one. Language
7
+ * attribution lives in `ocr-18-language-routing.ts` and the one-review-many-
8
+ * languages path in `ocr-18-multi.ts`.
4
9
  */
5
10
  import { spawnSync } from 'node:child_process';
6
11
  import { resolveNpxInvocation } from './npx-resolver.js';
7
- export const OCR_18_PACKAGE = '@alibaba-group/open-code-review@1.8.9';
8
- export const OCR_18_LANGUAGES = [
9
- 'python',
10
- 'go',
11
- 'java',
12
- 'rust',
13
- 'cpp',
14
- 'csharp',
15
- 'ruby',
16
- 'php'
17
- ];
18
- function isSupportedLanguage(value) {
19
- return OCR_18_LANGUAGES.includes(value);
20
- }
21
- function severityFor(value) {
22
- if (value === 'error' || value === 'critical' || value === 2)
12
+ import { isSupportedLanguage, languageForPath, OCR_18_LANGUAGES } from './ocr-18-language-routing.js';
13
+ export const OCR_18_PACKAGE = '@alibaba-group/open-code-review@1.13.1';
14
+ /**
15
+ * The one severity map: OCR comments (`parseComments`) and the delegated
16
+ * envelope (`ocr-18-delegate-record`) both map through it, so the two cannot
17
+ * disagree about what `high` means.
18
+ */
19
+ export function severityFor(value) {
20
+ if (value === 'error' || value === 'critical' || value === 'high' || value === 2)
23
21
  return 'error';
24
- if (value === 'warn' || value === 'warning' || value === 1)
22
+ if (value === 'warn' || value === 'warning' || value === 'medium' || value === 1)
25
23
  return 'warn';
26
24
  return 'info';
27
25
  }
28
- function emptyByLanguage() {
26
+ export function emptyByLanguage() {
29
27
  const out = {};
30
- for (const lang of OCR_18_LANGUAGES) {
31
- out[lang] = 0;
28
+ for (const language of OCR_18_LANGUAGES) {
29
+ out[language] = 0;
32
30
  }
33
31
  return out;
34
32
  }
33
+ export function rangeArgs(range) {
34
+ const args = [];
35
+ if (range.from !== undefined)
36
+ args.push('--from', range.from);
37
+ if (range.to !== undefined)
38
+ args.push('--to', range.to);
39
+ if (range.commit !== undefined)
40
+ args.push('--commit', range.commit);
41
+ return args;
42
+ }
43
+ /** The review argv — no language flag exists, and none is emitted. */
44
+ export function buildReviewArgs(range) {
45
+ return [
46
+ '--package',
47
+ OCR_18_PACKAGE,
48
+ '--',
49
+ 'ocr',
50
+ 'review',
51
+ ...rangeArgs(range),
52
+ '--format',
53
+ 'json'
54
+ ];
55
+ }
35
56
  export function buildOcr18Args(options) {
36
- if (!isSupportedLanguage(options.language)) {
37
- throw Object.assign(new Error(`unsupported language: ${options.language}`), {
38
- code: 'LANGUAGE_UNSUPPORTED'
39
- });
40
- }
41
- const args = ['--package', OCR_18_PACKAGE, '--', 'ocr'];
42
57
  if (options.delegate === true) {
43
- args.push('delegate', 'preview');
44
- if (options.from !== undefined)
45
- args.push('--from', options.from);
46
- if (options.to !== undefined)
47
- args.push('--to', options.to);
48
- if (options.commit !== undefined)
49
- args.push('--commit', options.commit);
58
+ // Delegation mode hands the host agent a spec and takes no language: the
59
+ // language is ignored by `ocr delegate preview`, so requiring one would be
60
+ // a value the code carries but does not mean.
61
+ return ['--package', OCR_18_PACKAGE, '--', 'ocr', 'delegate', 'preview', ...rangeArgs(options)];
50
62
  }
51
- else {
52
- args.push('review', '--filter-language', options.language);
53
- if (options.from !== undefined)
54
- args.push('--from', options.from);
55
- if (options.to !== undefined)
56
- args.push('--to', options.to);
57
- if (options.commit !== undefined)
58
- args.push('--commit', options.commit);
59
- args.push('--format', 'json');
63
+ if (options.language === undefined || !isSupportedLanguage(options.language)) {
64
+ throw Object.assign(new Error(`unsupported language: ${options.language ?? '<missing>'}`), {
65
+ code: 'LANGUAGE_UNSUPPORTED'
66
+ });
60
67
  }
61
- return args;
68
+ return buildReviewArgs(options);
62
69
  }
63
- export function runOcr18(options) {
64
- const start = Date.now();
65
- if (!isSupportedLanguage(options.language)) {
66
- return {
67
- state: 'language-unsupported',
68
- findings: [],
69
- summary: null,
70
- durationMs: Date.now() - start,
71
- rawOutput: `unsupported language: ${options.language}`
72
- };
73
- }
74
- const args = buildOcr18Args(options);
70
+ export function invokeOcr(args, cwd, timeoutMs) {
75
71
  const spawnOptions = {
76
- cwd: options.cwd,
72
+ cwd,
77
73
  encoding: 'utf8',
78
74
  // Repo convention: without this the child pops a console window on the
79
75
  // user's desktop — and this child can run for the length of a full review.
80
76
  windowsHide: true,
81
- timeout: options.timeoutMs ?? 60_000,
77
+ timeout: timeoutMs ?? 60_000,
82
78
  maxBuffer: 32 * 1024 * 1024
83
79
  };
84
80
  // 2026-09-10: bare `spawnSync('npx', …)` cannot launch the Windows `npx.cmd`
85
81
  // shim (ENOENT, no shell) — same fix and same helper as `detect-ocr-18.ts` /
86
- // `detect-eslint.ts`. `shell: true` is NOT an option: it would concatenate the
87
- // argv unescaped and split the `--package` flag.
88
- const { command, args: npxArgs, baseEnv } = resolveNpxInvocation(args);
82
+ // `detect-eslint.ts`. `shell: true` is NOT an option: it would concatenate
83
+ // the argv unescaped and split the `--package` flag.
84
+ const { command, args: npxArgs, baseEnv } = resolveNpxInvocation([...args]);
89
85
  const result = spawnSync(command, npxArgs, { ...spawnOptions, env: baseEnv });
90
86
  const stdout = typeof result.stdout === 'string' ? result.stdout : '';
91
87
  const stderr = typeof result.stderr === 'string' ? result.stderr : '';
92
88
  if (result.error !== undefined && result.error !== null) {
93
89
  return {
90
+ ok: false,
94
91
  state: 'ocr18-missing',
95
- findings: [],
96
- summary: null,
97
- durationMs: Date.now() - start,
98
92
  // Never discard WHY the launch failed — stdout/stderr are both empty here.
99
93
  rawOutput: stderr || stdout || result.error.message
100
94
  };
101
95
  }
102
96
  if (result.status !== 0) {
97
+ return { ok: false, state: 'execution-failed', rawOutput: stderr || stdout };
98
+ }
99
+ return { ok: true, stdout, stderr };
100
+ }
101
+ /**
102
+ * `comments[]` from the real 1.13.1 envelope, mapped onto `Ocr18Finding`.
103
+ *
104
+ * A discriminated result rather than `null`: `{ ok: false }` is the execution
105
+ * failure the caller must report, and it cannot be mistaken for an empty review
106
+ * (which is `{ ok: true, findings: [] }`).
107
+ */
108
+ export function parseComments(stdout) {
109
+ let parsed;
110
+ try {
111
+ parsed = JSON.parse(stdout);
112
+ }
113
+ catch {
114
+ return { ok: false };
115
+ }
116
+ // A missing or non-array `comments` is a clean review, not a parse failure.
117
+ if (!Array.isArray(parsed.comments))
118
+ return { ok: true, findings: [] };
119
+ const findings = [];
120
+ for (const entry of parsed.comments) {
121
+ if (entry === null || typeof entry !== 'object')
122
+ continue;
123
+ const comment = entry;
124
+ findings.push({
125
+ filePath: typeof comment.path === 'string' ? comment.path : '',
126
+ line: typeof comment.start_line === 'number' ? comment.start_line : 0,
127
+ ruleId: typeof comment.category === 'string' ? comment.category : null,
128
+ severity: severityFor(comment.severity),
129
+ message: typeof comment.content === 'string' ? comment.content : ''
130
+ });
131
+ }
132
+ return { ok: true, findings };
133
+ }
134
+ export function summarize(findings, counts) {
135
+ const bySeverity = { error: 0, warn: 0, info: 0 };
136
+ for (const finding of findings)
137
+ bySeverity[finding.severity]++;
138
+ return { total: findings.length, bySeverity, byLanguage: counts };
139
+ }
140
+ export function runOcr18(options) {
141
+ const start = Date.now();
142
+ const language = options.language;
143
+ if (options.delegate !== true && (language === undefined || !isSupportedLanguage(language))) {
103
144
  return {
104
- state: 'execution-failed',
145
+ state: 'language-unsupported',
105
146
  findings: [],
106
147
  summary: null,
107
148
  durationMs: Date.now() - start,
108
- rawOutput: stderr || stdout
149
+ rawOutput: `unsupported language: ${language ?? '<missing>'}`
150
+ };
151
+ }
152
+ const invoked = invokeOcr(buildOcr18Args(options), options.cwd, options.timeoutMs);
153
+ if (!invoked.ok) {
154
+ return {
155
+ state: invoked.state,
156
+ findings: [],
157
+ summary: null,
158
+ durationMs: Date.now() - start,
159
+ rawOutput: invoked.rawOutput
109
160
  };
110
161
  }
111
162
  let findings = [];
112
- if (stdout.trim().length > 0) {
113
- try {
114
- const parsed = JSON.parse(stdout);
115
- if (Array.isArray(parsed.findings)) {
116
- for (const entry of parsed.findings) {
117
- if (entry === null || typeof entry !== 'object')
118
- continue;
119
- const f = entry;
120
- findings.push({
121
- filePath: typeof f.file === 'string' ? f.file : '',
122
- line: typeof f.line === 'number' ? f.line : 0,
123
- ruleId: typeof f.rule === 'string' ? f.rule : null,
124
- severity: severityFor(f.severity),
125
- message: typeof f.message === 'string' ? f.message : ''
126
- });
127
- }
128
- }
129
- }
130
- catch {
163
+ if (invoked.stdout.trim().length > 0) {
164
+ const parsed = parseComments(invoked.stdout);
165
+ if (!parsed.ok) {
131
166
  return {
132
167
  state: 'execution-failed',
133
168
  findings: [],
134
169
  summary: null,
135
170
  durationMs: Date.now() - start,
136
- rawOutput: stderr || stdout
171
+ rawOutput: invoked.stderr || invoked.stdout
137
172
  };
138
173
  }
174
+ // A single-language run reports only that language. Delegation mode has no
175
+ // language, and its preview carries no comments, so nothing is filtered.
176
+ findings =
177
+ language === undefined
178
+ ? parsed.findings
179
+ : parsed.findings.filter((finding) => languageForPath(finding.filePath) === language);
139
180
  }
140
- const bySeverity = { error: 0, warn: 0, info: 0 };
141
- for (const f of findings)
142
- bySeverity[f.severity]++;
143
- const byLanguageMut = { ...emptyByLanguage() };
144
- byLanguageMut[options.language] = findings.length;
181
+ const byLanguage = { ...emptyByLanguage() };
182
+ if (language !== undefined && isSupportedLanguage(language))
183
+ byLanguage[language] = findings.length;
145
184
  return {
146
185
  state: 'ok',
147
186
  findings,
148
- summary: { total: findings.length, bySeverity, byLanguage: byLanguageMut },
187
+ summary: summarize(findings, byLanguage),
149
188
  durationMs: Date.now() - start,
150
- rawOutput: stdout
189
+ rawOutput: invoked.stdout
151
190
  };
152
191
  }
@@ -1,16 +1,23 @@
1
+ import { z } from 'zod';
1
2
  import type { AstGateResult } from './types.js';
2
- export interface AstGateContext {
3
- readonly deps: Readonly<Record<string, {
4
- readonly version: string;
5
- readonly source: string;
6
- readonly resolved: string;
7
- }>>;
8
- readonly docSummaries: ReadonlyArray<{
9
- readonly dep: string;
10
- readonly version: string;
11
- readonly apis: ReadonlyArray<string>;
12
- }>;
13
- }
3
+ /**
4
+ * The locked-version context the gate compares against. The schema is the
5
+ * single source for both the type and the CLI's `--ast-context` validation —
6
+ * a malformed context is refused rather than silently read as empty.
7
+ */
8
+ export declare const AstGateContextSchema: z.ZodObject<{
9
+ deps: z.ZodRecord<z.ZodString, z.ZodObject<{
10
+ version: z.ZodString;
11
+ source: z.ZodString;
12
+ resolved: z.ZodString;
13
+ }, z.core.$strip>>;
14
+ docSummaries: z.ZodArray<z.ZodObject<{
15
+ dep: z.ZodString;
16
+ version: z.ZodString;
17
+ apis: z.ZodArray<z.ZodString>;
18
+ }, z.core.$strip>>;
19
+ }, z.core.$strip>;
20
+ export type AstGateContext = z.infer<typeof AstGateContextSchema>;
14
21
  export interface RunAstGateInput {
15
22
  readonly project: string;
16
23
  readonly changedFiles: ReadonlyArray<string>;
@@ -12,6 +12,16 @@
12
12
  */
13
13
  import { readFile } from 'node:fs/promises';
14
14
  import { join } from 'node:path';
15
+ import { z } from 'zod';
16
+ /**
17
+ * The locked-version context the gate compares against. The schema is the
18
+ * single source for both the type and the CLI's `--ast-context` validation —
19
+ * a malformed context is refused rather than silently read as empty.
20
+ */
21
+ export const AstGateContextSchema = z.object({
22
+ deps: z.record(z.string(), z.object({ version: z.string(), source: z.string(), resolved: z.string() })),
23
+ docSummaries: z.array(z.object({ dep: z.string(), version: z.string(), apis: z.array(z.string()) }))
24
+ });
15
25
  const IMPORT_RE = /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g;
16
26
  const CALL_RE = /\b([a-zA-Z_$][\w$]*)\s*\(/g;
17
27
  export async function runAstGate(input) {
@@ -0,0 +1 @@
1
+ export declare function canonicalSha256(content: object): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Canonical H8 digest shared by STRAT, TACT and the CLI verifiers.
3
+ *
4
+ * WHY one export: `writeStrategy`, `writeImpl` and the `peaks tact read|write`
5
+ * verifiers must compute the IDENTICAL digest, or an artifact signed by one
6
+ * side is refused by the other. Keeping the omit-`sha256` + sorted-keys rule
7
+ * in one place is what stops that drift.
8
+ *
9
+ * WHY A RECURSIVE SORT AND NOT `JSON.stringify(rest, Object.keys(rest).sort())`:
10
+ * the array-replacer form filters keys at EVERY nesting level, so a nested
11
+ * object whose keys are not top-level names serializes as `{}` — the digest
12
+ * then ignores `astGateResult`, `changedFiles[]` entries and
13
+ * `askUserQuestion` entirely. Measured: forging `impl.json#astGateResult`
14
+ * without touching `sha256` still verified. The sort must be applied by hand,
15
+ * per level, so every nested value is part of the digest.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ function stableValue(value) {
19
+ if (Array.isArray(value)) {
20
+ return value.map(stableValue);
21
+ }
22
+ if (value === null || typeof value !== 'object') {
23
+ return value;
24
+ }
25
+ const source = value;
26
+ const sorted = {};
27
+ for (const key of Object.keys(source).sort()) {
28
+ sorted[key] = stableValue(source[key]);
29
+ }
30
+ return sorted;
31
+ }
32
+ export function canonicalSha256(content) {
33
+ const { sha256: _omit, ...rest } = content;
34
+ void _omit;
35
+ return createHash('sha256')
36
+ .update(JSON.stringify(stableValue(rest)))
37
+ .digest('hex');
38
+ }
@@ -7,15 +7,9 @@
7
7
  * H6 (CLI裁决): refuses to write when AST gate has violations —
8
8
  * LLM MUST auto-fix and re-run.
9
9
  */
10
- import { createHash } from 'node:crypto';
11
10
  import { writeFile, rename, unlink } from 'node:fs/promises';
11
+ import { canonicalSha256 } from './canonical-hash.js';
12
12
  import { ImplOutputSchema } from './types.js';
13
- function sha256Of(content) {
14
- const { sha256: _omit, ...rest } = content;
15
- void _omit;
16
- const canonical = JSON.stringify(rest, Object.keys(rest).sort());
17
- return createHash('sha256').update(canonical).digest('hex');
18
- }
19
13
  export async function writeImpl(input) {
20
14
  // Defense-in-depth: passed flag and violations[] must agree.
21
15
  // A caller passing passed=true with non-empty violations (lying input)
@@ -40,7 +34,7 @@ export async function writeImpl(input) {
40
34
  externalApiCalls: [...input.externalApiCalls],
41
35
  astGateResult: input.astGate
42
36
  };
43
- const sha256 = sha256Of(partial);
37
+ const sha256 = canonicalSha256(partial);
44
38
  const final = { ...partial, sha256 };
45
39
  ImplOutputSchema.parse(final);
46
40
  const tmp = `${input.out}.tmp`;