@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,177 @@
1
+ /**
2
+ * Shared helpers for the plan-tools registrations.
3
+ * Moved from packages/pi-planning/plan-tools/helpers.ts (PMR-XCA9 — package
4
+ * absorbed into pi-flow). The slug rule now lives in slugify.ts (re-homed out of brainstorm/paths.ts, PMR-H7RW).
5
+ */
6
+
7
+ import { join } from 'node:path'
8
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
9
+ import { slugify } from '../slugify.ts'
10
+
11
+ // AIDEV-NOTE: PMR-HHS8 fix round (review P1) — getRepoName MUST prefer the
12
+ // origin remote name (basename of the URL, `.git` stripped) over the toplevel
13
+ // basename. In a herdr git worktree the toplevel basename is the worktree
14
+ // name (e.g. `feat-flow-document-paths-env-standard`), not the repo, which
15
+ // scattered notes/PR docs into per-worktree junk dirs. The skill fallbacks
16
+ // (notes-locator, pr-description SKILL.md) use `git remote get-url origin`
17
+ // first too — that "keep both in sync" claim holds again only because of
18
+ // this ordering. Toplevel basename remains the fallback when there is no
19
+ // remote or the lookup fails.
20
+ export async function getRepoName(pi: ExtensionAPI): Promise<string> {
21
+ try {
22
+ const remote = await pi.exec('git', ['remote', 'get-url', 'origin'], {})
23
+ const url = remote.stdout.trim()
24
+ if (url) {
25
+ let name = url.split('/').pop() ?? ''
26
+ if (name.endsWith('.git')) {
27
+ name = name.slice(0, -'.git'.length)
28
+ }
29
+ if (name) return name
30
+ }
31
+ } catch {
32
+ // No origin remote or git unavailable — fall through to the toplevel name.
33
+ }
34
+ try {
35
+ const r = await pi.exec('git', ['rev-parse', '--show-toplevel'], {})
36
+ if (r.stdout.trim()) return r.stdout.trim().split('/').pop() ?? 'unknown'
37
+ } catch {
38
+ // Not a git repo or git unavailable — fall through to 'unknown' below.
39
+ }
40
+ return 'unknown'
41
+ }
42
+
43
+ // AIDEV-NOTE: PMR-J97S — ONE documented non-git behavior across all three
44
+ // resolvers below: FAIL FAST. Outside a git repository a resolver must never
45
+ // return a relative path (join('', 'notes') → 'notes') despite promising an
46
+ // absolute one, and with a notes-root env var set it must never silently land
47
+ // files under <root>/unknown/ (getRepoName's last-resort name). Both cases
48
+ // throw with the resolver name in the message; pinned by test/plan-tools.
49
+ async function gitToplevelOrFail(
50
+ pi: ExtensionAPI,
51
+ who: string,
52
+ envName: string,
53
+ ): Promise<string> {
54
+ const r = await pi.exec('git', ['rev-parse', '--show-toplevel'], {})
55
+ const toplevel = r.stdout.trim()
56
+ if (!toplevel) {
57
+ throw new Error(
58
+ `${who}: not in a git repository and $${envName} is unset — cannot resolve an absolute path`,
59
+ )
60
+ }
61
+ return toplevel
62
+ }
63
+
64
+ async function repoNameOrFail(pi: ExtensionAPI, who: string): Promise<string> {
65
+ const repoName = await getRepoName(pi)
66
+ if (repoName === 'unknown') {
67
+ throw new Error(
68
+ `${who}: cannot derive a repo name (no origin remote, not a git repository) — refusing to resolve a path under an 'unknown' repo dir`,
69
+ )
70
+ }
71
+ return repoName
72
+ }
73
+
74
+ // AIDEV-NOTE: Spec path contract — if $LLM_NOTES_ROOT is set, specs live in
75
+ // $LLM_NOTES_ROOT/<repo>/notes/specs/<JIRA>__<slug>.md (work mode, centralised
76
+ // notes root). Otherwise fall back to repo-local <git-toplevel>/notes/specs/.
77
+ // The repo-local fallback is INTENTIONAL (repo writes allowed when no env var
78
+ // is set) — it was previously assumed to fail fast; that was wrong. Pinned by
79
+ // the resolveSpecPath tests in test/plan-tools.test.ts (PMR-BHM2). Do not
80
+ // convert this branch to a throw without updating those tests. PMR-J97S:
81
+ // OUTSIDE a git repo the fallback still fails fast (see gitToplevelOrFail) —
82
+ // the intentional case is a repo-local path inside a git repo.
83
+ export async function resolveSpecPath(
84
+ pi: ExtensionAPI,
85
+ jiraId: string,
86
+ summary: string,
87
+ ): Promise<string> {
88
+ const slug = slugify(summary)
89
+
90
+ const notesRoot = process.env.LLM_NOTES_ROOT
91
+ let specDir: string
92
+ if (notesRoot) {
93
+ const repoName = await repoNameOrFail(pi, 'resolveSpecPath')
94
+ specDir = join(notesRoot, repoName, 'notes', 'specs')
95
+ } else {
96
+ const toplevel = await gitToplevelOrFail(
97
+ pi,
98
+ 'resolveSpecPath',
99
+ 'LLM_NOTES_ROOT',
100
+ )
101
+ specDir = join(toplevel, 'notes', 'specs')
102
+ }
103
+
104
+ return join(specDir, `${jiraId}__${slug}.md`)
105
+ }
106
+
107
+ // AIDEV-NOTE: Notes subdir allowlist — resolve_notes_path only ever appends
108
+ // one of these fixed segments to the notes root, never an arbitrary path, so
109
+ // the tool cannot be used for path injection. '' means the notes root itself.
110
+ // resolve-notes-path.ts builds its TypeBox union from this array — adding a
111
+ // subdir here is a single edit (PMR-TF0R, PMR-HHS8 fix round).
112
+ export const NOTES_SUBDIRS = [
113
+ '',
114
+ 'prs',
115
+ 'specs',
116
+ 'research',
117
+ 'tickets',
118
+ ] as const
119
+ export type NotesSubdir = (typeof NOTES_SUBDIRS)[number]
120
+
121
+ // AIDEV-NOTE: Notes path contract — if $LLM_NOTES_ROOT is set, notes live in
122
+ // $LLM_NOTES_ROOT/<repo>/notes[/<subdir>] (work mode, centralised notes root).
123
+ // Otherwise fall back to <git-toplevel>/notes[/<subdir>] (repo-local). This is
124
+ // the generic counterpart of resolveSpecPath (which hardcodes 'specs').
125
+ export async function resolveNotesPath(
126
+ pi: ExtensionAPI,
127
+ subdir: NotesSubdir,
128
+ ): Promise<string> {
129
+ const notesRoot = process.env.LLM_NOTES_ROOT
130
+ let dir: string
131
+ if (notesRoot) {
132
+ const repoName = await repoNameOrFail(pi, 'resolveNotesPath')
133
+ dir = join(notesRoot, repoName, 'notes')
134
+ } else {
135
+ // AIDEV-NOTE: PMR-HHS8 fix round (review P3), unified by PMR-J97S —
136
+ // fail fast outside a git repo: join('', 'notes') would return the
137
+ // relative path 'notes' while the tool promises an absolute one. All
138
+ // three resolvers share this behavior via gitToplevelOrFail.
139
+ const toplevel = await gitToplevelOrFail(
140
+ pi,
141
+ 'resolveNotesPath',
142
+ 'LLM_NOTES_ROOT',
143
+ )
144
+ dir = join(toplevel, 'notes')
145
+ }
146
+
147
+ return join(dir, subdir)
148
+ }
149
+
150
+ // AIDEV-NOTE: Feature path contract — if $PERSONAL_FEATURES is set, feature
151
+ // plans live in $PERSONAL_FEATURES/<repo>/<date>-<slug>/plan.md (personal
152
+ // cross-repo features collection). Otherwise fall back to the repo-local
153
+ // <git-toplevel>/.pi/plans/<date>-<slug>/plan.md. resolveFeaturePath is the
154
+ // single contract for feature plan paths.
155
+ export async function resolveFeaturePath(
156
+ pi: ExtensionAPI,
157
+ summary: string,
158
+ ): Promise<string> {
159
+ const date = new Date().toISOString().slice(0, 10)
160
+ const slug = slugify(summary)
161
+
162
+ const personalFeatures = process.env.PERSONAL_FEATURES
163
+ let dir: string
164
+ if (personalFeatures) {
165
+ const repoName = await repoNameOrFail(pi, 'resolveFeaturePath')
166
+ dir = join(personalFeatures, repoName, `${date}-${slug}`)
167
+ } else {
168
+ const toplevel = await gitToplevelOrFail(
169
+ pi,
170
+ 'resolveFeaturePath',
171
+ 'PERSONAL_FEATURES',
172
+ )
173
+ dir = join(toplevel, '.pi', 'plans', `${date}-${slug}`)
174
+ }
175
+
176
+ return join(dir, 'plan.md')
177
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * jira_create_branch tool — thin registerTool wrapper around
3
+ * jira-branch.ts. Shared by the implement-plan and debug skills, replacing
4
+ * the formerly-duplicated scripts/jira-branch.sh in each skill directory.
5
+ * Moved from packages/pi-planning/implement-plan (PMR-XCA9).
6
+ */
7
+
8
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
9
+ import { Type } from 'typebox'
10
+ import { createJiraBranch } from './jira-branch.ts'
11
+
12
+ export function registerJiraCreateBranch(pi: ExtensionAPI) {
13
+ pi.registerTool({
14
+ name: 'jira_create_branch',
15
+ label: 'Jira: Create Branch',
16
+ description: [
17
+ 'Derive a git branch name from a Jira issue (type → prefix, summary → slug),',
18
+ 'and unless dry_run, create it in the given repo and set its git-town parent',
19
+ "to 'develop'. Requires acli and git-town on PATH. Run with cwd set to the target repo.",
20
+ ].join(' '),
21
+ promptSnippet: 'Derive/create a git branch from a Jira issue',
22
+ parameters: Type.Object({
23
+ jira_id: Type.String({ description: 'Jira ticket ID, e.g. DP-121' }),
24
+ cwd: Type.String({
25
+ description: 'Absolute path to the target repo (its git root)',
26
+ }),
27
+ dry_run: Type.Optional(
28
+ Type.Boolean({
29
+ description: 'Preview the derived branch name without creating it',
30
+ default: false,
31
+ }),
32
+ ),
33
+ }),
34
+ async execute(_id, params) {
35
+ const result = await createJiraBranch(
36
+ pi,
37
+ params.jira_id,
38
+ params.cwd,
39
+ params.dry_run ?? false,
40
+ )
41
+
42
+ let text: string
43
+ if (params.dry_run) {
44
+ text = `[dry-run] Branch: ${result.branch} (type '${result.issueType}' → prefix '${result.prefix}')`
45
+ } else if (result.alreadyExisted) {
46
+ text = `Branch '${result.branch}' already exists — not created.`
47
+ } else {
48
+ text = `Created branch '${result.branch}' and set git-town parent to 'develop'.`
49
+ }
50
+
51
+ return { content: [{ type: 'text', text }], details: result }
52
+ },
53
+ })
54
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Shared Jira branch derivation/creation logic.
3
+ * Ports scripts/jira-branch.sh (acli + slugify + git-town) to TS so both
4
+ * create-plan/implement-plan and debug skills share one implementation
5
+ * instead of a duplicated bash script.
6
+ */
7
+
8
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
9
+ import { fetchJiraIssue } from './jira-issue.ts'
10
+
11
+ // AIDEV-NOTE: Extend this map for additional Jira issue types. Keys lowercase.
12
+ const TYPE_PREFIX_MAP: Record<string, string> = {
13
+ bug: 'bugfix',
14
+ hotfix: 'hotfix',
15
+ story: 'feature',
16
+ feature: 'feature',
17
+ epic: 'feature',
18
+ task: 'chore',
19
+ 'sub-task': 'chore',
20
+ subtask: 'chore',
21
+ improvement: 'feature',
22
+ 'technical debt': 'chore',
23
+ spike: 'chore',
24
+ }
25
+ const DEFAULT_PREFIX = 'feature'
26
+ const PARENT_BRANCH = 'develop'
27
+
28
+ function slugify(summary: string): string {
29
+ return summary
30
+ .toLowerCase()
31
+ .replace(/[^a-z0-9 -]/g, '')
32
+ .trim()
33
+ .replace(/\s+/g, '-')
34
+ .replace(/-+/g, '-')
35
+ .split('-')
36
+ .slice(0, 5)
37
+ .join('-')
38
+ .replace(/^-|-$/g, '')
39
+ }
40
+
41
+ export interface DeriveBranchResult {
42
+ branch: string
43
+ summary: string
44
+ issueType: string
45
+ prefix: string
46
+ }
47
+
48
+ /**
49
+ * Fetch the issue from Jira via acli and derive the branch name.
50
+ *
51
+ * AIDEV-NOTE: PMR-9DZ0 — the acli fetch/validation/parse moved to the shared
52
+ * helper (plan-tools/jira-issue.ts); its thrown messages are unchanged, so
53
+ * this stays fail-closed: an invalid key, a failing acli, or a summary-less
54
+ * ticket aborts branch derivation before any git ref is built.
55
+ */
56
+ export async function deriveBranchName(
57
+ pi: ExtensionAPI,
58
+ jiraId: string,
59
+ ): Promise<DeriveBranchResult> {
60
+ const { summary, issueType } = await fetchJiraIssue(pi, jiraId)
61
+
62
+ const prefix = TYPE_PREFIX_MAP[issueType.toLowerCase()] ?? DEFAULT_PREFIX
63
+ const branch = `${prefix}/${jiraId}-${slugify(summary)}`
64
+
65
+ return { branch, summary, issueType, prefix }
66
+ }
67
+
68
+ export interface CreateBranchResult extends DeriveBranchResult {
69
+ created: boolean
70
+ alreadyExisted: boolean
71
+ }
72
+
73
+ /**
74
+ * Derive the branch name for a Jira issue and, unless dryRun, create it and
75
+ * set the git-town parent to 'develop'. cwd must be the target repo root.
76
+ */
77
+ export async function createJiraBranch(
78
+ pi: ExtensionAPI,
79
+ jiraId: string,
80
+ cwd: string,
81
+ dryRun: boolean,
82
+ ): Promise<CreateBranchResult> {
83
+ const derived = await deriveBranchName(pi, jiraId)
84
+ const branchRef = `refs/heads/${derived.branch}`
85
+
86
+ const existing = await pi.exec(
87
+ 'git',
88
+ ['show-ref', '--verify', '--quiet', branchRef],
89
+ { cwd },
90
+ )
91
+ const alreadyExisted = existing.code === 0
92
+
93
+ if (dryRun || alreadyExisted) {
94
+ return { ...derived, created: false, alreadyExisted }
95
+ }
96
+
97
+ const checkout = await pi.exec('git', ['checkout', '-b', derived.branch], {
98
+ cwd,
99
+ })
100
+ if (checkout.code !== 0) {
101
+ throw new Error(
102
+ `git checkout -b '${derived.branch}' failed: ${checkout.stderr}`,
103
+ )
104
+ }
105
+
106
+ await pi.exec('git', ['town', 'set-parent', PARENT_BRANCH], { cwd })
107
+
108
+ return { ...derived, created: true, alreadyExisted: false }
109
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Shared Jira issue lookup via acli.
3
+ *
4
+ * AIDEV-NOTE: PMR-9DZ0 — two callers already fetched the same Jira issue the
5
+ * same way (plan-tools/jira-branch.ts and worktree/branch.ts had verbatim
6
+ * copies of this exec/validate/parse block). The pi-flow title journaling at
7
+ * run-start is the third consumer, so the fetch lives here once. The helper
8
+ * THROWS with the exact messages the branch callers threw before the split —
9
+ * their contract is fail-closed (a wrong branch name must never be built from
10
+ * a half-read ticket) — and callers that want best-effort behaviour catch.
11
+ */
12
+
13
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
14
+
15
+ // AIDEV-NOTE: the guard guarantees jiraId only ever contains [A-Z0-9-] before
16
+ // it is interpolated into an exec arg (and, in the callers, a branch ref).
17
+ // Moved here from the two branch callers so the safe-by-construction property
18
+ // covers every acli consumer, including the run-start title lookup. Ported
19
+ // from the original jira-branch bash script's arg-parsing regex.
20
+ const JIRA_ID_RE = /^[A-Z]+-[0-9]+$/
21
+
22
+ // AIDEV-NOTE: the branch callers passed `{}` — no timeout — so a hanging acli
23
+ // stalled them forever. 15 s is generous for a workitem view. Verified against
24
+ // pi's execCommand: a timed-out exec resolves as {code: 0, killed: true, stdout:
25
+ // ''}, so the hang case lands in the `Could not parse acli JSON response` throw
26
+ // rather than the nonzero-exit one — still fail-closed, just a different message.
27
+ const ACLI_TIMEOUT_MS = 15_000
28
+
29
+ export interface JiraIssue {
30
+ summary: string
31
+ issueType: string
32
+ }
33
+
34
+ /**
35
+ * Fetch a Jira work item's summary and issue-type name via `acli`.
36
+ * Throws on an invalid key, a nonzero exit, unparseable JSON, or a missing
37
+ * summary — callers decide whether that aborts (branch derivation) or is
38
+ * merely a warning (best-effort title lookup).
39
+ */
40
+ export async function fetchJiraIssue(
41
+ pi: ExtensionAPI,
42
+ jiraId: string,
43
+ ): Promise<JiraIssue> {
44
+ if (!JIRA_ID_RE.test(jiraId)) {
45
+ throw new Error(
46
+ `Invalid Jira key '${jiraId}' — expected format like IMP-1234`,
47
+ )
48
+ }
49
+
50
+ const result = await pi.exec(
51
+ 'acli',
52
+ [
53
+ 'jira',
54
+ 'workitem',
55
+ 'view',
56
+ jiraId,
57
+ '--json',
58
+ '--fields',
59
+ 'summary,issuetype',
60
+ ],
61
+ { timeout: ACLI_TIMEOUT_MS },
62
+ )
63
+ if (result.code !== 0) {
64
+ throw new Error(
65
+ `acli failed to fetch '${jiraId}': ${result.stderr || result.stdout}`,
66
+ )
67
+ }
68
+
69
+ let parsed: { fields?: { summary?: string; issuetype?: { name?: string } } }
70
+ try {
71
+ parsed = JSON.parse(result.stdout)
72
+ } catch {
73
+ throw new Error(`Could not parse acli JSON response for '${jiraId}'`)
74
+ }
75
+
76
+ const summary = parsed.fields?.summary ?? ''
77
+ const issueType = parsed.fields?.issuetype?.name ?? ''
78
+ if (!summary) {
79
+ throw new Error(
80
+ `Could not parse summary from Jira response for '${jiraId}'`,
81
+ )
82
+ }
83
+
84
+ return { summary, issueType }
85
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * resolve_feature_path tool — compute the canonical feature plan path.
3
+ * Moved from packages/pi-planning (PMR-XCA9).
4
+ */
5
+
6
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
7
+ import { Type } from 'typebox'
8
+ import { resolveFeaturePath } from './helpers.ts'
9
+
10
+ export function registerResolveFeaturePath(pi: ExtensionAPI) {
11
+ pi.registerTool({
12
+ name: 'resolve_feature_path',
13
+ label: 'Resolve Feature Path',
14
+ description:
15
+ 'Compute the canonical plan.md path for a personal feature. If $PERSONAL_FEATURES is set, uses $PERSONAL_FEATURES/<repo>/<date>-<slug>/plan.md; otherwise falls back to <git-toplevel>/.pi/plans/<date>-<slug>/plan.md. Slug is generated from the summary (max 5 words, lowercase, dashes). Returns the full absolute path.',
16
+ promptSnippet: 'Compute the canonical plan.md path for a personal feature',
17
+ parameters: Type.Object({
18
+ summary: Type.String({
19
+ description: 'Feature summary/title used to generate the slug',
20
+ }),
21
+ }),
22
+ async execute(_id, params) {
23
+ const featurePath = await resolveFeaturePath(pi, params.summary)
24
+ return {
25
+ content: [{ type: 'text', text: featurePath }],
26
+ details: { featurePath },
27
+ }
28
+ },
29
+ })
30
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * resolve_notes_path tool — compute the canonical notes directory path.
3
+ * Added for PMR-TF0R (feature PMR-HHS8: make all flow document paths env-standard).
4
+ */
5
+
6
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
7
+ import { Type } from 'typebox'
8
+ import { NOTES_SUBDIRS, resolveNotesPath } from './helpers.ts'
9
+
10
+ // AIDEV-NOTE: PMR-HHS8 fix round (review P3) — the union is derived from
11
+ // NOTES_SUBDIRS, so adding a subdir is a single edit in helpers.ts.
12
+
13
+ export function registerResolveNotesPath(pi: ExtensionAPI) {
14
+ pi.registerTool({
15
+ name: 'resolve_notes_path',
16
+ label: 'Resolve Notes Path',
17
+ description:
18
+ 'Compute the canonical notes directory path for this repo. If $LLM_NOTES_ROOT is set, uses $LLM_NOTES_ROOT/<repo>/notes[/<subdir>]; otherwise falls back to <git-toplevel>/notes[/<subdir>]. subdir is restricted to a fixed allowlist ("" for the notes root, or "prs", "specs", "research", "tickets"). Returns the full absolute path.',
19
+ promptSnippet: 'Compute the canonical notes directory path for this repo',
20
+ parameters: Type.Object({
21
+ subdir: Type.Union(
22
+ NOTES_SUBDIRS.map((subdir) => Type.Literal(subdir)),
23
+ {
24
+ description:
25
+ 'Notes subdirectory ("" for the notes root; allowlist: prs, specs, research, tickets)',
26
+ },
27
+ ),
28
+ }),
29
+ async execute(_id, params) {
30
+ const notesPath = await resolveNotesPath(pi, params.subdir)
31
+ return {
32
+ content: [{ type: 'text', text: notesPath }],
33
+ details: { notesPath },
34
+ }
35
+ },
36
+ })
37
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * resolve_spec_path tool — compute the canonical spec file path for a Jira ticket.
3
+ * Moved from packages/pi-planning (PMR-XCA9).
4
+ */
5
+
6
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
7
+ import { Type } from 'typebox'
8
+ import { resolveSpecPath } from './helpers.ts'
9
+
10
+ export function registerResolveSpecPath(pi: ExtensionAPI) {
11
+ pi.registerTool({
12
+ name: 'resolve_spec_path',
13
+ label: 'Resolve Spec Path',
14
+ description:
15
+ 'Compute the canonical spec file path for a Jira ticket. Resolves repo name from git remote, applies $LLM_NOTES_ROOT if set, generates a slug from the summary (max 5 words, lowercase, dashes). Returns the full absolute path.',
16
+ promptSnippet: 'Compute the canonical spec file path for a Jira ticket',
17
+ parameters: Type.Object({
18
+ jira_id: Type.String({ description: 'Jira ticket ID, e.g. IMP-7070' }),
19
+ summary: Type.String({
20
+ description: 'Jira summary/title used to generate the slug',
21
+ }),
22
+ }),
23
+ async execute(_id, params) {
24
+ const specPath = await resolveSpecPath(pi, params.jira_id, params.summary)
25
+ return {
26
+ content: [{ type: 'text', text: specPath }],
27
+ details: { specPath },
28
+ }
29
+ },
30
+ })
31
+ }