@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,145 @@
1
+ // AIDEV-NOTE (PMR-HFK1, pi-flow observability M1): attribution env stamping
2
+ // for the MAIN process. The /flow loop is the root of the trace tree: run
3
+ // start stamps PI_FLOW_REF / PI_FLOW_PHASE / PI_FLOW_TRACEPARENT into the
4
+ // main process env, phase transitions re-stamp PI_FLOW_PHASE, and every
5
+ // terminal transition (halt, pause, done) clears all flow keys so a later
6
+ // non-flow session can never be misattributed to a dead run.
7
+ //
8
+ // Children do not inherit these by accident — the subagents package copies
9
+ // them into each `tab create --env` block (applyFlowEnv, pure) and adds
10
+ // PI_FLOW_SUBTASK for 1:1 worker spawns. The traceparent is W3C shape so a
11
+ // later telemetry module can join children onto the flow's trace tree.
12
+ //
13
+ // Every value is charset-validated BEFORE it enters env (the runFileName
14
+ // rule): a ref that can never be a filename can never be an env value.
15
+ import { randomBytes } from 'node:crypto'
16
+ import { FLOW_VALUE_RE, TRACEPARENT_RE } from '@gtheys/pi-interactive-subagents'
17
+
18
+ /** Env keys owned by this module (PI_FLOW_SUBTASK is child-only). */
19
+ export const FLOW_ENV_KEYS = [
20
+ 'PI_FLOW_REF',
21
+ 'PI_FLOW_PHASE',
22
+ 'PI_FLOW_TRACEPARENT',
23
+ // AIDEV-NOTE: work/personal separation. PI_FLOW_REF stays the AVEN ref (the
24
+ // journal + aven operations key on it); PI_FLOW_TRACK_REF is the ref humans
25
+ // TRACK the run by (the Jira key in work mode, the aven ref in personal
26
+ // mode) and is what telemetry/metrics/dashboards show. PI_FLOW_MODE is
27
+ // 'work' | 'personal'.
28
+ 'PI_FLOW_TRACK_REF',
29
+ 'PI_FLOW_MODE',
30
+ // AIDEV-NOTE (yolo plan 2.1): '1' when the run started with --yolo (no
31
+ // gates). Worker subagents read it to skip gate behavior.
32
+ 'PI_FLOW_YOLO',
33
+ ] as const
34
+
35
+ export type FlowEnv = Record<string, string | undefined>
36
+
37
+ function toHex(bytes: Uint8Array): string {
38
+ let out = ''
39
+ for (const byte of bytes) out += byte.toString(16).padStart(2, '0')
40
+ return out
41
+ }
42
+
43
+ /**
44
+ * Fresh W3C traceparent root: `00-<32-hex trace id>-<16-hex span id>-01`
45
+ * (16 + 8 bytes of randomness). Randomness is injected so tests are
46
+ * deterministic. A fresh root per /flow invocation (never reused across
47
+ * runs): a crashed run's env may survive in the process, and reusing its
48
+ * trace id would merge two invocations of the same (or worse, a different)
49
+ * ref into one trace tree. Cost rollup keys on PI_FLOW_REF, not the trace
50
+ * id, so per-invocation roots lose nothing.
51
+ */
52
+ export function newTraceparent(
53
+ rng: () => Uint8Array = () => randomBytes(24),
54
+ ): string {
55
+ const bytes = rng()
56
+ const traceId = toHex(bytes.subarray(0, 16))
57
+ const spanId = toHex(bytes.subarray(16, 24))
58
+ return `00-${traceId}-${spanId}-01`
59
+ }
60
+
61
+ export type StampResult = { ok: true } | { ok: false; reason: string }
62
+
63
+ /**
64
+ * Stamp a flow start into `env`: ref + phase + a fresh traceparent root.
65
+ * An invalid ref fails closed with a reason (the caller aborts the run —
66
+ * the journal filename would be unusable anyway).
67
+ */
68
+ export interface StampExtras {
69
+ /** Tracking ref (Jira key in work mode); falls back to `ref` when absent/invalid. */
70
+ trackRef?: string
71
+ mode?: 'work' | 'personal'
72
+ /** --yolo run: stamp PI_FLOW_YOLO for worker visibility. */
73
+ yolo?: boolean
74
+ }
75
+
76
+ export function stampFlowStart(
77
+ env: FlowEnv,
78
+ ref: string,
79
+ phase: string,
80
+ rng?: () => Uint8Array,
81
+ extras?: StampExtras,
82
+ ): StampResult {
83
+ if (!FLOW_VALUE_RE.test(ref)) {
84
+ return {
85
+ ok: false,
86
+ reason: `invalid flow ref "${ref}" (must match [A-Za-z0-9][A-Za-z0-9._-]{0,99})`,
87
+ }
88
+ }
89
+ if (!FLOW_VALUE_RE.test(phase)) {
90
+ return { ok: false, reason: `invalid flow phase "${phase}"` }
91
+ }
92
+ env.PI_FLOW_REF = ref
93
+ env.PI_FLOW_PHASE = phase
94
+ // a stale tracking ref/mode/yolo from a superseded run must never survive
95
+ delete env.PI_FLOW_TRACK_REF
96
+ delete env.PI_FLOW_MODE
97
+ delete env.PI_FLOW_YOLO
98
+ if (extras?.trackRef !== undefined && FLOW_VALUE_RE.test(extras.trackRef)) {
99
+ env.PI_FLOW_TRACK_REF = extras.trackRef
100
+ }
101
+ if (extras?.mode === 'work' || extras?.mode === 'personal') {
102
+ env.PI_FLOW_MODE = extras.mode
103
+ }
104
+ if (extras?.yolo === true) {
105
+ env.PI_FLOW_YOLO = '1'
106
+ }
107
+ let generated = newTraceparent(rng)
108
+ if (!TRACEPARENT_RE.test(generated)) {
109
+ // AIDEV-NOTE: defensive — an injected rng returning short byte arrays
110
+ // would produce a malformed root. Pad is impossible to do honestly, so
111
+ // fall back to real randomness rather than stamping a broken value.
112
+ generated = newTraceparent()
113
+ }
114
+ env.PI_FLOW_TRACEPARENT = generated
115
+ return { ok: true }
116
+ }
117
+
118
+ /** Re-stamp the phase on a transition (ref must already be stamped). */
119
+ export function stampFlowPhase(env: FlowEnv, phase: string): void {
120
+ if (!FLOW_VALUE_RE.test(phase)) return
121
+ env.PI_FLOW_PHASE = phase
122
+ }
123
+
124
+ /** Clear every flow env key — terminal transitions only. */
125
+ export function clearFlowEnv(env: FlowEnv): void {
126
+ for (const key of FLOW_ENV_KEYS) delete env[key]
127
+ delete env.PI_FLOW_SUBTASK
128
+ }
129
+
130
+ /**
131
+ * Which run journal a subagent spawn belongs to. The main process, while its
132
+ * loop runs, owns the full journal + projection path. A flow WORKER (scouts
133
+ * spawned by a plan agent, ...) has no running loop but inherited
134
+ * PI_FLOW_REF, so its spawns still belong to that flow — those go to the
135
+ * journal only (see recordRunEventJournalOnly). null = not part of any flow.
136
+ */
137
+ export function spawnJournalTarget(
138
+ activeRef: string | null,
139
+ env: FlowEnv,
140
+ ): { ref: string; nested: boolean } | null {
141
+ if (activeRef !== null) return { ref: activeRef, nested: false }
142
+ const envRef = env.PI_FLOW_REF
143
+ if (envRef === undefined || envRef.length === 0) return null
144
+ return { ref: envRef, nested: true }
145
+ }
@@ -0,0 +1,95 @@
1
+ // AIDEV-NOTE: Boundary for aven ref resolution (PMR-5900) — all shell-outs
2
+ // live here, decisions come from the pure ./aven-resolve.ts module.
3
+ // Resolution: plain `show` (cwd-inferred workspace) → `search` in the active
4
+ // workspace → iterate `workspace list`. An explicit override skips straight
5
+ // to `show --workspace <override>`.
6
+ // AIDEV-NOTE: AvenRunner's single definition lives in aven/client.ts
7
+ // (PMR-T22H); re-exported here so existing imports keep working.
8
+ import type { AvenRunner } from '../aven/client.ts'
9
+ import {
10
+ isUnknownRef,
11
+ overrideFailureReason,
12
+ parseWorkspaceList,
13
+ searchHasExactRef,
14
+ unknownRefFailureReason,
15
+ workspaceSearchOrder,
16
+ } from './aven-resolve.ts'
17
+
18
+ export type { AvenRunner } from '../aven/client.ts'
19
+
20
+ export type RefResolution =
21
+ | { ok: true; workspace?: string }
22
+ | { ok: false; reason: string }
23
+
24
+ function stderrOf(error: unknown): string | undefined {
25
+ const stderr = (error as { stderr?: unknown })?.stderr
26
+ if (typeof stderr === 'string') return stderr
27
+ const msg = error instanceof Error ? error.message : String(error)
28
+ return msg
29
+ }
30
+
31
+ export async function resolveAvenRef(
32
+ ref: string,
33
+ exec: AvenRunner,
34
+ workspaceOverride?: string,
35
+ ): Promise<RefResolution> {
36
+ if (workspaceOverride !== undefined) {
37
+ try {
38
+ await exec(['show', ref, '--json', '--workspace', workspaceOverride])
39
+ return { ok: true, workspace: workspaceOverride }
40
+ } catch (error: unknown) {
41
+ return {
42
+ ok: false,
43
+ reason: overrideFailureReason(
44
+ ref,
45
+ workspaceOverride,
46
+ stderrOf(error) ?? 'unknown error',
47
+ ),
48
+ }
49
+ }
50
+ }
51
+ try {
52
+ await exec(['show', ref, '--json'])
53
+ return { ok: true }
54
+ } catch (error: unknown) {
55
+ if (!isUnknownRef(stderrOf(error))) {
56
+ return {
57
+ ok: false,
58
+ reason: `aven show ${ref} failed: ${stderrOf(error) ?? 'unknown error'}`,
59
+ }
60
+ }
61
+ }
62
+ const tried: string[] = []
63
+ try {
64
+ const searched = await exec(['search', ref, '--json'])
65
+ if (searchHasExactRef(searched.stdout, ref)) {
66
+ return { ok: true }
67
+ }
68
+ } catch {
69
+ // active-workspace search unavailable — fall through to the sweep
70
+ }
71
+ let available: string[] = []
72
+ try {
73
+ available = parseWorkspaceList((await exec(['workspace', 'list'])).stdout)
74
+ } catch {
75
+ available = []
76
+ }
77
+ for (const workspace of workspaceSearchOrder(available, tried)) {
78
+ tried.push(workspace)
79
+ try {
80
+ const searched = await exec([
81
+ 'search',
82
+ ref,
83
+ '--json',
84
+ '--workspace',
85
+ workspace,
86
+ ])
87
+ if (!searchHasExactRef(searched.stdout, ref)) continue
88
+ await exec(['show', ref, '--json', '--workspace', workspace])
89
+ return { ok: true, workspace }
90
+ } catch {
91
+ // workspace unreachable or show failed — keep sweeping
92
+ }
93
+ }
94
+ return { ok: false, reason: unknownRefFailureReason(ref) }
95
+ }
@@ -0,0 +1,80 @@
1
+ // AIDEV-NOTE: Pure decision logic for aven ref resolution (PMR-5900).
2
+ // No I/O here — the boundary (index.ts / aven exec helpers) shells out and
3
+ // feeds observed outcomes into these functions. Fallback order:
4
+ // 1. `aven show <ref> --json` (fast path, implicit cwd-inferred workspace)
5
+ // 2. `aven search <ref> --json` in the active workspace
6
+ // 3. `aven workspace list`, then search each workspace in listed order
7
+ // until an exact ref match is found, then re-show with `--workspace <ws>`.
8
+ // An explicit `avenWorkspace` config override skips the whole dance.
9
+
10
+ /** aven's unknown-ref marker — seen on stderr as `error unknown-ref`. */
11
+ export function isUnknownRef(stderr: string | undefined): boolean {
12
+ return stderr?.includes('unknown-ref') === true
13
+ }
14
+
15
+ /** True when a search result array contains an entry whose ref matches exactly. */
16
+ export function searchHasExactRef(stdout: string, ref: string): boolean {
17
+ let parsed: unknown
18
+ try {
19
+ parsed = JSON.parse(stdout)
20
+ } catch {
21
+ return false
22
+ }
23
+ if (!Array.isArray(parsed)) return false
24
+ return parsed.some(
25
+ (entry) =>
26
+ typeof entry === 'object' &&
27
+ entry !== null &&
28
+ (entry as { ref?: unknown }).ref === ref,
29
+ )
30
+ }
31
+
32
+ /**
33
+ * Parse `aven workspace list` output (plain text, one workspace per line:
34
+ * `<name> key="..."`). Returns names in listed order.
35
+ */
36
+ export function parseWorkspaceList(stdout: string): string[] {
37
+ return stdout
38
+ .split('\n')
39
+ .map((line) => line.trim())
40
+ .filter((line) => line.length > 0)
41
+ .map((line) => line.split(/\s+/)[0])
42
+ .filter((name) => name.length > 0)
43
+ }
44
+
45
+ /** Workspaces still to search: listed order, minus already-tried, deduped. */
46
+ export function workspaceSearchOrder(
47
+ available: string[],
48
+ tried: string[],
49
+ ): string[] {
50
+ const triedSet = new Set(tried)
51
+ const seen = new Set<string>()
52
+ const order: string[] = []
53
+ for (const name of available) {
54
+ if (triedSet.has(name) || seen.has(name)) continue
55
+ seen.add(name)
56
+ order.push(name)
57
+ }
58
+ return order
59
+ }
60
+
61
+ /** Actionable failure message — never a bare unknown-ref (PMR-5900). */
62
+ export function unknownRefFailureReason(ref: string): string {
63
+ return (
64
+ `aven ref ${ref} not found in any workspace. ` +
65
+ `Fix one of: (1) one-time mapping \`aven project path add pi-my-rifle-ext <this-checkout-path>\`, ` +
66
+ `(2) set "avenWorkspace" in pi-flow config.json to the workspace holding ${ref}`
67
+ )
68
+ }
69
+
70
+ /** Actionable failure message for an explicit override that did not resolve. */
71
+ export function overrideFailureReason(
72
+ ref: string,
73
+ workspace: string,
74
+ cause: string,
75
+ ): string {
76
+ return (
77
+ `aven ref ${ref} could not be read in configured avenWorkspace "${workspace}": ${cause}. ` +
78
+ `Check the avenWorkspace value in pi-flow config.json and that ${ref} exists there`
79
+ )
80
+ }
@@ -0,0 +1,32 @@
1
+ // AIDEV-NOTE: PMR-DMHH — standalone awaiting-approval marker (subtask 1.2).
2
+ // Tracks refs whose /plan or /spec-review session is waiting for a recorded
3
+ // spec-gate answer, so a later `/flow answer <ref> …` can wake THIS session.
4
+ // Semantics:
5
+ // - STANDALONE SESSIONS ONLY: a flow loop pause needs no marker — the paused
6
+ // run-state snapshot is the signal. The marker exists because a standalone
7
+ // /plan or /spec-review session has no loop state to consult (research F6
8
+ // hazard 7: the receipt is the only approval evidence).
9
+ // - EXACT-REF SCOPING: the set is keyed by the exact ref string passed to
10
+ // /plan or /spec-review; lookups and consumption must use the same ref.
11
+ // - CONSUMPTION: consumeAwaitingSpecApproval is single-shot — one wake per
12
+ // mark; a re-arm requires a fresh mark from a new dispatch.
13
+ // - FLOW-START RETIREMENT: the /flow run-start path consumes any marker for
14
+ // the started ref — a real loop owns the ref now, so the standalone wake
15
+ // path is retired.
16
+ // - STALENESS POSTURE: fail-safe. A stale marker can at worst cause one
17
+ // extra scoped plain wake for that ref (never a loop re-arm, never a
18
+ // foreign-process wake — the marker is in-process module state, so it only
19
+ // exists in the session that set it).
20
+ const awaiting = new Set<string>()
21
+
22
+ export function markAwaitingSpecApproval(ref: string): void {
23
+ awaiting.add(ref)
24
+ }
25
+
26
+ export function isAwaitingSpecApproval(ref: string): boolean {
27
+ return awaiting.has(ref)
28
+ }
29
+
30
+ export function consumeAwaitingSpecApproval(ref: string): boolean {
31
+ return awaiting.delete(ref)
32
+ }
@@ -0,0 +1,68 @@
1
+ import {
2
+ type ResolvedWorktree,
3
+ type ReviewDeps,
4
+ resolveReviewWorktree,
5
+ } from '../tools/code-review-parse.ts'
6
+ import {
7
+ getActiveFlowRef,
8
+ getFlowWorktree,
9
+ setActiveFlowRef,
10
+ setFlowWorktree,
11
+ } from './worktree-context.ts'
12
+
13
+ export type HealResult =
14
+ | { ok: true; worktree: ResolvedWorktree; healed: boolean }
15
+ | { ok: false; reason: string; recovery: string }
16
+
17
+ /** Recovery hint surfaced to the human/agent when healing fails. */
18
+ export function recoveryCommand(ref: string): string {
19
+ return `/flow ${ref}`
20
+ }
21
+
22
+ // AIDEV-NOTE: PMR-DRKH — heal primitive for a lost/stale flow binding
23
+ // (module state dies on pi reload, PMR-PJM0). Resolve-only rule: when a
24
+ // DIFFERENT ref is live, we resolve for informational purposes but never
25
+ // mutate — the live flow owns the binding (PMR-1CCT/PMR-7ZEE). Mutation
26
+ // happens only when mayMutate (no live ref, or the ref we were asked to
27
+ // heal) AND needsRebind (the current binding differs from the resolution).
28
+ export async function healFlowBinding(
29
+ ref: string,
30
+ deps: ReviewDeps,
31
+ ): Promise<HealResult> {
32
+ let resolved: ResolvedWorktree
33
+ try {
34
+ resolved = await resolveReviewWorktree(ref, deps)
35
+ } catch (error) {
36
+ let reason: string
37
+ if (error instanceof Error) {
38
+ reason = error.message
39
+ } else {
40
+ reason = String(error)
41
+ }
42
+ return { ok: false, reason, recovery: recoveryCommand(ref) }
43
+ }
44
+
45
+ const live = getActiveFlowRef()
46
+ const mayMutate = live === null || live === ref
47
+
48
+ const binding = getFlowWorktree()
49
+ let needsRebind = true
50
+ if (
51
+ binding !== null &&
52
+ binding.ref === ref &&
53
+ binding.path === resolved.path &&
54
+ binding.branch === resolved.branch
55
+ ) {
56
+ needsRebind = false
57
+ }
58
+
59
+ if (mayMutate) {
60
+ if (needsRebind) {
61
+ setActiveFlowRef(ref)
62
+ setFlowWorktree(resolved.path, resolved.branch)
63
+ return { ok: true, worktree: resolved, healed: true }
64
+ }
65
+ return { ok: true, worktree: resolved, healed: false }
66
+ }
67
+ return { ok: true, worktree: resolved, healed: false }
68
+ }
@@ -0,0 +1,162 @@
1
+ // AIDEV-NOTE: automatic cost push at the end of a flow run. The manual
2
+ // `/flow-cost <ref> --push` step is what put cost metrics in Prometheus, so
3
+ // runs nobody pushed had no cost (and no per-phase bars). The loop now calls
4
+ // this on every terminal transition (done, halt, pause). Env-gated exactly
5
+ // like the manual push: PI_FLOW_PUSHGATEWAY_URL unset = nothing happens, not
6
+ // even a journal read. Idempotent — same-identity series are overwritten in
7
+ // place (official Pushgateway replaces the whole group; the homelab build
8
+ // merges on write, PMR-WBC2), so a rerun/resume simply refreshes the
9
+ // numbers. Never throws:
10
+ // failures become one warning, and /flow-cost remains the ground truth.
11
+ // AIDEV-NOTE (PMR-8MQH 4.2): this terminal push is no longer the ONLY push
12
+ // of a run — while a run is in flight the daemon's liveness pass
13
+ // (flow/liveness.ts) re-pushes the same full body every
14
+ // liveness.intervalMinutes so `status="running"` reaches the board (the
15
+ // DP-253 gap). Division of labour, both sides of it deliberate: in-flight
16
+ // refresh is the DAEMON's job (never this session-side hook), and the
17
+ // terminal push here stays the LAST writer for an ended run — the liveness
18
+ // pass re-gates the journal immediately before its POST precisely so it
19
+ // cannot land after this one.
20
+ // Same render path on both sides (buildPushBody), so a liveness body and
21
+ // a terminal body differ only in the status line.
22
+ // AIDEV-NOTE (PMR-2EGV 2.2): when the run's derived state retires the phase
23
+ // gauge (done/stale — isPhaseRetiredState), the terminal POST is preceded by
24
+ // the GUARDED purge (flow/terminal-purge.ts): read the stored group back,
25
+ // DELETE it only when the fresh body provably contains every stored series
26
+ // except pi_flow_phase/pi_flow_step, then POST as before. The gateway merges
27
+ // on write, so without the DELETE the phase stored while the run was active
28
+ // would be served forever. Halted/waiting runs keep the plain POST — a
29
+ // halted run is still IN its phase. Every purge failure mode degrades to a
30
+ // warning plus the plain POST; the push itself is never blocked.
31
+ import { buildPushBody } from './cost.ts'
32
+ import { computeCostRollup, type FlowCostDeps } from './cost-command.ts'
33
+ import type { GroupBodyResult, PushResult } from './push.ts'
34
+ import { deriveV2State, isPhaseRetiredState } from './state-metrics.ts'
35
+ import {
36
+ purgeTerminalResidue,
37
+ type TerminalPurgeOutcome,
38
+ } from './terminal-purge.ts'
39
+
40
+ export interface CostAutoPushDeps extends FlowCostDeps {
41
+ /** True when a Pushgateway URL is configured (env PI_FLOW_PUSHGATEWAY_URL). */
42
+ enabled: () => boolean
43
+ notify: (message: string, level: 'info' | 'warning') => void
44
+ /**
45
+ * PMR-2EGV: read one stored group back (full-dump GET, filtered — the
46
+ * push.ts fetchGroupBody, pre-bound to URL/token by the wiring). Only
47
+ * called on terminal (done/stale) publications, after the enabled() gate.
48
+ */
49
+ fetchGroupBody: (
50
+ ref: string,
51
+ mode: 'work' | 'personal',
52
+ ) => Promise<GroupBodyResult>
53
+ /**
54
+ * PMR-2EGV: DELETE one stored group (the push.ts deleteGroup, pre-bound).
55
+ * Called only when the purge guard proved the fresh body a superset.
56
+ */
57
+ deleteGroup: (ref: string, mode: 'work' | 'personal') => Promise<PushResult>
58
+ /**
59
+ * Let the journal's fire-and-forget appends land before re-reading it
60
+ * (the loop writes phase-complete / "flow complete" right before it ends
61
+ * the run). Default 1500 ms; tests inject an immediate resolver.
62
+ */
63
+ settle?: () => Promise<void>
64
+ }
65
+
66
+ /** Turn a non-clean purge outcome into the warning that names the recovery. */
67
+ function purgeWarning(ref: string, outcome: TerminalPurgeOutcome): string {
68
+ if (outcome.kind === 'skipped') {
69
+ return `${ref}: terminal purge SKIPPED (${outcome.reason}) — stored pi_flow_phase/pi_flow_step residue left in place; remove it with the manual runbook (DELETE the pushgateway group, then /flow-cost ${ref} --push).`
70
+ }
71
+ if (outcome.kind === 'read-failed') {
72
+ return `${ref}: terminal purge could not read the stored group (${outcome.error}) — pushing without cleanup; stored phase residue may survive. Once the gateway recovers, use the manual runbook: DELETE the pushgateway group, then run /flow-cost ${ref} --push.`
73
+ }
74
+ if (outcome.kind === 'delete-failed') {
75
+ return `${ref}: terminal purge DELETE failed (${outcome.error}) — pushing without cleanup; stored phase residue may survive. Use the manual runbook: DELETE the pushgateway group, then run /flow-cost ${ref} --push.`
76
+ }
77
+ return ''
78
+ }
79
+
80
+ export function createCostAutoPush(
81
+ deps: CostAutoPushDeps,
82
+ ): (ref: string) => Promise<void> {
83
+ return async (ref) => {
84
+ if (!deps.enabled()) return
85
+ try {
86
+ const settle =
87
+ deps.settle ?? (() => new Promise<void>((r) => setTimeout(r, 1500)))
88
+ await settle()
89
+ const rollup = await computeCostRollup(ref, deps)
90
+ if (rollup.kind !== 'ok') return
91
+ const body = buildPushBody(
92
+ rollup.trackRef,
93
+ rollup.rows,
94
+ rollup.durations,
95
+ rollup.events,
96
+ )
97
+ // PMR-2EGV: only a done/stale publication purges. Halted keeps its
98
+ // phase (the run may resume); waiting/running are not terminal at all.
99
+ // rollup.events is optional on the CostRollup type; an absent list
100
+ // derives a null state, which isPhaseRetiredState treats as non-terminal.
101
+ let purged = false
102
+ if (isPhaseRetiredState(deriveV2State(rollup.events ?? []))) {
103
+ const outcome = await purgeTerminalResidue(
104
+ {
105
+ fetchGroupBody: deps.fetchGroupBody,
106
+ deleteGroup: deps.deleteGroup,
107
+ },
108
+ rollup.trackRef,
109
+ rollup.mode,
110
+ body,
111
+ )
112
+ if (outcome.kind === 'purged') {
113
+ purged = true
114
+ deps.notify(
115
+ `${ref}: terminal purge removed stored pi_flow_phase/pi_flow_step residue.`,
116
+ 'info',
117
+ )
118
+ } else if (outcome.kind !== 'no-residue') {
119
+ deps.notify(purgeWarning(ref, outcome), 'warning')
120
+ }
121
+ }
122
+ let result = await deps.push(rollup.trackRef, body, rollup.mode)
123
+ // AIDEV-NOTE (PMR-30AC): a successful purge DELETE removed the WHOLE
124
+ // stored group, so a failed terminal POST leaves the done run's group
125
+ // EMPTY — and nothing else recovers done runs (the liveness pass only
126
+ // re-pushes in-flight runs). Retry the POST exactly once with the
127
+ // identical terminal body, mirroring the reconcile pass's bounded
128
+ // DELETE→POST retry (runReconcilePass in flow/reconcile.ts). Only the
129
+ // purge path retries: without a DELETE the stored group is intact, so
130
+ // the plain /flow-cost warning below stays the recovery story.
131
+ if (result.ok === false && purged) {
132
+ result = await deps.push(rollup.trackRef, body, rollup.mode)
133
+ if (result.ok) {
134
+ deps.notify(
135
+ `${ref}: cost metrics pushed to the pushgateway on retry — group restored after the terminal purge.`,
136
+ 'info',
137
+ )
138
+ return
139
+ }
140
+ deps.notify(
141
+ `${ref}: automatic cost push FAILED after the terminal purge (${result.error ?? 'unknown error'}, retried once) — the pushgateway group may be EMPTY; restore it with /flow-cost ${ref} --push.`,
142
+ 'warning',
143
+ )
144
+ return
145
+ }
146
+ if (result.ok) {
147
+ deps.notify(`${ref}: cost metrics pushed to the pushgateway.`, 'info')
148
+ return
149
+ }
150
+ deps.notify(
151
+ `${ref}: automatic cost push FAILED (${result.error ?? 'unknown error'}) — run /flow-cost ${ref} --push to retry.`,
152
+ 'warning',
153
+ )
154
+ } catch (error) {
155
+ const message = error instanceof Error ? error.message : String(error)
156
+ deps.notify(
157
+ `${ref}: automatic cost push failed (${message}) — run /flow-cost ${ref} --push to retry.`,
158
+ 'warning',
159
+ )
160
+ }
161
+ }
162
+ }