@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,134 @@
1
+ // AIDEV-NOTE: Review gate (PMR-JTAM) — the FINAL step of the validate phase.
2
+ // After the environment/human gate passes, /review runs on the change and its
3
+ // artifact is parsed here. PURE only: no /review invocation, no aven/Jira/git
4
+ // I/O — the handoff prompt (validate/prompt.ts) owns all side effects.
5
+ //
6
+ // AIDEV-NOTE: blockers_count artifact contract (DEFINED HERE — single
7
+ // owner since PMR-W8SG absorbed pi-review into pi-flow). The emitter
8
+ // (review/verdict.ts) imports VERDICT_HEADING and BLOCKER_LINE from here so
9
+ // parser and emitter can never drift. The validate prompt still restates the
10
+ // contract so hand-written artifacts match too:
11
+ // - exactly one line matching `blockers_count: <integer >= 0>`
12
+ // - optional blocker descriptions as lines starting with `- blocker: `
13
+ // Parsing is scoped to the verdict section (a fenced block or headed
14
+ // section containing the count) so contract text QUOTED elsewhere in the
15
+ // review cannot false-positive. Parsing is STRICT: missing, duplicated,
16
+ // non-integer or negative counts are explicit errors — never a silent 0 (a
17
+ // silent 0 would auto-land broken code).
18
+
19
+ // AIDEV-NOTE: Contract pieces shared with the emitter (review/verdict.ts).
20
+ // parseReviewArtifact scopes parsing to the verdict section, so the heading
21
+ // wording is load-bearing on both sides.
22
+ export const VERDICT_HEADING = '## Verdict'
23
+ export const BLOCKER_LINE =
24
+ ' - blocker: <description> (omit this line entirely when N is 0)'
25
+
26
+ // AIDEV-NOTE: The exact contract wording handed to the validating agent so
27
+ // the artifact it writes matches parseReviewArtifact byte-for-byte.
28
+ export const REVIEW_CONTRACT_PROMPT = ` blockers_count: 0
29
+ ${BLOCKER_LINE}`
30
+
31
+ export type ReviewArtifact =
32
+ | { ok: true; blockersCount: number; blockers: readonly string[] }
33
+ | { ok: false; reason: string }
34
+
35
+ const COUNT_RE = /^blockers_count:\s*(\d+)\s*$/
36
+ const BLOCKER_RE = /^- blocker:\s*(.+)$/
37
+
38
+ // AIDEV-NOTE: Scopes parsing to the verdict section so a review that merely
39
+ // QUOTES the contract (e.g. while discussing the gate) does not double-count.
40
+ // Preference order: the section after the LAST "## Verdict"-style heading
41
+ // (up to the next heading) ALWAYS wins — that is what review/verdict.ts
42
+ // emits canonically. Only when no heading exists do we
43
+ // fall back to the LAST fenced block containing a count line (hand-written
44
+ // artifacts), else the whole artifact. A quoted fenced example (e.g.
45
+ // "blockers_count: 0" in a fence) must NEVER override a real heading
46
+ // verdict — that would parse 0 and auto-land blocked code.
47
+ export function extractVerdictSection(artifact: string): string {
48
+ const headings = [
49
+ ...artifact.matchAll(/^[ \t]*#{1,6}[ \t]+verdict\b[^\n]*$/gim),
50
+ ]
51
+ const lastHeading = headings[headings.length - 1]
52
+ if (lastHeading !== undefined) {
53
+ const start = (lastHeading.index ?? 0) + lastHeading[0].length
54
+ const rest = artifact.slice(start)
55
+ const nextHeading = /^[ \t]*#{1,6}[ \t]+\S/m.exec(rest)
56
+ if (nextHeading?.index !== undefined) {
57
+ return rest.slice(0, nextHeading.index)
58
+ }
59
+ return rest
60
+ }
61
+ const fences = [...artifact.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)]
62
+ for (let i = fences.length - 1; i >= 0; i--) {
63
+ const body = fences[i]?.[1]
64
+ if (body !== undefined && /^blockers_count:\s*\d+\s*$/m.test(body)) {
65
+ return body
66
+ }
67
+ }
68
+ return artifact
69
+ }
70
+
71
+ export function parseReviewArtifact(artifact: string): ReviewArtifact {
72
+ const counts: number[] = []
73
+ const blockers: string[] = []
74
+ for (const rawLine of extractVerdictSection(artifact).split('\n')) {
75
+ const line = rawLine.trim()
76
+ const countMatch = COUNT_RE.exec(line)
77
+ if (countMatch !== null) {
78
+ counts.push(Number.parseInt(countMatch[1] as string, 10))
79
+ continue
80
+ }
81
+ const blockerMatch = BLOCKER_RE.exec(line)
82
+ if (blockerMatch !== null) {
83
+ blockers.push((blockerMatch[1] as string).trim())
84
+ }
85
+ }
86
+ if (counts.length === 0) {
87
+ return {
88
+ ok: false,
89
+ reason:
90
+ 'review artifact has no "blockers_count: <N>" line — re-run /review and ensure the artifact ends with the count',
91
+ }
92
+ }
93
+ if (counts.length > 1) {
94
+ return {
95
+ ok: false,
96
+ reason: `review artifact has multiple blockers_count lines (${counts.join(', ')}) — exactly one is required`,
97
+ }
98
+ }
99
+ const count = counts[0] as number
100
+ if (!Number.isInteger(count) || count < 0) {
101
+ return { ok: false, reason: `invalid blockers_count value: ${count}` }
102
+ }
103
+ return { ok: true, blockersCount: count, blockers }
104
+ }
105
+
106
+ export type ReviewDecision =
107
+ | { route: 'landing' }
108
+ | { route: 'implement'; blockersNote: string }
109
+
110
+ // AIDEV-NOTE: Pure gate decision (PMR-V31Z 1.1). 0 blockers -> the landing
111
+ // route, no longer mode-keyed — landing is one decision; the per-mode
112
+ // delivery story lives in the prompt prose. >0 -> back to /implement with
113
+ // the blockers recorded as an aven note (retry budget applies there). The
114
+ // `mode` parameter stays in the signature for call-site stability (tests
115
+ // pin both modes); it no longer selects a route.
116
+ export function decideReviewRoute(
117
+ _mode: 'work' | 'personal',
118
+ blockersCount: number,
119
+ blockers: readonly string[] = [],
120
+ ): ReviewDecision {
121
+ if (blockersCount === 0) {
122
+ return { route: 'landing' }
123
+ }
124
+ const listed = blockers.filter((b) => b.length > 0)
125
+ let blockersNote: string
126
+ if (listed.length > 0) {
127
+ blockersNote = `review blockers (${blockersCount}):\n${listed
128
+ .map((b) => `- ${b}`)
129
+ .join('\n')}`
130
+ } else {
131
+ blockersNote = `${blockersCount} review blocker(s) — see the review artifact for details`
132
+ }
133
+ return { route: 'implement', blockersNote }
134
+ }
@@ -0,0 +1,113 @@
1
+ // AIDEV-NOTE: Per-subtask gate ranges (PMR-6EEW remainder, observability
2
+ // plan Phase 6 / M7 item 4). Subtask attribution is derived from history:
3
+ // every flow commit carries a `Subtask: <aven-ref>` trailer, so a reviewer
4
+ // assigned to subtask X can be pinned to exactly X's commits — never "the
5
+ // branch". Commits without a trailer are surfaced as unattributed rather
6
+ // than guessed at. PURE only: no git, no journal. The exec-backed derivation
7
+ // lives in gate-target.ts (deriveSubtaskAttribution), journal events in
8
+ // run-state.ts ('subtask-ranges').
9
+
10
+ import { isFullSha } from './gate-target.ts'
11
+
12
+ export const SUBTASK_TRAILER_PREFIX = 'Subtask:'
13
+
14
+ // AIDEV-NOTE: PMR-JJ8Z — exported as the package's ONE ref-shape
15
+ // definition; worktree/branch.ts validates flow refs against it too.
16
+ export const SUBTASK_REF_RE = /^[A-Za-z][A-Za-z0-9]*-[A-Za-z0-9]+$/
17
+ // /g for matchAll, /i for case, /m for per-line trailer matching
18
+ const TRAILER_RE = /^Subtask:\s*([A-Za-z][A-Za-z0-9]*-[A-Za-z0-9]+)\s*$/gim
19
+
20
+ export interface SubtaskCommit {
21
+ sha: string
22
+ message: string
23
+ /** aven refs found in `Subtask:` trailers (0 = unattributed). */
24
+ subtaskRefs: string[]
25
+ }
26
+
27
+ export type SubtaskLogParse =
28
+ | { ok: true; commits: SubtaskCommit[] }
29
+ | { ok: false; reason: string }
30
+
31
+ /**
32
+ * Parse `git log --format=%H%x1f%B%x1e` output (field separator U+001F,
33
+ * record separator U+001E) into attributed commits. Malformed SHAs are an
34
+ * error, not silent data loss — a range derived from garbage history must
35
+ * never be handed to a gate.
36
+ */
37
+ export function parseSubtaskLog(stdout: string): SubtaskLogParse {
38
+ const commits: SubtaskCommit[] = []
39
+ for (const record of stdout.split('\x1e')) {
40
+ const trimmed = record.replace(/^\n+/, '').replace(/\n+$/, '')
41
+ if (trimmed.length === 0) continue
42
+ const sep = trimmed.indexOf('\x1f')
43
+ if (sep < 0) {
44
+ return {
45
+ ok: false,
46
+ reason: `log record has no field separator: '${trimmed.slice(0, 40)}'`,
47
+ }
48
+ }
49
+ const sha = trimmed.slice(0, sep).trim()
50
+ const message = trimmed.slice(sep + 1)
51
+ if (!isFullSha(sha)) {
52
+ return {
53
+ ok: false,
54
+ reason: `log record sha is not full 40-hex: '${sha.slice(0, 40)}'`,
55
+ }
56
+ }
57
+ const subtaskRefs: string[] = []
58
+ for (const m of message.matchAll(TRAILER_RE)) {
59
+ const ref = m[1] ?? ''
60
+ if (!subtaskRefs.includes(ref)) subtaskRefs.push(ref)
61
+ }
62
+ commits.push({ sha, message, subtaskRefs })
63
+ }
64
+ return { ok: true, commits }
65
+ }
66
+
67
+ /** Validate a standalone subtask ref (used by buildSubtaskGateTarget). */
68
+ export function isSubtaskRef(value: string): boolean {
69
+ return SUBTASK_REF_RE.test(value)
70
+ }
71
+
72
+ /** subtask ref -> its commits, in log order (newest first). */
73
+ export function subtaskCommitMap(
74
+ commits: SubtaskCommit[],
75
+ ): Map<string, string[]> {
76
+ const map = new Map<string, string[]>()
77
+ for (const c of commits) {
78
+ for (const ref of c.subtaskRefs) {
79
+ const list = map.get(ref) ?? []
80
+ list.push(c.sha)
81
+ map.set(ref, list)
82
+ }
83
+ }
84
+ return map
85
+ }
86
+
87
+ /** Commits in the range with NO subtask trailer — never silently attributed. */
88
+ export function unattributedCommits(commits: SubtaskCommit[]): SubtaskCommit[] {
89
+ return commits.filter((c) => c.subtaskRefs.length === 0)
90
+ }
91
+
92
+ export interface SubtaskAttribution {
93
+ /** subtask ref -> commit SHAs (newest first, as git log emits). */
94
+ bySubtask: Array<{ subtask: string; commits: string[] }>
95
+ /** SHAs of commits without any `Subtask:` trailer. */
96
+ unattributed: string[]
97
+ }
98
+
99
+ /** The journal-shaped projection of one range's attribution. */
100
+ export function subtaskAttribution(
101
+ commits: SubtaskCommit[],
102
+ ): SubtaskAttribution {
103
+ const map = subtaskCommitMap(commits)
104
+ const bySubtask: Array<{ subtask: string; commits: string[] }> = []
105
+ for (const [subtask, shas] of map) {
106
+ bySubtask.push({ subtask, commits: shas })
107
+ }
108
+ bySubtask.sort((a, b) => a.subtask.localeCompare(b.subtask))
109
+ return {
110
+ bySubtask,
111
+ unattributed: unattributedCommits(commits).map((c) => c.sha),
112
+ }
113
+ }
package/work-mode.ts ADDED
@@ -0,0 +1,19 @@
1
+ // AIDEV-NOTE: Pure work-mode detection — unit-testable without pi/herdr.
2
+ // The pi-bound wrapper (resolveMode) shells out to git and lives in index.ts.
3
+
4
+ export type WorkMode = 'work' | 'personal'
5
+
6
+ // AIDEV-NOTE: Path-segment aware prefix match — /foo/bar must not match
7
+ // /foo/barbaz. Equality counts as "under" the root.
8
+ export function modeForToplevel(
9
+ toplevel: string,
10
+ workRoots: readonly string[],
11
+ ): WorkMode {
12
+ for (const root of workRoots) {
13
+ const normalized = root.endsWith('/') ? root : `${root}/`
14
+ if (toplevel === root || toplevel.startsWith(normalized)) {
15
+ return 'work'
16
+ }
17
+ }
18
+ return 'personal'
19
+ }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Lockfile-based dependency bootstrap + missing-only `.env*` copy.
3
+ */
4
+
5
+ import { copyFile, readdir } from 'node:fs/promises'
6
+ import { join } from 'node:path'
7
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
8
+
9
+ export interface BootstrapStep {
10
+ label: string
11
+ command: string
12
+ shell: boolean
13
+ }
14
+
15
+ export interface BootstrapPlan {
16
+ steps: BootstrapStep[]
17
+ note?: string
18
+ }
19
+
20
+ const GO_NOTE = 'go: global module cache, nothing to install'
21
+ const NONE_NOTE = 'no recognized lockfile — nothing to bootstrap'
22
+
23
+ // AIDEV-NOTE: all JS installs run as a single bash -c string so GH_TOKEN
24
+ // is expanded inside the shell and never appears in process argv (ISC-5).
25
+ // gh-auth fallback (plain command) happens in runStep.
26
+ const GH_PREFIX = 'GH_TOKEN="$(gh auth token)" '
27
+
28
+ const JS_LOCKFILES = [
29
+ 'bun.lock',
30
+ 'bun.lockb',
31
+ 'yarn.lock',
32
+ 'package-lock.json',
33
+ 'pnpm-lock.yaml',
34
+ ] as const
35
+
36
+ /**
37
+ * Pick the bootstrap plan from basenames found at the worktree root.
38
+ * First matching JS lockfile wins; ambiguity is noted, not an error.
39
+ */
40
+ export function detectBootstrapPlan(filesPresent: string[]): BootstrapPlan {
41
+ const present = new Set(filesPresent)
42
+ const notes: string[] = []
43
+
44
+ const matched = JS_LOCKFILES.filter((name) => present.has(name))
45
+ const steps: BootstrapStep[] = []
46
+ if (matched.length > 1) {
47
+ notes.push(
48
+ `multiple JS lockfiles found (${matched.join(', ')}); using ${matched[0]}`,
49
+ )
50
+ }
51
+
52
+ if (present.has('bun.lock') || present.has('bun.lockb')) {
53
+ steps.push({
54
+ label: 'bun install',
55
+ command: `${GH_PREFIX}bun install`,
56
+ shell: true,
57
+ })
58
+ } else if (present.has('yarn.lock')) {
59
+ steps.push({
60
+ label: 'yarn install',
61
+ command: `${GH_PREFIX}yarn install`,
62
+ shell: true,
63
+ })
64
+ } else if (present.has('package-lock.json')) {
65
+ steps.push({
66
+ label: 'npm ci',
67
+ command: `${GH_PREFIX}npm ci`,
68
+ shell: true,
69
+ })
70
+ } else if (present.has('pnpm-lock.yaml')) {
71
+ steps.push({
72
+ label: 'pnpm install',
73
+ command: `${GH_PREFIX}pnpm install --frozen-lockfile`,
74
+ shell: true,
75
+ })
76
+ }
77
+
78
+ if (present.has('Cargo.toml')) {
79
+ steps.push({ label: 'cargo fetch', command: 'cargo fetch', shell: false })
80
+ }
81
+ if (present.has('go.mod')) {
82
+ notes.push(GO_NOTE)
83
+ }
84
+ if (steps.length === 0 && notes.length === 0) {
85
+ notes.push(NONE_NOTE)
86
+ }
87
+
88
+ const plan: BootstrapPlan = { steps }
89
+ if (notes.length > 0) {
90
+ plan.note = notes.join('; ')
91
+ }
92
+ return plan
93
+ }
94
+
95
+ /**
96
+ * AIDEV-NOTE: missing-only contract — a `.env*` file already present in
97
+ * the worktree is NEVER copied over (ISC-6; snapshots by design).
98
+ * `.env` prefix match is exact: startsWith('.env'), so `.environment`
99
+ * is ignored.
100
+ */
101
+ export function selectEnvFiles(
102
+ sourceDirListing: string[],
103
+ targetDirListing: string[],
104
+ ): string[] {
105
+ const target = new Set(targetDirListing)
106
+ const isEnvFile = (name: string): boolean =>
107
+ name === '.env' || name.startsWith('.env.')
108
+ return sourceDirListing.filter((name) => isEnvFile(name) && !target.has(name))
109
+ }
110
+
111
+ function tail(text: string): string {
112
+ return text.slice(-300)
113
+ }
114
+
115
+ export interface BootstrapStepResult {
116
+ label: string
117
+ ok: boolean
118
+ output: string
119
+ }
120
+
121
+ async function runStep(
122
+ pi: ExtensionAPI,
123
+ step: BootstrapStep,
124
+ cwd: string,
125
+ signal: AbortSignal | undefined,
126
+ ): Promise<BootstrapStepResult> {
127
+ let command = step.command
128
+ let args: string[]
129
+ if (step.shell) {
130
+ // Verify gh auth first; fall back to plain command if gh missing.
131
+ const gh = await pi.exec('gh', ['auth', 'token'], { cwd })
132
+ if (gh.code !== 0) {
133
+ command = command.replace(GH_PREFIX, '')
134
+ const result = await pi.exec('bash', ['-c', command], {
135
+ cwd,
136
+ signal,
137
+ timeout: 10 * 60 * 1000,
138
+ })
139
+ return {
140
+ label: step.label,
141
+ ok: result.code === 0,
142
+ output: `warning: gh auth token failed, running plain ${command}\n${tail(result.stdout + result.stderr)}`,
143
+ }
144
+ }
145
+ // AIDEV-NOTE: PMR-K8BW — spawn via bash; without this the whole
146
+ // `GH_TOKEN=... <cmd>` string was exec'd as one binary (ENOENT),
147
+ // the recurring bootstrap false-negative FAIL.
148
+ command = 'bash'
149
+ args = ['-c', step.command]
150
+ } else {
151
+ const parts = command.split(' ')
152
+ args = parts.slice(1)
153
+ command = parts[0]
154
+ }
155
+ const result = await pi.exec(command, args, {
156
+ cwd,
157
+ signal,
158
+ timeout: 10 * 60 * 1000,
159
+ })
160
+ return {
161
+ label: step.label,
162
+ ok: result.code === 0,
163
+ output: tail(result.stdout + result.stderr),
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Never throws (ISC-11): failures are recorded per-step; the worktree
169
+ * stays usable. Remaining steps are marked skipped once aborted.
170
+ */
171
+ export async function runBootstrap(
172
+ pi: ExtensionAPI,
173
+ worktreePath: string,
174
+ signal: AbortSignal | undefined,
175
+ onUpdate?: (text: string) => void,
176
+ ): Promise<BootstrapStepResult[]> {
177
+ try {
178
+ const files = await readdir(worktreePath)
179
+ const plan = detectBootstrapPlan(files)
180
+ const results: BootstrapStepResult[] = []
181
+ for (const step of plan.steps) {
182
+ if (signal?.aborted) {
183
+ results.push({
184
+ label: step.label,
185
+ ok: false,
186
+ output: 'skipped: aborted',
187
+ })
188
+ continue
189
+ }
190
+ if (onUpdate) {
191
+ onUpdate(`bootstrap: ${step.label}`)
192
+ }
193
+ try {
194
+ results.push(await runStep(pi, step, worktreePath, signal))
195
+ } catch (error) {
196
+ results.push({
197
+ label: step.label,
198
+ ok: false,
199
+ output: tail(String(error)),
200
+ })
201
+ }
202
+ }
203
+ return results
204
+ } catch (error) {
205
+ return [
206
+ {
207
+ label: 'bootstrap',
208
+ ok: false,
209
+ output: tail(String(error)),
210
+ },
211
+ ]
212
+ }
213
+ }
214
+
215
+ /** Copy missing-only `.env*` from the main checkout; never throws. */
216
+ export async function copyEnvFiles(
217
+ pi: ExtensionAPI,
218
+ mainCheckout: string,
219
+ worktreePath: string,
220
+ ): Promise<string[]> {
221
+ // AIDEV-NOTE: pi unused here but kept for signature symmetry with
222
+ // runBootstrap (future per-file exec hooks); fs/promises suffices.
223
+ void pi
224
+ try {
225
+ const [sourceEntries, targetEntries] = await Promise.all([
226
+ readdir(mainCheckout),
227
+ readdir(worktreePath),
228
+ ])
229
+ const toCopy = selectEnvFiles(sourceEntries, targetEntries)
230
+ const copied: string[] = []
231
+ for (const name of toCopy) {
232
+ try {
233
+ await copyFile(join(mainCheckout, name), join(worktreePath, name))
234
+ copied.push(name)
235
+ } catch {
236
+ // per-file skip — never abort the whole copy
237
+ }
238
+ }
239
+ return copied
240
+ } catch {
241
+ return []
242
+ }
243
+ }
@@ -0,0 +1,168 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
2
+ import { fetchJiraIssue } from '../plan-tools/jira-issue.ts'
3
+ // AIDEV-NOTE: PMR-JJ8Z — one definition of the ref shape for the whole
4
+ // package; branch validation must not drift from the subtask trailer's.
5
+ import { SUBTASK_REF_RE } from '../validate/subtask-range.ts'
6
+
7
+ export type PersonalType = 'feat' | 'fix' | 'chore' | 'docs' | 'refactor'
8
+
9
+ export type BranchInput =
10
+ | { kind: 'jira'; jiraId: string }
11
+ | { kind: 'personal'; name: string; type: PersonalType; flowRef?: string }
12
+ | { kind: 'literal'; branch: string }
13
+
14
+ const PERSONAL_TYPES: readonly PersonalType[] = [
15
+ 'feat',
16
+ 'fix',
17
+ 'chore',
18
+ 'docs',
19
+ 'refactor',
20
+ ]
21
+
22
+ export interface RawBranchInput {
23
+ jira_id?: string
24
+ name?: string
25
+ type?: string
26
+ branch?: string
27
+ }
28
+
29
+ /**
30
+ * Validate raw tool input into exactly one branch derivation mode:
31
+ * jira_id XOR name XOR branch.
32
+ */
33
+ export function parseBranchInput(raw: RawBranchInput): BranchInput {
34
+ const modes = [
35
+ Boolean(raw.jira_id),
36
+ Boolean(raw.name),
37
+ Boolean(raw.branch),
38
+ ].filter(Boolean).length
39
+
40
+ if (modes === 0) {
41
+ throw new Error(
42
+ 'Missing branch input — provide exactly one of: jira_id, name, branch',
43
+ )
44
+ }
45
+ if (modes > 1) {
46
+ throw new Error(
47
+ 'Ambiguous branch input — provide exactly one of: jira_id, name, branch',
48
+ )
49
+ }
50
+
51
+ if (raw.jira_id) {
52
+ return { kind: 'jira', jiraId: raw.jira_id }
53
+ }
54
+
55
+ if (raw.name) {
56
+ let type: PersonalType = 'feat'
57
+ if (raw.type !== undefined) {
58
+ if (!PERSONAL_TYPES.includes(raw.type as PersonalType)) {
59
+ throw new Error(
60
+ `Invalid type '${raw.type}' — expected one of: ${PERSONAL_TYPES.join(', ')}`,
61
+ )
62
+ }
63
+ type = raw.type as PersonalType
64
+ }
65
+ return { kind: 'personal', name: raw.name, type }
66
+ }
67
+
68
+ return { kind: 'literal', branch: raw.branch as string }
69
+ }
70
+
71
+ // AIDEV-NOTE: PMR-XCA9 — intentionally duplicates pi-flow's jira-branch
72
+ // slugify rules (plan-tools/jira-branch.ts; pi-planning retired).
73
+ // Cross-package runtime import avoided; keep the rules in sync when they change.
74
+ export function slugify(text: string): string {
75
+ return text
76
+ .toLowerCase()
77
+ .replace(/[^a-z0-9 -]/g, '')
78
+ .trim()
79
+ .replace(/\s+/g, '-')
80
+ .replace(/-+/g, '-')
81
+ .split('-')
82
+ .slice(0, 5)
83
+ .join('-')
84
+ .replace(/^-|-$/g, '')
85
+ }
86
+
87
+ // AIDEV-NOTE: PMR-902B — branch-shape contract for personal flows. When a
88
+ // personal flow is active, its aven ref is injected into the branch as
89
+ // `<type>/<REF>-<slug>` (e.g. feat/PMR-AB12-add-save-button). The ref is used
90
+ // bare — no brackets — because git refnames reject `[`. PMR-JJ8Z: the ref
91
+ // shape now REUSES the package's one definition (SUBTASK_REF_RE,
92
+ // validate/subtask-range.ts) instead of a narrower uppercase-only variant,
93
+ // and the ref is normalized with toUpperCase so branch names stay in
94
+ // lockstep with titleBranch's ref-prefixed expectation. Callers with no
95
+ // active flow pass null/undefined and get the bare `<type>/<slug>` shape.
96
+ export function personalBranch(
97
+ name: string,
98
+ type: PersonalType,
99
+ ref?: string | null,
100
+ ): string {
101
+ if (ref === null || ref === undefined) {
102
+ return `${type}/${slugify(name)}`
103
+ }
104
+ if (!SUBTASK_REF_RE.test(ref)) {
105
+ throw new Error(`Invalid flow ref '${ref}' — expected format like PMR-AB12`)
106
+ }
107
+ return `${type}/${ref.toUpperCase()}-${slugify(name)}`
108
+ }
109
+
110
+ // AIDEV-NOTE: PMR-XCA9 — deriveBranchName inlined from the retired
111
+ // pi-planning shared/jira-branch.ts (only pi-worktree consumed it; pi-flow
112
+ // keeps the tool-facing copy in plan-tools/jira-branch.ts). Keys lowercase.
113
+ const TYPE_PREFIX_MAP: Record<string, string> = {
114
+ bug: 'bugfix',
115
+ hotfix: 'hotfix',
116
+ story: 'feature',
117
+ feature: 'feature',
118
+ epic: 'feature',
119
+ task: 'chore',
120
+ 'sub-task': 'chore',
121
+ subtask: 'chore',
122
+ improvement: 'feature',
123
+ 'technical debt': 'chore',
124
+ spike: 'chore',
125
+ }
126
+ const DEFAULT_PREFIX = 'feature'
127
+
128
+ /**
129
+ * Fetch the issue from Jira via acli and derive the branch name.
130
+ *
131
+ * AIDEV-NOTE: PMR-9DZ0 — the acli exec / key-validation / JSON-parse moved to
132
+ * the shared helper (plan-tools/jira-issue.ts), which now owns the guard that
133
+ * used to live here: it guarantees jiraId only ever contains [A-Z0-9-] before
134
+ * it's interpolated into a branch ref / exec arg, and it throws with the exact
135
+ * same messages, so this caller stays fail-closed. The local prefix map and
136
+ * branch shape below are unchanged.
137
+ */
138
+ async function deriveBranchName(
139
+ pi: ExtensionAPI,
140
+ jiraId: string,
141
+ ): Promise<{ branch: string }> {
142
+ const { summary, issueType } = await fetchJiraIssue(pi, jiraId)
143
+
144
+ const prefix = TYPE_PREFIX_MAP[issueType.toLowerCase()] ?? DEFAULT_PREFIX
145
+ return { branch: `${prefix}/${jiraId}-${slugify(summary)}` }
146
+ }
147
+
148
+ export interface DerivedBranch {
149
+ branch: string
150
+ source: 'jira' | 'personal' | 'literal'
151
+ }
152
+
153
+ export async function deriveBranch(
154
+ pi: ExtensionAPI,
155
+ input: BranchInput,
156
+ ): Promise<DerivedBranch> {
157
+ if (input.kind === 'jira') {
158
+ const result = await deriveBranchName(pi, input.jiraId)
159
+ return { branch: result.branch, source: 'jira' }
160
+ }
161
+ if (input.kind === 'personal') {
162
+ return {
163
+ branch: personalBranch(input.name, input.type, input.flowRef),
164
+ source: 'personal',
165
+ }
166
+ }
167
+ return { branch: input.branch, source: 'literal' }
168
+ }