@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
package/flow/gates.ts ADDED
@@ -0,0 +1,211 @@
1
+ // AIDEV-NOTE (PMR-ZGPY 2.1, D4/D5/D6; fix round 2): pure open-gate derivation
2
+ // over run projections — the shared data source for the flow-status widget and
3
+ // the answer picker. No IO here beyond the GateDeps interface declaration (2.2
4
+ // wires real IO); D6 anti-false-open, REAL-WRITER SEMANTICS
5
+ // (fix round 2): closers exist only for the spec-review answer kind —
6
+ // gate-decisions are written only by tools/deviation.ts (gate 'deviation'),
7
+ // gate-answers only carry 'spec-review' since PMR-V31Z 7.1 (the code-review
8
+ // journal kind belongs to the deleted review gate).
9
+ // PMR-V31Z 7.2 — the phase-derived code-review gate is DELETED: its H1
10
+ // consumer died with the personal validate prompt (phase 1) and its closure
11
+ // vocabulary (code_review receipts, 'code-review' answers) had no flow
12
+ // consumer left, so a validate-phase run derives NO gate rows. The ad-hoc
13
+ // code_review tool still exists, but its verdict is an aven note — it never
14
+ // journals a closure record, so there is nothing here to derive from.
15
+ // 'review' pins (journalled by /review, review/review.ts) still have NO
16
+ // closer, so they remain EXCLUDED from answer-gate derivation entirely — a
17
+ // pin with no closer must never render as an answerable gate.
18
+ // Paused runs whose ref also has plan-state=review are deduped in
19
+ // collectOpenGates (2.2), not here — no aven knowledge in this module.
20
+
21
+ import { readdir, readFile } from 'node:fs/promises'
22
+ import { listOpenTicketRefs, listPlansAtReviewRefs } from '../aven/client.ts'
23
+ import type { FlowRunState } from '../run-state.ts'
24
+ import { isFlowRunState, runsDir } from '../run-state.ts'
25
+
26
+ /** One actionable gate the user can open or answer. */
27
+ export interface OpenGate {
28
+ ref: string
29
+ // AIDEV-NOTE: PMR-V31Z 7.2 — the 'code-review' kind is deleted with the
30
+ // phase-derived gate that emitted it.
31
+ kind: 'plan-review' | 'flow-paused' | 'answer-gate'
32
+ /** Single-line, lead with the ref. */
33
+ title: string
34
+ /** Only for answer-gates; the choice itself is supplied by the picker menu. */
35
+ answerCommand?: string
36
+ }
37
+
38
+ // AIDEV-NOTE: IO seam only — implemented and wired by collectOpenGates in
39
+ // 2.2. listOpenRefs (PMR-384R) is the aven-status truth source: null means
40
+ // aven FAILED (suppress nothing, ISC-13); an array is the live-ref universe
41
+ // (absent ref = terminal or no record = suppress).
42
+ export interface GateDeps {
43
+ /** Refs of plan-state=review tickets (aven list; --all-projects). */
44
+ listPlansAtReview(): Promise<string[]>
45
+ /** Refs with a live (nonterminal) aven ticket, all projects; null = aven
46
+ * failed or its output was unclassifiable (error text / non-JSON /
47
+ * schema drift). Fail-closed per ISC-13: unverifiable status suppresses
48
+ * nothing. */
49
+ listOpenRefs(): Promise<string[] | null>
50
+ /** Validated FlowRunState projections from the local runs dir. */
51
+ readRuns(): Promise<FlowRunState[]>
52
+ }
53
+
54
+ // AIDEV-NOTE: injectable fs seam for readRunsFromDisk (the readRunEvents io
55
+ // param pattern) — tests inject a fake fs; no real disk touched.
56
+ export interface GateIo {
57
+ readdir(dir: string): Promise<string[]>
58
+ readFile(path: string): Promise<string>
59
+ }
60
+
61
+ const nodeGateIo: GateIo = {
62
+ readdir: (dir) => readdir(dir),
63
+ readFile: (path) => readFile(path, 'utf8'),
64
+ }
65
+
66
+ function isAnswered(
67
+ state: FlowRunState,
68
+ targetId: string,
69
+ gate: GateTargetGate,
70
+ ): boolean {
71
+ const decisions = state.gateDecisions ?? []
72
+ const answers = state.gateAnswers ?? []
73
+ // D6 conservative OR: either record closes the gate.
74
+ return (
75
+ decisions.some((d) => d.targetId === targetId) ||
76
+ answers.some((a) => a.gate === gate)
77
+ )
78
+ }
79
+
80
+ type GateTargetGate = NonNullable<FlowRunState['gateTargets']>[number]['gate']
81
+
82
+ /** Pure derivation: one or more open gates per run projection, in input order. */
83
+ export function deriveRunGates(states: readonly FlowRunState[]): OpenGate[] {
84
+ const gates: OpenGate[] = []
85
+ for (const state of states) {
86
+ if (state.loop?.status === 'paused') {
87
+ gates.push({
88
+ ref: state.ref,
89
+ kind: 'flow-paused',
90
+ title: `${state.ref} — flow run paused`,
91
+ })
92
+ }
93
+ // AIDEV-NOTE: PMR-V31Z 7.2 — no phase-derived code-review gate is
94
+ // derived anymore (the gate concept is deleted; see the module note).
95
+ // The former suppression rule ("a state emitting the code-review gate
96
+ // emits NO answer-gates") dies with it: answer-gates now derive in
97
+ // every phase, including validate.
98
+ const targets = state.gateTargets ?? []
99
+ for (const target of targets) {
100
+ // 'review' pins have no real closer (see module AIDEV-NOTE) — never
101
+ // derive an answer-gate for them; there is no code-review gate rule
102
+ // above that could own that decision anymore (PMR-V31Z 7.2).
103
+ if (target.gate === 'review') continue
104
+ if (!isAnswered(state, target.targetId, target.gate)) {
105
+ gates.push({
106
+ ref: state.ref,
107
+ kind: 'answer-gate',
108
+ title: `${state.ref} — ${target.gate} gate awaiting answer`,
109
+ answerCommand: `/flow answer ${state.ref}`,
110
+ })
111
+ }
112
+ }
113
+ }
114
+ return gates
115
+ }
116
+
117
+ // AIDEV-NOTE (PMR-ZGPY 2.2, D5): disk scan of runsDir(agentDir) — one
118
+ // validated FlowRunState per *.json file. Fail-soft per file: unreadable,
119
+ // unparsable, or non-conforming files are skipped (a corrupt run file must
120
+ // never blank the widget). io is injectable so tests run without disk.
121
+ export async function readRunsFromDisk(
122
+ agentDir: string,
123
+ io: GateIo = nodeGateIo,
124
+ ): Promise<FlowRunState[]> {
125
+ const dir = runsDir(agentDir)
126
+ let entries: string[]
127
+ try {
128
+ entries = await io.readdir(dir)
129
+ } catch {
130
+ return []
131
+ }
132
+ const runs: FlowRunState[] = []
133
+ for (const entry of entries) {
134
+ if (!entry.endsWith('.json')) continue
135
+ try {
136
+ const raw = await io.readFile(`${dir}/${entry}`)
137
+ const parsed: unknown = JSON.parse(raw)
138
+ if (isFlowRunState(parsed)) runs.push(parsed)
139
+ } catch {
140
+ // corrupt/missing file — skip
141
+ }
142
+ }
143
+ return runs
144
+ }
145
+
146
+ // AIDEV-NOTE (PMR-ZGPY 2.2): real GateDeps factory for phases 3–4 consumers.
147
+ // Aven boundary rule: the aven shell-out itself lives in aven/client.ts
148
+ // (listPlansAtReviewRefs) — this module only calls through it; nothing else
149
+ // in flow/ may exec aven.
150
+ export function createGateDeps(agentDir: string): GateDeps {
151
+ return {
152
+ listPlansAtReview: () => listPlansAtReviewRefs(),
153
+ listOpenRefs: () => listOpenTicketRefs(),
154
+ readRuns: () => readRunsFromDisk(agentDir),
155
+ }
156
+ }
157
+
158
+ // AIDEV-NOTE (PMR-ZGPY 2.2, D5, ISC-13; PMR-384R): merges run-derived gates
159
+ // with the aven plan-state=review list. Each source fails closed
160
+ // INDEPENDENTLY — an aven failure keeps run-derived gates, a runs-scan
161
+ // failure keeps plan-review gates, and (PMR-384R) an aven-status failure
162
+ // (listOpenRefs → null) suppresses NOTHING — so one broken source never
163
+ // blanks the other's signal. Dedupe per D5: a ref that already has ANY
164
+ // run-derived gate (in practice the flow-paused gate, whose title already
165
+ // mentions the pause) appears exactly once; only review refs with no
166
+ // run-derived gate get a fresh plan-review row.
167
+ // PMR-384R suppression: aven ticket status is the truth (user invariant — a
168
+ // stale journal gate record cannot override it). When the open-ref universe
169
+ // is available (non-null), gates whose ref is absent from it are dropped:
170
+ // the ticket is terminal (done/canceled) or has no aven record at all
171
+ // (ungrounded projection — an unanswerable gate). [] is a REAL "zero open
172
+ // tickets" answer and suppresses everything; only null keeps gates.
173
+ // Cross-project scope note: the universe is deliberately --all-projects so
174
+ // other projects' terminal tickets (e.g. TP-85GY) suppress gates that leak
175
+ // in via the shared runsDir; the runsDir scan itself is left unfiltered —
176
+ // scoping accepted per the PMR-384R acceptance criteria (raw journal
177
+ // display in flow-viewer renders immutable history, not derived gates).
178
+ export async function collectOpenGates(deps: GateDeps): Promise<OpenGate[]> {
179
+ const [runs, reviewRefs, openRefs] = await Promise.all([
180
+ deps.readRuns().catch(() => [] as FlowRunState[]),
181
+ deps.listPlansAtReview().catch(() => [] as string[]),
182
+ deps.listOpenRefs().catch(() => null),
183
+ ])
184
+ const runGates = deriveRunGates(runs)
185
+ // PMR-JJ2J: the dedupe must match the suppression filter's case handling —
186
+ // journal refs keep user-typed casing (parseRefKind journals raw input)
187
+ // while aven resolves refs case-insensitively, so a case-variant review
188
+ // ref has to dedupe against its run-derived gate or the widget shows the
189
+ // same ticket twice (run-derived gate + plan-review row).
190
+ const gatedRefs = new Set(runGates.map((g) => g.ref.toUpperCase()))
191
+ const gates = [...runGates]
192
+ for (const ref of reviewRefs) {
193
+ if (gatedRefs.has(ref.toUpperCase())) continue
194
+ gates.push({
195
+ ref,
196
+ kind: 'plan-review',
197
+ title: `${ref} · plan awaiting approval`,
198
+ answerCommand: `/flow answer ${ref}`,
199
+ })
200
+ }
201
+ if (openRefs !== null) {
202
+ // PMR-384R fix round (review blocker 2): aven resolves refs
203
+ // case-insensitively ("a case variant is the same ticket" —
204
+ // ticketSnapshotFor/showFullGuarded) while journal refs keep user-typed
205
+ // casing (parseRefKind journals raw input). Normalize BOTH sides or a
206
+ // case-variant journal ref loses its live gate.
207
+ const open = new Set(openRefs.map((r) => r.toUpperCase()))
208
+ return gates.filter((g) => open.has(g.ref.toUpperCase()))
209
+ }
210
+ return gates
211
+ }
@@ -0,0 +1,212 @@
1
+ // AIDEV-NOTE: Jira-ID → local-epic resolution for /flow and the phase
2
+ // commands (option B). The feature-plan-aven skill plans on a LOCAL epic
3
+ // carrying jira-ref=<JIRA-ID> metadata, dep-linked to the synced ticket —
4
+ // but /flow needs a real aven ref BEFORE the plan phase runs (labels are the
5
+ // run state), so the extension resolves or creates the epic itself. The
6
+ // shared contract with the skill is exactly two things: the jira-ref
7
+ // metadata key and the dep-link. aven prints errors (unknown-metadata-field,
8
+ // unknown-ref) with exit 0, so detection is by output text, not exit code.
9
+
10
+ // AIDEV-NOTE: AvenRunner's single definition lives in aven/client.ts
11
+ // (PMR-T22H); re-exported here so existing imports keep working.
12
+ import type { AvenRunner } from '../aven/client.ts'
13
+
14
+ export type { AvenRunner } from '../aven/client.ts'
15
+
16
+ export type EpicLookup =
17
+ | { kind: 'found'; ref: string }
18
+ | { kind: 'none' }
19
+ | { kind: 'error'; reason: string }
20
+
21
+ export type JiraEpicResolution =
22
+ | { kind: 'epic'; ref: string; created: boolean }
23
+ | { kind: 'abort'; reason: string }
24
+
25
+ interface AvenEntry {
26
+ ref: string
27
+ title: string
28
+ isEpic: boolean
29
+ }
30
+
31
+ // AIDEV-NOTE: aven prints errors (unknown-metadata-field, unknown-ref) with
32
+ // exit 0, so detection is by output text. unknown-metadata-field = the
33
+ // workspace never registered the field (nothing pulled in yet) -> same as an
34
+ // empty list, NOT an aven failure. Fail-closed on everything else.
35
+ async function listByMetadata(
36
+ aven: AvenRunner,
37
+ key: string,
38
+ value: string,
39
+ ): Promise<
40
+ | { kind: 'none' }
41
+ | { kind: 'entries'; entries: AvenEntry[] }
42
+ | { kind: 'error'; reason: string }
43
+ > {
44
+ let stdout: string
45
+ try {
46
+ // AIDEV-NOTE: --all-projects is required — aven >=0.1.51 scopes a plain
47
+ // `list` to the project inferred from the cwd's git root name, so synced
48
+ // Jira tickets living in another project (e.g. dp from an account-api
49
+ // cwd) were invisible and /flow aborted "not aven-managed" (DP-252).
50
+ const out = await aven([
51
+ 'list',
52
+ '--metadata',
53
+ `${key}=${value}`,
54
+ '--all-projects',
55
+ '--json',
56
+ ])
57
+ stdout = out.stdout
58
+ } catch (error) {
59
+ const msg = error instanceof Error ? error.message : String(error)
60
+ return { kind: 'error', reason: `aven list failed: ${msg}` }
61
+ }
62
+ if (/unknown-metadata-field/.test(stdout)) return { kind: 'none' }
63
+ let parsed: unknown
64
+ try {
65
+ parsed = JSON.parse(stdout)
66
+ } catch {
67
+ return {
68
+ kind: 'error',
69
+ reason: `aven list returned bad JSON: ${stdout.slice(0, 120)}`,
70
+ }
71
+ }
72
+ if (!Array.isArray(parsed)) {
73
+ return { kind: 'error', reason: 'aven list JSON was not an array' }
74
+ }
75
+ const entries: AvenEntry[] = parsed.flatMap((e) => {
76
+ if (typeof e !== 'object' || e === null) return []
77
+ const ref = (e as { ref?: unknown }).ref
78
+ if (typeof ref !== 'string') return []
79
+ const rawTitle = (e as { title?: unknown }).title
80
+ return [
81
+ {
82
+ ref,
83
+ title: typeof rawTitle === 'string' ? rawTitle : value,
84
+ isEpic: (e as { is_epic?: unknown }).is_epic === true,
85
+ },
86
+ ]
87
+ })
88
+ return { kind: 'entries', entries }
89
+ }
90
+
91
+ export async function findJiraEpic(
92
+ jiraId: string,
93
+ aven: AvenRunner,
94
+ ): Promise<EpicLookup> {
95
+ const result = await listByMetadata(aven, 'jira-ref', jiraId)
96
+ if (result.kind === 'none') return { kind: 'none' }
97
+ if (result.kind === 'error') return result
98
+ const refs = result.entries.map((e) => e.ref)
99
+ if (refs.length === 0) return { kind: 'none' }
100
+ if (refs.length > 1) {
101
+ return {
102
+ kind: 'error',
103
+ reason: `multiple local epics for ${jiraId} (${refs.join(', ')}) — pass the epic ref explicitly`,
104
+ }
105
+ }
106
+ return { kind: 'found', ref: refs[0] as string }
107
+ }
108
+
109
+ export type TicketBrainstormTarget =
110
+ | { kind: 'epic'; ref: string }
111
+ | { kind: 'synced'; ref: string }
112
+ | { kind: 'none' }
113
+ | { kind: 'error'; reason: string }
114
+
115
+ // AIDEV-NOTE: Brainstorm-time ticket resolution, strictest source first: the
116
+ // local epic (jira-ref) — labels land there and /flow resumes clean; else
117
+ // the synced ticket (jira-key) — full Jira content is already in aven, no
118
+ // acli needed; else acli fallback. The metadata list is run with
119
+ // --all-projects (see listByMetadata): plain `aven list` is project-scoped
120
+ // from the cwd's git root name since aven 0.1.51.
121
+ export async function findTicketBrainstormTarget(
122
+ jiraId: string,
123
+ aven: AvenRunner,
124
+ ): Promise<TicketBrainstormTarget> {
125
+ const epic = await findJiraEpic(jiraId, aven)
126
+ if (epic.kind === 'error') return epic
127
+ if (epic.kind === 'found') return { kind: 'epic', ref: epic.ref }
128
+ const synced = await findSyncedTicket(jiraId, aven)
129
+ if (synced !== null && 'kind' in synced) return synced
130
+ if (synced === null) return { kind: 'none' }
131
+ return { kind: 'synced', ref: synced.ref }
132
+ }
133
+
134
+ interface SyncedTicket {
135
+ ref: string
136
+ title: string
137
+ }
138
+
139
+ async function findSyncedTicket(
140
+ jiraId: string,
141
+ aven: AvenRunner,
142
+ ): Promise<SyncedTicket | null | { kind: 'error'; reason: string }> {
143
+ const result = await listByMetadata(aven, 'jira-key', jiraId)
144
+ if (result.kind === 'none') return null
145
+ if (result.kind === 'error') return result
146
+ const ticket = result.entries.find((e) => !e.isEpic)
147
+ if (ticket === undefined) return null
148
+ return { ref: ticket.ref, title: ticket.title }
149
+ }
150
+
151
+ export async function resolveJiraEpic(
152
+ jiraId: string,
153
+ aven: AvenRunner,
154
+ ): Promise<JiraEpicResolution> {
155
+ const existing = await findJiraEpic(jiraId, aven)
156
+ if (existing.kind === 'found') {
157
+ return { kind: 'epic', ref: existing.ref, created: false }
158
+ }
159
+ if (existing.kind === 'error') {
160
+ return { kind: 'abort', reason: existing.reason }
161
+ }
162
+ const synced = await findSyncedTicket(jiraId, aven)
163
+ if (synced !== null && 'kind' in synced) {
164
+ return { kind: 'abort', reason: synced.reason }
165
+ }
166
+ if (synced === null) {
167
+ return {
168
+ kind: 'abort',
169
+ reason: `${jiraId} is not aven-managed — sync the ticket first, or plan it in Jira directly`,
170
+ }
171
+ }
172
+ // AIDEV-NOTE: the pull-in epic intentionally lands in the cwd-inferred
173
+ // project (aven add has no --project here), NOT the synced ticket's
174
+ // project — confirmed correct by the owner 2026-11-05. The epic is
175
+ // repo-local work tracking; the dep-link ties it to the source ticket.
176
+ let addStdout: string
177
+ try {
178
+ const out = await aven([
179
+ 'add',
180
+ `${jiraId} — ${synced.title}`,
181
+ '--epic',
182
+ '--status',
183
+ 'todo',
184
+ '--metadata',
185
+ `jira-ref=${jiraId}`,
186
+ '--description',
187
+ `Jira ${jiraId} — source of truth: synced ticket ${synced.ref}.`,
188
+ ])
189
+ addStdout = out.stdout
190
+ } catch (error) {
191
+ const msg = error instanceof Error ? error.message : String(error)
192
+ return { kind: 'abort', reason: `aven add failed: ${msg}` }
193
+ }
194
+ const created = /created (\S+)/.exec(addStdout)
195
+ if (created === null) {
196
+ return {
197
+ kind: 'abort',
198
+ reason: `aven add did not report a ref: ${addStdout.slice(0, 120)}`,
199
+ }
200
+ }
201
+ const epicRef = created[1] as string
202
+ try {
203
+ await aven(['dep', 'add', epicRef, synced.ref])
204
+ } catch (error) {
205
+ const msg = error instanceof Error ? error.message : String(error)
206
+ return {
207
+ kind: 'abort',
208
+ reason: `epic ${epicRef} was created but the dep-link to ${synced.ref} failed (${msg}) — re-run /flow; the epic will be found and reused`,
209
+ }
210
+ }
211
+ return { kind: 'epic', ref: epicRef, created: true }
212
+ }
@@ -0,0 +1,149 @@
1
+ // AIDEV-NOTE: PMR-EZHA — pure decision module at the enforcement boundary of
2
+ // the flow_phase_complete tool. checkPhaseCompletion re-states the phase
3
+ // ordering (plan -> implement -> validate -> feedback; PMR-Z2K7 dropped the
4
+ // research stage) over the ticket's current labels; the implement case
5
+ // DELEGATES to the original gate (canImplement in gates.ts) so its reason
6
+ // stays the single source of refusal text. lifecycleLabelMutation is the
7
+ // matcher the bash tool_call interceptor uses to block direct `aven` writes
8
+ // of lifecycle labels. Both functions are pure — the tool in index.ts wraps
9
+ // them.
10
+ import { canImplement, type GateResult } from '../gates.ts'
11
+ import { LIFECYCLE_LABELS } from '../phase-state.ts'
12
+ import { PHASE_LABEL, type Phase } from './orchestrate.ts'
13
+
14
+ const PHASES: readonly Phase[] = ['plan', 'implement', 'validate', 'feedback']
15
+
16
+ function phaseComplete(phase: Phase, labels: readonly string[]): boolean {
17
+ return labels.includes(PHASE_LABEL[phase])
18
+ }
19
+
20
+ // The gate flow_phase_complete consults before writing PHASE_LABEL[phase].
21
+ // Idempotent: an already-complete phase returns ok and the tool reports
22
+ // "already recorded" instead of re-writing.
23
+ export function checkPhaseCompletion(
24
+ phase: Phase,
25
+ labels: readonly string[],
26
+ ): GateResult {
27
+ if (phaseComplete(phase, labels)) return { ok: true }
28
+ if (phase === 'implement') {
29
+ return canImplement(labels)
30
+ }
31
+ const missing = PHASES.slice(0, PHASES.indexOf(phase)).find(
32
+ (p) => !phaseComplete(p, labels),
33
+ )
34
+ if (missing === undefined) return { ok: true }
35
+ return {
36
+ ok: false,
37
+ reason: `phase "${missing}" is not complete — "${PHASE_LABEL[missing]}" label missing on the ticket; run the phases in order`,
38
+ }
39
+ }
40
+
41
+ // AIDEV-NOTE: PMR-VE27 — bounded global-option sequence allowed between
42
+ // `aven` and the mutating subcommand, mirroring the land-gate CMD_START /
43
+ // GIT_OPTS grammar (flow/land-gate.ts). Enumerates aven's live global
44
+ // option set (checked against `aven --help` 2026-11-30: --db <DB>,
45
+ // --workspace <WS>, -p/--project [PROJECT] with an optional value,
46
+ // -A/--all-projects, -h, -V) plus a generic one-token --flag[=value]
47
+ // catchall for boolean globals. Unknown future arg-taking globals would
48
+ // evade this matcher — the same known-limits class as the land gate
49
+ // (aliases, `sh -c '...'`, variable-built commands). Defense in depth
50
+ // ONLY, not a security boundary: labels stay claims that consumers
51
+ // reconcile; this matcher just narrows the obvious direct-write shapes.
52
+ const AVEN_GLOBAL_OPTS = String.raw`(?:\s+(?:--(?:db|workspace)(?:\s+\S+|=\S+)|--project(?:\s+\S+|=\S+)?|-p(?:\s+\S+|=\S+)?|-[AVh]|--[\w-]+(?:=\S+)?))*`
53
+ // The mutating-subcommand gate built from that grammar; zero repetitions
54
+ // of AVEN_GLOBAL_OPTS reproduces the old `\baven\s+(subcommand)\b` shape
55
+ // byte-identically, so every plain-form behavior is unchanged.
56
+ const AVEN_MUTATION_RE = new RegExp(
57
+ `\\baven${AVEN_GLOBAL_OPTS}\\s+(?:edit|add|bulk-update)\\b`,
58
+ )
59
+
60
+ // Matches bash commands that directly mutate a lifecycle label (aven edit
61
+ // --label X, aven label add/remove X — also behind aven's global-option
62
+ // prefixes since PMR-VE27, e.g. `aven --workspace X edit --label done`).
63
+ // Returns the offending label so the
64
+ // interceptor can name it in the block reason; null when the command is
65
+ // allowed. Type labels (bug, oneshot, plan) stay agent-writable — only
66
+ // LIFECYCLE_LABELS are gated.
67
+ //
68
+ // AIDEV-NOTE: PMR-5RFR — the flag match only fires under the mutating
69
+ // subcommands `aven edit` and `aven add` (PMR-TCE5: add can birth a ticket
70
+ // carrying a lifecycle label), optionally behind aven's bounded global-
71
+ // option sequence (PMR-VE27, AVEN_GLOBAL_OPTS above); read-only commands
72
+ // like `aven search --label done` — plain or global-option form — must
73
+ // pass. The separator is (?:=|\s+) so
74
+ // `--label done` (extra whitespace) cannot evade.
75
+ //
76
+ // AIDEV-NOTE: PMR-8N7C — bulk-update also mutates labels (repeatable
77
+ // --label/--remove-label across every matched task), so it joins edit|add
78
+ // in the gated subcommand set.
79
+ export function lifecycleLabelMutation(command: string): string | null {
80
+ if (!command.includes('aven')) return null
81
+ const lifecycle = new Set<string>(LIFECYCLE_LABELS)
82
+ if (AVEN_MUTATION_RE.test(command)) {
83
+ // AIDEV-NOTE: PMR-9P9E — matchAll, not match: repeated --label flags are
84
+ // all inspected, so `--label foo --label done` cannot smuggle a lifecycle
85
+ // label past a first-flag-only capture.
86
+ for (const flag of command.matchAll(
87
+ /--(?:remove-)?label(?:=|\s+)["']?([\w-]+)/g,
88
+ )) {
89
+ if (lifecycle.has(flag[1])) return flag[1]
90
+ }
91
+ }
92
+ if (/\blabel\s+(add|remove|set|rm|delete)\b/.test(command)) {
93
+ for (const token of command.split(/[\s,'"|;&]+/)) {
94
+ if (lifecycle.has(token)) return token
95
+ }
96
+ }
97
+ return null
98
+ }
99
+
100
+ // Matches bash commands that directly write gated aven metadata under the
101
+ // mutating subcommands. Returns the offending key (e.g. "spec-answer") or
102
+ // "plan-state=approved" for the P2 case so the interceptor can name it in
103
+ // the block reason; null when the command is allowed.
104
+ //
105
+ // AIDEV-NOTE: PMR-R5VB — the receipt key spec-answer is blocked with ANY
106
+ // value (writing any value — approve, reject, or empty — is a forge attempt;
107
+ // even clearing a reject must go through /flow answer). plan-state is blocked
108
+ // ONLY with the value "approved": the protected transition goes through the
109
+ // receipt-gated spec_approve tool. plan-state=draft/review stay
110
+ // agent-writable — deliberate: the feature-plan-aven skill legitimately
111
+ // writes those standalone, outside flow context. The review-answer key left
112
+ // the blocked set when PMR-V31Z 7.1 deleted the review gate: with no reader
113
+ // left, writing it forges nothing.
114
+ //
115
+ // AIDEV-NOTE: PMR-TCE5/PMR-8N7C (mirrors lifecycleLabelMutation) — the
116
+ // match only fires under the mutating subcommands `aven edit`, `aven add`,
117
+ // `aven bulk-update`, optionally behind aven's bounded global-option
118
+ // sequence (PMR-VE27, AVEN_GLOBAL_OPTS); read-only commands like
119
+ // `aven show --metadata ...` — plain or global-option form — must pass. PMR-9P9E — matchAll over ALL --metadata flags so a receipt key
120
+ // smuggled behind an innocent first flag still blocks. The separator is
121
+ // (?:=|\s+) so `--metadata key=value` (extra whitespace) cannot evade; the
122
+ // key is captured followed by `=` — any remainder (including embedded `=`)
123
+ // is the value. PMR-SB3H — whitespace is ALSO allowed between the key and
124
+ // the `=` (\s*=, and \s*=\s* in the plan-state variant): aven accepts
125
+ // `--metadata 'spec-answer =approve'` verbatim (live-verified 2026-11-19:
126
+ // stored key spec-answer, clean value approve), which both evaded the old
127
+ // key-then-'=' match and produced a gate-passing value.
128
+ export function receiptMetadataMutation(command: string): string | null {
129
+ if (!command.includes('aven')) return null
130
+ // PMR-V31Z 7.1 rebase compose: the review-answer key left the blocked set
131
+ // (its reader was deleted with the review gate), while the VE27
132
+ // global-option matcher stays — read-only/global-option forms must still
133
+ // pass, mutating forms still block.
134
+ if (!AVEN_MUTATION_RE.test(command)) return null
135
+ const keys = new Set<string>(['spec-answer'])
136
+ for (const flag of command.matchAll(
137
+ /--metadata(?:=|\s+)["']?([\w-]+)\s*=/g,
138
+ )) {
139
+ if (keys.has(flag[1])) return flag[1]
140
+ }
141
+ if (
142
+ /--metadata(?:=|\s+)["']?plan-state(?:\s*=\s*|\s+)["']?approved\b/.test(
143
+ command,
144
+ )
145
+ ) {
146
+ return 'plan-state=approved'
147
+ }
148
+ return null
149
+ }
@@ -0,0 +1,98 @@
1
+ // AIDEV-NOTE: PMR-06RH — pure landing gate consumed by the flow_land tool
2
+ // and the bash tool_call interceptor. landDecision re-states the validate
3
+ // review gate at the landing boundary: the "review-passed" label (written
4
+ // only via flow_phase_complete) is the hard gate; when the agent supplies
5
+ // the review artifact, parseReviewArtifact's verdict is cross-checked so a
6
+ // labeled-but-blocked landing cannot slip through. landingBashBlock is the
7
+ // interceptor matcher for `git push` / `gh pr create` — it blocks ONLY while
8
+ // a flow landing context (the loop's active ref) exists; normal git use
9
+ // outside a flow run is never touched. Both functions are pure.
10
+ import { parseReviewArtifact } from '../validate/review-gate.ts'
11
+
12
+ export type LandDecision = { ok: true } | { ok: false; reason: string }
13
+
14
+ export function landDecision(
15
+ labels: readonly string[] | null,
16
+ reviewArtifact: string | null,
17
+ ): LandDecision {
18
+ if (labels === null) {
19
+ return {
20
+ ok: false,
21
+ reason: 'cannot read aven labels (fail-closed) — landing refused',
22
+ }
23
+ }
24
+ if (!labels.includes('review-passed')) {
25
+ return {
26
+ ok: false,
27
+ reason:
28
+ 'ticket has no "review-passed" label — complete the validate phase (flow_phase_complete with phase="validate") before landing',
29
+ }
30
+ }
31
+ if (reviewArtifact !== null) {
32
+ const parsed = parseReviewArtifact(reviewArtifact)
33
+ if (!parsed.ok) {
34
+ return { ok: false, reason: parsed.reason }
35
+ }
36
+ if (parsed.blockersCount > 0) {
37
+ return {
38
+ ok: false,
39
+ reason: `review artifact reports ${parsed.blockersCount} blocker(s) — resolve them and re-run /review before landing`,
40
+ }
41
+ }
42
+ }
43
+ return { ok: true }
44
+ }
45
+
46
+ // AIDEV-NOTE: PMR-4Y1Z — command position = start, or after any shell
47
+ // separator (&& || ; | & newline), a subshell/group opener ( { , a backtick or
48
+ // $( — but NOT after a quote, so `echo "git push"` is not a landing. Git
49
+ // global options (-C <dir>, -c k=v, --git-dir[=]..., --no-pager, ...) and env
50
+ // assignments may sit between the command words. Known limit (guardrail, not
51
+ // a privilege boundary): aliases, `sh -c '...'`, and variable-built commands
52
+ // are not detected. The same limits apply to the merge matcher (MERGE_RE) in
53
+ // flow/effect-gate.ts, which is built from this grammar (PMR-VDVJ).
54
+ // AIDEV-NOTE: exported (PMR-VDVJ phase 2) so flow/effect-gate.ts can build
55
+ // MERGE_RE from the same command-position and git-option grammar. Export-only
56
+ // change — no behavior change.
57
+ export const CMD_START = String.raw`(?:^|[;&|(){}\n\x60]|\$\()\s*(?:\w+=\S*\s+)*`
58
+ // AIDEV-NOTE: exported (PMR-VDVJ phase 2), same rationale as CMD_START.
59
+ export const GIT_OPTS = String.raw`(?:\s+(?:-[Cc]\s+\S+|--(?:git-dir|work-tree|namespace|exec-path)\s+\S+|--[\w-]+(?:=\S+)?|-[pP]))*`
60
+ const GH_OPTS = String.raw`(?:\s+(?:-R|--repo)\s+\S+)*`
61
+ const LANDING_RE = new RegExp(
62
+ `${CMD_START}(?:git${GIT_OPTS}\\s+push|gh${GH_OPTS}\\s+pr\\s+create)\\b`,
63
+ )
64
+
65
+ // Matches bash landing commands (git push / gh pr create) at command
66
+ // position (see CMD_START). Returns the active ref the
67
+ // block reason should name, or null when the command is allowed. Only called
68
+ // while a flow ref is active — never globally.
69
+ export function landingBashBlock(
70
+ command: string,
71
+ activeRef: string | null,
72
+ ): string | null {
73
+ if (activeRef === null) return null
74
+ const landing = LANDING_RE.test(command)
75
+ if (!landing) return null
76
+ return `landing for flow ${activeRef} is gated — call the flow_land tool (ref=${activeRef}); direct git push / gh pr create during a flow run are blocked`
77
+ }
78
+
79
+ // AIDEV-NOTE: PMR-VZEV — pure decision behind the index.ts tool_call
80
+ // interceptor. `clear` is true only when an ALLOWED-THROUGH command was a
81
+ // landing command while authorized === activeRef: one authorization = one
82
+ // landing command, so the caller clears authorized (PMR-V31Z 7.2 deleted
83
+ // the humanReviewPassed marker the clear used to also reset).
84
+ export type LandingInterceptDecision =
85
+ | { action: 'allow'; clear: boolean }
86
+ | { action: 'block'; reason: string }
87
+
88
+ export function landingIntercept(
89
+ command: string,
90
+ activeRef: string | null,
91
+ authorized: string | null,
92
+ ): LandingInterceptDecision {
93
+ if (activeRef === null) return { action: 'allow', clear: false }
94
+ const reason = landingBashBlock(command, activeRef)
95
+ if (reason === null) return { action: 'allow', clear: false }
96
+ if (authorized === activeRef) return { action: 'allow', clear: true }
97
+ return { action: 'block', reason }
98
+ }