peaks-loop 4.1.6 → 4.1.8

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 (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +78 -0
  3. package/config/eslint/tsconfig.lint.json +1 -0
  4. package/dist/cli/commands/core/skill-registry-commands.js +9 -4
  5. package/dist/cli/commands/dispatch-from-dag.js +17 -0
  6. package/dist/cli/commands/job-commands.js +15 -5
  7. package/dist/cli/commands/lint-baseline-command.d.ts +15 -0
  8. package/dist/cli/commands/lint-baseline-command.js +64 -0
  9. package/dist/cli/commands/lint-commands.js +27 -51
  10. package/dist/cli/commands/request-command-options.d.ts +6 -0
  11. package/dist/cli/commands/request-commands.js +2 -0
  12. package/dist/cli/commands/request-mark-qa-initiated-command.d.ts +3 -0
  13. package/dist/cli/commands/request-mark-qa-initiated-command.js +80 -0
  14. package/dist/cli/commands/request-transition-failures.js +1 -0
  15. package/dist/cli/commands/reviewer-commands.d.ts +6 -6
  16. package/dist/cli/commands/reviewer-commands.js +154 -56
  17. package/dist/cli/commands/reviewer-config-commands.d.ts +9 -0
  18. package/dist/cli/commands/reviewer-config-commands.js +133 -0
  19. package/dist/services/artifacts/artifact-lint-service.js +102 -27
  20. package/dist/services/artifacts/artifact-prerequisites.d.ts +2 -0
  21. package/dist/services/artifacts/artifact-prerequisites.js +22 -110
  22. package/dist/services/artifacts/artifact-template-bodies.d.ts +7 -1
  23. package/dist/services/artifacts/artifact-template-bodies.js +14 -3
  24. package/dist/services/artifacts/artifact-templates.d.ts +6 -1
  25. package/dist/services/artifacts/artifact-templates.js +8 -5
  26. package/dist/services/artifacts/backcompat-acceptance.d.ts +66 -0
  27. package/dist/services/artifacts/backcompat-acceptance.js +222 -0
  28. package/dist/services/artifacts/prerequisite-checks.d.ts +42 -9
  29. package/dist/services/artifacts/prerequisite-checks.js +35 -11
  30. package/dist/services/artifacts/prerequisite-path-resolver.d.ts +39 -0
  31. package/dist/services/artifacts/prerequisite-path-resolver.js +110 -0
  32. package/dist/services/artifacts/qa-initiated-marker.d.ts +24 -0
  33. package/dist/services/artifacts/qa-initiated-marker.js +36 -0
  34. package/dist/services/artifacts/request-artifact-metadata.d.ts +9 -0
  35. package/dist/services/artifacts/request-artifact-metadata.js +9 -0
  36. package/dist/services/artifacts/request-artifact-service.js +6 -10
  37. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +2 -1
  38. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -3
  39. package/dist/services/dispatch/isolation-lease.d.ts +3 -2
  40. package/dist/services/dispatch/isolation-lease.js +15 -6
  41. package/dist/services/doctor/doctor-service/checks/backcompat-acceptance.d.ts +15 -0
  42. package/dist/services/doctor/doctor-service/checks/backcompat-acceptance.js +53 -0
  43. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.d.ts +38 -0
  44. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.js +243 -0
  45. package/dist/services/doctor/doctor-service/plugin-registry.js +4 -0
  46. package/dist/services/doctor/doctor-service/types.d.ts +12 -0
  47. package/dist/services/job/subagent-job-wrapper.d.ts +20 -7
  48. package/dist/services/job/subagent-job-wrapper.js +53 -5
  49. package/dist/services/lint/eslint-report.d.ts +19 -0
  50. package/dist/services/lint/eslint-report.js +60 -0
  51. package/dist/services/lint/eslint-runner-support.d.ts +18 -1
  52. package/dist/services/lint/eslint-runner-support.js +35 -2
  53. package/dist/services/lint/eslint-runner-types.d.ts +21 -1
  54. package/dist/services/lint/eslint-runner.js +43 -33
  55. package/dist/services/prd/gate-evidence-derivation.d.ts +2 -4
  56. package/dist/services/prd/gate-evidence-derivation.js +3 -1
  57. package/dist/services/qa/bdd-test-style-contract.d.ts +17 -0
  58. package/dist/services/qa/bdd-test-style-contract.js +41 -0
  59. package/dist/services/qa/bdd-test-style-verifier.d.ts +9 -6
  60. package/dist/services/qa/bdd-test-style-verifier.js +24 -37
  61. package/dist/services/rd/reviewer-dispatch-policy.d.ts +18 -14
  62. package/dist/services/rd/reviewer-dispatch-policy.js +14 -11
  63. package/dist/services/release/release-state.js +20 -5
  64. package/dist/services/reviewer/model-family.js +1 -1
  65. package/dist/services/reviewer/reviewer-artifacts.d.ts +12 -0
  66. package/dist/services/reviewer/reviewer-artifacts.js +67 -0
  67. package/dist/services/reviewer/reviewer-config-write.d.ts +18 -0
  68. package/dist/services/reviewer/reviewer-config-write.js +71 -0
  69. package/dist/services/reviewer/reviewer-config.d.ts +33 -5
  70. package/dist/services/reviewer/reviewer-config.js +102 -46
  71. package/dist/services/reviewer/reviewer-envelopes.d.ts +8 -0
  72. package/dist/services/reviewer/reviewer-envelopes.js +53 -0
  73. package/dist/services/reviewer/reviewer-service.d.ts +7 -4
  74. package/dist/services/reviewer/reviewer-service.js +46 -52
  75. package/dist/services/reviewer/reviewer-types.d.ts +9 -1
  76. package/dist/services/session/getSessionDir.js +16 -7
  77. package/dist/services/web/daemon-registry.d.ts +6 -4
  78. package/dist/services/web/daemon-registry.js +92 -17
  79. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +4 -1
  80. package/dist/services/workflow/pipeline-verify-gate-support.js +8 -79
  81. package/dist/services/workflow/pipeline-verify-rd-phase.d.ts +67 -0
  82. package/dist/services/workflow/pipeline-verify-rd-phase.js +122 -0
  83. package/dist/services/workflow/pipeline-verify-service.js +16 -17
  84. package/dist/services/workspace/workspace-service.js +4 -16
  85. package/package.json +5 -5
  86. package/schemas/doctor-report.schema.json +2 -2
  87. package/schemas/reviewer-envelope.schema.json +1 -1
  88. package/skills/bee/peaks-reviewer/SKILL.md +20 -4
  89. package/skills/bee/peaks-reviewer/references/reviewer-schema.md +12 -7
  90. package/skills/bee/peaks-security-audit/SKILL.md +20 -0
@@ -23,7 +23,8 @@ import { join } from 'node:path';
23
23
  import { repoRelativeKey } from '../../shared/path-utils.js';
24
24
  import { resolveNpxInvocation } from './npx-resolver.js';
25
25
  import { ESLINT_PACKAGE_PINS } from './eslint-runner-types.js';
26
- import { aggregateRedLine, buildEslintArgs, EMPTY_DIFF_RANGE, EMPTY_REDLINE, emptyResult, inDiff, loadBaseline, matchBaseline, resolveProjectRoot, severityFor, summarize } from './eslint-runner-support.js';
26
+ import { aggregateRedLine, buildEslintArgs, EMPTY_DIFF_RANGE, emptyPopulationReason, EMPTY_REDLINE, emptyResult, inDiff, loadBaseline, matchBaseline, resolveProjectRoot, summarize } from './eslint-runner-support.js';
27
+ import { parseEslintReport } from './eslint-report.js';
27
28
  export { ESLINT_PACKAGE_PINS } from './eslint-runner-types.js';
28
29
  export { buildEslintArgs, resolveProjectRoot } from './eslint-runner-support.js';
29
30
  /**
@@ -87,7 +88,9 @@ export function runEslint(options) {
87
88
  args = buildEslintArgs(options);
88
89
  }
89
90
  catch (error) {
90
- return emptyResult('execution-failed', start, error instanceof Error ? error.message : String(error), 'the eslint argument list could not be built');
91
+ return emptyResult('execution-failed', start, error instanceof Error ? error.message : String(error), {
92
+ reason: 'the eslint argument list could not be built'
93
+ });
91
94
  }
92
95
  const projectRoot = resolveProjectRoot(options.cwd);
93
96
  // Invoke eslint via `node <node_modules/eslint/bin/eslint.js>` to bypass
@@ -139,51 +142,45 @@ export function runEslint(options) {
139
142
  // and did not finish, and that difference is the whole diagnosis.
140
143
  const timedOut = result.error.code === 'ETIMEDOUT';
141
144
  const budgetMs = options.timeoutMs ?? ESLINT_DEFAULT_TIMEOUT_MS;
142
- return emptyResult(state, start, typeof result.stdout === 'string' ? result.stdout : '', timedOut
143
- ? `eslint did not finish within the ${budgetMs}ms spawn timeout`
144
- : `eslint could not be spawned: ${message}`);
145
+ return emptyResult(state, start, typeof result.stdout === 'string' ? result.stdout : '', {
146
+ reason: timedOut
147
+ ? `eslint did not finish within the ${budgetMs}ms spawn timeout`
148
+ : `eslint could not be spawned: ${message}`
149
+ });
145
150
  }
146
151
  if (result.signal !== null && result.signal !== undefined) {
147
152
  // A kill that arrived WITHOUT a spawn error — a signal from outside, not the
148
153
  // spawn timeout (that one is caught above as ETIMEDOUT). Named so it is not
149
154
  // read as linter output that would not parse.
150
155
  const budgetMs = options.timeoutMs ?? ESLINT_DEFAULT_TIMEOUT_MS;
151
- return emptyResult('execution-failed', start, typeof result.stdout === 'string' ? result.stdout : '', `eslint was killed by ${result.signal} after ${Date.now() - start}ms (spawn timeout ${budgetMs}ms)`);
156
+ return emptyResult('execution-failed', start, typeof result.stdout === 'string' ? result.stdout : '', {
157
+ reason: `eslint was killed by ${result.signal} after ${Date.now() - start}ms (spawn timeout ${budgetMs}ms)`
158
+ });
152
159
  }
153
160
  const stdout = typeof result.stdout === 'string' ? result.stdout : '';
154
- let findings = [];
161
+ // A valid JSON report means eslint RAN. Its exit code is 2 when nothing
162
+ // matched the scope, so the exit code alone cannot tell "the scope is empty"
163
+ // from "the toolchain is missing" — that distinction is §2.41's whole point.
164
+ let report = { findings: [], checkedFiles: 0, ignoredFiles: 0 };
165
+ let parsedOutput = false;
155
166
  if (stdout.trim().length > 0) {
156
167
  try {
157
- const parsed = JSON.parse(stdout);
158
- for (const entry of parsed) {
159
- if (typeof entry !== 'object' || entry === null)
160
- continue;
161
- const parentFile = typeof entry.filePath === 'string'
162
- ? entry.filePath
163
- : '';
164
- const messages = Array.isArray(entry.messages)
165
- ? entry.messages
166
- : [];
167
- for (const m of messages) {
168
- if (m === null || typeof m !== 'object')
169
- continue;
170
- findings.push({
171
- filePath: typeof m.filePath === 'string' && m.filePath.length > 0 ? m.filePath : parentFile,
172
- line: typeof m.line === 'number' ? m.line : 0,
173
- column: typeof m.column === 'number' ? m.column : 0,
174
- ruleId: typeof m.ruleId === 'string' ? m.ruleId : null,
175
- severity: severityFor(m.severity),
176
- message: typeof m.message === 'string' ? m.message : ''
177
- });
178
- }
179
- }
168
+ report = parseEslintReport(stdout);
169
+ parsedOutput = true;
180
170
  }
181
171
  catch {
182
- return emptyResult('execution-failed', start, stdout, `eslint stdout was not valid JSON (${stdout.length} bytes)`);
172
+ return emptyResult('execution-failed', start, stdout, {
173
+ reason: `eslint stdout was not valid JSON (${stdout.length} bytes)`
174
+ });
183
175
  }
184
176
  }
185
- if (result.status !== 0 && findings.length === 0) {
186
- return emptyResult('eslint-missing', start, typeof result.stderr === 'string' ? result.stderr : stdout);
177
+ const { findings, checkedFiles, ignoredFiles } = report;
178
+ // eslint exits 2 with an empty stdout when the scope matched no file at all.
179
+ // That is an empty population (§2.41), not a missing toolchain.
180
+ const stderr = typeof result.stderr === 'string' ? result.stderr : '';
181
+ const noFilesMatched = /No files matching the pattern/.test(stderr);
182
+ if (result.status !== 0 && findings.length === 0 && !parsedOutput && !noFilesMatched) {
183
+ return emptyResult('eslint-missing', start, stderr.length > 0 ? stderr : stdout);
187
184
  }
188
185
  // PRD-002b slice: incremental-first / no-touch-stockcode filters.
189
186
  // PRD-002b D6: baselineFile is project-level; if missing we surface
@@ -216,6 +213,17 @@ export function runEslint(options) {
216
213
  activeFindings = next;
217
214
  }
218
215
  const redLine = redLineMode === 'baseline-aware' ? aggregateRedLine(baseline) : EMPTY_REDLINE;
216
+ if (checkedFiles === 0 && options.allowEmpty !== true) {
217
+ // Backlog §2.41: a count of findings must carry the population that
218
+ // produced it, and an empty population is refused rather than reported
219
+ // green. eslint skips dot-directories by default, so this is the state a
220
+ // scope like `.husky` used to reach silently.
221
+ return emptyResult('empty-scope', start, stdout, {
222
+ reason: emptyPopulationReason(options.scope, ignoredFiles),
223
+ checkedFiles,
224
+ ignoredFiles
225
+ });
226
+ }
219
227
  const finalState = baseline.length === 0 && diffOnly && options.baselineFile !== undefined
220
228
  ? 'baseline-missing'
221
229
  : 'ok';
@@ -225,6 +233,8 @@ export function runEslint(options) {
225
233
  summary: summarize(activeFindings),
226
234
  durationMs: Date.now() - start,
227
235
  rawOutput: stdout,
236
+ checkedFiles,
237
+ ignoredFiles,
228
238
  baselineWaived: waived,
229
239
  redLine
230
240
  };
@@ -74,6 +74,7 @@
74
74
  * is not reported as `undefined` — see `deriveGateEvidenceForRequest`.
75
75
  */
76
76
  import { type RequestType } from '../artifacts/artifact-prerequisites.js';
77
+ import type { UnmetPrerequisite } from '../artifacts/prerequisite-checks.js';
77
78
  import { type GateEvidence } from './handoff-types.js';
78
79
  /**
79
80
  * The `gateEvidence` map for a slice of `requestType` — the evidence paths
@@ -119,10 +120,7 @@ export declare function deriveGateEvidenceForRequest(opts: {
119
120
  /** `missing` / `warnings` in the same shape `checkPrerequisites` reports. */
120
121
  export interface GateEvidenceDeclarationCheck {
121
122
  readonly ok: boolean;
122
- readonly missing: ReadonlyArray<{
123
- path: string;
124
- description: string;
125
- }>;
123
+ readonly missing: ReadonlyArray<UnmetPrerequisite>;
126
124
  readonly warnings: ReadonlyArray<{
127
125
  path: string;
128
126
  code: string;
@@ -88,7 +88,7 @@ import { PROJECT_SCAN_RELATIVE } from './project-scan-reader.js';
88
88
  * prerequisite's path moves the declared path with it.
89
89
  *
90
90
  * `mut/mut-report.json`, `rd/karpathy-review-<rid>.md`,
91
- * `rd/third-party-review.md`, `qa/test-cases/<rid>.md` and the unit-test
91
+ * `rd/third-party-review-<rid>.md`, `qa/test-cases/<rid>.md` and the unit-test
92
92
  * marker have no key — the vocabulary is five keys, and those artifacts are
93
93
  * already enforced by the table itself, so they are deliberately not
94
94
  * declared here rather than being forced into a key that does not mean them.
@@ -235,6 +235,7 @@ export async function checkDeclaredGateEvidence(opts) {
235
235
  ok: false,
236
236
  missing: [
237
237
  {
238
+ kind: 'body',
238
239
  path: `gateEvidence(${declared.status})`,
239
240
  description: `the handoff's gateEvidence declaration is unusable (${declared.status}) — ` +
240
241
  'a declaration that cannot be read is not the same as no declaration'
@@ -251,6 +252,7 @@ export async function checkDeclaredGateEvidence(opts) {
251
252
  if (await pathExists(join(opts.projectRoot, declaredPath)))
252
253
  continue;
253
254
  missing.push({
255
+ kind: 'absent',
254
256
  path: `gateEvidence.${key}`,
255
257
  description: `gateEvidence.${key} declares "${declaredPath}", which does not exist`
256
258
  });
@@ -39,3 +39,20 @@ export interface VerifyBddStyleInput {
39
39
  export declare function matchesBddTriple(triple: readonly string[]): boolean;
40
40
  /** True when `text` contains `when` or `should` as a whole word. */
41
41
  export declare function hasWhenOrShould(text: string): boolean;
42
+ /**
43
+ * The leading logical comments of a callback block, in source order.
44
+ *
45
+ * The contract's unit is the COMMENT, not the source line
46
+ * (`contracts/test-style-contract.md` §1.2: the body must start with
47
+ * "exactly three leading comments"). A `// given:` wrapped onto a second
48
+ * line is still ONE comment, so it must not consume a second slot and push
49
+ * `// when:` out of the triple. A comment line that carries no keyword
50
+ * counts as a continuation of the previous comment only when it is
51
+ * hanging-indented beneath that comment's text; written at the same column
52
+ * it is a separate leading comment, and a fourth one violates "exactly
53
+ * three".
54
+ *
55
+ * Scanning stops at the first executable line: only the region before any
56
+ * executable code is contract-bound, so comments after it are permitted.
57
+ */
58
+ export declare function leadingBddComments(blockBody: string): string[];
@@ -35,3 +35,44 @@ export function matchesBddTriple(triple) {
35
35
  export function hasWhenOrShould(text) {
36
36
  return /(\bwhen\b|\bshould\b)/i.test(text);
37
37
  }
38
+ /** True when a `//` line starts with one of the three BDD keywords. */
39
+ function isBddKeywordLine(line) {
40
+ return /^\s*\/\/\s*(?:given|when|then)\s*:/i.test(line);
41
+ }
42
+ /**
43
+ * The leading logical comments of a callback block, in source order.
44
+ *
45
+ * The contract's unit is the COMMENT, not the source line
46
+ * (`contracts/test-style-contract.md` §1.2: the body must start with
47
+ * "exactly three leading comments"). A `// given:` wrapped onto a second
48
+ * line is still ONE comment, so it must not consume a second slot and push
49
+ * `// when:` out of the triple. A comment line that carries no keyword
50
+ * counts as a continuation of the previous comment only when it is
51
+ * hanging-indented beneath that comment's text; written at the same column
52
+ * it is a separate leading comment, and a fourth one violates "exactly
53
+ * three".
54
+ *
55
+ * Scanning stops at the first executable line: only the region before any
56
+ * executable code is contract-bound, so comments after it are permitted.
57
+ */
58
+ export function leadingBddComments(blockBody) {
59
+ const comments = [];
60
+ let previousContentColumn = -1;
61
+ for (const line of blockBody.split(/\r?\n/)) {
62
+ if (line.trim().length === 0)
63
+ continue;
64
+ if (!line.trimStart().startsWith('//'))
65
+ break;
66
+ const commentAt = line.indexOf('//');
67
+ const content = line.slice(commentAt + 2);
68
+ if (content.trim().length === 0)
69
+ continue;
70
+ const contentColumn = commentAt + 2 + (content.length - content.trimStart().length);
71
+ if (comments.length > 0 && !isBddKeywordLine(line) && contentColumn > previousContentColumn) {
72
+ continue; // hanging-indent continuation of the previous comment
73
+ }
74
+ comments.push(line);
75
+ previousContentColumn = contentColumn;
76
+ }
77
+ return comments;
78
+ }
@@ -50,12 +50,15 @@ import { type BddStyleVerdict, type VerifyBddStyleInput } from './bdd-test-style
50
50
  * here because the description itself is a literal — there is
51
51
  * no nested template literal to misread.
52
52
  * 2. The callback body (the second argument when it is an arrow /
53
- * function expression with a block) MUST have a `// given:`,
54
- * `// when:`, `// then:` triple at the top, in that order,
55
- * within the first 3 leading-comment ranges before the first
56
- * statement. The `// arrange:` / `// act:` / `// assert:` AAA
57
- * legacy is NOT accepted — the contract is given-when-then
58
- * only.
53
+ * function expression with a block) MUST start with the
54
+ * `// given:` / `// when:` / `// then:` triple, in that order. The
55
+ * unit is the leading COMMENT, not the source line: a keyword
56
+ * comment plus any hanging-indented continuation lines counts as
57
+ * one, so a wrapped `// given:` does not shift `// when:` into a
58
+ * later slot. Before any executable code the body must hold exactly
59
+ * those three comments — a fourth leading comment is refused. The
60
+ * `// arrange:` / `// act:` / `// assert:` AAA legacy is NOT
61
+ * accepted — the contract is given-when-then only.
59
62
  *
60
63
  * Returns the FIRST failure encountered (file order, then
61
64
  * top-to-bottom line order). A structured `BddStyleFail` is what the
@@ -41,7 +41,7 @@
41
41
  import { readFileSync } from 'node:fs';
42
42
  import { resolve } from 'node:path';
43
43
  import ts from 'typescript';
44
- import { matchesBddTriple, hasWhenOrShould } from './bdd-test-style-contract.js';
44
+ import { leadingBddComments, matchesBddTriple, hasWhenOrShould } from './bdd-test-style-contract.js';
45
45
  /** Test runners whose first string-arg is the test description. */
46
46
  const TEST_NAMES = new Set(['it', 'test']);
47
47
  /**
@@ -55,12 +55,15 @@ const TEST_NAMES = new Set(['it', 'test']);
55
55
  * here because the description itself is a literal — there is
56
56
  * no nested template literal to misread.
57
57
  * 2. The callback body (the second argument when it is an arrow /
58
- * function expression with a block) MUST have a `// given:`,
59
- * `// when:`, `// then:` triple at the top, in that order,
60
- * within the first 3 leading-comment ranges before the first
61
- * statement. The `// arrange:` / `// act:` / `// assert:` AAA
62
- * legacy is NOT accepted — the contract is given-when-then
63
- * only.
58
+ * function expression with a block) MUST start with the
59
+ * `// given:` / `// when:` / `// then:` triple, in that order. The
60
+ * unit is the leading COMMENT, not the source line: a keyword
61
+ * comment plus any hanging-indented continuation lines counts as
62
+ * one, so a wrapped `// given:` does not shift `// when:` into a
63
+ * later slot. Before any executable code the body must hold exactly
64
+ * those three comments — a fourth leading comment is refused. The
65
+ * `// arrange:` / `// act:` / `// assert:` AAA legacy is NOT
66
+ * accepted — the contract is given-when-then only.
64
67
  *
65
68
  * Returns the FIRST failure encountered (file order, then
66
69
  * top-to-bottom line order). A structured `BddStyleFail` is what the
@@ -210,41 +213,25 @@ function getCallbackBlock(call) {
210
213
  return null;
211
214
  }
212
215
  function checkBlockLeadingComments(block, sourceFile, relPath) {
213
- // TypeScript's `getLeadingCommentRanges` API is unreliable for
214
- // comment-only blocks: with `setParentNodes: true`, an empty
215
- // block (no statements, only comments) has no anchor to attach
216
- // the comments to, so the API returns zero ranges. To get a
217
- // deterministic answer, we scan the block's text directly and
218
- // pick the first three non-empty lines.
219
- //
220
- // The block's text spans `{` ... `}`. We extract the body,
221
- // split on lines, and check the first three non-empty lines for
222
- // the BDD triple. This is AST-driven (we use the block's source
223
- // range from the SourceFile, not a global regex) and survives
224
- // both empty-body and populated-body cases.
225
- const blockStart = block.getStart(sourceFile) + 1; // skip `{`
226
- const blockEnd = block.end - 1; // skip `}`
227
- const body = sourceFile.text.slice(blockStart, blockEnd);
228
- const lines = body.split(/\r?\n/);
229
- const nonEmpty = [];
230
- for (const line of lines) {
231
- if (line.trim().length === 0)
232
- continue;
233
- nonEmpty.push(line);
234
- if (nonEmpty.length === 3)
235
- break;
236
- }
237
- if (nonEmpty.length < 3 || !matchesBddTriple(nonEmpty)) {
216
+ const body = sourceFile.text.slice(block.getStart(sourceFile) + 1, block.end - 1);
217
+ // `matchesBddTriple` also refuses anything other than three comments, so
218
+ // the contract's "exactly three leading comments" needs no second count.
219
+ if (!matchesBddTriple(leadingBddComments(body))) {
238
220
  return makeMissingCommentFailure(block, sourceFile, relPath);
239
221
  }
240
222
  return null;
241
223
  }
242
224
  function makeMissingCommentFailure(block, sourceFile, relPath) {
243
- // Report the line of the opening `{` + 1 — the line that should
244
- // contain the first comment of the BDD triple. This gives the
245
- // caller a stable pointer even when the block is empty.
246
- const pos = block.getStart(sourceFile) + 1;
247
- const { line } = sourceFile.getLineAndCharacterOfPosition(pos);
225
+ // Point at the first line the author must change: the first
226
+ // non-whitespace character inside the braces (where the triple belongs),
227
+ // or just inside the braces when the block is empty. Anchoring on
228
+ // `getStart() + 1` reported the `{` — and with it the `it(` line — one
229
+ // line too early.
230
+ const bodyStart = block.getStart(sourceFile) + 1;
231
+ const bodyEnd = block.end - 1;
232
+ const firstContent = sourceFile.text.slice(bodyStart, bodyEnd).search(/\S/);
233
+ const anchor = firstContent === -1 ? bodyEnd : bodyStart + firstContent;
234
+ const { line } = sourceFile.getLineAndCharacterOfPosition(anchor);
248
235
  return {
249
236
  ok: false,
250
237
  reason: 'missing-given-when-then',
@@ -32,23 +32,26 @@
32
32
  * mechanism — an LLM reads prose, not TypeScript exports — and that is the
33
33
  * reason every export below sat at zero importers until slice F2.
34
34
  *
35
- * Pinning is half-done. The two test files this block used to cite —
36
- * element pinning) and
37
- * back-compat cases) — were both deleted in `f17aa377`. The **predicate
38
- * half** was re-pinned by `tests/unit/rd/reviewer-dispatch-policy.test.ts`
39
- * (`7191140f`, 6 cases: `RD_DEPRECATED_REVIEWERS` + `isDeprecatedReviewer`).
35
+ * Pinning is complete. The two test files this block used to cite were
36
+ * both deleted in `f17aa377`. The **predicate half**
37
+ * (`RD_DEPRECATED_REVIEWERS` + `isDeprecatedReviewer`) was re-pinned by
38
+ * `tests/unit/rd/reviewer-dispatch-policy.test.ts` (`7191140f`, 6 cases).
40
39
  * The **decision-table half** — `RD_FANOUT_REVIEWERS`' 3-element
41
40
  * membership, `reviewerListFor`, `karpathySlotIndex`,
42
- * `shouldDispatchKarpathy` — still has no pin.
41
+ * `shouldDispatchKarpathy` — is pinned by
42
+ * `tests/unit/rd/reviewer-dispatch-policy-decision-table.test.ts`,
43
+ * including the 5→3 relationship: the fanout request types are exactly
44
+ * the review request types `isFanoutTriggerType` accepts, and no
45
+ * deprecated reviewer appears in the returned list.
43
46
  *
44
47
  * `src/cli/commands/sub-agent-shared.ts` (`deprecatedReviewerWarnings`),
45
48
  * invoked from the dispatch chokepoint in
46
49
  * `src/cli/commands/dispatch-commands.ts` and pinned by
47
- * `tests/unit/cli/sub-agent-dispatch-deprecated-reviewer.test.ts`. Before
48
- * that, all 13 exports had zero importers across src/ + packages/ +
49
- * scripts/, so nothing rejected or rerouted `security-reviewer` /
50
- * `perf-baseline-reviewer` on the way in. That import is still the only
51
- * one: the other 12 exports below remain unreferenced in this repo.
50
+ * `tests/unit/cli/sub-agent-dispatch-deprecated-reviewer.test.ts`, is the
51
+ * only runtime importer. The decision-table exports are pinned by tests
52
+ * rather than imported, which is the point of the table. The three type
53
+ * aliases derived from the tuple constants are module-internal: no
54
+ * importer names them, so they are not exported.
52
55
  *
53
56
  * For `config | docs | chore` request types, the slice already skips
54
57
  * the entire fanout (SKILL.md line 132 says "Config / docs / chore: no
@@ -75,7 +78,7 @@
75
78
  * does not disagree with the prereq side about the same deprecation.
76
79
  */
77
80
  export declare const RD_REVIEW_REQUEST_TYPES: readonly ["feat", "bugfix", "refactor", "config", "docs", "chore"];
78
- export type RdReviewRequestType = (typeof RD_REVIEW_REQUEST_TYPES)[number];
81
+ type RdReviewRequestType = (typeof RD_REVIEW_REQUEST_TYPES)[number];
79
82
  /**
80
83
  * The 3-sub-agent fanout triggered at the end of RD implementation
81
84
  * (v2.12.0). In v2.11.x this was a 5-element list; the
@@ -83,7 +86,7 @@ export type RdReviewRequestType = (typeof RD_REVIEW_REQUEST_TYPES)[number];
83
86
  * the standalone `peaks-security-audit` / `peaks-perf-audit` skills.
84
87
  */
85
88
  export declare const RD_FANOUT_REVIEWERS: readonly ["code-reviewer", "qa-test-cases-writer", "karpathy-reviewer"];
86
- export type RdFanoutReviewer = (typeof RD_FANOUT_REVIEWERS)[number];
89
+ type RdFanoutReviewer = (typeof RD_FANOUT_REVIEWERS)[number];
87
90
  /**
88
91
  * Reviewer roles removed from the v2.11.x 5-way fanout. Exposed as a
89
92
  * separate constant so:
@@ -101,7 +104,7 @@ export declare const RD_DEPRECATED_REVIEWERS: readonly ["security-reviewer", "pe
101
104
  export type RdDeprecatedReviewer = (typeof RD_DEPRECATED_REVIEWERS)[number];
102
105
  /** Subset of request types that fire the 3-way fanout. */
103
106
  export declare const RD_FANOUT_REQUEST_TYPES: readonly ["feat", "bugfix", "refactor"];
104
- export type RdFanoutRequestType = (typeof RD_FANOUT_REQUEST_TYPES)[number];
107
+ type RdFanoutRequestType = (typeof RD_FANOUT_REQUEST_TYPES)[number];
105
108
  /**
106
109
  * True iff the karpathy-reviewer sub-agent should be dispatched for
107
110
  * this request type. For `config | docs | chore` the entire 3-way
@@ -144,3 +147,4 @@ export declare function karpathySlotIndex(type: RdReviewRequestType): number;
144
147
  * list.
145
148
  */
146
149
  export declare function isDeprecatedReviewer(name: string): name is RdDeprecatedReviewer;
150
+ export {};
@@ -32,23 +32,26 @@
32
32
  * mechanism — an LLM reads prose, not TypeScript exports — and that is the
33
33
  * reason every export below sat at zero importers until slice F2.
34
34
  *
35
- * Pinning is half-done. The two test files this block used to cite —
36
- * element pinning) and
37
- * back-compat cases) — were both deleted in `f17aa377`. The **predicate
38
- * half** was re-pinned by `tests/unit/rd/reviewer-dispatch-policy.test.ts`
39
- * (`7191140f`, 6 cases: `RD_DEPRECATED_REVIEWERS` + `isDeprecatedReviewer`).
35
+ * Pinning is complete. The two test files this block used to cite were
36
+ * both deleted in `f17aa377`. The **predicate half**
37
+ * (`RD_DEPRECATED_REVIEWERS` + `isDeprecatedReviewer`) was re-pinned by
38
+ * `tests/unit/rd/reviewer-dispatch-policy.test.ts` (`7191140f`, 6 cases).
40
39
  * The **decision-table half** — `RD_FANOUT_REVIEWERS`' 3-element
41
40
  * membership, `reviewerListFor`, `karpathySlotIndex`,
42
- * `shouldDispatchKarpathy` — still has no pin.
41
+ * `shouldDispatchKarpathy` — is pinned by
42
+ * `tests/unit/rd/reviewer-dispatch-policy-decision-table.test.ts`,
43
+ * including the 5→3 relationship: the fanout request types are exactly
44
+ * the review request types `isFanoutTriggerType` accepts, and no
45
+ * deprecated reviewer appears in the returned list.
43
46
  *
44
47
  * `src/cli/commands/sub-agent-shared.ts` (`deprecatedReviewerWarnings`),
45
48
  * invoked from the dispatch chokepoint in
46
49
  * `src/cli/commands/dispatch-commands.ts` and pinned by
47
- * `tests/unit/cli/sub-agent-dispatch-deprecated-reviewer.test.ts`. Before
48
- * that, all 13 exports had zero importers across src/ + packages/ +
49
- * scripts/, so nothing rejected or rerouted `security-reviewer` /
50
- * `perf-baseline-reviewer` on the way in. That import is still the only
51
- * one: the other 12 exports below remain unreferenced in this repo.
50
+ * `tests/unit/cli/sub-agent-dispatch-deprecated-reviewer.test.ts`, is the
51
+ * only runtime importer. The decision-table exports are pinned by tests
52
+ * rather than imported, which is the point of the table. The three type
53
+ * aliases derived from the tuple constants are module-internal: no
54
+ * importer names them, so they are not exported.
52
55
  *
53
56
  * For `config | docs | chore` request types, the slice already skips
54
57
  * the entire fanout (SKILL.md line 132 says "Config / docs / chore: no
@@ -50,6 +50,14 @@ const STATE_FILE = '.peaks/release-state.json';
50
50
  export function getReleaseStatePath(projectRoot) {
51
51
  return resolve(projectRoot, STATE_FILE);
52
52
  }
53
+ /** A persisted record is only as trustworthy as its stage: `currentStage` is
54
+ * typed `ReleaseStage`, but it comes out of a JSON file nothing validated. */
55
+ function hasValidStage(value) {
56
+ if (typeof value !== 'object' || value === null)
57
+ return false;
58
+ const stage = value.currentStage;
59
+ return typeof stage === 'string' && isReleaseStage(stage);
60
+ }
53
61
  export function readReleaseState(projectRoot) {
54
62
  const path = getReleaseStatePath(projectRoot);
55
63
  if (!existsSync(path))
@@ -59,11 +67,18 @@ export function readReleaseState(projectRoot) {
59
67
  const parsed = JSON.parse(raw);
60
68
  if (parsed.version !== 1)
61
69
  return EMPTY_RELEASE_STATE;
62
- return {
63
- version: 1,
64
- active: parsed.active ?? null,
65
- history: Array.isArray(parsed.history) ? parsed.history : []
66
- };
70
+ const active = parsed.active ?? null;
71
+ const history = Array.isArray(parsed.history) ? parsed.history : [];
72
+ // Fail closed, exactly as the version check and the catch above do: a state
73
+ // file naming a stage this table no longer has (e.g. the dropped
74
+ // 'hotfixed') is a file this build cannot interpret. `transitionRelease`
75
+ // would otherwise throw on it (its error message indexes the stage table),
76
+ // so the reader is where an unknown stage has to stop.
77
+ if (active !== null && !hasValidStage(active))
78
+ return EMPTY_RELEASE_STATE;
79
+ if (!history.every(hasValidStage))
80
+ return EMPTY_RELEASE_STATE;
81
+ return { version: 1, active, history };
67
82
  }
68
83
  catch {
69
84
  return EMPTY_RELEASE_STATE;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * model-family.ts — derive `modelFamily` from a `modelId` for the G4
3
- * `third-party-review.json.modelFamily !== karpathy-review.json.modelFamily`,
3
+ * `third-party-review-<rid>.json.modelFamily !== karpathy-review.json.modelFamily`,
4
4
  * so the family bucket must be stable, provider-distinguishing, and
5
5
  * version-tolerant (e.g. `claude-opus-4-8` and `claude-haiku-4-5` both
6
6
  * bucket to `claude`, while `gpt-4o-mini` and `gpt-3.5-turbo` bucket
@@ -0,0 +1,12 @@
1
+ import type { ReviewerEnvelope } from './reviewer-types.js';
2
+ export type ReviewerArtifactPaths = {
3
+ markdown: string;
4
+ json: string;
5
+ };
6
+ export declare function renderReviewerMarkdown(rid: string, envelope: ReviewerEnvelope): string;
7
+ export declare function writeReviewerArtifacts(input: {
8
+ projectRoot: string;
9
+ sessionId: string;
10
+ rid: string;
11
+ envelope: ReviewerEnvelope;
12
+ }): ReviewerArtifactPaths;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * reviewer-artifacts.ts — the producer side of the G4 reviewer: writes
3
+ * `rd/third-party-review-<rid>.md` and `rd/third-party-review-<rid>.json` under
4
+ * the session's `.peaks/_runtime/<sessionId>/rd/`.
5
+ *
6
+ * Only a real verdict reaches here. The caller must not call this with a
7
+ * skip envelope (backlog §7.10 ④): a skip stays a skip.
8
+ */
9
+ import { mkdirSync, writeFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
12
+ import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
13
+ /** One table cell: newlines and pipes from the model cannot break the table. */
14
+ function cell(value) {
15
+ return value.replace(/\r?\n/g, ' ').replace(/\|/g, '\\|');
16
+ }
17
+ export function renderReviewerMarkdown(rid, envelope) {
18
+ const violations = envelope.violations.length === 0
19
+ ? 'None.'
20
+ : envelope.violations
21
+ .map((v) => `- \`${cell(v.kind)}\` — ${cell(v.file)}:${String(v.line)} — ${cell(v.hint)}`)
22
+ .join('\n');
23
+ return [
24
+ `# third-party-review — ${cell(rid)}`,
25
+ '',
26
+ 'Schema-validated ReviewerEnvelope produced by `peaks reviewer run`.',
27
+ `The JSON sibling \`third-party-review-${cell(rid)}.json\` carries the same envelope.`,
28
+ '',
29
+ '| Field | Value |',
30
+ '| --- | --- |',
31
+ `| reviewerId | ${cell(envelope.reviewerId)} |`,
32
+ `| modelId | ${cell(envelope.modelId)} |`,
33
+ `| modelFamily | ${cell(envelope.modelFamily)} |`,
34
+ `| passed | ${String(envelope.passed)} |`,
35
+ `| gateAction | ${cell(envelope.gateAction)} |`,
36
+ `| reason | ${cell(envelope.reason)} |`,
37
+ '',
38
+ '## Violations',
39
+ '',
40
+ violations,
41
+ ''
42
+ ].join('\n');
43
+ }
44
+ export function writeReviewerArtifacts(input) {
45
+ // `isUnsafePathInput` is a traversal guard, not a single-segment guard: it
46
+ // admits `a/b`. The session id is ONE directory name under `_runtime/`, so
47
+ // the separator axes are refused here as well.
48
+ if (isUnsafePathInput(input.sessionId) ||
49
+ input.sessionId.includes('/') ||
50
+ input.sessionId.includes('\\')) {
51
+ throw new Error(`Invalid session id: ${input.sessionId} (must be a single path segment)`);
52
+ }
53
+ // The rid becomes a filename below, so the repo's own request-id guard runs
54
+ // before the first mkdir — a `..` segment must not reach `join`.
55
+ if (!REQUEST_ID_PATTERN.test(input.rid)) {
56
+ throw new Error(`Invalid request id: ${input.rid} (expected letters, digits, dots, underscores, or dashes)`);
57
+ }
58
+ const dir = join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'rd');
59
+ mkdirSync(dir, { recursive: true });
60
+ const paths = {
61
+ markdown: join(dir, `third-party-review-${input.rid}.md`),
62
+ json: join(dir, `third-party-review-${input.rid}.json`)
63
+ };
64
+ writeFileSync(paths.markdown, renderReviewerMarkdown(input.rid, input.envelope), 'utf8');
65
+ writeFileSync(paths.json, JSON.stringify(input.envelope, null, 2), 'utf8');
66
+ return paths;
67
+ }
@@ -0,0 +1,18 @@
1
+ import { type ReviewerConfig, type ReviewerProviderConfig } from './reviewer-config.js';
2
+ /** Providers `reviewer-service.ts` can actually dispatch to. */
3
+ export declare const DISPATCHABLE_PROVIDER_NAMES: ReadonlyArray<string>;
4
+ export type ReviewerConfigWriteResult = {
5
+ ok: true;
6
+ path: string;
7
+ } | {
8
+ ok: false;
9
+ reason: 'unreadable-config';
10
+ message: string;
11
+ };
12
+ /** Null when valid; otherwise the reason the section cannot be written. */
13
+ export declare function validateReviewerSection(config: ReviewerConfig): string | null;
14
+ export declare function writeReviewerConfig(config: ReviewerConfig, options?: {
15
+ path?: string;
16
+ }): ReviewerConfigWriteResult;
17
+ /** `name:model`; the first colon splits, so `llama3.2:8b` survives. */
18
+ export declare function parseProviderSpec(spec: string): ReviewerProviderConfig | null;