peaks-loop 4.1.7 → 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 (73) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +47 -0
  3. package/config/eslint/tsconfig.lint.json +1 -0
  4. package/dist/cli/commands/dispatch-from-dag.js +17 -0
  5. package/dist/cli/commands/job-commands.js +15 -5
  6. package/dist/cli/commands/lint-baseline-command.d.ts +15 -0
  7. package/dist/cli/commands/lint-baseline-command.js +64 -0
  8. package/dist/cli/commands/lint-commands.js +27 -51
  9. package/dist/cli/commands/request-command-options.d.ts +6 -0
  10. package/dist/cli/commands/request-commands.js +2 -0
  11. package/dist/cli/commands/request-mark-qa-initiated-command.d.ts +3 -0
  12. package/dist/cli/commands/request-mark-qa-initiated-command.js +80 -0
  13. package/dist/cli/commands/request-transition-failures.js +1 -0
  14. package/dist/cli/commands/reviewer-commands.d.ts +6 -6
  15. package/dist/cli/commands/reviewer-commands.js +154 -56
  16. package/dist/cli/commands/reviewer-config-commands.d.ts +9 -0
  17. package/dist/cli/commands/reviewer-config-commands.js +133 -0
  18. package/dist/services/artifacts/artifact-lint-service.js +102 -27
  19. package/dist/services/artifacts/artifact-prerequisites.d.ts +1 -0
  20. package/dist/services/artifacts/artifact-prerequisites.js +13 -13
  21. package/dist/services/artifacts/artifact-template-bodies.d.ts +7 -1
  22. package/dist/services/artifacts/artifact-template-bodies.js +14 -3
  23. package/dist/services/artifacts/artifact-templates.d.ts +6 -1
  24. package/dist/services/artifacts/artifact-templates.js +8 -5
  25. package/dist/services/artifacts/backcompat-acceptance.js +7 -5
  26. package/dist/services/artifacts/prerequisite-checks.d.ts +34 -9
  27. package/dist/services/artifacts/prerequisite-checks.js +28 -9
  28. package/dist/services/artifacts/qa-initiated-marker.d.ts +24 -0
  29. package/dist/services/artifacts/qa-initiated-marker.js +36 -0
  30. package/dist/services/artifacts/request-artifact-metadata.d.ts +9 -0
  31. package/dist/services/artifacts/request-artifact-metadata.js +9 -0
  32. package/dist/services/artifacts/request-artifact-service.js +6 -10
  33. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +2 -1
  34. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -3
  35. package/dist/services/dispatch/isolation-lease.d.ts +3 -2
  36. package/dist/services/dispatch/isolation-lease.js +15 -6
  37. package/dist/services/job/subagent-job-wrapper.d.ts +20 -7
  38. package/dist/services/job/subagent-job-wrapper.js +53 -5
  39. package/dist/services/lint/eslint-report.d.ts +19 -0
  40. package/dist/services/lint/eslint-report.js +60 -0
  41. package/dist/services/lint/eslint-runner-support.d.ts +18 -1
  42. package/dist/services/lint/eslint-runner-support.js +35 -2
  43. package/dist/services/lint/eslint-runner-types.d.ts +21 -1
  44. package/dist/services/lint/eslint-runner.js +43 -33
  45. package/dist/services/prd/gate-evidence-derivation.d.ts +2 -4
  46. package/dist/services/prd/gate-evidence-derivation.js +3 -1
  47. package/dist/services/qa/bdd-test-style-contract.d.ts +17 -0
  48. package/dist/services/qa/bdd-test-style-contract.js +41 -0
  49. package/dist/services/qa/bdd-test-style-verifier.d.ts +9 -6
  50. package/dist/services/qa/bdd-test-style-verifier.js +24 -37
  51. package/dist/services/rd/reviewer-dispatch-policy.d.ts +18 -14
  52. package/dist/services/rd/reviewer-dispatch-policy.js +14 -11
  53. package/dist/services/release/release-state.js +20 -5
  54. package/dist/services/reviewer/model-family.js +1 -1
  55. package/dist/services/reviewer/reviewer-artifacts.d.ts +12 -0
  56. package/dist/services/reviewer/reviewer-artifacts.js +67 -0
  57. package/dist/services/reviewer/reviewer-config-write.d.ts +18 -0
  58. package/dist/services/reviewer/reviewer-config-write.js +71 -0
  59. package/dist/services/reviewer/reviewer-config.d.ts +33 -5
  60. package/dist/services/reviewer/reviewer-config.js +102 -46
  61. package/dist/services/reviewer/reviewer-envelopes.d.ts +8 -0
  62. package/dist/services/reviewer/reviewer-envelopes.js +53 -0
  63. package/dist/services/reviewer/reviewer-service.d.ts +7 -4
  64. package/dist/services/reviewer/reviewer-service.js +46 -52
  65. package/dist/services/reviewer/reviewer-types.d.ts +9 -1
  66. package/dist/services/session/getSessionDir.js +16 -7
  67. package/dist/services/web/daemon-registry.d.ts +6 -4
  68. package/dist/services/web/daemon-registry.js +92 -17
  69. package/package.json +5 -5
  70. package/schemas/reviewer-envelope.schema.json +1 -1
  71. package/skills/bee/peaks-reviewer/SKILL.md +20 -4
  72. package/skills/bee/peaks-reviewer/references/reviewer-schema.md +12 -7
  73. package/skills/bee/peaks-security-audit/SKILL.md +20 -0
@@ -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';
@@ -1,8 +1,8 @@
1
1
  import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
- import { existsSync } from 'node:fs';
3
2
  import { dirname, join } from 'node:path';
4
3
  import { isDirectory, listDirectories } from 'peaks-loop-shared/fs';
5
4
  import { checkPrerequisites, DEFAULT_REQUEST_TYPE, isRequestType, VALID_REQUEST_TYPES } from './artifact-prerequisites.js';
5
+ import { markQaInitiated } from './qa-initiated-marker.js';
6
6
  import { ensureSession, getSessionIdCanonical } from '../session/session-manager.js';
7
7
  // removed with the change-id axis. The change-id binding file is
8
8
  // gone; request-artifact callers pass `options.sessionId` explicitly
@@ -147,7 +147,7 @@ export async function createRequestArtifact(options) {
147
147
  const content = renderTemplate(options.role, options.requestId, sessionId, sessionSlug, timestamp,
148
148
  // `null`, not the default: an untyped request records no type, so the
149
149
  // reader's substitution stays visible as a substitution.
150
- options.requestType ?? null);
150
+ { requestType: options.requestType ?? null, projectRoot: options.projectRoot });
151
151
  if (options.apply !== true) {
152
152
  // session-axis dir (`.peaks/_runtime/<sid>/`). Pre-resolved here
153
153
  // so dry-run output reports the canonical scope location.
@@ -166,14 +166,10 @@ export async function createRequestArtifact(options) {
166
166
  await mkdir(dirname(path), { recursive: true });
167
167
  await writeFile(path, content, 'utf8');
168
168
  // Create QA initiated marker so rd:qa-handoff gate can verify QA was invoked.
169
- // The marker lives under the SESSION dir (canonical post-F3 home).
169
+ // The writer is shared with `peaks request mark-qa-initiated`, the in-order
170
+ // path for a QA role that wrote its artifact before this command ran.
170
171
  if (options.role === 'qa') {
171
- const qaDir = runtimeRoot(options.projectRoot).join(guardRuntimeSegment(sessionId, 'session id'), guardRuntimeSegment('qa', 'role'));
172
- const initiatedPath = join(qaDir, '.initiated');
173
- if (!existsSync(initiatedPath)) {
174
- await mkdir(qaDir, { recursive: true });
175
- await writeFile(initiatedPath, '', 'utf8');
176
- }
172
+ await markQaInitiated({ projectRoot: options.projectRoot, sessionId });
177
173
  }
178
174
  return {
179
175
  role: options.role,
@@ -403,7 +399,7 @@ export async function transitionRequestArtifact(options) {
403
399
  if (lintReport !== null && !lintReport.ok) {
404
400
  const errors = lintReport.findings.filter((f) => f.severity === 'error');
405
401
  if (errors.length > 0) {
406
- throw new LintGateError(options.role, options.newState, errors);
402
+ throw new LintGateError(options.role, options.newState, errors, lintReport.path);
407
403
  }
408
404
  }
409
405
  }
@@ -31,7 +31,8 @@ export declare class LintGateError extends Error {
31
31
  readonly newState: RequestArtifactState;
32
32
  readonly errorCount: number;
33
33
  readonly findings: ReadonlyArray<LintGateFinding>;
34
- constructor(role: RequestArtifactRole, newState: RequestArtifactState, findings: ReadonlyArray<LintGateFinding>);
34
+ readonly path: string;
35
+ constructor(role: RequestArtifactRole, newState: RequestArtifactState, findings: ReadonlyArray<LintGateFinding>, path: string);
35
36
  }
36
37
  export declare class TypeSanityViolationError extends Error {
37
38
  readonly code = "TYPE_SANITY_VIOLATION";
@@ -1,3 +1,4 @@
1
+ import { unmetPrerequisiteMessage } from './prerequisite-checks.js';
1
2
  export const ALLOWED_STATES_PER_ROLE = {
2
3
  prd: ['draft', 'confirmed-by-user', 'handed-off', 'blocked'],
3
4
  ui: ['draft', 'direction-locked', 'handed-off', 'blocked'],
@@ -22,7 +23,7 @@ export class PrerequisitesNotSatisfiedError extends Error {
22
23
  */
23
24
  warnings;
24
25
  constructor(role, newState, sessionId, missing, warnings = []) {
25
- super(`Cannot transition ${role} to ${newState}: ${missing.length} unmet requirement${missing.length === 1 ? '' : 's'} under .peaks/_runtime/${sessionId}/`);
26
+ super(unmetPrerequisiteMessage(role, newState, sessionId, missing));
26
27
  this.name = 'PrerequisitesNotSatisfiedError';
27
28
  this.role = role;
28
29
  this.newState = newState;
@@ -37,14 +38,16 @@ export class LintGateError extends Error {
37
38
  newState;
38
39
  errorCount;
39
40
  findings;
40
- constructor(role, newState, findings) {
41
- super(`Cannot transition ${role} to ${newState}: ${findings.length} lint error(s) found in artifact. ` +
41
+ path;
42
+ constructor(role, newState, findings, path) {
43
+ super(`Cannot transition ${role} to ${newState}: ${findings.length} lint error(s) found in ${path}. ` +
42
44
  'Fix lint errors or use --allow-incomplete to bypass.');
43
45
  this.name = 'LintGateError';
44
46
  this.role = role;
45
47
  this.newState = newState;
46
48
  this.findings = findings;
47
49
  this.errorCount = findings.length;
50
+ this.path = path;
48
51
  }
49
52
  }
50
53
  export class TypeSanityViolationError extends Error {
@@ -1,3 +1,4 @@
1
+ import { spawn as childProcessSpawn } from 'node:child_process';
1
2
  /**
2
3
  * lease by shelling out to `peaks worktree spawn` (avoid re-implementing
3
4
  * the lease-write + git-worktree-add sequence in this file). The CLI
@@ -15,7 +16,7 @@ export declare function spawnWorktreeLease(args: {
15
16
  rid: string;
16
17
  role: string;
17
18
  purpose: string;
18
- }): Promise<{
19
+ }, spawnImplOverride?: typeof childProcessSpawn): Promise<{
19
20
  leaseId: string;
20
21
  path: string;
21
22
  branch: string;
@@ -36,6 +37,6 @@ export declare function spawnContainerLease(args: {
36
37
  rid: string;
37
38
  role: string;
38
39
  purpose: string;
39
- }): Promise<{
40
+ }, spawnImplOverride?: typeof childProcessSpawn): Promise<{
40
41
  leaseId: string;
41
42
  }>;
@@ -10,9 +10,11 @@ import { spawn as childProcessSpawn } from 'node:child_process';
10
10
  * dispatch is already async, the lease is a few hundred ms of FS work,
11
11
  * and we need the leaseId before we build the dispatch record.
12
12
  */
13
- export function spawnWorktreeLease(args) {
13
+ export function spawnWorktreeLease(args, spawnImplOverride = childProcessSpawn) {
14
+ // A same-file alias, not the parameter, is what the spawn guard resolves.
15
+ const spawnImpl = spawnImplOverride ?? childProcessSpawn;
14
16
  return new Promise((resolve, reject) => {
15
- const child = childProcessSpawn(process.execPath, [
17
+ const child = spawnImpl(process.execPath, [
16
18
  // The compiled CLI lives in dist/cli/peaks.js. We pass the entry
17
19
  // through node so the test suite (which also runs on the same
18
20
  // process) and the production binary share the same path. When
@@ -92,9 +94,11 @@ export function spawnWorktreeLease(args) {
92
94
  * path because the envelope surfaces a different set of
93
95
  * fields (image + containerId; see container-lease.ts).
94
96
  */
95
- export function spawnContainerLease(args) {
97
+ export function spawnContainerLease(args, spawnImplOverride = childProcessSpawn) {
98
+ // A same-file alias, not the parameter, is what the spawn guard resolves.
99
+ const spawnImpl = spawnImplOverride ?? childProcessSpawn;
96
100
  return new Promise((resolve, reject) => {
97
- const child = childProcessSpawn(process.execPath, [
101
+ const child = spawnImpl(process.execPath, [
98
102
  process.argv[1] ?? '',
99
103
  'container',
100
104
  'spawn',
@@ -142,8 +146,13 @@ export function spawnContainerLease(args) {
142
146
  return;
143
147
  }
144
148
  resolve({ leaseId: env.data.lease.leaseId });
149
+ // Same deferral as spawnWorktreeLease: the unref must not run
150
+ // before the close, or the parent's event loop empties before
151
+ // the buffered stdout drains and the caller sees an empty
152
+ // envelope with exit 0.
153
+ setImmediate(() => {
154
+ child.unref();
155
+ });
145
156
  });
146
- // See spawnWorktreeLease above for the rationale.
147
- child.unref();
148
157
  });
149
158
  }
@@ -25,11 +25,24 @@ export declare class SubAgentJobWrapper {
25
25
  constructor(store: JobStateStore, dispatch: DispatchFn);
26
26
  wrap(input: WrapInput): Promise<WrapOutput>;
27
27
  canCheckpointDone(jobId: string, batchId: string): boolean;
28
- cleanup(input: {
29
- jobId: string;
30
- batchId: string;
31
- force: boolean;
32
- }): Promise<{
33
- cleaned: boolean;
34
- }>;
28
+ cleanup(input: CleanupInput): Promise<CleanupResult>;
29
+ }
30
+ export interface CleanupInput {
31
+ jobId: string;
32
+ batchId: string;
33
+ force: boolean;
34
+ /**
35
+ * On-disk ledger context, supplied by the CLI. Omitted by same-process
36
+ * callers, which keep the in-memory map above as their pending set.
37
+ */
38
+ projectRoot?: string;
39
+ sessionId?: string;
40
+ }
41
+ export interface CleanupResult {
42
+ cleaned: boolean;
43
+ cleanedRecords: string[];
44
+ skipped: {
45
+ recordPath: string;
46
+ reason: string;
47
+ }[];
35
48
  }
@@ -1,3 +1,6 @@
1
+ import { getErrorMessage } from 'peaks-loop-shared/result';
2
+ import { readActiveDispatchIndex } from '../dispatch/active-dispatch-index.js';
3
+ import { markCompleted } from '../dispatch/dispatch-record-writer.js';
1
4
  export class SubAgentJobWrapper {
2
5
  store;
3
6
  dispatch;
@@ -25,10 +28,55 @@ export class SubAgentJobWrapper {
25
28
  return !set?.has(batchId);
26
29
  }
27
30
  async cleanup(input) {
28
- const set = this.dispatchedBatches.get(input.jobId);
29
- if (!set?.has(input.batchId))
30
- return { cleaned: true };
31
- set.delete(input.batchId);
32
- return { cleaned: true };
31
+ this.dispatchedBatches.get(input.jobId)?.delete(input.batchId);
32
+ if (input.projectRoot === undefined || input.sessionId === undefined) {
33
+ return { cleaned: true, cleanedRecords: [], skipped: [] };
34
+ }
35
+ return cleanLedgerBatch({
36
+ projectRoot: input.projectRoot,
37
+ sessionId: input.sessionId,
38
+ batchId: input.batchId,
39
+ force: input.force
40
+ });
41
+ }
42
+ }
43
+ /**
44
+ * Clean a batch by its rows in `.peaks/_sub_agents/<sessionId>/active-dispatches.json`
45
+ * — the ledger the dispatching process wrote, not a set a fresh CLI process
46
+ * cannot have populated.
47
+ *
48
+ * A row is finalized (`status: 'done'` on the record, row removed from the
49
+ * index) when it is `queued`, the same rows `sub-agent finalize --batch` acts
50
+ * on. `--force` extends that to rows in any other status. An absent batch
51
+ * cleans nothing and reports `cleaned: false`: "nothing to clean" must not
52
+ * read as "cleaned it".
53
+ */
54
+ function cleanLedgerBatch(input) {
55
+ const result = { cleaned: false, cleanedRecords: [], skipped: [] };
56
+ const rows = Object.values(readActiveDispatchIndex(input.projectRoot, input.sessionId));
57
+ for (const entry of rows) {
58
+ if (entry.batchId !== input.batchId)
59
+ continue;
60
+ if (entry.status !== 'queued' && !input.force) {
61
+ result.skipped.push({
62
+ recordPath: entry.recordPath,
63
+ reason: `status is ${entry.status}; pass --force to clean it anyway`
64
+ });
65
+ continue;
66
+ }
67
+ try {
68
+ markCompleted({
69
+ recordPath: entry.recordPath,
70
+ projectRoot: input.projectRoot,
71
+ status: 'done',
72
+ outcome: 'success'
73
+ });
74
+ result.cleanedRecords.push(entry.recordPath);
75
+ }
76
+ catch (error) {
77
+ result.skipped.push({ recordPath: entry.recordPath, reason: getErrorMessage(error) });
78
+ }
33
79
  }
80
+ result.cleaned = result.cleanedRecords.length > 0;
81
+ return result;
34
82
  }