@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,20 @@
1
+ import { join } from 'node:path'
2
+
3
+ // AIDEV-NOTE: The devctl repository name is fixed (machine-specific layout is
4
+ // handled by workRoots in pi-flow config, which must contain the parent dir of
5
+ // this repo, e.g. /home/dev/Code/salaryhero). If SalaryHero ever renames the
6
+ // repo, change it here.
7
+ export const DEVCTL_REPO_NAME = 'sh-devctl'
8
+
9
+ // AIDEV-NOTE: Pure path resolution — <workRoot>/<sh-devctl>/scripts for the
10
+ // first configured workRoot. Returns null when no workRoots are configured;
11
+ // the caller (command handler / prompt) surfaces that as a config error.
12
+ // The resolution rule is documented in config.schema.json's workRoots
13
+ // description — keep the two in sync.
14
+ export function resolveDevctlScriptsDir(
15
+ workRoots: readonly string[],
16
+ ): string | null {
17
+ const first = workRoots[0]
18
+ if (first === undefined) return null
19
+ return join(first, DEVCTL_REPO_NAME, 'scripts')
20
+ }
@@ -0,0 +1,104 @@
1
+ // AIDEV-NOTE: Personal-mode /validate core (PMR-8449). No cluster here — the
2
+ // human IS the test environment. composeHumanTest turns the plan/research
3
+ // artifact sections into concrete runnable steps; empty/whitespace-only
4
+ // sections yield an explicit insufficient-context result instead of generic
5
+ // filler (that is the "not generic advice" acceptance criterion, tested in
6
+ // test/validate.test.ts). routePersonalOutcome is the pure outcome router:
7
+ // pass -> complete with a dated aven note; fail -> back to /implement with
8
+ // the human's failure description as the note and the retry budget reset.
9
+ // Both are side-effect-free; the command handler and the handoff prompt own
10
+ // all I/O (aven notes, ask_user_question).
11
+
12
+ import { parseMetadataBlock } from '../spec-review/aven-spec.ts'
13
+
14
+ export interface HumanTestInput {
15
+ whatChanged: string
16
+ planValidationNotes: string
17
+ researchFindings: string
18
+ }
19
+
20
+ export type ComposedTest =
21
+ | { ok: true; steps: string[]; expectedOutcome: string }
22
+ | { ok: false; reason: string }
23
+
24
+ function hasContent(value: string): boolean {
25
+ return value.trim().length > 0
26
+ }
27
+
28
+ // AIDEV-NOTE: research-path (NOT brainstorm-path) is kept for backwards
29
+ // compat — brainstorm tickets already carry it (see brainstorm/prompt.ts).
30
+ // Returns null when the metadata block is absent: most tickets are never
31
+ // brainstormed, so validate must tolerate its absence (never fail on it).
32
+ export function readResearchPath(avenShowFullStdout: string): string | null {
33
+ const p = parseMetadataBlock(avenShowFullStdout, 'research-path')
34
+ if (p === null) return null
35
+ if (p.trim().length === 0) return null
36
+ return p.trim()
37
+ }
38
+
39
+ export function composeHumanTest(input: HumanTestInput): ComposedTest {
40
+ const sections: Array<[string, string]> = [
41
+ ['what changed', input.whatChanged],
42
+ ['plan validation notes', input.planValidationNotes],
43
+ ['research findings', input.researchFindings],
44
+ ]
45
+ const present = sections.filter(([, v]) => hasContent(v))
46
+ if (present.length === 0) {
47
+ return {
48
+ ok: false,
49
+ reason:
50
+ 'insufficient context: none of whatChanged / planValidationNotes / researchFindings are present — read the ticket artifacts before composing test instructions',
51
+ }
52
+ }
53
+ const steps: string[] = []
54
+ steps.push(`Context — ${present[0]?.[0]}: ${present[0]?.[1].trim()}`)
55
+ for (const [name, value] of present.slice(1)) {
56
+ steps.push(`${name}: ${value.trim()}`)
57
+ }
58
+ let expectedOutcome: string
59
+ if (hasContent(input.planValidationNotes)) {
60
+ expectedOutcome = input.planValidationNotes.trim()
61
+ } else if (hasContent(input.researchFindings)) {
62
+ expectedOutcome = input.researchFindings.trim()
63
+ } else {
64
+ expectedOutcome = input.whatChanged.trim()
65
+ }
66
+ return { ok: true, steps, expectedOutcome }
67
+ }
68
+
69
+ // AIDEV-NOTE: Pure outcome router for the human pass/fail answer. The date is
70
+ // injected (not new Date()) so the router stays deterministic and testable.
71
+ export type PersonalOutcome =
72
+ | { kind: 'pass' }
73
+ | { kind: 'fail'; description: string }
74
+
75
+ export type PersonalRouting =
76
+ | { action: 'complete'; avenNote: string }
77
+ | {
78
+ action: 'reimplement'
79
+ avenNote: string
80
+ route: '/implement'
81
+ retryBudgetReset: boolean
82
+ }
83
+ | { action: 'invalid'; reason: string }
84
+
85
+ export function routePersonalOutcome(
86
+ outcome: PersonalOutcome,
87
+ date: string,
88
+ ): PersonalRouting {
89
+ if (outcome.kind === 'pass') {
90
+ return { action: 'complete', avenNote: `validated by human, ${date}` }
91
+ }
92
+ if (!hasContent(outcome.description)) {
93
+ return {
94
+ action: 'invalid',
95
+ reason: 'fail outcome requires the human’s failure description',
96
+ }
97
+ }
98
+ return {
99
+ action: 'reimplement',
100
+ avenNote: outcome.description.trim(),
101
+ route: '/implement',
102
+ retryBudgetReset: true,
103
+ }
104
+ }
@@ -0,0 +1,525 @@
1
+ // AIDEV-NOTE: Work-mode handoff prompt for /validate, sent via
2
+ // sendUserMessage (same pattern as implement/prompt.ts). Runs the gate steps
3
+ // in validate/gate.ts order via bash, bounded minikube poll, deploy via the
4
+ // user's devctl skill BY NAME, manual-test results collected via
5
+ // ask_user_question, evidence comment posted via acli. Validation passes ONLY
6
+ // after the Jira comment lands. Personal mode (PMR-8449): the human runs the
7
+ // test themselves — the agent locates the artifacts, composes instructions via
8
+ // validate/personal.ts, asks pass/fail via ask_user_question, then records and
9
+ // routes per routePersonalOutcome. Personal mode is never treated as work mode.
10
+
11
+ import { MODE_PROFILE } from '../mode-profile.ts'
12
+ import { DEFAULT_POLL_CONFIG } from './gate.ts'
13
+ import { REVIEW_CONTRACT_PROMPT } from './review-gate.ts'
14
+
15
+ // AIDEV-NOTE: PMR-PKSS — delta re-review on fix rounds. Detection is
16
+ // prompt-level (no run-state): a prior blockers aven note carrying
17
+ // "reviewed-at: <sha>" marks a fix round. Fail-closed toward MORE review: a
18
+ // missing sha or empty diff falls back to a full /review. The verdict
19
+ // contract (blockers_count) and every later gate are unchanged, so
20
+ // review-passed still only comes from a fresh 0 against the current tree.
21
+ function buildDeltaReviewStep(ref: string): string {
22
+ return `7a. Fix round? Check the aven notes on ${ref} (read via "aven context ${ref} --full") for a prior review-blockers
23
+ note carrying "reviewed-at: <sha>" (use the MOST RECENT one). If none, the step 7 full review stands.
24
+ If one exists, run the review as a DELTA instead: call the review tool with custom
25
+ instructions containing (i) the recorded blockers and (ii) the output of
26
+ "git diff <sha>..HEAD". The reviewer must verify each recorded blocker is
27
+ resolved (an unresolved one counts as a blocker) and scan the fix diff for
28
+ new blockers, then emit the same blockers_count verdict as above. If the
29
+ sha is missing or unresolvable, or the diff is empty, run the full review.`
30
+ }
31
+
32
+ // AIDEV-NOTE: PMR-TPN7 — one pinned diff base for the review AND deviation
33
+ // gates. pi-review resolves its base from <base>@{upstream}; comparing that to
34
+ // `git diff main...HEAD` made unpushed commits look like a reviewer mix-up
35
+ // (PMR-KKDC). The agent records ONE sha here and reuses it in 7, D2 and D3.
36
+ // AIDEV-NOTE: PMR-S87F (rewritten by PMR-5NZB; the PMR-7N3D merge-base policy
37
+ // is replaced history) — the resolution rule is mode-keyed
38
+ // (MODE_PROFILE[mode].baseResolution). Work mode pushes the branch, so
39
+ // <base>@{upstream} tracks the real base. Personal mode NEVER pushes, so
40
+ // upstream lags local main by every previous personal merge and a moving
41
+ // merge-base sweeps unrelated tickets into the review (PMR-MH1Y needed human
42
+ // arbitration toward the recorded flow base). PMR-5NZB: personal BASE_SHA is
43
+ // now the RECORDED creation-time SHA (`branch.<branch>.flowbasesha`,
44
+ // shared/flow-base.ts) — the same value the deviation gate resolves via
45
+ // resolveStableRange (shared/stable-range.ts), so the two gates agree by
46
+ // construction. The integrity cross-check is
47
+ // merge-base(HEAD, <flowbase branch>) === flowbasesha: it holds while the
48
+ // branch is unrebased however far main advances; a difference means an early
49
+ // rebase or base-merge — STOP and ask the human (never adopt the merge-base,
50
+ // never include upstream commits). Personal mode still NEVER resolves against
51
+ // the base's upstream ref.
52
+ function buildBasePinStep(mode: 'work' | 'personal'): string {
53
+ const tail = `Record the SHA as BASE_SHA, then run \`git log BASE_SHA..HEAD --oneline\`
54
+ and \`git diff --stat BASE_SHA..HEAD\`. Use this BASE_SHA for the review
55
+ (7). The deviation gate resolves its own range (base recorded at worktree
56
+ create) and reports the base SHA: if it differs from BASE_SHA, or the
57
+ range the reviewer describes differs from the recorded one, ASK the human
58
+ — never call it a reviewer or tool error. If <base> cannot be resolved
59
+ unambiguously, STOP and ask the human.`
60
+ if (MODE_PROFILE[mode].baseResolution === 'recorded-sha-integrity') {
61
+ return `6a. Pin the diff base ONCE, before the review gate: BASE_SHA is the
62
+ creation-time flow base SHA recorded at worktree create — read it with
63
+ \`git config branch.$(git branch --show-current).flowbasesha\`. Integrity
64
+ cross-check: \`git merge-base HEAD $(git config branch.$(git branch --show-current).flowbase)\`
65
+ must EQUAL BASE_SHA — it does while the branch is unrebased, however far
66
+ main advances. If it differs, the branch was rebased or the base was merged
67
+ into it mid-flow: STOP and ask the human — never treat the merge-base as
68
+ the new base, never review upstream commits as flow work. If flowbasesha is
69
+ missing or unresolvable, STOP and ask the human. NEVER resolve against the
70
+ base's upstream ref: personal mode never pushes, so the upstream lags local
71
+ main and would sweep unrelated commits into the review.
72
+ ${tail}`
73
+ }
74
+ return `6a. Pin the diff base ONCE, before the review gate: resolve <base> (the
75
+ flow's base branch) and run
76
+ \`git merge-base HEAD "$(git rev-parse --abbrev-ref <base>@{upstream})"\`,
77
+ falling back to \`git merge-base HEAD <base>\` when there is no upstream.
78
+ ${tail}`
79
+ }
80
+
81
+ // AIDEV-NOTE: Review gate section (PMR-JTAM) — appended to BOTH validate
82
+ // prompts. Runs after the env/human gate passes: the review tool (fresh-context
83
+ // reviewer, in-package since PMR-W8SG) -> parse blockers_count artifact ->
84
+ // route. The contract wording lives in review-gate.ts; review/verdict.ts
85
+ // emits the verdict section natively from those shared constants
86
+ // (PMR-5PCB), and this prompt restates it for artifacts written by hand.
87
+ // AIDEV-NOTE: PMR-C6AK (rewritten by PMR-V31Z 1.2) — the personal branch
88
+ // USED to carry a step-9 human code-review gate (code_review/tuicr ->
89
+ // flow_land merge-main -> local ff-only merge). That gate is DELETED: the
90
+ // personal validate prompt now ends at the deviation gate, whose D5 pass
91
+ // routes call flow_phase_complete(validate) and let the loop advance to the
92
+ // feedback phase — feedback owns the PR delivery. Ordering:
93
+ // human test gate -> review blockers -> deviation gate -> flow_phase_complete.
94
+ // AIDEV-NOTE: PMR-S7FQ — two EVIDENCE-ONLY registry names cover the validate
95
+ // boundaries the prompts already ask an agent to journal but that had no name,
96
+ // so every honest flow_submit there drew the registry advisory (flow_submit
97
+ // hints only when the phase registry is non-empty: flow/step-output.ts:301-308):
98
+ // validate.review-tool = the review tool's blockers_count verdict (step 7/8
99
+ // below, BOTH modes and the yolo copy) — distinct from
100
+ // validate.code-review/H1 (RETIRED by PMR-V31Z: the human code_review
101
+ // gate is gone; the ad-hoc code_review tool still emits its own ask
102
+ // step events under that registry name — PMR-V31Z 7.2);
103
+ // validate.land = the flow_land authorization plus the landing command
104
+ // (work step 9 push/PR; personal mode journals its PR delivery in the
105
+ // feedback phase via flow_submit phase=feedback prUrl instead —
106
+ // PMR-V31Z — so it never emits validate.land).
107
+ // Like validate.spec-diff / validate.aven-notes they have NO machine-emitted
108
+ // step-start/step-stop pair: the flow_submit step-output row is the whole
109
+ // record, so they add no boundary and no Prometheus step window. Rename in
110
+ // flow/steps.ts must be reflected here and in docs/pi-flow-observability.md §5.
111
+ // `gate-evidence` (the work-mode validate gate) stays FREE-FORM on purpose: it
112
+ // is the unregistered example test/flow-submit-registry.test.ts pins the
113
+ // advisory on, so registering it would break that protected contract.
114
+ function buildReviewGateSection(
115
+ mode: 'work' | 'personal',
116
+ ref: string,
117
+ ): string {
118
+ // AIDEV-NOTE: PMR-V31Z 1.1/1.2 — prompts are route-free: the work step 9
119
+ // below calls flow_land without a route (the tool param is optional,
120
+ // default 'pr'; the param itself dies in phase 4). 1.2 deleted the
121
+ // personal code-review gate: the personal branch below stops at the
122
+ // review tool + blockers and names flow_land nowhere.
123
+ if (mode === 'personal') {
124
+ return `
125
+ Review gate — run ONLY after validation has fully passed:
126
+
127
+ ${buildBasePinStep(mode)}
128
+ 7. Call the review tool on this change (the fresh-context reviewer) with target
129
+ { type: "branch", branch: BASE_SHA } — the tool accepts any ref, and the
130
+ pinned SHA keeps the reviewer range identical to 6a even on a legacy
131
+ worktree without a recorded flow base (a branch-NAME target would
132
+ re-resolve through the base's upstream ref, which lags local main in
133
+ personal mode — PMR-DQ7Z).
134
+ When it returns,
135
+ write the review artifact's verdict as machine-readable lines — exactly
136
+ one line "blockers_count: <N>" (N = number of must-fix blockers, integer,
137
+ 0 when clean) plus one "- blocker: <description>" line per blocker:
138
+ ${REVIEW_CONTRACT_PROMPT}
139
+ ${buildDeltaReviewStep(ref)}
140
+ 8. Read the count. NEVER treat a missing or malformed count as 0 — a
141
+ malformed artifact means call the review tool again, not silent landing.
142
+ On blockers_count > 0: record each blocker as an aven note on ${ref}
143
+ (append "reviewed-at: <git rev-parse HEAD>" to the note) and STOP — the
144
+ flow loop re-runs implement automatically (retry budget applies); do not
145
+ run implement yourself. When blockers_count is 0, the deviation gate
146
+ below runs next. Journal the verdict with the flow_submit tool using
147
+ step="validate.review-tool" and output.phase="validate" (registered
148
+ evidence-only name for the review tool's blockers_count; advisory only,
149
+ it never replaces the gates or the phase-completion label).`
150
+ }
151
+ let landing: string
152
+ if (mode === 'work') {
153
+ landing = `push the branch and create a PR via
154
+ the gh CLI, then post a Jira comment on
155
+ ${ref} linking the PR URL.`
156
+ } else {
157
+ landing = `merge the branch into main LOCALLY —
158
+ git -C <main repo> merge --ff-only <branch> (main repo = first entry of
159
+ \`git worktree list\`). Run the pinned command ALONE, nothing appended —
160
+ flow_land authorizes that exact command string and a compound command
161
+ (e.g. appending && git log) is refused. NEVER push. No PR, no Jira link
162
+ step. On ff-only failure STOP and ask the human.`
163
+ }
164
+ return `
165
+ Review gate — run ONLY after validation has fully passed:
166
+
167
+ ${buildBasePinStep(mode)}
168
+ 7. Call the review tool on this change (the fresh-context reviewer). When it returns,
169
+ write the review artifact's verdict as machine-readable lines — exactly
170
+ one line "blockers_count: <N>" (N = number of must-fix blockers, integer,
171
+ 0 when clean) plus one "- blocker: <description>" line per blocker:
172
+ ${REVIEW_CONTRACT_PROMPT}
173
+ ${buildDeltaReviewStep(ref)}
174
+ 8. Read the count. NEVER treat a missing or malformed count as 0 — a
175
+ malformed artifact means call the review tool again, not silent landing.
176
+ Journal the verdict with the flow_submit tool using
177
+ step="validate.review-tool" and output.phase="validate" (registered
178
+ evidence-only name for the review tool's blockers_count; advisory only,
179
+ it never replaces the gates or the phase-completion label).
180
+ 9. If blockers_count is 0: call the flow_phase_complete tool with ref=${ref}
181
+ and phase="validate" — it applies the "review-passed" label after
182
+ re-checking the gates, and its result confirms the label landed; without
183
+ it the flow halts at validate. Then call the flow_land tool with
184
+ ref=${ref} — it authorizes the landing;
185
+ while the flow is active, direct git push / gh pr create are BLOCKED
186
+ until flow_land returns ok. On ok, run the landing step:
187
+ ${landing}
188
+ Journal the landing with the flow_submit tool using step="validate.land"
189
+ and output.phase="validate" (registered evidence-only name for the
190
+ flow_land authorization plus the landing command; advisory only).
191
+ 10. If blockers_count > 0: record each blocker as an aven note on ${ref}
192
+ (append "reviewed-at: <git rev-parse HEAD>" to the note) and STOP — do
193
+ not land. The flow loop re-runs implement automatically (retry budget
194
+ applies); do not run implement yourself.`
195
+ }
196
+
197
+ // AIDEV-NOTE: Deviation gate section (PMR-BAGD) — appended to BOTH validate
198
+ // prompts, AFTER the review gate section. Ordering contract: it runs once the
199
+ // review gate returned blockers_count: 0, and BEFORE the flow calls D5's
200
+ // pass routes make (work: the flow_phase_complete / flow_land calls that
201
+ // review-gate step 9 describes; personal since PMR-V31Z 1.2: the
202
+ // flow_phase_complete(validate) call alone) — the prose below restates that
203
+ // ordering explicitly. Spec-source resolution is mode-keyed:
204
+ // - work: spec file via resolve_spec_path + Jira text via acli
205
+ // - personal planned: plan.md read from plan-path metadata (aven show --full
206
+ // heredoc parsing per spec-review/aven-spec.ts — NEVER `aven show --json`,
207
+ // metadata is omitted on aven 0.1.39)
208
+ // - personal oneshot (oneshot=true): the ticket description itself
209
+ // Artifact parsing and routing delegate to the contracts the agent runs in
210
+ // the deviation_review tool (tools/deviation.ts, which wraps
211
+ // review/deviation.ts's startDeviationReview and
212
+ // validate/deviation-gate.ts's parseDeviationArtifact).
213
+ // Fail-closed everywhere: a missing/malformed spec source or artifact stops
214
+ // the flow — never a silent pass.
215
+ // AIDEV-NOTE: PMR-C6AK (rewritten by PMR-V31Z 1.2) — mode-keyed routing
216
+ // targets. Work: unchanged (D5 continues into flow_phase_complete ->
217
+ // flow_land). Personal: the 0-deviation and "accept" routes call
218
+ // flow_phase_complete(validate) directly — the loop advances to the
219
+ // feedback phase, which owns the PR delivery; no code_review call follows.
220
+ export function buildDeviationGateSection(
221
+ mode: 'work' | 'personal',
222
+ ref: string,
223
+ oneshot = false,
224
+ ): string {
225
+ let specSource: string
226
+ if (mode === 'work') {
227
+ specSource = `Resolve the spec file path via the resolve_spec_path tool
228
+ (repo from the git remote, slug from the Jira summary) and read that spec
229
+ file. Also fetch the Jira ticket text via acli.`
230
+ } else if (oneshot) {
231
+ specSource = `This is a personal-mode oneshot with no plan: the spec is the
232
+ ticket description itself, read from \`aven show ${ref} --full\`.`
233
+ } else {
234
+ specSource = `Read the plan: run \`aven show ${ref} --full\` and trust ONLY
235
+ the \`metadata field_id=... key=plan-path\` / value<<EOF heredoc blocks
236
+ (same parsing as spec-review/aven-spec.ts). NEVER use \`aven show --json\`
237
+ for metadata — aven 0.1.39 omits it. Read plan.md from the resolved
238
+ plan-path. If the plan-path metadata is missing or the plan file is
239
+ unreadable: STOP and report to the human — never invent a spec, never
240
+ proceed without one.`
241
+ }
242
+ let gateBefore: string
243
+ let continueTarget: string
244
+ let acceptTarget: string
245
+ if (mode === 'work') {
246
+ gateBefore = `and BEFORE the flow_phase_complete(phase="validate") / flow_land calls named
247
+ in review-gate step 9`
248
+ continueTarget = `then continue to flow_phase_complete with
249
+ ref=${ref} and phase="validate", then flow_land (review-gate step 9).`
250
+ acceptTarget = `On "accept": proceed to flow_phase_complete with ref=${ref}
251
+ and phase="validate", then flow_land.`
252
+ } else {
253
+ gateBefore = `and BEFORE the flow_phase_complete(phase="validate") call that
254
+ ends the validate phase`
255
+ continueTarget = `then call the flow_phase_complete tool with
256
+ ref=${ref} and phase="validate" — the loop then advances to the
257
+ feedback phase, which owns the PR delivery.`
258
+ acceptTarget = `On "accept": call the flow_phase_complete tool with
259
+ ref=${ref} and phase="validate" — the loop then advances to the
260
+ feedback phase, which owns the PR delivery.`
261
+ }
262
+ // AIDEV-NOTE: PMR-ZV9Y 1.2 step registry — the lettered deviation steps in
263
+ // the template below bind 1:1 to flow/steps.ts STEP_REGISTRY names, so a
264
+ // future rename there must be reflected here (and vice versa). This section
265
+ // is appended to BOTH the work and personal (non-yolo) validate prompts, so
266
+ // these three bindings cover both modes:
267
+ // D1 = validate.spec-diff (resolve the spec source the diff compares to)
268
+ // D2 = validate.aven-notes (mine the why-input aven notes)
269
+ // D3 = validate.deviation (the deviation_review tool boundary)
270
+ // H1 = validate.code-review is retired (PMR-V31Z 1.2): the human
271
+ // code_review gate is deleted from the personal validate prompt.
272
+ // PMR-V31Z 7.2 cleaned up the code_review internals (receipt +
273
+ // marker deleted); the registry name stays because the ad-hoc
274
+ // tool's own step events still use it.
275
+ return `
276
+ Deviation gate — run ONLY after the review gate returned blockers_count: 0,
277
+ ${gateBefore}. Steps, in order:
278
+
279
+ D1. Resolve the spec source. ${specSource}
280
+ D2. Mine the why-inputs: recent aven notes on ${ref} via
281
+ "aven context ${ref} --full" (interview note, worktree note, oneshot outcome,
282
+ escalation notes). Commit messages are resolved by the tool itself.
283
+ D3. Run the deviation reviewer: call the deviation_review tool with
284
+ mode="${mode}", the resolved spec text (D1) and the mined aven notes (D2).
285
+ Do NOT pass a diff or commit messages: the tool resolves the base, diff
286
+ and commits itself in the flow worktree and reports the base SHA and
287
+ range in its result. Compare that base SHA to BASE_SHA (6a); if it
288
+ differs, or the tool errors on a missing base / empty range, STOP and ask
289
+ the human. Await its result.
290
+ D4. Read the tool result. The tool already parses the artifact STRICTLY
291
+ (deviations_count contract). An ERROR tool result (spawn failure or
292
+ malformed artifact) means re-run deviation_review — NEVER treat it as 0
293
+ deviations, never silent landing. On ok, continue with the returned
294
+ deviations_count.
295
+ D5. Route on the returned deviations_count:
296
+ - 0 deviations: record an aven note on ${ref} reading
297
+ "no deviation from spec", ${continueTarget}
298
+ - more than 0: present the full deviation report to the human via
299
+ ask_user_question with exactly two options: "accept" and "fix". WAIT
300
+ for the answer. Record the human decision as an aven note on ${ref}
301
+ either way. ${acceptTarget} On "fix": record the deviation
302
+ report as an aven note on ${ref} (append "reviewed-at: <git rev-parse
303
+ HEAD>") and STOP — do not land. The flow loop re-runs implement
304
+ automatically and points the agent at that note.`
305
+ }
306
+
307
+ export interface ValidatePromptInput {
308
+ mode: 'work' | 'personal'
309
+ ref: string
310
+ scriptsDir: string | null
311
+ // AIDEV-NOTE: personal mode only — a oneshot ticket has no plan.md, so the
312
+ // deviation gate resolves the spec from the ticket description instead.
313
+ oneshot?: boolean
314
+ // AIDEV-NOTE: /flow --yolo run: gates are skipped and the agent acts
315
+ // autonomously. Personal-only — the work-mode prompt ignores this bit.
316
+ yolo?: boolean
317
+ }
318
+
319
+ // AIDEV-NOTE: yolo 4.2 (wording swept by PMR-V31Z 1.2) — yolo variant of the
320
+ // personal validate prompt. The human test gate is replaced by the agent
321
+ // running the suite itself via the run_tests tool (pi-test-runner), the
322
+ // human code-review gate is skipped ENTIRELY (PMR-V31Z 1.2 deleted it from
323
+ // every personal validate prompt — yolo always skipped it), deviations_count
324
+ // > 0 ALWAYS routes back to implement via the blocker-retry loop (never
325
+ // auto-accept — there is no human to accept), and the landing is
326
+ // flow_land — one git push + one gh pr create, the flow's GitHub PR is its
327
+ // delivery (no local merge, no code_review). flow_phase_complete(validate)
328
+ // runs after the review gate returns 0 blockers AND the deviation review
329
+ // passes. The reviewed-at marker contract (PMR-69V8) is kept on every fail
330
+ // path so the loop can re-inject implement.
331
+ // AIDEV-NOTE: PMR-ZV9Y 1.2 step registry — the inline deviation steps in the
332
+ // template below (D1/D2/D3, the yolo copy) bind 1:1 to flow/steps.ts exactly
333
+ // as in buildDeviationGateSection:
334
+ // D1 = validate.spec-diff D2 = validate.aven-notes D3 = validate.deviation
335
+ // There is NO H1/validate.code-review anchor here: PMR-V31Z 1.2 removed the
336
+ // human code_review gate from every personal validate prompt (yolo always
337
+ // skipped it), so no step-stop{validate.code-review} is
338
+ // ever emitted for it. Rename in flow/steps.ts must be reflected here.
339
+ // AIDEV-NOTE: PMR-E1ZN — a run_tests error means zero tests ran. Yolo must
340
+ // rerun the suite directly and can never record that wrapper failure as a pass.
341
+ function yoloPersonalValidatePrompt(ref: string, oneshot: boolean): string {
342
+ const specSource = oneshot
343
+ ? `This is a personal-mode oneshot with no plan: the spec is the
344
+ ticket description itself, read from \`aven show ${ref} --full\`.`
345
+ : `Read the plan: run \`aven show ${ref} --full\` and trust ONLY
346
+ the \`metadata field_id=... key=plan-path\` / value<<EOF heredoc blocks
347
+ (same parsing as spec-review/aven-spec.ts). NEVER use \`aven show --json\`
348
+ for metadata — aven 0.1.39 omits it. Read plan.md from the resolved
349
+ plan-path. If the plan-path metadata is missing or the plan file is
350
+ unreadable: STOP — never invent a spec, never proceed without one.`
351
+ return `Validate phase (PIV flow). Mode: personal. Ref: ${ref}. YOLO run: gates are skipped — act autonomously, no human confirmation steps.
352
+ Personal-mode validation (yolo variant): there is no cluster — you run the
353
+ tests yourself. Do NOT run the work-mode gate (no cluster tools, no devctl,
354
+ no acli). There is NO human code-review gate in a yolo run.
355
+
356
+ 1. Locate the ticket's plan/research artifacts for ${ref}: run
357
+ \`aven show ${ref} --full\` and look for a \`metadata ... key=research-path\`
358
+ block (set by /brainstorm on confirmed aven tickets). If present, read
359
+ that file for the research findings. If absent, that is NORMAL — most
360
+ tickets are never brainstormed; skip the research-findings section and
361
+ continue (do NOT fail or stop because of it). Extract from the remaining
362
+ artifacts (plan-path metadata): what changed, and the plan's validation
363
+ notes.
364
+ 2. Compose concrete runnable test instructions from those sections using the
365
+ rules in validate/personal.ts (composeHumanTest): numbered steps with the
366
+ expected outcome. If ALL sections are empty, STOP — the artifacts are
367
+ missing; never invent generic filler steps.
368
+ 3. Run the tests YOURSELF via the run_tests tool (pi-test-runner) in the
369
+ flow worktree — this is a yolo run: there is no human test gate and no
370
+ human pass/fail question. A run_tests error ⇒ zero evidence ⇒ run
371
+ \`cd packages/<pkg> && bun run test\` directly; never record a pass.
372
+ On failure: record the failing output as
373
+ an aven note on ${ref} (append "reviewed-at: <git rev-parse HEAD>") and
374
+ STOP — the flow loop re-runs implement automatically. On pass: record an
375
+ aven note on ${ref} reading "validated by agent (yolo), <today's date>"
376
+ and continue to the review gate.
377
+
378
+ Review gate — run ONLY after the tests have passed:
379
+
380
+ ${buildBasePinStep('personal')}
381
+ 7. Call the review tool on this change (the fresh-context reviewer) with target
382
+ { type: "branch", branch: BASE_SHA } — the pinned SHA keeps the reviewer
383
+ range identical to 6a even on a legacy worktree without a recorded flow
384
+ base. When it returns, write the review artifact's verdict as
385
+ machine-readable lines — exactly one line "blockers_count: <N>" (N =
386
+ number of must-fix blockers, integer, 0 when clean) plus one
387
+ "- blocker: <description>" line per blocker:
388
+ ${REVIEW_CONTRACT_PROMPT}
389
+ ${buildDeltaReviewStep(ref)}
390
+ 8. Read the count. NEVER treat a missing or malformed count as 0 — a
391
+ malformed artifact means call the review tool again, not silent landing.
392
+ On blockers_count > 0: record each blocker as an aven note on ${ref}
393
+ (append "reviewed-at: <git rev-parse HEAD>" to the note) and STOP — the
394
+ flow loop re-runs implement automatically (retry budget applies); do not
395
+ run implement yourself. When blockers_count is 0, the deviation gate
396
+ below runs next. Journal the verdict with the flow_submit tool using
397
+ step="validate.review-tool" and output.phase="validate" (registered
398
+ evidence-only name for the review tool's blockers_count; advisory only).
399
+
400
+ Deviation gate — run ONLY after the review gate returned blockers_count: 0.
401
+ Steps, in order:
402
+
403
+ D1. Resolve the spec source. ${specSource}
404
+ D2. Mine the why-inputs: recent aven notes on ${ref} via
405
+ "aven context ${ref} --full" (interview note, worktree note, oneshot
406
+ outcome, escalation notes). Commit messages are resolved by the tool
407
+ itself.
408
+ D3. Run the deviation reviewer: call the deviation_review tool with
409
+ mode="personal", the resolved spec text (D1) and the mined aven notes
410
+ (D2). Do NOT pass a diff or commit messages: the tool resolves the base,
411
+ diff and commits itself in the flow worktree and reports the base SHA and
412
+ range in its result. Compare that base SHA to BASE_SHA (6a); if it
413
+ differs, or the tool errors on a missing base / empty range, STOP. Await
414
+ its result.
415
+ D4. Read the tool result. The tool already parses the artifact STRICTLY
416
+ (deviations_count contract). An ERROR tool result (spawn failure or
417
+ malformed artifact) means re-run deviation_review — NEVER treat it as 0
418
+ deviations, never silent landing. On ok, continue with the returned
419
+ deviations_count.
420
+ D5. Route on the returned deviations_count:
421
+ - 0 deviations: record an aven note on ${ref} reading
422
+ "no deviation from spec", then call the flow_phase_complete tool with
423
+ ref=${ref} and phase="validate" — it applies the "review-passed" label
424
+ after re-checking the gates. Do NOT land here: the flow advances to
425
+ the feedback phase automatically, and feedback lands via
426
+ flow_land — one git push + one gh pr create, the flow's GitHub PR is
427
+ its delivery — there is NO local merge into main and no human
428
+ review-tool step in a yolo run.
429
+ - more than 0: record the full deviation report as an aven note on
430
+ ${ref} (append "reviewed-at: <git rev-parse HEAD>") and STOP — do not
431
+ land. In a yolo run deviations ALWAYS route back to implement via the
432
+ blocker-retry loop; never auto-accept, never ask a human (there is no
433
+ human gate in yolo).`
434
+ }
435
+
436
+ export function buildValidatePrompt(input: ValidatePromptInput): string {
437
+ const header = `Validate phase (PIV flow). Mode: ${input.mode}. Ref: ${input.ref}.`
438
+ if (input.mode === 'personal') {
439
+ if (input.yolo === true) {
440
+ let isOneshotYolo: boolean
441
+ if (input.oneshot === true) {
442
+ isOneshotYolo = true
443
+ } else {
444
+ isOneshotYolo = false
445
+ }
446
+ return yoloPersonalValidatePrompt(input.ref, isOneshotYolo)
447
+ }
448
+ let isOneshot: boolean
449
+ if (input.oneshot === true) {
450
+ isOneshot = true
451
+ } else {
452
+ isOneshot = false
453
+ }
454
+ return `${header}
455
+ Personal-mode validation: there is no cluster — the human is the test
456
+ environment. Do NOT run the work-mode gate (no cluster tools, no devctl, no acli).
457
+
458
+ 1. Locate the ticket's plan/research artifacts for ${input.ref}: run
459
+ \`aven show ${input.ref} --full\` and look for a \`metadata ... key=research-path\`
460
+ block (set by /brainstorm on confirmed aven tickets). If present, read
461
+ that file for the research findings. If absent, that is NORMAL — most
462
+ tickets are never brainstormed; skip the research-findings section and
463
+ continue (do NOT fail or stop because of it). Extract from the remaining
464
+ artifacts (plan-path metadata): what changed, and the plan's validation
465
+ notes.
466
+ 2. Compose concrete runnable test instructions from those sections using the
467
+ rules in validate/personal.ts (composeHumanTest): numbered steps the human
468
+ can literally run, plus the expected outcome. If ALL sections are empty,
469
+ STOP and tell the human the artifacts are missing — never invent generic
470
+ filler steps.
471
+ 3. Present the instructions to the human via ask_user_question with exactly
472
+ two options: "pass" and "fail". WAIT for the answer — do not proceed until
473
+ the human has run the steps and replied.
474
+ 4. On "pass": record an aven note on ${input.ref} reading
475
+ "validated by human, <today's date>" and report validation complete (the
476
+ review gate runs next).
477
+ 5. On "fail": ask the human for a short failure description, record it as an
478
+ aven note on ${input.ref} (append "reviewed-at: <git rev-parse HEAD>") and
479
+ STOP — the flow loop re-runs implement automatically.
480
+ ${buildReviewGateSection('personal', input.ref)}
481
+ ${buildDeviationGateSection('personal', input.ref, isOneshot)}`
482
+ }
483
+ const scripts = input.scriptsDir
484
+ return `${header}
485
+ Run the work-mode validation gate. Execute these steps IN ORDER and do not skip
486
+ or reorder any of them. Every step must succeed before the next one starts.
487
+
488
+ 1. Minikube (bounded): run \`minikube status\`. If it is not Running:
489
+ run \`minikube start\`, then poll \`minikube status\` until Running —
490
+ at most ${DEFAULT_POLL_CONFIG.maxAttempts} attempts,
491
+ ${DEFAULT_POLL_CONFIG.intervalMs / 1000}s apart. If it is still not
492
+ Running after the bound, the gate FAILS (never hang the flow).
493
+ 2. Connectivity: run \`${scripts}/test-services-connectivity.sh\` — must exit 0.
494
+ 3. SQS queues: run \`${scripts}/add-sqs-queues.sh\` — must exit 0.
495
+ 4. Deploy: use the user's devctl skill to deploy the affected services
496
+ (from the plan's validation notes) to the local cluster.
497
+ 5. Manual tests: read the plan's validation notes for the manual checks.
498
+ Collect each check's result from the human via ask_user_question
499
+ (pass/fail + evidence). A single fail fails the gate.
500
+ 6. Jira evidence comment: via acli, post a comment on ${input.ref} describing
501
+ HOW the change was validated — what was deployed, which tests ran, and the
502
+ evidence from steps 1-5.
503
+ Advisory: report gate evidence via the flow_submit tool after the gate
504
+ steps complete — free-form step label (e.g. step="gate-evidence"),
505
+ output.phase="validate", and validate-legal facts only: prUrl/prNumber/
506
+ gateTargetIds (command is an implement-phase fact and would be refused).
507
+ It journals evidence only and never replaces step 6 or the
508
+ phase-completion label.
509
+
510
+ Completion rule: the phase passes ONLY after the Jira comment from step 6 has
511
+ landed. Track progress against the ordered gate steps
512
+ (minikube, connectivity, queues, deploy, manual-tests, jira-comment).
513
+
514
+ On ANY step failure: STOP. Write the failing step's name and its full failing
515
+ output as an aven note on ${input.ref}, and report the failure to the human.
516
+ Never continue past a failed step, never mark the phase validated.
517
+ ${buildReviewGateSection('work', input.ref)}
518
+ ${buildDeviationGateSection('work', input.ref, false)}`
519
+ }
520
+
521
+ // AIDEV-NOTE: PMR-69V8 — route-backs are NOT agent actions. Every fail path
522
+ // above writes a note carrying "reviewed-at:" and stops; flow/loop-settle.ts
523
+ // sees the fresh marker note on the unlabelled validate settle and re-injects
524
+ // the implement prompt (bounded by MAX_ATTEMPTS). Keep the marker in any new
525
+ // fail path or the loop will plain-halt instead.