@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/tools/land.ts ADDED
@@ -0,0 +1,608 @@
1
+ // AIDEV-NOTE: PMR-06RH — the ONLY sanctioned landing path for a flow run.
2
+ // Re-checks the review gate at the landing boundary via the pure
3
+ // landDecision (flow/land-gate.ts): 'review-passed' label required, and when
4
+ // the agent supplies the review artifact its blockers_count verdict is
5
+ // cross-checked. On ok, the ref's landing is authorized so the subsequent
6
+ // git push / gh pr create passes the interceptor. PMR-V31Z 4.1: PR delivery
7
+ // is the only story — the route parameter and the merge-main leg are gone.
8
+
9
+ import { execFile } from 'node:child_process'
10
+ import { promises as fs } from 'node:fs'
11
+ import path from 'node:path'
12
+ import { promisify } from 'node:util'
13
+ import type {
14
+ AgentToolResult,
15
+ ExtensionAPI,
16
+ ExtensionToolContext,
17
+ } from '@earendil-works/pi-coding-agent'
18
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
19
+ import { Type } from 'typebox'
20
+ import { readAvenLabels } from '../aven/client.ts'
21
+ import { loadConfigWithOrigins } from '../config.ts'
22
+ import {
23
+ type HealResult,
24
+ healFlowBinding,
25
+ recoveryCommand,
26
+ } from '../flow/binding-heal.ts'
27
+ import { DEFAULT_RECIPES } from '../flow/effect-gate.ts'
28
+ import { landDecision } from '../flow/land-gate.ts'
29
+ // PMR-V31Z 4.2 — the integrate.ts / approval-lineage.ts imports died with the
30
+ // merge-main helpers; flow_land no longer depends on the sanctioned-rebase
31
+ // subsystem (deleted in 5.1).
32
+ import { getFlowWorktree } from '../flow/worktree-context.ts'
33
+ import {
34
+ createEffectJournal,
35
+ createReceiptJournal,
36
+ type EffectJournal,
37
+ type ReceiptJournal,
38
+ } from '../run-state.ts'
39
+ import type { EventWriter } from '../server/writer.ts'
40
+ import { toolResult } from './result.ts'
41
+ import { productionReviewDeps } from './review-deps.ts'
42
+
43
+ // AIDEV-NOTE: PMR-DRKH — injectable heal seam for flow_land. Production
44
+ // default resolves the ref's worktree via healFlowBinding (aven note → herdr
45
+ // list) and rebinds module state; fully try/catch-wrapped so ANY throw
46
+ // (mockPi without exec in tests, missing binaries, ...) degrades to a heal
47
+ // failure, never an escaped exception.
48
+ async function defaultHealBinding(
49
+ pi: ExtensionAPI,
50
+ repoRoot: string,
51
+ ref: string,
52
+ ): Promise<HealResult> {
53
+ try {
54
+ return await healFlowBinding(ref, productionReviewDeps(pi, repoRoot))
55
+ } catch (error) {
56
+ let reason: string
57
+ if (error instanceof Error) {
58
+ reason = error.message
59
+ } else {
60
+ reason = String(error)
61
+ }
62
+ return { ok: false, reason, recovery: recoveryCommand(ref) }
63
+ }
64
+ }
65
+
66
+ const execFileAsync = promisify(execFile)
67
+ const LAND_SUITE_TIMEOUT_MS = 10 * 60 * 1000
68
+ const LAND_SUITE_TAIL_CHARS = 2000
69
+
70
+ // AIDEV-NOTE: PMR-VDVJ — declare-before-authorize for the pr landing:
71
+ // git-push and gh-pr-create must both be journaled (canonical commands + DEFAULT_RECIPES)
72
+ // before the landing is authorized. Declarations are fail-closed, receipts
73
+ // stay best-effort — the deliberate split. Shared by BOTH success paths
74
+ // (receipt adoption and fresh suite) so neither can authorize undeclared.
75
+ async function declarePushEffects(
76
+ effects: EffectJournal,
77
+ ref: string,
78
+ head: string | null,
79
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
80
+ for (const effect of ['git-push', 'gh-pr-create'] as const) {
81
+ let command: string
82
+ if (effect === 'git-push') {
83
+ command = 'git push'
84
+ } else {
85
+ command = 'gh pr create'
86
+ }
87
+ const result = await effects.declare({
88
+ ref,
89
+ effect,
90
+ command,
91
+ recipe: DEFAULT_RECIPES[effect],
92
+ headSha: head ?? undefined,
93
+ })
94
+ if (!result.ok) {
95
+ return { ok: false, reason: result.reason }
96
+ }
97
+ }
98
+ return { ok: true }
99
+ }
100
+
101
+ // AIDEV-NOTE: shared with the bash tool_call interceptor in index.ts — the
102
+ // interceptor refuses git push / gh pr create for the active flow ref until
103
+ // this state names it.
104
+ // AIDEV-NOTE: PMR-V31Z 7.2 — the humanReviewPassed marker (PMR-T8ZG) is
105
+ // DELETED: the personal merge gate that read it died in phase 4 and the
106
+ // ad-hoc code_review tool now records its verdict as an aven note only. The
107
+ // in-session surface is just the push one-shot (authorized).
108
+ export interface LandingState {
109
+ authorized: string | null
110
+ }
111
+
112
+ export function createLandingState(): LandingState {
113
+ return {
114
+ authorized: null,
115
+ }
116
+ }
117
+
118
+ // AIDEV-NOTE: PMR-05HX — the landing gate never trusts a claimed-green
119
+ // suite. flow_land runs the test command itself before authorizing any
120
+ // route; a misbehaving agent must be UNABLE to land unverified work
121
+ // (evidence: pi:01a1b102 ord 36, "tests pass, committed" over a red suite).
122
+ export interface SuiteRun {
123
+ ok: boolean
124
+ summary: string
125
+ }
126
+
127
+ export type SuiteRunner = (cwd: string) => Promise<SuiteRun>
128
+
129
+ export const DEFAULT_LAND_TEST_COMMAND = ['bun', 'run', 'test'] as const
130
+
131
+ // AIDEV-NOTE: PMR-H5ST — repo-aware land test detection. Consulted ONLY when
132
+ // neither global nor project config sets landTestCommand. First match wins in
133
+ // this fixed order (bun-style signals, then cargo, then npm, then pnpm) so a
134
+ // hybrid repo resolves deterministically. Adding a row here must come with a
135
+ // detection-matrix test in test/land-detect.test.ts.
136
+ // AIDEV-NOTE: PMR-RH97 — entries are matched with fs.stat + isFile(), so only
137
+ // regular files count as signals: a directory named Cargo.toml, a FIFO, or a
138
+ // dangling symlink must NOT route the land test. Any stat error (ENOENT,
139
+ // EPERM, EACCES, …) is treated as "signal absent" and scanning continues —
140
+ // failure always falls toward the bun default, never toward a wrong
141
+ // detection.
142
+ const LAND_TEST_SIGNALS: ReadonlyArray<{
143
+ files: readonly string[]
144
+ command: readonly string[]
145
+ }> = [
146
+ { files: ['bun.lock', 'bunfig.toml'], command: ['bun', 'run', 'test'] },
147
+ { files: ['Cargo.toml'], command: ['cargo', 'test'] },
148
+ { files: ['package-lock.json'], command: ['npm', 'test'] },
149
+ { files: ['pnpm-lock.yaml'], command: ['pnpm', 'test'] },
150
+ ]
151
+
152
+ export interface DetectedLandTest {
153
+ command: readonly string[]
154
+ /** The signal file that matched, e.g. 'bun.lock' — surfaced in summaries. */
155
+ signal: string
156
+ }
157
+
158
+ export interface LandTestScan {
159
+ /** First matching signal, or null when none matched. */
160
+ detected: DetectedLandTest | null
161
+ /**
162
+ * Signals that EXIST but could not be stat'd (stat error other than
163
+ * ENOENT/ENOTDIR — e.g. EACCES on an ancestor dir or ELOOP on a symlink
164
+ * loop), formatted as 'Cargo.toml (EACCES)'. Surfaced in the fallback
165
+ * source label so "no signals" and "signal present but unreadable" are
166
+ * distinguishable; the command still falls toward the bun default
167
+ * (fail-safe direction unchanged, PMR-RH97).
168
+ */
169
+ unreadable: readonly string[]
170
+ }
171
+
172
+ /**
173
+ * Repo-signal detection for the land test (PMR-H5ST): lockfile/manifest
174
+ * presence under repoRoot picks the suite command. detected is null when no
175
+ * signal matches (caller falls back to DEFAULT_LAND_TEST_COMMAND); unreadable
176
+ * names present-but-unreadable signals (caller may label the fallback with
177
+ * them).
178
+ */
179
+ export async function detectLandTestCommand(
180
+ repoRoot: string,
181
+ ): Promise<LandTestScan> {
182
+ const unreadable: string[] = []
183
+ for (const entry of LAND_TEST_SIGNALS) {
184
+ for (const file of entry.files) {
185
+ let stat: Awaited<ReturnType<typeof fs.stat>>
186
+ try {
187
+ // PMR-RH97: stat (not access) so the entry TYPE is checked — only a
188
+ // regular file is a signal. ENOENT/ENOTDIR mean absent; any other
189
+ // error means the signal exists but cannot be read — recorded, and
190
+ // the scan continues. Failure always falls toward the bun default,
191
+ // never toward a wrong detection.
192
+ stat = await fs.stat(path.join(repoRoot, file))
193
+ } catch (error) {
194
+ const code = (error as NodeJS.ErrnoException | undefined)?.code
195
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') {
196
+ unreadable.push(`${file} (${code ?? 'unknown error'})`)
197
+ }
198
+ continue
199
+ }
200
+ if (stat.isFile()) {
201
+ return {
202
+ detected: { command: [...entry.command], signal: file },
203
+ unreadable,
204
+ }
205
+ }
206
+ }
207
+ }
208
+ return { detected: null, unreadable }
209
+ }
210
+
211
+ // AIDEV-NOTE: PMR-5NZB 3.3 / D9 — unstarted-suite evidence check. Only a
212
+ // COMPLETELY empty combined stdout+stderr (after trim) means no test
213
+ // evidence: any real runner prints something, so nothing printed = an
214
+ // unstarted runner (e.g. a provider failure before spawn, PMR-XKVK class),
215
+ // never green. Runner-specific zero-test parsing is deliberately out of
216
+ // scope — deeper detection is not attempted here.
217
+ /** Pure: did the suite run produce ANY output evidence at all? */
218
+ export function suiteRanEvidence(stdout: string, stderr: string): boolean {
219
+ return `${stdout}${stderr}`.trim().length > 0
220
+ }
221
+
222
+ /** Pure: bounded tail of the suite output for the refusal message. */
223
+ export function suiteSummary(output: string): string {
224
+ const trimmed = output.trimEnd()
225
+ if (trimmed.length <= LAND_SUITE_TAIL_CHARS) return trimmed
226
+ return `…${trimmed.slice(-LAND_SUITE_TAIL_CHARS)}`
227
+ }
228
+
229
+ /**
230
+ * Suite command resolution (PMR-H5ST), in order: explicit `landTestCommand`
231
+ * from pi-flow config (global, main checkout project, or project —
232
+ * loadConfig merges, nearest wins per key), then repo-signal detection, then
233
+ * `bun run test`. Fail-closed: a spawn error or timeout is a red run. The
234
+ * summary names the command and its source so landing refusals are
235
+ * explainable.
236
+ */
237
+ export async function defaultSuiteRunner(cwd: string): Promise<SuiteRun> {
238
+ const { config, origins } = await loadConfigWithOrigins(cwd)
239
+ let command: readonly string[]
240
+ let source: string
241
+ if (config.landTestCommand !== undefined) {
242
+ command = config.landTestCommand
243
+ // PMR-1QKY: name WHICH config file won the per-key merge (global /
244
+ // main checkout project / project) so precedence surprises are
245
+ // explainable without inspecting both files by hand. The undefined
246
+ // fallback keeps the old bare label if provenance is ever lost.
247
+ const origin = origins.landTestCommand
248
+ if (origin === undefined) {
249
+ source = 'landTestCommand config'
250
+ } else {
251
+ source = `landTestCommand config (${origin})`
252
+ }
253
+ } else {
254
+ const scan = await detectLandTestCommand(cwd)
255
+ if (scan.detected !== null) {
256
+ command = scan.detected.command
257
+ source = `repo detection via ${scan.detected.signal}`
258
+ } else {
259
+ command = [...DEFAULT_LAND_TEST_COMMAND]
260
+ // Distinguish "no signals at all" from "signal present but unreadable"
261
+ // in the fallback label (both still run the bun default).
262
+ if (scan.unreadable.length > 0) {
263
+ source = `default (signal read failed: ${scan.unreadable.join(', ')})`
264
+ } else {
265
+ source = 'default'
266
+ }
267
+ }
268
+ }
269
+ const header = `land test command: ${command.join(' ')} (${source})`
270
+ const [cmd, ...args] = command
271
+ if (cmd === undefined) {
272
+ return { ok: false, summary: 'empty landTestCommand in config' }
273
+ }
274
+ try {
275
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
276
+ cwd,
277
+ timeout: LAND_SUITE_TIMEOUT_MS,
278
+ maxBuffer: 16 * 1024 * 1024,
279
+ })
280
+ // AIDEV-NOTE: PMR-5NZB 3.3 / D9 — exit 0 with zero output evidence is an
281
+ // UNSTARTED suite (PMR-XKVK class), never green. This applies to every
282
+ // suite flow_land runs, including integration cycles (same runner).
283
+ if (!suiteRanEvidence(stdout, stderr)) {
284
+ return {
285
+ ok: false,
286
+ summary: `${header}\nsuite produced no output — no evidence any test executed; an unstarted runner (e.g. a provider failure before spawn) is never green (PMR-XKVK)`,
287
+ }
288
+ }
289
+ return {
290
+ ok: true,
291
+ summary: `${header}\n${suiteSummary(`${stdout}\n${stderr}`)}`,
292
+ }
293
+ } catch (error: unknown) {
294
+ const err = error as {
295
+ stdout?: string
296
+ stderr?: string
297
+ message?: string
298
+ }
299
+ return {
300
+ ok: false,
301
+ summary: `${header}\n${suiteSummary(
302
+ `${err.stdout ?? ''}\n${err.stderr ?? ''}\n${err.message ?? 'suite runner failed'}`,
303
+ )}`,
304
+ }
305
+ }
306
+ }
307
+
308
+ /** Where the suite runs: the flow's worktree when bound, else the cwd. */
309
+ export function landingSuiteCwd(): string {
310
+ return getFlowWorktree()?.path ?? process.cwd()
311
+ }
312
+
313
+ // AIDEV-NOTE: PMR-4S6V — HEAD-pin anchor for receipt adoption (PMR-05HX:
314
+ // never land work the gate has not seen a green suite over — unresolvable
315
+ // HEAD -> no adoption, full suite re-run). Returns null on any error.
316
+ // PMR-1TCN — optional cwd param: the code_review tool passes its RESOLVED
317
+ // review worktree path so the receipt pins that tree's HEAD; with no arg
318
+ // (the land tool's own adoption/record call sites) it still resolves
319
+ // landingSuiteCwd() exactly as before.
320
+ export async function defaultResolveHead(cwd?: string): Promise<string | null> {
321
+ let headCwd: string
322
+ if (cwd !== undefined) {
323
+ headCwd = cwd
324
+ } else {
325
+ headCwd = landingSuiteCwd()
326
+ }
327
+ try {
328
+ const { stdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], {
329
+ cwd: headCwd,
330
+ })
331
+ return stdout.trim()
332
+ } catch {
333
+ return null
334
+ }
335
+ }
336
+
337
+ // AIDEV-NOTE: PMR-5NZB 3.2 — the structured MainAdvancement refusal types
338
+ // (kind 'stale' = merge-base-behind-tip vs kind 'refuse') lived here until
339
+ // PMR-V31Z deleted them with the merge-main consumer and the
340
+ // sanctioned-rebase subsystem (4.2/5.1).
341
+ // AIDEV-NOTE: PMR-XNVV — the registerLandTool signature collapsed from 9
342
+ // positional params into RegisterLandToolOptions: harnesses pass named fakes
343
+ // without undefined holes (the trailing optionals used to force
344
+ // `undefined, undefined, ...` threading at every call site). Required
345
+ // fields first; optional seams keep their exact production defaults
346
+ // (receipts/effects via getAgentDir(), resolveHead, writer/healBinding).
347
+ export interface RegisterLandToolOptions {
348
+ /** Shared landing state; index.ts wires the object the bash interceptor reads. */
349
+ state: LandingState
350
+ // AIDEV-NOTE: PMR-VZEV — active-ref getter from the flow loop; null when
351
+ // no flow is in flight (hand-run landing outside a flow is allowed).
352
+ activeRef: () => string | null
353
+ // AIDEV-NOTE: PMR-05HX — injected so tests never run a real suite.
354
+ runSuite: SuiteRunner
355
+ receipts?: ReceiptJournal
356
+ // AIDEV-NOTE: PMR-4S6V — receipts adopt only when the worktree HEAD is
357
+ // unchanged since the committed transition (PMR-05HX: never land work
358
+ // the gate has not seen a green suite over). Null = unresolvable -> no adoption.
359
+ // PMR-5NZB 3.4 — the optional cwd lets the integration core pin the FLOW
360
+ // WORKTREE's HEAD (defaultResolveHead already accepts it); the land
361
+ // tool's own call sites still resolve landingSuiteCwd() with no arg.
362
+ resolveHead?: (cwd?: string) => Promise<string | null>
363
+ // AIDEV-NOTE: PMR-XTQQ — mode-aware writer (server/writer.ts). Present =
364
+ // receipt writes route through it (journal-only while the daemon owns the
365
+ // projection); absent = today's exact full-writer behavior.
366
+ writer?: EventWriter
367
+ // AIDEV-NOTE: PMR-VDVJ — strict effect journal (run-state.ts). The pr
368
+ // landing declares git-push + gh-pr-create through it BEFORE setting
369
+ // `authorized`; a failed declaration refuses the landing (fail-closed).
370
+ effects?: EffectJournal
371
+ // AIDEV-NOTE: PMR-DRKH — injectable heal seam. Absent = production
372
+ // defaultHealBinding above. (Formerly the LAST positional param "so
373
+ // earlier positional call sites keep working" — PMR-XNVV collapsed the
374
+ // signature into this options object, superseding that rationale: every
375
+ // call site now passes named options with no undefined holes.)
376
+ // PMR-V31Z 4.2 — the merge-main seams (resolveMainRepo, resolveLandingBranch,
377
+ // checkMainAdvancement, readEvents, isAncestor, integrationExec,
378
+ // the strict integration-receipt writer, the directory probe) were deleted
379
+ // with the merge-main leg in 4.1; their defaults and the orphaned helpers
380
+ // died in 4.2, and the remaining sanctioned-rebase machinery in 5.1.
381
+ healBinding?: (ref: string) => Promise<HealResult>
382
+ }
383
+
384
+ export function registerLandTool(
385
+ pi: ExtensionAPI,
386
+ options: RegisterLandToolOptions,
387
+ ): void {
388
+ const state = options.state
389
+ const activeRef = options.activeRef
390
+ const runSuite = options.runSuite
391
+ const resolveHead = options.resolveHead ?? defaultResolveHead
392
+ const writer = options.writer
393
+ const healBinding = options.healBinding
394
+ const receipts = options.receipts ?? createReceiptJournal(getAgentDir())
395
+ const effects = options.effects ?? createEffectJournal(getAgentDir())
396
+ let effectiveReceipts = receipts
397
+ if (writer !== undefined) {
398
+ effectiveReceipts = createReceiptJournal(
399
+ getAgentDir(),
400
+ undefined,
401
+ writer.record,
402
+ )
403
+ }
404
+ pi.registerTool({
405
+ name: 'flow_land',
406
+ label: 'flow land',
407
+ description:
408
+ 'Gate a flow landing: verifies the review-passed label (and an optional review artifact verdict) for the ref, then authorizes git push / gh pr create for it. Direct git push / gh pr create are blocked while the flow is active until this returns ok. It runs the land test suite itself before authorizing: landTestCommand config wins if set; otherwise repo-signal detection in fixed order (bun.lock/bunfig.toml → Cargo.toml → package-lock.json → pnpm-lock.yaml); otherwise bun run test as the last fallback. A red suite refuses the landing with the failing output.',
409
+ promptSnippet:
410
+ 'Gated landing for PIV flow runs — call before pushing the branch or creating the PR.',
411
+ promptGuidelines: [
412
+ // AIDEV-NOTE: PMR-AC49 — the suite-resolution text below MUST stay in
413
+ // sync with the LAND_TEST_SIGNALS table order (bun.lock/bunfig.toml →
414
+ // Cargo.toml → package-lock.json → pnpm-lock.yaml, bun fallback) and
415
+ // the defaultSuiteRunner doc comment. Agents read this string to
416
+ // predict which command the gate runs.
417
+ 'Call flow_land AFTER flow_phase_complete(phase="validate") and BEFORE git push / gh pr create — direct landing commands are blocked until it returns ok.',
418
+ 'flow_land runs the test suite itself before authorizing: landTestCommand config wins if set; otherwise repo-signal detection in fixed order (bun.lock/bunfig.toml → Cargo.toml → package-lock.json → pnpm-lock.yaml); otherwise bun run test as the last fallback. The run summary names the command and its source (config, detected signal, or bun default), so refusals are explainable. A red suite refuses the landing with the failing output. Never claim tests are green to skip it; the gate does not read claims.',
419
+ "A refusal carries the gate reason (missing review-passed label, blockers in the artifact, red test suite); fix the cause, do not retry the call. After ok, run the git push and gh pr create step — that PR is the flow's delivery; direct merges are blocked while the flow is active.",
420
+ ],
421
+ parameters: Type.Object({
422
+ ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
423
+ artifact: Type.Optional(
424
+ Type.String({
425
+ description:
426
+ 'The review artifact text (must contain "blockers_count: <N>") — cross-checked when provided',
427
+ }),
428
+ ),
429
+ }),
430
+ async execute(
431
+ _toolCallId: string,
432
+ params: {
433
+ ref: string
434
+ artifact?: string
435
+ },
436
+ _signal?: AbortSignal,
437
+ _onUpdate?: unknown,
438
+ ctx?: ExtensionToolContext,
439
+ ): Promise<AgentToolResult<{ ok: boolean; reason: string }>> {
440
+ // AIDEV-NOTE: PMR-VZEV — ref validation: a live flow only lands its
441
+ // OWN ref. null = no flow active, the gate does not apply (matches
442
+ // the interceptor, which also stands down without an active ref).
443
+ const flowRef = activeRef()
444
+ if (flowRef !== null && flowRef !== params.ref) {
445
+ return toolResult(
446
+ `flow_land refused landing ${params.ref}: it does not match the active flow ref ${flowRef} — land the active flow's ref, or run outside the flow`,
447
+ { ok: false, reason: 'ref does not match active flow ref' },
448
+ { isError: true },
449
+ )
450
+ }
451
+ // AIDEV-NOTE: PMR-DRKH — scoped entry heal, ALWAYS after the mismatch
452
+ // gate above (heal must never run across a live different ref). Only
453
+ // heals when the binding is null/mismatched AND no live flow owns a
454
+ // different ref. Active-flow heal failure refuses LOUDLY before the
455
+ // suite (running it in the session checkout would be a silent
456
+ // false-green); hand-run failure keeps the cwd fallback but appends a
457
+ // WARNING naming the recovery command. landingSuiteCwd() itself is
458
+ // unchanged — healing rebinds state before it is read.
459
+ let healWarning = ''
460
+ // AIDEV-NOTE: PMR-51PV — suite-specific variant of the heal warning.
461
+ // Receipt-adoption ok-messages state 'the suite was NOT re-run', so
462
+ // appending 'the suite ran in <cwd> instead' there would be
463
+ // self-contradictory. Only paths that actually ran the suite use
464
+ // healSuiteWarning; adoption paths use the suite-agnostic healWarning.
465
+ let healSuiteWarning = ''
466
+ const binding = getFlowWorktree()
467
+ const healNeeded = binding === null || binding.ref !== params.ref
468
+ const healAllowed = flowRef === null || flowRef === params.ref
469
+ // AIDEV-NOTE: PMR-DRKH — the production default only runs under the
470
+ // real Pi runtime (a tool context is present); a bare execute call
471
+ // (unit-test harnesses with a mockPi lacking exec) skips healing and
472
+ // keeps today's behavior exactly.
473
+ const canAttemptHeal = healBinding !== undefined || ctx !== undefined
474
+ if (healNeeded && healAllowed && canAttemptHeal) {
475
+ let heal: HealResult
476
+ try {
477
+ if (healBinding !== undefined) {
478
+ heal = await healBinding(params.ref)
479
+ } else if (ctx !== undefined) {
480
+ heal = await defaultHealBinding(pi, ctx.cwd, params.ref)
481
+ } else {
482
+ // canAttemptHeal guarantees one of the branches above runs.
483
+ heal = {
484
+ ok: false,
485
+ reason: 'healing unavailable',
486
+ recovery: recoveryCommand(params.ref),
487
+ }
488
+ }
489
+ } catch (error) {
490
+ let reason: string
491
+ if (error instanceof Error) {
492
+ reason = error.message
493
+ } else {
494
+ reason = String(error)
495
+ }
496
+ heal = { ok: false, reason, recovery: recoveryCommand(params.ref) }
497
+ }
498
+ if (!heal.ok) {
499
+ if (flowRef === params.ref) {
500
+ return toolResult(
501
+ `flow_land refused landing ${params.ref}: the flow worktree for the active flow could not be resolved (${heal.reason}) — running the landing suite outside the flow worktree would be a false green. Recovery: run ${heal.recovery} to re-arm the flow binding, then re-call.`,
502
+ {
503
+ ok: false,
504
+ reason: 'flow worktree unresolvable for active flow',
505
+ },
506
+ { isError: true },
507
+ )
508
+ }
509
+ const healBase = `\n\nWARNING: the flow worktree could not be resolved (${heal.reason})`
510
+ healWarning = `${healBase}. Recovery: run ${heal.recovery} to re-arm the flow binding.`
511
+ healSuiteWarning = `${healBase}; the suite ran in ${process.cwd()} instead. Recovery: run ${heal.recovery} to re-arm the flow binding.`
512
+ }
513
+ }
514
+ // AIDEV-NOTE: PMR-C6AK — the landing gates, in order: ref match,
515
+ // review-passed label + artifact blockers_count cross-check (pure
516
+ // landDecision below), then the self-run suite. PMR-V31Z 4.2 — the
517
+ // merge-main human pass check that lived here (PMR-T8ZG marker,
518
+ // PMR-5NZB 2.4's three head-checked adoption routes via
519
+ // resolveMergeMainHumanGate) is deleted: PR delivery is the only
520
+ // story. PMR-V31Z 7.2 — the PMR-T8ZG marker and the code_review
521
+ // receipt surface are deleted outright (no reader remained).
522
+ const labels = await readAvenLabels(params.ref)
523
+ const decision = landDecision(labels, params.artifact ?? null)
524
+ if (!decision.ok) {
525
+ return toolResult(
526
+ `flow_land refused landing ${params.ref}: ${decision.reason}`,
527
+ { ok: false, reason: decision.reason },
528
+ { isError: true },
529
+ )
530
+ }
531
+ // AIDEV-NOTE: PMR-4S6V — best-effort receipt adoption: on a hit for
532
+ // (ref, flow_land, target 'pr' — the only landing since PMR-V31Z 4.1)
533
+ // with unchanged HEAD, return the stored ok WITHOUT re-running the
534
+ // suite. Gate order is unchanged — a receipt only ever skips the
535
+ // suite, never the ref/labels gates above. The 'pr' target keeps
536
+ // adoption working across the 4.1 surface change (pre-4.1 pr receipts
537
+ // stored the same target).
538
+ const head = await resolveHead()
539
+ if (head !== null) {
540
+ const stored = await effectiveReceipts.find({
541
+ ref: params.ref,
542
+ command: 'flow_land',
543
+ target: 'pr',
544
+ headSha: head,
545
+ })
546
+ if (stored !== null) {
547
+ const declared = await declarePushEffects(effects, params.ref, head)
548
+ if (!declared.ok) {
549
+ return toolResult(
550
+ `flow_land refused landing ${params.ref} via pr: ${declared.reason} — the landing is NOT authorized`,
551
+ { ok: false, reason: 'effect declaration failed' },
552
+ { isError: true },
553
+ )
554
+ }
555
+ state.authorized = params.ref
556
+ return toolResult(
557
+ `flow_land: landing for ${params.ref} authorized via pr — adopted the stored receipt from ${stored.at} (HEAD unchanged) — the suite was NOT re-run — run the git push / gh pr create step now${healWarning}`,
558
+ { ok: true, reason: '' },
559
+ )
560
+ }
561
+ }
562
+ // AIDEV-NOTE: PMR-05HX — guardrail, not a prompt: the gate runs the
563
+ // suite itself before authorizing anything, so a claimed-green suite
564
+ // (pi:01a1b102 ord 36) can no longer land red work. Runs in the flow
565
+ // worktree when one is bound.
566
+ const suiteCwd = landingSuiteCwd()
567
+ const suite = await runSuite(suiteCwd)
568
+ if (!suite.ok) {
569
+ return toolResult(
570
+ `flow_land refused landing ${params.ref}: the test suite FAILED in ${suiteCwd} — a landing requires a suite the gate ran and saw green. Fix the failures and call flow_land again.\n\n${suite.summary}`,
571
+ { ok: false, reason: 'test suite failed' },
572
+ { isError: true },
573
+ )
574
+ }
575
+ // AIDEV-NOTE: PMR-4S6V — best-effort receipt record after a green
576
+ // suite; a journal failure never blocks authorization.
577
+ try {
578
+ await effectiveReceipts.record({
579
+ ref: params.ref,
580
+ command: 'flow_land',
581
+ target: 'pr',
582
+ headSha: head ?? undefined,
583
+ })
584
+ } catch {
585
+ // best-effort — journal failures never block a gate transition
586
+ }
587
+ // AIDEV-NOTE: PMR-VDVJ — both pr success paths (receipt adoption and
588
+ // fresh suite) declare the push effects BEFORE setting `authorized`:
589
+ // declarations are fail-closed, receipts stay best-effort — the
590
+ // deliberate split (plan Key decision 3). On a failed declaration the
591
+ // landing is NOT authorized (any suite cost already spent is accepted;
592
+ // correctness first).
593
+ const declared = await declarePushEffects(effects, params.ref, head)
594
+ if (!declared.ok) {
595
+ return toolResult(
596
+ `flow_land refused landing ${params.ref} via pr: ${declared.reason} — the landing is NOT authorized`,
597
+ { ok: false, reason: 'effect declaration failed' },
598
+ { isError: true },
599
+ )
600
+ }
601
+ state.authorized = params.ref
602
+ return toolResult(
603
+ `flow_land: landing for ${params.ref} authorized via pr — run the git push / gh pr create step now${healSuiteWarning}`,
604
+ { ok: true, reason: '' },
605
+ )
606
+ },
607
+ })
608
+ }