peaks-loop 4.1.5 → 4.1.6

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 (86) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +36 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  5. package/dist/cli/commands/best-practice-scan-command.d.ts +11 -6
  6. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  7. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  8. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  9. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  10. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  11. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  12. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  13. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  14. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  15. package/dist/cli/commands/dispatch-prompt-composition.d.ts +1 -1
  16. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  17. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  18. package/dist/cli/commands/openspec-command-shared.js +2 -2
  19. package/dist/cli/commands/request-transition-failures.js +31 -4
  20. package/dist/cli/commands/request-transition-preflight.js +1 -1
  21. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  22. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  23. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  24. package/dist/cli/program.js +0 -2
  25. package/dist/services/artifacts/artifact-contract-block.js +21 -2
  26. package/dist/services/artifacts/artifact-prerequisites.js +7 -7
  27. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  28. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  29. package/dist/services/artifacts/request-artifact-service.js +22 -20
  30. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +9 -1
  31. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -4
  32. package/dist/services/audit-independent/judged-declaration-check.d.ts +1 -0
  33. package/dist/services/audit-independent/judged-declaration-check.js +62 -1
  34. package/dist/services/context/build-dispatch-system-prompt.d.ts +5 -9
  35. package/dist/services/context/build-dispatch-system-prompt.js +11 -11
  36. package/dist/services/context/post-compact-reinjection.js +1 -1
  37. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  38. package/dist/services/dispatch/test-tool-detection.js +12 -1
  39. package/dist/services/evidence/evidence-generator.js +8 -4
  40. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  41. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  42. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  43. package/dist/services/openspec/openspec-archive-service.js +6 -6
  44. package/dist/services/scan/file-size-baseline.d.ts +13 -6
  45. package/dist/services/scan/file-size-baseline.js +54 -31
  46. package/dist/services/scan/file-size-scan.d.ts +7 -14
  47. package/dist/services/scan/file-size-scan.js +6 -1
  48. package/dist/services/scan/type-corroboration.d.ts +32 -0
  49. package/dist/services/scan/type-corroboration.js +51 -0
  50. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  51. package/dist/services/scan/type-sanity-service.js +10 -19
  52. package/dist/services/security/safe-settings-path.d.ts +5 -0
  53. package/dist/services/security/safe-settings-path.js +64 -8
  54. package/dist/services/skill/resume-detector.js +8 -8
  55. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  56. package/dist/services/workflow/pipeline-verify-gate-support.js +32 -38
  57. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  58. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  59. package/dist/services/workflow/pipeline-verify-service.js +26 -27
  60. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  61. package/dist/services/workflow/request-type-resolution.js +130 -0
  62. package/dist/services/workflow/workflow-skip-service.d.ts +1 -0
  63. package/dist/services/workflow/workflow-skip-service.js +19 -21
  64. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  65. package/dist/services/workflow/workflow-state-store.js +26 -1
  66. package/dist/shared/incrementing-number.d.ts +23 -2
  67. package/dist/shared/incrementing-number.js +57 -15
  68. package/package.json +5 -7
  69. package/skills/bee/peaks-prd/SKILL.md +3 -2
  70. package/skills/peaks-code/SKILL.md +32 -15
  71. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  72. package/dist/cli/commands/vm-command-shared.js +0 -23
  73. package/dist/cli/commands/vm-commands.d.ts +0 -3
  74. package/dist/cli/commands/vm-commands.js +0 -45
  75. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  76. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  77. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  78. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  79. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  80. package/dist/cli/commands/vm-release-command.js +0 -101
  81. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  82. package/dist/cli/commands/vm-spawn-command.js +0 -177
  83. package/dist/cli/commands/vm-status-command.d.ts +0 -3
  84. package/dist/cli/commands/vm-status-command.js +0 -50
  85. package/dist/services/vm/vm-lease.d.ts +0 -40
  86. package/dist/services/vm/vm-lease.js +0 -160
@@ -1,6 +1,7 @@
1
1
  import { join, dirname, basename } from 'node:path';
2
2
  import { readFile, readdir } from 'node:fs/promises';
3
3
  import { pathExists } from 'peaks-loop-shared/fs';
4
+ import { NUMBERED_PREFIX_RE, slugifyDescription } from '../../shared/incrementing-number.js';
4
5
  import { emitPrereqTransitionEvent } from './prerequisite-transition-event.js';
5
6
  import { isUnsafePathInput } from '../../shared/path-safety.js';
6
7
  import { bodyViolationsIfDeclared, missingPrerequisiteWarning } from './prerequisite-checks.js';
@@ -359,7 +360,9 @@ async function resolvePrerequisiteAbsolutePath(sessionRoot, prerequisite, reques
359
360
  return null;
360
361
  }
361
362
  const dir = dirname(exact);
362
- const targetSuffix = `-${basename(exact)}`;
363
+ // The on-disk suffix is the SLUG of this basename — the writer lowercases the
364
+ // rid — so a mixed-case rid used to be reported absent with the file on disk.
365
+ const suffix = `-${slugifyDescription(basename(exact).replace(/\.md$/, ''))}.md`;
363
366
  let entries;
364
367
  try {
365
368
  entries = await readdir(dir);
@@ -368,7 +371,7 @@ async function resolvePrerequisiteAbsolutePath(sessionRoot, prerequisite, reques
368
371
  // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
369
372
  return null;
370
373
  }
371
- const match = entries.find((name) => /^\d+-/.test(name) && name.endsWith(targetSuffix));
374
+ const match = entries.find((name) => NUMBERED_PREFIX_RE.test(name) && name.endsWith(suffix));
372
375
  return match ? join(dir, match) : null;
373
376
  }
374
377
  export async function checkPrerequisites(options) {
@@ -456,16 +459,13 @@ export async function checkPrerequisites(options) {
456
459
  // re-hashes them, so a repair after the audit is refused by name. An
457
460
  // artifact with no declaration is refused here, not waved through — a
458
461
  // deleted section is the shed this arm exists to close.
459
- const { verifyJudgedDeclaration } = await import('../audit-independent/judged-declaration-check.js');
462
+ const { describeJudgedRefusal, verifyJudgedDeclaration } = await import('../audit-independent/judged-declaration-check.js');
460
463
  for (const refusal of verifyJudgedDeclaration({
461
464
  projectRoot: options.projectRoot,
462
465
  sessionId: options.sessionId,
463
466
  requestId: options.requestId
464
467
  }).refusals) {
465
- missing.push({
466
- path: refusal.artifact,
467
- description: `Judged declaration ${refusal.code} at ${refusal.path}`
468
- });
468
+ missing.push({ path: refusal.artifact, description: describeJudgedRefusal(refusal) });
469
469
  }
470
470
  }
471
471
  const result = { ok: missing.length === 0, missing, warnings };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The gates `transitionRequestArtifact` applies on `rd → implemented`,
3
+ * `rd → qa-handoff` and `rd → handed-off`: the per-file size ratchet and the
4
+ * declared-type corroboration. Extracted so `request-artifact-service.ts`
5
+ * (already over its cap) grows by one call instead of two blocks, and so the
6
+ * checks run for EVERY caller — not only the CLI flag path.
7
+ *
8
+ * ONE ENUMERATION PER TRANSITION. At `implemented` the change set is read once
9
+ * and shared: the type rule judges every path (deletions included, rename
10
+ * sources included), while the size scan measures the A/M/R/untracked subset.
11
+ * `qa-handoff` / `handed-off` run only the type rule (two git spawns); the size
12
+ * ratchet keeps the single state it has always judged.
13
+ */
14
+ import type { RequestType } from './artifact-prerequisites.js';
15
+ import { type TypeCorroboration } from '../scan/type-corroboration.js';
16
+ export type RdGatePhase = 'implemented' | 'qa-handoff' | 'handed-off';
17
+ export declare class TypeCorroborationViolationError extends Error {
18
+ readonly code = "TYPE_CORROBORATION_VIOLATION";
19
+ readonly declaredType: RequestType;
20
+ readonly kind: 'source-touched' | 'diff-unavailable';
21
+ constructor(declaredType: RequestType, verdict: Extract<TypeCorroboration, {
22
+ ok: false;
23
+ }>);
24
+ }
25
+ /** Written into the artifact when `--allow-incomplete` skips a gate that COULD
26
+ * have judged this type: a silent bypass is indistinguishable from a pass. */
27
+ export declare function rdGatesBypassNote(phase: RdGatePhase): string;
28
+ export declare function runRdTransitionGates(options: {
29
+ projectRoot: string;
30
+ declaredType: RequestType;
31
+ allowIncomplete: boolean;
32
+ phase: RdGatePhase;
33
+ }): string | null;
@@ -0,0 +1,71 @@
1
+ import { FileSizeViolationError } from './request-artifact-state-helpers.js';
2
+ import { readGitChangeSet } from '../scan/file-size-baseline.js';
3
+ import { scanFileSize } from '../scan/file-size-scan.js';
4
+ import { corroborateDeclaredType, diffUnavailableVerdict, isToolingOnlyDeclaredType } from '../scan/type-corroboration.js';
5
+ export class TypeCorroborationViolationError extends Error {
6
+ code = 'TYPE_CORROBORATION_VIOLATION';
7
+ declaredType;
8
+ kind;
9
+ constructor(declaredType, verdict) {
10
+ super(verdict.message);
11
+ this.name = 'TypeCorroborationViolationError';
12
+ this.declaredType = declaredType;
13
+ this.kind = verdict.kind;
14
+ }
15
+ }
16
+ /** Written into the artifact when `--allow-incomplete` skips a gate that COULD
17
+ * have judged this type: a silent bypass is indistinguishable from a pass. */
18
+ export function rdGatesBypassNote(phase) {
19
+ const gates = phase === 'implemented'
20
+ ? 'file-size ratchet, declared-type corroboration'
21
+ : 'declared-type corroboration';
22
+ return (`bypassed the rd ${phase} gates (${gates}) via --allow-incomplete; ` +
23
+ 'none of them was evaluated');
24
+ }
25
+ /** The shared read, or the fail-closed verdict built from the same message. */
26
+ function readOrRefuse(projectRoot, declaredType) {
27
+ try {
28
+ return readGitChangeSet(projectRoot, 'HEAD');
29
+ }
30
+ catch {
31
+ throw new TypeCorroborationViolationError(declaredType, diffUnavailableVerdict(declaredType));
32
+ }
33
+ }
34
+ export function runRdTransitionGates(options) {
35
+ const judged = isToolingOnlyDeclaredType(options.declaredType);
36
+ if (options.allowIncomplete)
37
+ return judged ? rdGatesBypassNote(options.phase) : null;
38
+ if (!judged) {
39
+ // The size ratchet still runs at implemented; the type rule is a no-op here.
40
+ if (options.phase === 'implemented') {
41
+ const size = scanFileSize({ projectRoot: options.projectRoot });
42
+ if (!size.ok)
43
+ throw new FileSizeViolationError(size.violations);
44
+ }
45
+ return null;
46
+ }
47
+ if (options.phase !== 'implemented') {
48
+ const verdict = corroborateDeclaredType({
49
+ projectRoot: options.projectRoot,
50
+ declaredType: options.declaredType
51
+ });
52
+ if (!verdict.ok)
53
+ throw new TypeCorroborationViolationError(options.declaredType, verdict);
54
+ return null;
55
+ }
56
+ const changeSet = readOrRefuse(options.projectRoot, options.declaredType);
57
+ const verdict = corroborateDeclaredType({
58
+ projectRoot: options.projectRoot,
59
+ declaredType: options.declaredType,
60
+ changedPaths: changeSet.changedPaths
61
+ });
62
+ if (!verdict.ok)
63
+ throw new TypeCorroborationViolationError(options.declaredType, verdict);
64
+ const size = scanFileSize({
65
+ projectRoot: options.projectRoot,
66
+ changedFiles: changeSet.changedFiles
67
+ });
68
+ if (!size.ok)
69
+ throw new FileSizeViolationError(size.violations);
70
+ return null;
71
+ }
@@ -15,7 +15,7 @@ import { isUnsafePathInput } from '../../shared/path-safety.js';
15
15
  import { guardRuntimeSegment, runtimeRoot } from '../../shared/runtime-root.js';
16
16
  import { checkTypeSanity } from '../scan/type-sanity-service.js';
17
17
  import { requireUserConfirmation } from '../mode/mode-enforcement.js';
18
- import { scanFileSize } from '../scan/file-size-scan.js';
18
+ import { runRdTransitionGates } from './rd-transition-gates.js';
19
19
  import { emitObservabilityEvent } from '../observability/observability-service.js';
20
20
  export { VALID_REQUEST_TYPES, DEFAULT_REQUEST_TYPE, isRequestType };
21
21
  // Re-export the pure-function template surface so external callers (CLI,
@@ -127,13 +127,13 @@ export async function createRequestArtifact(options) {
127
127
  if (await isDirectory(requestsDir)) {
128
128
  const existingFiles = await listMarkdownFiles(requestsDir);
129
129
  // The writer lowercases the request id into a kebab slug
130
- // (`buildNumberedFilename`), so the duplicate-detection endsWith must
131
- // compare against the SAME slug — a mixed-case id like
130
+ // (`buildNumberedFilename`), so the duplicate check compares against the SAME
131
+ // slug — read off each filename by the one reader that owns the naming rule.
132
132
  const slug = slugifyDescription(options.requestId);
133
133
  const alreadyExists = existingFiles.some((file) => {
134
134
  if (file === `${options.requestId}.md`)
135
135
  return true;
136
- if (/^\d+-/.test(file) && file.endsWith(`-${slug}.md`))
136
+ if (requestIdFromFileName(file) === slug)
137
137
  return true;
138
138
  return false;
139
139
  });
@@ -280,8 +280,8 @@ export async function showRequestArtifact(options) {
280
280
  if (file === `${options.requestId}.md`) {
281
281
  return { fileName: file, path: join(dir, file) };
282
282
  }
283
- // Match numbered format: ${number}-${requestId}.md
284
- if (/^\d+-/.test(file) && file.endsWith(`-${slug}.md`)) {
283
+ // Match the id this filename carries, by the ONE rule that owns it
284
+ if (requestIdFromFileName(file) === slug) {
285
285
  return { fileName: file, path: join(dir, file) };
286
286
  }
287
287
  }
@@ -333,7 +333,7 @@ async function readRequestArtifact(dir, role, found, sessionId) {
333
333
  // the sibling `request-artifact-state-helpers.ts` module — see
334
334
  // v2.18.3 file-split for the rationale. Function signatures and
335
335
  // behaviour are unchanged (verbatim move).
336
- import { ALLOWED_STATES_PER_ROLE, FileSizeViolationError, LintGateError, PrerequisitesNotSatisfiedError, TypeSanityViolationError, updateStatusBlock } from './request-artifact-state-helpers.js';
336
+ import { ALLOWED_STATES_PER_ROLE, LintGateError, PrerequisitesNotSatisfiedError, TypeSanityViolationError, updateStatusBlock } from './request-artifact-state-helpers.js';
337
337
  import { assertLegalStateStep } from './request-state-order.js';
338
338
  export { allowedStatesForRole, FileSizeViolationError, LintGateError, PrerequisitesNotSatisfiedError, TypeSanityViolationError, updateStatusBlock } from './request-artifact-state-helpers.js';
339
339
  export async function transitionRequestArtifact(options) {
@@ -401,27 +401,29 @@ export async function transitionRequestArtifact(options) {
401
401
  sessionId: existing.sessionId
402
402
  });
403
403
  if (lintReport !== null && !lintReport.ok) {
404
- const errorCount = lintReport.findings.filter((f) => f.severity === 'error').length;
405
- if (errorCount > 0) {
406
- throw new LintGateError(options.role, options.newState, errorCount);
404
+ const errors = lintReport.findings.filter((f) => f.severity === 'error');
405
+ if (errors.length > 0) {
406
+ throw new LintGateError(options.role, options.newState, errors);
407
407
  }
408
408
  }
409
409
  }
410
- // File-size ratchet: refuse only a file this change made worse (Simplicity First).
411
- if (options.role === 'rd' &&
412
- options.newState === 'implemented' &&
413
- options.allowIncomplete !== true) {
414
- const sizeResult = scanFileSize({ projectRoot: options.projectRoot });
415
- if (!sizeResult.ok) {
416
- throw new FileSizeViolationError(sizeResult.violations);
417
- }
418
- }
410
+ const gateBypassNote = options.role === 'rd' &&
411
+ (options.newState === 'implemented' ||
412
+ options.newState === 'qa-handoff' ||
413
+ options.newState === 'handed-off')
414
+ ? runRdTransitionGates({
415
+ projectRoot: options.projectRoot,
416
+ declaredType: existing.requestType,
417
+ allowIncomplete: options.allowIncomplete === true,
418
+ phase: options.newState
419
+ })
420
+ : null;
419
421
  const clock = options.clock ?? defaultClock;
420
422
  const timestamp = clock();
421
423
  const bypassNote = !prerequisiteResult.ok && options.allowIncomplete === true
422
424
  ? `bypassed prerequisites (${prerequisiteResult.missing.map((entry) => entry.path).join(', ')})`
423
425
  : undefined;
424
- const combinedReason = [options.reason, bypassNote]
426
+ const combinedReason = [options.reason, bypassNote, gateBypassNote ?? undefined]
425
427
  .filter((part) => part !== undefined && part.length > 0)
426
428
  .join(' | ');
427
429
  const reasonForNote = combinedReason.length > 0 ? combinedReason : undefined;
@@ -18,12 +18,20 @@ export declare class PrerequisitesNotSatisfiedError extends Error {
18
18
  readonly warnings: PrerequisiteCheckResult['warnings'];
19
19
  constructor(role: RequestArtifactRole, newState: RequestArtifactState, sessionId: string, missing: PrerequisiteCheckResult['missing'], warnings?: PrerequisiteCheckResult['warnings']);
20
20
  }
21
+ /** The diagnosis a lint refusal carries: the `line`, `text` and `reason` the linter
22
+ * computed for each finding and this error previously kept only a count of. */
23
+ export type LintGateFinding = {
24
+ line: number;
25
+ text: string;
26
+ reason: string;
27
+ };
21
28
  export declare class LintGateError extends Error {
22
29
  readonly code = "LINT_GATE_FAILED";
23
30
  readonly role: RequestArtifactRole;
24
31
  readonly newState: RequestArtifactState;
25
32
  readonly errorCount: number;
26
- constructor(role: RequestArtifactRole, newState: RequestArtifactState, errorCount: number);
33
+ readonly findings: ReadonlyArray<LintGateFinding>;
34
+ constructor(role: RequestArtifactRole, newState: RequestArtifactState, findings: ReadonlyArray<LintGateFinding>);
27
35
  }
28
36
  export declare class TypeSanityViolationError extends Error {
29
37
  readonly code = "TYPE_SANITY_VIOLATION";
@@ -22,7 +22,7 @@ export class PrerequisitesNotSatisfiedError extends Error {
22
22
  */
23
23
  warnings;
24
24
  constructor(role, newState, sessionId, missing, warnings = []) {
25
- super(`Cannot transition ${role} to ${newState}: ${missing.length} required artifact${missing.length === 1 ? '' : 's'} missing under .peaks/_runtime/${sessionId}/`);
25
+ super(`Cannot transition ${role} to ${newState}: ${missing.length} unmet requirement${missing.length === 1 ? '' : 's'} under .peaks/_runtime/${sessionId}/`);
26
26
  this.name = 'PrerequisitesNotSatisfiedError';
27
27
  this.role = role;
28
28
  this.newState = newState;
@@ -36,13 +36,15 @@ export class LintGateError extends Error {
36
36
  role;
37
37
  newState;
38
38
  errorCount;
39
- constructor(role, newState, errorCount) {
40
- super(`Cannot transition ${role} to ${newState}: ${errorCount} lint error(s) found in artifact. ` +
39
+ findings;
40
+ constructor(role, newState, findings) {
41
+ super(`Cannot transition ${role} to ${newState}: ${findings.length} lint error(s) found in artifact. ` +
41
42
  'Fix lint errors or use --allow-incomplete to bypass.');
42
43
  this.name = 'LintGateError';
43
44
  this.role = role;
44
45
  this.newState = newState;
45
- this.errorCount = errorCount;
46
+ this.findings = findings;
47
+ this.errorCount = findings.length;
46
48
  }
47
49
  }
48
50
  export class TypeSanityViolationError extends Error {
@@ -23,6 +23,7 @@ export type JudgedRefusal = {
23
23
  readonly artifact: string;
24
24
  readonly path: string;
25
25
  };
26
+ export declare function describeJudgedRefusal(refusal: JudgedRefusal): string;
26
27
  export type JudgedCheckResult = {
27
28
  readonly refusals: readonly JudgedRefusal[];
28
29
  readonly checked: number;
@@ -20,7 +20,68 @@
20
20
  import { existsSync, readFileSync } from 'node:fs';
21
21
  import { execFileSync } from 'node:child_process';
22
22
  import { join } from 'node:path';
23
- import { parseJudgedDeclaration, sha256OfFile } from './judged-declaration.js';
23
+ import { JUDGED_HEADING, parseJudgedDeclaration, sha256OfFile } from './judged-declaration.js';
24
+ /**
25
+ * What a refusal means, partitioned by THE ONE QUESTION its codes answer:
26
+ * **did this check complete the observation its sentence would assert?** One
27
+ * sentence for all 17 told a producer to satisfy a declaration a `declared-path-*`
28
+ * refusal had already read — "name the requirement that is unmet" broken one level
29
+ * in, and the reason the arm has been split four times since. The partition below
30
+ * is stated so a reviewer checks it, rather than hunting members:
31
+ *
32
+ * A. `declaration-*` — **11 codes** (`missing`, `unfenced`, `unterminated`,
33
+ * `empty`, `schema`, `path`, `hash`, `duplicate`, `bare-root`, `escaped`,
34
+ * `unparsable`). No declaration was read at all, so the sentence is about the
35
+ * BLOCK and claims nothing about the tree.
36
+ * B. `artifact-unreadable` — **1**. The artifact was not read; nothing about its
37
+ * declaration is known.
38
+ * C. `declared-path-unreadable` — **1**. The path was reached and could not be
39
+ * read, so its hash is **UNKNOWN**, not mismatched. Its own arm because the
40
+ * remedy differs and "re-run the producer" cannot work: a re-run hashes the
41
+ * same unreadable path and refuses identically.
42
+ * D. `root-listing-failed` — **1**. A root was declared and could NOT be listed,
43
+ * so no file under it was compared. Its answer is "no observation", not
44
+ * "mismatch".
45
+ * E. `declared-path-gone`, `declared-path-modified`,
46
+ * `undeclared-path-under-root` — **3**. All three COMPLETED their observation:
47
+ * a declared path is absent or edited, or the listing succeeded and found a
48
+ * file under a declared root that the declaration does not name. Together they
49
+ * are the only codes that may say the tree and the declaration disagree — which
50
+ * is why they are a LIST and not the `else` arm.
51
+ * F. **0 codes today** — the fail-safe. Anything unrecognised gets a sentence that
52
+ * asserts only what is certain (it parsed and was read). Codes A–E are
53
+ * exhaustive over the 17 the two modules emit, so this arm is unreachable now;
54
+ * it exists so a NEW code cannot inherit an observation it did not make, which
55
+ * is the failure this comment records four times.
56
+ *
57
+ * A producer reads this in a refusal, so the classes are the ACTIONS, not the codes:
58
+ * write the block, make the path readable, or re-run the producer.
59
+ */
60
+ /** The codes that completed a tree observation, and so may say the tree disagrees. */
61
+ const OBSERVED_DISAGREEMENT = new Set([
62
+ 'declared-path-gone',
63
+ 'declared-path-modified',
64
+ 'undeclared-path-under-root'
65
+ ]);
66
+ export function describeJudgedRefusal(refusal) {
67
+ const where = `Judged declaration ${refusal.code} at ${refusal.path}`;
68
+ if (refusal.code === 'artifact-unreadable') {
69
+ return `${where}: the artifact is present but could not be read, so its \`${JUDGED_HEADING}\` declaration is unverified`;
70
+ }
71
+ if (refusal.code === 'declared-path-unreadable') {
72
+ return `${where}: the declaration is present and parses, but a path it names is present and unreadable, so its hash is unknown — make that path readable; re-running the producer hashes the same path and refuses identically`;
73
+ }
74
+ if (refusal.code === 'root-listing-failed') {
75
+ return `${where}: the declaration is present and parses and names this as a root, but the root could not be listed, so no file under it was compared — re-run the producer, which declares no roots`;
76
+ }
77
+ if (refusal.code.startsWith('declaration-')) {
78
+ return `${where}: the artifact is present; what is unmet is its \`${JUDGED_HEADING}\` block, absent or not one this check can accept`;
79
+ }
80
+ if (OBSERVED_DISAGREEMENT.has(refusal.code)) {
81
+ return `${where}: the declaration was read and the tree compared against it, and the two do not agree — re-run the producer`;
82
+ }
83
+ return `${where}: the declaration is present and parses; this code records no comparison this check completed, so treat the tree as unverified and re-run the producer`;
84
+ }
24
85
  /** Where the security audit artifact may live, newest tier first. */
25
86
  export function securityArtifactTiers(rid) {
26
87
  return [
@@ -208,15 +208,11 @@ export declare const CODEGRAPH_UNAVAILABLE_BLOCK: string;
208
208
  /** Binding phrases every dispatch prompt must contain, for every role. */
209
209
  export declare const BINDING_RULE_TOKENS: readonly string[];
210
210
  /**
211
- * The runner-direct-path tokens: the refusal example, the two direct paths
212
- * the block names (`peaks test --json` to introspect; PB-5, the repo-defined
213
- * `test` / `test:*` scripts that are NOT gated), and the two pieces of
214
- * quality guidance that must survive any compression — never assume a
215
- * runner without asking the user as a last resort, and prefer
216
- * `peaks test <file>` because it resolves the local binary Windows-aware.
217
- *
218
- * so this set is asserted IDENTICALLY for every role. The runner EXAMPLES
219
- * were removed as part of the unification — they were never rules.
211
+ * The runner-direct-path tokens: the scope requirement; the whole-tree tier by ALL THREE of its
212
+ * members (both guard directories and the root selector); the PRINCIPLE they are the mechanism
213
+ * for; the two direct paths the block names (`peaks test --json` to introspect, PB-5 = the
214
+ * repo-defined `test` / `test:*` scripts that are NOT gated); and the quality guidance that must
215
+ * survive compression — never assume a runner without asking; prefer `peaks test <file>`.
220
216
  */
221
217
  export declare const TEST_RUNNER_RULE_TOKENS: readonly string[];
222
218
  /**
@@ -334,25 +334,25 @@ export const BINDING_RULE_TOKENS = [
334
334
  'do NOT invoke `npx <runner>`',
335
335
  '## Test Scope (mandatory)',
336
336
  'PEAKS_FULL_TEST=1',
337
- 'refused'
337
+ 'not permitted'
338
338
  ];
339
339
  /**
340
- * The runner-direct-path tokens: the refusal example, the two direct paths
341
- * the block names (`peaks test --json` to introspect; PB-5, the repo-defined
342
- * `test` / `test:*` scripts that are NOT gated), and the two pieces of
343
- * quality guidance that must survive any compression — never assume a
344
- * runner without asking the user as a last resort, and prefer
345
- * `peaks test <file>` because it resolves the local binary Windows-aware.
346
- *
347
- * so this set is asserted IDENTICALLY for every role. The runner EXAMPLES
348
- * were removed as part of the unification — they were never rules.
340
+ * The runner-direct-path tokens: the scope requirement; the whole-tree tier by ALL THREE of its
341
+ * members (both guard directories and the root selector); the PRINCIPLE they are the mechanism
342
+ * for; the two direct paths the block names (`peaks test --json` to introspect, PB-5 = the
343
+ * repo-defined `test` / `test:*` scripts that are NOT gated); and the quality guidance that must
344
+ * survive compression — never assume a runner without asking; prefer `peaks test <file>`.
349
345
  */
350
346
  export const TEST_RUNNER_RULE_TOKENS = [
351
347
  '`./node_modules/.bin/vitest run`',
352
348
  'PB-5',
353
349
  '`peaks test --json`',
354
350
  'ask the user before assuming a runner',
355
- '(Windows-aware)'
351
+ '(Windows-aware)',
352
+ 'subject is the tree, not one file, is in scope for every slice',
353
+ '`tests/unit/standards`',
354
+ '`tests/unit/lint`',
355
+ '`tests/unit/*.test.ts`'
356
356
  ];
357
357
  /**
358
358
  * Return the subset of `tokens` that `text` does NOT contain. Pure; used by
@@ -108,7 +108,7 @@ export const POST_COMPACT_REINJECTION_BYTE_BUDGET = 3072;
108
108
  */
109
109
  export const AGENT_RUNTIME_RULES = Object.freeze([
110
110
  'CLI: run `node --import tsx src/cli/index.ts <cmd>`, never `pnpm exec tsx` — on Windows the latter truncates any argument at its first newline.',
111
- 'Test scope: one file or pattern per run; the full suite requires PEAKS_FULL_TEST=1.',
111
+ 'Test scope: one file or pattern per run; the full suite requires PEAKS_FULL_TEST=1; a slice also runs the whole-tree tier tests/unit/standards + tests/unit/lint + the root of tests/unit/ (tests/unit/*.test.ts).',
112
112
  "Exit codes: never read a test result through a pipe (`| tail` reports tail's status); read ${PIPESTATUS[0]}.",
113
113
  'Never write `.claude/settings.local.json` from a slice — reproduce against a temp project copy via `--project <tmpdir>`.',
114
114
  'Git: commit / push policy is per-dispatch and is NOT inherited from this card — re-read the dispatch record before any state-mutating git command.',
@@ -36,11 +36,20 @@
36
36
  * examples. No role split remains, so every role receives a byte-identical
37
37
  * block.
38
38
  */
39
- export declare const TEST_TOOL_DETECTION_BLOCK = "## Test Tool Detection (mandatory)\n\nRead `package.json#scripts.test` for the project's framework and use the project-local runner \u2014 do NOT invoke `npx <runner>`. If unsure, run `peaks test --json` first. Only as a last resort, ask the user before assuming a runner. `peaks test <file>` already resolves the local binary for you (Windows-aware).\n\n## Test Scope (mandatory)\n\nAny test command MUST be **scoped** to a single file or pattern; a bare `./node_modules/.bin/vitest run` is **refused** unless you prefix the explicit opt-in token `PEAKS_FULL_TEST=1` (CI / release verification only, never routine slice verification).\n\nRepo-defined `test` / `test:*` scripts are the human/LLM direct path and are NOT gated by this scope rule (PB-5).";
39
+ export declare const TEST_TOOL_DETECTION_BLOCK = "## Test Tool Detection (mandatory)\n\nRead `package.json#scripts.test` for the project's framework and use the project-local runner \u2014 do NOT invoke `npx <runner>`. If unsure, run `peaks test --json` first. Only as a last resort, ask the user before assuming a runner. `peaks test <file>` already resolves the local binary for you (Windows-aware).\n\n## Test Scope (mandatory)\n\nAny test command MUST be **scoped** to a single file or pattern \u2014 a bare `./node_modules/.bin/vitest run` is **not permitted** without the explicit opt-in token `PEAKS_FULL_TEST=1` (CI / release verification only, never routine slice verification). Nothing inspects the command you run: this is a rule you follow, not a gate that fires.\n\nA suite whose subject is the tree, not one file, is in scope for every slice, whatever the slice changed \u2014 it can go red for a change outside its own subtree. This repo's tier is `tests/unit/standards`, `tests/unit/lint` and the root of `tests/unit/` (`tests/unit/*.test.ts`): add all three to a slice's run, once per slice rather than per reviewer pass.\n\nRepo-defined `test` / `test:*` scripts are the human/LLM direct path and are NOT gated by this scope rule (PB-5).";
40
40
  /**
41
41
  * Pure helper that returns the block. Exists as a function (not just an
42
42
  * exported constant) so future variants can take a runtime parameter
43
43
  * (e.g. projectRoot for context) without churning every call site.
44
+ *
45
+ * The whole-tree tier (2026-10-16) names `tests/unit/standards`, `tests/unit/lint`
46
+ * and the root of `tests/unit/` (`tests/unit/*.test.ts`). A file-scoped run cannot
47
+ * cover a suite whose subject is the tree: the push gate's area rule turns
48
+ * `src/<area>` into `tests/unit/<area>`, and no guard directory has an area of its
49
+ * own to be reached through. That gap is a HAND-run's alone — the classifier's
50
+ * `subset()` unions the whole tier into every subset verdict, so the gate reaches
51
+ * the tier on every diff it runs at all. The one diff it does NOT run is gate data
52
+ * alone whose content did not move: that verdict selects 0 tests, root tier included.
44
53
  */
45
54
  export declare function formatTestToolDetection(): string;
46
55
  /**
@@ -49,6 +58,13 @@ export declare function formatTestToolDetection(): string;
49
58
  * whether the command is allowed, refused, or requires the explicit
50
59
  * opt-in.
51
60
  *
61
+ * NO CALLER YET, stated so the next reader does not look for one: nothing
62
+ * under `src/`, `tests/` or `scripts/` imports this. The dispatch block
63
+ * states the scope as a rule the agent follows, and does not claim a run is
64
+ * refused — wiring this into the `peaks test` CLI or a hook is a separate
65
+ * change with its own blast radius, and it is the owner's call, not a
66
+ * consequence of the rule text.
67
+ *
52
68
  * - 'scoped' — the command names a file/pattern after `run`
53
69
  * - 'opt-in' — the user/LLM set PEAKS_FULL_TEST=1 to override
54
70
  * - 'refused' — bare `vitest run` with no path and no opt-in
@@ -42,13 +42,24 @@ Read \`package.json#scripts.test\` for the project's framework and use the proje
42
42
 
43
43
  ## Test Scope (mandatory)
44
44
 
45
- Any test command MUST be **scoped** to a single file or pattern; a bare \`./node_modules/.bin/vitest run\` is **refused** unless you prefix the explicit opt-in token \`PEAKS_FULL_TEST=1\` (CI / release verification only, never routine slice verification).
45
+ Any test command MUST be **scoped** to a single file or pattern — a bare \`./node_modules/.bin/vitest run\` is **not permitted** without the explicit opt-in token \`PEAKS_FULL_TEST=1\` (CI / release verification only, never routine slice verification). Nothing inspects the command you run: this is a rule you follow, not a gate that fires.
46
+
47
+ A suite whose subject is the tree, not one file, is in scope for every slice, whatever the slice changed — it can go red for a change outside its own subtree. This repo's tier is \`tests/unit/standards\`, \`tests/unit/lint\` and the root of \`tests/unit/\` (\`tests/unit/*.test.ts\`): add all three to a slice's run, once per slice rather than per reviewer pass.
46
48
 
47
49
  Repo-defined \`test\` / \`test:*\` scripts are the human/LLM direct path and are NOT gated by this scope rule (PB-5).`;
48
50
  /**
49
51
  * Pure helper that returns the block. Exists as a function (not just an
50
52
  * exported constant) so future variants can take a runtime parameter
51
53
  * (e.g. projectRoot for context) without churning every call site.
54
+ *
55
+ * The whole-tree tier (2026-10-16) names `tests/unit/standards`, `tests/unit/lint`
56
+ * and the root of `tests/unit/` (`tests/unit/*.test.ts`). A file-scoped run cannot
57
+ * cover a suite whose subject is the tree: the push gate's area rule turns
58
+ * `src/<area>` into `tests/unit/<area>`, and no guard directory has an area of its
59
+ * own to be reached through. That gap is a HAND-run's alone — the classifier's
60
+ * `subset()` unions the whole tier into every subset verdict, so the gate reaches
61
+ * the tier on every diff it runs at all. The one diff it does NOT run is gate data
62
+ * alone whose content did not move: that verdict selects 0 tests, root tier included.
52
63
  */
53
64
  export function formatTestToolDetection() {
54
65
  return TEST_TOOL_DETECTION_BLOCK;
@@ -34,6 +34,7 @@ import { handoffRelativePath, sha256OfBody } from '../prd/handoff-service.js';
34
34
  import { getSessionDir } from '../session/getSessionDir.js';
35
35
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
36
36
  import { isUnsafePathInput } from '../../shared/path-safety.js';
37
+ import { requestIdFromFileName, slugifyDescription } from '../../shared/incrementing-number.js';
37
38
  import { renderJudgedSection } from '../audit-independent/judged-declaration-build.js';
38
39
  import { buildCodeReview, buildKarpathyReview, buildPerfAudit, buildPerformanceFindings, buildQaRequest, buildSecurityFindings, buildSecurityReview, buildTechDoc, buildTestCases, buildTestReport, filesMd, lineCountsMd } from './evidence-body-builders.js';
39
40
  /** Comma/space tolerant `--files` splitter. */
@@ -105,19 +106,22 @@ ${lineCountsMd(lineCounts)}
105
106
  };
106
107
  return { content: `${serializeHandoffFrontmatter(frontmatter)}${body}`, hash: handoffHash };
107
108
  }
108
- /** Find the existing numbered QA request file for `rid`, else the default. */
109
+ /** Find the QA request file whose carried id is `rid`, else the default. */
109
110
  async function resolveQaRequestPath(qaDir, rid) {
110
- const suffix = `-${rid}.md`;
111
111
  try {
112
112
  const entries = await readdir(join(qaDir, 'requests'));
113
- const match = entries.find((name) => /^\d+-/.test(name) && name.endsWith(suffix));
113
+ // The operand is the SLUG, as it is at the two `request-artifact-service.ts`
114
+ // sites: the writer lowercases the rid into the filename, so comparing a
115
+ // carried id against the raw rid answers a different question about the same
116
+ // file and misses it whenever the rid carries a capital.
117
+ const match = entries.find((name) => requestIdFromFileName(name) === slugifyDescription(rid));
114
118
  if (match !== undefined)
115
119
  return join(qaDir, 'requests', match);
116
120
  }
117
121
  catch {
118
122
  // directory missing — fall through to the default numbered name
119
123
  }
120
- return join(qaDir, 'requests', `001-${rid}.md`);
124
+ return join(qaDir, 'requests', `001-${slugifyDescription(rid)}.md`);
121
125
  }
122
126
  export async function generateEvidence(options) {
123
127
  const { projectRoot, rid, title, files, lineCounts, sessionId } = options;
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Coverage Evidence reader for c8 `coverage-summary.json` (Fix-6B).
2
+ * Coverage Evidence reader for the istanbul `coverage-summary.json` shape (Fix-6B).
3
3
  *
4
4
  * - pure helper module, no side effects beyond FS reads
5
- * - reads the istanbul-reporter JSON shape emitted by `c8 --reporter=json-summary`
6
- * (the project's coverage tool — see scripts/coverage-c8.mjs)
5
+ * - reads the istanbul-reporter JSON shape a `--reporter=json-summary` run emits
6
+ * (the project's instrument is `.husky/coverage-ratchet.mjs`, which emits it)
7
7
  * - resolves a `coverage-summary.json` from a fixed discovery order
8
8
  * - validates per-capability coverage against a `## Capability Mapping` block
9
9
  *
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * Conventions:
16
16
  * - All paths are POSIX-normalized for JSON safety.
17
- * - The c8 summary's per-file keys are project-root-relative POSIX paths
17
+ * - The summary's per-file keys are project-root-relative POSIX paths
18
18
  * (e.g. `src/services/openspec/openspec-archive-service.ts`).
19
19
  * - Capability mapping `source` field is also project-root-relative, may be
20
20
  * a file (`foo.ts`) or a directory (`src/services/openspec/`).
@@ -37,7 +37,7 @@ export type CoverageSummary = {
37
37
  files: ReadonlyMap<string, CoverageFileEntry>;
38
38
  };
39
39
  export type CoverageFileEntry = {
40
- /** Absolute path the c8 entry covers (POSIX). */
40
+ /** Absolute path the summary entry covers (POSIX). */
41
41
  path: string;
42
42
  /** Project-root-relative POSIX path (the key the summary uses). */
43
43
  relativePath: string;
@@ -101,7 +101,7 @@ export type CoverageValidation = {
101
101
  *
102
102
  * Discovery order (per Fix-6B AC1):
103
103
  * 1. `explicitPath` (passed via `--coverage-summary`)
104
- * 2. `<projectRoot>/coverage/coverage-summary.json` (c8 wrapper default)
104
+ * 2. `<projectRoot>/coverage/coverage-summary.json` (the coverage run's default)
105
105
  * 3. `<projectRoot>/openspec/coverage-summary.json` (per-project override)
106
106
  *
107
107
  * Returns:
@@ -153,7 +153,7 @@ export declare function parseCapabilityMapping(proposalPath: string): Promise<{
153
153
  * - File path: returns `[file]`.
154
154
  * - Directory path: returns every `*.ts` file recursively under it (relative
155
155
  * to `projectRoot`, POSIX separators). Non-TS files are excluded because
156
- * c8 only collects coverage on TS source modules.
156
+ * the summary only carries TS source modules.
157
157
  */
158
158
  export declare function resolveCapabilityFiles(input: {
159
159
  projectRoot: string;
@@ -161,7 +161,7 @@ export declare function resolveCapabilityFiles(input: {
161
161
  }): Promise<ReadonlyArray<string>>;
162
162
  /**
163
163
  * Validate per-capability coverage. Each capability row's `source` is resolved
164
- * to one or more files; each file must appear in the c8 summary with all four
164
+ * to one or more files; each file must appear in the summary with all four
165
165
  * metrics at exactly 100%.
166
166
  *
167
167
  * Returns `{ ok: true }` when every capability passes; `{ ok: false, mismatches }`
@@ -175,7 +175,7 @@ export declare function validateCapabilityCoverage(input: {
175
175
  }): Promise<CoverageValidation>;
176
176
  /**
177
177
  * Compare the mtime of every spec/proposal/tasks file under the change against
178
- * the mtime of the c8 summary. If any change file is newer than the summary,
178
+ * the mtime of the summary. If any change file is newer than the summary,
179
179
  * the captured V8 counters no longer match the source on disk and the summary
180
180
  * is stale.
181
181
  *