peaks-loop 4.1.4 → 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 (294) hide show
  1. package/.claude-plugin/marketplace.json +7 -2
  2. package/CHANGELOG.md +148 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  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/best-practice-scan-command.d.ts +11 -6
  9. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  10. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  11. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  12. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  13. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  14. package/dist/cli/commands/code-commands.d.ts +6 -4
  15. package/dist/cli/commands/code-commands.js +6 -4
  16. package/dist/cli/commands/code-gate-command.d.ts +5 -5
  17. package/dist/cli/commands/code-gate-command.js +49 -9
  18. package/dist/cli/commands/code-mode-gate-plan-command.d.ts +1 -1
  19. package/dist/cli/commands/code-mode-gate-plan-command.js +2 -2
  20. package/dist/cli/commands/core/memory-extract-command.js +10 -5
  21. package/dist/cli/commands/dispatch-cli-invocation-check.d.ts +108 -0
  22. package/dist/cli/commands/dispatch-cli-invocation-check.js +87 -0
  23. package/dist/cli/commands/dispatch-cli-invocation-scan.d.ts +66 -0
  24. package/dist/cli/commands/dispatch-cli-invocation-scan.js +162 -0
  25. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  26. package/dist/cli/commands/dispatch-commands.js +12 -5
  27. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  28. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  29. package/dist/cli/commands/dispatch-preflight.js +46 -0
  30. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  31. package/dist/cli/commands/dispatch-prompt-composition.d.ts +7 -1
  32. package/dist/cli/commands/dispatch-prompt-composition.js +29 -7
  33. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  34. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  35. package/dist/cli/commands/doc-commands.js +1 -1
  36. package/dist/cli/commands/feedback-commands-helpers.js +1 -1
  37. package/dist/cli/commands/final-review-prepare-command.js +22 -1
  38. package/dist/cli/commands/gate-commands-enforce.js +3 -3
  39. package/dist/cli/commands/hook-handle.js +41 -20
  40. package/dist/cli/commands/lint-commands.js +3 -1
  41. package/dist/cli/commands/loop-eval-capture-index.js +2 -4
  42. package/dist/cli/commands/openspec-command-shared.js +2 -2
  43. package/dist/cli/commands/perf-audit-commands.js +15 -5
  44. package/dist/cli/commands/project-commands.js +9 -6
  45. package/dist/cli/commands/race-commands.d.ts +15 -0
  46. package/dist/cli/commands/race-commands.js +65 -0
  47. package/dist/cli/commands/race-pilot-gate-record-command.d.ts +3 -0
  48. package/dist/cli/commands/race-pilot-gate-record-command.js +81 -0
  49. package/dist/cli/commands/request-command-options.d.ts +8 -0
  50. package/dist/cli/commands/request-commands.js +2 -0
  51. package/dist/cli/commands/request-init-command.js +67 -12
  52. package/dist/cli/commands/{vm-status-command.d.ts → request-retag-command.d.ts} +1 -1
  53. package/dist/cli/commands/request-retag-command.js +50 -0
  54. package/dist/cli/commands/request-show-command.d.ts +8 -0
  55. package/dist/cli/commands/request-show-command.js +14 -1
  56. package/dist/cli/commands/request-transition-command.js +12 -4
  57. package/dist/cli/commands/request-transition-failures.d.ts +14 -0
  58. package/dist/cli/commands/request-transition-failures.js +76 -7
  59. package/dist/cli/commands/request-transition-preflight.js +1 -1
  60. package/dist/cli/commands/scan-scope-commands.js +2 -2
  61. package/dist/cli/commands/security-audit-commands.js +26 -6
  62. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  63. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  64. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  65. package/dist/cli/commands/worktree-lease-gc-command.js +1 -1
  66. package/dist/cli/program.js +0 -2
  67. package/dist/services/artifacts/artifact-contract-block.d.ts +53 -0
  68. package/dist/services/artifacts/artifact-contract-block.js +231 -0
  69. package/dist/services/artifacts/artifact-prerequisites.d.ts +27 -19
  70. package/dist/services/artifacts/artifact-prerequisites.js +65 -135
  71. package/dist/services/artifacts/artifact-templates.d.ts +1 -1
  72. package/dist/services/artifacts/artifact-templates.js +17 -10
  73. package/dist/services/artifacts/prerequisite-checks.d.ts +87 -0
  74. package/dist/services/artifacts/prerequisite-checks.js +198 -0
  75. package/dist/services/artifacts/prerequisite-transition-event.d.ts +20 -0
  76. package/dist/services/artifacts/prerequisite-transition-event.js +27 -0
  77. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  78. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  79. package/dist/services/artifacts/request-artifact-metadata.d.ts +31 -0
  80. package/dist/services/artifacts/request-artifact-metadata.js +44 -0
  81. package/dist/services/artifacts/request-artifact-service.d.ts +5 -0
  82. package/dist/services/artifacts/request-artifact-service.js +43 -69
  83. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +21 -1
  84. package/dist/services/artifacts/request-artifact-state-helpers.js +34 -8
  85. package/dist/services/artifacts/request-retag-service.d.ts +68 -0
  86. package/dist/services/artifacts/request-retag-service.js +125 -0
  87. package/dist/services/artifacts/request-state-order.d.ts +38 -0
  88. package/dist/services/artifacts/request-state-order.js +99 -0
  89. package/dist/services/artifacts/request-type-demand.d.ts +44 -0
  90. package/dist/services/artifacts/request-type-demand.js +71 -0
  91. package/dist/services/audit/audit-goal-service.d.ts +7 -0
  92. package/dist/services/audit/enforcers/active-skill-resolver.d.ts +18 -0
  93. package/dist/services/audit/enforcers/active-skill-resolver.js +48 -1
  94. package/dist/services/audit/enforcers/code-ban.d.ts +11 -2
  95. package/dist/services/audit/enforcers/code-ban.js +21 -1
  96. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.d.ts +17 -0
  97. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.js +24 -7
  98. package/dist/services/audit-independent/handoff-missing-refusal.d.ts +26 -0
  99. package/dist/services/audit-independent/handoff-missing-refusal.js +109 -0
  100. package/dist/services/audit-independent/handoff-readers.d.ts +37 -0
  101. package/dist/services/audit-independent/handoff-readers.js +81 -0
  102. package/dist/services/audit-independent/index.d.ts +6 -1
  103. package/dist/services/audit-independent/index.js +6 -1
  104. package/dist/services/audit-independent/judged-declaration-build.d.ts +48 -0
  105. package/dist/services/audit-independent/judged-declaration-build.js +73 -0
  106. package/dist/services/audit-independent/judged-declaration-check.d.ts +80 -0
  107. package/dist/services/audit-independent/judged-declaration-check.js +216 -0
  108. package/dist/services/audit-independent/judged-declaration.d.ts +94 -0
  109. package/dist/services/audit-independent/judged-declaration.js +218 -0
  110. package/dist/services/audit-independent/perf-audit-service.js +12 -14
  111. package/dist/services/audit-independent/security-audit-artifact.d.ts +28 -0
  112. package/dist/services/audit-independent/security-audit-artifact.js +90 -0
  113. package/dist/services/audit-independent/security-audit-service.d.ts +6 -53
  114. package/dist/services/audit-independent/security-audit-service.js +34 -178
  115. package/dist/services/capability-guard-runner/contracts/J05.js +60 -14
  116. package/dist/services/codegraph/codegraph-index-integrity.js +2 -0
  117. package/dist/services/context/build-dispatch-system-prompt.d.ts +8 -12
  118. package/dist/services/context/build-dispatch-system-prompt.js +18 -18
  119. package/dist/services/context/collector.js +5 -1
  120. package/dist/services/context/post-compact-reinjection.js +1 -1
  121. package/dist/services/dispatch/active-dispatch-index.d.ts +36 -0
  122. package/dist/services/dispatch/active-dispatch-index.js +118 -0
  123. package/dist/services/dispatch/batch-counter.js +1 -2
  124. package/dist/services/dispatch/dispatch-record-writer.d.ts +29 -16
  125. package/dist/services/dispatch/dispatch-record-writer.js +58 -100
  126. package/dist/services/dispatch/dispatch-sub-agent.js +1 -1
  127. package/dist/services/dispatch/karpathy-block.d.ts +55 -0
  128. package/dist/services/dispatch/karpathy-block.js +101 -0
  129. package/dist/services/dispatch/ledger-reaper.d.ts +80 -0
  130. package/dist/services/dispatch/ledger-reaper.js +131 -0
  131. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  132. package/dist/services/dispatch/test-tool-detection.js +12 -1
  133. package/dist/services/evidence/evidence-generator.js +23 -12
  134. package/dist/services/feedback/feedback-promotion-service.d.ts +8 -11
  135. package/dist/services/feedback/feedback-promotion-service.js +30 -35
  136. package/dist/services/feedback/promotion-artifact-json-evidence.d.ts +18 -0
  137. package/dist/services/feedback/promotion-artifact-missing.d.ts +22 -0
  138. package/dist/services/feedback/promotion-artifact-missing.js +63 -0
  139. package/dist/services/final-review/final-review-contract.d.ts +95 -4
  140. package/dist/services/final-review/final-review-contract.js +64 -0
  141. package/dist/services/final-review/final-review-delivery.d.ts +13 -0
  142. package/dist/services/final-review/final-review-delivery.js +26 -12
  143. package/dist/services/final-review/final-review-evidence-collect.js +8 -53
  144. package/dist/services/final-review/final-review-evidence-records.d.ts +21 -0
  145. package/dist/services/final-review/final-review-evidence-records.js +67 -0
  146. package/dist/services/final-review/final-review-evidence-sources.d.ts +22 -0
  147. package/dist/services/final-review/final-review-evidence-sources.js +28 -4
  148. package/dist/services/final-review/final-review-prompt.js +19 -6
  149. package/dist/services/final-review/final-review-runner.js +5 -0
  150. package/dist/services/final-review/final-review-service.d.ts +2 -2
  151. package/dist/services/final-review/index.d.ts +1 -1
  152. package/dist/services/final-review/pre-post-diff.d.ts +2 -75
  153. package/dist/services/final-review/pre-post-diff.js +60 -59
  154. package/dist/services/hooks/pre-tool-code-gate.d.ts +7 -1
  155. package/dist/services/hooks/pre-tool-code-gate.js +21 -2
  156. package/dist/services/hooks/worktree-authorization-gate.js +6 -31
  157. package/dist/services/hooks/worktree-refusal-messages.d.ts +74 -0
  158. package/dist/services/hooks/worktree-refusal-messages.js +102 -0
  159. package/dist/services/lint/eslint-runner-support.d.ts +1 -1
  160. package/dist/services/lint/eslint-runner-support.js +2 -1
  161. package/dist/services/lint/eslint-runner-types.d.ts +8 -0
  162. package/dist/services/lint/eslint-runner.js +17 -4
  163. package/dist/services/llm/anthropic-runner.js +24 -7
  164. package/dist/services/loop/loop-observability.d.ts +39 -0
  165. package/dist/services/loop/loop-observability.js +55 -0
  166. package/dist/services/loop/monotonic-guard.js +6 -9
  167. package/dist/services/loop/monotonic-runner.js +8 -7
  168. package/dist/services/loop/run-driver.js +18 -22
  169. package/dist/services/memory/project-memory-service/index/kind-dispatch.js +14 -1
  170. package/dist/services/memory/project-memory-service/index/project-memory-plan-exec.js +13 -2
  171. package/dist/services/memory/project-memory-service/index.d.ts +2 -2
  172. package/dist/services/memory/project-memory-service/index.js +1 -1
  173. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.d.ts +36 -0
  174. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.js +48 -2
  175. package/dist/services/memory/project-memory-service/parsers/markdown-pure.d.ts +23 -1
  176. package/dist/services/memory/project-memory-service/parsers/markdown-pure.js +37 -0
  177. package/dist/services/memory/project-memory-service/types.d.ts +32 -0
  178. package/dist/services/observability/observability-service.d.ts +7 -0
  179. package/dist/services/observability/observability-service.js +2 -1
  180. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  181. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  182. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  183. package/dist/services/openspec/openspec-archive-service.js +6 -6
  184. package/dist/services/prd/gate-evidence-derivation.d.ts +4 -3
  185. package/dist/services/prd/gate-evidence-derivation.js +4 -3
  186. package/dist/services/qa/bdd-test-style-verifier.js +22 -8
  187. package/dist/services/race/gate2-evaluator.d.ts +58 -0
  188. package/dist/services/race/gate2-evaluator.js +111 -0
  189. package/dist/services/race/gate2-policy.d.ts +17 -0
  190. package/dist/services/race/gate2-policy.js +31 -0
  191. package/dist/services/race/lane-phase.d.ts +19 -0
  192. package/dist/services/race/lane-phase.js +113 -0
  193. package/dist/services/race/pilot-gate-store.d.ts +67 -0
  194. package/dist/services/race/pilot-gate-store.js +227 -0
  195. package/dist/services/scan/file-size-baseline.d.ts +33 -0
  196. package/dist/services/scan/file-size-baseline.js +173 -0
  197. package/dist/services/scan/file-size-scan.d.ts +35 -3
  198. package/dist/services/scan/file-size-scan.js +63 -42
  199. package/dist/services/scan/type-corroboration.d.ts +32 -0
  200. package/dist/services/scan/type-corroboration.js +51 -0
  201. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  202. package/dist/services/scan/type-sanity-service.js +23 -22
  203. package/dist/services/security/safe-settings-path.d.ts +5 -0
  204. package/dist/services/security/safe-settings-path.js +64 -8
  205. package/dist/services/skill/resume-detector.js +11 -11
  206. package/dist/services/skills/hooks-codegate-superpowers.d.ts +5 -6
  207. package/dist/services/skills/hooks-codegate-superpowers.js +7 -8
  208. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  209. package/dist/services/skills/hooks-settings-service.js +1 -1
  210. package/dist/services/skills/presence-lease-order.d.ts +13 -0
  211. package/dist/services/skills/presence-lease-order.js +24 -0
  212. package/dist/services/skills/skill-conformance-service.js +1 -0
  213. package/dist/services/skills/skill-statusline-service.js +4 -7
  214. package/dist/services/slice/slice-check-service.js +8 -8
  215. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  216. package/dist/services/workflow/pipeline-verify-gate-support.js +34 -39
  217. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  218. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  219. package/dist/services/workflow/pipeline-verify-service.js +27 -28
  220. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  221. package/dist/services/workflow/request-type-resolution.js +130 -0
  222. package/dist/services/workflow/workflow-skip-service.d.ts +1 -20
  223. package/dist/services/workflow/workflow-skip-service.js +22 -25
  224. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  225. package/dist/services/workflow/workflow-state-store.js +26 -1
  226. package/dist/services/workspace/claude-settings-retirements.d.ts +54 -0
  227. package/dist/services/workspace/claude-settings-retirements.js +112 -0
  228. package/dist/services/workspace/claude-settings-template-merge.d.ts +35 -15
  229. package/dist/services/workspace/claude-settings-template-merge.js +33 -53
  230. package/dist/services/workspace/claude-settings-template.d.ts +62 -12
  231. package/dist/services/workspace/claude-settings-template.js +58 -58
  232. package/dist/services/workspace/migrate-1-4-1-service.js +3 -0
  233. package/dist/services/workspace/reconcile-service.js +0 -1
  234. package/dist/shared/incrementing-number.d.ts +33 -2
  235. package/dist/shared/incrementing-number.js +72 -3
  236. package/package.json +5 -7
  237. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  238. package/skills/bee/peaks-prd/SKILL.md +4 -3
  239. package/skills/bee/peaks-qa/SKILL.md +1 -1
  240. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  241. package/skills/bee/peaks-qa/references/qa-transition-gates.md +1 -1
  242. package/skills/bee/peaks-rd/SKILL.md +2 -2
  243. package/skills/bee/peaks-rd/references/rd-fanout-contracts.md +1 -1
  244. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +8 -4
  245. package/skills/bee/peaks-rd/references/rd-transition-gates.md +3 -3
  246. package/skills/bee/peaks-rd/references/v2-12-fanout-collapse.md +2 -2
  247. package/skills/bee/peaks-rd/references/writing-handoff-frontmatter.md +1 -1
  248. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  249. package/skills/bee/peaks-sc/SKILL.md +1 -1
  250. package/skills/bee/peaks-security-audit/SKILL.md +10 -2
  251. package/skills/bee/peaks-txt/SKILL.md +4 -3
  252. package/skills/bee/peaks-ui/SKILL.md +3 -3
  253. package/skills/peaks-audit/SKILL.md +29 -1
  254. package/skills/peaks-code/SKILL.md +37 -17
  255. package/skills/peaks-code/references/fast-lane-norm.md +42 -0
  256. package/skills/peaks-code/references/fast-mode.md +3 -2
  257. package/skills/peaks-code/references/local-artifact-workspace.md +3 -3
  258. package/skills/peaks-code/references/micro-cycle.md +3 -3
  259. package/skills/peaks-code/references/resume-detection.md +1 -1
  260. package/skills/peaks-code/references/runbook.md +12 -6
  261. package/skills/peaks-code/references/step-11-memory-sediment.md +4 -0
  262. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  263. package/skills/peaks-code/references/swarm-dispatch-contract.md +40 -16
  264. package/skills/peaks-code/references/workflow-gates-and-types.md +6 -6
  265. package/skills/peaks-code/references/worktree-governance.md +4 -4
  266. package/skills/peaks-content/SKILL.md +1 -1
  267. package/skills/peaks-doctor/SKILL.md +1 -1
  268. package/skills/peaks-final-review/SKILL.md +31 -11
  269. package/skills/peaks-ide/SKILL.md +1 -1
  270. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  271. package/skills/peaks-race-code/SKILL.md +185 -0
  272. package/skills/peaks-resume/SKILL.md +1 -1
  273. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  274. package/skills/peaks-solo/SKILL.md +1 -1
  275. package/skills/peaks-sop/SKILL.md +1 -1
  276. package/skills/peaks-status/SKILL.md +1 -1
  277. package/skills/peaks-test/SKILL.md +7 -4
  278. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  279. package/dist/cli/commands/vm-command-shared.js +0 -23
  280. package/dist/cli/commands/vm-commands.d.ts +0 -3
  281. package/dist/cli/commands/vm-commands.js +0 -45
  282. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  283. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  284. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  285. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  286. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  287. package/dist/cli/commands/vm-release-command.js +0 -101
  288. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  289. package/dist/cli/commands/vm-spawn-command.js +0 -177
  290. package/dist/cli/commands/vm-status-command.js +0 -50
  291. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.d.ts +0 -23
  292. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.js +0 -64
  293. package/dist/services/vm/vm-lease.d.ts +0 -40
  294. package/dist/services/vm/vm-lease.js +0 -160
@@ -8,13 +8,14 @@ import { ensureSession, getSessionIdCanonical } from '../session/session-manager
8
8
  // gone; request-artifact callers pass `options.sessionId` explicitly
9
9
  // or accept the requestId as the default. Path-safety helpers now
10
10
  // live at `shared/path-safety.ts` if this module ever needs them.
11
- import { getNextNumber, buildNumberedFilename, slugifyDescription } from '../../shared/incrementing-number.js';
11
+ import { getNextNumber, buildNumberedFilename, requestIdFromFileName, slugifyDescription } from '../../shared/incrementing-number.js';
12
+ import { extractMetadata } from './request-artifact-metadata.js';
12
13
  import { lintRequestArtifact } from './artifact-lint-service.js';
13
14
  import { isUnsafePathInput } from '../../shared/path-safety.js';
14
15
  import { guardRuntimeSegment, runtimeRoot } from '../../shared/runtime-root.js';
15
16
  import { checkTypeSanity } from '../scan/type-sanity-service.js';
16
17
  import { requireUserConfirmation } from '../mode/mode-enforcement.js';
17
- import { scanFileSize } from '../scan/file-size-scan.js';
18
+ import { runRdTransitionGates } from './rd-transition-gates.js';
18
19
  import { emitObservabilityEvent } from '../observability/observability-service.js';
19
20
  export { VALID_REQUEST_TYPES, DEFAULT_REQUEST_TYPE, isRequestType };
20
21
  // Re-export the pure-function template surface so external callers (CLI,
@@ -74,7 +75,6 @@ export async function createRequestArtifact(options) {
74
75
  if (!REQUEST_ID_PATTERN.test(options.requestId)) {
75
76
  throw new Error(`Invalid request id: ${options.requestId} (expected letters, digits, dots, underscores, or dashes)`);
76
77
  }
77
- const requestType = options.requestType ?? DEFAULT_REQUEST_TYPE;
78
78
  const clock = options.clock ?? defaultClock;
79
79
  const timestamp = clock();
80
80
  // Use provided session ID or get/create current session. The session
@@ -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
  });
@@ -144,7 +144,10 @@ export async function createRequestArtifact(options) {
144
144
  const number = getNextNumber(requestsDir);
145
145
  const filename = buildNumberedFilename(number, options.requestId);
146
146
  const path = join(requestsDir, filename);
147
- const content = renderTemplate(options.role, options.requestId, sessionId, sessionSlug, timestamp, requestType);
147
+ const content = renderTemplate(options.role, options.requestId, sessionId, sessionSlug, timestamp,
148
+ // `null`, not the default: an untyped request records no type, so the
149
+ // reader's substitution stays visible as a substitution.
150
+ options.requestType ?? null);
148
151
  if (options.apply !== true) {
149
152
  // session-axis dir (`.peaks/_runtime/<sid>/`). Pre-resolved here
150
153
  // so dry-run output reports the canonical scope location.
@@ -183,47 +186,12 @@ export async function createRequestArtifact(options) {
183
186
  ...(options.callerId !== undefined ? { callerId: options.callerId } : {})
184
187
  };
185
188
  }
186
- function extractMetadata(markdown) {
187
- const state = readArtifactState(markdown) ?? 'unknown';
188
- let createdAt;
189
- let requestType = DEFAULT_REQUEST_TYPE;
190
- let sessionId;
191
- for (const rawLine of markdown.split(/\r?\n/)) {
192
- const line = rawLine.trim();
193
- const createdMatch = /^-\s*created:\s*(.+?)\s*$/.exec(line);
194
- if (createdMatch !== null && createdMatch[1] !== undefined) {
195
- createdAt = createdMatch[1];
196
- continue;
197
- }
198
- const typeMatch = /^-\s*type:\s*(.+?)\s*$/.exec(line);
199
- if (typeMatch !== null && typeMatch[1] !== undefined) {
200
- const candidate = typeMatch[1];
201
- if (isRequestType(candidate)) {
202
- requestType = candidate;
203
- }
204
- // Placeholder values (e.g. "feature | bug | refactor | clarification") fall back to default.
205
- continue;
206
- }
207
- const sessionMatch = /^-\s*session:\s*(.+?)\s*$/.exec(line);
208
- if (sessionMatch !== null && sessionMatch[1] !== undefined) {
209
- sessionId = sessionMatch[1];
210
- continue;
211
- }
212
- }
213
- const base = { state, requestType };
214
- if (createdAt !== undefined)
215
- base.createdAt = createdAt;
216
- if (sessionId !== undefined)
217
- base.sessionId = sessionId;
218
- return base;
219
- }
220
189
  async function readSummary(dir, role, fileName, sessionId) {
221
190
  const path = join(dir, fileName);
222
191
  const body = await readFile(path, 'utf8');
223
- const { state, createdAt, requestType, sessionId: bodySessionId } = extractMetadata(body);
224
- // Strip numbered prefix (e.g., "001-requestId.md" -> "requestId")
225
- // Only strip 3-digit zero-padded prefixes (our incrementing number format)
226
- const requestId = fileName.replace(/^0\d{2}-/, '').replace(/\.md$/, '');
192
+ const { state, createdAt, requestType, requestTypeSource, sessionId: bodySessionId } = extractMetadata(body);
193
+ // The id, stripped by the rule that writes the prefix (see `buildNumberedFilename`).
194
+ const requestId = requestIdFromFileName(fileName) ?? fileName.replace(/\.md$/, '');
227
195
  // Repair R5: this used to take the *scope* path fragment (`_runtime/<sid>`)
228
196
  // and re-join it onto the project root, then strip the prefix back off to
229
197
  // recover the bare session id. The round-trip was the escape's carrier — an
@@ -237,6 +205,7 @@ async function readSummary(dir, role, fileName, sessionId) {
237
205
  path,
238
206
  state,
239
207
  requestType,
208
+ requestTypeSource,
240
209
  writerSessionId: bodySessionId ?? sessionId
241
210
  };
242
211
  if (createdAt !== undefined) {
@@ -311,8 +280,8 @@ export async function showRequestArtifact(options) {
311
280
  if (file === `${options.requestId}.md`) {
312
281
  return { fileName: file, path: join(dir, file) };
313
282
  }
314
- // Match numbered format: ${number}-${requestId}.md
315
- 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) {
316
285
  return { fileName: file, path: join(dir, file) };
317
286
  }
318
287
  }
@@ -364,7 +333,8 @@ async function readRequestArtifact(dir, role, found, sessionId) {
364
333
  // the sibling `request-artifact-state-helpers.ts` module — see
365
334
  // v2.18.3 file-split for the rationale. Function signatures and
366
335
  // behaviour are unchanged (verbatim move).
367
- import { ALLOWED_STATES_PER_ROLE, FileSizeViolationError, LintGateError, PrerequisitesNotSatisfiedError, readArtifactState, 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
+ import { assertLegalStateStep } from './request-state-order.js';
368
338
  export { allowedStatesForRole, FileSizeViolationError, LintGateError, PrerequisitesNotSatisfiedError, TypeSanityViolationError, updateStatusBlock } from './request-artifact-state-helpers.js';
369
339
  export async function transitionRequestArtifact(options) {
370
340
  if (!VALID_ROLES.has(options.role)) {
@@ -397,6 +367,8 @@ export async function transitionRequestArtifact(options) {
397
367
  confirmed: options.confirmed,
398
368
  forceConfirm: options.forceConfirm
399
369
  });
370
+ // A forward jump past an intermediate state is refused (request-state-order.ts).
371
+ assertLegalStateStep(options.role, existing.state, options.newState, options.allowIncomplete === true);
400
372
  const prerequisiteResult = await checkPrerequisites({
401
373
  projectRoot: options.projectRoot,
402
374
  sessionId: existing.sessionId,
@@ -408,9 +380,6 @@ export async function transitionRequestArtifact(options) {
408
380
  if (!prerequisiteResult.ok && options.allowIncomplete !== true) {
409
381
  throw new PrerequisitesNotSatisfiedError(options.role, options.newState, existing.sessionId, prerequisiteResult.missing, prerequisiteResult.warnings);
410
382
  }
411
- // (Removed in v2.11.0 Group A: the tech-doc-presence + tech-doc-mandatory-
412
- // sections gates. The rd → spec-locked transition now relies on the
413
- // immutable peaks-prd handoff (sha256-frontmatter) for the same intent;
414
383
  // Type sanity check for PRD handoff
415
384
  if (options.typeSanityCheck !== undefined &&
416
385
  options.role === 'prd' &&
@@ -432,37 +401,36 @@ export async function transitionRequestArtifact(options) {
432
401
  sessionId: existing.sessionId
433
402
  });
434
403
  if (lintReport !== null && !lintReport.ok) {
435
- const errorCount = lintReport.findings.filter((f) => f.severity === 'error').length;
436
- if (errorCount > 0) {
437
- 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);
438
407
  }
439
408
  }
440
409
  }
441
- // File size gate: when RD declares implemented, scan for oversized files (karpathy-skills "Simplicity First")
442
- if (options.role === 'rd' &&
443
- options.newState === 'implemented' &&
444
- options.allowIncomplete !== true) {
445
- const sizeResult = scanFileSize({ projectRoot: options.projectRoot });
446
- if (!sizeResult.ok) {
447
- throw new FileSizeViolationError(sizeResult.violations);
448
- }
449
- }
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;
450
421
  const clock = options.clock ?? defaultClock;
451
422
  const timestamp = clock();
452
423
  const bypassNote = !prerequisiteResult.ok && options.allowIncomplete === true
453
424
  ? `bypassed prerequisites (${prerequisiteResult.missing.map((entry) => entry.path).join(', ')})`
454
425
  : undefined;
455
- const combinedReason = [options.reason, bypassNote]
426
+ const combinedReason = [options.reason, bypassNote, gateBypassNote ?? undefined]
456
427
  .filter((part) => part !== undefined && part.length > 0)
457
428
  .join(' | ');
458
429
  const reasonForNote = combinedReason.length > 0 ? combinedReason : undefined;
459
430
  const { updated, previousState } = updateStatusBlock(existing.content, options.newState, timestamp, reasonForNote);
460
431
  await writeFile(existing.path, updated, 'utf8');
461
- // Slice v2.11.1 — observability hook #1/7. Fire-and-forget emit per
462
- // PRD Q4 (full-auto must never fail-loud on observability). The
463
- // synchronous `emitObservabilityEvent` returns `{written: false}` on
464
- // any error path; we deliberately ignore the result so the
465
- // transition contract remains unchanged.
432
+ // Fire-and-forget: the synchronous emit returns `{written: false}` on any
433
+ // error path and we ignore it, so observability never fails the transition.
466
434
  emitObservabilityEvent({
467
435
  schemaVersion: 1,
468
436
  ts: timestamp,
@@ -483,6 +451,7 @@ export async function transitionRequestArtifact(options) {
483
451
  path: existing.path,
484
452
  state: options.newState,
485
453
  requestType: existing.requestType,
454
+ requestTypeSource: existing.requestTypeSource,
486
455
  previousState,
487
456
  content: updated
488
457
  };
@@ -492,5 +461,10 @@ export async function transitionRequestArtifact(options) {
492
461
  if (!prerequisiteResult.ok && options.allowIncomplete === true) {
493
462
  result.bypassedPrerequisites = prerequisiteResult;
494
463
  }
464
+ // Soft-passed prerequisites travel on the SUCCESS path too, not only inside
465
+ // the throw above — otherwise `ok: true` drops what it soft-passed.
466
+ if (prerequisiteResult.warnings.length > 0) {
467
+ result.prerequisiteWarnings = prerequisiteResult.warnings;
468
+ }
495
469
  return result;
496
470
  }
@@ -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";
@@ -34,15 +42,27 @@ export declare class TypeSanityViolationError extends Error {
34
42
  }
35
43
  export declare class FileSizeViolationError extends Error {
36
44
  readonly code = "FILE_SIZE_VIOLATION";
45
+ /** `previousLines` is the file's size at the scan's base ref, or `null` when
46
+ * the change CREATED it over the cap. Carried so the message can name the
47
+ * growth — a refusal that does not say how much worse the file got reads as
48
+ * an absolute cap breach, which is the reading this gate no longer makes.
49
+ *
50
+ * The `violations` array also drives the sentence naming the AGGREGATE
51
+ * ratchet row this gate is easily confused with. This gate is PER FILE; that
52
+ * row is a sum over the census. In a working tree the two can disagree with
53
+ * neither being wrong, and the message says so rather than leaving a reader
54
+ * to conclude that one of them is broken. */
37
55
  readonly violations: Array<{
38
56
  file: string;
39
57
  lines: number;
40
58
  cap: number;
59
+ previousLines: number | null;
41
60
  }>;
42
61
  constructor(violations: Array<{
43
62
  file: string;
44
63
  lines: number;
45
64
  cap: number;
65
+ previousLines: number | null;
46
66
  }>);
47
67
  }
48
68
  export interface ArtifactStateLocation {
@@ -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 {
@@ -62,12 +64,36 @@ export class TypeSanityViolationError extends Error {
62
64
  }
63
65
  export class FileSizeViolationError extends Error {
64
66
  code = 'FILE_SIZE_VIOLATION';
67
+ /** `previousLines` is the file's size at the scan's base ref, or `null` when
68
+ * the change CREATED it over the cap. Carried so the message can name the
69
+ * growth — a refusal that does not say how much worse the file got reads as
70
+ * an absolute cap breach, which is the reading this gate no longer makes.
71
+ *
72
+ * The `violations` array also drives the sentence naming the AGGREGATE
73
+ * ratchet row this gate is easily confused with. This gate is PER FILE; that
74
+ * row is a sum over the census. In a working tree the two can disagree with
75
+ * neither being wrong, and the message says so rather than leaving a reader
76
+ * to conclude that one of them is broken. */
65
77
  violations;
66
78
  constructor(violations) {
67
- const summary = violations.map((v) => `${v.file} (${v.lines} lines, cap ${v.cap})`).join(', ');
68
- super(`File size violation: ${violations.length} file(s) exceed their file-size cap: ${summary}. ` +
69
- 'Split into smaller modules, or consider reusing existing components / existing API data ' +
70
- '(karpathy-guidelines §2 Simplicity First), or use --allow-incomplete to bypass.');
79
+ const summary = violations
80
+ .map((v) => v.previousLines === null
81
+ ? `${v.file} (${v.lines} lines, cap ${v.cap}, created over the cap)`
82
+ : `${v.file} (${v.lines} lines, cap ${v.cap}, grew +${v.lines - v.previousLines} from ${v.previousLines})`)
83
+ .join(', ');
84
+ super(`File size regression: ${violations.length} changed file(s) grew past (or were created over) their file-size cap: ${summary}. ` +
85
+ 'This is the PER-FILE rule: each changed file is judged against its own size at the base ref. ' +
86
+ 'It is a different measurement from the aggregate ratchet row `file-size excess lines` ' +
87
+ '(fileSizeExcessLines), which sums the whole census — so `node .husky/peaks-gate.mjs repo` ' +
88
+ 'can print that row green at this same moment (it prints a ✓ for a held row), and ' +
89
+ '`node .husky/peaks-gate-baseline.mjs` can report "monotonicity: every ceiling held": one ' +
90
+ 'file growing a few lines sits inside an aggregate fall and never reaches that row. Neither ' +
91
+ 'reading is wrong and neither takes priority over the other; they measure different things, ' +
92
+ 'and both must hold. ' +
93
+ 'A file already over its cap at the base ref is accepted unless this change enlarges it; ' +
94
+ 'a rename is measured against the size it had before the move. Split into smaller modules, ' +
95
+ 'or consider reusing existing components / existing API data (karpathy-guidelines §2 ' +
96
+ 'Simplicity First), or use --allow-incomplete to bypass.');
71
97
  this.name = 'FileSizeViolationError';
72
98
  this.violations = violations;
73
99
  }
@@ -0,0 +1,68 @@
1
+ import type { RequestType } from './artifact-prerequisites.js';
2
+ import { type RequestTypeSource } from './request-artifact-metadata.js';
3
+ import { type RequestArtifactRole } from './request-artifact-service.js';
4
+ export type RequestTypeChange = {
5
+ readonly from: RequestType;
6
+ readonly fromSource: RequestTypeSource;
7
+ readonly to: RequestType;
8
+ };
9
+ export type RetagImpact = {
10
+ /** Paths the new type demands and the old one did not. */
11
+ readonly added: ReadonlyArray<string>;
12
+ /** Paths the old type demanded and the new one does not. */
13
+ readonly removed: ReadonlyArray<string>;
14
+ /** Everything the new type's table demands that is not on disk, added or not. */
15
+ readonly missing: ReadonlyArray<string>;
16
+ };
17
+ export type RetagRequestArtifactOptions = {
18
+ projectRoot: string;
19
+ role: RequestArtifactRole;
20
+ requestId: string;
21
+ requestType: RequestType;
22
+ /**
23
+ * Required. Omitting it made `showRequestArtifact` resolve the first session
24
+ * holding a matching rid, so a WRITE verb could mutate an artifact nobody
25
+ * named. A write has to say which one.
26
+ */
27
+ sessionId: string;
28
+ clock?: () => string;
29
+ };
30
+ export type RetagRequestArtifactResult = {
31
+ role: RequestArtifactRole;
32
+ requestId: string;
33
+ sessionId: string;
34
+ path: string;
35
+ change: RequestTypeChange;
36
+ impact: RetagImpact;
37
+ /** The durable line appended to the artifact body; see `appendRetagNote`. */
38
+ note: string;
39
+ content: string;
40
+ };
41
+ /**
42
+ * Rewrite the artifact's type, changing the line the READER would take.
43
+ * `extractMetadata` scans every top-level `- type:` line and keeps the last
44
+ * usable one, so the writer targets the last line regardless of validity: if the
45
+ * last is a placeholder and an earlier one is real, the rewrite lands on the
46
+ * placeholder, which then becomes the usable one — the same line the reader
47
+ * picks up either way. With no such line at all (the shape a hand-written
48
+ * carrier has) one is inserted into the metadata block.
49
+ *
50
+ * The one other change it makes: lines are split on `\r?\n` and rejoined with
51
+ * `\n`, so a CRLF body comes back LF-terminated. Reproduced by an independent
52
+ * reviewer; named rather than implied.
53
+ */
54
+ export declare function setRequestTypeInBody(markdown: string, requestType: RequestType): string;
55
+ /**
56
+ * The durable record of a retag, appended rather than rewritten so a later retag
57
+ * — or a transition's own `- transition note` — leaves every earlier one intact.
58
+ *
59
+ * It exists because the type line itself is overwritten and the difference it
60
+ * makes is not cosmetic: retagging down (`feature` → `chore`) stops nine
61
+ * artifacts being demanded. Without a line like this the only visible trace of
62
+ * that would be the envelope of the run that did it, and the artifact tree lives
63
+ * under a gitignored directory. Same idiom as `updateStatusBlock`'s note.
64
+ */
65
+ export declare function appendRetagNote(markdown: string, change: RequestTypeChange, timestamp: string): string;
66
+ export declare function retagRequestArtifact(options: RetagRequestArtifactOptions): Promise<RetagRequestArtifactResult | null>;
67
+ /** The envelope lines a retag reports, so the change is not silent. */
68
+ export declare function describeRetag(result: RetagRequestArtifactResult): string[];
@@ -0,0 +1,125 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { extractMetadata } from './request-artifact-metadata.js';
3
+ import { demandDelta, unsatisfiedDemand } from './request-type-demand.js';
4
+ import { showRequestArtifact } from './request-artifact-service.js';
5
+ const TYPE_LINE_RE = /^-\s*type:\s*(.+?)\s*$/;
6
+ const SESSION_LINE_RE = /^-\s*session:\s*/;
7
+ const HEADING_RE = /^#\s/;
8
+ function defaultClock() {
9
+ return new Date().toISOString();
10
+ }
11
+ /**
12
+ * Rewrite the artifact's type, changing the line the READER would take.
13
+ * `extractMetadata` scans every top-level `- type:` line and keeps the last
14
+ * usable one, so the writer targets the last line regardless of validity: if the
15
+ * last is a placeholder and an earlier one is real, the rewrite lands on the
16
+ * placeholder, which then becomes the usable one — the same line the reader
17
+ * picks up either way. With no such line at all (the shape a hand-written
18
+ * carrier has) one is inserted into the metadata block.
19
+ *
20
+ * The one other change it makes: lines are split on `\r?\n` and rejoined with
21
+ * `\n`, so a CRLF body comes back LF-terminated. Reproduced by an independent
22
+ * reviewer; named rather than implied.
23
+ */
24
+ export function setRequestTypeInBody(markdown, requestType) {
25
+ const lines = markdown.split(/\r?\n/);
26
+ let target = -1;
27
+ for (const [index, raw] of lines.entries()) {
28
+ if (TYPE_LINE_RE.test(raw.trim()))
29
+ target = index;
30
+ }
31
+ if (target >= 0) {
32
+ lines[target] = `- type: ${requestType}`;
33
+ return lines.join('\n');
34
+ }
35
+ lines.splice(insertionIndex(lines), 0, `- type: ${requestType}`);
36
+ return lines.join('\n');
37
+ }
38
+ /** After the `- session:` line the templates write, else below the title, else first. */
39
+ function insertionIndex(lines) {
40
+ const sessionIndex = lines.findIndex((raw) => SESSION_LINE_RE.test(raw.trim()));
41
+ if (sessionIndex >= 0)
42
+ return sessionIndex + 1;
43
+ const headingIndex = lines.findIndex((raw) => HEADING_RE.test(raw));
44
+ if (headingIndex < 0)
45
+ return 0;
46
+ let index = headingIndex + 1;
47
+ while (index < lines.length && lines[index]?.trim() === '')
48
+ index += 1;
49
+ return index;
50
+ }
51
+ /**
52
+ * The durable record of a retag, appended rather than rewritten so a later retag
53
+ * — or a transition's own `- transition note` — leaves every earlier one intact.
54
+ *
55
+ * It exists because the type line itself is overwritten and the difference it
56
+ * makes is not cosmetic: retagging down (`feature` → `chore`) stops nine
57
+ * artifacts being demanded. Without a line like this the only visible trace of
58
+ * that would be the envelope of the run that did it, and the artifact tree lives
59
+ * under a gitignored directory. Same idiom as `updateStatusBlock`'s note.
60
+ */
61
+ export function appendRetagNote(markdown, change, timestamp) {
62
+ const body = markdown.replace(/\n+$/, '');
63
+ return `${body}\n- retag note (${timestamp}): ${change.from} (${change.fromSource}) -> ${change.to}\n`;
64
+ }
65
+ export async function retagRequestArtifact(options) {
66
+ const existing = await showRequestArtifact({
67
+ projectRoot: options.projectRoot,
68
+ role: options.role,
69
+ requestId: options.requestId,
70
+ sessionId: options.sessionId
71
+ });
72
+ if (existing === null)
73
+ return null;
74
+ const from = extractMetadata(existing.content).requestType;
75
+ const change = {
76
+ from,
77
+ fromSource: existing.requestTypeSource,
78
+ to: options.requestType
79
+ };
80
+ const delta = demandDelta(from, options.requestType);
81
+ // Measured before the write: a probe that throws must leave the type as it was.
82
+ const missing = await unsatisfiedDemand({
83
+ projectRoot: options.projectRoot,
84
+ sessionId: existing.sessionId,
85
+ requestId: options.requestId,
86
+ requestType: options.requestType
87
+ });
88
+ const timestamp = (options.clock ?? defaultClock)();
89
+ const note = `- retag note (${timestamp}): ${change.from} (${change.fromSource}) -> ${change.to}`;
90
+ const content = appendRetagNote(setRequestTypeInBody(existing.content, options.requestType), change, timestamp);
91
+ await writeFile(existing.path, content, 'utf8');
92
+ return {
93
+ role: options.role,
94
+ requestId: options.requestId,
95
+ sessionId: existing.sessionId,
96
+ path: existing.path,
97
+ change,
98
+ impact: {
99
+ added: delta.added.map((path) => path.replace('<rid>', options.requestId)),
100
+ removed: delta.removed.map((path) => path.replace('<rid>', options.requestId)),
101
+ missing
102
+ },
103
+ note,
104
+ content
105
+ };
106
+ }
107
+ /** The envelope lines a retag reports, so the change is not silent. */
108
+ export function describeRetag(result) {
109
+ const { change, impact } = result;
110
+ const lines = [
111
+ change.fromSource === 'default'
112
+ ? `request type was the default '${change.from}' (the artifact recorded no type); it is now '${change.to}'.`
113
+ : `request type '${change.from}' is now '${change.to}'.`
114
+ ];
115
+ if (impact.added.length > 0) {
116
+ lines.push(`now demanded (${impact.added.length}): ${impact.added.join(', ')}.`);
117
+ }
118
+ if (impact.removed.length > 0) {
119
+ lines.push(`no longer demanded (${impact.removed.length}): ${impact.removed.join(', ')}.`);
120
+ }
121
+ if (impact.missing.length > 0) {
122
+ lines.push(`unsatisfied at '${change.to}' (${impact.missing.length} not on disk): ${impact.missing.join(', ')} — the next gate reads the new table and will refuse until they exist.`);
123
+ }
124
+ return lines;
125
+ }
@@ -0,0 +1,38 @@
1
+ import { type RequestArtifactState } from './request-artifact-state-helpers.js';
2
+ import type { RequestArtifactRole } from './artifact-templates.js';
3
+ export type StateOrderBreach = {
4
+ /** `jump` — the move skips past an intermediate state. `unreadable` — the
5
+ * current state could not be read, so the move cannot be shown to be legal. */
6
+ kind: 'jump' | 'unreadable';
7
+ /** The states this move skips over. Empty for `unreadable`. */
8
+ skipped: ReadonlyArray<RequestArtifactState>;
9
+ /** The one legal next state from a READABLE current one, else `null`. */
10
+ next: RequestArtifactState | null;
11
+ };
12
+ /**
13
+ * `null` when the move is allowed, or the breach when it is not.
14
+ *
15
+ * FAIL-CLOSED on an unreadable current state. A carrier with no `- state:` line
16
+ * reads as the literal `'unknown'` (the `readArtifactState(...) ?? 'unknown'`
17
+ * fallback in the transition service), and this gate runs before every other
18
+ * one. Reading "I could not read it" as "no jump" would therefore hand the gate
19
+ * an off-switch that is one deleted line — re-opening the `rd → handed-off` jump
20
+ * this module exists to stop — so an unreadable state is refused, not allowed.
21
+ */
22
+ export declare function stateOrderViolation(role: RequestArtifactRole, from: string, to: RequestArtifactState): StateOrderBreach | null;
23
+ /** The breach kinds get their own codes: a refusal that cannot be named is a
24
+ * refusal a consumer cannot act on, and "jumped" is not "could not be read". */
25
+ export declare const STATE_ORDER_JUMP_CODE = "STATE_ORDER_JUMP";
26
+ export declare const STATE_ORDER_UNREADABLE_CODE = "STATE_ORDER_UNREADABLE";
27
+ export declare class StateOrderViolationError extends Error {
28
+ readonly code: string;
29
+ readonly role: RequestArtifactRole;
30
+ readonly from: string;
31
+ readonly to: RequestArtifactState;
32
+ readonly skipped: ReadonlyArray<RequestArtifactState>;
33
+ readonly kind: StateOrderBreach['kind'];
34
+ constructor(role: RequestArtifactRole, from: string, to: RequestArtifactState, breach: StateOrderBreach);
35
+ }
36
+ /** Throws when `to` skips an intermediate state or the current state is
37
+ * unreadable. `bypass` is the caller's `--allow-incomplete` escape hatch. */
38
+ export declare function assertLegalStateStep(role: RequestArtifactRole, from: string, to: RequestArtifactState, bypass: boolean): void;