peaks-loop 4.1.4 → 4.1.5

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 (240) hide show
  1. package/.claude-plugin/marketplace.json +7 -2
  2. package/CHANGELOG.md +112 -0
  3. package/README-en.md +1 -1
  4. package/README.md +1 -1
  5. package/dist/cli/cli-helpers.d.ts +20 -0
  6. package/dist/cli/cli-helpers.js +34 -0
  7. package/dist/cli/commands/_register.js +2 -0
  8. package/dist/cli/commands/code-commands.d.ts +6 -4
  9. package/dist/cli/commands/code-commands.js +6 -4
  10. package/dist/cli/commands/code-gate-command.d.ts +5 -5
  11. package/dist/cli/commands/code-gate-command.js +49 -9
  12. package/dist/cli/commands/code-mode-gate-plan-command.d.ts +1 -1
  13. package/dist/cli/commands/code-mode-gate-plan-command.js +2 -2
  14. package/dist/cli/commands/core/memory-extract-command.js +10 -5
  15. package/dist/cli/commands/dispatch-cli-invocation-check.d.ts +108 -0
  16. package/dist/cli/commands/dispatch-cli-invocation-check.js +87 -0
  17. package/dist/cli/commands/dispatch-cli-invocation-scan.d.ts +66 -0
  18. package/dist/cli/commands/dispatch-cli-invocation-scan.js +162 -0
  19. package/dist/cli/commands/dispatch-commands.js +12 -5
  20. package/dist/cli/commands/dispatch-preflight.js +46 -0
  21. package/dist/cli/commands/dispatch-prompt-composition.d.ts +6 -0
  22. package/dist/cli/commands/dispatch-prompt-composition.js +29 -7
  23. package/dist/cli/commands/doc-commands.js +1 -1
  24. package/dist/cli/commands/feedback-commands-helpers.js +1 -1
  25. package/dist/cli/commands/final-review-prepare-command.js +22 -1
  26. package/dist/cli/commands/gate-commands-enforce.js +3 -3
  27. package/dist/cli/commands/hook-handle.js +41 -20
  28. package/dist/cli/commands/lint-commands.js +3 -1
  29. package/dist/cli/commands/loop-eval-capture-index.js +2 -4
  30. package/dist/cli/commands/perf-audit-commands.js +15 -5
  31. package/dist/cli/commands/project-commands.js +9 -6
  32. package/dist/cli/commands/race-commands.d.ts +15 -0
  33. package/dist/cli/commands/race-commands.js +65 -0
  34. package/dist/cli/commands/race-pilot-gate-record-command.d.ts +3 -0
  35. package/dist/cli/commands/race-pilot-gate-record-command.js +81 -0
  36. package/dist/cli/commands/request-command-options.d.ts +8 -0
  37. package/dist/cli/commands/request-commands.js +2 -0
  38. package/dist/cli/commands/request-init-command.js +67 -12
  39. package/dist/cli/commands/request-retag-command.d.ts +3 -0
  40. package/dist/cli/commands/request-retag-command.js +50 -0
  41. package/dist/cli/commands/request-show-command.d.ts +8 -0
  42. package/dist/cli/commands/request-show-command.js +14 -1
  43. package/dist/cli/commands/request-transition-command.js +12 -4
  44. package/dist/cli/commands/request-transition-failures.d.ts +14 -0
  45. package/dist/cli/commands/request-transition-failures.js +45 -3
  46. package/dist/cli/commands/scan-scope-commands.js +2 -2
  47. package/dist/cli/commands/security-audit-commands.js +26 -6
  48. package/dist/cli/commands/worktree-lease-gc-command.js +1 -1
  49. package/dist/services/artifacts/artifact-contract-block.d.ts +53 -0
  50. package/dist/services/artifacts/artifact-contract-block.js +212 -0
  51. package/dist/services/artifacts/artifact-prerequisites.d.ts +27 -19
  52. package/dist/services/artifacts/artifact-prerequisites.js +63 -133
  53. package/dist/services/artifacts/artifact-templates.d.ts +1 -1
  54. package/dist/services/artifacts/artifact-templates.js +17 -10
  55. package/dist/services/artifacts/prerequisite-checks.d.ts +87 -0
  56. package/dist/services/artifacts/prerequisite-checks.js +198 -0
  57. package/dist/services/artifacts/prerequisite-transition-event.d.ts +20 -0
  58. package/dist/services/artifacts/prerequisite-transition-event.js +27 -0
  59. package/dist/services/artifacts/request-artifact-metadata.d.ts +31 -0
  60. package/dist/services/artifacts/request-artifact-metadata.js +44 -0
  61. package/dist/services/artifacts/request-artifact-service.d.ts +5 -0
  62. package/dist/services/artifacts/request-artifact-service.js +23 -51
  63. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +12 -0
  64. package/dist/services/artifacts/request-artifact-state-helpers.js +28 -4
  65. package/dist/services/artifacts/request-retag-service.d.ts +68 -0
  66. package/dist/services/artifacts/request-retag-service.js +125 -0
  67. package/dist/services/artifacts/request-state-order.d.ts +38 -0
  68. package/dist/services/artifacts/request-state-order.js +99 -0
  69. package/dist/services/artifacts/request-type-demand.d.ts +44 -0
  70. package/dist/services/artifacts/request-type-demand.js +71 -0
  71. package/dist/services/audit/audit-goal-service.d.ts +7 -0
  72. package/dist/services/audit/enforcers/active-skill-resolver.d.ts +18 -0
  73. package/dist/services/audit/enforcers/active-skill-resolver.js +48 -1
  74. package/dist/services/audit/enforcers/code-ban.d.ts +11 -2
  75. package/dist/services/audit/enforcers/code-ban.js +21 -1
  76. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.d.ts +17 -0
  77. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.js +24 -7
  78. package/dist/services/audit-independent/handoff-missing-refusal.d.ts +26 -0
  79. package/dist/services/audit-independent/handoff-missing-refusal.js +109 -0
  80. package/dist/services/audit-independent/handoff-readers.d.ts +37 -0
  81. package/dist/services/audit-independent/handoff-readers.js +81 -0
  82. package/dist/services/audit-independent/index.d.ts +6 -1
  83. package/dist/services/audit-independent/index.js +6 -1
  84. package/dist/services/audit-independent/judged-declaration-build.d.ts +48 -0
  85. package/dist/services/audit-independent/judged-declaration-build.js +73 -0
  86. package/dist/services/audit-independent/judged-declaration-check.d.ts +79 -0
  87. package/dist/services/audit-independent/judged-declaration-check.js +155 -0
  88. package/dist/services/audit-independent/judged-declaration.d.ts +94 -0
  89. package/dist/services/audit-independent/judged-declaration.js +218 -0
  90. package/dist/services/audit-independent/perf-audit-service.js +12 -14
  91. package/dist/services/audit-independent/security-audit-artifact.d.ts +28 -0
  92. package/dist/services/audit-independent/security-audit-artifact.js +90 -0
  93. package/dist/services/audit-independent/security-audit-service.d.ts +6 -53
  94. package/dist/services/audit-independent/security-audit-service.js +34 -178
  95. package/dist/services/capability-guard-runner/contracts/J05.js +60 -14
  96. package/dist/services/codegraph/codegraph-index-integrity.js +2 -0
  97. package/dist/services/context/build-dispatch-system-prompt.d.ts +3 -3
  98. package/dist/services/context/build-dispatch-system-prompt.js +7 -7
  99. package/dist/services/context/collector.js +5 -1
  100. package/dist/services/dispatch/active-dispatch-index.d.ts +36 -0
  101. package/dist/services/dispatch/active-dispatch-index.js +118 -0
  102. package/dist/services/dispatch/batch-counter.js +1 -2
  103. package/dist/services/dispatch/dispatch-record-writer.d.ts +29 -16
  104. package/dist/services/dispatch/dispatch-record-writer.js +58 -100
  105. package/dist/services/dispatch/dispatch-sub-agent.js +1 -1
  106. package/dist/services/dispatch/karpathy-block.d.ts +55 -0
  107. package/dist/services/dispatch/karpathy-block.js +101 -0
  108. package/dist/services/dispatch/ledger-reaper.d.ts +80 -0
  109. package/dist/services/dispatch/ledger-reaper.js +131 -0
  110. package/dist/services/evidence/evidence-generator.js +15 -8
  111. package/dist/services/feedback/feedback-promotion-service.d.ts +8 -11
  112. package/dist/services/feedback/feedback-promotion-service.js +30 -35
  113. package/dist/services/feedback/promotion-artifact-json-evidence.d.ts +18 -0
  114. package/dist/services/feedback/promotion-artifact-missing.d.ts +22 -0
  115. package/dist/services/feedback/promotion-artifact-missing.js +63 -0
  116. package/dist/services/final-review/final-review-contract.d.ts +95 -4
  117. package/dist/services/final-review/final-review-contract.js +64 -0
  118. package/dist/services/final-review/final-review-delivery.d.ts +13 -0
  119. package/dist/services/final-review/final-review-delivery.js +26 -12
  120. package/dist/services/final-review/final-review-evidence-collect.js +8 -53
  121. package/dist/services/final-review/final-review-evidence-records.d.ts +21 -0
  122. package/dist/services/final-review/final-review-evidence-records.js +67 -0
  123. package/dist/services/final-review/final-review-evidence-sources.d.ts +22 -0
  124. package/dist/services/final-review/final-review-evidence-sources.js +28 -4
  125. package/dist/services/final-review/final-review-prompt.js +19 -6
  126. package/dist/services/final-review/final-review-runner.js +5 -0
  127. package/dist/services/final-review/final-review-service.d.ts +2 -2
  128. package/dist/services/final-review/index.d.ts +1 -1
  129. package/dist/services/final-review/pre-post-diff.d.ts +2 -75
  130. package/dist/services/final-review/pre-post-diff.js +60 -59
  131. package/dist/services/hooks/pre-tool-code-gate.d.ts +7 -1
  132. package/dist/services/hooks/pre-tool-code-gate.js +21 -2
  133. package/dist/services/hooks/worktree-authorization-gate.js +6 -31
  134. package/dist/services/hooks/worktree-refusal-messages.d.ts +74 -0
  135. package/dist/services/hooks/worktree-refusal-messages.js +102 -0
  136. package/dist/services/lint/eslint-runner-support.d.ts +1 -1
  137. package/dist/services/lint/eslint-runner-support.js +2 -1
  138. package/dist/services/lint/eslint-runner-types.d.ts +8 -0
  139. package/dist/services/lint/eslint-runner.js +17 -4
  140. package/dist/services/llm/anthropic-runner.js +24 -7
  141. package/dist/services/loop/loop-observability.d.ts +39 -0
  142. package/dist/services/loop/loop-observability.js +55 -0
  143. package/dist/services/loop/monotonic-guard.js +6 -9
  144. package/dist/services/loop/monotonic-runner.js +8 -7
  145. package/dist/services/loop/run-driver.js +18 -22
  146. package/dist/services/memory/project-memory-service/index/kind-dispatch.js +14 -1
  147. package/dist/services/memory/project-memory-service/index/project-memory-plan-exec.js +13 -2
  148. package/dist/services/memory/project-memory-service/index.d.ts +2 -2
  149. package/dist/services/memory/project-memory-service/index.js +1 -1
  150. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.d.ts +36 -0
  151. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.js +48 -2
  152. package/dist/services/memory/project-memory-service/parsers/markdown-pure.d.ts +23 -1
  153. package/dist/services/memory/project-memory-service/parsers/markdown-pure.js +37 -0
  154. package/dist/services/memory/project-memory-service/types.d.ts +32 -0
  155. package/dist/services/observability/observability-service.d.ts +7 -0
  156. package/dist/services/observability/observability-service.js +2 -1
  157. package/dist/services/prd/gate-evidence-derivation.d.ts +4 -3
  158. package/dist/services/prd/gate-evidence-derivation.js +4 -3
  159. package/dist/services/qa/bdd-test-style-verifier.js +22 -8
  160. package/dist/services/race/gate2-evaluator.d.ts +58 -0
  161. package/dist/services/race/gate2-evaluator.js +111 -0
  162. package/dist/services/race/gate2-policy.d.ts +17 -0
  163. package/dist/services/race/gate2-policy.js +31 -0
  164. package/dist/services/race/lane-phase.d.ts +19 -0
  165. package/dist/services/race/lane-phase.js +113 -0
  166. package/dist/services/race/pilot-gate-store.d.ts +67 -0
  167. package/dist/services/race/pilot-gate-store.js +227 -0
  168. package/dist/services/scan/file-size-baseline.d.ts +26 -0
  169. package/dist/services/scan/file-size-baseline.js +150 -0
  170. package/dist/services/scan/file-size-scan.d.ts +42 -3
  171. package/dist/services/scan/file-size-scan.js +58 -42
  172. package/dist/services/scan/type-sanity-service.js +13 -3
  173. package/dist/services/skill/resume-detector.js +3 -3
  174. package/dist/services/skills/hooks-codegate-superpowers.d.ts +5 -6
  175. package/dist/services/skills/hooks-codegate-superpowers.js +7 -8
  176. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  177. package/dist/services/skills/hooks-settings-service.js +1 -1
  178. package/dist/services/skills/presence-lease-order.d.ts +13 -0
  179. package/dist/services/skills/presence-lease-order.js +24 -0
  180. package/dist/services/skills/skill-conformance-service.js +1 -0
  181. package/dist/services/skills/skill-statusline-service.js +4 -7
  182. package/dist/services/slice/slice-check-service.js +8 -8
  183. package/dist/services/workflow/pipeline-verify-gate-support.js +2 -1
  184. package/dist/services/workflow/pipeline-verify-service.js +1 -1
  185. package/dist/services/workflow/workflow-skip-service.d.ts +0 -20
  186. package/dist/services/workflow/workflow-skip-service.js +3 -4
  187. package/dist/services/workspace/claude-settings-retirements.d.ts +54 -0
  188. package/dist/services/workspace/claude-settings-retirements.js +112 -0
  189. package/dist/services/workspace/claude-settings-template-merge.d.ts +35 -15
  190. package/dist/services/workspace/claude-settings-template-merge.js +33 -53
  191. package/dist/services/workspace/claude-settings-template.d.ts +62 -12
  192. package/dist/services/workspace/claude-settings-template.js +58 -58
  193. package/dist/services/workspace/migrate-1-4-1-service.js +3 -0
  194. package/dist/services/workspace/reconcile-service.js +0 -1
  195. package/dist/shared/incrementing-number.d.ts +10 -0
  196. package/dist/shared/incrementing-number.js +27 -0
  197. package/package.json +5 -5
  198. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  199. package/skills/bee/peaks-prd/SKILL.md +1 -1
  200. package/skills/bee/peaks-qa/SKILL.md +1 -1
  201. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  202. package/skills/bee/peaks-qa/references/qa-transition-gates.md +1 -1
  203. package/skills/bee/peaks-rd/SKILL.md +2 -2
  204. package/skills/bee/peaks-rd/references/rd-fanout-contracts.md +1 -1
  205. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +8 -4
  206. package/skills/bee/peaks-rd/references/rd-transition-gates.md +3 -3
  207. package/skills/bee/peaks-rd/references/v2-12-fanout-collapse.md +2 -2
  208. package/skills/bee/peaks-rd/references/writing-handoff-frontmatter.md +1 -1
  209. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  210. package/skills/bee/peaks-sc/SKILL.md +1 -1
  211. package/skills/bee/peaks-security-audit/SKILL.md +10 -2
  212. package/skills/bee/peaks-txt/SKILL.md +4 -3
  213. package/skills/bee/peaks-ui/SKILL.md +3 -3
  214. package/skills/peaks-audit/SKILL.md +29 -1
  215. package/skills/peaks-code/SKILL.md +5 -2
  216. package/skills/peaks-code/references/fast-lane-norm.md +42 -0
  217. package/skills/peaks-code/references/fast-mode.md +3 -2
  218. package/skills/peaks-code/references/local-artifact-workspace.md +3 -3
  219. package/skills/peaks-code/references/micro-cycle.md +3 -3
  220. package/skills/peaks-code/references/resume-detection.md +1 -1
  221. package/skills/peaks-code/references/runbook.md +12 -6
  222. package/skills/peaks-code/references/step-11-memory-sediment.md +4 -0
  223. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  224. package/skills/peaks-code/references/swarm-dispatch-contract.md +40 -16
  225. package/skills/peaks-code/references/workflow-gates-and-types.md +6 -6
  226. package/skills/peaks-code/references/worktree-governance.md +4 -4
  227. package/skills/peaks-content/SKILL.md +1 -1
  228. package/skills/peaks-doctor/SKILL.md +1 -1
  229. package/skills/peaks-final-review/SKILL.md +31 -11
  230. package/skills/peaks-ide/SKILL.md +1 -1
  231. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  232. package/skills/peaks-race-code/SKILL.md +185 -0
  233. package/skills/peaks-resume/SKILL.md +1 -1
  234. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  235. package/skills/peaks-solo/SKILL.md +1 -1
  236. package/skills/peaks-sop/SKILL.md +1 -1
  237. package/skills/peaks-status/SKILL.md +1 -1
  238. package/skills/peaks-test/SKILL.md +7 -4
  239. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.d.ts +0 -23
  240. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.js +0 -64
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The machine-readable declaration of what an audit judged.
3
+ *
4
+ * `## Red-line scope` in the RD request is prose for a human and is read by no
5
+ * machine here. The declaration is the only machine-read statement of a
6
+ * slice's surface, and the producer that emits the artifact writes it, so a
7
+ * caller cannot produce the artifact without one.
8
+ *
9
+ * Grammar — exactly one fenced json block under the heading `## Judged content`:
10
+ *
11
+ * ## Judged content
12
+ *
13
+ * ```json
14
+ * {"schemaVersion":1,"judgedAt":"2026-10-13T00:00:00.000Z","handoffHash":"unknown",
15
+ * "files":[{"path":"src/a.ts","sha256":"<64 hex>"}],
16
+ * "roots":[{"path":"src/dir","why":"<text>"}]}
17
+ * ```
18
+ *
19
+ * Rules. No backslash anywhere in the block: JSON resolves an escaped spelling
20
+ * to the same string, so a raw reader and a parsing reader could disagree about
21
+ * what was declared. A `path` is a relative POSIX path with no `..` and no
22
+ * leading slash; `files` is non-empty; a duplicate path is refused. A root
23
+ * entry must carry a non-empty `why` — a bare directory root is refused.
24
+ *
25
+ * LIMIT, recorded rather than fixed: any rule keyed on a self-reported field is
26
+ * closed against accidental shedding, and not against a producer that rewrites
27
+ * its own field.
28
+ */
29
+ export declare const JUDGED_HEADING = "## Judged content";
30
+ export declare const JUDGED_SCHEMA_VERSION = 1;
31
+ export type JudgedFile = {
32
+ readonly path: string;
33
+ readonly sha256: string;
34
+ };
35
+ export type JudgedRoot = {
36
+ readonly path: string;
37
+ readonly why: string;
38
+ };
39
+ export type JudgedDeclaration = {
40
+ readonly schemaVersion: number;
41
+ readonly judgedAt: string;
42
+ readonly handoffHash: string;
43
+ readonly files: readonly JudgedFile[];
44
+ readonly roots: readonly JudgedRoot[];
45
+ };
46
+ export type JudgedParseFailure = {
47
+ readonly ok: false;
48
+ readonly code: string;
49
+ readonly detail: string;
50
+ };
51
+ export type JudgedParseResult = {
52
+ readonly ok: true;
53
+ readonly declaration: JudgedDeclaration;
54
+ } | JudgedParseFailure;
55
+ /**
56
+ * The audit service's detect result when the declaration cannot be built. It
57
+ * lives here so the producer can substitute it for the probe's verdict without
58
+ * growing the service's own branch count.
59
+ */
60
+ export declare function declarationMissingDetect(detect: {
61
+ readonly handoffPresent: boolean;
62
+ readonly templatePresent: boolean;
63
+ }, failure: JudgedParseFailure): {
64
+ readonly state: 'declaration-missing';
65
+ readonly handoffPresent: boolean;
66
+ readonly templatePresent: boolean;
67
+ readonly warnings: readonly string[];
68
+ readonly nextActions: readonly string[];
69
+ };
70
+ export type Sha256Result = {
71
+ readonly ok: true;
72
+ readonly sha256: string;
73
+ } | {
74
+ readonly ok: false;
75
+ readonly code: 'missing' | 'unreadable';
76
+ readonly detail: string;
77
+ };
78
+ /** Hash the bytes of one file. A missing file is reported, never guessed. */
79
+ export declare function sha256OfFile(absPath: string): Sha256Result;
80
+ /** A declared path is a relative POSIX path pointing at one file. */
81
+ export declare function validateDeclaredPath(raw: unknown): {
82
+ ok: true;
83
+ path: string;
84
+ } | {
85
+ ok: false;
86
+ detail: string;
87
+ };
88
+ /** Render the declaration as the artifact section the check reads back. */
89
+ export declare function renderJudgedDeclaration(declaration: JudgedDeclaration): string;
90
+ /**
91
+ * Parse the declaration out of an artifact body. Strict on shape: a block that
92
+ * parses to something other than the grammar is a refusal, never a default.
93
+ */
94
+ export declare function parseJudgedDeclaration(body: string): JudgedParseResult;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * The machine-readable declaration of what an audit judged.
3
+ *
4
+ * `## Red-line scope` in the RD request is prose for a human and is read by no
5
+ * machine here. The declaration is the only machine-read statement of a
6
+ * slice's surface, and the producer that emits the artifact writes it, so a
7
+ * caller cannot produce the artifact without one.
8
+ *
9
+ * Grammar — exactly one fenced json block under the heading `## Judged content`:
10
+ *
11
+ * ## Judged content
12
+ *
13
+ * ```json
14
+ * {"schemaVersion":1,"judgedAt":"2026-10-13T00:00:00.000Z","handoffHash":"unknown",
15
+ * "files":[{"path":"src/a.ts","sha256":"<64 hex>"}],
16
+ * "roots":[{"path":"src/dir","why":"<text>"}]}
17
+ * ```
18
+ *
19
+ * Rules. No backslash anywhere in the block: JSON resolves an escaped spelling
20
+ * to the same string, so a raw reader and a parsing reader could disagree about
21
+ * what was declared. A `path` is a relative POSIX path with no `..` and no
22
+ * leading slash; `files` is non-empty; a duplicate path is refused. A root
23
+ * entry must carry a non-empty `why` — a bare directory root is refused.
24
+ *
25
+ * LIMIT, recorded rather than fixed: any rule keyed on a self-reported field is
26
+ * closed against accidental shedding, and not against a producer that rewrites
27
+ * its own field.
28
+ */
29
+ import { createHash } from 'node:crypto';
30
+ import { readFileSync } from 'node:fs';
31
+ export const JUDGED_HEADING = '## Judged content';
32
+ export const JUDGED_SCHEMA_VERSION = 1;
33
+ /**
34
+ * The audit service's detect result when the declaration cannot be built. It
35
+ * lives here so the producer can substitute it for the probe's verdict without
36
+ * growing the service's own branch count.
37
+ */
38
+ export function declarationMissingDetect(detect, failure) {
39
+ return {
40
+ state: 'declaration-missing',
41
+ handoffPresent: detect.handoffPresent,
42
+ templatePresent: detect.templatePresent,
43
+ warnings: [
44
+ `security-audit refused: the judged declaration is not buildable (${failure.code}: ${failure.detail}).`
45
+ ],
46
+ nextActions: [
47
+ 'Pass every judged path with --judged <path> (repeatable); each must exist and be a file.',
48
+ 'A run that declares nothing is refused rather than given an unbounded surface.'
49
+ ]
50
+ };
51
+ }
52
+ /** Hash the bytes of one file. A missing file is reported, never guessed. */
53
+ export function sha256OfFile(absPath) {
54
+ let bytes;
55
+ try {
56
+ bytes = readFileSync(absPath);
57
+ }
58
+ catch (error) {
59
+ const code = error.code === 'ENOENT' ? 'missing' : 'unreadable';
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ return { ok: false, code, detail };
62
+ }
63
+ return { ok: true, sha256: createHash('sha256').update(bytes).digest('hex') };
64
+ }
65
+ /** A declared path is a relative POSIX path pointing at one file. */
66
+ export function validateDeclaredPath(raw) {
67
+ if (typeof raw !== 'string' || raw.length === 0) {
68
+ return { ok: false, detail: 'path must be a non-empty string' };
69
+ }
70
+ if (raw.includes('\\'))
71
+ return { ok: false, detail: `path must not contain a backslash: ${raw}` };
72
+ if (raw.startsWith('/'))
73
+ return { ok: false, detail: `path must be relative: ${raw}` };
74
+ if (/^[a-zA-Z]:/.test(raw))
75
+ return { ok: false, detail: `path must be relative: ${raw}` };
76
+ if (raw.endsWith('/')) {
77
+ return { ok: false, detail: `path must name a file, not a directory: ${raw}` };
78
+ }
79
+ const segments = raw.split('/');
80
+ if (segments.some((s) => s === '' || s === '.' || s === '..')) {
81
+ return { ok: false, detail: `path must be normalised with no traversal: ${raw}` };
82
+ }
83
+ return { ok: true, path: raw };
84
+ }
85
+ const HEX64 = /^[a-f0-9]{64}$/;
86
+ /** Render the declaration as the artifact section the check reads back. */
87
+ export function renderJudgedDeclaration(declaration) {
88
+ const payload = {
89
+ schemaVersion: declaration.schemaVersion,
90
+ judgedAt: declaration.judgedAt,
91
+ handoffHash: declaration.handoffHash,
92
+ files: declaration.files.map((f) => ({ path: f.path, sha256: f.sha256 })),
93
+ roots: declaration.roots.map((r) => ({ path: r.path, why: r.why }))
94
+ };
95
+ return [JUDGED_HEADING, '', '```json', JSON.stringify(payload), '```', ''].join('\n');
96
+ }
97
+ /**
98
+ * Extract the fenced block under the heading. Returns the raw block text or a
99
+ * code naming why there is none. Deliberately literal: a heading that does not
100
+ * match byte-for-byte is a missing declaration, not a variant to accommodate.
101
+ */
102
+ function extractJudgedBlock(body) {
103
+ const lines = body.split(/\r?\n/);
104
+ const start = lines.findIndex((line) => line.trimEnd() === JUDGED_HEADING);
105
+ if (start === -1)
106
+ return { ok: false, code: 'declaration-missing' };
107
+ const rest = lines.slice(start + 1);
108
+ const fenceStart = rest.findIndex((line) => line.trim() === '```json');
109
+ if (fenceStart === -1)
110
+ return { ok: false, code: 'declaration-unfenced' };
111
+ const block = [];
112
+ for (const line of rest.slice(fenceStart + 1)) {
113
+ if (line.trim() === '```')
114
+ return { ok: true, block: block.join('\n') };
115
+ block.push(line);
116
+ }
117
+ return { ok: false, code: 'declaration-unterminated' };
118
+ }
119
+ function parseFileEntries(raw) {
120
+ if (!Array.isArray(raw) || raw.length === 0) {
121
+ return { ok: false, code: 'declaration-empty', detail: 'files must be a non-empty array' };
122
+ }
123
+ const files = [];
124
+ const seen = new Set();
125
+ for (const entry of raw) {
126
+ if (entry === null || typeof entry !== 'object') {
127
+ return { ok: false, code: 'declaration-schema', detail: 'a files entry is not an object' };
128
+ }
129
+ const row = entry;
130
+ const checked = validateDeclaredPath(row['path']);
131
+ if (!checked.ok)
132
+ return { ok: false, code: 'declaration-path', detail: checked.detail };
133
+ if (typeof row['sha256'] !== 'string' || !HEX64.test(row['sha256'])) {
134
+ return { ok: false, code: 'declaration-hash', detail: checked.path };
135
+ }
136
+ if (seen.has(checked.path)) {
137
+ return { ok: false, code: 'declaration-duplicate', detail: checked.path };
138
+ }
139
+ seen.add(checked.path);
140
+ files.push({ path: checked.path, sha256: row['sha256'] });
141
+ }
142
+ return { ok: true, files };
143
+ }
144
+ function parseRootEntries(raw) {
145
+ if (!Array.isArray(raw)) {
146
+ return { ok: false, code: 'declaration-schema', detail: 'roots must be an array' };
147
+ }
148
+ const roots = [];
149
+ for (const entry of raw) {
150
+ if (entry === null || typeof entry !== 'object') {
151
+ return { ok: false, code: 'declaration-schema', detail: 'a roots entry is not an object' };
152
+ }
153
+ const row = entry;
154
+ const checked = validateDeclaredPath(row['path']);
155
+ if (!checked.ok)
156
+ return { ok: false, code: 'declaration-path', detail: checked.detail };
157
+ const why = row['why'];
158
+ if (typeof why !== 'string' || why.trim().length === 0) {
159
+ return { ok: false, code: 'declaration-bare-root', detail: checked.path };
160
+ }
161
+ roots.push({ path: checked.path, why });
162
+ }
163
+ return { ok: true, roots };
164
+ }
165
+ function parseEnvelopeBlock(block) {
166
+ // A backslash is refused before parsing, not after: JSON resolves escapes, so
167
+ // a parsed value and the raw bytes could describe different surfaces.
168
+ if (block.includes('\\')) {
169
+ return { ok: false, code: 'declaration-escaped', detail: 'the block contains a backslash' };
170
+ }
171
+ let raw;
172
+ try {
173
+ raw = JSON.parse(block);
174
+ }
175
+ catch (error) {
176
+ const detail = error instanceof Error ? error.message : String(error);
177
+ return { ok: false, code: 'declaration-unparsable', detail };
178
+ }
179
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
180
+ return { ok: false, code: 'declaration-unparsable', detail: 'the block is not a JSON object' };
181
+ }
182
+ const obj = raw;
183
+ if (obj['schemaVersion'] !== JUDGED_SCHEMA_VERSION) {
184
+ return { ok: false, code: 'declaration-schema', detail: String(obj['schemaVersion']) };
185
+ }
186
+ if (typeof obj['judgedAt'] !== 'string' || typeof obj['handoffHash'] !== 'string') {
187
+ return { ok: false, code: 'declaration-schema', detail: 'judgedAt / handoffHash' };
188
+ }
189
+ return { ok: true, obj };
190
+ }
191
+ /**
192
+ * Parse the declaration out of an artifact body. Strict on shape: a block that
193
+ * parses to something other than the grammar is a refusal, never a default.
194
+ */
195
+ export function parseJudgedDeclaration(body) {
196
+ const extracted = extractJudgedBlock(body);
197
+ if (!extracted.ok)
198
+ return { ok: false, code: extracted.code, detail: JUDGED_HEADING };
199
+ const envelope = parseEnvelopeBlock(extracted.block);
200
+ if (!envelope.ok)
201
+ return envelope;
202
+ const files = parseFileEntries(envelope.obj['files']);
203
+ if (!files.ok)
204
+ return files;
205
+ const roots = parseRootEntries(envelope.obj['roots'] ?? []);
206
+ if (!roots.ok)
207
+ return roots;
208
+ return {
209
+ ok: true,
210
+ declaration: {
211
+ schemaVersion: JUDGED_SCHEMA_VERSION,
212
+ judgedAt: envelope.obj['judgedAt'],
213
+ handoffHash: envelope.obj['handoffHash'],
214
+ files: files.files,
215
+ roots: roots.roots
216
+ }
217
+ };
218
+ }
@@ -20,11 +20,12 @@
20
20
  * - Schema: `.peaks/project-scan/audit-output-schema.md` (schemaVersion: 1)
21
21
  * - Companion: `src/services/audit-independent/security-audit-service.ts`
22
22
  */
23
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
23
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
24
24
  import { join, resolve, isAbsolute } from 'node:path';
25
25
  import { createHash } from 'node:crypto';
26
26
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
27
27
  import { resolveHandoffPath } from '../prd/handoff-service.js';
28
+ import { handoffMissingRefusal } from './handoff-missing-refusal.js';
28
29
  /**
29
30
  * Validate a raw value as a PerfAuditEnvelope. Mirrors the
30
31
  * `isSecurityAuditEnvelope` strict-shape pattern.
@@ -150,22 +151,20 @@ export function detectPerfAudit(input) {
150
151
  const templatePath = join(input.projectRoot, '.peaks', 'project-scan', 'perf-template.md');
151
152
  const templatePresent = existsSync(templatePath);
152
153
  if (!handoffPresent) {
154
+ const refusal = handoffMissingRefusal({
155
+ role: 'perf',
156
+ projectRoot: input.projectRoot,
157
+ sessionId: input.sessionId,
158
+ ...(input.requestId !== undefined ? { requestId: input.requestId } : {}),
159
+ // Measured, not assumed: `detect` supplies no envelope at all.
160
+ envelopeValidated: input.envelope !== undefined && isPerfAuditEnvelope(input.envelope)
161
+ });
153
162
  return {
154
163
  state: 'handoff-missing',
155
164
  handoffPresent: false,
156
165
  templatePresent,
157
- warnings: [
158
- `peaks-prd handoff not found under ${join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'prd')}`,
159
- ...(input.requestId === undefined
160
- ? [
161
- "No --rid was supplied, so only the pre-rid-scoping `prd/handoff.md` could be probed. Pass --rid to resolve this slice's `prd/handoff-<rid>.md`."
162
- ]
163
- : [])
164
- ],
165
- nextActions: [
166
- 'Run peaks-prd handoff init to produce a sha256-locked handoff before running peaks perf-audit.',
167
- 'Until the handoff exists, peaks-perf-audit cannot start (gate fail).'
168
- ]
166
+ warnings: refusal.warnings,
167
+ nextActions: refusal.nextActions
169
168
  };
170
169
  }
171
170
  if (!templatePresent) {
@@ -303,7 +302,6 @@ export function writePerfAuditArtifact(projectRoot, sessionId, rid, body) {
303
302
  const tmpPath = `${targetPath}.tmp`;
304
303
  writeFileSync(tmpPath, body, 'utf8');
305
304
  // Sync rename: on Windows, fs.renameSync overwrites if target exists (Node 22+)
306
- const { renameSync } = require('node:fs');
307
305
  renameSync(tmpPath, targetPath);
308
306
  return targetPath;
309
307
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Rendering and writing of the security audit artifact. Split out of
3
+ * `security-audit-service.ts`, which was over the per-file cap; the service now
4
+ * depends on this module rather than carrying the markdown itself.
5
+ */
6
+ import type { SecurityAuditEnvelope, SecurityAuditVerdict } from './security-audit-service.js';
7
+ /**
8
+ * Render a SecurityAuditEnvelope to the canonical audit artifact body
9
+ * (markdown). Produce a markdown body with all required sections, ready to
10
+ * write to `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
11
+ */
12
+ export declare function renderSecurityAuditArtifact(env: SecurityAuditEnvelope, opts: {
13
+ rid: string;
14
+ handoffHash: string;
15
+ generatedAt: string;
16
+ }): {
17
+ body: string;
18
+ violationsCount: number;
19
+ verdict: SecurityAuditVerdict;
20
+ };
21
+ /**
22
+ * Write the rendered audit artifact to
23
+ * `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
24
+ *
25
+ * Atomic write (tmp + rename) to avoid partial writes on crash.
26
+ * Returns the absolute path on success.
27
+ */
28
+ export declare function writeSecurityAuditArtifact(projectRoot: string, sessionId: string, rid: string, body: string): string;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Rendering and writing of the security audit artifact. Split out of
3
+ * `security-audit-service.ts`, which was over the per-file cap; the service now
4
+ * depends on this module rather than carrying the markdown itself.
5
+ */
6
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
9
+ /**
10
+ * Render a SecurityAuditEnvelope to the canonical audit artifact body
11
+ * (markdown). Produce a markdown body with all required sections, ready to
12
+ * write to `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
13
+ */
14
+ export function renderSecurityAuditArtifact(env, opts) {
15
+ const counts = {};
16
+ for (const v of env.violations) {
17
+ counts[v.severity] = (counts[v.severity] ?? 0) + 1;
18
+ }
19
+ const criticalCount = counts['CRITICAL'] ?? 0;
20
+ const findingsBullets = env.violations.length === 0
21
+ ? '- (none)'
22
+ : env.violations
23
+ .map((v) => `- [${v.severity}] ${v.dimension} @ ${v.file}:${v.line} — ${v.hint}`)
24
+ .join('\n');
25
+ const requiredFixes = buildRequiredFixes(env);
26
+ const body = [
27
+ '## Summary',
28
+ '',
29
+ env.summary,
30
+ '',
31
+ '## Threat model coverage',
32
+ '',
33
+ `audited at: ${opts.generatedAt}`,
34
+ `verdict: ${env.verdict}`,
35
+ `handoffHash: ${opts.handoffHash}`,
36
+ '',
37
+ '## Findings',
38
+ '',
39
+ findingsBullets,
40
+ '',
41
+ requiredFixes,
42
+ '## Verdict',
43
+ '',
44
+ `verdict: ${env.verdict}`,
45
+ `CRITICAL: ${criticalCount}`,
46
+ ''
47
+ ]
48
+ .filter((s) => s.length > 0)
49
+ .join('\n');
50
+ return {
51
+ body,
52
+ violationsCount: env.violations.length,
53
+ verdict: env.verdict
54
+ };
55
+ }
56
+ function buildRequiredFixes(env) {
57
+ const requiredFixes = env.violations.length === 0
58
+ ? ''
59
+ : [
60
+ '## Required fixes',
61
+ '',
62
+ ...env.violations.map((v) => `- [${v.severity}] ${v.file}:${v.line} — ${v.hint}`),
63
+ ''
64
+ ].join('\n');
65
+ return requiredFixes;
66
+ }
67
+ /**
68
+ * Write the rendered audit artifact to
69
+ * `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
70
+ *
71
+ * Atomic write (tmp + rename) to avoid partial writes on crash.
72
+ * Returns the absolute path on success.
73
+ */
74
+ export function writeSecurityAuditArtifact(projectRoot, sessionId, rid, body) {
75
+ // The rid is a filename below, and the write is tmp+rename, so an
76
+ // unvalidated rid can OVERWRITE an arbitrary `.md` rather than merely create
77
+ // one. Guarded here (not only at the CLI boundary) so no caller can skip it.
78
+ if (!REQUEST_ID_PATTERN.test(rid)) {
79
+ throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
80
+ }
81
+ const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
82
+ mkdirSync(targetDir, { recursive: true });
83
+ const targetPath = join(targetDir, `security-${rid}.md`);
84
+ // tmp + rename for atomicity
85
+ const tmpPath = `${targetPath}.tmp`;
86
+ writeFileSync(tmpPath, body, 'utf8');
87
+ // Sync rename: on Windows, fs.renameSync overwrites if target exists (Node 22+)
88
+ renameSync(tmpPath, targetPath);
89
+ return targetPath;
90
+ }
@@ -39,7 +39,7 @@
39
39
  * - `dispatch-failed` — parent LLM threw before returning the audit envelope
40
40
  * - `envelope-malformed` — parent LLM returned a value that fails `isSecurityAuditEnvelope`
41
41
  */
42
- export type SecurityAuditDetectState = 'ready' | 'handoff-missing' | 'template-missing' | 'dispatch-failed' | 'envelope-malformed';
42
+ export type SecurityAuditDetectState = 'ready' | 'handoff-missing' | 'template-missing' | 'dispatch-failed' | 'envelope-malformed' | 'declaration-missing';
43
43
  export interface SecurityAuditDetectResult {
44
44
  readonly state: SecurityAuditDetectState;
45
45
  readonly handoffPresent: boolean;
@@ -65,35 +65,6 @@ export interface SecurityAuditEnvelope {
65
65
  * `isEccEnvelope` strict-shape pattern.
66
66
  */
67
67
  export declare function isSecurityAuditEnvelope(value: unknown): value is SecurityAuditEnvelope;
68
- /**
69
- * Handoff frontmatter — minimal projection of peaks-prd v2.11.0 handoff
70
- * frontmatter. We only need sha256 for verification; the rest of the
71
- * handoff body is consumed by the parent LLM, not by this service.
72
- */
73
- export interface HandoffFrontmatter {
74
- readonly sha256: string;
75
- readonly schemaVersion: number;
76
- }
77
- /**
78
- * Read the peaks-prd handoff frontmatter + body, verify sha256 matches
79
- * the body. Returns null on missing file or sha256 mismatch; otherwise
80
- * returns the parsed frontmatter + body string.
81
- *
82
- * Defensive: we read frontmatter via a 1-line regex match, not via
83
- * a YAML parser. The handoff service (`src/services/prd/handoff-service.ts`)
84
- * is the canonical writer; we only consume its output here.
85
- */
86
- export declare function readAndVerifyHandoff(handoffPath: string, projectRoot: string): {
87
- frontmatter: HandoffFrontmatter;
88
- body: string;
89
- } | null;
90
- /**
91
- * Read the project-level security-template.md. Returns the body
92
- * string (with frontmatter stripped) or null if the file is absent.
93
- * Does NOT validate the template content; the parent LLM validates
94
- * by reading.
95
- */
96
- export declare function readSecurityTemplate(projectRoot: string): string | null;
97
68
  /**
98
69
  * 5-state detector. The parent skill inspects the state and either
99
70
  * proceeds (when `ready`) or records a degradation note and falls
@@ -115,29 +86,6 @@ export declare function detectSecurityAudit(input: {
115
86
  readonly dispatchError?: unknown;
116
87
  readonly envelope?: unknown;
117
88
  }): SecurityAuditDetectResult;
118
- /**
119
- * Render a SecurityAuditEnvelope to the canonical audit artifact body
120
- * (markdown). Mirrors `adaptEccEnvelopeToRdCodeReview` in ecc-bridge.ts:
121
- * produce a markdown body with all required sections, ready to write
122
- * to `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
123
- */
124
- export declare function renderSecurityAuditArtifact(env: SecurityAuditEnvelope, opts: {
125
- rid: string;
126
- handoffHash: string;
127
- generatedAt: string;
128
- }): {
129
- body: string;
130
- violationsCount: number;
131
- verdict: SecurityAuditVerdict;
132
- };
133
- /**
134
- * Write the rendered audit artifact to
135
- * `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
136
- *
137
- * Atomic write (tmp + rename) to avoid partial writes on crash.
138
- * Returns the absolute path on success.
139
- */
140
- export declare function writeSecurityAuditArtifact(projectRoot: string, sessionId: string, rid: string, body: string): string;
141
89
  /**
142
90
  * Convenience: run `detectSecurityAudit` + `renderSecurityAuditArtifact`
143
91
  * + `writeSecurityAuditArtifact` in one call.
@@ -150,6 +98,11 @@ export declare function runSecurityAudit(input: {
150
98
  readonly sessionId: string;
151
99
  readonly rid: string;
152
100
  readonly generatedAt: string;
101
+ /** Project-relative paths this audit judged; written into the artifact as
102
+ * the declaration the transition gate reads back. Required — a path that
103
+ * cannot be hashed is refused, because a declaration naming a file that is
104
+ * not there cannot be checked later. */
105
+ readonly judgedPaths: readonly string[];
153
106
  readonly dispatchError?: unknown;
154
107
  readonly envelope?: unknown;
155
108
  }): {