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
@@ -12,6 +12,7 @@ import { existsSync, statSync } from 'node:fs';
12
12
  import { join, resolve } from 'node:path';
13
13
  import { REQUEST_ID_PATTERN } from '../../services/artifacts/request-artifact-service.js';
14
14
  import { createAnthropicRunner, LlmBindingError, resolveAnthropicConfig } from '../../services/llm/anthropic-runner.js';
15
+ import { emitTokenUsageEvent } from '../../services/observability/observability-service.js';
15
16
  import { prepareFinalReview } from '../../services/final-review/final-review-service.js';
16
17
  import { getErrorMessage } from '../cli-helpers.js';
17
18
  import { DEFAULT_LLM_PROVIDER, isSupportedLlmProvider, SUPPORTED_LLM_PROVIDERS } from './final-review-command-shared.js';
@@ -136,6 +137,25 @@ function resolvePrepareInputs(rid, options) {
136
137
  function isRefusal(value) {
137
138
  return !('projectRoot' in value);
138
139
  }
140
+ /**
141
+ * The `token-usage` emission owner: the one site where a completed review's
142
+ * token counts and the session binding are both in scope. Fire-and-forget —
143
+ * `emitTokenUsageEvent` never throws, and this never blocks or fails the review
144
+ * it reports on.
145
+ *
146
+ * `source` defaults to `'provider'` only for a runner that states neither: the
147
+ * real runner always tags its counts (`anthropic-runner.ts` `tokenCounts`), so
148
+ * the default is reached by a test fake, not by a production call.
149
+ */
150
+ function emitReviewTokenUsage(inputs, tokens) {
151
+ emitTokenUsageEvent({
152
+ projectRoot: inputs.projectRoot,
153
+ sessionId: inputs.sessionId,
154
+ inputTokens: tokens.input,
155
+ outputTokens: tokens.output,
156
+ source: tokens.source ?? 'provider'
157
+ });
158
+ }
139
159
  /**
140
160
  * Real provider path: bind a real `LlmRunner` and run the service.
141
161
  *
@@ -153,7 +173,8 @@ async function runRealReview(io, rid, inputs, options) {
153
173
  projectRoot: inputs.projectRoot,
154
174
  sessionId: inputs.sessionId,
155
175
  llmRunner,
156
- ...(options.base === undefined ? {} : { baseRef: options.base })
176
+ ...(options.base === undefined ? {} : { baseRef: options.base }),
177
+ onLlmTokens: (tokens) => emitReviewTokenUsage(inputs, tokens)
157
178
  });
158
179
  emitReviewEnvelope(io, { rid, goal: inputs, model: config.model, review, json });
159
180
  }
@@ -149,9 +149,9 @@ export function emitAllowSkipped(io, options) {
149
149
  }
150
150
  /**
151
151
  * Hard block: a worktree-mutating tool call without a current-task user grant. emitBlock writes
152
- * the Claude Code permissionDecision:"deny" envelope and exits 2. The reason includes the
153
- * remediation hint so the LLM can run `peaks worktree auth grant` and retry, and the user can
154
- * read the deny text in the next-turn stderr.
152
+ * the Claude Code permissionDecision:"deny" envelope and exits 2. The reason carries the
153
+ * remediation hint from `worktree-refusal-messages.ts`, which names the USER-side path — the
154
+ * grant is not the agent's to issue — and the user can read the deny text in the next-turn stderr.
155
155
  */
156
156
  function emitWorktreeDeny(io, options, wtDecision) {
157
157
  emitBlock(io, `[worktree-gate:${wtDecision.code}] ${wtDecision.reason} — ${wtDecision.remediation}`);
@@ -5,7 +5,7 @@ import { getAdapter } from '../../services/ide/ide-registry.js';
5
5
  import { evaluateCodeBan } from '../../services/audit/enforcers/code-ban.js';
6
6
  import { isRootWrite } from '../../services/audit/enforcers/no-root-pollution.js';
7
7
  import { checkLoginGate } from '../../services/audit/enforcers/login-gate.js';
8
- import { resolveActiveSkillForCaller } from '../../services/audit/enforcers/active-skill-resolver.js';
8
+ import { hasLeaseForCaller, hasPeaksLeaseInSession, resolveActiveSkillForCaller } from '../../services/audit/enforcers/active-skill-resolver.js';
9
9
  import { fail, ok } from 'peaks-loop-shared/result';
10
10
  import { emitDecision, emitHint } from '../../services/hooks/output.js';
11
11
  /**
@@ -98,26 +98,47 @@ export function registerHookHandleCommand(program, io) {
98
98
  // The envelope shape (skill / callerId / sessionId / source) is
99
99
  // unchanged from 4.0.7; the underlying source is now
100
100
  // `canonical` for the lease + index path.
101
- const activeSkill = resolveActiveSkillForCaller(projectRoot);
102
- if (activeSkill.skill !== null) {
103
- const codeDecision = evaluateCodeBan({
104
- skill: activeSkill.skill,
105
- command: fallbackCommand
106
- });
107
- if (codeDecision.denied) {
108
- const formatted = formatDecisionResponse(ide, 'deny', codeDecision.reason);
109
- emitDecision(io, formatted.stdout);
110
- if (options.json === true) {
111
- emitHint(io, JSON.stringify(ok('hook.handle', {
112
- ide,
113
- tool: hook.toolName,
114
- decision: 'deny',
115
- reason: codeDecision.reason,
116
- enforcer: 'code-ban'
117
- })));
118
- }
119
- return;
101
+ //
102
+ // Scoped to THIS caller: without a callerId the resolver returns
103
+ // whichever lease `readdirSync` yields first, so another window's skill
104
+ // would be applied here. The identity comes from the payload, not the
105
+ // environment — whether the hook subprocess inherits the
106
+ // caller-identifying env is unverified, and the payload already has it.
107
+ const callerId = pluckString(parsed, ['caller_id']) ?? pluckString(parsed, ['session_id']);
108
+ const identityAvailable = typeof callerId === 'string' && callerId.length > 0;
109
+ const callerHasLease = identityAvailable && hasLeaseForCaller(projectRoot, callerId);
110
+ // A scoped resolve answers for THIS caller only when this caller owns a
111
+ // lease. An id with no lease is ambiguous: either a caller with no peaks
112
+ // skill, or an id that is not the lease's key — and the harness does
113
+ // hand over a differing session id (skill-statusline-service.ts:100-103).
114
+ // The two are indistinguishable here, so that case keeps the unscoped
115
+ // answer, which denies, rather than turning a peaks commit into an allow.
116
+ const activeSkill = !identityAvailable
117
+ ? { skill: null, callerId: null, sessionId: null, mode: null, source: 'none' }
118
+ : callerHasLease
119
+ ? resolveActiveSkillForCaller(projectRoot, { callerId })
120
+ : resolveActiveSkillForCaller(projectRoot);
121
+ // Evaluated even when nothing resolved: the old `if (skill !== null)`
122
+ // guard meant an unresolved driver skipped the ban entirely.
123
+ const codeDecision = evaluateCodeBan({
124
+ skill: activeSkill.skill,
125
+ command: fallbackCommand,
126
+ peaksLeasePresent: hasPeaksLeaseInSession(projectRoot),
127
+ identityResolved: callerHasLease
128
+ });
129
+ if (codeDecision.denied) {
130
+ const formatted = formatDecisionResponse(ide, 'deny', codeDecision.reason);
131
+ emitDecision(io, formatted.stdout);
132
+ if (options.json === true) {
133
+ emitHint(io, JSON.stringify(ok('hook.handle', {
134
+ ide,
135
+ tool: hook.toolName,
136
+ decision: 'deny',
137
+ reason: codeDecision.reason,
138
+ enforcer: 'code-ban'
139
+ })));
120
140
  }
141
+ return;
121
142
  }
122
143
  // Lazy import to avoid circular: peaks gate enforce logic
123
144
  const { enforceBashCommand } = await import('../../services/sop/gate-enforce-service.js');
@@ -116,7 +116,9 @@ export function registerLintCommands(program, io) {
116
116
  }
117
117
  const envelope = result.state === 'ok' || result.state === 'baseline-missing'
118
118
  ? ok('code.lint', { ...result, ...extras }, [], [])
119
- : fail('code.lint', result.state.toUpperCase().replace(/-/g, '_'), `peaks code lint state: ${result.state}`, { ...result, ...extras }, [`Re-run with --scope <path> or restore the ESLint toolchain.`]);
119
+ : fail('code.lint', result.state.toUpperCase().replace(/-/g, '_'), `peaks code lint state: ${result.state}${result.reason === undefined ? '' : ` — ${result.reason}`}`, { ...result, ...extras }, [
120
+ 'The reason above names which condition fired; a spawn timeout wants a larger --timeout-ms.'
121
+ ]);
120
122
  printResult(io, envelope, options.json);
121
123
  });
122
124
  addJsonOption(lint
@@ -1,7 +1,7 @@
1
1
  // The cycle-file index seam for `--capture-score`. Pure path/IO plus its own path-safety
2
2
  // contract; it owns no command registration, which is why it lives outside the
3
3
  // registrar that calls it.
4
- import { existsSync } from 'node:fs';
4
+ import { existsSync, readdirSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { isUnsafePathInput } from '../../shared/path-safety.js';
7
7
  /** Test seam: pick the next cycle-N.json number for capture-score
@@ -22,11 +22,9 @@ export function nextEvalCaptureIndex(projectRoot, sid, rid) {
22
22
  const dir = join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'cycles');
23
23
  if (!existsSync(dir))
24
24
  return 1;
25
- // eslint-disable-next-line @typescript-eslint/no-var-requires
26
- const fs = require('node:fs');
27
25
  let entries;
28
26
  try {
29
- entries = fs.readdirSync(dir);
27
+ entries = readdirSync(dir);
30
28
  }
31
29
  catch {
32
30
  return 1;
@@ -19,9 +19,7 @@ function readStdinSync() {
19
19
  // Node 22: read stdin synchronously via fs.readFileSync(0, 'utf8').
20
20
  // We use the file descriptor 0 convention.
21
21
  try {
22
- // Lazy import to avoid pulling readline at module load
23
- const { readFileSync: rfs } = require('node:fs');
24
- const raw = rfs(0, 'utf8');
22
+ const raw = readFileSync(0, 'utf8');
25
23
  if (raw.trim().length === 0) {
26
24
  throw new Error('stdin was empty; expected JSON envelope on stdin or --envelope <path>');
27
25
  }
@@ -63,7 +61,14 @@ export function registerPerfAuditCommands(program, io) {
63
61
  });
64
62
  const envelope = detect.state === 'ready'
65
63
  ? ok('perf-audit.detect', detect, [...detect.warnings], [...detect.nextActions])
66
- : fail('perf-audit.detect', detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${detect.state}`, detect, [...detect.nextActions]);
64
+ : {
65
+ // `fail()` builds `warnings: []`, so the detector's own diagnosis is
66
+ // spread over it. Without this the human-readable refusal drops the
67
+ // sentence saying WHY the run is not ready, while `--json` keeps it
68
+ // at `data.detect.warnings` — the 9.2 shape, one surface over.
69
+ ...fail('perf-audit.detect', detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${detect.state}`, detect, [...detect.nextActions]),
70
+ warnings: [...detect.warnings]
71
+ };
67
72
  printResult(io, envelope, options.json);
68
73
  if (detect.state !== 'ready') {
69
74
  process.exitCode = 1;
@@ -118,7 +123,12 @@ export function registerPerfAuditCommands(program, io) {
118
123
  envelope: envelopeValue
119
124
  });
120
125
  if (result.detect.state !== 'ready' || result.artifactPath === null) {
121
- printResult(io, fail('perf-audit.run', result.detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${result.detect.state}`, result, [...result.detect.nextActions]), options.json);
126
+ printResult(io, {
127
+ // Same spread as the detect arm: the run's refusal is the only place
128
+ // the detector's warning would reach a person, and `fail()` empties it.
129
+ ...fail('perf-audit.run', result.detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${result.detect.state}`, result, [...result.detect.nextActions]),
130
+ warnings: [...result.detect.warnings]
131
+ }, options.json);
122
132
  process.exitCode = 1;
123
133
  return;
124
134
  }
@@ -17,7 +17,7 @@
17
17
  * `project-memory-index-command.ts`, `project-memories-show-command.ts`,
18
18
  * `project-knowledge-command.ts`.
19
19
  */
20
- import { describeMemoryBlockDrops, describeSessionScanFailures, extractSessionMemories, readProjectMemories, VALID_PROJECT_MEMORY_KINDS } from '../../services/memory/project-memory-service.js';
20
+ import { describeMemoryBlockDrops, describeMemoryWriteSkips, describeSessionScanFailures, extractSessionMemories, readProjectMemories, VALID_PROJECT_MEMORY_KINDS } from '../../services/memory/project-memory-service.js';
21
21
  import { fail, ok } from 'peaks-loop-shared/result';
22
22
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
23
23
  import { registerProjectDashboardCommand } from './project-dashboard-command.js';
@@ -38,15 +38,18 @@ function extractData(result) {
38
38
  };
39
39
  }
40
40
  /**
41
- * Two drop axes, one channel. `droppedBlocks` = a block was found and rejected
42
- * (or a marker-shaped comment was not findable at all); `scanFailures` = the
43
- * whole artifact could not be read, so its blocks were never candidates.
44
- * `data` is unchanged by either — same contract as `memory.extract`.
41
+ * Three axes, one channel. `droppedBlocks` = a block was found and rejected (or
42
+ * a marker-shaped comment was not findable at all); `scanFailures` = the whole
43
+ * artifact could not be read, so its blocks were never candidates;
44
+ * `skippedWrites` = the block parsed and was planned, and the store already held
45
+ * its target name, so nothing was written. `data` is unchanged by any of them —
46
+ * same contract as `memory.extract`.
45
47
  */
46
48
  function extractWarnings(result) {
47
49
  return [
48
50
  ...describeMemoryBlockDrops(result.droppedBlocks),
49
- ...describeSessionScanFailures(result.scanFailures)
51
+ ...describeSessionScanFailures(result.scanFailures),
52
+ ...describeMemoryWriteSkips(result.skippedWrites, result.extractedCount, result.writtenFiles.length)
50
53
  ];
51
54
  }
52
55
  function runProjectMemories(io, options) {
@@ -0,0 +1,15 @@
1
+ import type { Command } from 'commander';
2
+ import { type PilotGateCounts, type PilotGateReason, type PilotGateVerdict } from '../../services/race/gate2-evaluator.js';
3
+ import { type RaceGate2Policy } from '../../services/race/gate2-policy.js';
4
+ import { type ProgramIO } from '../cli-helpers.js';
5
+ export type PilotStatusReport = {
6
+ readonly policyVersion: string;
7
+ readonly evaluatorVersion: string;
8
+ readonly recordedPolicyVersion?: string;
9
+ readonly policy: RaceGate2Policy;
10
+ readonly verdict: PilotGateVerdict;
11
+ readonly counts: PilotGateCounts;
12
+ readonly reasons: readonly PilotGateReason[];
13
+ readonly evidencePath: string;
14
+ };
15
+ export declare function registerRaceCommands(program: Command, io: ProgramIO): void;
@@ -0,0 +1,65 @@
1
+ import { CLI_VERSION } from 'peaks-loop-shared/version';
2
+ import { fail, ok } from 'peaks-loop-shared/result';
3
+ import { evaluatePilotGate } from '../../services/race/gate2-evaluator.js';
4
+ import { RACE_GATE2_POLICY_V1, RACE_GATE2_POLICY_VERSION } from '../../services/race/gate2-policy.js';
5
+ import { readPilotGate } from '../../services/race/pilot-gate-store.js';
6
+ import { addJsonOption, printResult } from '../cli-helpers.js';
7
+ import { registerRacePilotGateRecordCommand } from './race-pilot-gate-record-command.js';
8
+ const RACE_DESCRIPTION = 'peaks-race-code fast lane: gate-2 threshold policy and evidence';
9
+ const PILOT_STATUS_DESCRIPTION = 'Judge .peaks/race/pilot-gate.json against the gate-2 policy. Read-only; prints pass | fail | insufficient-evidence.';
10
+ const PROJECT_HELP = 'project root (default: cwd)';
11
+ export function registerRaceCommands(program, io) {
12
+ const race = program.command('race').description(RACE_DESCRIPTION);
13
+ registerRacePilotStatusCommand(race, io);
14
+ registerRacePilotGateRecordCommand(race, io);
15
+ }
16
+ function registerRacePilotStatusCommand(race, io) {
17
+ addJsonOption(race
18
+ .command('pilot-status')
19
+ .description(PILOT_STATUS_DESCRIPTION)
20
+ .option('--project <path>', PROJECT_HELP, '.')).action((options) => runPilotStatus(options, io));
21
+ }
22
+ function refuseNoVerdict(io, options, refusal, path) {
23
+ printResult(io, fail('race.pilot-status', refusal.code, refusal.message, { evidencePath: path }, [
24
+ refusal.nextAction
25
+ ]), options.json);
26
+ process.exitCode = 1;
27
+ }
28
+ function runPilotStatus(options, io) {
29
+ const read = readPilotGate(options.project);
30
+ if (read.kind === 'missing') {
31
+ refuseNoVerdict(io, options, {
32
+ code: 'PILOT_GATE_EVIDENCE_MISSING',
33
+ message: `No gate-2 evidence at ${read.path}: no verdict was reached`,
34
+ nextAction: 'Record a pilot task with `peaks race pilot-gate record`'
35
+ }, read.path);
36
+ return;
37
+ }
38
+ if (read.kind === 'invalid') {
39
+ refuseNoVerdict(io, options, {
40
+ code: 'PILOT_GATE_EVIDENCE_INVALID',
41
+ message: `Gate-2 evidence at ${read.path} is unreadable, so no verdict was reached: ${read.message}`,
42
+ nextAction: 'Repair or re-record the evidence file before judging it'
43
+ }, read.path);
44
+ return;
45
+ }
46
+ const evaluation = evaluatePilotGate(read.gate.tasks, RACE_GATE2_POLICY_V1);
47
+ const report = {
48
+ policyVersion: RACE_GATE2_POLICY_VERSION,
49
+ evaluatorVersion: CLI_VERSION,
50
+ policy: RACE_GATE2_POLICY_V1,
51
+ verdict: evaluation.verdict,
52
+ counts: evaluation.counts,
53
+ reasons: evaluation.reasons,
54
+ evidencePath: read.path
55
+ };
56
+ const withRecorded = read.gate.policyVersion === undefined
57
+ ? report
58
+ : { ...report, recordedPolicyVersion: read.gate.policyVersion };
59
+ printResult(io, ok('race.pilot-status', withRecorded, [], []), options.json);
60
+ // `fail` is the only non-zero verdict: `insufficient-evidence` is the normal
61
+ // "keep running the pilot" state, not a failure (PRD §5.1).
62
+ if (evaluation.verdict === 'fail') {
63
+ process.exitCode = 1;
64
+ }
65
+ }
@@ -0,0 +1,3 @@
1
+ import type { Command } from 'commander';
2
+ import { type ProgramIO } from '../cli-helpers.js';
3
+ export declare function registerRacePilotGateRecordCommand(race: Command, io: ProgramIO): void;
@@ -0,0 +1,81 @@
1
+ import { fail, getErrorMessage, ok } from 'peaks-loop-shared/result';
2
+ import { buildPilotTaskRow, RISK_SURFACE_MAX, upsertPilotTask, HANDLING_VALUES, LANE_CHOSEN_BY_VALUES, OUTCOME_VALUES } from '../../services/race/pilot-gate-store.js';
3
+ import { addJsonOption, multipleOption, printResult } from '../cli-helpers.js';
4
+ const PILOT_GATE_DESCRIPTION = 'Gate-2 evidence for the peaks-race-code fast lane';
5
+ const RECORD_DESCRIPTION = 'Upsert one gate-2 evidence row into .peaks/race/pilot-gate.json, keyed by --rid. Refreshes lastEvaluation.';
6
+ const PROJECT_HELP = 'project root (default: cwd)';
7
+ /**
8
+ * A boolean is required with an explicit `true|false` rather than a `--no-*`
9
+ * flag: Commander's negated form DEFAULTS the flag, which would let a row be
10
+ * written with a `false` nobody chose. A required value makes "must be given
11
+ * explicitly" mechanical instead of a convention.
12
+ */
13
+ function parseBooleanFlag(value) {
14
+ if (value === 'true')
15
+ return true;
16
+ if (value === 'false')
17
+ return false;
18
+ throw new Error(`expected true or false, got ${JSON.stringify(value)}`);
19
+ }
20
+ export function registerRacePilotGateRecordCommand(race, io) {
21
+ const pilotGate = race.command('pilot-gate').description(PILOT_GATE_DESCRIPTION);
22
+ addJsonOption(pilotGate
23
+ .command('record')
24
+ .description(RECORD_DESCRIPTION)
25
+ .requiredOption('--rid <id>', 'task request id (letters or digits, then letters, digits, ".", "_" or "-")')
26
+ .requiredOption('--session-id <session>', 'session the task ran in')
27
+ .requiredOption('--date <YYYY-MM-DD>', 'task date')
28
+ .requiredOption('--lane-chosen-by <who>', `who chose the lane (${LANE_CHOSEN_BY_VALUES.join(' | ')})`)
29
+ .requiredOption('--outcome <outcome>', `task outcome (${OUTCOME_VALUES.join(' | ')})`)
30
+ .option('--file <path>', 'repo-relative changed file (repeatable)', multipleOption, [])
31
+ .option('--risk-surface <n>', `risk surface hit, 1..${RISK_SURFACE_MAX} (repeatable)`, multipleOption, [])
32
+ .requiredOption('--risk-surface-handling <handling>', `how a hit was handled (${HANDLING_VALUES.join(' | ')})`)
33
+ .requiredOption('--rolled-back <true|false>', 'was the change rolled back?', parseBooleanFlag)
34
+ .requiredOption('--ci-red <true|false>', 'is a CI failure attributed to this task?', parseBooleanFlag)
35
+ .requiredOption('--missed-risk-surface <true|false>', 'is a missed risk surface known? (no procedure exists for setting this yet)', parseBooleanFlag)
36
+ .option('--project <path>', PROJECT_HELP, '.')).action((options) => runRecord(options, io));
37
+ }
38
+ /**
39
+ * Validate, then write. Validation is fail-closed and runs BEFORE the upsert:
40
+ * a refusal leaves the evidence file exactly as it was, and the message names
41
+ * the flag that broke a rule.
42
+ */
43
+ /** Flags in, row input out. Every value is re-validated by the store. */
44
+ function toInput(options) {
45
+ return {
46
+ rid: options.rid,
47
+ sessionId: options.sessionId,
48
+ date: options.date,
49
+ laneChosenBy: options.laneChosenBy,
50
+ outcome: options.outcome,
51
+ filesChanged: options.file ?? [],
52
+ riskSurfacesHit: (options.riskSurface ?? []).map((value) => Number(value)),
53
+ riskSurfaceHandling: options.riskSurfaceHandling,
54
+ rolledBack: options.rolledBack,
55
+ ciRed: options.ciRed,
56
+ missedRiskSurface: options.missedRiskSurface
57
+ };
58
+ }
59
+ function runRecord(options, io) {
60
+ const built = buildPilotTaskRow(toInput(options));
61
+ if (built.kind === 'invalid') {
62
+ printResult(io, fail('race.pilot-gate.record', 'PILOT_TASK_INVALID', built.message, { rid: options.rid }, [
63
+ 'Fix the flag this message names; nothing was written'
64
+ ]), options.json);
65
+ process.exitCode = 1;
66
+ return;
67
+ }
68
+ try {
69
+ const result = upsertPilotTask(options.project, built.row);
70
+ printResult(io, ok('race.pilot-gate.record', {
71
+ rid: built.row.rid,
72
+ evidencePath: result.path,
73
+ verdict: result.evaluation.verdict,
74
+ counts: result.evaluation.counts
75
+ }, [], []), options.json);
76
+ }
77
+ catch (error) {
78
+ printResult(io, fail('race.pilot-gate.record', 'PILOT_GATE_WRITE_FAILED', getErrorMessage(error), { rid: options.rid }, ['The evidence file was left as it was']), options.json);
79
+ process.exitCode = 1;
80
+ }
81
+ }
@@ -35,6 +35,14 @@ export type RequestTransitionOptions = {
35
35
  forceConfirm?: boolean;
36
36
  json?: boolean;
37
37
  };
38
+ export type RequestRetagOptions = {
39
+ role: RequestArtifactRole;
40
+ type: RequestType;
41
+ project: string;
42
+ /** Required on this write verb — see the note in `request-retag-command.ts`. */
43
+ sessionId: string;
44
+ json?: boolean;
45
+ };
38
46
  export type RequestLintOptions = {
39
47
  role: RequestArtifactRole;
40
48
  project: string;
@@ -1,6 +1,7 @@
1
1
  import { registerRequestInitCommand } from './request-init-command.js';
2
2
  import { registerRequestListCommand } from './request-list-command.js';
3
3
  import { registerRequestShowCommand } from './request-show-command.js';
4
+ import { registerRequestRetagCommand } from './request-retag-command.js';
4
5
  import { registerRequestTransitionCommand } from './request-transition-command.js';
5
6
  import { registerRequestLintCommand } from './request-lint-command.js';
6
7
  import { registerRequestRepairStatusCommand } from './request-repair-status-command.js';
@@ -13,6 +14,7 @@ export function registerRequestCommands(program, io) {
13
14
  registerRequestInitCommand(request, io);
14
15
  registerRequestListCommand(request, io);
15
16
  registerRequestShowCommand(request, io);
17
+ registerRequestRetagCommand(request, io);
16
18
  registerRequestTransitionCommand(request, io);
17
19
  registerRequestLintCommand(request, io);
18
20
  registerRequestRepairStatusCommand(request, io);
@@ -1,27 +1,81 @@
1
1
  import { createRequestArtifact, VALID_REQUEST_TYPES } from '../../services/artifacts/request-artifact-service.js';
2
2
  import { parseRole, parseRequestType, VALID_ROLES } from './request-format-helpers.js';
3
3
  import { fail, ok } from 'peaks-loop-shared/result';
4
- import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
4
+ import { addJsonOption, getErrorMessage, printResult, printableWarningText } from '../cli-helpers.js';
5
+ import { isUnsafePathInput } from '../../shared/path-safety.js';
6
+ import { getCurrentSessionId } from '../../services/skills/skill-presence-service.js';
5
7
  const INIT_DESCRIPTION = 'Create the per-request artifact template for a Peaks role (dry-run by default)';
6
8
  const INIT_ID_HELP = 'request id, e.g. 2026-05-23-add-foo. With --apply, also pre-creates the canonical change-id scope dir at .peaks/_runtime/change/<id>/ so sub-agents never write .peaks/_runtime/<id>/ at top level.';
7
9
  const INIT_PROJECT_HELP = 'target project root';
8
- const INIT_SESSION_HELP = 'override the default date-stamped session id';
10
+ const INIT_SESSION_HELP = 'explicit session id (default: the active session recorded in .peaks/_runtime/session.json)';
9
11
  const INIT_APPLY_HELP = 'write the artifact file (default: preview only)';
10
12
  const INIT_CALLER_ID_HELP = 'Override the caller id for this invocation (D4 priority: flag beats env beats platform fallback). The resolved callerId is stamped on the artifact body and surfaced in the response envelope.';
11
13
  const CALLER_ID_INVALID_HINTS = [
12
14
  'Set --caller-id to a value matching ^[a-zA-Z0-9._-]{1,200}$',
13
15
  'Or set PEAKS_CALLER_ID env var (or CLAUDE_CODE_SESSION_ID for Claude Code)'
14
16
  ];
15
- function failInitSessionIdRequired(io, options) {
16
- printResult(io, fail('request.init', 'SESSION_ID_REQUIRED', '--session-id is required: the CLI writes envelopes only to .peaks/_runtime/<sessionId>/... (one-axis layout)', { role: options.role, requestId: options.id }, ['Re-run with --session-id <sid>', 'Or run `peaks workspace init` to create a session first']), options.json);
17
+ const INIT_SESSION_HINTS = [
18
+ 'Re-run with --session-id <sid>',
19
+ 'Or run `peaks workspace init` to create a session first'
20
+ ];
21
+ function initSessionProblemMessage(problem) {
22
+ if (problem === 'blank') {
23
+ return '--session-id was passed but is blank. Give it a session id, or omit the flag to use the session recorded in .peaks/_runtime/session.json';
24
+ }
25
+ if (problem === 'malformed') {
26
+ return 'the session id recorded in .peaks/_runtime/session.json is not usable: it must be one printable path segment, because the artifact is scoped to a directory named after it. Pass --session-id, or re-run `peaks workspace init`';
27
+ }
28
+ return 'no session id: pass --session-id, or run inside a workspace that records one in .peaks/_runtime/session.json (the CLI writes envelopes only to .peaks/_runtime/<sessionId>/..., one-axis layout)';
29
+ }
30
+ function failInitSession(io, options, problem) {
31
+ printResult(io, fail('request.init', 'SESSION_ID_REQUIRED', initSessionProblemMessage(problem), { role: options.role, requestId: options.id }, INIT_SESSION_HINTS), options.json);
17
32
  process.exitCode = 1;
18
33
  }
34
+ /**
35
+ * The session id is used verbatim as ONE directory name under `.peaks/_runtime/`,
36
+ * so a usable one is a single printable path segment. `isUnsafePathInput` covers
37
+ * `.`/`..`, separators, drive/UNC/URL shapes — and NOT the C0/C1 control
38
+ * characters, so a recorded id carrying a newline would be accepted and would
39
+ * forge a line in the preview and in the artifact body's `session:` field.
40
+ * `printableWarningText` is the canonical control-character check; a value equal
41
+ * to its printable form carries none.
42
+ */
43
+ function isUsableSessionSegment(value) {
44
+ return !isUnsafePathInput(value) && printableWarningText(value) === value;
45
+ }
46
+ /**
47
+ * The session id the artifact must land under. An explicit `--session-id` wins;
48
+ * otherwise read the workspace's active session from
49
+ * `.peaks/_runtime/session.json` — the source `peaks sub-agent dispatch` and
50
+ * `peaks skill presence` already read for this same id. The caller refuses
51
+ * rather than writing under a placeholder directory; unlike dispatch, this
52
+ * command never falls back to `'unknown-sid'`, because it writes files.
53
+ *
54
+ * A SUPPLIED-but-blank flag is its own problem, not an omission: silently
55
+ * substituting the workspace id would hide a caller mistake (an unset variable
56
+ * expanding to empty would quietly target a different session), and this is the
57
+ * behaviour the flag had before the fallback existed.
58
+ *
59
+ * Only the fallback value is shape-checked here. A value passed via
60
+ * `--session-id` flows downstream exactly as it did before, so a caller who
61
+ * passes that flag sees no change.
62
+ */
63
+ function resolveInitSessionId(options) {
64
+ if (options.sessionId !== undefined) {
65
+ const explicit = options.sessionId.trim();
66
+ return explicit.length === 0 ? { problem: 'blank' } : { id: explicit };
67
+ }
68
+ const recorded = getCurrentSessionId(options.project);
69
+ if (recorded === null)
70
+ return { problem: 'absent' };
71
+ return isUsableSessionSegment(recorded) ? { id: recorded } : { problem: 'malformed' };
72
+ }
19
73
  function buildInitServiceOptions(options, sessionId) {
20
- // One-axis layout: --session-id is REQUIRED. The on-disk root
21
- // is always `.peaks/_runtime/<sessionId>/<role>/...`. The user
22
- // has forbidden the `.peaks/_runtime/<id>/` root layout — without an
23
- // explicit session id, we cannot guarantee the artifact lands
24
- // under `_runtime/`. See
74
+ // One-axis layout: the on-disk root is always
75
+ // `.peaks/_runtime/<sessionId>/<role>/...`, and the session id arrives
76
+ // already resolved (`resolveInitSessionId`) — the caller refuses when it
77
+ // could not be. The user has forbidden the `.peaks/_runtime/<id>/` root
78
+ // layout. See
25
79
  // `.peaks/memory/2026-06-21-peaks-request-session-id-leaks-into-change-id.md`.
26
80
  const serviceOptions = {
27
81
  role: options.role,
@@ -66,11 +120,12 @@ async function resolveInitCallerId(io, options) {
66
120
  }
67
121
  async function runRequestInit(options, io) {
68
122
  try {
69
- if (options.sessionId === undefined || options.sessionId.trim().length === 0) {
70
- failInitSessionIdRequired(io, options);
123
+ const resolved = resolveInitSessionId(options);
124
+ if (resolved.id === undefined) {
125
+ failInitSession(io, options, resolved.problem);
71
126
  return;
72
127
  }
73
- const serviceOptions = buildInitServiceOptions(options, options.sessionId);
128
+ const serviceOptions = buildInitServiceOptions(options, resolved.id);
74
129
  const callerId = await resolveInitCallerId(io, options);
75
130
  if (callerId === null)
76
131
  return;
@@ -0,0 +1,3 @@
1
+ import type { Command } from 'commander';
2
+ import { type ProgramIO } from '../cli-helpers.js';
3
+ export declare function registerRequestRetagCommand(request: Command, io: ProgramIO): void;
@@ -0,0 +1,50 @@
1
+ import { retagRequestArtifact, describeRetag } from '../../services/artifacts/request-retag-service.js';
2
+ import { VALID_REQUEST_TYPES } from '../../services/artifacts/request-artifact-service.js';
3
+ import { parseRequestType, parseRole, VALID_ROLES } from './request-format-helpers.js';
4
+ import { fail, ok } from 'peaks-loop-shared/result';
5
+ import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
6
+ const RETAG_DESCRIPTION = "Set a request artifact's type, replacing whatever it currently records. Reports the prerequisite table the new type selects and any of its artifacts that are not on disk yet.";
7
+ const RETAG_REQUEST_ID_HELP = 'request id, e.g. 2026-05-23-add-foo';
8
+ const RETAG_TYPE_HELP = `request type (${VALID_REQUEST_TYPES.join(' | ')})`;
9
+ const RETAG_PROJECT_HELP = 'target project root';
10
+ /**
11
+ * Required, unlike the read verbs' optional flag. `showRequestArtifact` resolves
12
+ * the first session holding a matching rid when none is given, which is a fine
13
+ * way to READ and a way to WRITE the wrong artifact — so this verb names its
14
+ * target or does nothing.
15
+ */
16
+ const RETAG_SESSION_HELP = 'session id holding the artifact to retag (required)';
17
+ async function runRequestRetag(requestId, options, io) {
18
+ try {
19
+ const result = await retagRequestArtifact({
20
+ projectRoot: options.project,
21
+ role: options.role,
22
+ requestId,
23
+ requestType: options.type,
24
+ sessionId: options.sessionId
25
+ });
26
+ if (result === null) {
27
+ printResult(io, fail('request.retag', 'REQUEST_NOT_FOUND', `No artifact found for role=${options.role} requestId=${requestId}`, { role: options.role, requestId }, ['Verify the request id, role, and session id']), options.json);
28
+ process.exitCode = 1;
29
+ return;
30
+ }
31
+ printResult(io, ok('request.retag', result, describeRetag(result)), options.json);
32
+ }
33
+ catch (error) {
34
+ printResult(io, fail('request.retag', 'REQUEST_RETAG_FAILED', getErrorMessage(error), {
35
+ role: options.role,
36
+ requestId
37
+ }), options.json);
38
+ process.exitCode = 1;
39
+ }
40
+ }
41
+ export function registerRequestRetagCommand(request, io) {
42
+ addJsonOption(request
43
+ .command('retag')
44
+ .description(RETAG_DESCRIPTION)
45
+ .argument('<request-id>', RETAG_REQUEST_ID_HELP)
46
+ .requiredOption('--role <role>', `target role (${VALID_ROLES.join(' | ')})`, parseRole)
47
+ .requiredOption('--type <type>', RETAG_TYPE_HELP, parseRequestType)
48
+ .requiredOption('--project <path>', RETAG_PROJECT_HELP)
49
+ .requiredOption('--session-id <session>', RETAG_SESSION_HELP)).action((requestId, options) => runRequestRetag(requestId, options, io));
50
+ }
@@ -1,3 +1,11 @@
1
1
  import type { Command } from 'commander';
2
+ import { type ShowRequestArtifactResult } from '../../services/artifacts/request-artifact-service.js';
2
3
  import { type ProgramIO } from '../cli-helpers.js';
4
+ /**
5
+ * The type a `request show` reports is the EFFECTIVE one: an artifact that
6
+ * records no type still reads as `feature`, and a reader who cannot tell that
7
+ * from a chosen `feature` cannot tell which prerequisite table the next gate
8
+ * will apply. The field says which; this line says it in words.
9
+ */
10
+ export declare function typeProvenanceWarning(result: ShowRequestArtifactResult): string[];
3
11
  export declare function registerRequestShowCommand(request: Command, io: ProgramIO): void;