@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,177 @@
1
+ // AIDEV-NOTE: Feedback-phase handoff prompts (PMR-XDRB phase 5), sent via
2
+ // sendUserMessage (same pattern as validate/prompt.ts). Work mode runs
3
+ // the sonarqube and pr_quality TOOLS (PMR-69V8: agents cannot invoke slash
4
+ // commands).
5
+ // The triage rules mirror classify() in feedback/triage.ts; the escalation
6
+ // rule (new work = new task through the gates) is stated as an absolute in
7
+ // the prompt so the agent can never fix silently or ignore a finding.
8
+
9
+ import { classify, FIX_NOW_SEVERITIES } from './triage.ts'
10
+
11
+ export interface FeedbackPromptInput {
12
+ /** 'work' gates an existing PR; 'personal' delivers the PR then closes out (PMR-81SX, PMR-V31Z). */
13
+ mode: 'work' | 'personal'
14
+ ref: string
15
+ // AIDEV-NOTE: /flow --yolo run: gates are skipped and the agent acts
16
+ // autonomously. Personal-only — the work-mode prompt ignores this bit.
17
+ yolo?: boolean
18
+ }
19
+
20
+ // AIDEV-NOTE: PMR-V31Z 1.3 — the PR body contract for personal delivery,
21
+ // embedded in the prompt prose and pinned verbatim by feedback.test.ts and
22
+ // phase-prompts.test.ts so later phases (docs, PR digest) can reference it
23
+ // without re-describing it.
24
+ export const PERSONAL_PR_BODY_SPEC =
25
+ 'TL;DR: 2–3 lines at the top — what this PR does and why, plain words. Then **What changed** / **Why** / **How to test** sections. Short sentences, bullets over paragraphs, **bold** key facts. How-to-test lists the concrete commands and expected results (including the flow_land land-suite run).'
26
+
27
+ const MECHANICAL = [...FIX_NOW_SEVERITIES].join(', ')
28
+
29
+ // AIDEV-NOTE: raw Aven CLI commands use the main checkout's project path
30
+ // mappings; implementation remains isolated in the flow worktree.
31
+ const AVEN_CWD_RULE =
32
+ 'Run every raw `aven` command from the main checkout (for example, `cd <main checkout> && aven ...`); keep implementation in the flow worktree.'
33
+
34
+ function workSection(ref: string): string {
35
+ return `Run the feedback work gate on ${ref}'s PR. Execute IN ORDER:
36
+
37
+ 1. Call the sonarqube tool on the PR and read its report.
38
+ 2. For EACH unresolved finding, triage it with these rules:
39
+ - Mechanical findings (severity ${MECHANICAL}) that do NOT touch
40
+ behavior, architecture, data, migrations, schema, or API contracts are
41
+ fixed immediately.
42
+ - Anything touching behavior/architecture/data — regardless of severity —
43
+ and every major/critical/blocker, and every finding whose severity you
44
+ cannot determine, becomes a NEW Jira/aven task (plan it via the
45
+ normal flow phases). NEVER fix such a
46
+ finding silently inside feedback. NEVER ignore a finding: every finding
47
+ ends as either a fix commit or a new task. Nothing is left unresolved.
48
+ - Non-blocking review observations (P2/P3, "for later", "non-blocking",
49
+ "worth knowing") each become their OWN backlog ticket labeled
50
+ review-feedback (aven add "<sentence-case title>" --label
51
+ review-feedback --status backlog --priority <medium|low>; create the
52
+ label first with aven label create if missing), carrying the finding,
53
+ the source artifact, file references, and a done-when. Skip purely
54
+ informational/self-healing notes and anything an open ticket already
55
+ covers; mention siblings ("related to PMR-XXXX") when one exists.
56
+ Skip silently when there are none.
57
+ 3. Fix-now findings: use the pr_quality tool for review-thread context, fix, and COMMIT each fix.
58
+ 4. Address all unresolved GitHub review comments on the PR (same triage
59
+ rules; reply to comments you escalated, linking the new task).
60
+
61
+ Completion rule: every finding is fixed-and-committed or escalated as a new
62
+ task. Report the final counts in your reply, then transition ${ref} to status
63
+ done AND call the flow_phase_complete tool with ref=${ref} and
64
+ phase="feedback" — it applies the "done" label after re-checking the gates,
65
+ and its result confirms the label landed.`
66
+ }
67
+
68
+ // AIDEV-NOTE: PMR-V31Z 1.3 — ONE personal feedback section for yolo and
69
+ // non-yolo (converges the old personalSection + yoloPersonalFeedbackSection,
70
+ // ex PMR-81SX; the yolo section was the target shape). Validate completes
71
+ // WITHOUT landing, so feedback owns the entire PR delivery: flow_land(ref)
72
+ // FIRST — route-free, the tool param defaults to 'pr' (PMR-V31Z 1.1) — as
73
+ // the final integrity gate; a refusal writes the reviewed-at aven note and
74
+ // STOPs so the loop routes back to implement. Then exactly ONE authorized
75
+ // git push + ONE gh pr create (body per PERSONAL_PR_BODY_SPEC), verify, the
76
+ // prUrl note, and the flow_submit delivery row (prMerged=false — merging
77
+ // stays manual on GitHub; the open PR is the end state). Every fail path
78
+ // writes an aven note carrying "reviewed-at: <git rev-parse HEAD>" and
79
+ // STOPs (PMR-69V8). The outcome summary follows the outcomeSummary()
80
+ // contract in feedback/triage.ts and must exist before done (canClose(),
81
+ // prompt contract only). Idempotent and oneshot-tolerant: already-done or
82
+ // already-recorded steps count as success, and no plan artifact is assumed.
83
+ // Yolo keeps its autonomy prefix; non-yolo keeps the gate wording (the
84
+ // gates already ran; flow_land re-checks review-passed + the suite
85
+ // regardless).
86
+ function personalPrDeliverySection(ref: string, yolo: boolean): string {
87
+ let prefix: string
88
+ if (yolo) {
89
+ prefix = `Close out the personal-mode flow on ${ref}. YOLO run: gates are
90
+ skipped — act autonomously, no human confirmation steps. The validate phase
91
+ completed WITHOUT landing, so this phase owns the entire landing sequence.`
92
+ } else {
93
+ prefix = `Close out the personal-mode flow on ${ref}. The validate gates
94
+ have already passed and landed the review-passed label without landing any
95
+ code, so this phase owns the entire PR delivery sequence.`
96
+ }
97
+ return `${prefix}
98
+ Execute IN ORDER:
99
+
100
+ 1. Call the flow_land tool with ref=${ref}. This is the final
101
+ integrity gate: it re-checks the review-passed label, runs the land test
102
+ suite itself, declares the git-push and gh-pr-create effects, and on ok
103
+ authorizes exactly ONE git push and ONE gh pr create for this flow. If
104
+ flow_land refuses (missing label, red suite), write an aven note on ${ref}
105
+ with the refusal reason plus "reviewed-at: <git rev-parse HEAD>" and STOP
106
+ — the flow loop routes back to implement; never push or open a PR without
107
+ the authorization, never retry blindly.
108
+ 2. On flow_land ok: push the flow branch with
109
+ \`git push -u origin <flow branch>\` (the exact branch the flow worktree
110
+ is on — the single push flow_land authorized).
111
+ 3. Open the pull request with \`gh pr create\` targeting main. Write the
112
+ body following this spec exactly: ${PERSONAL_PR_BODY_SPEC} Ground the
113
+ sections in the ${ref} description and this run's commits and test
114
+ output — the substantive changes, not a commit dump.
115
+ 4. Verify the PR exists: run \`gh pr view --json url\` on the branch. If the
116
+ URL is missing or the command fails, treat step 3 as failed: fix the
117
+ cause (do not open duplicate PRs) and re-verify.
118
+ 5. Record the PR URL as an aven note on ${ref} together with a one-line
119
+ summary of what shipped.
120
+ 6. Journal the delivery with the flow_submit tool: call it with
121
+ ref=${ref}, step="deliver-pr", ok=true, and output phase="feedback"
122
+ carrying prUrl=<the verified PR URL> and prMerged=false. prMerged stays
123
+ false — merging the PR is manual on GitHub; the open PR is the end state.
124
+ 7. Write the outcome summary as an aven note on ${ref}, following this
125
+ contract exactly: a "## Outcome summary" heading with "### What
126
+ shipped", "### Test evidence" and "### Review verdict" sections
127
+ (whatShipped / testEvidence / reviewVerdict). Gather the content from
128
+ this run's notes, commits, and test output. If any section has no
129
+ content, write an aven note on ${ref} containing
130
+ "reviewed-at: <git rev-parse HEAD>" instead and STOP — never invent
131
+ filler. The outcome-summary note MUST exist before ${ref} can be set to
132
+ done (canClose contract) — never skip it.
133
+ 8. Review-feedback triage: collect every non-blocking review observation
134
+ (P2/P3, "for later", "non-blocking", "worth knowing") recorded in the
135
+ review notes and artifacts on ${ref} during this flow, and file each
136
+ actionable one as its OWN backlog ticket: aven add "<sentence-case
137
+ title>" --label review-feedback --status backlog --priority
138
+ <medium|low> --description "..." (create the label first with
139
+ \`aven label create\` if missing). Each description carries the finding,
140
+ the source note/artifact id, file references, and a done-when; skip
141
+ purely informational/self-healing notes and anything an open ticket
142
+ already covers; mention siblings ("related to PMR-XXXX") when one
143
+ exists. If there are no non-blocking observations, skip silently.
144
+ 9. Wrap up IN ORDER: first set ${ref} to done with
145
+ \`aven edit ${ref} --status done\`, THEN call the flow_phase_complete
146
+ tool with ref=${ref} and phase="feedback" — it applies the "done" label
147
+ after re-checking the gates, and its result confirms the label landed.
148
+ The aven edit is the verified last step; do not run them in the other
149
+ order.
150
+ 10. Idempotency: if ${ref} is already status done, or a step above was
151
+ already recorded (PR URL note exists, delivery flow_submit row exists,
152
+ outcome-summary note exists, review-feedback tickets already filed),
153
+ treat that step as success and move on — never fail the close-out
154
+ because a step already ran. NEVER re-run the push or gh pr create
155
+ outside the single authorization from step 1, and never merge the PR —
156
+ merging stays manual on GitHub; the open PR is the end state of the
157
+ run. This flow may be a oneshot with no plan artifact: do not assume or
158
+ look for a plan.md; the ticket description is the spec.
159
+ 11. After flow_phase_complete returns ok, report the outcome counts (what
160
+ shipped, review verdict, PR URL, review-feedback ticket refs) in your
161
+ reply. The harness removes the flow worktree automatically — no manual
162
+ \`git worktree remove\` is needed.`
163
+ }
164
+
165
+ export function buildFeedbackPrompt(input: FeedbackPromptInput): string {
166
+ const header = `Feedback phase (PIV flow). Mode: ${input.mode}. Ref: ${input.ref}.`
167
+ let section: string
168
+ if (input.mode === 'personal') {
169
+ section = personalPrDeliverySection(input.ref, input.yolo === true)
170
+ } else {
171
+ section = workSection(input.ref)
172
+ }
173
+ return `${header}\n${AVEN_CWD_RULE}\n${section}`
174
+ }
175
+
176
+ // AIDEV-NOTE: re-export so prompt consumers and tests share one classifier.
177
+ export { classify }
@@ -0,0 +1,88 @@
1
+ // AIDEV-NOTE: Pure feedback triage core (PMR-XDRB phase 5). classify() is the
2
+ // work-mode decision over a SonarQube / review finding: small mechanical
3
+ // findings are fixed immediately; anything behavioral/architectural/data
4
+ // touching MUST become a new task through the flow gates — feedback can never
5
+ // re-open implementation silently. canClose() is the completion guard: the
6
+ // personal-mode outcome summary note must exist before the ticket goes done.
7
+ // All pure — the command handler and handoff prompt own all I/O.
8
+ //
9
+ // AIDEV-NOTE: Classifier thresholds are JUDGMENT CALLS, documented here:
10
+ // - Mechanical set = {minor, style, naming}: cosmetic, zero behavior risk.
11
+ // - ANY finding whose description mentions behavior/architecture/data/
12
+ // migration/schema/API-contract escalates even if severity says "minor" —
13
+ // severity labels lie more often than descriptions do.
14
+ // - UNKNOWN severity escalates (fail-closed): silence beats a broken fix.
15
+ // - major/critical/blocker always escalate: too big to "just fix" while
16
+ // closing out a phase.
17
+
18
+ export interface Finding {
19
+ severity?: string
20
+ description?: string
21
+ }
22
+
23
+ export type TriageAction = 'fix-now' | 'new-task'
24
+
25
+ export interface TriageDecision {
26
+ action: TriageAction
27
+ }
28
+
29
+ export const FIX_NOW_SEVERITIES = new Set(['minor', 'style', 'naming'])
30
+
31
+ const BEHAVIORAL_RE =
32
+ /\b(behaviou?r|architect|data|migration|schema|api contract|breaking|logic)\b/i
33
+
34
+ export function classify(finding: Finding): TriageDecision {
35
+ const description = finding.description ?? ''
36
+ if (BEHAVIORAL_RE.test(description)) {
37
+ return { action: 'new-task' }
38
+ }
39
+ const severity = finding.severity
40
+ if (severity === undefined) {
41
+ return { action: 'new-task' }
42
+ }
43
+ if (FIX_NOW_SEVERITIES.has(severity.toLowerCase())) {
44
+ return { action: 'fix-now' }
45
+ }
46
+ return { action: 'new-task' }
47
+ }
48
+
49
+ export interface OutcomeSummaryInput {
50
+ whatShipped: string
51
+ testEvidence: string
52
+ reviewVerdict: string
53
+ }
54
+
55
+ function hasContent(value: string): boolean {
56
+ return value.trim().length > 0
57
+ }
58
+
59
+ export function outcomeSummary(input: OutcomeSummaryInput): string {
60
+ const sections: Array<[string, string]> = [
61
+ ['What shipped', input.whatShipped],
62
+ ['Test evidence', input.testEvidence],
63
+ ['Review verdict', input.reviewVerdict],
64
+ ]
65
+ for (const [name, value] of sections) {
66
+ if (!hasContent(value)) {
67
+ return `insufficient context: outcome summary section "${name}" is empty — fill every section before closing the ticket`
68
+ }
69
+ }
70
+ return [
71
+ '## Outcome summary',
72
+ '',
73
+ '### What shipped',
74
+ input.whatShipped.trim(),
75
+ '',
76
+ '### Test evidence',
77
+ input.testEvidence.trim(),
78
+ '',
79
+ '### Review verdict',
80
+ input.reviewVerdict.trim(),
81
+ ].join('\n')
82
+ }
83
+
84
+ // AIDEV-NOTE: Completion guard — done REQUIRES the outcome summary note to
85
+ // have been written. Fail-closed by design.
86
+ export function canClose(summaryWritten: boolean): boolean {
87
+ return summaryWritten
88
+ }
@@ -0,0 +1,46 @@
1
+ // AIDEV-NOTE: ONE place that decides an agent's "role" — the short, groupable
2
+ // label used in trace session-span names ("<ref> - <role>") and in the cost
3
+ // dashboards (pi_flow_run_role_info). Both the agent TYPE and the display NAME
4
+ // are normalized into the closed vocabulary below; unknown free text collapses
5
+ // to "worker" so ticket refs and worktree slugs never become metric labels.
6
+ const ROLE_ALIASES: ReadonlyMap<string, string> = new Map([
7
+ ['scout', 'scout'],
8
+ ['worker', 'worker'],
9
+ ['fixer', 'worker'],
10
+ ['planner', 'planner'],
11
+ ['reviewer', 'reviewer'],
12
+ ['review', 'review'],
13
+ ['deviation check', 'deviation check'],
14
+ ['spec publish', 'spec-publish'],
15
+ ['resume', 'resume'],
16
+ ['test', 'test'],
17
+ ])
18
+
19
+ function normalizeRole(value: string | null | undefined): string | null {
20
+ if (value === undefined || value === null) return null
21
+ let normalized = value
22
+ .trim()
23
+ .toLowerCase()
24
+ .replace(/^[^a-z0-9]+/, '')
25
+ normalized = normalized.replace(
26
+ /^(?:pmr-[a-z0-9]+|[a-z][a-z0-9]*-\d+)(?:\s+|[-_:]+)?/,
27
+ '',
28
+ )
29
+ normalized = normalized.replace(/^[a-z0-9]*\d[a-z0-9]*-/, '')
30
+ normalized = normalized.replace(/[^a-z0-9]+/g, ' ').trim()
31
+ return ROLE_ALIASES.get(normalized) ?? null
32
+ }
33
+
34
+ export function agentRole(
35
+ agentType: string | null | undefined,
36
+ agentName: string | null | undefined,
37
+ ): string {
38
+ const fromType = normalizeRole(agentType)
39
+ if (fromType !== null) return fromType
40
+ const fromName = normalizeRole((agentName ?? '').split(':')[0])
41
+ if (fromName !== null) return fromName
42
+ return 'worker'
43
+ }
44
+
45
+ /** Role of the orchestrator = the main pi session that runs the flow. */
46
+ export const ORCHESTRATOR_ROLE = 'orchestrator'
@@ -0,0 +1,212 @@
1
+ // AIDEV-NOTE: PMR-DMHH — gate-answer wake decision module. Decides whether a
2
+ // recorded `/flow answer <ref> <choice>` should inject a wake into THIS
3
+ // session (rearm a paused flow loop, or a plain standalone-session wake) or
4
+ // stay notification-only.
5
+ //
6
+ // PI-FREE-BY-DEPS CONTRACT: like flow/answer.ts and server/consumer.ts this
7
+ // module must NEVER import a pi package or call a model-turn API — every
8
+ // effectful surface (loop probe, run-state read, session identity, marker,
9
+ // latch, notify, send) is injected via AnswerWakeDeps and wired in index.ts,
10
+ // so tests run without a live pi process and the agent structurally cannot
11
+ // reach this path.
12
+ //
13
+ // GUARD ORDER (plan PMR-DMHH subtask 1.1 — do not reorder):
14
+ // 1. gate !== 'spec' → silent return. VESTIGIAL since PMR-V31Z 7.1: the
15
+ // review gate is deleted and AnswerGate is the single-member 'spec'
16
+ // type, so no typed caller can pass anything else — the guard stays as
17
+ // fail-closed defense for untyped/legacy callers.
18
+ // 2. Latch supersede: a prior 'plain' entry is deleted (a new human answer
19
+ // supersedes); a prior 'rearm' entry → in-flight notify, no send.
20
+ // 3. loopActive() → notify reason, no send.
21
+ // 4. readRunState fail-soft: a throwing read is treated as `null`.
22
+ // 5. approve → rearm only when the latest snapshot is paused AND owned by
23
+ // this session (ownsPausedRun); else a standalone marker grants a plain
24
+ // wake; else notification-only with the reason.
25
+ // 6. reject → refusal wake when (paused AND owned) or marker present; else
26
+ // notification-only.
27
+ //
28
+ // LATCH-BEFORE-SEND: the latch entry is set BEFORE deps.send so a throwing
29
+ // user-message injection (e.g. mid-streaming) cannot cause a second injection
30
+ // on the next answer; a throw deletes the entry again and degrades to a
31
+ // warning with the manual `/flow <ref>` hint (server/consumer.ts shape).
32
+
33
+ import type { AnswerChoice, AnswerGate } from '../aven/client.ts'
34
+ import type { FlowRunState } from '../run-state.ts'
35
+
36
+ export type WakeLatchKind = 'rearm' | 'plain'
37
+
38
+ export interface AnswerWakeDeps {
39
+ /** True while a /flow loop is running in this process — no injection then. */
40
+ loopActive(): boolean
41
+ /** Latest run-state snapshot; a throw is degraded to `null` (fail-soft). */
42
+ readRunState(ref: string): Promise<FlowRunState | null>
43
+ /** Local session identity for the paused-waiter ownership guard (PMR-DMHH). */
44
+ localIdentity(): { pid: number; sessionFile: string | null }
45
+ hasStandaloneAwait(ref: string): boolean
46
+ consumeStandaloneAwait(ref: string): void
47
+ /** In-process per-ref latch; caller clears entries on /flow start. */
48
+ latch: Map<string, WakeLatchKind>
49
+ notify(message: string, level: 'info' | 'warning' | 'error'): void
50
+ /** The pi user-message injection seam, wired in index.ts. */
51
+ send(message: string): void
52
+ }
53
+
54
+ /** Paused-waiter ownership: same process (one pi process = one session), or
55
+ * the same session file resumed in a new process. Absent owner evidence or
56
+ * a mismatch → false (fail-closed: cross-process never wakes, ISC-13). */
57
+ export function ownsPausedRun(
58
+ owner: { pid: number; sessionFile: string | null } | undefined,
59
+ local: { pid: number; sessionFile: string | null },
60
+ ): boolean {
61
+ if (owner === undefined) return false
62
+ if (owner.pid === local.pid) return true
63
+ if (owner.sessionFile === null || local.sessionFile === null) return false
64
+ return owner.sessionFile === local.sessionFile
65
+ }
66
+
67
+ // AIDEV-NOTE: exact strings below are pinned verbatim by
68
+ // test/answer-wake.test.ts — edit test and template together.
69
+ function resumeMessage(ref: string): string {
70
+ return `flow answer: ${ref} approved — resuming the paused flow automatically (/flow ${ref})`
71
+ }
72
+
73
+ function inFlightMessage(ref: string): string {
74
+ return `flow answer: ${ref} already has a resume in flight — no second injection; if nothing resumes, run /flow ${ref} manually.`
75
+ }
76
+
77
+ function sendFailedMessage(ref: string, err: unknown): string {
78
+ return `flow answer wake failed for ${ref} (${String(err)}) — the receipt is recorded; run /flow ${ref} manually.`
79
+ }
80
+
81
+ function loopActiveMessage(ref: string, choice: AnswerChoice): string {
82
+ return `flow answer: ${ref} ${choice} recorded — the flow loop is active in this session, so no wake was injected; the running turn reads the receipt at its next gate check.`
83
+ }
84
+
85
+ function approveNoScopeMessage(ref: string, reason: string): string {
86
+ return `flow answer: ${ref} approve recorded — no auto-wake (${reason}). Resume manually with /flow ${ref} if the run should continue.`
87
+ }
88
+
89
+ function rejectNoScopeMessage(ref: string, reason: string): string {
90
+ return `flow answer: ${ref} reject recorded — no auto-wake (${reason}).`
91
+ }
92
+
93
+ function plainApproveWake(ref: string): string {
94
+ return `Spec approval recorded for ${ref}: the human ran /flow answer ${ref} approve. The receipt is the approval signal — proceed now: call the spec_approve tool with ref=${ref} (then spec_publish), then finish the standing plan-tail instructions. Do not wait for a spoken "approve". No flow loop is armed in this session: when the plan tail is complete, tell the human to run /flow ${ref} to start implement.`
95
+ }
96
+
97
+ function plainRejectWake(ref: string): string {
98
+ return `Spec gate rejected for ${ref}: the human ran /flow answer ${ref} reject. Do NOT call spec_approve and do NOT proceed to implement. Address the rejection — revise the plan/spec as the rejection directs and re-present it for review (plan-state stays "review"). The flow is not re-armed: after a revised approval is recorded (/flow answer ${ref} approve), this session wakes again automatically.`
99
+ }
100
+
101
+ /** Why no wake fires for a non-waking snapshot (also covers paused-foreign). */
102
+ function noWakeReason(state: FlowRunState | null): string {
103
+ if (state === null) return 'no run found'
104
+ if (state.loop === undefined) {
105
+ return 'no paused flow run or awaiting review in this session'
106
+ }
107
+ if (state.loop.status !== 'paused') {
108
+ return `latest snapshot is '${state.loop.status}'`
109
+ }
110
+ return 'paused run is not owned by this session'
111
+ }
112
+
113
+ /** Latch BEFORE send; a send throw clears the latch and degrades to a warning. */
114
+ function sendWithLatch(
115
+ ref: string,
116
+ kind: WakeLatchKind,
117
+ message: string,
118
+ deps: AnswerWakeDeps,
119
+ ): void {
120
+ deps.latch.set(ref, kind)
121
+ try {
122
+ deps.send(message)
123
+ } catch (err) {
124
+ deps.latch.delete(ref)
125
+ deps.notify(sendFailedMessage(ref, err), 'warning')
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Decide and (maybe) inject the wake for a recorded gate answer. Never
131
+ * throws: every effectful dep failure degrades to a notification.
132
+ */
133
+ export async function wakeOnGateAnswer(
134
+ ref: string,
135
+ gate: AnswerGate,
136
+ choice: AnswerChoice,
137
+ deps: AnswerWakeDeps,
138
+ ): Promise<void> {
139
+ // (1) Vestigial review-gate guard — kept fail-closed for untyped callers
140
+ // (the review gate itself was deleted, PMR-V31Z 7.1). Complete no-op.
141
+ if (gate !== 'spec') return
142
+
143
+ // (2) Latch supersede: a fresh human answer retires a 'plain' wake; a
144
+ // 'rearm' already in flight blocks a second injection.
145
+ const prior = deps.latch.get(ref)
146
+ if (prior === 'rearm') {
147
+ deps.notify(inFlightMessage(ref), 'info')
148
+ return
149
+ }
150
+ if (prior === 'plain') {
151
+ deps.latch.delete(ref)
152
+ }
153
+
154
+ // (3) A running loop reads the receipt at its next gate check itself.
155
+ if (deps.loopActive()) {
156
+ deps.notify(loopActiveMessage(ref, choice), 'info')
157
+ return
158
+ }
159
+
160
+ // (4) Fail-soft snapshot read: a throwing read counts as "no run found".
161
+ let state: FlowRunState | null = null
162
+ try {
163
+ state = await deps.readRunState(ref)
164
+ } catch {
165
+ state = null
166
+ }
167
+
168
+ const paused = state?.loop?.status === 'paused'
169
+ let owned = false
170
+ if (paused) {
171
+ owned = ownsPausedRun(state?.owner, deps.localIdentity())
172
+ }
173
+
174
+ if (choice === 'approve') {
175
+ // (5a) Rearm the paused loop — only when THIS session owns the waiter.
176
+ if (owned) {
177
+ deps.notify(resumeMessage(ref), 'info')
178
+ sendWithLatch(ref, 'rearm', `/flow ${ref}`, deps)
179
+ return
180
+ }
181
+ if (paused) {
182
+ deps.notify(
183
+ approveNoScopeMessage(ref, 'paused run is not owned by this session'),
184
+ 'info',
185
+ )
186
+ return
187
+ }
188
+ // (5b) Standalone session: the marker is in-process state, inherently
189
+ // this session — no ownership check applies.
190
+ if (deps.hasStandaloneAwait(ref)) {
191
+ deps.consumeStandaloneAwait(ref)
192
+ sendWithLatch(ref, 'plain', plainApproveWake(ref), deps)
193
+ return
194
+ }
195
+ deps.notify(approveNoScopeMessage(ref, noWakeReason(state)), 'info')
196
+ return
197
+ }
198
+
199
+ // (6) Reject: a refusal wake for the paused-owned loop or the standalone
200
+ // marker — never a `/flow` rearm. Consume any stale marker either way.
201
+ if (owned) {
202
+ deps.consumeStandaloneAwait(ref)
203
+ sendWithLatch(ref, 'plain', plainRejectWake(ref), deps)
204
+ return
205
+ }
206
+ if (deps.hasStandaloneAwait(ref)) {
207
+ deps.consumeStandaloneAwait(ref)
208
+ sendWithLatch(ref, 'plain', plainRejectWake(ref), deps)
209
+ return
210
+ }
211
+ deps.notify(rejectNoScopeMessage(ref, noWakeReason(state)), 'info')
212
+ }