@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
@@ -0,0 +1,229 @@
1
+ // AIDEV-NOTE: Deviation gate (PMR-BAGD) — runs in the validate phase after a
2
+ // 0-blocker review. A fresh-context deviation reviewer compares the resolved
3
+ // spec against the diff; its artifact is parsed here. PURE only: no
4
+ // subagent spawn, no aven/Jira/git I/O — wiring lives in review/review.ts
5
+ // (subtask 2) and the handoff prompt in validate/prompt.ts (subtask 3).
6
+ //
7
+ // AIDEV-NOTE: deviations_count artifact contract (DEFINED HERE). The emitter
8
+ // (subtask 2's prompt) imports DEVIATION_VERDICT_HEADING and
9
+ // DEVIATION_CONTRACT_PROMPT so parser and emitter can never drift. Parsing is
10
+ // scoped to the section after the LAST deviation-verdict heading so contract
11
+ // text QUOTED elsewhere cannot false-positive. Parsing is STRICT and
12
+ // fail-closed: missing, duplicated, non-integer or negative counts are
13
+ // explicit errors — never a silent 0 (a silent 0 would skip the human gate).
14
+
15
+ export const DEVIATION_VERDICT_HEADING = '## Deviation Verdict'
16
+
17
+ // AIDEV-NOTE: Each deviation carries what / why (rationale always labelled
18
+ // inferred, with evidence) / file:line. The line format is the single owner
19
+ // of that shape:
20
+ // - deviation: <what> | why: <why> (inferred: <evidence>) | <file>:<line>
21
+ export const DEVIATION_CONTRACT_PROMPT =
22
+ '- deviation: <what> | why: <why> (inferred: <evidence>) | <file>:<line>'
23
+
24
+ export type DeviationArtifact =
25
+ | {
26
+ ok: true
27
+ deviationsCount: number
28
+ deviations: readonly {
29
+ what: string
30
+ why: string
31
+ evidence: string | undefined
32
+ file: string
33
+ line: number
34
+ }[]
35
+ /**
36
+ * AIDEV-NOTE (PMR-6YC7): set when the declared count could not be
37
+ * backed by the extracted verdict section but exactly that many
38
+ * well-formed deviation lines existed elsewhere in the artifact
39
+ * (a restated trailing heading or an in-section subheading had
40
+ * scoped them out). Recovery is still a STRICT exact-count match —
41
+ * never a partial or best-effort payload.
42
+ */
43
+ recovered?: true
44
+ }
45
+ | { ok: false; reason: string }
46
+
47
+ const COUNT_RE = /^deviations_count:\s*(\d+)\s*$/
48
+ const DEVIATION_RE =
49
+ /^- deviation:\s*(.+?)\s*\|\s*why:\s*(.+?)\s*\|\s*(.+?):(\d+)\s*$/
50
+ const EVIDENCE_RE = /\(inferred:\s*(.+?)\)\s*$/
51
+
52
+ type ScannedDeviation = Extract<
53
+ Extract<DeviationArtifact, { ok: true }>['deviations'][number],
54
+ unknown
55
+ >
56
+
57
+ interface SectionScan {
58
+ counts: number[]
59
+ deviations: ScannedDeviation[]
60
+ }
61
+
62
+ function scanSection(section: string): SectionScan {
63
+ const counts: number[] = []
64
+ const deviations: ScannedDeviation[] = []
65
+ for (const rawLine of section.split('\n')) {
66
+ const line = rawLine.trim()
67
+ const countMatch = COUNT_RE.exec(line)
68
+ if (countMatch !== null) {
69
+ counts.push(Number.parseInt(countMatch[1] as string, 10))
70
+ continue
71
+ }
72
+ const deviationMatch = DEVIATION_RE.exec(line)
73
+ if (deviationMatch !== null) {
74
+ const what = (deviationMatch[1] as string).trim()
75
+ const why = (deviationMatch[2] as string).trim()
76
+ const file = (deviationMatch[3] as string).trim()
77
+ const lineNo = Number.parseInt(deviationMatch[4] as string, 10)
78
+ const evidenceMatch = EVIDENCE_RE.exec(why)
79
+ let evidence: string | undefined
80
+ if (evidenceMatch !== null) {
81
+ evidence = (evidenceMatch[1] as string).trim()
82
+ }
83
+ deviations.push({ what, why, evidence, file, line: lineNo })
84
+ }
85
+ }
86
+ return { counts, deviations }
87
+ }
88
+
89
+ // AIDEV-NOTE: Scopes parsing to the deviation verdict section so a verdict
90
+ // that merely QUOTES the contract does not double-count. The section after
91
+ // the LAST "Deviation Verdict"-style heading ALWAYS wins (that is what the
92
+ // emitter writes canonically); only when no heading exists do we fall back to
93
+ // the LAST fenced block containing a count line, else the whole artifact. A
94
+ // quoted fenced example must NEVER override a real heading verdict — that
95
+ // would parse 0 and skip the human gate.
96
+ export function extractDeviationSection(artifact: string): string {
97
+ const headings = [
98
+ ...artifact.matchAll(/^[ \t]*#{1,6}[ \t]+deviation verdict\b[^\n]*$/gim),
99
+ ]
100
+ const lastHeading = headings[headings.length - 1]
101
+ if (lastHeading !== undefined) {
102
+ const start = (lastHeading.index ?? 0) + lastHeading[0].length
103
+ const rest = artifact.slice(start)
104
+ const nextHeading = /^[ \t]*#{1,6}[ \t]+\S/m.exec(rest)
105
+ if (nextHeading?.index !== undefined) {
106
+ return rest.slice(0, nextHeading.index)
107
+ }
108
+ return rest
109
+ }
110
+ const fences = [...artifact.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)]
111
+ for (let i = fences.length - 1; i >= 0; i--) {
112
+ const body = fences[i]?.[1]
113
+ if (body !== undefined && /^deviations_count:\s*\d+\s*$/m.test(body)) {
114
+ return body
115
+ }
116
+ }
117
+ return artifact
118
+ }
119
+
120
+ // AIDEV-NOTE (PMR-J129): strip fenced regions before the artifact-wide
121
+ // cross-check — a fenced EXAMPLE of the contract shape (an illustration of
122
+ // what a filled verdict looks like) is not a verdict payload. Without this,
123
+ // a reviewer that quotes a filled fenced example while genuinely declaring
124
+ // deviations_count: 0 trips the contradictory-artifact error, and a
125
+ // count-matching fenced example could back a recovery the real payload
126
+ // never carried. Same fence shape as extractDeviationSection.
127
+ function stripFences(text: string): string {
128
+ return text.replace(/^```[^\n]*\n[\s\S]*?^```/gm, '')
129
+ }
130
+
131
+ export function parseDeviationArtifact(artifact: string): DeviationArtifact {
132
+ const scoped = scanSection(extractDeviationSection(artifact))
133
+ const counts = scoped.counts
134
+ const deviations = scoped.deviations
135
+ // AIDEV-NOTE (PMR-6YC7): the verdict-section scoping above can exclude
136
+ // well-formed "- deviation:" lines that live OUTSIDE the extracted
137
+ // section (a restated trailing verdict heading wins the LAST-heading
138
+ // rule; a subheading between the count and the lines cuts the section
139
+ // early) — the PMR-C0YV 8ed3ad1 run failed "declares 3 but 0 parsed"
140
+ // with 3 well-formed lines plainly visible in the raw artifact. Scan the
141
+ // WHOLE artifact as a cross-check so scoping misses are recoverable and
142
+ // diagnostics can distinguish scoping exclusion from transport loss.
143
+ // PMR-F3VC: computed BEFORE the no-count early return so that diagnostic
144
+ // can carry the artifact-wide count too — a bare restated trailing
145
+ // heading can scope out the count line itself.
146
+ const full = scanSection(stripFences(artifact))
147
+ if (counts.length === 0) {
148
+ return {
149
+ ok: false,
150
+ reason: `deviation artifact has no "deviations_count: <N>" line (${full.deviations.length} well-formed "- deviation:" line(s) artifact-wide) — re-run the deviation reviewer and ensure the artifact ends with the count`,
151
+ }
152
+ }
153
+ if (counts.length > 1) {
154
+ return {
155
+ ok: false,
156
+ reason: `deviation artifact has multiple deviations_count lines (${counts.join(', ')}) — exactly one is required`,
157
+ }
158
+ }
159
+ const count = counts[0] as number
160
+ if (!Number.isInteger(count) || count < 0) {
161
+ return { ok: false, reason: `invalid deviations_count value: ${count}` }
162
+ }
163
+ // AIDEV-NOTE: a declared 0 must be corroborated artifact-wide — with the
164
+ // lines scoped out, a bare "deviations_count: 0" would otherwise skip the
165
+ // human gate while well-formed findings sit elsewhere in the artifact.
166
+ if (count === 0 && full.deviations.length > 0) {
167
+ return {
168
+ ok: false,
169
+ reason: `deviation artifact is contradictory: deviations_count declares 0 but ${full.deviations.length} well-formed "- deviation:" line(s) exist in the artifact — re-run the deviation reviewer and ensure the count matches the payload`,
170
+ }
171
+ }
172
+ // AIDEV-NOTE (PMR-N98C): a declared count the payload cannot back up is a
173
+ // TRUNCATED artifact (observed in production: "N deviation(s) from spec:"
174
+ // with the payload lines missing) — fail loudly here so the caller gets an
175
+ // error result to re-run, never an ok result it cannot present. Checked in
176
+ // BOTH directions: more lines than the count is equally malformed.
177
+ if (count !== deviations.length) {
178
+ // AIDEV-NOTE (PMR-6YC7): exact-count recovery — when the section scoped
179
+ // too narrowly but the artifact as a whole carries exactly the declared
180
+ // number of well-formed lines, accept the artifact-wide payload (flagged
181
+ // as recovered). A partial or over-long artifact-wide payload still
182
+ // fails: recovery never loosens the strict count contract.
183
+ if (full.deviations.length === count) {
184
+ return {
185
+ ok: true,
186
+ deviationsCount: count,
187
+ deviations: full.deviations,
188
+ recovered: true,
189
+ }
190
+ }
191
+ return {
192
+ ok: false,
193
+ reason: `deviation artifact is truncated or malformed: deviations_count declares ${count} but ${deviations.length} "- deviation: ..." line(s) parsed (${full.deviations.length} well-formed line(s) artifact-wide) — re-run the deviation reviewer and ensure exactly one deviation line per deviation`,
194
+ }
195
+ }
196
+ return { ok: true, deviationsCount: count, deviations }
197
+ }
198
+
199
+ export type DeviationDecision =
200
+ | { route: 'validate-complete' }
201
+ | { route: 'human-decision'; deviationsNote: string }
202
+
203
+ // AIDEV-NOTE: no production caller — the deviation_review tool renders
204
+ // the routing text inline (deviationResultToToolResult); this function stays
205
+ // as the documented route contract and is covered by deviation-gate tests.
206
+ // AIDEV-NOTE: Pure gate decision. 0 deviations -> proceed to
207
+ // flow_phase_complete(validate). >0 -> a HUMAN decides: accept the deviations
208
+ // or send the work back to /implement. This function only builds the note;
209
+ // the accept/implement choice is made by the caller (subtask 3) with the user.
210
+ export function decideDeviationRoute(
211
+ deviationsCount: number,
212
+ deviations: readonly string[] = [],
213
+ ): DeviationDecision {
214
+ if (deviationsCount === 0) {
215
+ return { route: 'validate-complete' }
216
+ }
217
+ const listed = deviations.filter((d) => d.length > 0)
218
+ let deviationsNote: string
219
+ if (listed.length > 0) {
220
+ deviationsNote = `${deviationsCount} deviation(s) from spec:\n${listed
221
+ .map((d) => `- ${d}`)
222
+ .join(
223
+ '\n',
224
+ )}\nHuman decision required: accept deviations, or return to /implement`
225
+ } else {
226
+ deviationsNote = `${deviationsCount} deviation(s) from spec — see the deviation artifact for details. Human decision required: accept deviations, or return to /implement`
227
+ }
228
+ return { route: 'human-decision', deviationsNote }
229
+ }
@@ -0,0 +1,371 @@
1
+ // AIDEV-NOTE: Gate integrity (PMR-6EEW, observability plan Phase 6 / M7) —
2
+ // pin the exact bytes every gate judges, then verify the verifier with
3
+ // string compares. A gate (review / deviation / code-review) that silently
4
+ // reviews the WRONG diff emits a green promise-shaped object, which is worse
5
+ // than a failing gate: nothing downstream can tell. The fix is not better
6
+ // prompts — it is making the target of every gate a pinned, hash-verified
7
+ // artifact. PURE only: no git, no journal, no spawn I/O. Wiring lives at the
8
+ // tool boundary (tools/deviation.ts and later the review gates); journal
9
+ // events live in run-state.ts.
10
+
11
+ import { createHash } from 'node:crypto'
12
+ import type { Exec } from '../shared/diff-base.ts'
13
+ import {
14
+ isSubtaskRef,
15
+ parseSubtaskLog,
16
+ type SubtaskAttribution,
17
+ subtaskAttribution,
18
+ } from './subtask-range.ts'
19
+
20
+ export type GateKind = 'review' | 'deviation' | 'code-review' | 'spec-review'
21
+
22
+ /** The pinned target of one gate run: which bytes it was spawned to judge. */
23
+ export interface GateTarget {
24
+ gate: GateKind
25
+ ref: string
26
+ baseSha: string
27
+ headSha: string
28
+ /** sha256 of the exact `git diff base..head` bytes handed to the reviewer. */
29
+ diffSha256: string
30
+ /**
31
+ * AIDEV-NOTE: PMR-6EEW per-subtask ranges — when the gate judges ONE
32
+ * subtask, the exact commit set derived from `Subtask:` trailers. The
33
+ * reviewer must additionally echo `reviewed_commits: <sha>,...` and the
34
+ * harness compares it element by element. Absent = whole-range gate.
35
+ */
36
+ subtask?: { ref: string; commits: string[] }
37
+ }
38
+
39
+ const SHA_RE = /^[0-9a-f]{40}$/
40
+
41
+ export function sha256Hex(text: string): string {
42
+ return createHash('sha256').update(text, 'utf8').digest('hex')
43
+ }
44
+
45
+ // AIDEV-NOTE: full 40-hex SHAs only. Short SHAs would make the echo compare
46
+ // ambiguous (two distinct commits sharing a prefix must never compare equal).
47
+ export function isFullSha(value: string): boolean {
48
+ return SHA_RE.test(value)
49
+ }
50
+
51
+ /**
52
+ * Build the pinned target for a gate spawn. Rejects malformed SHAs rather
53
+ * than pinning garbage — a target with a bad SHA can never be echoed back.
54
+ */
55
+ export function buildGateTarget(input: {
56
+ gate: GateKind
57
+ ref: string
58
+ baseSha: string
59
+ headSha: string
60
+ diff: string
61
+ }): GateTarget | { ok: false; reason: string } {
62
+ if (!isFullSha(input.baseSha)) {
63
+ return {
64
+ ok: false,
65
+ reason: `baseSha is not a full 40-hex SHA: '${input.baseSha}'`,
66
+ }
67
+ }
68
+ if (!isFullSha(input.headSha)) {
69
+ return {
70
+ ok: false,
71
+ reason: `headSha is not a full 40-hex SHA: '${input.headSha}'`,
72
+ }
73
+ }
74
+ if (input.baseSha === input.headSha) {
75
+ return { ok: false, reason: 'empty range: baseSha == headSha' }
76
+ }
77
+ if (input.ref.length === 0) {
78
+ return { ok: false, reason: 'ref is empty' }
79
+ }
80
+ return {
81
+ gate: input.gate,
82
+ ref: input.ref,
83
+ baseSha: input.baseSha,
84
+ headSha: input.headSha,
85
+ diffSha256: sha256Hex(input.diff),
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Deterministic id for a gate target: first 12 hex of the sha256 over the
91
+ * canonical target parts. Deterministic on purpose — replaying the same
92
+ * journal produces the same ids, so a decision can always cite its target.
93
+ */
94
+ export function gateTargetId(target: GateTarget): string {
95
+ const subtaskPart =
96
+ target.subtask !== undefined
97
+ ? `|${target.subtask.ref}|${target.subtask.commits.join(',')}`
98
+ : ''
99
+ return sha256Hex(
100
+ `${target.ref}|${target.gate}|${target.baseSha}|${target.headSha}|${target.diffSha256}${subtaskPart}`,
101
+ ).slice(0, 12)
102
+ }
103
+
104
+ // AIDEV-NOTE: PMR-6EEW per-subtask pins — same pin discipline as
105
+ // buildGateTarget, plus the subtask commit set. Commits must be full SHAs
106
+ // and non-empty; the subtask ref must be aven-shaped (validated here so a
107
+ // malformed ref can never reach a prompt).
108
+ export function buildSubtaskGateTarget(input: {
109
+ gate: GateKind
110
+ ref: string
111
+ baseSha: string
112
+ headSha: string
113
+ diff: string
114
+ subtaskRef: string
115
+ commits: string[]
116
+ }): GateTarget | { ok: false; reason: string } {
117
+ const base = buildGateTarget(input)
118
+ if (!('gate' in base)) return base
119
+ if (!isSubtaskRef(input.subtaskRef)) {
120
+ return {
121
+ ok: false,
122
+ reason: `subtaskRef is not an aven-shaped ref: '${input.subtaskRef}'`,
123
+ }
124
+ }
125
+ if (input.commits.length === 0) {
126
+ return { ok: false, reason: 'subtask commit list is empty' }
127
+ }
128
+ for (const sha of input.commits) {
129
+ if (!isFullSha(sha)) {
130
+ return {
131
+ ok: false,
132
+ reason: `subtask commit is not a full 40-hex SHA: '${sha}'`,
133
+ }
134
+ }
135
+ }
136
+ return {
137
+ ...base,
138
+ subtask: { ref: input.subtaskRef, commits: [...input.commits] },
139
+ }
140
+ }
141
+
142
+ // AIDEV-NOTE: Echo contract. The gate prompt tells the reviewer to emit ONE
143
+ // line `reviewed_range: <baseSha>..<headSha>` in its verdict section, copied
144
+ // from the pinned range in its prompt. The harness compares that line against
145
+ // the pinned target character by character BEFORE any finding is read.
146
+ export const ECHO_LINE_PREFIX = 'reviewed_range:'
147
+
148
+ export function reviewedRangeLine(target: GateTarget): string {
149
+ return `${ECHO_LINE_PREFIX} ${target.baseSha}..${target.headSha}`
150
+ }
151
+
152
+ const ECHO_RE = /^reviewed_range:\s*([0-9a-f]{40})\.\.([0-9a-f]{40})$/
153
+
154
+ export interface ReviewedRange {
155
+ baseSha: string
156
+ headSha: string
157
+ }
158
+
159
+ /**
160
+ * Extract the reviewed_range echo from a gate artifact. LAST matching line
161
+ * wins (same preference as the verdict parsers: canonical emitters write it
162
+ * once at the end). Null when absent.
163
+ */
164
+ export function extractReviewedRange(artifact: string): ReviewedRange | null {
165
+ let found: ReviewedRange | null = null
166
+ for (const rawLine of artifact.split('\n')) {
167
+ const line = rawLine.trim()
168
+ const match = ECHO_RE.exec(line)
169
+ if (match !== null) {
170
+ found = {
171
+ baseSha: match[1] as string,
172
+ headSha: match[2] as string,
173
+ }
174
+ }
175
+ }
176
+ return found
177
+ }
178
+
179
+ // AIDEV-NOTE: PMR-6EEW — second echo line for subtask-scoped gates. The
180
+ // reviewer echoes `reviewed_commits: <sha>,<sha>,...` (its pinned commit
181
+ // list) and the harness compares element by element, same discipline as
182
+ // reviewed_range. LAST matching line wins, like extractReviewedRange.
183
+ export const SUBTASK_ECHO_PREFIX = 'reviewed_commits:'
184
+
185
+ export function reviewedCommitsLine(target: GateTarget): string {
186
+ if (target.subtask === undefined) return ''
187
+ return `${SUBTASK_ECHO_PREFIX} ${target.subtask.commits.join(',')}`
188
+ }
189
+
190
+ const COMMITS_ECHO_RE = /^reviewed_commits:\s*([0-9a-f]{40}(?:,[0-9a-f]{40})*)$/
191
+
192
+ export function extractReviewedCommits(artifact: string): string[] | null {
193
+ let found: string[] | null = null
194
+ for (const rawLine of artifact.split('\n')) {
195
+ const match = COMMITS_ECHO_RE.exec(rawLine.trim())
196
+ if (match !== null) {
197
+ found = (match[1] ?? '').split(',')
198
+ }
199
+ }
200
+ return found
201
+ }
202
+
203
+ // 'fail' covers harness-side failures (e.g. HEAD cannot be re-resolved) —
204
+ // the gate could not be verified at all, which is never a pass.
205
+ export type GateStatus =
206
+ | 'pass'
207
+ | 'echo-missing'
208
+ | 'target-mismatch'
209
+ | 'stale'
210
+ | 'fail'
211
+
212
+ export type GateVerification =
213
+ | { ok: true; status: 'pass' }
214
+ | { ok: false; status: GateStatus; reason: string }
215
+
216
+ /**
217
+ * Verify a gate result against its pinned target, in the order the plan
218
+ * fixes: echo FIRST (a reviewer that looked at the wrong work can never
219
+ * pass, no matter how good its review reads), staleness SECOND (a verdict
220
+ * applies only to the exact bytes it was pinned to).
221
+ */
222
+ export function verifyGateResult(input: {
223
+ target: GateTarget
224
+ artifact: string
225
+ /** HEAD re-resolved AFTER the gate returned. */
226
+ currentHeadSha: string
227
+ }): GateVerification {
228
+ const echo = extractReviewedRange(input.artifact)
229
+ if (echo === null) {
230
+ return {
231
+ ok: false,
232
+ status: 'echo-missing',
233
+ reason:
234
+ 'gate artifact has no "reviewed_range: <base>..<head>" line — the reviewer did not echo its pinned target; re-run the gate',
235
+ }
236
+ }
237
+ if (
238
+ echo.baseSha !== input.target.baseSha ||
239
+ echo.headSha !== input.target.headSha
240
+ ) {
241
+ return {
242
+ ok: false,
243
+ status: 'target-mismatch',
244
+ reason: `gate reviewed the wrong range: echoed ${echo.baseSha.slice(0, 9)}..${echo.headSha.slice(0, 9)} but was pinned to ${input.target.baseSha.slice(0, 9)}..${input.target.headSha.slice(0, 9)}`,
245
+ }
246
+ }
247
+ // AIDEV-NOTE: PMR-6EEW — subtask-scoped gates additionally echo the exact
248
+ // commit list; element-by-element compare, order included (the order IS
249
+ // the attribution — a reviewer that reordered or dropped commits looked
250
+ // at different work).
251
+ if (input.target.subtask !== undefined) {
252
+ const echoedCommits = extractReviewedCommits(input.artifact)
253
+ const pinned = input.target.subtask.commits
254
+ if (echoedCommits === null) {
255
+ return {
256
+ ok: false,
257
+ status: 'echo-missing',
258
+ reason: `gate artifact has no "reviewed_commits: <sha>,..." line — the subtask-scoped reviewer did not echo its pinned commit set; re-run the gate`,
259
+ }
260
+ }
261
+ if (
262
+ echoedCommits.length !== pinned.length ||
263
+ echoedCommits.some((sha, i) => sha !== pinned[i])
264
+ ) {
265
+ return {
266
+ ok: false,
267
+ status: 'target-mismatch',
268
+ reason: `gate reviewed the wrong commits for ${input.target.subtask?.ref}: echoed ${echoedCommits.length} commit(s) but was pinned to ${pinned.length} — the commit sets differ`,
269
+ }
270
+ }
271
+ }
272
+ if (input.currentHeadSha !== input.target.headSha) {
273
+ return {
274
+ ok: false,
275
+ status: 'stale',
276
+ reason: `gate verdict is stale: HEAD moved to ${input.currentHeadSha.slice(0, 9)} while the gate judged ${input.target.headSha.slice(0, 9)} — re-run the gate on the new range`,
277
+ }
278
+ }
279
+ return { ok: true, status: 'pass' }
280
+ }
281
+
282
+ export interface GateDecisionRecord {
283
+ gate: GateKind
284
+ targetId: string
285
+ status: GateStatus | 'fail'
286
+ }
287
+
288
+ /**
289
+ * Exec-backed delivery check shared by every wired gate: re-resolve HEAD for
290
+ * the staleness recheck, then verify echo + staleness against the pin. Exec
291
+ * is injected (type-only import) so tests never touch a real repo.
292
+ */
293
+ export async function verifyGateWithExec(
294
+ exec: Exec,
295
+ cwd: string,
296
+ target: GateTarget,
297
+ artifact: string,
298
+ ): Promise<GateVerification> {
299
+ const head = await exec('git', ['rev-parse', 'HEAD'], { cwd })
300
+ if (head.code !== 0 || head.stdout.trim() === '') {
301
+ return {
302
+ ok: false,
303
+ status: 'fail',
304
+ reason: `cannot re-resolve HEAD for staleness check in ${cwd}: ${head.stderr ?? ''}`,
305
+ }
306
+ }
307
+ return verifyGateResult({
308
+ target,
309
+ artifact,
310
+ currentHeadSha: head.stdout.trim(),
311
+ })
312
+ }
313
+
314
+ /**
315
+ * AIDEV-NOTE: PMR-6EEW per-subtask ranges — derive the subtask → commits
316
+ * attribution of a pinned range from `Subtask:` trailers in history. Exec-
317
+ * backed twin of subtask-range.ts (pure). Fail-closed: git errors and
318
+ * malformed log output are an error result, never an empty "no subtasks"
319
+ * answer — an attribution of "nothing" would let a subtask gate skip its
320
+ * commit pin silently.
321
+ */
322
+ export async function deriveSubtaskAttribution(
323
+ exec: Exec,
324
+ cwd: string,
325
+ baseSha: string,
326
+ headSha: string,
327
+ ): Promise<
328
+ { ok: true; attribution: SubtaskAttribution } | { ok: false; reason: string }
329
+ > {
330
+ const log = await exec(
331
+ 'git',
332
+ ['log', '--format=%H%x1f%B%x1e', `${baseSha}..${headSha}`],
333
+ { cwd },
334
+ )
335
+ if (log.code !== 0) {
336
+ return {
337
+ ok: false,
338
+ reason: `git log failed in ${cwd}: ${log.stderr ?? ''}`,
339
+ }
340
+ }
341
+ const parsed = parseSubtaskLog(log.stdout)
342
+ if (!parsed.ok) {
343
+ return { ok: false, reason: `cannot parse subtask log: ${parsed.reason}` }
344
+ }
345
+ return { ok: true, attribution: subtaskAttribution(parsed.commits) }
346
+ }
347
+
348
+ /**
349
+ * Orchestrator discipline (plan item 5): every gate decision must cite the
350
+ * gate_target id it applied. A decision citing an unknown target id is
351
+ * invalid state, surfaced like a coverage flag — never silently accepted.
352
+ */
353
+ export function validateDecisionCitation(
354
+ decision: GateDecisionRecord,
355
+ knownTargets: readonly GateTarget[],
356
+ ): { ok: true; target: GateTarget } | { ok: false; reason: string } {
357
+ const cited = knownTargets.find((t) => gateTargetId(t) === decision.targetId)
358
+ if (cited === undefined) {
359
+ return {
360
+ ok: false,
361
+ reason: `gate decision cites unknown gate_target id '${decision.targetId}' (gate '${decision.gate}') — the decision is invalid state`,
362
+ }
363
+ }
364
+ if (cited.gate !== decision.gate) {
365
+ return {
366
+ ok: false,
367
+ reason: `gate decision cites target of gate '${cited.gate}' but claims gate '${decision.gate}'`,
368
+ }
369
+ }
370
+ return { ok: true, target: cited }
371
+ }
@@ -0,0 +1,79 @@
1
+ // AIDEV-NOTE: Work-mode validation gate — a pure, ordered state machine over
2
+ // the six mandatory steps (minikube -> connectivity -> queues -> deploy ->
3
+ // manual-tests -> jira-comment). Success advances; failure records
4
+ // {step, output} for the aven note and FREEZES the gate: no step can advance
5
+ // past a recorded failure (the agent must re-run /validate after fixing).
6
+ // The phase counts as validated only when every step has completed — the
7
+ // Jira evidence comment is the LAST step, so validation can never pass
8
+ // without it.
9
+
10
+ export const GATE_STEPS = [
11
+ 'minikube',
12
+ 'connectivity',
13
+ 'queues',
14
+ 'deploy',
15
+ 'manual-tests',
16
+ 'jira-comment',
17
+ ] as const
18
+
19
+ export type GateStep = (typeof GATE_STEPS)[number]
20
+
21
+ // AIDEV-NOTE: Bounded-poll config for the minikube start loop. Tests pass
22
+ // intervalMs: 0 — the agent-side poller never sleeps in tests.
23
+ export interface PollConfig {
24
+ maxAttempts: number
25
+ intervalMs: number
26
+ }
27
+
28
+ export interface StepFailure {
29
+ step: GateStep
30
+ output: string
31
+ }
32
+
33
+ export interface GateState {
34
+ step: GateStep
35
+ completed: readonly GateStep[]
36
+ failed: StepFailure | null
37
+ }
38
+
39
+ export const DEFAULT_POLL_CONFIG: PollConfig = {
40
+ maxAttempts: 12,
41
+ intervalMs: 10_000,
42
+ }
43
+
44
+ export function initialGateState(): GateState {
45
+ return { step: 'minikube', completed: [], failed: null }
46
+ }
47
+
48
+ export function gatePassed(state: GateState): boolean {
49
+ return state.completed.length === GATE_STEPS.length && state.failed === null
50
+ }
51
+
52
+ // AIDEV-NOTE: Refusal is the safety property: once failed !== null the state
53
+ // is returned unchanged — no success can silently clear a failure.
54
+ export function stepSucceeds(state: GateState): GateState {
55
+ if (state.failed !== null) return state
56
+ const idx = GATE_STEPS.indexOf(state.step)
57
+ const completed = [...state.completed, state.step]
58
+ const next = GATE_STEPS[idx + 1]
59
+ if (next === undefined) {
60
+ return { step: state.step, completed, failed: null }
61
+ }
62
+ return { step: next, completed, failed: null }
63
+ }
64
+
65
+ export function stepFails(state: GateState, output: string): GateState {
66
+ if (state.failed !== null) return state
67
+ return {
68
+ step: state.step,
69
+ completed: state.completed,
70
+ failed: { step: state.step, output },
71
+ }
72
+ }
73
+
74
+ // AIDEV-NOTE: Pure bounded-poll predicate — attempt is 1-based "attempts made
75
+ // so far". The agent loop is: poll status -> if running, done; else if
76
+ // pollExhausted, fail the gate (never hang); else wait intervalMs and retry.
77
+ export function pollExhausted(attempts: number, config: PollConfig): boolean {
78
+ return attempts >= config.maxAttempts
79
+ }