@gtheys/pi-flow 0.0.0-stage → 0.2.0

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 (164) hide show
  1. package/README.md +833 -2
  2. package/adhoc/tracker.ts +360 -0
  3. package/aven/client.ts +996 -0
  4. package/aven/status.ts +395 -0
  5. package/brainstorm/args.ts +24 -0
  6. package/brainstorm/artifact.ts +67 -0
  7. package/brainstorm/paths.ts +43 -0
  8. package/brainstorm/prompt.ts +172 -0
  9. package/brainstorm/refs.ts +41 -0
  10. package/config.schema.json +161 -0
  11. package/config.ts +577 -0
  12. package/feedback/args.ts +21 -0
  13. package/feedback/prompt.ts +177 -0
  14. package/feedback/triage.ts +88 -0
  15. package/flow/agent-role.ts +46 -0
  16. package/flow/answer-wake.ts +212 -0
  17. package/flow/answer.ts +183 -0
  18. package/flow/args.ts +48 -0
  19. package/flow/ask-emitter.ts +331 -0
  20. package/flow/attribution.ts +145 -0
  21. package/flow/aven-resolve-exec.ts +95 -0
  22. package/flow/aven-resolve.ts +80 -0
  23. package/flow/awaiting-approval.ts +32 -0
  24. package/flow/binding-heal.ts +68 -0
  25. package/flow/cost-autopush.ts +162 -0
  26. package/flow/cost-command.ts +122 -0
  27. package/flow/cost-rows-journal.ts +296 -0
  28. package/flow/cost-rows-push.ts +112 -0
  29. package/flow/cost-rows-rows.ts +209 -0
  30. package/flow/cost-rows.ts +228 -0
  31. package/flow/cost.ts +173 -0
  32. package/flow/durable-refs.ts +287 -0
  33. package/flow/effect-gate.ts +137 -0
  34. package/flow/ensure-labels.ts +44 -0
  35. package/flow/frame.ts +172 -0
  36. package/flow/gates.ts +211 -0
  37. package/flow/jira-ref.ts +212 -0
  38. package/flow/label-gate.ts +149 -0
  39. package/flow/land-gate.ts +98 -0
  40. package/flow/lifecycle-policy.ts +162 -0
  41. package/flow/live-wait.ts +52 -0
  42. package/flow/liveness.ts +408 -0
  43. package/flow/loop-deps.ts +210 -0
  44. package/flow/loop-settle.ts +531 -0
  45. package/flow/loop.ts +437 -0
  46. package/flow/orchestrate.ts +45 -0
  47. package/flow/phase-command.ts +287 -0
  48. package/flow/phase-emoji.ts +13 -0
  49. package/flow/phase-prompts.ts +251 -0
  50. package/flow/picker.ts +307 -0
  51. package/flow/push.ts +475 -0
  52. package/flow/reconcile-command.ts +253 -0
  53. package/flow/reconcile-deps.ts +329 -0
  54. package/flow/reconcile.ts +738 -0
  55. package/flow/ref-kind.ts +80 -0
  56. package/flow/resume-picker.ts +222 -0
  57. package/flow/resume.ts +116 -0
  58. package/flow/run-health.ts +252 -0
  59. package/flow/run-liveness.ts +33 -0
  60. package/flow/state-metrics.ts +559 -0
  61. package/flow/status.ts +105 -0
  62. package/flow/step-output.ts +416 -0
  63. package/flow/steps.ts +73 -0
  64. package/flow/terminal-purge.ts +281 -0
  65. package/flow/turn-generation.ts +19 -0
  66. package/flow/v2-emission.ts +381 -0
  67. package/flow/v2-resume.ts +100 -0
  68. package/flow/vocabulary.ts +261 -0
  69. package/flow/widget.ts +448 -0
  70. package/flow/worktree-context.ts +136 -0
  71. package/flow-diagram/assemble.ts +27 -0
  72. package/flow-diagram/command.ts +252 -0
  73. package/flow-diagram/translate.ts +862 -0
  74. package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
  75. package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
  76. package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
  77. package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
  78. package/flow-diagram/vendor/harness-profiler/view.html +436 -0
  79. package/gates.ts +20 -0
  80. package/herdr/sync.ts +355 -0
  81. package/herdr/viewer.ts +432 -0
  82. package/implement/args.ts +21 -0
  83. package/implement/prompt.ts +98 -0
  84. package/implement/retry.ts +57 -0
  85. package/implement/routing.ts +31 -0
  86. package/index.ts +3206 -0
  87. package/mode-profile.ts +56 -0
  88. package/package.json +205 -4
  89. package/phase-state.ts +18 -0
  90. package/plan/args.ts +20 -0
  91. package/plan/prompt.ts +251 -0
  92. package/plan/size-check.ts +46 -0
  93. package/plan-tools/helpers.ts +177 -0
  94. package/plan-tools/jira-branch-tool.ts +54 -0
  95. package/plan-tools/jira-branch.ts +109 -0
  96. package/plan-tools/jira-issue.ts +85 -0
  97. package/plan-tools/resolve-feature-path.ts +30 -0
  98. package/plan-tools/resolve-notes-path.ts +37 -0
  99. package/plan-tools/resolve-spec-path.ts +31 -0
  100. package/pr-quality/index.ts +908 -0
  101. package/review/LICENSE +19 -0
  102. package/review/deviation.ts +252 -0
  103. package/review/review.ts +3053 -0
  104. package/review/sem-guidance.d.mts +8 -0
  105. package/review/sem-guidance.mjs +89 -0
  106. package/review/verdict.ts +13 -0
  107. package/run-state.ts +2046 -0
  108. package/run-title.ts +91 -0
  109. package/server/consumer.ts +146 -0
  110. package/server/daemon.ts +1094 -0
  111. package/server/lifecycle.ts +679 -0
  112. package/server/pending.ts +267 -0
  113. package/server/staleness.ts +320 -0
  114. package/server/writer.ts +86 -0
  115. package/shared/diff-base.ts +138 -0
  116. package/shared/flow-base.ts +210 -0
  117. package/shared/sonarqube-utils.ts +415 -0
  118. package/shared/stable-range.ts +102 -0
  119. package/slugify.ts +13 -0
  120. package/sonarqube/sonarqube.ts +821 -0
  121. package/spec-review/approve.ts +91 -0
  122. package/spec-review/args.ts +21 -0
  123. package/spec-review/aven-spec.ts +142 -0
  124. package/spec-review/commands.ts +336 -0
  125. package/spec-review/escape-regexp.ts +7 -0
  126. package/spec-review/open-in-pane.ts +166 -0
  127. package/spec-review/picker.ts +74 -0
  128. package/spec-review/prompt.ts +72 -0
  129. package/spec-review/publish-args.ts +33 -0
  130. package/spec-review/publish.ts +210 -0
  131. package/telemetry/attributes.ts +118 -0
  132. package/telemetry/content.ts +140 -0
  133. package/telemetry/dispatch.ts +521 -0
  134. package/telemetry/exporter.ts +124 -0
  135. package/telemetry/index.ts +776 -0
  136. package/telemetry/loki.ts +224 -0
  137. package/tools/code-review-parse.ts +518 -0
  138. package/tools/code-review.ts +312 -0
  139. package/tools/deviation.ts +737 -0
  140. package/tools/flow-submit.ts +302 -0
  141. package/tools/land.ts +608 -0
  142. package/tools/phase-complete.ts +476 -0
  143. package/tools/result.ts +18 -0
  144. package/tools/review-deps.ts +44 -0
  145. package/tools/run-attempt.ts +312 -0
  146. package/tools/spec-approve.ts +265 -0
  147. package/validate/args.ts +22 -0
  148. package/validate/deviation-gate.ts +229 -0
  149. package/validate/gate-target.ts +371 -0
  150. package/validate/gate.ts +79 -0
  151. package/validate/paths.ts +20 -0
  152. package/validate/personal.ts +104 -0
  153. package/validate/prompt.ts +525 -0
  154. package/validate/review-gate.ts +134 -0
  155. package/validate/subtask-range.ts +113 -0
  156. package/work-mode.ts +19 -0
  157. package/worktree/bootstrap.ts +243 -0
  158. package/worktree/branch.ts +168 -0
  159. package/worktree/herdr.ts +447 -0
  160. package/worktree/index.ts +1447 -0
  161. package/worktree/orphan.ts +384 -0
  162. package/worktree/remove-guards.ts +99 -0
  163. package/worktree/residue.ts +216 -0
  164. package/worktree/sweep.ts +526 -0
package/flow/status.ts ADDED
@@ -0,0 +1,105 @@
1
+ // AIDEV-NOTE (PMR-ZGPY 3.1, D1/D2): pure render helpers for the flow-status
2
+ // widget — no IO, no Pi imports. D1 (rewritten, PMR-C3B6): shouldShowWidget
3
+ // now answers "is there content to render" (state, subtasks, or gates
4
+ // exist), NOT "should the widget be visible" — registration is
5
+ // flash/pin-gated by the visibility state machine in flow/widget.ts
6
+ // (phase-transition flash + toggleFlowDashboardPin). D2 (output shape):
7
+ // phase lines mirror flow-viewer.mjs renderState (PMR-Z2K7 lifecycle, no
8
+ // research row): `[x]`/`[ ]` marks plus ` <- running` on the current phase;
9
+ // the `-> /flow answer <ref>` hint is only for answerCommand gates — the
10
+ // picker (3.2 wiring) supplies the choices, so we never invent vocabulary
11
+ // here. Presentation (✅/emoji/SGR) lives in frame.ts (PMR-X7BH); widget lines
12
+ // from renderFlowStatusLines stay ASCII by contract — the footer
13
+ // (renderFooterStatus, PMR-C3B6) is deliberately emoji-bearing. Subtasks use a
14
+ // minimal structural AssignmentSummary mapped from
15
+ // pi-interactive-subagents listAssignments by the 3.2 lifecycle caller.
16
+
17
+ import type { FlowRunState } from '../run-state.ts'
18
+ import type { OpenGate } from './gates.ts'
19
+ import { PHASE_EMOJI } from './phase-emoji.ts'
20
+
21
+ /** Minimal structural slice of a subagents assignment record. */
22
+ export interface AssignmentSummary {
23
+ name: string
24
+ status: string
25
+ }
26
+
27
+ export interface StatusInput {
28
+ state: FlowRunState | null
29
+ subtasks: AssignmentSummary[]
30
+ gates: OpenGate[]
31
+ }
32
+
33
+ const PHASES: readonly {
34
+ phase: FlowRunState['completedPhases'][number]
35
+ label: string
36
+ }[] = [
37
+ { phase: 'plan', label: 'planned' },
38
+ { phase: 'implement', label: 'active' },
39
+ { phase: 'validate', label: 'review-passed' },
40
+ { phase: 'feedback', label: 'done' },
41
+ ]
42
+
43
+ /** D1: widget registers only when there is something to show. */
44
+ export function shouldShowWidget(input: StatusInput): boolean {
45
+ if (input.state !== null) return true
46
+ if (input.subtasks.length > 0) return true
47
+ if (input.gates.length > 0) return true
48
+ return false
49
+ }
50
+
51
+ /** Footer text: `📋 <ref> <emoji> <phase>`; phase suffix omitted when null;
52
+ * undefined when there is no state (no active flow ⇒ no footer). */
53
+ export function renderFooterStatus(
54
+ state: FlowRunState | null,
55
+ ): string | undefined {
56
+ if (state === null) {
57
+ return undefined
58
+ }
59
+ let suffix = ''
60
+ const phase = state.currentPhase
61
+ if (phase !== null) {
62
+ suffix = ` ${PHASE_EMOJI[phase]} ${phase}`
63
+ }
64
+ return `📋 ${state.ref}${suffix}`
65
+ }
66
+
67
+ export function renderFlowStatusLines(input: StatusInput): string[] {
68
+ const lines: string[] = []
69
+ if (input.state !== null) {
70
+ lines.push(`flow ${input.state.ref} · ${input.state.mode}`)
71
+ for (const { phase, label } of PHASES) {
72
+ const completed = input.state.completedPhases.includes(phase)
73
+ let mark: string
74
+ if (completed) {
75
+ mark = '[x]'
76
+ } else {
77
+ mark = '[ ]'
78
+ }
79
+ let running: string
80
+ if (input.state.currentPhase === phase) {
81
+ running = ' <- running'
82
+ } else {
83
+ running = ''
84
+ }
85
+ lines.push(`${mark} ${phase.padEnd(11)} (${label})${running}`)
86
+ }
87
+ }
88
+ if (input.subtasks.length > 0) {
89
+ lines.push('subtasks:')
90
+ for (const subtask of input.subtasks) {
91
+ lines.push(` ${subtask.name} — ${subtask.status}`)
92
+ }
93
+ }
94
+ if (input.gates.length > 0) {
95
+ lines.push('gates:')
96
+ for (const gate of input.gates) {
97
+ if (gate.answerCommand !== undefined) {
98
+ lines.push(` ${gate.title} → ${gate.answerCommand}`)
99
+ } else {
100
+ lines.push(` ${gate.title}`)
101
+ }
102
+ }
103
+ }
104
+ return lines
105
+ }
@@ -0,0 +1,416 @@
1
+ // AIDEV-NOTE (PMR-HVAX, structured step outputs; phase 2 of PMR-C998):
2
+ // advisory-only contract. Submitting a step-output event journals evidence
3
+ // (facts, SHA, PR link) but NEVER gates completion — the /flow loop's labels
4
+ // remain the gate of record. Sole exception (PMR-AYMZ, named per PMR-N3AH):
5
+ // an ok=true plan.route-confirmed step-output journaled in the current run,
6
+ // together with the live oneshot label, satisfies the
7
+ // flow_phase_complete(plan) receipt gate. Validation here is schema
8
+ // enforcement (well-formed
9
+ // facts, actionable rejection reasons), not a completion gate: a bare step
10
+ // boundary with zero facts is a valid submission, and a rejected submission
11
+ // only means the caller should fix the payload, not that a phase is blocked.
12
+
13
+ import { FLOW_VALUE_RE } from '@gtheys/pi-interactive-subagents'
14
+ import { type Static, Type } from 'typebox'
15
+ import type { FlowPhase } from '../run-state.ts'
16
+ import { isFullSha } from '../validate/gate-target.ts'
17
+ import { isRegisteredStep, STEP_REGISTRY } from './steps.ts'
18
+
19
+ /**
20
+ * Per-phase fact schemas, discriminated on `phase`. Every fact is optional so
21
+ * a bare step boundary (phase + step label, no facts) is a valid submission.
22
+ * Field descriptions are part of the contract: tools/flow-submit.ts uses this
23
+ * schema directly as its `output` param (single source, never inlined).
24
+ */
25
+ export const StepOutputSchema = Type.Union(
26
+ [
27
+ Type.Object({
28
+ phase: Type.Literal('plan'),
29
+ planPath: Type.Optional(
30
+ Type.String({ description: 'Path of the written plan' }),
31
+ ),
32
+ subtaskRefs: Type.Optional(
33
+ Type.Array(Type.String(), {
34
+ description: 'Subtask refs covered by the plan',
35
+ }),
36
+ ),
37
+ }),
38
+ Type.Object({
39
+ phase: Type.Literal('implement'),
40
+ command: Type.Optional(
41
+ Type.String({ description: 'Verification command that ran' }),
42
+ ),
43
+ passed: Type.Optional(
44
+ Type.Boolean({ description: 'Whether the command passed' }),
45
+ ),
46
+ headSha: Type.Optional(
47
+ Type.String({ description: 'Full 40-char HEAD SHA the evidence pins' }),
48
+ ),
49
+ }),
50
+ Type.Object({
51
+ phase: Type.Literal('validate'),
52
+ prNumber: Type.Optional(
53
+ Type.Number({ description: 'PR number under validation' }),
54
+ ),
55
+ prUrl: Type.Optional(
56
+ Type.String({ description: 'PR URL under validation' }),
57
+ ),
58
+ gateTargetIds: Type.Optional(
59
+ Type.Array(Type.String(), {
60
+ description: 'Ids of gate-target events this evidence covers',
61
+ }),
62
+ ),
63
+ }),
64
+ Type.Object({
65
+ phase: Type.Literal('feedback'),
66
+ prUrl: Type.Optional(
67
+ Type.String({ description: 'PR URL the feedback is about' }),
68
+ ),
69
+ prMerged: Type.Optional(
70
+ Type.Boolean({ description: 'Whether the PR merged' }),
71
+ ),
72
+ }),
73
+ ],
74
+ {
75
+ description:
76
+ 'Phase-discriminated step output; phase is the discriminator and no separate phase param exists',
77
+ },
78
+ )
79
+
80
+ export type StepOutputFacts = Static<typeof StepOutputSchema>
81
+
82
+ // AIDEV-NOTE (PMR-C998): schema-derived union of every optional fact key.
83
+ // Extract picks each union branch by its literal `phase` discriminator and
84
+ // the mapped type collects the branch's fact keys. Deriving — instead of a
85
+ // third hand-written list — is what makes the drift guards below compile-
86
+ // time enforced rather than wishful.
87
+ type SchemaFactKeys = {
88
+ [P in StepOutputFacts['phase']]: Exclude<
89
+ keyof Extract<StepOutputFacts, { phase: P }>,
90
+ 'phase'
91
+ >
92
+ }[StepOutputFacts['phase']]
93
+
94
+ // Exhaustiveness idiom: Expect<T extends true> only compiles for `true`, so
95
+ // wrapping IsNever<X> turns "X has leftover members" into a tsc error.
96
+ type IsNever<T> = [T] extends [never] ? true : false
97
+ type Expect<T extends true> = T
98
+
99
+ /**
100
+ * Payload shape of the `step-output` FlowRunEvent member that subtask 2.2
101
+ * adds to run-state.ts. Kept local here so this pure module compiles
102
+ * standalone; 2.2 must carry exactly these fields.
103
+ */
104
+ export interface StepOutputEventPayload {
105
+ kind: 'step-output'
106
+ /** ISO timestamp — every FlowRunEvent carries `at` as an ISO string. */
107
+ at: string
108
+ ref: string
109
+ phase: FlowPhase
110
+ step: string
111
+ ok?: boolean
112
+ detail?: string
113
+ planPath?: string
114
+ subtaskRefs?: string[]
115
+ command?: string
116
+ passed?: boolean
117
+ headSha?: string
118
+ headShaVerified?: boolean
119
+ prNumber?: number
120
+ prUrl?: string
121
+ gateTargetIds?: string[]
122
+ prMerged?: boolean
123
+ }
124
+
125
+ /** Union of every optional per-phase fact field, all optional. */
126
+ /**
127
+ * AIDEV-NOTE: PMR-C998 — flat mirror of every optional fact field across the
128
+ * four StepOutputSchema branches. Kept in sync with the schema BY HAND:
129
+ * StepOutputSchema remains the authoritative tool-boundary contract (TypeBox
130
+ * validates the `output` param per phase in tools/flow-submit.ts), and
131
+ * validateFactTypes below is the runtime cross-check of phase/fact
132
+ * consistency, including cross-phase rejection: any fact key from a foreign
133
+ * phase branch (even correctly typed) is refused, because TypeBox unions
134
+ * allow additional properties and would otherwise let a spread journal
135
+ * wrong-phase evidence. Not derived from the schema union: intersecting optional
136
+ * props from different union branches resolves them to never, which would
137
+ * make every facts-carrying caller untypeable without casts.
138
+ */
139
+ type StepOutputFactFields = {
140
+ planPath?: string
141
+ subtaskRefs?: string[]
142
+ command?: string
143
+ passed?: boolean
144
+ headSha?: string
145
+ prNumber?: number
146
+ prUrl?: string
147
+ gateTargetIds?: string[]
148
+ prMerged?: boolean
149
+ }
150
+
151
+ // AIDEV-NOTE: compile-time drift guard — tsc fails when StepOutputFactFields
152
+ // and the schema union disagree in EITHER direction (a fact added to the
153
+ // schema without mirroring it here, or a stale mirror key after schema
154
+ // removal). Without this, a drifted key would silently skip cross-phase
155
+ // rejection for it.
156
+ export type FactFieldsMirrorGuard = [
157
+ Expect<IsNever<Exclude<SchemaFactKeys, keyof StepOutputFactFields>>>,
158
+ Expect<IsNever<Exclude<keyof StepOutputFactFields, SchemaFactKeys>>>,
159
+ ]
160
+
161
+ export type StepOutputInput = StepOutputFactFields & {
162
+ ref: string
163
+ step: string
164
+ phase: FlowPhase
165
+ ok?: boolean
166
+ detail?: string
167
+ }
168
+
169
+ // AIDEV-NOTE: PMR-ZV9Y 1.2 — `hint` is the advisory step-registry note. It is
170
+ // NEVER a rejection: a submission with an unregistered step name is still ok
171
+ // and still journals; the hint only asks the caller to prefer a registered
172
+ // name (see flow/steps.ts STEP_REGISTRY). It is absent for phases whose
173
+ // registry is empty (implement/feedback — free-form step labels are the
174
+ // documented contract there) so the advisory never nags those runs.
175
+ // PMR-S7FQ: that emptiness is load-bearing, not an omission — the
176
+ // `registeredNames.length > 0` guard below is what keeps implement/feedback
177
+ // hint-free, so registering names there would ADD noise rather than remove it.
178
+ export type StepOutputResult =
179
+ | { ok: true; event: StepOutputEventPayload; hint?: string }
180
+ | { ok: false; reason: string }
181
+
182
+ function buildTypeMismatchReason(
183
+ field: string,
184
+ phase: StepOutputFacts['phase'],
185
+ expected: string,
186
+ ): string {
187
+ return `Invalid ${phase} fact "${field}": expected ${expected}.`
188
+ }
189
+
190
+ // AIDEV-NOTE: value type is DERIVED per phase from the schema union, so a
191
+ // key from a foreign phase cannot be listed here (element type mismatch) —
192
+ // only the "missing key" direction needs the guard below.
193
+ const FACT_KEYS_BY_PHASE: {
194
+ [P in StepOutputFacts['phase']]: readonly Exclude<
195
+ keyof Extract<StepOutputFacts, { phase: P }>,
196
+ 'phase'
197
+ >[]
198
+ } = {
199
+ plan: ['planPath', 'subtaskRefs'],
200
+ implement: ['command', 'passed', 'headSha'],
201
+ validate: ['prNumber', 'prUrl', 'gateTargetIds'],
202
+ feedback: ['prUrl', 'prMerged'],
203
+ }
204
+
205
+ // AIDEV-NOTE: compile-time exhaustiveness guard — tsc fails when a schema
206
+ // fact key is missing from FACT_KEYS_BY_PHASE (a missing key would silently
207
+ // skip cross-phase rejection for it). Extra keys are already rejected by the
208
+ // derived per-phase array element types above.
209
+ type MappedFactKeys =
210
+ (typeof FACT_KEYS_BY_PHASE)[StepOutputFacts['phase']][number]
211
+ export type FactKeysExhaustiveGuard = Expect<
212
+ IsNever<Exclude<SchemaFactKeys, MappedFactKeys>>
213
+ >
214
+
215
+ function buildCrossPhaseReason(
216
+ field: string,
217
+ phase: StepOutputFacts['phase'],
218
+ ): string {
219
+ const phases = FACT_KEY_PHASES[field].join(' or ')
220
+ let plural = ''
221
+ if (FACT_KEY_PHASES[field].length > 1) {
222
+ plural = 's'
223
+ }
224
+ return `Invalid ${phase} fact "${field}": not a ${phase} fact — ${field} belongs to the ${phases} phase${plural}.`
225
+ }
226
+
227
+ // AIDEV-NOTE (PMR-C998): reverse index of fact key -> owning phases. prUrl is
228
+ // legitimately shared by validate and feedback, so values are arrays and a key
229
+ // is only foreign when the input's phase is absent from the list.
230
+ const FACT_KEY_PHASES: Record<string, StepOutputFacts['phase'][]> = {}
231
+ for (const phase of Object.keys(FACT_KEYS_BY_PHASE) as Array<
232
+ StepOutputFacts['phase']
233
+ >) {
234
+ for (const key of FACT_KEYS_BY_PHASE[phase]) {
235
+ const owners = FACT_KEY_PHASES[key]
236
+ if (owners === undefined) {
237
+ FACT_KEY_PHASES[key] = [phase]
238
+ } else {
239
+ owners.push(phase)
240
+ }
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Rejects fact keys that belong only to phases other than the input's phase.
246
+ * Returns null when no foreign keys are present.
247
+ */
248
+ function validateCrossPhaseFacts(input: StepOutputInput): string | null {
249
+ for (const field of Object.keys(FACT_KEY_PHASES)) {
250
+ if (FACT_KEY_PHASES[field].includes(input.phase)) {
251
+ continue
252
+ }
253
+ const value = input[field as keyof StepOutputFactFields]
254
+ if (value !== undefined) {
255
+ return buildCrossPhaseReason(field, input.phase)
256
+ }
257
+ }
258
+ return null
259
+ }
260
+
261
+ export function buildStepOutputEvent(input: StepOutputInput): StepOutputResult {
262
+ if (!FLOW_VALUE_RE.test(input.ref)) {
263
+ return {
264
+ ok: false,
265
+ reason: `Invalid ref "${input.ref}": must match the flow value charset (alphanumeric, plus dots, underscores and dashes, e.g. "pmr-hvax").`,
266
+ }
267
+ }
268
+
269
+ if (input.step.length === 0) {
270
+ return {
271
+ ok: false,
272
+ reason:
273
+ 'Invalid step: must be 1-64 chars matching the flow value charset (alphanumeric, plus dots, underscores and dashes).',
274
+ }
275
+ }
276
+ if (input.step.length > 64) {
277
+ return {
278
+ ok: false,
279
+ reason: `Invalid step "${input.step.slice(0, 12)}…": must be 1-64 chars matching the flow value charset (alphanumeric, plus dots, underscores and dashes).`,
280
+ }
281
+ }
282
+ if (!FLOW_VALUE_RE.test(input.step)) {
283
+ return {
284
+ ok: false,
285
+ reason: `Invalid step "${input.step}": must be 1-64 chars matching the flow value charset (alphanumeric, plus dots, underscores and dashes).`,
286
+ }
287
+ }
288
+
289
+ if (input.headSha !== undefined && !isFullSha(input.headSha)) {
290
+ return {
291
+ ok: false,
292
+ reason: `Invalid headSha "${input.headSha}": must be a full 40-character hex SHA.`,
293
+ }
294
+ }
295
+
296
+ const factsTypeCheck = validateFactTypes(input)
297
+ if (factsTypeCheck !== null) {
298
+ return { ok: false, reason: factsTypeCheck }
299
+ }
300
+
301
+ // AIDEV-NOTE: PMR-ZV9Y 1.2 — advisory step-registry hint (after charset
302
+ // validation, advisory posture ONLY: never rejects, the submission is still
303
+ // ok and still journals below). Only surfaces when the phase HAS registered
304
+ // names and the submitted step is not one of them, so implement/feedback
305
+ // (empty registries, free-form labels by design) stay hint-free. The hint
306
+ // text deliberately says "not in the <phase> step registry" +
307
+ // "registered names" rather than "warning" so it reads as advisory
308
+ // vocabulary and is distinguishable from the tool's verification warnings.
309
+ // PMR-S7FQ: the non-empty precondition is the whole reason implement and
310
+ // feedback never warn — see the AIDEV anchors on those STEP_REGISTRY entries.
311
+ let hint: string | undefined
312
+ const registeredNames = STEP_REGISTRY[input.phase]
313
+ if (
314
+ registeredNames.length > 0 &&
315
+ !isRegisteredStep(input.phase, input.step)
316
+ ) {
317
+ hint = `advisory: step "${input.step}" is not in the ${input.phase} step registry; registered names: ${registeredNames.join(', ')} (flow/steps.ts). The submission is still journaled — prefer a registered name.`
318
+ }
319
+
320
+ return {
321
+ ok: true,
322
+ hint,
323
+ event: {
324
+ kind: 'step-output',
325
+ at: new Date().toISOString(),
326
+ ref: input.ref,
327
+ phase: input.phase,
328
+ step: input.step,
329
+ ok: input.ok,
330
+ detail: input.detail,
331
+ planPath: input.planPath,
332
+ subtaskRefs: input.subtaskRefs,
333
+ command: input.command,
334
+ passed: input.passed,
335
+ headSha: input.headSha,
336
+ prNumber: input.prNumber,
337
+ prUrl: input.prUrl,
338
+ gateTargetIds: input.gateTargetIds,
339
+ prMerged: input.prMerged,
340
+ },
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Belt-and-braces fact type gate. The tool layer (2.3) validates params with
346
+ * TypeBox before calling here; this re-check keeps the journal clean even if
347
+ * a caller skips that layer. Returns null when everything checks out.
348
+ */
349
+ function validateFactTypes(input: StepOutputInput): string | null {
350
+ const crossPhase = validateCrossPhaseFacts(input)
351
+ if (crossPhase !== null) {
352
+ return crossPhase
353
+ }
354
+ if (input.phase === 'plan') {
355
+ if (input.planPath !== undefined && typeof input.planPath !== 'string') {
356
+ return buildTypeMismatchReason('planPath', input.phase, 'a string path')
357
+ }
358
+ if (input.subtaskRefs !== undefined && !isStringArray(input.subtaskRefs)) {
359
+ return buildTypeMismatchReason(
360
+ 'subtaskRefs',
361
+ input.phase,
362
+ 'an array of ref strings',
363
+ )
364
+ }
365
+ }
366
+
367
+ if (input.phase === 'implement') {
368
+ if (input.command !== undefined && typeof input.command !== 'string') {
369
+ return buildTypeMismatchReason('command', input.phase, 'a command string')
370
+ }
371
+ if (input.passed !== undefined && typeof input.passed !== 'boolean') {
372
+ return buildTypeMismatchReason('passed', input.phase, 'a boolean')
373
+ }
374
+ }
375
+
376
+ if (input.phase === 'validate') {
377
+ if (input.prNumber !== undefined && !isInteger(input.prNumber)) {
378
+ return buildTypeMismatchReason('prNumber', input.phase, 'an integer')
379
+ }
380
+ if (input.prUrl !== undefined && typeof input.prUrl !== 'string') {
381
+ return buildTypeMismatchReason('prUrl', input.phase, 'a URL string')
382
+ }
383
+ if (
384
+ input.gateTargetIds !== undefined &&
385
+ !isStringArray(input.gateTargetIds)
386
+ ) {
387
+ return buildTypeMismatchReason(
388
+ 'gateTargetIds',
389
+ input.phase,
390
+ 'an array of gate-target id strings',
391
+ )
392
+ }
393
+ }
394
+
395
+ if (input.phase === 'feedback') {
396
+ if (input.prUrl !== undefined && typeof input.prUrl !== 'string') {
397
+ return buildTypeMismatchReason('prUrl', input.phase, 'a URL string')
398
+ }
399
+ if (input.prMerged !== undefined && typeof input.prMerged !== 'boolean') {
400
+ return buildTypeMismatchReason('prMerged', input.phase, 'a boolean')
401
+ }
402
+ }
403
+
404
+ return null
405
+ }
406
+
407
+ function isStringArray(value: unknown): boolean {
408
+ if (!Array.isArray(value)) {
409
+ return false
410
+ }
411
+ return value.every((item) => typeof item === 'string')
412
+ }
413
+
414
+ function isInteger(value: unknown): boolean {
415
+ return typeof value === 'number' && Number.isInteger(value)
416
+ }
package/flow/steps.ts ADDED
@@ -0,0 +1,73 @@
1
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — the registered step names (v2 vocabulary). Steps
2
+ // are the named boundaries INSIDE a phase. The registry CLOSES THE PROMETHEUS
3
+ // LABEL SURFACE ONLY: flow/state-metrics.ts drops any (phase, step) this map
4
+ // does not list before it reaches a `pi_flow_step` / `pi_flow_step_seconds`
5
+ // label (closed enum => bounded cardinality, ISC-A-1). The 'step-start'/
6
+ // 'step-stop' JOURNAL EVENTS and the Tempo step spans / Loki lines derived
7
+ // from them are NOT registry-closed — they keep the raw step name by design,
8
+ // so the cardinality bound lives only on the exported metric labels.
9
+ //
10
+ // `validate.spec-diff` and `validate.aven-notes` are documented names WITHOUT
11
+ // machine-emitted boundaries: no tool boundary exists for them (they are
12
+ // prose steps in validate/prompt.ts), so flow_submit evidence is all they get.
13
+ // Subtask 1.2 binds the prompt letters (D1/D2/D3/H1, the plan approval wait)
14
+ // to these names with AIDEV anchors and makes flow_submit warn (advisory,
15
+ // never reject) on an unregistered name. PMR-V31Z 1.2: H1 is retired from
16
+ // the PROMPTS — the human code_review gate is deleted from the personal
17
+ // validate prompt — but the validate.code-review registry name stays: the
18
+ // code_review tool still machine-emits step-start/step-stop{validate.code-review}
19
+ // until phase 7 cleans up the tool.
20
+ //
21
+ // AIDEV-NOTE: PMR-S7FQ — three MORE evidence-only names follow that same shape
22
+ // (registered vocabulary, NO machine-emitted step-start/step-stop pair, so
23
+ // flow_submit evidence is all they ever get): `plan.route-confirmed` (the
24
+ // oneshot-vs-plan route gate in plan/prompt.ts step 3), `validate.review-tool`
25
+ // (the fresh-context review tool's blockers_count verdict) and `validate.land`
26
+ // (the flow_land authorization + landing command). They exist because
27
+ // flow/step-output.ts:301-308 only hints when the phase's registry is NON-empty
28
+ // and lists no name for those boundaries, so an honest submission could never
29
+ // pick a registered one — noise on every submission is what trains an agent to
30
+ // ignore the advisory. Adding a name widens the closed enum by exactly one
31
+ // label value (ISC-A-1/A-2: the map stays finite and phase-prefixed, pinned in
32
+ // test/flow-submit-evidence-steps.test.ts) and admits nothing to the Prometheus
33
+ // surface in practice: scanStepWindows reads only step-start/step-stop, which no
34
+ // tool emits for an evidence-only name.
35
+ //
36
+ // PURE module: only a type-only import of `Phase`, so it stays runtime
37
+ // dependency-free and daemon-reachable (the cost-rows closure guard).
38
+ import type { Phase } from './orchestrate.ts'
39
+
40
+ /** phase -> registered step names (empty array = no named steps in a phase). */
41
+ export const STEP_REGISTRY: Readonly<Record<Phase, readonly string[]>> = {
42
+ plan: ['plan.spec-approval', 'plan.route-confirmed'],
43
+ // AIDEV-NOTE: PMR-S7FQ — these two arrays are EMPTY ON PURPOSE. Do NOT
44
+ // "fix" them by registering implement/feedback names: flow/step-output.ts
45
+ // :301-308 skips the advisory whenever the phase registry is empty, so
46
+ // free-form step labels in these phases are hint-free BY DESIGN (that is the
47
+ // documented contract test/flow-submit-registry.test.ts pins, and the reason
48
+ // the PMR-S7FR-era implement observations never warned). Registering even one
49
+ // name here flips that guard on and starts nagging every other free-form
50
+ // label — strictly MORE noise, which is the failure mode PMR-S7FQ exists to
51
+ // remove. Boundaries in these phases need no registry entry to journal.
52
+ implement: [],
53
+ validate: [
54
+ 'validate.code-review',
55
+ 'validate.deviation',
56
+ 'validate.spec-diff',
57
+ 'validate.aven-notes',
58
+ // PMR-S7FQ evidence-only names (no machine-emitted start/stop pair).
59
+ 'validate.review-tool',
60
+ 'validate.land',
61
+ ],
62
+ feedback: [],
63
+ }
64
+
65
+ /**
66
+ * Is this step name registered for this phase? Defensive against a drifted
67
+ * phase value (journals are parsed leniently): an unknown phase simply has
68
+ * no registered steps instead of throwing.
69
+ */
70
+ export function isRegisteredStep(phase: Phase, step: string): boolean {
71
+ if (!Object.hasOwn(STEP_REGISTRY, phase)) return false
72
+ return STEP_REGISTRY[phase].includes(step)
73
+ }