@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,287 @@
1
+ import {
2
+ type FlowPhase,
3
+ type FlowRunEvent,
4
+ type FlowRunState,
5
+ type LoopRunStatus,
6
+ type OwnerRecord,
7
+ projectRunState,
8
+ runFileName,
9
+ } from '../run-state.ts'
10
+ import {
11
+ isParkedLoop,
12
+ type PendingIo,
13
+ pendingPaths,
14
+ } from '../server/pending.ts'
15
+
16
+ // AIDEV-NOTE: PMR-DRKH — leaf module for deriving candidate flow refs from
17
+ // durable pending-run records (used by binding self-heal / worktree bind).
18
+ // All paths and IO are injected; this module must never call getAgentDir()
19
+ // itself so tests can run against fakes and consumers control resolution.
20
+ // AIDEV-NOTE: PMR-T9ZQ — the scan body is shared (scanRunStates) between
21
+ // deriveFlowRefs (plain refs, binding self-heal) and deriveParkedCandidates
22
+ // (rich records for the parked-run resume picker). Both mappers keep the
23
+ // same base filters (gitRoot match, non-terminal loop) and the same
24
+ // parked-first order — the picker and the self-heal have to agree on what
25
+ // is live; test/durable-refs-candidates.test.ts pins that equality.
26
+ // AIDEV-NOTE: PMR-RRW9 — the two mappers no longer share the FULL filter
27
+ // set: deriveFlowRefs additionally drops records owned by a LIVE foreign
28
+ // session (owner-scoped adoption, isForeignLiveOwner below), because a
29
+ // worktree bind must never adopt another running session's flow. The
30
+ // picker deliberately keeps the wider scan — it puts every candidate in
31
+ // front of the human with an owner-liveness hint (flow/resume-picker.ts),
32
+ // so the human, not the scan, arbitrates there.
33
+ //
34
+ // DERIVATION-ONLY RULES (PMR-DRKH gotcha 5, consent gate added by PMR-T9ZQ):
35
+ // this scan is a *derivation*, never a consumption — only consumePending
36
+ // (server/pending.ts) may consume a record. Two consumers, two rules:
37
+ // - deriveFlowRefs (worktree bind self-heal) keeps the SINGLE-CANDIDATE
38
+ // rule: zero or multiple → refuse, never guess across refs.
39
+ // - deriveParkedCandidates (the resume picker) may NOT act on its own at
40
+ // all: index.ts's askResumeThenArm gate puts every candidate in front of
41
+ // the human and adopts exactly the picked ref. The gate runs strictly
42
+ // BEFORE consumePending, so a declined/headless session never renames a
43
+ // pending record (the old automatic single-candidate takeover is gone).
44
+
45
+ const NON_TERMINAL: readonly LoopRunStatus[] = ['running', 'paused']
46
+
47
+ export interface DurableRefDeps {
48
+ pendingDir: string
49
+ io: Pick<PendingIo, 'readdir' | 'readFile'>
50
+ readRunEvents: (
51
+ agentDir: string,
52
+ ref: string,
53
+ io?: { readFile: (p: string) => Promise<string> },
54
+ ) => Promise<FlowRunEvent[] | null>
55
+ agentDir: string
56
+ gitRoot: string
57
+ /**
58
+ * AIDEV-NOTE: PMR-RRW9 — bind-adoption owner filter inputs, consumed by
59
+ * deriveFlowRefs ONLY (deriveParkedCandidates keeps the wide scan).
60
+ * `callerSessionFile` is the calling session's main session file (null
61
+ * when the caller has none); `pidAlive` is the owner-pid liveness probe
62
+ * (production injects ownerPidAlive from flow/resume-picker.ts). Both
63
+ * optional: when `pidAlive` is absent the scan keeps the legacy
64
+ * owner-agnostic behavior (tests and pre-PMR-RRW9 callers).
65
+ * AIDEV-NOTE: PMR-3N9N — `callerPid` is the calling process's own pid,
66
+ * injected at the production seam (this module never reads process.pid
67
+ * itself) so a live owner with a null sessionFile can still be proven
68
+ * to be the caller (headless flows journal no session file). Absent =>
69
+ * fail closed, exactly as before.
70
+ * AIDEV-NOTE: PMR-MG9S — omitting `callerSessionFile` while injecting
71
+ * `pidAlive` fails CLOSED for every live-owned record: no owner
72
+ * sessionFile can be compared, so even a record owned by the caller is
73
+ * classified as foreign and skipped by deriveFlowRefs. The single
74
+ * exception is PMR-3N9N above: a live null-sessionFile owner whose pid
75
+ * exactly matches an injected `callerPid` stays adoptable. Production
76
+ * injects `callerSessionFile`, `callerPid`, and `pidAlive`, so this is
77
+ * a wiring sharp edge for alternate callers, not a current behavior bug.
78
+ */
79
+ callerSessionFile?: string | null
80
+ callerPid?: number
81
+ pidAlive?: (pid: number) => boolean
82
+ }
83
+
84
+ function isCandidateName(name: string): boolean {
85
+ return name.endsWith('.json') && !name.endsWith('.consumed.json')
86
+ }
87
+
88
+ function keepRef(state: FlowRunState, gitRoot: string): boolean {
89
+ if (state.input === undefined) return false
90
+ if (state.input.gitRoot !== gitRoot) return false
91
+ if (state.loop === undefined) return false
92
+ return NON_TERMINAL.includes(state.loop.status)
93
+ }
94
+
95
+ /**
96
+ * AIDEV-NOTE: PMR-RRW9 — true when the record's journaled owner is a LIVE
97
+ * session that is not provably the caller, so bind adoption must skip it
98
+ * (the PMR-B033 incident: bind adopted a different session's live flow in
99
+ * the same repo). Kept adoptable: records without an owner (pre-owner
100
+ * journals), records whose owner pid is dead (the cross-session restart
101
+ * resume PMR-DRKH/PMR-T9ZQ were built for), and records whose owner
102
+ * sessionFile matches the caller. FAIL-CLOSED: a live owner with no
103
+ * sessionFile (or a caller with none to compare) cannot be proven to be
104
+ * the caller, so it is treated as foreign — with ONE exemption
105
+ * (PMR-3N9N): a live owner whose pid exactly matches the injected
106
+ * `callerPid` IS the caller (headless flows journal no session file, so
107
+ * after a reload in the same process the pid is the only identity left).
108
+ * When no liveness probe is injected the legacy owner-agnostic behavior
109
+ * is preserved.
110
+ */
111
+ function isForeignLiveOwner(
112
+ state: FlowRunState,
113
+ deps: DurableRefDeps,
114
+ ): boolean {
115
+ if (deps.pidAlive === undefined) return false
116
+ const owner = state.owner
117
+ if (owner === undefined) return false
118
+ if (!deps.pidAlive(owner.pid)) return false
119
+ if (owner.sessionFile === null) {
120
+ // AIDEV-NOTE: PMR-3N9N — self-owned headless run: only an EXACT
121
+ // live self-PID match exempts; absent callerPid or any other pid
122
+ // stays fail-closed foreign.
123
+ if (deps.callerPid !== undefined && owner.pid === deps.callerPid) {
124
+ return false
125
+ }
126
+ return true
127
+ }
128
+ return owner.sessionFile !== deps.callerSessionFile
129
+ }
130
+
131
+ /**
132
+ * AIDEV-NOTE: PMR-T9ZQ — one rich record per live candidate run, derived
133
+ * from the same scan as deriveFlowRefs. `phase` is the journaled current
134
+ * phase, `status` the loop status, `updatedAt` the last run-activity stamp
135
+ * (owner refreshes never move it), `owner` is absent for runs journaled
136
+ * before the owner-session event (the picker then renders no liveness
137
+ * hint), and `hasWorktree` reports whether a worktree-create effect was
138
+ * ever declared for the run.
139
+ */
140
+ export interface ParkedCandidate {
141
+ ref: string
142
+ phase: FlowPhase | null
143
+ status: LoopRunStatus
144
+ updatedAt: string
145
+ owner?: OwnerRecord
146
+ hasWorktree: boolean
147
+ }
148
+
149
+ // AIDEV-NOTE: PMR-T9ZQ — one scanned live record; `parked` is the
150
+ // awaitingOutcome flag the resume picker (flow/resume-picker.ts) labels with,
151
+ // and it also decides the parked-first ordering below.
152
+ interface ScannedRun {
153
+ ref: string
154
+ state: FlowRunState
155
+ parked: boolean
156
+ }
157
+
158
+ function hasWorktreeDeclared(state: FlowRunState): boolean {
159
+ const declarations = state.effectDeclarations
160
+ if (declarations === undefined) return false
161
+ return declarations.some((d) => d.effect === 'worktree-create')
162
+ }
163
+
164
+ /**
165
+ * Shared scan: pending records that are still live for the given repo
166
+ * (latest journaled input.gitRoot matches, loop status non-terminal).
167
+ * Parked runs (awaitingOutcome) come before paused/running. Missing or
168
+ * unreadable journals are silently skipped; readdir failure yields an empty
169
+ * list — this never throws.
170
+ */
171
+ async function scanRunStates(deps: DurableRefDeps): Promise<ScannedRun[]> {
172
+ let names: string[]
173
+ try {
174
+ names = await deps.io.readdir(deps.pendingDir)
175
+ } catch {
176
+ return []
177
+ }
178
+
179
+ const parked: ScannedRun[] = []
180
+ const active: ScannedRun[] = []
181
+ for (const name of names) {
182
+ if (!isCandidateName(name)) continue
183
+ const ref = name.slice(0, -'.json'.length)
184
+ // Charset guard via runFileName + pendingPaths: a derived ref must map
185
+ // back to exactly this filename, else it can never be a pending record.
186
+ const paths = pendingPaths(deps.pendingDir, ref)
187
+ if (paths.pendingPath === null) continue
188
+ if (runFileName(ref) !== name) continue
189
+
190
+ const events = await deps.readRunEvents(deps.agentDir, ref, {
191
+ readFile: deps.io.readFile,
192
+ })
193
+ if (events === null) continue
194
+ const state = projectRunState(events)
195
+ if (state === null) continue
196
+ if (!keepRef(state, deps.gitRoot)) continue
197
+
198
+ // isParkedLoop is typed over LoopStateRecord; project here for the check.
199
+ const entry: ScannedRun = {
200
+ ref,
201
+ state,
202
+ parked: isParkedLoop(state.loop),
203
+ }
204
+ if (entry.parked) {
205
+ parked.push(entry)
206
+ } else {
207
+ active.push(entry)
208
+ }
209
+ }
210
+ return [...parked, ...active]
211
+ }
212
+
213
+ /**
214
+ * Scan <pendingDir> for pending records and return refs that are still
215
+ * live for the given repo: latest journaled input.gitRoot matches and the
216
+ * loop state is non-terminal (running/paused). Parked runs
217
+ * (awaitingOutcome) sort before paused/running. Records owned by a LIVE
218
+ * foreign session are dropped (owner-scoped adoption, PMR-RRW9 — see
219
+ * isForeignLiveOwner; deriveParkedCandidates deliberately does NOT apply
220
+ * this filter). Any candidate whose journal is missing or unreadable is
221
+ * silently skipped; readdir failure yields an empty list — this function
222
+ * never throws.
223
+ */
224
+ /**
225
+ * AIDEV-NOTE: PMR-YN61 — detailed bind-adoption derivation: the same scan
226
+ * and the same owner-scoped filter as deriveFlowRefs, but the refs dropped
227
+ * by the foreign-live-owner filter are returned alongside instead of
228
+ * vanishing. The worktree bind refusal uses `foreignSkipped` to name each
229
+ * filtered live foreign run and its `/flow <ref>` recovery command — it
230
+ * NEVER adopts them (they are not in `refs`). `deriveFlowRefs` keeps its
231
+ * plain string[] contract for its other callers by projecting `refs`.
232
+ */
233
+ export interface FlowRefDerivation {
234
+ refs: string[]
235
+ foreignSkipped: string[]
236
+ }
237
+
238
+ export async function deriveFlowRefsDetailed(
239
+ deps: DurableRefDeps,
240
+ ): Promise<FlowRefDerivation> {
241
+ const entries = await scanRunStates(deps)
242
+ const refs: string[] = []
243
+ const foreignSkipped: string[] = []
244
+ for (const entry of entries) {
245
+ if (isForeignLiveOwner(entry.state, deps)) {
246
+ foreignSkipped.push(entry.ref)
247
+ continue
248
+ }
249
+ refs.push(entry.ref)
250
+ }
251
+ return { refs, foreignSkipped }
252
+ }
253
+
254
+ export async function deriveFlowRefs(deps: DurableRefDeps): Promise<string[]> {
255
+ const derivation = await deriveFlowRefsDetailed(deps)
256
+ return derivation.refs
257
+ }
258
+
259
+ /**
260
+ * AIDEV-NOTE: PMR-T9ZQ — rich variant of deriveFlowRefs for the parked-run
261
+ * resume picker: same scan, same base filters and parked-first order, but one
262
+ * ParkedCandidate per ref carrying what the menu label and the owner hint
263
+ * need. Pure derivation (no consumption, no side effects).
264
+ */
265
+ export async function deriveParkedCandidates(
266
+ deps: DurableRefDeps,
267
+ ): Promise<ParkedCandidate[]> {
268
+ const entries = await scanRunStates(deps)
269
+ const candidates: ParkedCandidate[] = []
270
+ for (const entry of entries) {
271
+ const state = entry.state
272
+ // keepRef guarantees a non-terminal loop; the guard keeps that fact in
273
+ // the type system instead of a non-null assertion.
274
+ const loop = state.loop
275
+ if (loop === undefined) continue
276
+ const candidate: ParkedCandidate = {
277
+ ref: entry.ref,
278
+ phase: state.currentPhase,
279
+ status: loop.status,
280
+ updatedAt: state.updatedAt,
281
+ hasWorktree: hasWorktreeDeclared(state),
282
+ }
283
+ if (state.owner !== undefined) candidate.owner = state.owner
284
+ candidates.push(candidate)
285
+ }
286
+ return candidates
287
+ }
@@ -0,0 +1,137 @@
1
+ // AIDEV-NOTE: PMR-VDVJ phase 2 — pure effect gate. The validation seam
2
+ // (buildEffectDeclaration) lives in run-state.ts since PMR-5ME4 so the
3
+ // journal's declare() can enforce it on the production write path without an
4
+ // import cycle; this module re-exports it and carries DEFAULT_RECIPES (the
5
+ // plain-language undo steps shown to the agent on declaration, ISC-4).
6
+ // The active matchers are the stray-merge block — MERGE_RE + mergeIntercept,
7
+ // unconditional while a flow ref is active (PMR-VZEV; PMR-V31Z 4.1 removed
8
+ // the authorization escape) — and the R4 runs-journal forge blocker
9
+ // (runsJournalWrite / runsJournalWriteBlock). The PMR-5NZB 3.1 rebase
10
+ // start-form interceptor (REBASE_RE + rebaseBashIntercept) was deleted in
11
+ // PMR-V31Z 6.1 with the sanctioned-rebase subsystem it guarded: rebase
12
+ // start-forms are no longer intercepted during flows. All pure — no fs, no
13
+ // git, no clock (timestamp is injected via the `now` parameter for
14
+ // testability).
15
+
16
+ import type { EffectKind } from '../run-state.ts'
17
+ import {
18
+ CMD_START,
19
+ GIT_OPTS,
20
+ type LandingInterceptDecision,
21
+ } from './land-gate.ts'
22
+
23
+ // AIDEV-NOTE: plain-language undo steps per effect kind. These are shown to
24
+ // the agent when the effect is declared (ISC-4) so recovery is always at hand.
25
+ // Exactly the shrunk EffectKind set (PMR-V31Z 6.1 retired the merge-main and
26
+ // rebase-flow recipes with their kinds).
27
+ export const DEFAULT_RECIPES: Record<EffectKind, string[]> = {
28
+ 'git-push': [
29
+ 'nothing local to undo — a push moves the remote branch; recover remote-side: git revert <range> on the remote branch, or git push origin --delete <branch> if the push itself was mistaken',
30
+ ],
31
+ 'gh-pr-create': [
32
+ 'close the PR: gh pr close <number> --delete-branch; if it already merged, git revert the merge on the remote base branch',
33
+ ],
34
+ 'worktree-create': [
35
+ 'remove the half-created worktree: herdr worktree remove --workspace <id> (or git worktree remove <path>)',
36
+ 'clear the pre-recorded flow base: git config --unset flow-base.<branch>',
37
+ ],
38
+ 'worktree-remove': [
39
+ 're-create it: worktree tool action=create with branch=<branch> (commits live in the shared store — removal alone deletes nothing)',
40
+ 're-bind it to the flow: worktree tool action=bind',
41
+ ],
42
+ // AIDEV-NOTE: PMR-DMZR — a workspace-close only ever targets a PROVEN
43
+ // dangling workspace (checkout gone, no agents), so there is nothing to
44
+ // recover; the recipe states that instead of a fake undo step.
45
+ 'workspace-close': [
46
+ 'the closed workspace was proven dangling (checkout path gone, absent from herdr worktree list, no agents attached) — nothing to recover; if the worktree is needed again: worktree tool action=create branch=<branch>',
47
+ ],
48
+ }
49
+
50
+ // AIDEV-NOTE: command position = start, or after any shell separator, a
51
+ // subshell opener, a backtick or $( — but NOT after a quote (same grammar as
52
+ // land-gate's CMD_START). The negative lookahead (?![\w-]) is load-bearing
53
+ // (ISC-10): git merge-base / merge-file / merge-tree must NEVER match, while
54
+ // `git merge`, `git -C /path merge --ff-only x`, `git merge --abort` do.
55
+ // Known limit (guardrail, not a privilege boundary, same as land-gate
56
+ // PMR-4Y1Z): aliases, `sh -c '...'`, and variable-built commands are not
57
+ // detected.
58
+ const MERGE_RE = new RegExp(`${CMD_START}git${GIT_OPTS}\\s+merge(?![\\w-])`)
59
+
60
+ // Matches bash merge commands at command position (see MERGE_RE). Returns the
61
+ // active ref the block reason should name, or null when the command is
62
+ // allowed. Only called while a flow ref is active — never globally.
63
+ export function mergeBashBlock(
64
+ command: string,
65
+ activeRef: string | null,
66
+ ): string | null {
67
+ if (activeRef === null) return null
68
+ if (!MERGE_RE.test(command)) return null
69
+ return `merges are blocked while flow ${activeRef} is active — the flow delivers via its GitHub PR; call the flow_land tool (ref=${activeRef}) to authorize the git push / gh pr create step`
70
+ }
71
+
72
+ // AIDEV-NOTE: PMR-V31Z 4.1 — pure decision behind the index.ts tool_call
73
+ // interceptor. While a flow is active EVERY git-merge form is blocked and
74
+ // there is NO clear path: the flow's delivery is its GitHub PR (flow_land
75
+ // authorizes the git push / gh pr create step), never a local merge.
76
+ // PMR-VZEV's one-shot mergeAuthorized pin is gone with the merge-main
77
+ // landing route.
78
+ export function mergeIntercept(
79
+ command: string,
80
+ activeRef: string | null,
81
+ ): LandingInterceptDecision {
82
+ if (activeRef === null) return { action: 'allow', clear: false }
83
+ const reason = mergeBashBlock(command, activeRef)
84
+ if (reason === null) return { action: 'allow', clear: false }
85
+ return { action: 'block', reason }
86
+ }
87
+
88
+ // AIDEV-NOTE: PMR-5NZB 3.1 (R4) — runs-journal forge blocker. The pi-flow
89
+ // runs journal (getAgentDir()/pi-flow/runs/<ref>.json + .journal.jsonl,
90
+ // see run-state.ts) is the extension's evidence record: effect declarations
91
+ // and receipts are written ONLY by pi-flow's own journal writers. A model
92
+ // bash command that appends/redirects onto that path would forge the receipt
93
+ // surface (R4), so write-shaped commands targeting it are blocked while a
94
+ // flow ref is active. This is guardrail hardening, NOT a security boundary
95
+ // (same doctrine as the merge/landing matchers): reads (cat/grep/jq/tail)
96
+ // stay allowed, and the known limits stand — aliases, `sh -c '...'`,
97
+ // variable-built paths, and writers outside the matched set (cp/mv/rm onto
98
+ // the path) are not detected.
99
+ const RUNS_PATH = 'pi-flow/runs/'
100
+ const JOURNAL_REDIRECT_RE =
101
+ /(?:^|[\s;&|()])\d?>{1,2}\s*["']?[^\s"';|&]*pi-flow\/runs\//
102
+ const JOURNAL_TEE_RE = /\btee\b(?:\s+-\S+)*\s+["']?[^\s"';|&]*pi-flow\/runs\//
103
+ const JOURNAL_DD_RE = /\bdd\b[^;&|]*\bof=["']?[^\s"']*pi-flow\/runs\//
104
+ const JOURNAL_SED_RE = /\bsed\b[^;&|]*\s-i\S*[^;&|]*pi-flow\/runs\//
105
+
106
+ // True when the command writes/appends/redirects onto a pi-flow/runs path.
107
+ // Pure string matcher — active-ref gating lives in runsJournalWriteBlock.
108
+ export function runsJournalWrite(command: string): boolean {
109
+ if (!command.includes(RUNS_PATH)) return false
110
+ if (JOURNAL_REDIRECT_RE.test(command)) return true
111
+ if (JOURNAL_TEE_RE.test(command)) return true
112
+ if (JOURNAL_DD_RE.test(command)) return true
113
+ if (JOURNAL_SED_RE.test(command)) return true
114
+ return false
115
+ }
116
+
117
+ // Returns the block reason when a write-shaped command targets the runs
118
+ // journal while a flow ref is active, or null when allowed.
119
+ export function runsJournalWriteBlock(
120
+ command: string,
121
+ activeRef: string | null,
122
+ ): string | null {
123
+ if (activeRef === null) return null
124
+ if (!runsJournalWrite(command)) return null
125
+ return 'the pi-flow/runs journal is extension-governed — effect declarations and receipts are written by pi-flow tools; model bash writes to it would forge the evidence record'
126
+ }
127
+
128
+ // AIDEV-NOTE: PMR-5ME4 — buildEffectDeclaration moved to run-state.ts (its
129
+ // dependencies — EFFECT_KINDS, effectDeclarationId, runFileName,
130
+ // EffectDeclarationRecord, isFullSha — live there or alongside, and the
131
+ // journal's declare() must run it on the production write path without an
132
+ // import cycle). Re-exported here so the single validation seam stays
133
+ // importable from the gate module for tests and future consumers.
134
+ export {
135
+ buildEffectDeclaration,
136
+ type EffectDeclarationResult,
137
+ } from '../run-state.ts'
@@ -0,0 +1,44 @@
1
+ // AIDEV-NOTE: Pure failure classification for the best-effort label
2
+ // bootstrap (PMR-SE93). No I/O — the boundary in index.ts shells out and
3
+ // feeds the thrown error here, then acts on the kind:
4
+ // aven-missing → one visible warning; gates will fail-closed later
5
+ // already-exists → fine, silent
6
+ // other → surfaced warning with stderr included
7
+ // Classification stays best-effort: any of these must never break startup.
8
+
9
+ export type LabelFailureKind = 'aven-missing' | 'already-exists' | 'other'
10
+
11
+ export interface LabelFailure {
12
+ kind: LabelFailureKind
13
+ /** stderr or message text, for the "other" surface-the-error warning. */
14
+ detail?: string
15
+ }
16
+
17
+ function errorText(error: unknown): string | undefined {
18
+ const stderr = (error as { stderr?: unknown })?.stderr
19
+ if (typeof stderr === 'string' && stderr.length > 0) return stderr
20
+ if (error instanceof Error) return error.message
21
+ if (typeof error === 'string') return error
22
+ return undefined
23
+ }
24
+
25
+ // AIDEV-NOTE: PMR-XQ7Y — the 'already exists' text match is legacy
26
+ // defence only: current `aven label create` is idempotent (a duplicate
27
+ // prints created-label and exits 0, verified), so this branch is normally
28
+ // unreachable. aven exposes no distinct exit code for it.
29
+ // AIDEV-TODO: drop the message match if aven stays idempotent; key off an
30
+ // exit code if aven ever reintroduces a duplicate error with one.
31
+ export function classifyLabelFailure(error: unknown): LabelFailure {
32
+ const code = (error as { code?: unknown })?.code
33
+ if (code === 'ENOENT') {
34
+ return { kind: 'aven-missing' }
35
+ }
36
+ const text = errorText(error)
37
+ if (text?.includes('already exists')) {
38
+ return { kind: 'already-exists' }
39
+ }
40
+ if (text !== undefined) {
41
+ return { kind: 'other', detail: text }
42
+ }
43
+ return { kind: 'other' }
44
+ }
package/flow/frame.ts ADDED
@@ -0,0 +1,172 @@
1
+ // AIDEV-NOTE (PMR-MGWP): pure framing helper for the flow-status widget —
2
+ // wraps plain status lines in a rounded box (╭─╮ │ │ ╰─╯) modeled on
3
+ // boxWidgetLines in pi-interactive-subagents (subagents/index.ts), but the
4
+ // frame color comes from the ACTIVE flow phase via Pi theme roles
5
+ // (theme.fg), never hardcoded RGB. Byte-shaping of the inner content lives
6
+ // HERE (indentation, blank separators, the PMR-X7BH styling pass: ✅ swap
7
+ // with 4-col mark-column normalization, per-phase emoji, bold header,
8
+ // bold+underline current phase row, italic status words, lazily-accented
9
+ // bold running marker, bold subtask names), not in flow/status.ts, because
10
+ // flow-status.test.ts asserts renderFlowStatusLines output byte-identical.
11
+
12
+ import type { ThemeColor } from '@earendil-works/pi-coding-agent'
13
+ import { truncateToWidth, visibleWidth } from '@mariozechner/pi-tui'
14
+ import { PHASE_EMOJI } from './phase-emoji.ts'
15
+
16
+ /** Minimal structural slice of Theme we rely on — keeps this module pure
17
+ * and unit-testable with a fake. getFgAnsi gives the raw opening SGR
18
+ * sequence, which is what border chrome needs (no reset churn per cell). */
19
+ export interface FramingTheme {
20
+ getFgAnsi(color: ThemeColor): string
21
+ }
22
+
23
+ /** Phase → theme role for the frame. No phase (state null / idle) falls back
24
+ * to the normal border token. */
25
+ export function phaseAccent(currentPhase: string | null): ThemeColor {
26
+ if (currentPhase === 'plan') return 'accent'
27
+ if (currentPhase === 'implement') return 'success'
28
+ if (currentPhase === 'validate') return 'warning'
29
+ if (currentPhase === 'feedback') return 'muted'
30
+ return 'border'
31
+ }
32
+
33
+ /** Render one inner row: two-space indent (only when there is content),
34
+ * ANSI-aware truncation to the inner width, right-padded to it. Styled
35
+ * rows arrive with all SGR attributes already closed, so padding never
36
+ * carries emphasis. */
37
+
38
+ // AIDEV-NOTE (PMR-X7BH): raw SGR styling constants — narrow resets only,
39
+ // never \x1b[0m in content rows (rifle-batteries/tool-pills/icons.ts
40
+ // precedent). The frame border re-opens its color after each row, and
41
+ // frameRow pads AFTER these closes, so underlines never bleed into padding.
42
+ const BOLD = '\x1b[1m'
43
+ const BOLD_RST = '\x1b[22m'
44
+ const ITALIC = '\x1b[3m'
45
+ const ITALIC_RST = '\x1b[23m'
46
+ const UNDERLINE = '\x1b[4m'
47
+ const UNDERLINE_RST = '\x1b[24m'
48
+ const FG_RST = '\x1b[39m'
49
+
50
+ const PHASE_ORDER = ['plan', 'implement', 'validate', 'feedback'] as const
51
+
52
+ /** Style a `flow <REF> · <mode>` header row: bold. */
53
+ function styleHeader(line: string): string {
54
+ return `${BOLD}${line}${BOLD_RST}`
55
+ }
56
+
57
+ /** Style a phase checkbox row (PMR-X7BH): `[x]`→`✅` with the mark column
58
+ * padded to 4 visible cols, per-phase emoji between mark and name, italic
59
+ * `(label)`, accent-bold ` <- running`, and bold+underline for the current
60
+ * phase row. Emphasis is fully closed before returning so frameRow's
61
+ * padding stays plain. */
62
+ function stylePhaseRow(
63
+ line: string,
64
+ currentPhase: string | null,
65
+ theme: FramingTheme,
66
+ ): string {
67
+ const done = line.startsWith('[x] ')
68
+ const rest = line.slice(4) // '[x] ' and '[ ] ' are both 4 chars
69
+ const phase = PHASE_ORDER.find((p) => rest.startsWith(p))
70
+ if (phase === undefined) return line
71
+ const tail = rest.slice(phase.length) // pad spaces + '(label)' + optional ' <- running'
72
+ const runningAt = tail.indexOf(' <- running')
73
+ let padLabel = tail
74
+ let running = ''
75
+ if (runningAt !== -1) {
76
+ padLabel = tail.slice(0, runningAt)
77
+ running = tail.slice(runningAt)
78
+ }
79
+ const parenAt = padLabel.indexOf('(')
80
+ if (parenAt === -1) return line
81
+ const pad = padLabel.slice(0, parenAt)
82
+ const label = padLabel.slice(parenAt) // '(planned)' etc.
83
+ // Mark-column normalization: '✅' is 2 visible cols vs '[x]'/'[ ]' 3 —
84
+ // pad done marks with one extra space so the emoji column stays aligned.
85
+ let mark = '[ ] '
86
+ if (done) mark = '✅ ' // 2-col emoji + 2 spaces = 4 visible cols
87
+ let emojiPrefix = ''
88
+ if (PHASE_EMOJI[phase] !== undefined) emojiPrefix = `${PHASE_EMOJI[phase]} `
89
+ // Lazy accent: only ask the theme when a running row is actually styled
90
+ // (frame.test.ts asserts requested.length === 1 without a runner).
91
+ // AIDEV-NOTE: ordering constraint — runningPart closes with BOLD_RST (SGR
92
+ // 22), which ALSO terminates the outer current-phase bold opened below
93
+ // (the `${BOLD}${UNDERLINE}${body}` wrapper). Harmless only while
94
+ // runningPart stays the FINAL span of body; any future append after it
95
+ // silently loses bold on the current-phase row (move the outer close or
96
+ // re-order first).
97
+ let runningPart = ''
98
+ if (running !== '') {
99
+ runningPart = ` ${theme.getFgAnsi('accent')}${BOLD}${running.slice(1)}${BOLD_RST}${FG_RST}`
100
+ }
101
+ const body = `${mark}${emojiPrefix}${phase}${pad}${ITALIC}${label}${ITALIC_RST}${runningPart}`
102
+ if (phase !== currentPhase) return body
103
+ // Whole current row bold+underlined; closes emit BEFORE frameRow pads.
104
+ return `${BOLD}${UNDERLINE}${body}${UNDERLINE_RST}${BOLD_RST}`
105
+ }
106
+
107
+ /** Dispatch a raw status line to its styling. Gates rows and block headers
108
+ * pass through unchanged (PMR-X7BH). */
109
+ function styleContentLine(
110
+ line: string,
111
+ currentPhase: string | null,
112
+ theme: FramingTheme,
113
+ block: 'subtasks' | 'gates' | null,
114
+ ): string {
115
+ if (line.startsWith('flow ')) return styleHeader(line)
116
+ if (line.startsWith('[x] ') || line.startsWith('[ ] ')) {
117
+ return stylePhaseRow(line, currentPhase, theme)
118
+ }
119
+ if (block === 'subtasks' && line.startsWith(' ')) {
120
+ const idx = line.indexOf(' — ')
121
+ if (idx > 2) {
122
+ return ` ${BOLD}${line.slice(2, idx)}${BOLD_RST}${line.slice(idx)}`
123
+ }
124
+ }
125
+ return line
126
+ }
127
+ function frameRow(line: string, indent: string, inner: number): string {
128
+ const indented = indent + line
129
+ const trunc = truncateToWidth(indented, inner)
130
+ const pad = Math.max(0, inner - visibleWidth(trunc))
131
+ return trunc + ' '.repeat(pad)
132
+ }
133
+
134
+ /** Wrap plain status lines in a phase-colored rounded box.
135
+ * Blank separators are inserted before `subtasks:` / `gates:` blocks and
136
+ * phase rows are indented under the header — presentation-only shaping that
137
+ * must NOT leak into flow/status.ts (its output is asserted byte-identical). */
138
+ export function frameFlowStatusLines(
139
+ lines: readonly string[],
140
+ width: number,
141
+ theme: FramingTheme,
142
+ currentPhase: string | null,
143
+ ): string[] {
144
+ if (width <= 2) return [...lines]
145
+ const inner = width - 2
146
+ const open = theme.getFgAnsi(phaseAccent(currentPhase))
147
+ const close = '\x1b[0m'
148
+ const framed: string[] = [`${open}╭${'─'.repeat(inner)}╮${close}`]
149
+ let previous = ''
150
+ // Track which block we are in so subtask names can be bolded (PMR-X7BH).
151
+ let block: 'subtasks' | 'gates' | null = null
152
+ for (const line of lines) {
153
+ // Presentation shaping: blank line before each block header.
154
+ if ((line === 'subtasks:' || line === 'gates:') && previous !== '') {
155
+ framed.push(`${open}│${close}${frameRow('', '', inner)}${open}│${close}`)
156
+ }
157
+ if (line === 'subtasks:') block = 'subtasks'
158
+ else if (line === 'gates:') block = 'gates'
159
+ // Phase rows (checkbox rows) indent under the header line — indent is
160
+ // keyed on the RAW status.ts vocabulary, before styling.
161
+ let indent = ''
162
+ if (line.startsWith('[x] ') || line.startsWith('[ ] ')) {
163
+ indent = ' '
164
+ }
165
+ framed.push(
166
+ `${open}│${close}${frameRow(styleContentLine(line, currentPhase, theme, block), indent, inner)}${open}│${close}`,
167
+ )
168
+ previous = line
169
+ }
170
+ framed.push(`${open}╰${'─'.repeat(inner)}╯${close}`)
171
+ return framed
172
+ }