peaks-loop 4.1.7 → 4.1.9

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 (85) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +72 -0
  3. package/config/eslint/tsconfig.lint.json +1 -0
  4. package/dist/cli/commands/code-gate-step-08-command.js +21 -11
  5. package/dist/cli/commands/code-gate-step-08-remedy.d.ts +17 -0
  6. package/dist/cli/commands/code-gate-step-08-remedy.js +76 -0
  7. package/dist/cli/commands/code-job-shape-commands.js +21 -5
  8. package/dist/cli/commands/dispatch-from-dag.js +17 -0
  9. package/dist/cli/commands/job-commands.js +15 -5
  10. package/dist/cli/commands/job-init-status-commands.js +45 -5
  11. package/dist/cli/commands/lint-baseline-command.d.ts +15 -0
  12. package/dist/cli/commands/lint-baseline-command.js +64 -0
  13. package/dist/cli/commands/lint-commands.js +27 -51
  14. package/dist/cli/commands/request-command-options.d.ts +6 -0
  15. package/dist/cli/commands/request-commands.js +2 -0
  16. package/dist/cli/commands/request-mark-qa-initiated-command.d.ts +3 -0
  17. package/dist/cli/commands/request-mark-qa-initiated-command.js +80 -0
  18. package/dist/cli/commands/request-transition-failures.js +1 -0
  19. package/dist/cli/commands/reviewer-commands.d.ts +6 -6
  20. package/dist/cli/commands/reviewer-commands.js +154 -56
  21. package/dist/cli/commands/reviewer-config-commands.d.ts +9 -0
  22. package/dist/cli/commands/reviewer-config-commands.js +133 -0
  23. package/dist/services/artifacts/artifact-lint-service.js +102 -27
  24. package/dist/services/artifacts/artifact-prerequisites.d.ts +1 -0
  25. package/dist/services/artifacts/artifact-prerequisites.js +13 -13
  26. package/dist/services/artifacts/artifact-template-bodies.d.ts +7 -1
  27. package/dist/services/artifacts/artifact-template-bodies.js +14 -3
  28. package/dist/services/artifacts/artifact-templates.d.ts +6 -1
  29. package/dist/services/artifacts/artifact-templates.js +8 -5
  30. package/dist/services/artifacts/backcompat-acceptance.js +7 -5
  31. package/dist/services/artifacts/prerequisite-checks.d.ts +34 -9
  32. package/dist/services/artifacts/prerequisite-checks.js +28 -9
  33. package/dist/services/artifacts/qa-initiated-marker.d.ts +24 -0
  34. package/dist/services/artifacts/qa-initiated-marker.js +36 -0
  35. package/dist/services/artifacts/request-artifact-metadata.d.ts +9 -0
  36. package/dist/services/artifacts/request-artifact-metadata.js +9 -0
  37. package/dist/services/artifacts/request-artifact-service.js +6 -10
  38. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +2 -1
  39. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -3
  40. package/dist/services/code/job-shape-provisional.d.ts +51 -0
  41. package/dist/services/code/job-shape-provisional.js +80 -0
  42. package/dist/services/code/step-08-gate.d.ts +24 -12
  43. package/dist/services/code/step-08-gate.js +54 -97
  44. package/dist/services/code/step-08-session-readers.d.ts +27 -0
  45. package/dist/services/code/step-08-session-readers.js +105 -0
  46. package/dist/services/dispatch/isolation-lease.d.ts +3 -2
  47. package/dist/services/dispatch/isolation-lease.js +15 -6
  48. package/dist/services/job/subagent-job-wrapper.d.ts +20 -7
  49. package/dist/services/job/subagent-job-wrapper.js +53 -5
  50. package/dist/services/lint/eslint-report.d.ts +19 -0
  51. package/dist/services/lint/eslint-report.js +60 -0
  52. package/dist/services/lint/eslint-runner-support.d.ts +18 -1
  53. package/dist/services/lint/eslint-runner-support.js +35 -2
  54. package/dist/services/lint/eslint-runner-types.d.ts +21 -1
  55. package/dist/services/lint/eslint-runner.js +43 -33
  56. package/dist/services/prd/gate-evidence-derivation.d.ts +2 -4
  57. package/dist/services/prd/gate-evidence-derivation.js +3 -1
  58. package/dist/services/qa/bdd-test-style-contract.d.ts +17 -0
  59. package/dist/services/qa/bdd-test-style-contract.js +41 -0
  60. package/dist/services/qa/bdd-test-style-verifier.d.ts +9 -6
  61. package/dist/services/qa/bdd-test-style-verifier.js +24 -37
  62. package/dist/services/rd/reviewer-dispatch-policy.d.ts +18 -14
  63. package/dist/services/rd/reviewer-dispatch-policy.js +14 -11
  64. package/dist/services/release/release-state.js +20 -5
  65. package/dist/services/reviewer/model-family.js +1 -1
  66. package/dist/services/reviewer/reviewer-artifacts.d.ts +12 -0
  67. package/dist/services/reviewer/reviewer-artifacts.js +67 -0
  68. package/dist/services/reviewer/reviewer-config-write.d.ts +18 -0
  69. package/dist/services/reviewer/reviewer-config-write.js +71 -0
  70. package/dist/services/reviewer/reviewer-config.d.ts +33 -5
  71. package/dist/services/reviewer/reviewer-config.js +102 -46
  72. package/dist/services/reviewer/reviewer-envelopes.d.ts +8 -0
  73. package/dist/services/reviewer/reviewer-envelopes.js +53 -0
  74. package/dist/services/reviewer/reviewer-service.d.ts +7 -4
  75. package/dist/services/reviewer/reviewer-service.js +46 -52
  76. package/dist/services/reviewer/reviewer-types.d.ts +9 -1
  77. package/dist/services/session/getSessionDir.js +16 -7
  78. package/dist/services/web/daemon-registry.d.ts +6 -4
  79. package/dist/services/web/daemon-registry.js +92 -17
  80. package/package.json +5 -5
  81. package/schemas/reviewer-envelope.schema.json +1 -1
  82. package/skills/bee/peaks-reviewer/SKILL.md +20 -4
  83. package/skills/bee/peaks-reviewer/references/reviewer-schema.md +12 -7
  84. package/skills/bee/peaks-security-audit/SKILL.md +20 -0
  85. package/skills/peaks-code/references/step-0-8-gate.md +2 -1
@@ -1,4 +1,6 @@
1
1
  import { showRequestArtifact } from './request-artifact-service.js';
2
+ import { isRequestType, VALID_REQUEST_TYPES } from './artifact-prerequisites.js';
3
+ import { allowedStatesForRole, locateArtifactState } from './request-artifact-state-helpers.js';
2
4
  const RULES = [
3
5
  {
4
6
  test: (line) => /<[A-Za-z][^>]*>/.test(line.trim()) && !/^\s*-?\s*linked-/i.test(line),
@@ -27,7 +29,6 @@ const ALLOWLIST_PATTERNS = [
27
29
  /^\s*```/, // code fences
28
30
  /^\s*-\s*last update:/i, // metadata
29
31
  /^\s*-\s*created:/i,
30
- /^\s*-\s*state:/i,
31
32
  /^\s*-\s*type:\s*(feature|bugfix|refactor|docs|config|chore)\s*$/i,
32
33
  /^\s*-\s*session:\s*[a-z0-9-]+/i,
33
34
  /^\s*-\s*transition note/i // bypass / repair notes are not placeholders
@@ -44,26 +45,77 @@ function isAllowlisted(line) {
44
45
  function stripInlineCode(line) {
45
46
  return line.replace(/`[^`]*`/g, '');
46
47
  }
47
- export async function lintRequestArtifact(options) {
48
- const showOptions = {
49
- projectRoot: options.projectRoot,
50
- role: options.role,
51
- requestId: options.requestId
52
- };
53
- if (options.sessionId !== undefined) {
54
- showOptions.sessionId = options.sessionId;
48
+ /**
49
+ * The reader's own `- type:` locator: `extractMetadata` trims every line before
50
+ * matching, and takes everything after `type:`. `- state:` is matched at column
51
+ * 0, exactly as `locateArtifactState` does. Both are "handled" whether the value
52
+ * is valid or not, so the placeholder rules never fire on the same line.
53
+ */
54
+ const METADATA_TYPE_RE = /^-\s*type:\s*(.+?)\s*$/;
55
+ const METADATA_STATE_RE = /^-\s*state:\s*(.+?)\s*$/;
56
+ function checkMetadataLine(rawLine, role) {
57
+ const typeMatch = METADATA_TYPE_RE.exec(rawLine.trim());
58
+ if (typeMatch?.[1] !== undefined) {
59
+ const value = typeMatch[1];
60
+ return {
61
+ handled: true,
62
+ reason: isRequestType(value)
63
+ ? null
64
+ : `Invalid - type: "${value}" — expected one of: ${VALID_REQUEST_TYPES.join(', ')}`
65
+ };
55
66
  }
56
- const artifact = await showRequestArtifact(showOptions);
57
- if (artifact === null) {
67
+ const stateMatch = METADATA_STATE_RE.exec(rawLine);
68
+ if (stateMatch?.[1] !== undefined) {
69
+ const value = stateMatch[1];
70
+ const allowed = allowedStatesForRole(role);
71
+ return {
72
+ handled: true,
73
+ reason: allowed.includes(value)
74
+ ? null
75
+ : `Invalid - state: "${value}" for role ${role} — expected one of: ${allowed.join(', ')}`
76
+ };
77
+ }
78
+ return { handled: false };
79
+ }
80
+ /** The finding a metadata line produces, or `undefined` when the line is not metadata. */
81
+ function metadataFinding(rawLine, role, line) {
82
+ const metadata = checkMetadataLine(rawLine, role);
83
+ if (!metadata.handled)
84
+ return undefined;
85
+ if (metadata.reason === null)
86
+ return null;
87
+ return { line, text: rawLine.trim(), reason: metadata.reason, severity: 'error' };
88
+ }
89
+ /**
90
+ * The finding for an artifact with NO `- state:` line, or null when the reader
91
+ * can locate one. The locator is the reader's own (`locateArtifactState`), so
92
+ * this check agrees with the transition's fail-closed `STATE_ORDER_UNREADABLE`
93
+ * instead of only with the per-line spelling rule in `checkMetadataLine`.
94
+ */
95
+ function missingStateFinding(lines, role) {
96
+ if (locateArtifactState(lines).stateLineIndex !== -1)
58
97
  return null;
98
+ const allowed = allowedStatesForRole(role);
99
+ return {
100
+ line: 1,
101
+ text: '(no - state: line)',
102
+ reason: `Missing - state: line for role ${role} — expected one of: ${allowed.join(', ')}`,
103
+ severity: 'error'
104
+ };
105
+ }
106
+ /** The first placeholder rule this line violates, or null when it violates none. */
107
+ function firstRule(rawLine) {
108
+ const testLine = stripInlineCode(rawLine);
109
+ for (const rule of RULES) {
110
+ if (rule.test(testLine))
111
+ return rule;
59
112
  }
60
- const lines = artifact.content.split(/\r?\n/);
113
+ return null;
114
+ }
115
+ function scanLines(lines, role) {
61
116
  const findings = [];
62
117
  let insideFence = false;
63
- for (let index = 0; index < lines.length; index += 1) {
64
- const rawLine = lines[index];
65
- if (rawLine === undefined)
66
- continue;
118
+ for (const [index, rawLine] of lines.entries()) {
67
119
  // Fenced code blocks hold literal examples, not prose to fill; skip their
68
120
  // contents entirely (the fence delimiters themselves toggle the state).
69
121
  if (/^\s*```/.test(rawLine)) {
@@ -72,21 +124,44 @@ export async function lintRequestArtifact(options) {
72
124
  }
73
125
  if (insideFence)
74
126
  continue;
127
+ const metadata = metadataFinding(rawLine, role, index + 1);
128
+ if (metadata !== undefined) {
129
+ if (metadata !== null)
130
+ findings.push(metadata);
131
+ continue;
132
+ }
75
133
  if (isAllowlisted(rawLine))
76
134
  continue;
77
- const testLine = stripInlineCode(rawLine);
78
- for (const rule of RULES) {
79
- if (rule.test(testLine)) {
80
- findings.push({
81
- line: index + 1,
82
- text: rawLine.trim(),
83
- reason: rule.reason,
84
- severity: rule.severity
85
- });
86
- break;
87
- }
135
+ const rule = firstRule(rawLine);
136
+ if (rule !== null) {
137
+ findings.push({
138
+ line: index + 1,
139
+ text: rawLine.trim(),
140
+ reason: rule.reason,
141
+ severity: rule.severity
142
+ });
88
143
  }
89
144
  }
145
+ return findings;
146
+ }
147
+ export async function lintRequestArtifact(options) {
148
+ const showOptions = {
149
+ projectRoot: options.projectRoot,
150
+ role: options.role,
151
+ requestId: options.requestId
152
+ };
153
+ if (options.sessionId !== undefined) {
154
+ showOptions.sessionId = options.sessionId;
155
+ }
156
+ const artifact = await showRequestArtifact(showOptions);
157
+ if (artifact === null) {
158
+ return null;
159
+ }
160
+ const lines = artifact.content.split(/\r?\n/);
161
+ const findings = scanLines(lines, options.role);
162
+ const missingState = missingStateFinding(lines, options.role);
163
+ if (missingState !== null)
164
+ findings.unshift(missingState);
90
165
  const hasError = findings.some((finding) => finding.severity === 'error');
91
166
  return {
92
167
  ok: !hasError,
@@ -66,6 +66,7 @@ export type PrerequisiteCheckResult = {
66
66
  missing: Array<{
67
67
  path: string;
68
68
  description: string;
69
+ kind: 'absent' | 'body';
69
70
  }>;
70
71
  /**
71
72
  * Missing files inside a back-compat window (see
@@ -179,16 +179,16 @@ const KARPATHY_REVIEW = {
179
179
  // to KARPATHY_REVIEW. The body MUST carry the literal substring
180
180
  // `third-party-review` so a stub file with an empty envelope cannot
181
181
  // pass the gate. The full envelope lives at the JSON sibling path
182
- // (`rd/third-party-review.json`); this MD file is the human-readable
183
- // companion. The body is also expected to declare a `modelFamily`
184
- // gate diffs `rd/third-party-review.json.modelFamily` against
185
- // `rd/karpathy-review.md` parsed `modelFamily`); equality fails the
186
- // build. When `~/.peaks/config.json` lacks a `reviewer.providers`
187
- // section, the prereq is auto-marked `skipped: no-reviewer-config`
188
- // and the transition still passes (A4.3 fallbackOnError=skip).
182
+ // (`rd/third-party-review-<rid>.json`); this MD file is the human-readable
183
+ // companion. The body declares a `modelFamily` that the gate diffs against
184
+ // the karpathy review's: equality fails the build. When `~/.peaks/config.json`
185
+ // lacks a `reviewer.providers` section, the prereq is auto-marked `skipped:
186
+ // no-reviewer-config` and the transition still passes (A4.3 fallbackOnError=skip).
187
+ // The bare pre-rid path is the legacy tier, so sessions already on disk pass.
189
188
  const THIRD_PARTY_REVIEW = {
190
- relativePath: 'rd/third-party-review.md',
191
- description: 'v2.14.0 G4 third-party reviewer (peaks-reviewer skill) — must declare a `modelFamily` distinct from the karpathy-reviewer modelFamily (AC-4.4). Skipped when `~/.peaks/config.json` lacks `reviewer.providers` (>=2 entries); the prereq then resolves to a soft warning (`no-reviewer-config`) rather than a hard failure. The JSON sibling at `rd/third-party-review.json` carries the schema-validated ReviewerEnvelope (no free-form LLM JSON). v2.14.0 ships as a soft-warning prereq (1-minor-release back-compat window); v2.15.0 will hard-fail when the file is absent AND `reviewer.providers` is configured.',
189
+ relativePath: 'rd/third-party-review-<rid>.md',
190
+ legacyRelativePath: 'rd/third-party-review.md',
191
+ description: 'v2.14.0 G4 third-party reviewer (peaks-reviewer skill) — must declare a `modelFamily` distinct from the karpathy-reviewer modelFamily (AC-4.4). Skipped when `~/.peaks/config.json` lacks `reviewer.providers` (>=2 entries); the prereq then resolves to a soft warning (`no-reviewer-config`) rather than a hard failure. The JSON sibling at `rd/third-party-review-<rid>.json` carries the schema-validated ReviewerEnvelope (no free-form LLM JSON); the rid is part of both filenames so two slices in one session do not collide, and the bare location is accepted as the legacy tier. v2.14.0 ships as a soft-warning prereq (1-minor-release back-compat window); v2.15.0 will hard-fail when the file is absent AND `reviewer.providers` is configured.',
192
192
  mustContain: ['third-party-review', 'modelFamily'],
193
193
  backCompat: true,
194
194
  backCompatUntil: 'v2.15.0'
@@ -378,13 +378,13 @@ export async function checkPrerequisites(options) {
378
378
  warnings.push(softWarning);
379
379
  continue;
380
380
  }
381
- missing.push({ path: relative, description: prerequisite.description });
381
+ missing.push({ kind: 'absent', path: relative, description: prerequisite.description });
382
382
  continue;
383
383
  }
384
384
  // Read handed over as a thunk: the no-body-contract guard lives with the check.
385
385
  const bodyViolations = await bodyViolationsIfDeclared(prerequisite, () => readFile(absolute, 'utf8'));
386
386
  for (const description of bodyViolations) {
387
- missing.push({ path: relative, description });
387
+ missing.push({ kind: 'body', path: relative, description });
388
388
  }
389
389
  }
390
390
  // own `gateEvidence` DECLARATION must be true — every path it names must
@@ -424,12 +424,12 @@ export async function checkPrerequisites(options) {
424
424
  // artifact with no declaration is refused here, not waved through — a
425
425
  // deleted section is the shed this arm exists to close.
426
426
  const { describeJudgedRefusal, verifyJudgedDeclaration } = await import('../audit-independent/judged-declaration-check.js');
427
- for (const refusal of verifyJudgedDeclaration({
427
+ for (const gap of verifyJudgedDeclaration({
428
428
  projectRoot: options.projectRoot,
429
429
  sessionId: options.sessionId,
430
430
  requestId: options.requestId
431
431
  }).refusals) {
432
- missing.push({ path: refusal.artifact, description: describeJudgedRefusal(refusal) });
432
+ missing.push({ kind: 'body', path: gap.artifact, description: describeJudgedRefusal(gap) });
433
433
  }
434
434
  }
435
435
  const result = { ok: missing.length === 0, missing, warnings };
@@ -8,5 +8,11 @@
8
8
  export declare const PRD_TEMPLATE_BODY = "## Goals\n\n- ...\n\n## Non-goals\n\n- ...\n\n## Preserved behavior\n\n- ...\n\n## Acceptance criteria\n\n- ... (browser-verifiable when frontend is in scope)\n\n## Frontend delta (only when target is frontend)\n\n- pages / routes / components / states / permissions / data deps / edge cases\n- \u5F85\u8054\u8C03\u6001: ...\n- API contracts pending: ...\n\n## Risks and open questions\n\n- ...\n\n";
9
9
  export declare const UI_TEMPLATE_BODY = "## Affected surfaces\n\n- pages / routes / components / modals / states (loading, empty, error, hover, focus, active, responsive)\n- explicit out-of-scope surfaces (do not modify)\n\n## UX flow and page states\n\n- entry points, primary flow, secondary flows, exit points\n- state machine per surface when state transitions matter\n\n## Visual constraints\n\n- typography pair: ...\n- palette: ...\n- density and motion intensity dials: ...\n- rejected generic patterns\n\n## Interaction constraints\n\n- keyboard, focus order, ARIA roles, gesture support, accessibility minima\n\n## UI regression seeds\n\n- list of visible regressions QA must check against the prior state\n\n## Browser evidence\n\n- sanitized observations only \u2014 no login URLs, cookies, headers, tokens, storage state, browser traces, or screenshots/logs with PII / SSO / MFA material\n\n";
10
10
  export declare const RD_TEMPLATE_BODY = "## Red-line scope\n\n- in-scope files / routes / API paths / data models\n- explicit out-of-scope surfaces (do not modify, mock, delete, or replace)\n\n## Standards preflight\n\n- peaks standards init/update --project <path> --dry-run output paths and status\n- planned application: apply | review-only | blocked\n\n## OpenSpec linkage (when openspec/ exists)\n\n- change-id: <openspec change id>\n- entry validate: peaks openspec validate <change-id> data.valid status\n- to-rd projection: peaks openspec to-rd <change-id> artifact path\n- exit validate (after implementation): status\n\n## Coverage status\n\n- current total UT coverage: <percent>\n- new/changed code coverage: <percent>\n- gate verdict: pass | legacy-accepted | blocked\n\n## Slice contract\n\n- slice id, functional boundary, pre-refactor behavior, target structure, unit-test requirements, acceptance checks, rollback plan, commit boundary\n\n## Implementation evidence\n\n- diff paths, test commands + outputs, code review findings + fixes, security review findings + fixes, dry-run output\n\n## MCP usage (when external docs lookup was used)\n\n- capabilityId / tool / sanitized args\n- artifact path of stored result\n- no secrets, no full network bodies\n\n";
11
- export declare const QA_TEMPLATE_BODY = "## Red-line boundary check\n\n- in-scope changes seen in the diff (match PRD + RD scope)\n- out-of-scope changes flagged (any extra file, route, mock, fixture, behavior)\n- verdict: clean | boundary-violation\n\n## OpenSpec exit gate (when openspec/ exists)\n\n- change-id: <id>\n- peaks openspec validate <id> data.valid: true | false\n- issues: ...\n\n## Acceptance checks\n\n- per-criterion: check method, result (pass | fail | blocked), evidence path\n\n## Mandatory validation gates\n\n- unit tests: command + pass/fail + coverage delta\n- API validation (when applicable): request paths exercised, evidence\n- browser E2E (when frontend): headed gstack/browse/dist/browse visible-browser confirmation, sanitized route/actions, console/network observations\n- browser-error feedback loop: page errors, console exceptions, broken network, hydration failures \u2192 return-to-RD evidence\n- security check: tool used, findings, fixes, unresolved risks\n- performance check: tool used, baseline vs after numbers when available\n- validation report path\n\n## Regression matrix\n\n- list of surfaces / API paths / browser flows checked\n- pass/fail per row\n\n## Browser evidence\n\n- sanitized observations only \u2014 no login URLs, cookies, headers, tokens, storage state, browser traces, or screenshots/logs with PII / SSO / MFA material\n\n## Verdict\n\n- overall: pass | return-to-rd | blocked\n\n";
11
+ /**
12
+ * QA body. The OpenSpec exit gate is conditional: when the target repository
13
+ * has no `openspec/changes/`, the prompt form's `<id>` tokens are unfillable
14
+ * and a pristine artifact fails lint before QA can start. The N/A form records
15
+ * the same fact without a placeholder. Every other section is unconditional.
16
+ */
17
+ export declare function renderQaTemplateBody(hasOpenspecChanges: boolean): string;
12
18
  export declare const SC_TEMPLATE_BODY = "## Change impact\n\n- modules / files / routes / data models touched\n- blast radius: local | cross-cutting | release-critical\n- rollback strategy\n\n## Commit boundaries\n\n- one commit per OpenSpec heading (when openspec/ exists)\n- otherwise: list of slice ids \u2192 commit message + scope\n\n## Artifact retention\n\n- prd artifact: ...\n- rd artifact: ...\n- qa artifact: ...\n- ui artifact: ... (when UI involved)\n- coverage evidence: ...\n- code review evidence: ...\n\n## Sync / authorization\n\n";
@@ -100,7 +100,14 @@ export const RD_TEMPLATE_BODY = `## Red-line scope
100
100
  - no secrets, no full network bodies
101
101
 
102
102
  `;
103
- export const QA_TEMPLATE_BODY = `## Red-line boundary check
103
+ /**
104
+ * QA body. The OpenSpec exit gate is conditional: when the target repository
105
+ * has no `openspec/changes/`, the prompt form's `<id>` tokens are unfillable
106
+ * and a pristine artifact fails lint before QA can start. The N/A form records
107
+ * the same fact without a placeholder. Every other section is unconditional.
108
+ */
109
+ export function renderQaTemplateBody(hasOpenspecChanges) {
110
+ return `## Red-line boundary check
104
111
 
105
112
  - in-scope changes seen in the diff (match PRD + RD scope)
106
113
  - out-of-scope changes flagged (any extra file, route, mock, fixture, behavior)
@@ -108,10 +115,13 @@ export const QA_TEMPLATE_BODY = `## Red-line boundary check
108
115
 
109
116
  ## OpenSpec exit gate (when openspec/ exists)
110
117
 
111
- - change-id: <id>
118
+ ${hasOpenspecChanges
119
+ ? `- change-id: <id>
112
120
  - peaks openspec validate <id> data.valid: true | false
113
121
  - issues: ...
114
-
122
+ `
123
+ : `- N/A — openspec/changes/ is absent; no validate run
124
+ `}
115
125
  ## Acceptance checks
116
126
 
117
127
  - per-criterion: check method, result (pass | fail | blocked), evidence path
@@ -140,6 +150,7 @@ export const QA_TEMPLATE_BODY = `## Red-line boundary check
140
150
  - overall: pass | return-to-rd | blocked
141
151
 
142
152
  `;
153
+ }
143
154
  export const SC_TEMPLATE_BODY = `## Change impact
144
155
 
145
156
  - modules / files / routes / data models touched
@@ -6,6 +6,11 @@ import type { RequestType } from './artifact-prerequisites.js';
6
6
  * back-compat with external callers.
7
7
  */
8
8
  export type RequestArtifactRole = 'prd' | 'ui' | 'rd' | 'qa' | 'sc';
9
+ /** What every role's render needs beyond the request's own identity. */
10
+ export type RenderTemplateContext = {
11
+ requestType: RequestType | null;
12
+ projectRoot: string;
13
+ };
9
14
  /**
10
15
  * Handoff path helpers.
11
16
  *
@@ -26,4 +31,4 @@ export declare function formatHandoffPath(sessionId: string, role: string, reque
26
31
  export declare function formatCommitBoundaryPath(sessionId: string, requestId: string): string;
27
32
  /** Canonical path for the txt skill-usage lessons log under a session scope. */
28
33
  export declare function formatSkillUsageLessonsPath(sessionId: string): string;
29
- export declare function renderTemplate(role: RequestArtifactRole, requestId: string, sessionId: string, changeSlug: string, timestamp: string, requestType: RequestType | null): string;
34
+ export declare function renderTemplate(role: RequestArtifactRole, requestId: string, sessionId: string, changeSlug: string, timestamp: string, context: RenderTemplateContext): string;
@@ -1,4 +1,6 @@
1
- import { PRD_TEMPLATE_BODY, UI_TEMPLATE_BODY, RD_TEMPLATE_BODY, QA_TEMPLATE_BODY, SC_TEMPLATE_BODY } from './artifact-template-bodies.js';
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { PRD_TEMPLATE_BODY, UI_TEMPLATE_BODY, RD_TEMPLATE_BODY, renderQaTemplateBody, SC_TEMPLATE_BODY } from './artifact-template-bodies.js';
2
4
  /**
3
5
  * Handoff path helpers.
4
6
  *
@@ -102,7 +104,7 @@ ${renderTypeLine(requestType)}
102
104
  - state: draft
103
105
  `);
104
106
  }
105
- function renderQaTemplate(requestId, _sessionId, sessionId, timestamp, requestType) {
107
+ function renderQaTemplate(requestId, _sessionId, sessionId, timestamp, requestType, hasOpenspecChanges) {
106
108
  return (`# QA Request ${requestId}
107
109
 
108
110
  - session: ${sessionId}
@@ -111,7 +113,7 @@ function renderQaTemplate(requestId, _sessionId, sessionId, timestamp, requestTy
111
113
  - linked-ui: ${formatHandoffPath(sessionId, 'ui', requestId)} (when UI involved)
112
114
  ${renderTypeLine(requestType)}
113
115
  ` +
114
- QA_TEMPLATE_BODY +
116
+ renderQaTemplateBody(hasOpenspecChanges) +
115
117
  `## Status
116
118
 
117
119
  - created: ${timestamp}
@@ -150,7 +152,8 @@ ${renderTypeLine(requestType)}
150
152
  - state: draft
151
153
  `);
152
154
  }
153
- export function renderTemplate(role, requestId, sessionId, changeSlug, timestamp, requestType) {
155
+ export function renderTemplate(role, requestId, sessionId, changeSlug, timestamp, context) {
156
+ const { requestType } = context;
154
157
  switch (role) {
155
158
  case 'prd':
156
159
  return renderPrdTemplate(requestId, sessionId, changeSlug, timestamp, requestType);
@@ -159,7 +162,7 @@ export function renderTemplate(role, requestId, sessionId, changeSlug, timestamp
159
162
  case 'rd':
160
163
  return renderRdTemplate(requestId, sessionId, changeSlug, timestamp, requestType);
161
164
  case 'qa':
162
- return renderQaTemplate(requestId, sessionId, changeSlug, timestamp, requestType);
165
+ return renderQaTemplate(requestId, sessionId, changeSlug, timestamp, requestType, existsSync(join(context.projectRoot, 'openspec', 'changes')));
163
166
  case 'sc':
164
167
  return renderScTemplate(requestId, sessionId, changeSlug, timestamp, requestType);
165
168
  }
@@ -35,7 +35,7 @@ import { pathExists } from 'peaks-loop-shared/fs';
35
35
  import { CLI_VERSION } from 'peaks-loop-shared/version';
36
36
  import { isUnsafePathInput } from '../../shared/path-safety.js';
37
37
  import { compareReleaseVersions, missingPrerequisiteWarning } from './prerequisite-checks.js';
38
- import { resolvePrerequisiteAbsolutePathWithFallback, resolvePrerequisitePath, sessionRootsFor } from './prerequisite-path-resolver.js';
38
+ import { resolvePrerequisiteAbsolutePathWithFallback, sessionRootsFor } from './prerequisite-path-resolver.js';
39
39
  /** The one tracked acceptance list. Adding an entry is a reviewed diff the LLM
40
40
  * authors on the user's behalf; no source file keeps a second copy. */
41
41
  const BACKCOMPAT_ACCEPTANCE_PATH = '.peaks/lint/backcompat-expired-acceptance.json';
@@ -64,7 +64,7 @@ export function backcompatAcceptanceSeed(installedVersion = CLI_VERSION) {
64
64
  reviewBy
65
65
  },
66
66
  {
67
- path: 'rd/third-party-review.md',
67
+ path: 'rd/third-party-review-<rid>.md',
68
68
  until: 'v2.15.0',
69
69
  reason: 'No reviewer configured: peaks reviewer status reports no-reviewer-config, and the prerequisite table soft-skips this artifact in that state. Documented deviation: this commit-leg gate does not re-evaluate the reviewer.providers conditional, so the window is accepted here regardless of that config.',
70
70
  reviewBy
@@ -140,13 +140,14 @@ async function closedBackCompatWindows(requirements, installedVersion, requestId
140
140
  const closed = [];
141
141
  for (const prerequisite of requirements) {
142
142
  const until = prerequisite.backCompatUntil;
143
- const relative = resolvePrerequisitePath(prerequisite, requestId);
143
+ const relative = prerequisite.relativePath;
144
+ const aliases = [prerequisite.legacyRelativePath, ...(prerequisite.legacyRelativePaths ?? [])];
144
145
  const softWarning = missingPrerequisiteWarning(prerequisite, relative, installedVersion);
145
146
  if (until === undefined || softWarning?.expiredWindow === undefined)
146
147
  continue;
147
148
  const absolute = await resolvePrerequisiteAbsolutePathWithFallback(roots.canonical, roots.legacy, prerequisite, requestId);
148
149
  if (absolute === null)
149
- closed.push({ path: relative, until });
150
+ closed.push({ path: relative, until, aliases });
150
151
  }
151
152
  return closed;
152
153
  }
@@ -163,7 +164,8 @@ function reviewCapFor(installedVersion) {
163
164
  * target) and capped (`reviewBy` may sit at most two minors ahead), so a list
164
165
  * that only grows or that jumps far ahead cannot keep accepting. */
165
166
  function judgeClosedWindow(list, window, installedVersion) {
166
- const entry = list.accepted.find((candidate) => candidate.path === window.path && candidate.until === window.until);
167
+ const paths = [window.path, ...window.aliases];
168
+ const entry = list.accepted.find((candidate) => paths.includes(candidate.path) && candidate.until === window.until);
167
169
  if (entry === undefined) {
168
170
  return {
169
171
  violation: `expired back-compat window and no current acceptance: ${window.path} — ${window.until} (installed ${installedVersion}); ask the LLM to add an entry to ${BACKCOMPAT_ACCEPTANCE_PATH} with a reason and a future reviewBy (the LLM edits the tracked file on the user's behalf), or produce the artifact`
@@ -19,27 +19,26 @@ import type { ArtifactPrerequisite } from './artifact-prerequisites.js';
19
19
  *
20
20
  * The stem is what makes the code name WHICH artifact is missing — the branch
21
21
  * this replaced emitted the literal `mut-report-missing-deprecated-in-v2.14.0`
22
- * for EVERY `backCompat` prerequisite, so the `rd/third-party-review.md`
22
+ * for EVERY `backCompat` prerequisite, so the `rd/third-party-review-<rid>.md`
23
23
  * warning carried the same code as the `mut/mut-report.json` one and a
24
24
  * consumer filtering on it matched both. `backCompatUntil` keeps the
25
25
  * deprecation semantics legible and is per-prerequisite, because the two live
26
26
  * windows close in different releases (v2.14.0 and v2.15.0).
27
27
  *
28
- * The stem is taken verbatim: both prerequisites that carry `backCompat` name
29
- * a fixed path, so no character is rewritten.
28
+ * The stem is taken verbatim from `relativePath`, so no character is rewritten
29
+ * — including a `<rid>` placeholder.
30
30
  *
31
31
  * TWO KNOWN LIMITS OF THE STEM, stated so neither is read as a guarantee:
32
32
  * - a `<rid>`-templated soft prerequisite keeps the placeholder, producing
33
33
  * the LITERAL `<rid>-missing-deprecated-in-…` — the same code for every
34
- * request. The code is therefore not per-slice filterable. No live
35
- * prerequisite carries `backCompat` with a `<rid>` path, so nothing
36
- * filters on one today; the placeholder is the honest thing to print, and
37
- * making it per-slice would mean resolving the rid into a code a consumer
38
- * would have to know to match.
34
+ * request. One live prerequisite now does (`rd/third-party-review-<rid>.md`):
35
+ * its code is filterable by ARTIFACT CLASS but not by slice. That is the
36
+ * deliberate trade — resolving the rid into the code would give every
37
+ * slice a code a consumer would have to already know to match.
39
38
  * - the stem comes from the FILENAME only, so two prerequisites sharing a
40
39
  * stem collide (`x.md` and `x.json` both yield `x-…`). Measured 0 live
41
40
  * collisions, and the pair that exists (`mut/mut-report.json` vs
42
- * `rd/third-party-review.md`) differs by stem as well as by directory.
41
+ * `rd/third-party-review-<rid>.md`) differs by stem as well as by directory.
43
42
  */
44
43
  export declare function backCompatWarningCode(prerequisite: ArtifactPrerequisite): string;
45
44
  /** Negative when `a` predates `b`, positive when it follows, 0 when their
@@ -93,3 +92,29 @@ export declare function prerequisiteBodyViolations(prerequisite: ArtifactPrerequ
93
92
  * rather than the body).
94
93
  */
95
94
  export declare function bodyViolationsIfDeclared(prerequisite: ArtifactPrerequisite, read: () => Promise<string>): Promise<string[]>;
95
+ /**
96
+ * One unmet prerequisite as `checkPrerequisites` reports it. `path` and
97
+ * `description` are unchanged from the pre-`kind` shape so every existing
98
+ * consumer keeps reading them; `kind` is the machine-readable answer to "is the
99
+ * file absent, or present and failing its body contract?" — the question a
100
+ * consumer previously had to infer by parsing the prose.
101
+ *
102
+ * - `absent`: nothing resolved at `path`.
103
+ * - `body`: a file resolved and failed the body markers its prerequisite
104
+ * declares.
105
+ */
106
+ export type UnmetPrerequisite = {
107
+ path: string;
108
+ description: string;
109
+ kind: 'absent' | 'body';
110
+ };
111
+ /**
112
+ * The transition refusal's message line: the total plus the split a reader
113
+ * needs to tell "you have not written it" from "you wrote it and it does not
114
+ * satisfy the contract". A bare total sent a producer to produce a file that
115
+ * already existed.
116
+ *
117
+ * A zero count is omitted, so the line never reads
118
+ * `…: 0 missing artifacts, 1 present but invalid`.
119
+ */
120
+ export declare function unmetPrerequisiteMessage(role: string, newState: string, sessionId: string, missing: ReadonlyArray<Pick<UnmetPrerequisite, 'kind'>>): string;
@@ -26,27 +26,26 @@ const UNDECLARED_WINDOW = 'a-future-release';
26
26
  *
27
27
  * The stem is what makes the code name WHICH artifact is missing — the branch
28
28
  * this replaced emitted the literal `mut-report-missing-deprecated-in-v2.14.0`
29
- * for EVERY `backCompat` prerequisite, so the `rd/third-party-review.md`
29
+ * for EVERY `backCompat` prerequisite, so the `rd/third-party-review-<rid>.md`
30
30
  * warning carried the same code as the `mut/mut-report.json` one and a
31
31
  * consumer filtering on it matched both. `backCompatUntil` keeps the
32
32
  * deprecation semantics legible and is per-prerequisite, because the two live
33
33
  * windows close in different releases (v2.14.0 and v2.15.0).
34
34
  *
35
- * The stem is taken verbatim: both prerequisites that carry `backCompat` name
36
- * a fixed path, so no character is rewritten.
35
+ * The stem is taken verbatim from `relativePath`, so no character is rewritten
36
+ * — including a `<rid>` placeholder.
37
37
  *
38
38
  * TWO KNOWN LIMITS OF THE STEM, stated so neither is read as a guarantee:
39
39
  * - a `<rid>`-templated soft prerequisite keeps the placeholder, producing
40
40
  * the LITERAL `<rid>-missing-deprecated-in-…` — the same code for every
41
- * request. The code is therefore not per-slice filterable. No live
42
- * prerequisite carries `backCompat` with a `<rid>` path, so nothing
43
- * filters on one today; the placeholder is the honest thing to print, and
44
- * making it per-slice would mean resolving the rid into a code a consumer
45
- * would have to know to match.
41
+ * request. One live prerequisite now does (`rd/third-party-review-<rid>.md`):
42
+ * its code is filterable by ARTIFACT CLASS but not by slice. That is the
43
+ * deliberate trade — resolving the rid into the code would give every
44
+ * slice a code a consumer would have to already know to match.
46
45
  * - the stem comes from the FILENAME only, so two prerequisites sharing a
47
46
  * stem collide (`x.md` and `x.json` both yield `x-…`). Measured 0 live
48
47
  * collisions, and the pair that exists (`mut/mut-report.json` vs
49
- * `rd/third-party-review.md`) differs by stem as well as by directory.
48
+ * `rd/third-party-review-<rid>.md`) differs by stem as well as by directory.
50
49
  */
51
50
  export function backCompatWarningCode(prerequisite) {
52
51
  const stem = basename(prerequisite.relativePath, extname(prerequisite.relativePath));
@@ -201,3 +200,23 @@ export async function bodyViolationsIfDeclared(prerequisite, read) {
201
200
  return [];
202
201
  return prerequisiteBodyViolations(prerequisite, await read());
203
202
  }
203
+ /**
204
+ * The transition refusal's message line: the total plus the split a reader
205
+ * needs to tell "you have not written it" from "you wrote it and it does not
206
+ * satisfy the contract". A bare total sent a producer to produce a file that
207
+ * already existed.
208
+ *
209
+ * A zero count is omitted, so the line never reads
210
+ * `…: 0 missing artifacts, 1 present but invalid`.
211
+ */
212
+ export function unmetPrerequisiteMessage(role, newState, sessionId, missing) {
213
+ const absent = missing.filter((entry) => entry.kind === 'absent').length;
214
+ const invalid = missing.length - absent;
215
+ const counts = [
216
+ ...(absent === 0 ? [] : [`${absent} missing artifact${absent === 1 ? '' : 's'}`]),
217
+ ...(invalid === 0 ? [] : [`${invalid} present but invalid`])
218
+ ].join(', ');
219
+ const total = missing.length;
220
+ return (`Cannot transition ${role} to ${newState}: ${total} unmet requirement${total === 1 ? '' : 's'}` +
221
+ `${counts === '' ? '' : `: ${counts}`} under .peaks/_runtime/${sessionId}/`);
222
+ }
@@ -0,0 +1,24 @@
1
+ export type MarkQaInitiatedOptions = {
2
+ projectRoot: string;
3
+ sessionId: string;
4
+ };
5
+ export type MarkQaInitiatedResult = {
6
+ /** Absolute path of the marker. */
7
+ path: string;
8
+ /** `true` only on the call that created the file; `false` when it already existed. */
9
+ created: boolean;
10
+ };
11
+ /**
12
+ * Create `.peaks/_runtime/<sessionId>/qa/.initiated` if it is absent.
13
+ *
14
+ * Idempotent by construction: the create is a single `O_EXCL` write (`flag:
15
+ * 'wx'`), so an existing marker — including one carrying bytes — is never
16
+ * truncated, and a concurrent caller sees `EEXIST` rather than a second write.
17
+ * The marker's content is the empty string, matching the shape `request init`
18
+ * has always produced.
19
+ *
20
+ * This function touches nothing under `qa/requests/`: the request artifact is
21
+ * the caller's, and this verb exists so it never has to be deleted or rewritten
22
+ * to reach the marker.
23
+ */
24
+ export declare function markQaInitiated(options: MarkQaInitiatedOptions): Promise<MarkQaInitiatedResult>;
@@ -0,0 +1,36 @@
1
+ // The session-scoped `qa/.initiated` marker, written from two callers:
2
+ // `createRequestArtifact` (its success path, after the request file is on disk)
3
+ // and `peaks request mark-qa-initiated` (the in-order path for a QA role that
4
+ // wrote its artifact first). Keeping one writer means the two paths cannot
5
+ // drift on content, permissions, or idempotence.
6
+ import { mkdir, writeFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { guardRuntimeSegment, runtimeRoot } from '../../shared/runtime-root.js';
9
+ /**
10
+ * Create `.peaks/_runtime/<sessionId>/qa/.initiated` if it is absent.
11
+ *
12
+ * Idempotent by construction: the create is a single `O_EXCL` write (`flag:
13
+ * 'wx'`), so an existing marker — including one carrying bytes — is never
14
+ * truncated, and a concurrent caller sees `EEXIST` rather than a second write.
15
+ * The marker's content is the empty string, matching the shape `request init`
16
+ * has always produced.
17
+ *
18
+ * This function touches nothing under `qa/requests/`: the request artifact is
19
+ * the caller's, and this verb exists so it never has to be deleted or rewritten
20
+ * to reach the marker.
21
+ */
22
+ export async function markQaInitiated(options) {
23
+ const qaDir = runtimeRoot(options.projectRoot).join(guardRuntimeSegment(options.sessionId, 'session id'), guardRuntimeSegment('qa', 'role'));
24
+ const path = join(qaDir, '.initiated');
25
+ await mkdir(qaDir, { recursive: true });
26
+ try {
27
+ await writeFile(path, '', { encoding: 'utf8', flag: 'wx' });
28
+ }
29
+ catch (error) {
30
+ if (error.code === 'EEXIST') {
31
+ return { path, created: false };
32
+ }
33
+ throw error;
34
+ }
35
+ return { path, created: true };
36
+ }
@@ -27,5 +27,14 @@ export type ArtifactMetadata = {
27
27
  * `request-artifact-service.ts` when the type's provenance was added; the only
28
28
  * behaviour change is `requestTypeSource`, which records whether a usable
29
29
  * `- type:` line was actually present.
30
+ *
31
+ * THIS READER IS THE CANONICAL `- type:` RULE. `.husky/pipeline/request-type-line.mjs`
32
+ * reimplements it because that module must load under bare `node` and cannot import
33
+ * `src/**`, and `tests/unit/hooks/pipeline-verify-type-derivation.test.ts` drives
34
+ * both readers over one corpus so they cannot drift. The rule: each line is
35
+ * trimmed, the bullet is a hyphen, the value is everything after `type:` and must
36
+ * be a request type (`isRequestType`), and the LAST usable line wins — an unusable
37
+ * later line does not erase an earlier usable one, and no usable line leaves the
38
+ * default with source `default`.
30
39
  */
31
40
  export declare function extractMetadata(markdown: string): ArtifactMetadata;
@@ -5,6 +5,15 @@ import { readArtifactState } from './request-artifact-state-helpers.js';
5
5
  * `request-artifact-service.ts` when the type's provenance was added; the only
6
6
  * behaviour change is `requestTypeSource`, which records whether a usable
7
7
  * `- type:` line was actually present.
8
+ *
9
+ * THIS READER IS THE CANONICAL `- type:` RULE. `.husky/pipeline/request-type-line.mjs`
10
+ * reimplements it because that module must load under bare `node` and cannot import
11
+ * `src/**`, and `tests/unit/hooks/pipeline-verify-type-derivation.test.ts` drives
12
+ * both readers over one corpus so they cannot drift. The rule: each line is
13
+ * trimmed, the bullet is a hyphen, the value is everything after `type:` and must
14
+ * be a request type (`isRequestType`), and the LAST usable line wins — an unusable
15
+ * later line does not erase an earlier usable one, and no usable line leaves the
16
+ * default with source `default`.
8
17
  */
9
18
  export function extractMetadata(markdown) {
10
19
  const state = readArtifactState(markdown) ?? 'unknown';