@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,302 @@
1
+ // AIDEV-NOTE: PMR-C998 — advisory posture. flow_submit is an EVIDENCE
2
+ // journal, never a gate: it records structured step-output events into the
3
+ // run journal and reports warnings, but nothing here blocks or refuses a
4
+ // flow phase. flow_phase_complete semantics are unchanged and the lifecycle
5
+ // labels remain the gate of record. The only refusal path is malformed
6
+ // params (schema enforcement); every verification failure degrades to a
7
+ // warning line on an ok result.
8
+ // AIDEV-NOTE: PMR-XTQQ — writer seam. When an EventWriter is injected,
9
+ // journal writes route through writer.record (journal-only while the daemon
10
+ // owns the projection); otherwise we fall back to the direct
11
+ // recordRunEvent path. Both are append-only ('step-output' is covered by
12
+ // isJournalOnlyEvent in run-state.ts).
13
+ // AIDEV-NOTE: PMR-4S6V — headSha pin lineage. When the submission carries a
14
+ // headSha, HEAD is resolved via the injected resolveHead (defaulting to
15
+ // land.ts's defaultResolveHead — read-only dependency, land.ts is never
16
+ // edited here) and headShaVerified is journaled on the event either way, so
17
+ // lineage stays auditable even when verification fails.
18
+ import type {
19
+ AgentToolResult,
20
+ ExtensionAPI,
21
+ } from '@earendil-works/pi-coding-agent'
22
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
23
+ import { Type } from 'typebox'
24
+ import {
25
+ buildStepOutputEvent,
26
+ type StepOutputEventPayload,
27
+ type StepOutputFacts,
28
+ type StepOutputInput,
29
+ StepOutputSchema,
30
+ } from '../flow/step-output.ts'
31
+ import {
32
+ type FlowRunEvent,
33
+ readRunEvents,
34
+ recordRunEvent,
35
+ } from '../run-state.ts'
36
+ import type { EventWriter } from '../server/writer.ts'
37
+ import { defaultResolveHead } from './land.ts'
38
+ import { toolResult } from './result.ts'
39
+
40
+ export interface FlowSubmitDetails {
41
+ ok: boolean
42
+ journaled: boolean
43
+ headShaVerified?: boolean
44
+ unknownGateTargetIds?: string[]
45
+ }
46
+
47
+ export interface FlowSubmitDeps {
48
+ writer?: EventWriter
49
+ resolveHead?: () => Promise<string | null>
50
+ readEvents?: (ref: string) => Promise<FlowRunEvent[] | null>
51
+ }
52
+
53
+ /** Gate-target ids cited by prior gate-target events for this ref. */
54
+ function citedGateTargetIds(events: FlowRunEvent[]): Set<string> {
55
+ const ids = new Set<string>()
56
+ for (const event of events) {
57
+ if (event.kind === 'gate-target') {
58
+ ids.add(event.targetId)
59
+ }
60
+ }
61
+ return ids
62
+ }
63
+
64
+ // AIDEV-NOTE: PMR-4S6V — headSha pin: resolve HEAD and journal the
65
+ // verification outcome either way; unresolvable HEAD is a warning, never a
66
+ // refusal. Appends warnings and mutates event/details in place.
67
+ async function verifyHeadSha(
68
+ event: StepOutputEventPayload,
69
+ details: FlowSubmitDetails,
70
+ warnings: string[],
71
+ resolveHead: () => Promise<string | null>,
72
+ ): Promise<void> {
73
+ if (event.headSha === undefined) return
74
+ const head = await resolveHead()
75
+ let verified: boolean
76
+ if (head === null) {
77
+ verified = false
78
+ warnings.push(
79
+ `could not resolve HEAD — headShaVerified journaled as false for ${event.headSha}`,
80
+ )
81
+ } else if (head !== event.headSha) {
82
+ verified = false
83
+ warnings.push(
84
+ `headSha mismatch — submitted ${event.headSha}, HEAD is ${head}; headShaVerified journaled as false`,
85
+ )
86
+ } else {
87
+ verified = true
88
+ }
89
+ event.headShaVerified = verified
90
+ details.headShaVerified = verified
91
+ }
92
+
93
+ // AIDEV-NOTE: PMR-C998 — gate-target membership check (validate phase):
94
+ // cited ids must appear as prior gate-target targetIds. An unreadable
95
+ // journal is a "cannot verify" warning, never a refusal (advisory posture).
96
+ async function verifyGateTargets(
97
+ event: StepOutputEventPayload,
98
+ ref: string,
99
+ details: FlowSubmitDetails,
100
+ warnings: string[],
101
+ readEvents: (r: string) => Promise<FlowRunEvent[] | null>,
102
+ ): Promise<void> {
103
+ if (event.gateTargetIds === undefined) return
104
+ const events = await readEvents(ref)
105
+ if (events === null) {
106
+ warnings.push(
107
+ 'could not read the run journal — cited gateTargetIds could not be verified',
108
+ )
109
+ return
110
+ }
111
+ const known = citedGateTargetIds(events)
112
+ const unknown = event.gateTargetIds.filter((id) => !known.has(id))
113
+ if (unknown.length > 0) {
114
+ details.unknownGateTargetIds = unknown
115
+ warnings.push(
116
+ `unknown gateTargetIds (no matching gate-target events for ${ref}): ${unknown.join(', ')}`,
117
+ )
118
+ }
119
+ }
120
+
121
+ // AIDEV-NOTE: PMR-C998 / PMR-XTQQ — best-effort journal write: a failure
122
+ // degrades to journaled:false + warning; the result stays ok. Injected
123
+ // writer wins; absence keeps the direct recordRunEvent path so index.ts
124
+ // stays untouched (subtask 2.4 owns wiring). Production writers report the
125
+ // write outcome via the record() boolean, so journaled:false is reachable
126
+ // even when the best-effort writer swallows the failure (PMR-HRZE).
127
+ async function journalEvent(
128
+ event: StepOutputEventPayload,
129
+ writer: EventWriter | undefined,
130
+ ): Promise<boolean> {
131
+ try {
132
+ if (writer !== undefined) {
133
+ return await writer.record(event)
134
+ }
135
+ await recordRunEvent(getAgentDir(), event)
136
+ return true
137
+ } catch {
138
+ return false
139
+ }
140
+ }
141
+
142
+ // AIDEV-NOTE: human-readable recap of the per-phase facts for the result
143
+ // text; mirrors StepOutputSchema's optional fields phase by phase.
144
+ function factsSummary(output: StepOutputFacts): string {
145
+ const parts: string[] = []
146
+ if (output.phase === 'plan') {
147
+ if (output.planPath !== undefined) parts.push(`planPath=${output.planPath}`)
148
+ if (output.subtaskRefs !== undefined) {
149
+ parts.push(`subtaskRefs=${output.subtaskRefs.join(',')}`)
150
+ }
151
+ }
152
+ if (output.phase === 'implement') {
153
+ if (output.command !== undefined) parts.push(`command=${output.command}`)
154
+ if (output.passed !== undefined) parts.push(`passed=${output.passed}`)
155
+ if (output.headSha !== undefined) parts.push(`headSha=${output.headSha}`)
156
+ }
157
+ if (output.phase === 'validate') {
158
+ if (output.prNumber !== undefined) parts.push(`prNumber=${output.prNumber}`)
159
+ if (output.prUrl !== undefined) parts.push(`prUrl=${output.prUrl}`)
160
+ if (output.gateTargetIds !== undefined) {
161
+ parts.push(`gateTargetIds=${output.gateTargetIds.join(',')}`)
162
+ }
163
+ }
164
+ if (output.phase === 'feedback') {
165
+ if (output.prUrl !== undefined) parts.push(`prUrl=${output.prUrl}`)
166
+ if (output.prMerged !== undefined) parts.push(`prMerged=${output.prMerged}`)
167
+ }
168
+ if (parts.length === 0) {
169
+ return 'no facts'
170
+ }
171
+ return parts.join(', ')
172
+ }
173
+
174
+ export function registerFlowSubmitTool(
175
+ pi: ExtensionAPI,
176
+ deps: FlowSubmitDeps = {},
177
+ ): void {
178
+ const writer = deps.writer
179
+ const resolveHead = deps.resolveHead
180
+ const readEvents = deps.readEvents
181
+ pi.registerTool({
182
+ name: 'flow_submit',
183
+ label: 'flow submit',
184
+ description:
185
+ 'Journal structured evidence for a flow step boundary (per-phase facts: plan paths and subtask refs, test commands and pass state, HEAD SHA, PR number/URL, cited gate-target ids). Advisory only: this NEVER gates completion and flow_phase_complete semantics are unchanged — sole exception (PMR-AYMZ): an ok=true plan.route-confirmed step-output journaled in the current run, together with the live oneshot label, satisfies the flow_phase_complete(plan) receipt gate; otherwise the lifecycle labels remain the gate of record. Verification failures (SHA mismatch, unknown cited ids, unresolvable HEAD, journal write failure) surface as warnings on an ok result; only malformed params are refused.',
186
+ promptSnippet:
187
+ 'Advisory step-evidence journaling for PIV flows (plan/implement/validate/feedback).',
188
+ promptGuidelines: [
189
+ 'Call flow_submit after each meaningful step boundary: a written plan (planPath, subtaskRefs), a test or verification run (command, passed, headSha), a PR or gate-relevant check (prNumber, prUrl, gateTargetIds), or a merge outcome (prUrl, prMerged).',
190
+ 'flow_submit is advisory: it journals evidence but never gates completion — sole exception (PMR-AYMZ): an ok=true plan.route-confirmed step-output plus the live oneshot label satisfies the flow_phase_complete(plan) receipt gate. flow_phase_complete semantics are otherwise unchanged and the lifecycle labels are the gate of record. A warned submission never blocks a phase.',
191
+ 'Include gateTargetIds on validate submissions to cite the gate targets the evidence covers; unknown ids come back as warnings — fix the ids or proceed, the labels decide.',
192
+ ],
193
+ parameters: Type.Object({
194
+ ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
195
+ step: Type.String({
196
+ description:
197
+ 'Short step label, free-form but 1-64 chars in the flow value charset (alphanumeric, plus dots, underscores and dashes), e.g. "unit-tests-green"',
198
+ }),
199
+ ok: Type.Optional(
200
+ Type.Boolean({
201
+ description: 'Whether the step succeeded (e.g. tests passed)',
202
+ }),
203
+ ),
204
+ detail: Type.Optional(
205
+ Type.String({
206
+ description: 'Free-form detail, e.g. failing test names',
207
+ }),
208
+ ),
209
+ output: StepOutputSchema,
210
+ }),
211
+ async execute(
212
+ _toolCallId: string,
213
+ params: {
214
+ ref: string
215
+ step: string
216
+ ok?: boolean
217
+ detail?: string
218
+ output: StepOutputFacts
219
+ },
220
+ ): Promise<AgentToolResult<FlowSubmitDetails>> {
221
+ // AIDEV-NOTE: PMR-C998 — the ONLY refusal path: malformed params. The
222
+ // reason carries re-run guidance; nothing else ever returns isError.
223
+ // Phase flows from the output union's discriminator — there is no
224
+ // top-level phase param.
225
+ // AIDEV-NOTE (PMR-C998): the input is built by spreading the output
226
+ // union — phase rides the discriminator, and TypeBox unions allow
227
+ // additional properties, so a wrong-typed or cross-phase fact passes
228
+ // the tool-layer schema. buildStepOutputEvent's validator rejects both
229
+ // (fact type checks + cross-phase rejection in flow/step-output.ts)
230
+ // before anything is journaled. Do not restructure the spread.
231
+ const input: StepOutputInput = {
232
+ ...params.output,
233
+ ref: params.ref,
234
+ step: params.step,
235
+ ok: params.ok,
236
+ detail: params.detail,
237
+ }
238
+ const built = buildStepOutputEvent(input)
239
+ if (!built.ok) {
240
+ return toolResult(
241
+ `flow_submit refused: ${built.reason} Re-run flow_submit with the correct shape (see the per-phase output schema; every fact is optional).`,
242
+ { ok: false, journaled: false },
243
+ { isError: true },
244
+ )
245
+ }
246
+
247
+ const event = built.event
248
+ const warnings: string[] = []
249
+ const details: FlowSubmitDetails = { ok: true, journaled: false }
250
+
251
+ let headResolver: () => Promise<string | null>
252
+ if (resolveHead !== undefined) {
253
+ headResolver = resolveHead
254
+ } else {
255
+ headResolver = defaultResolveHead
256
+ }
257
+ await verifyHeadSha(event, details, warnings, headResolver)
258
+
259
+ let eventReader: (r: string) => Promise<FlowRunEvent[] | null>
260
+ if (readEvents !== undefined) {
261
+ eventReader = readEvents
262
+ } else {
263
+ eventReader = (ref: string) => readRunEvents(getAgentDir(), ref)
264
+ }
265
+ await verifyGateTargets(event, params.ref, details, warnings, eventReader)
266
+
267
+ const journaled = await journalEvent(event, writer)
268
+ details.journaled = journaled
269
+ if (!journaled) {
270
+ warnings.push(
271
+ 'journal write failed (best-effort) — evidence NOT journaled',
272
+ )
273
+ }
274
+
275
+ const lines: string[] = []
276
+ if (journaled) {
277
+ lines.push(
278
+ `flow_submit: step-output journaled on ${params.ref} — phase=${event.phase}, step=${event.step}, ${factsSummary(params.output)}`,
279
+ )
280
+ } else {
281
+ lines.push(
282
+ `flow_submit: step-output NOT journaled on ${params.ref} — phase=${event.phase}, step=${event.step}`,
283
+ )
284
+ }
285
+ if (details.headShaVerified !== undefined) {
286
+ lines.push(`headShaVerified: ${details.headShaVerified}`)
287
+ }
288
+ // AIDEV-NOTE: PMR-ZV9Y 1.2 — advisory step-registry hint, carried out of
289
+ // buildStepOutputEvent. It is NOT a verification warning and NOT a
290
+ // rejection: the event is already journalled above and the result stays
291
+ // ok. The hint only nudges the caller toward a registered name for this
292
+ // phase; phases with no registry entries never get one (see step-output.ts).
293
+ if (built.hint !== undefined) {
294
+ lines.push(built.hint)
295
+ }
296
+ for (const warning of warnings) {
297
+ lines.push(`warning: ${warning}`)
298
+ }
299
+ return toolResult(lines.join('\n'), details)
300
+ },
301
+ })
302
+ }